content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Reflection;
using System.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("FactorialTrailingZeroes")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FactorialTrailingZeroes")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d483b290-54cd-4e32-8183-4b0897f832a9")]
// 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.351351 | 84 | 0.749119 | [
"MIT"
] | Ivelin153/SoftUni | Programming Fundamentals/MethodsAndDebuggingHomework/FactorialTrailingZeroes/Properties/AssemblyInfo.cs | 1,422 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Dhgms.Nucleotide.Generators;
using Dhgms.Nucleotide.Generators.Features.Cqrs;
using Dhgms.Nucleotide.Generators.Models;
using Dhgms.Nucleotide.ModelTests;
using Microsoft.CodeAnalysis;
using Moq;
using Xunit;
using Xunit.Abstractions;
namespace Dhgms.Nucleotide.UnitTests.Generators
{
[ExcludeFromCodeCoverage]
public static class QueryFactoryInterfaceGeneratorTests
{
public sealed class ConstructorMethod : BaseGeneratorTests.BaseConstructorMethod<QueryFactoryInterfaceGenerator, QueryFactoryInterfaceFeatureFlags, QueryFactoryInterfaceGeneratorProcessor, IEntityGenerationModel>
{
public ConstructorMethod(ITestOutputHelper output) : base(output)
{
}
protected override Func<AttributeData, QueryFactoryInterfaceGenerator> GetFactory()
{
return data => new TestQueryFactoryInterfaceGenerator();
}
}
public sealed class GenerateAsyncMethod : BaseGeneratorTests.BaseGenerateAsyncMethod<QueryFactoryInterfaceGenerator, QueryFactoryInterfaceFeatureFlags, QueryFactoryInterfaceGeneratorProcessor, IEntityGenerationModel>
{
public GenerateAsyncMethod(ITestOutputHelper output) : base(output)
{
}
protected override Func<AttributeData, QueryFactoryInterfaceGenerator> GetFactory()
{
return data => new TestQueryFactoryInterfaceGenerator();
}
}
}
} | 37.186047 | 224 | 0.72858 | [
"Apache-2.0"
] | dpvreony/nucleotide | src/Dhgms.Nucleotide.UnitTests/Generators/Cqrs/QueryFactoryInterfaceGeneratorTests.cs | 1,601 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web.Services.Protocols;
using DotNetShipping.RateServiceWebReference;
namespace DotNetShipping.ShippingProviders
{
public abstract class FedExBaseProvider : AbstractShippingProvider
{
protected string _accountNumber;
protected string _key;
protected string _meterNumber;
protected string _password;
protected bool _useProduction = true;
protected Dictionary<string, string> _serviceCodes;
/// <summary>
/// FedEx allows insured values for items being shipped except when utilizing SmartPost. This setting will this value to be overwritten.
/// </summary>
protected bool _allowInsuredValues = true;
/// <summary>
/// Paramaterless constructor that loads settings from app.config
/// </summary>
protected FedExBaseProvider()
{
var appSettings = ConfigurationManager.AppSettings;
Init(appSettings["FedExKey"], appSettings["FedExPassword"], appSettings["FedExAccountNumber"], appSettings["FedExMeterNumber"], true);
}
/// <summary>
/// </summary>
/// <param name="key"></param>
/// <param name="password"></param>
/// <param name="accountNumber"></param>
/// <param name="meterNumber"></param>
protected FedExBaseProvider(string key, string password, string accountNumber, string meterNumber)
{
Init(key, password, accountNumber, meterNumber, true);
}
private void Init(string key, string password, string accountNumber, string meterNumber, bool useProduction)
{
Name = "FedEx";
_key = key;
_password = password;
_accountNumber = accountNumber;
_meterNumber = meterNumber;
_useProduction = useProduction;
}
/// <summary>
/// Sets service codes.
/// </summary>
protected abstract void SetServiceCodes();
/// <summary>
/// Gets service codes.
/// </summary>
/// <returns></returns>
public IDictionary<string, string> GetServiceCodes()
{
if (_serviceCodes != null && _serviceCodes.Count > 0)
{
return new Dictionary<string, string>(_serviceCodes);
}
return null;
}
/// <summary>
/// Creates the rate request
/// </summary>
/// <returns></returns>
protected RateRequest CreateRateRequest()
{
// Build the RateRequest
var request = new RateRequest();
request.WebAuthenticationDetail = new WebAuthenticationDetail();
request.WebAuthenticationDetail.UserCredential = new WebAuthenticationCredential();
request.WebAuthenticationDetail.UserCredential.Key = _key;
request.WebAuthenticationDetail.UserCredential.Password = _password;
request.ClientDetail = new ClientDetail();
request.ClientDetail.AccountNumber = _accountNumber;
request.ClientDetail.MeterNumber = _meterNumber;
request.Version = new VersionId();
request.ReturnTransitAndCommit = true;
request.ReturnTransitAndCommitSpecified = true;
SetShipmentDetails(request);
return request;
}
/// <summary>
/// Sets shipment details
/// </summary>
/// <param name="request"></param>
protected abstract void SetShipmentDetails(RateRequest request);
/// <summary>
/// Gets rates
/// </summary>
public override void GetRates()
{
var request = CreateRateRequest();
var service = new RateService(_useProduction);
try
{
// Call the web service passing in a RateRequest and returning a RateReply
var reply = service.getRates(request);
//
if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING)
{
ProcessReply(reply);
}
ShowNotifications(reply);
}
catch (SoapException e)
{
Debug.WriteLine(e.Detail.InnerText);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
/// <summary>
/// Processes the reply
/// </summary>
/// <param name="reply"></param>
protected void ProcessReply(RateReply reply)
{
foreach (var rateReplyDetail in reply.RateReplyDetails)
{
var netCharge = rateReplyDetail.RatedShipmentDetails.Max(x => x.ShipmentRateDetail.TotalNetCharge.Amount);
var key = rateReplyDetail.ServiceType.ToString();
var deliveryDate = rateReplyDetail.DeliveryTimestampSpecified ? rateReplyDetail.DeliveryTimestamp : DateTime.Now.AddDays(30);
AddRate(key, _serviceCodes[key], netCharge, deliveryDate);
}
}
/// <summary>
/// Sets the destination
/// </summary>
/// <param name="request"></param>
protected void SetDestination(RateRequest request)
{
request.RequestedShipment.Recipient = new Party();
request.RequestedShipment.Recipient.Address = new RateServiceWebReference.Address();
request.RequestedShipment.Recipient.Address.StreetLines = new string[1] { "" };
request.RequestedShipment.Recipient.Address.City = "";
request.RequestedShipment.Recipient.Address.StateOrProvinceCode = "";
request.RequestedShipment.Recipient.Address.PostalCode = Shipment.DestinationAddress.PostalCode;
request.RequestedShipment.Recipient.Address.CountryCode = Shipment.DestinationAddress.CountryCode;
request.RequestedShipment.Recipient.Address.Residential = Shipment.DestinationAddress.IsResidential;
request.RequestedShipment.Recipient.Address.ResidentialSpecified = Shipment.DestinationAddress.IsResidential;
}
/// <summary>
/// Sets the origin
/// </summary>
/// <param name="request"></param>
protected void SetOrigin(RateRequest request)
{
request.RequestedShipment.Shipper = new Party();
request.RequestedShipment.Shipper.Address = new RateServiceWebReference.Address();
request.RequestedShipment.Shipper.Address.StreetLines = new string[1] { "" };
request.RequestedShipment.Shipper.Address.City = "";
request.RequestedShipment.Shipper.Address.StateOrProvinceCode = "";
request.RequestedShipment.Shipper.Address.PostalCode = Shipment.OriginAddress.PostalCode;
request.RequestedShipment.Shipper.Address.CountryCode = Shipment.OriginAddress.CountryCode;
request.RequestedShipment.Shipper.Address.Residential = Shipment.OriginAddress.IsResidential;
request.RequestedShipment.Shipper.Address.ResidentialSpecified = Shipment.OriginAddress.IsResidential;
}
/// <summary>
/// Sets package line items
/// </summary>
/// <param name="request"></param>
protected void SetPackageLineItems(RateRequest request)
{
request.RequestedShipment.RequestedPackageLineItems = new RequestedPackageLineItem[Shipment.PackageCount];
var i = 0;
foreach (var package in Shipment.Packages)
{
request.RequestedShipment.RequestedPackageLineItems[i] = new RequestedPackageLineItem();
request.RequestedShipment.RequestedPackageLineItems[i].SequenceNumber = (i + 1).ToString();
request.RequestedShipment.RequestedPackageLineItems[i].GroupPackageCount = "1";
// package weight
request.RequestedShipment.RequestedPackageLineItems[i].Weight = new Weight();
request.RequestedShipment.RequestedPackageLineItems[i].Weight.Units = WeightUnits.LB;
request.RequestedShipment.RequestedPackageLineItems[i].Weight.Value = package.RoundedWeight;
// package dimensions
request.RequestedShipment.RequestedPackageLineItems[i].Dimensions = new Dimensions();
request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Length = package.RoundedLength.ToString();
request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Width = package.RoundedWidth.ToString();
request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Height = package.RoundedHeight.ToString();
request.RequestedShipment.RequestedPackageLineItems[i].Dimensions.Units = LinearUnits.IN;
if (_allowInsuredValues)
{
// package insured value
request.RequestedShipment.RequestedPackageLineItems[i].InsuredValue = new Money();
request.RequestedShipment.RequestedPackageLineItems[i].InsuredValue.Amount = package.InsuredValue;
request.RequestedShipment.RequestedPackageLineItems[i].InsuredValue.AmountSpecified = true;
request.RequestedShipment.RequestedPackageLineItems[i].InsuredValue.Currency = "USD";
}
if (package.SignatureRequiredOnDelivery)
{
var signatureOptionDetail = new SignatureOptionDetail { OptionType = SignatureOptionType.DIRECT };
var specialServicesRequested = new PackageSpecialServicesRequested() { SignatureOptionDetail = signatureOptionDetail };
request.RequestedShipment.RequestedPackageLineItems[i].SpecialServicesRequested = specialServicesRequested;
}
i++;
}
}
/// <summary>
/// Outputs the notifications to the debug console
/// </summary>
/// <param name="reply"></param>
protected static void ShowNotifications(RateReply reply)
{
Debug.WriteLine("Notifications");
for (var i = 0; i < reply.Notifications.Length; i++)
{
var notification = reply.Notifications[i];
Debug.WriteLine("Notification no. {0}", i);
Debug.WriteLine(" Severity: {0}", notification.Severity);
Debug.WriteLine(" Code: {0}", notification.Code);
Debug.WriteLine(" Message: {0}", notification.Message);
Debug.WriteLine(" Source: {0}", notification.Source);
}
}
}
}
| 43.098425 | 197 | 0.62556 | [
"MIT"
] | judah4/DotNetShipping | DotNetShipping/ShippingProviders/FedExBaseProvider.cs | 10,949 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 08.05.2021.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.NullableDouble.NullableDouble{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Double>;
using T_DATA2 =System.Nullable<System.Double>;
using T_DATA1_U=System.Double;
using T_DATA2_U=System.Double;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields__01__VV
public static class TestSet_001__fields__01__VV
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_DOUBLE";
private const string c_NameOf__COL_DATA2 ="COL2_DOUBLE";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1_U c_value1=3;
const T_DATA2_U c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
var recs=db.testTable.Where(r => (((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA1).IS_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND ((").N("t",c_NameOf__COL_DATA1).IS_NOT_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NOT_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1_U c_value1=4;
const T_DATA2_U c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
var recs=db.testTable.Where(r => (((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA1).IS_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND ((").N("t",c_NameOf__COL_DATA1).IS_NOT_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NOT_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1_U c_value1=5;
const T_DATA2_U c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
var recs=db.testTable.Where(r => (((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA1).IS_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND ((").N("t",c_NameOf__COL_DATA1).IS_NOT_NULL().T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NOT_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_003__greater
//Helper methods --------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.NullableDouble.NullableDouble
| 31.444 | 361 | 0.568757 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/NotEqual/Complete2__objs/NullableDouble/NullableDouble/TestSet_001__fields__01__VV.cs | 7,863 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
public partial class RangeVariable
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IRangeVariable.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IRangeVariable.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IRangeVariable FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new RangeVariable(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="RangeVariable" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param>
internal RangeVariable(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_typeReference = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject>("typeReference"), out var __jsonTypeReference) ? Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180901Preview.IedmTypeReference.FromJson(__jsonTypeReference) : TypeReference;}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_kind = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNumber>("kind"), out var __jsonKind) ? (int?)__jsonKind : Kind;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="RangeVariable" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="RangeVariable" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != this._typeReference ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) this._typeReference.ToJson(null,serializationMode) : null, "typeReference" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != this._kind ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNumber((int)this._kind) : null, "kind" ,container.Add );
}
AfterToJson(ref container);
return container;
}
}
} | 70.353982 | 302 | 0.683522 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180901Preview/RangeVariable.json.cs | 7,838 | C# |
/*
Copyright (C) 2008 Jeroen Frijters
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
namespace IKVM.Reflection.Emit
{
public struct EventToken
{
public static readonly EventToken Empty;
private readonly int token;
internal EventToken(int token)
{
this.token = token;
}
public int Token
{
get { return token; }
}
public override bool Equals(object obj)
{
return obj as EventToken? == this;
}
public override int GetHashCode()
{
return token;
}
public bool Equals(EventToken other)
{
return this == other;
}
public static bool operator ==(EventToken et1, EventToken et2)
{
return et1.token == et2.token;
}
public static bool operator !=(EventToken et1, EventToken et2)
{
return et1.token != et2.token;
}
}
public struct FieldToken
{
public static readonly FieldToken Empty;
private readonly int token;
internal FieldToken(int token)
{
this.token = token;
}
internal bool IsPseudoToken
{
get { return token < 0; }
}
public int Token
{
get { return token; }
}
public override bool Equals(object obj)
{
return obj as FieldToken? == this;
}
public override int GetHashCode()
{
return token;
}
public bool Equals(FieldToken other)
{
return this == other;
}
public static bool operator ==(FieldToken ft1, FieldToken ft2)
{
return ft1.token == ft2.token;
}
public static bool operator !=(FieldToken ft1, FieldToken ft2)
{
return ft1.token != ft2.token;
}
}
public struct MethodToken
{
public static readonly MethodToken Empty;
private readonly int token;
internal MethodToken(int token)
{
this.token = token;
}
internal bool IsPseudoToken
{
get { return token < 0; }
}
public int Token
{
get { return token; }
}
public override bool Equals(object obj)
{
return obj as MethodToken? == this;
}
public override int GetHashCode()
{
return token;
}
public bool Equals(MethodToken other)
{
return this == other;
}
public static bool operator ==(MethodToken mt1, MethodToken mt2)
{
return mt1.token == mt2.token;
}
public static bool operator !=(MethodToken mt1, MethodToken mt2)
{
return mt1.token != mt2.token;
}
}
public struct SignatureToken
{
public static readonly SignatureToken Empty;
private readonly int token;
internal SignatureToken(int token)
{
this.token = token;
}
public int Token
{
get { return token; }
}
public override bool Equals(object obj)
{
return obj as SignatureToken? == this;
}
public override int GetHashCode()
{
return token;
}
public bool Equals(SignatureToken other)
{
return this == other;
}
public static bool operator ==(SignatureToken st1, SignatureToken st2)
{
return st1.token == st2.token;
}
public static bool operator !=(SignatureToken st1, SignatureToken st2)
{
return st1.token != st2.token;
}
}
public struct StringToken
{
private readonly int token;
internal StringToken(int token)
{
this.token = token;
}
public int Token
{
get { return token; }
}
public override bool Equals(object obj)
{
return obj as StringToken? == this;
}
public override int GetHashCode()
{
return token;
}
public bool Equals(StringToken other)
{
return this == other;
}
public static bool operator ==(StringToken st1, StringToken st2)
{
return st1.token == st2.token;
}
public static bool operator !=(StringToken st1, StringToken st2)
{
return st1.token != st2.token;
}
}
public struct TypeToken
{
public static readonly TypeToken Empty;
private readonly int token;
internal TypeToken(int token)
{
this.token = token;
}
public int Token
{
get { return token; }
}
public override bool Equals(object obj)
{
return obj as TypeToken? == this;
}
public override int GetHashCode()
{
return token;
}
public bool Equals(TypeToken other)
{
return this == other;
}
public static bool operator ==(TypeToken tt1, TypeToken tt2)
{
return tt1.token == tt2.token;
}
public static bool operator !=(TypeToken tt1, TypeToken tt2)
{
return tt1.token != tt2.token;
}
}
}
| 18.046099 | 76 | 0.675378 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/class/IKVM.Reflection/Emit/Tokens.cs | 5,089 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Project.EnviromentObjects.Scripts
{
public class FallingPlatformController : MonoBehaviour
{
[SerializeField] private TargetJoint2D targetJoint2D;
[SerializeField] private BoxCollider2D boxCollider2D;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
StartCoroutine(FallPlatform());
}
}
private IEnumerator FallPlatform()
{
yield return new WaitForSeconds(2);
targetJoint2D.enabled = false;
boxCollider2D.enabled = false;
Destroy(this.gameObject, 5f);
}
}
}
| 25.3125 | 62 | 0.623457 | [
"MIT"
] | IanAlves21/TCC1-Project | Assets/Project/EnviromentObjects/Scripts/FallingPlatformController.cs | 810 | C# |
namespace MSR.CVE.BackMaker.ImagePipeline
{
public class VEAddressLayout : ITileAddressLayout
{
public int XValueOneTileEast(TileAddress ta)
{
return WrapLongitude(ta.TileX + 1, ta.ZoomLevel);
}
public static int WrapLongitude(int TileX, int ZoomLevel)
{
int num = (1 << ZoomLevel) - 1;
return TileX & num;
}
public int YValueOneTileSouth(TileAddress ta)
{
return ta.TileY + 1;
}
}
}
| 23.545455 | 65 | 0.561776 | [
"MIT"
] | AkisKK/GMap.NET | Tools/MapCruncher/MSR.CVE.BackMaker.ImagePipeline/VEAddressLayout.cs | 518 | C# |
using UnityEngine;
using System.Collections;
public class FollowTransform : ExecutionOrderBehaviour {
public Transform follower;
public Transform target;
// Update is called once per frame
public override void LateUpdateCustom () {
follower.position = target.position;
}
}
| 20.5 | 56 | 0.770035 | [
"Apache-2.0"
] | MWold/RagdollThrower | Assets/3rdPersonShooter/Demo Scene Scripts/FollowTransform.cs | 287 | C# |
using System;
namespace IB.CSharpApiClient.Events
{
public class TickNewsEventArgs : EventArgs
{
public TickNewsEventArgs(int tickerId, long timeStamp, string providerCode, string articleId, string headline, string extraData)
{
TickerId = tickerId;
TimeStamp = timeStamp;
ProviderCode = providerCode;
ArticleId = articleId;
Headline = headline;
ExtraData = extraData;
}
public int TickerId { get; }
public long TimeStamp { get; }
public string ProviderCode { get; }
public string ArticleId { get; }
public string Headline { get; }
public string ExtraData { get; }
public override string ToString()
{
return $"{nameof(ArticleId)}: {ArticleId}, {nameof(ExtraData)}: {ExtraData}, {nameof(Headline)}: {Headline}, {nameof(ProviderCode)}: {ProviderCode}, {nameof(TickerId)}: {TickerId}, {nameof(TimeStamp)}: {TimeStamp}";
}
}
} | 35.034483 | 227 | 0.609252 | [
"MIT"
] | Hummel83/IB.CSharpApiClient | src/IB.CSharpApiClient/Events/TickNewsEventArgs.cs | 1,016 | C# |
/* Copyright (c) 2015 Tizian Zeltner, ETH Zurich
*
* 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 UnityEngine;
using System.Collections;
public class ConnectedLeverAction : LeverAction
{
public int i;
private ConnectedLeverPuzzleLogic logic;
void Start()
{
logic = GetComponentInParent<ConnectedLeverPuzzleLogic>();
}
override protected void Action()
{
logic.Toggle(i);
SoundManager.Instance.PlaySound(SoundManager.buttonSound);
}
override protected void OnUpdate()
{
if (logic.IsSolved())
{
leverScript.Deactivate();
}
else
{
leverScript.Activate();
}
}
} | 31.056604 | 80 | 0.745443 | [
"MIT"
] | fi-content2-games-platform/FIcontent.Gaming.Application.TreasureHunt | Assets/Scripts/Puzzles/ConnectedLeversPuzzle/ConnectedLeverAction.cs | 1,648 | C# |
using Newtonsoft.Json.Linq;
using Skybrud.Essentials.Json.Extensions;
using Skybrud.Social.Google.Models;
namespace Skybrud.Social.Google.Geocoding.Models {
/// <summary>
/// Class representing an address component of a <see cref="GeocodingResult"/>.
/// </summary>
public class GeocodingAddressComponent : GoogleApiObject {
#region Properties
/// <summary>
/// Gets the long name of the address component.
/// </summary>
public string LongName { get; }
/// <summary>
/// Gets the short name of the address component.
/// </summary>
public string ShortName { get; }
/// <summary>
/// Gets an array of tags/keywords that describe the type of the address component.
/// </summary>
public string[] Types { get; }
#endregion
#region Constructors
private GeocodingAddressComponent(JObject obj) : base(obj) {
LongName = obj.GetString("long_name");
ShortName = obj.GetString("short_name");
Types = obj.GetStringArray("types");
}
#endregion
#region Static methods
/// <summary>
/// Gets an instance of <see cref="GeocodingAddressComponent"/> from the specified <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The instance of <see cref="JObject"/> representing the address component.</param>
/// <returns>An instance of <see cref="GeocodingAddressComponent"/>.</returns>
public static GeocodingAddressComponent Parse(JObject obj) {
return obj == null ? null : new GeocodingAddressComponent(obj);
}
#endregion
}
} | 30.714286 | 114 | 0.60814 | [
"MIT"
] | abjerner/Skybrud.Social.Google.Geocoding | src/Skybrud.Social.Google.Geocoding/Models/GeocodingAddressComponent.cs | 1,722 | C# |
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AngelSix.SolidDna
{
/// <summary>
/// A command group for the top command bar in SolidWorks
/// </summary>
public class CommandManagerGroup : SolidDnaObject<ICommandGroup>
{
#region Private Members
/// <summary>
/// Keeps track if this group has been created already
/// </summary>
private bool mCreated;
/// <summary>
/// A list of all tabs that have been created
/// </summary>
private Dictionary<CommandManagerTabKey, CommandManagerTab> mTabs = new Dictionary<CommandManagerTabKey, CommandManagerTab>();
#endregion
#region Public Properties
/// <summary>
/// The Id used when this command group was created
/// </summary>
public int UserId { get; private set; }
/// <summary>
/// The title of this command group
/// </summary>
public string Title { get; set; }
/// <summary>
/// The hint of this command group
/// </summary>
public string Hint { get; set; }
/// <summary>
/// The tooltip of this command group
/// </summary>
public string Tooltip { get; set; }
/// <summary>
/// The absolute path to the bmp or png that contains an icon list containing all the icons for items in this group
/// This list should be 20px heigh, and each icon is 20x20, joined horizontally.
/// So a list of 4 icons would be 80px wide by 20px height
/// </summary>
public string IconList20Path { get; set; }
/// <summary>
/// The absolute path to the bmp or png that contains an icon list containing all the icons for items in this group
/// This list should be 32px heigh, and each icon is 32x32, joined horizontally.
/// So a list of 4 icons would be 128px wide by 32px height
/// </summary>
public string IconList32Path { get; set; }
/// <summary>
/// The absolute path to the bmp or png that contains an icon list containing all the icons for items in this group
/// This list should be 40px heigh, and each icon is 40x40, joined horizontally.
/// So a list of 4 icons would be 160px wide by 40px height
/// </summary>
public string IconList40Path { get; set; }
/// <summary>
/// The absolute path to the bmp or png that contains an icon list containing all the icons for items in this group
/// This list should be 64px heigh, and each icon is 64x64, joined horizontally.
/// So a list of 4 icons would be 256px wide by 64px height
/// </summary>
public string IconList64Path { get; set; }
/// <summary>
/// The absolute path to the bmp or png that contains an icon list containing all the icons for items in this group
/// This list should be 96px heigh, and each icon is 96x96, joined horizontally.
/// So a list of 4 icons would be 384px wide by 96px height
/// </summary>
public string IconList96Path { get; set; }
/// <summary>
/// The absolute path to the bmp or png that contains an icon list containing all the icons for items in this group
/// This list should be 20px heigh, and each icon is 128x128, joined horizontally.
/// So a list of 4 icons would be 512px wide by 128px height
/// </summary>
public string IconList128Path { get; set; }
/// <summary>
/// The type of documents to show this command group in as a menu
/// </summary>
public ModelTemplateType MenuVisibleInDocumentTypes
{
get
{
return (ModelTemplateType)mBaseObject.ShowInDocumentType;
}
set
{
// Set base object
mBaseObject.ShowInDocumentType = (int)value;
}
}
/// <summary>
/// Whether this command group has a Menu.
/// NOTE: The menu is the regular drop-down menu like File, Edit, View etc...
/// </summary>
public bool HasMenu
{
get
{
return mBaseObject.HasMenu;
}
set
{
// Set base object
mBaseObject.HasMenu = value;
}
}
/// <summary>
/// Whether this command group has a Toolbar.
/// NOTE: The toolbar is the small icons like the top-left SolidWorks menu New, Save, Open etc...
/// </summary>
public bool HasToolbar
{
get
{
return mBaseObject.HasToolbar;
}
set
{
// Set base object
mBaseObject.HasToolbar = value;
}
}
/// <summary>
/// The command items to add to this group
/// </summary>
public List<CommandManagerItem> Items { get; set; }
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <param name="userId">The unique Id this group was assigned with when created</param>
/// <param name="title">The title</param>
/// <param name="items">The command items to add</param>
/// <param name="tooltip">The tool tip</param>
/// <param name="hint">The hint</param>
public CommandManagerGroup(ICommandGroup commandGroup, List<CommandManagerItem> items, int userId, string title, string hint, string tooltip) : base(commandGroup)
{
// Store user Id, used to remove the command group
this.UserId = userId;
// Set items
this.Items = items;
// Set title
this.Title = title;
// Set hint
this.Hint = hint;
// Set tooltip
this.Tooltip = tooltip;
// Set defaults
// Show for all types
this.MenuVisibleInDocumentTypes = ModelTemplateType.Assembly | ModelTemplateType.Part | ModelTemplateType.Drawing;
// Have a menu
this.HasMenu = true;
// Have a toolbar
this.HasToolbar = true;
// Listen out for callbacks
PlugInIntegration.CallbackFired += PlugInIntegration_CallbackFired;
}
#endregion
#region Icon List Methods
/// <summary>
/// The list of full paths to a bmp or png's that contains the icon list
/// from first in the list being the smallest, to last being the largest
/// NOTE: Supported sizes for each icon in an array is 20x20, 32x32, 40x40, 64x64, 96x96 and 128x128
/// Set them via the appropriate properties on this class
/// </summary>
public List<string> GetIconListPaths()
{
// Create list
var list = new List<string>();
// Add 20x20 icons
if (!string.IsNullOrEmpty(IconList20Path))
list.Add(IconList20Path);
// Add 32x32 icons
if (!string.IsNullOrEmpty(IconList32Path))
list.Add(IconList32Path);
// Add 40x40 icons
if (!string.IsNullOrEmpty(IconList40Path))
list.Add(IconList40Path);
// Add 64x64 icons
if (!string.IsNullOrEmpty(IconList64Path))
list.Add(IconList64Path);
// Add 96x96 icons
if (!string.IsNullOrEmpty(IconList96Path))
list.Add(IconList96Path);
// Add 128 icons
if (!string.IsNullOrEmpty(IconList128Path))
list.Add(IconList128Path);
// Return the list
return list;
}
/// <summary>
/// Set's all icon lists based on a string format of the absolute path to the icon list images, replacing {0} with the size.
/// For example C:\Folder\myiconlist{0}.png would look for all sizes such as
/// C:\Folder\myiconlist20.png
/// C:\Folder\myiconlist32.png
/// C:\Folder\myiconlist40.png
/// ... and so on
/// </summary>
/// <param name="pathFormat">The absolute path, with {0} used to replace with the icon size</param>
public void SetIconLists(string pathFormat)
{
// Make sure we have something
if (string.IsNullOrWhiteSpace(pathFormat))
return;
// Make sure the path format contains "{0}"
if (!pathFormat.Contains("{0}"))
throw new SolidDnaException(SolidDnaErrors.CreateError(
SolidDnaErrorTypeCode.SolidWorksCommandManager,
SolidDnaErrorCode.SolidWorksCommandGroupIvalidPathFormatError,
Localization.GetString("ErrorSolidWorksCommandGroupIconListInvalidPathError")));
// Find 20 image
var result = string.Format(pathFormat, 20);
if (File.Exists(result))
IconList20Path = result;
// Find 32 image
result = string.Format(pathFormat, 32);
if (File.Exists(result))
IconList32Path = result;
// Find 40 image
result = string.Format(pathFormat, 40);
if (File.Exists(result))
IconList40Path = result;
// Find 64 image
result = string.Format(pathFormat, 64);
if (File.Exists(result))
IconList64Path = result;
// Find 96 image
result = string.Format(pathFormat, 96);
if (File.Exists(result))
IconList96Path = result;
// Find 128 image
result = string.Format(pathFormat, 128);
if (File.Exists(result))
IconList128Path = result;
}
#endregion
#region Callbacks
/// <summary>
/// Fired when a SolidWorks callback is fired
/// </summary>
/// <param name="name">The name of the callback that was fired</param>
private void PlugInIntegration_CallbackFired(string name)
{
// Find the item, if any
var item = this.Items.FirstOrDefault(f => f.CallbackId == name);
// Call the action
item?.OnClick?.Invoke();
}
#endregion
#region Public Methods
/// <summary>
/// Adds a command item to the group
/// </summary>
/// <param name="item">The item to add</param>
public void AddCommandItem(CommandManagerItem item)
{
// Add the item
var id = mBaseObject.AddCommandItem2(item.Name, item.Position, item.Hint, item.Tooltip, item.ImageIndex, $"Callback({item.CallbackId})", null, this.UserId, (int)item.ItemType);
// Set the Id we got
item.UniqueId = id;
}
/// <summary>
/// Creates the command group based on it's current children
/// NOTE: Once created, parent command manager must remove and re-create the group
/// This group cannot be re-used after creating, any edits will not take place
/// </summary>
/// <param name="manager">The command manager that is our owner</param>
public void Create(CommandManager manager)
{
if (mCreated)
throw new SolidDnaException(SolidDnaErrors.CreateError(
SolidDnaErrorTypeCode.SolidWorksCommandManager,
SolidDnaErrorCode.SolidWorksCommandGroupReActivateError,
Localization.GetString("ErrorSolidWorksCommandGroupReCreateError")));
#region Set Icons
//
// Set the icons
//
// NOTE: The order in which you specify the icons must be the same for this property and MainIconList.
//
// For example, if you specify an array of paths to
// 20 x 20 pixels, 32 x 32 pixels, and 40 x 40 pixels icons for this property
// then you must specify an array of paths to
// 20 x 20 pixels, 32 x 32 pixels, and 40 x 40 pixels icons for MainIconList.</remarks>
//
// Set all icon lists
var icons = GetIconListPaths();
// 2016+ support
mBaseObject.IconList = icons.ToArray();
// <2016 support
if (icons.Count > 0)
{
// Largest icon for this one
mBaseObject.LargeIconList = icons.Last();
// The list of icons
mBaseObject.MainIconList = icons.ToArray();
// Use the largest available image for small icons too
mBaseObject.SmallIconList = icons.Last();
}
#endregion
#region Add Items
// Add items
this.Items?.ForEach(item => AddCommandItem(item));
#endregion
// Activate the command group
mCreated = mBaseObject.Activate();
// Get command Ids
this.Items?.ForEach(item => item.CommandId = mBaseObject.CommandID[item.UniqueId]);
#region Command Tab
// Add to parts tab
var list = this.Items.Where(f => f.TabView != CommandManagerItemTabView.None && f.VisibleForParts).ToList();
if (list?.Count > 0)
AddItemsToTab(ModelType.Part, manager, list);
// Add to assembly tab
list = this.Items.Where(f => f.TabView != CommandManagerItemTabView.None && f.VisibleForAssemblies).ToList();
if (list?.Count > 0)
AddItemsToTab(ModelType.Assembly, manager, list);
// Add to drawing tab
list = this.Items.Where(f => f.TabView != CommandManagerItemTabView.None && f.VisibleForDrawings).ToList();
if (list?.Count > 0)
AddItemsToTab(ModelType.Drawing, manager, list);
#endregion
// If we failed to create, throw
if (!mCreated)
throw new SolidDnaException(SolidDnaErrors.CreateError(
SolidDnaErrorTypeCode.SolidWorksCommandManager,
SolidDnaErrorCode.SolidWorksCommandGroupActivateError,
Localization.GetString("ErrorSolidWorksCommandGroupActivateError")));
}
/// <summary>
/// Adds all <see cref="Items"/> to the command tab of the given title and model type
/// </summary>
/// <param name="type">The tab for this type of model</param>
/// <param name="manager">The command manager</param>
/// <param name="title">The title of the tab</param>
public void AddItemsToTab(ModelType type, CommandManager manager, List<CommandManagerItem> items, string title = "")
{
// Use default title if not specified
if (string.IsNullOrEmpty(title))
title = this.Title;
CommandManagerTab tab = null;
// Get the tab it it already exists
if (mTabs.Any(f => string.Equals(f.Key.Title, title) && f.Key.ModelType == type))
tab = mTabs.First(f => string.Equals(f.Key.Title, title) && f.Key.ModelType == type).Value;
// Otherwise create it
else
{
// Get the tab
tab = manager.GetCommandTab(type, title, createIfNotExist: true);
// Keep track of this tab
mTabs.Add(new CommandManagerTabKey { ModelType = type, Title = title }, tab);
}
// New list of values
var ids = new List<int>();
var styles = new List<int>();
// Add each items Id and style
items.ForEach(item =>
{
// Add command Id
ids.Add(item.CommandId);
// Add style
styles.Add((int)item.TabView);
});
// Add all the items
tab.Box.UnsafeObject.AddCommands(ids.ToArray(), styles.ToArray());
}
#endregion
#region Dispose
/// <summary>
/// Disposing
/// </summary>
public override void Dispose()
{
// Stop listening out for callbacks
PlugInIntegration.CallbackFired -= PlugInIntegration_CallbackFired;
// Dispose all tabs
foreach (var tab in mTabs.Values)
tab.Dispose();
base.Dispose();
}
#endregion
}
}
| 35.339623 | 188 | 0.556742 | [
"MIT"
] | Yobeekster/SolidWorks | SolidDna/AngelSix.SolidDna/SolidWorks/CommandManager/Group/CommandManagerGroup.cs | 16,859 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace InjectorGames.FarAlone.Items
{
[Serializable]
public class GunItem : WeaponItem
{
[SerializeField]
protected GameObject bulletPrefab;
public GameObject BulletPrefab => bulletPrefab;
}
}
| 20.722222 | 55 | 0.726542 | [
"Apache-2.0"
] | InjectorGames/FarAlone | Assets/FarAlone/Scripts/Items/GunItem.cs | 375 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
namespace Time_Owner
{
static class Extensions
{
public static void Swap<T>(this ObservableCollection<T> list, int index1, int index2)
{
T temp = list[index1];
list[index1] = list[index2];
list[index2] = temp;
}
}
}
| 22.2 | 93 | 0.641892 | [
"MIT"
] | Testosterone59/WPF_Time-Manager | Time Owner/Time Owner/Extensions.cs | 446 | C# |
using ALE.ETLBox;
using ALE.ETLBox.ConnectionManager;
using ALE.ETLBox.ControlFlow;
using ALE.ETLBox.DataFlow;
using ALE.ETLBox.Helper;
using ALE.ETLBox.Logging;
using ALE.ETLBoxTests.Fixtures;
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using Xunit;
namespace ALE.ETLBoxTests.DataFlowTests
{
[Collection("DataFlow")]
public class JsonDestinationDynamicObjectTests
{
public SqlConnectionManager SqlConnection => Config.SqlConnection.ConnectionManager("DataFlow");
public JsonDestinationDynamicObjectTests(DataFlowDatabaseFixture dbFixture)
{
}
[Fact]
public void SimpleFlowWithObject()
{
//Arrange
TwoColumnsTableFixture s2C = new TwoColumnsTableFixture("JsonDestDynamic");
s2C.InsertTestDataSet3();
DbSource<ExpandoObject> source = new DbSource<ExpandoObject>(SqlConnection, "JsonDestDynamic");
//Act
JsonDestination<ExpandoObject> dest = new JsonDestination<ExpandoObject>("./SimpleWithDynamicObject.json", ResourceType.File);
source.LinkTo(dest);
source.Execute();
dest.Wait();
//Assert
//Null values can't be ignored:
//https://github.com/JamesNK/Newtonsoft.Json/issues/1466
Assert.Equal(File.ReadAllText("res/JsonDestination/TwoColumnsSet3DynamicObject.json"),
File.ReadAllText("./SimpleWithDynamicObject.json"));
}
}
}
| 32.78 | 138 | 0.691885 | [
"MIT"
] | SipanOhanyan/etlbox | TestsETLBox/src/DataFlowTests/JsonDestination/JsonDestinationDynamicObjectTests.cs | 1,639 | C# |
namespace Genbox.SimpleS3.Core.Network.Responses.Buckets;
public class DeleteBucketTaggingResponse : BaseResponse {} | 39.333333 | 58 | 0.847458 | [
"MIT"
] | Genbox/SimpleS3Net | src/SimpleS3.Core/Network/Responses/Buckets/DeleteBucketTaggingResponse.cs | 120 | C# |
using System;
using System.IO;
using Abp.Reflection.Extensions;
namespace KP.FunOA
{
/// <summary>
/// Central point for application version.
/// </summary>
public class AppVersionHelper
{
/// <summary>
/// Gets current version of the application.
/// It's also shown in the web page.
/// </summary>
public const string Version = "5.5.0.0";
/// <summary>
/// Gets release (last build) date of the application.
/// It's shown in the web page.
/// </summary>
public static DateTime ReleaseDate => LzyReleaseDate.Value;
private static readonly Lazy<DateTime> LzyReleaseDate = new Lazy<DateTime>(() => new FileInfo(typeof(AppVersionHelper).GetAssembly().Location).LastWriteTime);
}
}
| 29.481481 | 166 | 0.619347 | [
"MIT"
] | wx0322/KpOA | aspnet-core/src/KP.FunOA.Core/AppVersionHelper.cs | 798 | C# |
// <auto-generated />
// Built from: hl7.fhir.r4b.core version: 4.1.0
// Option: "NAMESPACE" = "fhirCsR4"
using fhirCsR4.Models;
namespace fhirCsR4.ValueSets
{
/// <summary>
/// Category of an identified substance associated with allergies or intolerances.
/// </summary>
public static class AllergyIntoleranceCategoryCodes
{
/// <summary>
/// A preparation that is synthesized from living organisms or their products, especially a human or animal protein, such as a hormone or antitoxin, that is used as a diagnostic, preventive, or therapeutic agent. Examples of biologic medications include: vaccines; allergenic extracts, which are used for both diagnosis and treatment (for example, allergy shots); gene therapies; cellular therapies. There are other biologic products, such as tissues, which are not typically associated with allergies.
/// </summary>
public static readonly Coding Biologic = new Coding
{
Code = "biologic",
Display = "Biologic",
System = "http://hl7.org/fhir/allergy-intolerance-category"
};
/// <summary>
/// Any substances that are encountered in the environment, including any substance not already classified as food, medication, or biologic.
/// </summary>
public static readonly Coding Environment = new Coding
{
Code = "environment",
Display = "Environment",
System = "http://hl7.org/fhir/allergy-intolerance-category"
};
/// <summary>
/// Any substance consumed to provide nutritional support for the body.
/// </summary>
public static readonly Coding Food = new Coding
{
Code = "food",
Display = "Food",
System = "http://hl7.org/fhir/allergy-intolerance-category"
};
/// <summary>
/// Substances administered to achieve a physiological effect.
/// </summary>
public static readonly Coding Medication = new Coding
{
Code = "medication",
Display = "Medication",
System = "http://hl7.org/fhir/allergy-intolerance-category"
};
/// <summary>
/// Literal for code: Biologic
/// </summary>
public const string LiteralBiologic = "biologic";
/// <summary>
/// Literal for code: Environment
/// </summary>
public const string LiteralEnvironment = "environment";
/// <summary>
/// Literal for code: Food
/// </summary>
public const string LiteralFood = "food";
/// <summary>
/// Literal for code: Medication
/// </summary>
public const string LiteralMedication = "medication";
};
}
| 35.513889 | 507 | 0.666797 | [
"MIT"
] | GinoCanessa/Subscription-CS-Endpoint | src/Fhir/R4B/ValueSets/AllergyIntoleranceCategory.cs | 2,557 | C# |
using System;
using System.Dynamic;
using System.Threading.Tasks;
using CitizenFX.Core;
using CitizenFX.Core.Native;
using FivePD.API;
using FivePD.API.Utils;
namespace WildernessCallouts
{
[CalloutProperties("Hiker Stuck", "BGHDDevelopment", "1.0.0")]
public class HikerStuck : Callout
{
private Ped vic;
public HikerStuck()
{
Random random = new Random();
int x = random.Next(1, 100 + 1);
if(x <= 40)
{
InitInfo(new Vector3(-765.125f, 4342.06f, 146.31f));
}
else if(x > 40 && x <= 65)
{
InitInfo(new Vector3(-789.051f, 4546.31f, 114.618f));
}
else
{
InitInfo(new Vector3(-765.125f, 4342.06f, 146.31f)); //default
}
ShortName = "Hiker Stuck";
CalloutDescription = "A hiker is stuck and needs help.";
ResponseCode = 2;
StartDistance = 200f;
}
public async override void OnStart(Ped player)
{
base.OnStart(player);
vic = await SpawnPed(RandomUtils.GetRandomPed(), Location);
PedData data = new PedData();
data.BloodAlcoholLevel = 0.07;
Utilities.SetPedData(vic.NetworkId, data);
vic.AlwaysKeepTask = true;
vic.BlockPermanentEvents = true;
PedData data1 = await Utilities.GetPedData(vic.NetworkId);
string firstname = data1.FirstName;
vic.AttachBlip();
Random random = new Random();
int x = random.Next(1, 100 + 1);
if(x <= 40)
{
vic.Task.Wait(1000); //wait
DrawSubtitle("~r~[" + firstname + "] ~s~Please grab me and get me out of here!", 5000);
}
else if(x > 40 && x <= 65)
{
vic.Task.ReactAndFlee(player); //run
DrawSubtitle("~r~[" + firstname + "] ~s~Leave me alone!", 5000);
}
else
{
vic.Weapons.Give(WeaponHash.Pistol, 100, true, true);
DrawSubtitle("~r~[" + firstname + "] ~s~DIE!", 5000);
}
}
public async override Task OnAccept()
{
InitBlip();
UpdateData();
}
private void DrawSubtitle(string message, int duration)
{
API.BeginTextCommandPrint("STRING");
API.AddTextComponentSubstringPlayerName(message);
API.EndTextCommandPrint(duration, false);
}
}
} | 30.767442 | 103 | 0.504157 | [
"MIT"
] | BGHDDevelopment/WildernessCallouts | WildernessCallouts/HikerStuck.cs | 2,648 | C# |
using System;
namespace FibonacciNumbers
{
class MainClass
{
public static void Main (string[] args)
{
int n = int.Parse (Console.ReadLine());
Console.WriteLine (Fib(n));
}
public static int Fib(int n)
{
int a = 0;
int b = 1;
for (int i = 0; i <= n; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}
}
} | 13 | 42 | 0.53022 | [
"MIT"
] | ACheshirov/SoftUni | Methods and Debugging - Exercises/Fibonacci_Numbers.cs | 364 | C# |
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace DotNext.Reflection;
/// <summary>
/// Represents reflected event.
/// </summary>
/// <typeparam name="THandler">A delegate representing event handler.</typeparam>
public class EventBase<THandler> : EventInfo, IEvent, IEquatable<EventInfo?>
where THandler : MulticastDelegate
{
private readonly EventInfo @event;
private protected EventBase(EventInfo @event) => this.@event = @event;
private static bool AddOrRemoveHandler(EventInfo @event, object? target, THandler handler, Action<object?, Delegate> modifier)
{
if (@event.AddMethod is { IsStatic: true })
{
if (target is null)
{
modifier(null, handler);
return true;
}
}
else if (@event.DeclaringType?.IsInstanceOfType(target) ?? false)
{
modifier(target, handler);
return true;
}
return false;
}
/// <summary>
/// Adds an event handler to an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">Encapsulates a method or methods to be invoked when the event is raised by the target.</param>
/// <returns><see langword="true"/>, if arguments are correct; otherwise, <see langword="false"/>.</returns>
public virtual bool AddEventHandler(object? target, THandler handler)
=> AddOrRemoveHandler(@event, target, handler, @event.AddEventHandler);
/// <summary>
/// Removes an event handler from an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">The delegate to be disassociated from the events raised by target.</param>
/// <returns><see langword="true"/>, if arguments are correct; otherwise, <see langword="false"/>.</returns>
public virtual bool RemoveEventHandler(object? target, THandler handler)
=> AddOrRemoveHandler(@event, target, handler, @event.RemoveEventHandler);
/// <inheritdoc/>
EventInfo IMember<EventInfo>.Metadata => @event;
/// <summary>
/// Gets the class that declares this constructor.
/// </summary>
public sealed override Type? DeclaringType => @event.DeclaringType;
/// <summary>
/// Always returns <see cref="MemberTypes.Event"/>.
/// </summary>
public sealed override MemberTypes MemberType => @event.MemberType;
/// <summary>
/// Gets name of the event.
/// </summary>
public sealed override string Name => @event.Name;
/// <summary>
/// Gets the class object that was used to obtain this instance.
/// </summary>
public sealed override Type? ReflectedType => @event.ReflectedType;
/// <summary>
/// Returns an array of all custom attributes applied to this event.
/// </summary>
/// <param name="inherit"><see langword="true"/> to search this member's inheritance chain to find the attributes; otherwise, <see langword="false"/>.</param>
/// <returns>An array that contains all the custom attributes applied to this event.</returns>
public sealed override object[] GetCustomAttributes(bool inherit) => @event.GetCustomAttributes(inherit);
/// <summary>
/// Returns an array of all custom attributes applied to this event.
/// </summary>
/// <param name="attributeType">The type of attribute to search for. Only attributes that are assignable to this type are returned.</param>
/// <param name="inherit"><see langword="true"/> to search this member's inheritance chain to find the attributes; otherwise, <see langword="false"/>.</param>
/// <returns>An array that contains all the custom attributes applied to this event.</returns>
public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => @event.GetCustomAttributes(attributeType, inherit);
/// <summary>
/// Determines whether one or more attributes of the specified type or of its derived types is applied to this event.
/// </summary>
/// <param name="attributeType">The type of custom attribute to search for. The search includes derived types.</param>
/// <param name="inherit"><see langword="true"/> to search this member's inheritance chain to find the attributes; otherwise, <see langword="false"/>.</param>
/// <returns><see langword="true"/> if one or more instances of <paramref name="attributeType"/> or any of its derived types is applied to this event; otherwise, <see langword="false"/>.</returns>
public sealed override bool IsDefined(Type attributeType, bool inherit) => @event.IsDefined(attributeType, inherit);
/// <summary>
/// Gets a value that identifies a metadata element.
/// </summary>
public sealed override int MetadataToken => @event.MetadataToken;
/// <summary>
/// Gets the module in which the type that declares the event represented by the current instance is defined.
/// </summary>
public sealed override Module Module => @event.Module;
/// <summary>
/// Returns a list of custom attributes that have been applied to the target event.
/// </summary>
/// <returns>The data about the attributes that have been applied to the target event.</returns>
public sealed override IList<CustomAttributeData> GetCustomAttributesData() => @event.GetCustomAttributesData();
/// <summary>
/// Gets a collection that contains this member's custom attributes.
/// </summary>
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => @event.CustomAttributes;
/// <summary>
/// Gets the attributes associated with this event.
/// </summary>
public sealed override EventAttributes Attributes => @event.Attributes;
/// <summary>
/// Gets a value indicating whether the event is multicast.
/// </summary>
public sealed override bool IsMulticast => @event.IsMulticast;
/// <summary>
/// Gets the the underlying event-handler delegate associated with this event.
/// </summary>
public sealed override Type? EventHandlerType => @event.EventHandlerType;
/// <summary>
/// Gets event subscription method.
/// </summary>
public sealed override MethodInfo? AddMethod => @event.AddMethod;
/// <summary>
/// Gets the method that is called when the event is raised, including non-public methods.
/// </summary>
public sealed override MethodInfo? RaiseMethod => @event.RaiseMethod;
/// <summary>
/// Gets event unsubscription method.
/// </summary>
public sealed override MethodInfo? RemoveMethod => @event.RemoveMethod;
/// <summary>
/// Gets event subscription method.
/// </summary>
/// <param name="nonPublic"><see langword="true"/> if non-public methods can be returned; otherwise, <see langword="false"/>.</param>
/// <returns>Event subscription method.</returns>
/// <exception cref="MethodAccessException">
/// <paramref name="nonPublic"/> is <see langword="true"/>, the method used to add an event handler delegate is non-public,
/// and the caller does not have permission to reflect on non-public methods.
/// </exception>
public sealed override MethodInfo? GetAddMethod(bool nonPublic) => @event.GetAddMethod(nonPublic);
/// <summary>
/// Gets event unsubscription method.
/// </summary>
/// <param name="nonPublic"><see langword="true"/> if non-public methods can be returned; otherwise, <see langword="false"/>.</param>
/// <returns>Event unsubscription method.</returns>
/// <exception cref="MethodAccessException">
/// <paramref name="nonPublic"/> is <see langword="true"/>, the method used to remove an event handler delegate is non-public,
/// and the caller does not have permission to reflect on non-public methods.
/// </exception>
public sealed override MethodInfo? GetRemoveMethod(bool nonPublic) => @event.GetRemoveMethod(nonPublic);
/// <summary>
/// Gets the method that is called when the event is raised.
/// </summary>
/// <param name="nonPublic"><see langword="true"/> if non-public methods can be returned; otherwise, <see langword="false"/>.</param>
/// <returns>Raise method.</returns>
/// <exception cref="MethodAccessException">
/// <paramref name="nonPublic"/> is <see langword="true"/>, the method is non-public, and the caller does not have permission to reflect on non-public methods.
/// </exception>
public sealed override MethodInfo? GetRaiseMethod(bool nonPublic) => @event.GetRaiseMethod(nonPublic);
/// <summary>
/// Returns the methods that have been associated with the event in metadata using the <c>.other</c> directive, specifying whether to include non-public methods.
/// </summary>
/// <param name="nonPublic"><see langword="true"/> if non-public methods can be returned; otherwise, <see langword="false"/>.</param>
/// <returns>An array of event methods.</returns>
public sealed override MethodInfo[] GetOtherMethods(bool nonPublic) => @event.GetOtherMethods();
/// <summary>
/// Determines whether this event is equal to the given event.
/// </summary>
/// <param name="other">Other event to compare.</param>
/// <returns><see langword="true"/> if this object reflects the same event as the specified object; otherwise, <see langword="false"/>.</returns>
public bool Equals(EventInfo? other) => other is Event<THandler> @event ? this.@event == @event.@event : this.@event == other;
/// <summary>
/// Determines whether this event is equal to the given event.
/// </summary>
/// <param name="other">Other event to compare.</param>
/// <returns><see langword="true"/> if this object reflects the same event as the specified object; otherwise, <see langword="false"/>.</returns>
public sealed override bool Equals([NotNullWhen(true)] object? other) => other switch
{
EventBase<THandler> @event => @event.@event == this.@event,
EventInfo @event => this.@event == @event,
_ => false,
};
/// <summary>
/// Computes hash code uniquely identifies the reflected event.
/// </summary>
/// <returns>The hash code of the event.</returns>
public sealed override int GetHashCode() => @event.GetHashCode();
/// <summary>
/// Returns textual representation of this event.
/// </summary>
/// <returns>The textual representation of this event.</returns>
public sealed override string? ToString() => @event.ToString();
}
/// <summary>
/// Provides typed access to static event declared in type <typeparamref name="THandler"/>.
/// </summary>
/// <typeparam name="THandler">Type of event handler.</typeparam>
public sealed class Event<THandler> : EventBase<THandler>, IEvent<THandler>
where THandler : MulticastDelegate
{
private sealed class Cache<T> : MemberCache<EventInfo, Event<THandler>>
{
private protected override Event<THandler>? Create(string eventName, bool nonPublic) => Reflect(typeof(T), eventName, nonPublic);
}
private const BindingFlags PublicFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly;
private const BindingFlags NonPublicFlags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
private readonly Action<THandler>? addMethod, removeMethod;
private Event(EventInfo @event)
: base(@event)
{
addMethod = @event.AddMethod?.CreateDelegate<Action<THandler>>();
removeMethod = @event.RemoveMethod?.CreateDelegate<Action<THandler>>();
}
/// <summary>
/// Adds static event handler.
/// </summary>
/// <param name="target">Should be <see langword="null"/>.</param>
/// <param name="handler">Encapsulates a method or methods to be invoked when the event is raised by the target.</param>
/// <returns><see langword="true"/>, if <paramref name="target"/> is <see langword="null"/>, <see langword="false"/>.</returns>
public override bool AddEventHandler(object? target, THandler handler)
{
if (target is null && addMethod is not null)
{
addMethod(handler);
return true;
}
return false;
}
/// <summary>
/// Removes static event handler.
/// </summary>
/// <param name="target">Should be <see langword="null"/>.</param>
/// <param name="handler">The delegate to be disassociated from the events raised by target.</param>
/// <returns><see langword="true"/>, if <paramref name="target"/> is <see langword="null"/>, <see langword="false"/>.</returns>
public override bool RemoveEventHandler(object? target, THandler handler)
{
if (target is null && removeMethod is not null)
{
removeMethod(handler);
return true;
}
return false;
}
/// <summary>
/// Add event handler.
/// </summary>
/// <param name="handler">An event handler to add.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddEventHandler(THandler handler) => addMethod?.Invoke(handler);
/// <summary>
/// Adds static event handler.
/// </summary>
/// <param name="target">Should be <see langword="null"/>.</param>
/// <param name="handler">Encapsulates a method or methods to be invoked when the event is raised by the target.</param>
public override void AddEventHandler(object? target, Delegate? handler)
{
if (handler is THandler typedHandler)
AddEventHandler(typedHandler);
else
base.AddEventHandler(target, handler);
}
/// <summary>
/// Remove event handler.
/// </summary>
/// <param name="handler">An event handler to remove.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RemoveEventHandler(THandler handler) => removeMethod?.Invoke(handler);
/// <summary>
/// Removes static event handler.
/// </summary>
/// <param name="target">Should be <see langword="null"/>.</param>
/// <param name="handler">The delegate to be disassociated from the events raised by target.</param>
public override void RemoveEventHandler(object? target, Delegate? handler)
{
if (handler is THandler typedHandler)
RemoveEventHandler(typedHandler);
else
base.RemoveEventHandler(target, handler);
}
/// <summary>
/// Returns a delegate which can be used to attach new handlers to the event.
/// </summary>
/// <param name="event">Reflected event.</param>
/// <returns>The delegate which can be used to attach new handlers to the event.</returns>
[return: NotNullIfNotNull("event")]
public static Action<THandler>? operator +(Event<THandler>? @event) => @event?.addMethod;
/// <summary>
/// Returns a delegate which can be used to detach from the event.
/// </summary>
/// <param name="event">Reflected event.</param>
/// <returns>The delegate which can be used to detach from the event.</returns>
[return: NotNullIfNotNull("event")]
public static Action<THandler>? operator -(Event<THandler>? @event) => @event?.removeMethod;
private static Event<THandler>? Reflect(Type declaringType, string eventName, bool nonPublic)
{
EventInfo? @event = declaringType.GetEvent(eventName, nonPublic ? NonPublicFlags : PublicFlags);
return @event is null ? null : new(@event);
}
internal static Event<THandler>? GetOrCreate<T>(string eventName, bool nonPublic)
=> Cache<T>.Of<Cache<T>>(typeof(T)).GetOrCreate(eventName, nonPublic);
}
/// <summary>
/// Provides typed access to instance event declared in type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">Declaring type.</typeparam>
/// <typeparam name="THandler">Type of event handler.</typeparam>
public sealed class Event<T, THandler> : EventBase<THandler>, IEvent<T, THandler>
where THandler : MulticastDelegate
{
private sealed class Cache : MemberCache<EventInfo, Event<T, THandler>>
{
private protected override Event<T, THandler>? Create(string eventName, bool nonPublic) => Reflect(eventName, nonPublic);
}
private const BindingFlags PublicFlags = BindingFlags.Instance | BindingFlags.Public;
private const BindingFlags NonPublicFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
/// <summary>
/// Represents event accessor.
/// </summary>
/// <param name="instance">The event target.</param>
/// <param name="handler">The event handler.</param>
public delegate void Accessor([DisallowNull] in T instance, THandler handler);
private readonly Accessor? addMethod, removeMethod;
private Event(EventInfo @event)
: base(@event)
{
if (@event.DeclaringType is null)
throw new ArgumentException(ExceptionMessages.ModuleMemberDetected(@event), nameof(@event));
var instanceParam = Expression.Parameter(@event.DeclaringType.MakeByRefType());
if (@event.EventHandlerType is null)
{
addMethod = removeMethod = null;
}
else
{
var handlerParam = Expression.Parameter(@event.EventHandlerType);
addMethod = @event.AddMethod is null ? null : CompileAccessor(@event.AddMethod, instanceParam, handlerParam);
removeMethod = @event.RemoveMethod is null ? null : CompileAccessor(@event.RemoveMethod, instanceParam, handlerParam);
}
}
private static Accessor CompileAccessor(MethodInfo accessor, ParameterExpression instanceParam, ParameterExpression handlerParam)
{
if (accessor.DeclaringType is null)
throw new ArgumentException(ExceptionMessages.ModuleMemberDetected(accessor), nameof(accessor));
if (accessor.DeclaringType.IsValueType)
return accessor.CreateDelegate<Accessor>();
return Expression.Lambda<Accessor>(
Expression.Call(instanceParam, accessor, handlerParam), instanceParam, handlerParam).Compile();
}
/// <summary>
/// Adds an event handler to an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">Encapsulates a method or methods to be invoked when the event is raised by the target.</param>
/// <returns><see langword="true"/>, if arguments are correct; otherwise, <see langword="false"/>.</returns>
public override bool AddEventHandler(object? target, THandler handler)
{
if (target is T instance && addMethod is not null)
{
addMethod(instance, handler);
return true;
}
return false;
}
/// <summary>
/// Removes an event handler from an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">The delegate to be disassociated from the events raised by target.</param>
/// <returns><see langword="true"/>, if arguments are correct; otherwise, <see langword="false"/>.</returns>
public override bool RemoveEventHandler(object? target, THandler handler)
{
if (target is T instance && removeMethod is not null)
{
removeMethod(instance, handler);
return true;
}
return false;
}
/// <summary>
/// Adds an event handler to an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">Encapsulates a method or methods to be invoked when the event is raised by the target.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddEventHandler([DisallowNull] in T target, THandler handler)
=> addMethod?.Invoke(in target, handler);
/// <summary>
/// Adds an event handler to an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">Encapsulates a method or methods to be invoked when the event is raised by the target.</param>
public override void AddEventHandler(object? target, Delegate? handler)
{
if (target is T typedTarget && handler is THandler typedHandler)
AddEventHandler(typedTarget, typedHandler);
else
base.AddEventHandler(target, handler);
}
/// <summary>
/// Removes an event handler from an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">The delegate to be disassociated from the events raised by target.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RemoveEventHandler([DisallowNull] in T target, THandler handler)
=> removeMethod?.Invoke(in target, handler);
/// <summary>
/// Removes an event handler from an event source.
/// </summary>
/// <param name="target">The event source.</param>
/// <param name="handler">The delegate to be disassociated from the events raised by target.</param>
public override void RemoveEventHandler(object? target, Delegate? handler)
{
if (target is T typedTarget && handler is THandler typedHandler)
RemoveEventHandler(typedTarget, typedHandler);
else
base.RemoveEventHandler(target, handler);
}
/// <summary>
/// Returns a delegate which can be used to attach new handlers to the event.
/// </summary>
/// <param name="event">Reflected event.</param>
/// <returns>The delegate which can be used to attach new handlers to the event.</returns>
[return: NotNullIfNotNull("event")]
public static Accessor? operator +(Event<T, THandler>? @event) => @event?.addMethod;
/// <summary>
/// Returns a delegate which can be used to detach from the event.
/// </summary>
/// <param name="event">Reflected event.</param>
/// <returns>The delegate which can be used to detach from the event.</returns>
[return: NotNullIfNotNull("event")]
public static Accessor? operator -(Event<T, THandler>? @event) => @event?.removeMethod;
private static Event<T, THandler>? Reflect(string eventName, bool nonPublic)
{
EventInfo? @event = typeof(T).GetEvent(eventName, nonPublic ? NonPublicFlags : PublicFlags);
return @event is null ? null : new(@event);
}
internal static Event<T, THandler>? GetOrCreate(string eventName, bool nonPublic)
=> Cache.Of<Cache>(typeof(T)).GetOrCreate(eventName, nonPublic);
} | 45.013917 | 200 | 0.669729 | [
"MIT"
] | copenhagenatomics/dotNext | src/DotNext.Reflection/Reflection/Event.cs | 22,642 | C# |
using System.ComponentModel.DataAnnotations;
namespace Financial.Api.Models
{
public class WalletInputModel
{
[Required]
public string Name { get; set; }
public double CurrentBalance { get; set; }
}
} | 19.916667 | 50 | 0.65272 | [
"MIT"
] | gmilani/bilmo | api/FinancialApi/Models/WalletInputModel.cs | 241 | C# |
using System;
using System.Diagnostics;
namespace AIGames.UltimateTicTacToe.StarterBot.Communication
{
public struct RequestMoveInstruction : IInstruction
{
public RequestMoveInstruction(TimeSpan time) { m_Time = time; }
public TimeSpan Time { get { return m_Time; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private TimeSpan m_Time;
public override string ToString()
{
return String.Format("action move {0:0}", Time.TotalMilliseconds);
}
internal static IInstruction Parse(string[] splitted)
{
int ms;
if (splitted[1] == "move" && splitted.Length == 3 && Int32.TryParse(splitted[2], out ms))
{
return new RequestMoveInstruction(TimeSpan.FromMilliseconds(ms));
}
return null;
}
}
}
| 24.733333 | 92 | 0.722372 | [
"MIT"
] | Corniel/AIGames.UltimateTicTacToe.StarterBot | src/AIGames.UltimateTicTacToe.StarterBot/Communication/Instruction.Move.Request.cs | 744 | C# |
using Xunit;
namespace Grynwald.MarkdownGenerator.Test
{
public class MdEmptySpanTest
{
[Fact]
public void ToString_returns_the_expected_value()
{
Assert.Equal(string.Empty, MdEmptySpan.Instance.ToString());
}
}
}
| 19.428571 | 72 | 0.632353 | [
"MIT"
] | ap0llo/markdown-generator | src/MarkdownGenerator.Test/_Model/_Spans/MdEmptySpanTest.cs | 274 | 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.Oci.Bds
{
public static class GetBdsInstances
{
/// <summary>
/// This data source provides the list of Bds Instances in Oracle Cloud Infrastructure Big Data Service service.
///
/// Returns a list of all Big Data Service clusters in a compartment.
///
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Oci = Pulumi.Oci;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var testBdsInstances = Output.Create(Oci.Bds.GetBdsInstances.InvokeAsync(new Oci.Bds.GetBdsInstancesArgs
/// {
/// CompartmentId = @var.Compartment_id,
/// DisplayName = @var.Bds_instance_display_name,
/// State = @var.Bds_instance_state,
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetBdsInstancesResult> InvokeAsync(GetBdsInstancesArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetBdsInstancesResult>("oci:bds/getBdsInstances:getBdsInstances", args ?? new GetBdsInstancesArgs(), options.WithVersion());
}
public sealed class GetBdsInstancesArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The OCID of the compartment.
/// </summary>
[Input("compartmentId", required: true)]
public string CompartmentId { get; set; } = null!;
/// <summary>
/// A filter to return only resources that match the entire display name given.
/// </summary>
[Input("displayName")]
public string? DisplayName { get; set; }
[Input("filters")]
private List<Inputs.GetBdsInstancesFilterArgs>? _filters;
public List<Inputs.GetBdsInstancesFilterArgs> Filters
{
get => _filters ?? (_filters = new List<Inputs.GetBdsInstancesFilterArgs>());
set => _filters = value;
}
/// <summary>
/// The state of the cluster.
/// </summary>
[Input("state")]
public string? State { get; set; }
public GetBdsInstancesArgs()
{
}
}
[OutputType]
public sealed class GetBdsInstancesResult
{
/// <summary>
/// The list of bds_instances.
/// </summary>
public readonly ImmutableArray<Outputs.GetBdsInstancesBdsInstanceResult> BdsInstances;
/// <summary>
/// The OCID of the compartment.
/// </summary>
public readonly string CompartmentId;
/// <summary>
/// The name of the node.
/// </summary>
public readonly string? DisplayName;
public readonly ImmutableArray<Outputs.GetBdsInstancesFilterResult> Filters;
/// <summary>
/// The provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
/// <summary>
/// The state of the cluster.
/// </summary>
public readonly string? State;
[OutputConstructor]
private GetBdsInstancesResult(
ImmutableArray<Outputs.GetBdsInstancesBdsInstanceResult> bdsInstances,
string compartmentId,
string? displayName,
ImmutableArray<Outputs.GetBdsInstancesFilterResult> filters,
string id,
string? state)
{
BdsInstances = bdsInstances;
CompartmentId = compartmentId;
DisplayName = displayName;
Filters = filters;
Id = id;
State = state;
}
}
}
| 31.734848 | 178 | 0.560516 | [
"ECL-2.0",
"Apache-2.0"
] | EladGabay/pulumi-oci | sdk/dotnet/Bds/GetBdsInstances.cs | 4,189 | C# |
namespace AnimalCentre
{
using AnimalCentre.Core;
using AnimalCentre.IO;
public class StartUp
{
public static void Main()
{
IReader reader = new Reader();
IWriter writer = new Writer();
var engine = new Engine(reader, writer);
engine.Run();
}
}
}
| 19 | 52 | 0.532164 | [
"MIT"
] | VeselinBPavlov/csharp-oop-basics | 17. Exam - 18 November 2018/AnimalCentre/StartUp.cs | 344 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Diagnostics;
using Xamarin.Forms.Internals;
using Xamarin.Forms;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml;
using Windows.UI.Composition;
namespace Plugin.SharedTransitions.Platforms.UWP
{
/// <summary>
/// Set the navigation transition for the NavigationPage
/// </summary>
internal class NavigationTransition
{
public static void SetupAnimationEvents(SharedTransitionNavigationPage stnp)
{
stnp.PushRequested += Stnp_PushRequested;
stnp.Pushed += Stnp_Pushed;
stnp.PopRequested += Stnp_PopRequested;
stnp.Popped += Stnp_Popped;
stnp.PopToRootRequested += Stnp_PopToRootRequested;
stnp.PoppedToRoot += Stnp_PoppedToRoot;
stnp.RemovePageRequested += Stnp_RemovePageRequested;
stnp.InsertPageBeforeRequested += Stnp_InsertPageBeforeRequested;
}
private static void Stnp_PushRequested(object sender, NavigationRequestedEventArgs e)
{
// setup cross-page animation for source page
var stnp = sender as SharedTransitionNavigationPage;
var ns = stnp.Navigation.NavigationStack;
var tm = stnp.TransitionMap;
var pageFrom = e.BeforePage;
if (pageFrom == null && ns.Count >= 2)
pageFrom = ns[ns.Count - 2];
var pageTo = e.Page;
// PushRequested occurs after the navigation stack has been updated
System.Diagnostics.Debug.Assert(pageTo == ns[ns.Count - 1]);
PrepareSharedTransition(tm, pageFrom, pageTo, false);
}
private static void Stnp_Pushed(object sender, NavigationEventArgs e)
{
// execute cross-page animation setup above to new page
var stnp = sender as SharedTransitionNavigationPage;
var ns = stnp.Navigation.NavigationStack;
var tm = stnp.TransitionMap;
Page pageFrom = null;
if (ns.Count >= 2)
pageFrom = ns[ns.Count - 2];
var pageTo = ns[ns.Count - 1];
// Pushed occurs after the navigation stack has been updated
ExecutePreparedTransition(tm, pageFrom, pageTo, false);
}
private static void PrepareSharedTransition(ITransitionMapper tm, Page pageFrom, Page pageTo, bool isPop)
{
IReadOnlyList<TransitionDetail> transFrom = null;
if (isPop)
{
// current page is pageFrom being popped; new page will be pageTo
transFrom = tm.GetMap(pageFrom, null, isPop);
}
else
{
// current page == pageFrom; new page to push pageTo
// group is used when pushing from a page with the group defined
var group = (string)pageFrom?.GetValue(SharedTransitionNavigationPage.TransitionSelectedGroupProperty);
transFrom = tm.GetMap(pageFrom, group, isPop);
}
// save this so that when we return to the page, we don't have to guess which items to use
pageFrom?.SetValue(SharedTransitionNavigationPage.TransitionFromMapProperty, transFrom);
var cas = ConnectedAnimationService.GetForCurrentView();
if (pageFrom != null)
{
cas.DefaultDuration = TimeSpan.FromMilliseconds((long)pageFrom.GetValue(SharedTransitionNavigationPage.TransitionDurationProperty));
}
// TODO: better indication of Background items to do first...
foreach (var bg in transFrom.Where(td => td.TransitionName.Contains("Background")))
{
if (bg.NativeView.IsAlive)
{
var ca = cas.PrepareToAnimate(bg.TransitionName, (UIElement)bg.NativeView.Target);
}
}
foreach (var detail in transFrom.Where(td => !td.TransitionName.Contains("Background")))
{
if (detail.NativeView.IsAlive)
{
var ca = cas.PrepareToAnimate(detail.TransitionName, (UIElement)detail.NativeView.Target);
}
}
}
private static void ExecutePreparedTransition(ITransitionMapper tm, Page pageFrom, Page pageTo, bool isPop)
{
var cas = ConnectedAnimationService.GetForCurrentView();
var transFrom = (IReadOnlyList<TransitionDetail>)pageFrom?.GetValue(SharedTransitionNavigationPage.TransitionFromMapProperty);
pageFrom?.SetValue(SharedTransitionNavigationPage.TransitionFromMapProperty, null);
// group is used when popping back to a page with the group defined
var group = (string)pageTo?.GetValue(SharedTransitionNavigationPage.TransitionSelectedGroupProperty);
var transTo = tm.GetMap(pageTo, group, !isPop);
foreach (var detail in transTo)
{
ConnectedAnimation animation = cas.GetAnimation(detail.TransitionName);
if (animation != null)
{
if (detail.NativeView.IsAlive)
{
if (detail.View.Height == -1)
{
// need to capture the value and then use that in the event handler since it changes with each time through the loop
var acapture = animation;
detail.View.SizeChanged += (s, e) =>
{
// save this so we only call TryStart on the first time through
var atemp = acapture;
acapture = null;
if (atemp != null && detail.NativeView.IsAlive)
atemp.TryStart((UIElement)detail.NativeView.Target);
};
}
else
{
var b = animation.TryStart((UIElement)detail.NativeView.Target);
}
}
}
}
foreach (var transChk in transFrom ?? Enumerable.Empty<TransitionDetail>())
{
if (!transTo.Any(t => t.TransitionName == transChk.TransitionName))
{
// transFrom item not in transTo
ConnectedAnimation animation = cas.GetAnimation(transChk.TransitionName);
if (animation != null)
{
animation.Cancel();
}
if (isPop)
{
// TODO: figure out why this is needed
transChk.View.IsVisible = false;
if (transChk.NativeView.IsAlive)
((UIElement)transChk.NativeView.Target).Visibility = Visibility.Collapsed;
}
}
}
}
private static void Stnp_PopRequested(object sender, NavigationRequestedEventArgs e)
{
var stnp = sender as SharedTransitionNavigationPage;
var ns = stnp.Navigation.NavigationStack;
var tm = stnp.TransitionMap;
var pageFrom = e.Page;
// PopRequested occurs before nav stack is updated
System.Diagnostics.Debug.Assert(pageFrom == ns[ns.Count - 1]);
Page pageTo = null;
if (ns.Count >= 2)
pageTo = ns[ns.Count - 2];
PrepareSharedTransition(tm, pageFrom, pageTo, true);
}
private static void Stnp_Popped(object sender, NavigationEventArgs e)
{
var stnp = sender as SharedTransitionNavigationPage;
var ns = stnp.Navigation.NavigationStack;
var tm = stnp.TransitionMap;
Page pageFrom = e.Page;
var pageTo = ns[ns.Count - 1];
// Popped occurs after the navigation stack has been updated
ExecutePreparedTransition(tm, pageFrom, pageTo, true);
}
private static void Stnp_PopToRootRequested(object sender, NavigationRequestedEventArgs e)
{
}
private static void Stnp_PoppedToRoot(object sender, NavigationEventArgs e)
{
}
private static void Stnp_InsertPageBeforeRequested(object sender, NavigationRequestedEventArgs e)
{
}
private static void Stnp_RemovePageRequested(object sender, NavigationRequestedEventArgs e)
{
}
}
}
| 38.552632 | 148 | 0.568259 | [
"MIT"
] | craigwi/Xamarin.Plugin.SharedTransitions | src/SharedTransitions/Platforms/UWP/NavigationTransition.cs | 8,792 | C# |
using NBitcoin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Backend.Models;
using WalletWasabi.Blockchain.BlockFilters;
using WalletWasabi.Blockchain.Blocks;
using WalletWasabi.Helpers;
using WalletWasabi.Stores;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.Filters
{
public class IndexStoreTests
{
[Fact]
public async Task IndexStoreTestsAsync()
{
var network = Network.Main;
var indexStore = new IndexStore(network, new SmartHeaderChain());
var dir = (await GetIndexStorePathsAsync()).dir;
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
await indexStore.InitializeAsync(dir);
}
[Fact]
public async Task InconsistentMatureIndexAsync()
{
var (dir, matureFilters, _) = await GetIndexStorePathsAsync();
var network = Network.Main;
var headersChain = new SmartHeaderChain();
var indexStore = new IndexStore(network, headersChain);
var dummyFilter = GolombRiceFilter.Parse("00");
static DateTimeOffset MinutesAgo(int mins) => DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(mins));
var matureIndexStoreContent = new[]
{
new FilterModel(new SmartHeader(new uint256(2), new uint256(1), 1, MinutesAgo(30)), dummyFilter),
new FilterModel(new SmartHeader(new uint256(3), new uint256(2), 2, MinutesAgo(20)), dummyFilter),
new FilterModel(new SmartHeader(new uint256(99), new uint256(98), 98, MinutesAgo(10)), dummyFilter)
};
await File.WriteAllLinesAsync(matureFilters, matureIndexStoreContent.Select(x => x.ToLine()));
await Assert.ThrowsAsync<InvalidOperationException>(async () => await indexStore.InitializeAsync(dir));
Assert.Equal(new uint256(3), headersChain.TipHash);
Assert.Equal(2u, headersChain.TipHeight);
// Check if the matureIndex is deleted
Assert.False(File.Exists(matureFilters));
}
[Fact]
public async Task InconsistentImmatureIndexAsync()
{
var (dir, _, immatureFilters) = await GetIndexStorePathsAsync();
var network = Network.Main;
var headersChain = new SmartHeaderChain();
var indexStore = new IndexStore(network, headersChain);
var dummyFilter = GolombRiceFilter.Parse("00");
static DateTimeOffset MinutesAgo(int mins) => DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(mins));
var startingFilter = StartingFilters.GetStartingFilter(network);
var immatureIndexStoreContent = new[]
{
new FilterModel(new SmartHeader(new uint256(2), startingFilter.Header.BlockHash, startingFilter.Header.Height + 1, MinutesAgo(30)), dummyFilter),
new FilterModel(new SmartHeader(new uint256(3), new uint256(2), startingFilter.Header.Height + 2, MinutesAgo(20)), dummyFilter),
new FilterModel(new SmartHeader(new uint256(99), new uint256(98), startingFilter.Header.Height + 98, MinutesAgo(10)), dummyFilter)
};
await File.WriteAllLinesAsync(immatureFilters, immatureIndexStoreContent.Select(x => x.ToLine()));
await Assert.ThrowsAsync<InvalidOperationException>(async () => await indexStore.InitializeAsync(dir));
Assert.Equal(new uint256(3), headersChain.TipHash);
Assert.Equal(startingFilter.Header.Height + 2u, headersChain.TipHeight);
// Check if the immatureIndex is deleted
Assert.False(File.Exists(immatureFilters));
}
[Fact]
public async Task GapInIndexAsync()
{
var (dir, matureFilters, immatureFilters) = await GetIndexStorePathsAsync();
var network = Network.Main;
var headersChain = new SmartHeaderChain();
var indexStore = new IndexStore(network, headersChain);
var dummyFilter = GolombRiceFilter.Parse("00");
static DateTimeOffset MinutesAgo(int mins) => DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(mins));
var matureIndexStoreContent = new[]
{
new FilterModel(new SmartHeader(new uint256(2), new uint256(1), 1, MinutesAgo(30)), dummyFilter),
new FilterModel(new SmartHeader(new uint256(3), new uint256(2), 2, MinutesAgo(20)), dummyFilter),
};
await File.WriteAllLinesAsync(matureFilters, matureIndexStoreContent.Select(x => x.ToLine()));
var immatureIndexStoreContent = new[]
{
new FilterModel(new SmartHeader(new uint256(5), new uint256(4), 4, MinutesAgo(30)), dummyFilter),
new FilterModel(new SmartHeader(new uint256(6), new uint256(5), 5, MinutesAgo(20)), dummyFilter),
};
await File.WriteAllLinesAsync(immatureFilters, immatureIndexStoreContent.Select(x => x.ToLine()));
await Assert.ThrowsAsync<InvalidOperationException>(async () => await indexStore.InitializeAsync(dir));
Assert.Equal(new uint256(3), headersChain.TipHash);
Assert.Equal(2u, headersChain.TipHeight);
Assert.True(File.Exists(matureFilters)); // mature filters are ok
Assert.False(File.Exists(immatureFilters)); // immature filters are NOT ok
}
[Fact]
public async Task ReceiveNonMatchingFilterAsync()
{
var (dir, matureFilters, immatureFilters) = await GetIndexStorePathsAsync();
var network = Network.Main;
var headersChain = new SmartHeaderChain();
var indexStore = new IndexStore(network, headersChain);
var dummyFilter = GolombRiceFilter.Parse("00");
static DateTimeOffset MinutesAgo(int mins) => DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(mins));
var matureIndexStoreContent = new[]
{
new FilterModel(new SmartHeader(new uint256(2), new uint256(1), 1, MinutesAgo(30)), dummyFilter),
new FilterModel(new SmartHeader(new uint256(3), new uint256(2), 2, MinutesAgo(20)), dummyFilter),
};
await File.WriteAllLinesAsync(matureFilters, matureIndexStoreContent.Select(x => x.ToLine()));
await indexStore.InitializeAsync(dir);
Assert.Equal(new uint256(3), headersChain.TipHash);
Assert.Equal(2u, headersChain.TipHeight);
Assert.True(File.Exists(matureFilters)); // mature filters are ok
var nonMatchingBlockHashFilter = new FilterModel(new SmartHeader(new uint256(2), new uint256(1), 1, MinutesAgo(30)), dummyFilter);
await indexStore.AddNewFiltersAsync(new[] { nonMatchingBlockHashFilter }, CancellationToken.None);
Assert.Equal(new uint256(3), headersChain.TipHash); // the filter is not added!
Assert.Equal(2u, headersChain.TipHeight);
var nonMatchingHeightFilter = new FilterModel(new SmartHeader(new uint256(4), new uint256(3), 37, MinutesAgo(1)), dummyFilter);
await indexStore.AddNewFiltersAsync(new[] { nonMatchingHeightFilter }, CancellationToken.None);
Assert.Equal(new uint256(3), headersChain.TipHash); // the filter is not added!
Assert.Equal(2u, headersChain.TipHeight);
var correctFilter = new FilterModel(new SmartHeader(new uint256(4), new uint256(3), 3, MinutesAgo(1)), dummyFilter);
await indexStore.AddNewFiltersAsync(new[] { correctFilter }, CancellationToken.None);
Assert.Equal(new uint256(4), headersChain.TipHash); // the filter is not added!
Assert.Equal(3u, headersChain.TipHeight);
}
private async Task<(string dir, string matureFilters, string immatureFilters)> GetIndexStorePathsAsync([CallerFilePath]string callerFilePath = null, [CallerMemberName] string callerName = "")
{
var dir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.ExtractFileName(callerFilePath), callerName, "IndexStore");
await IoHelpers.DeleteRecursivelyWithMagicDustAsync(dir);
var matureFilters = Path.Combine(dir, "MatureIndex.dat");
var immatureFilters = Path.Combine(dir, "ImmatureIndex.dat");
IoHelpers.EnsureContainingDirectoryExists(matureFilters);
IoHelpers.EnsureContainingDirectoryExists(immatureFilters);
return (dir, matureFilters, immatureFilters);
}
}
}
| 42.916201 | 193 | 0.752408 | [
"MIT"
] | DanGould/WalletWasabi | WalletWasabi.Tests/UnitTests/Filters/IndexStoreTests.cs | 7,682 | C# |
using RumahScarlett.Presentation.Views.CommonControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RumahScarlett.Presentation.Views.Pembelian
{
public partial class ReturnPembelianView : BaseDataView, IReturnPembelianView
{
public event EventHandler OnButtonCariClick;
public event EventHandler OnLoadView;
public event EventHandler OnButtonTambahClick;
public event EventHandler OnButtonHapusClick;
public event EventHandler OnButtonSimpanClick;
public event EventHandler OnButtonBersihkanClick;
public event EventHandler OnButtonCetakNotaClick;
public ListDataGrid ListDataGrid
{
get { return listDataGrid; }
}
public TextBox TextBoxNoNotaReturn
{
get { return textBoxNoNotaRetrun; }
}
public Button ButtonCari
{
get { return buttonCari; }
}
public Label LabelQtyReturn
{
get { return labelQtyReturn; }
}
public Label LabelTotalReturn
{
get { return labelTotalReturn; }
}
public TextBox TextBoxCariNoNota
{
get { return textBoxCariNoNota; }
}
public Label LabelTanggalPembelian
{
get { return labelTanggalPembelian; }
}
public Label LabelSupplierPembelian
{
get { return labelSupplierPembelian; }
}
public Label LabelSubTotalPembelian
{
get { return labelSubTotalPembelian; }
}
public Label LabelDiskonPembelian
{
get { return labelDiskonPembelian; }
}
public Label LabelTotalPembelian
{
get { return labelTotalPembelian; }
}
public ReturnPembelianView()
{
InitializeComponent();
panelUp.LabelInfo = Text.ToUpper();
}
private void ReturnPembelianView_Load(object sender, EventArgs e)
{
labelTanggalReturn.Text = DateTime.Now.ToShortDateString();
OnLoadView?.Invoke(sender, e);
ActiveControl = buttonTutup;
}
private void buttonCari_Click(object sender, EventArgs e)
{
OnButtonCariClick?.Invoke(sender, e);
}
private void buttonTambah_Click(object sender, EventArgs e)
{
OnButtonTambahClick?.Invoke(sender, e);
}
private void buttonHapus_Click(object sender, EventArgs e)
{
OnButtonHapusClick?.Invoke(sender, e);
}
private void buttonSimpan_Click(object sender, EventArgs e)
{
OnButtonSimpanClick?.Invoke(sender, e);
}
private void buttonBersihkan_Click(object sender, EventArgs e)
{
OnButtonBersihkanClick?.Invoke(sender, e);
}
private void buttonCetak_Click(object sender, EventArgs e)
{
OnButtonCetakNotaClick?.Invoke(sender, e);
}
private void buttonTutup_Click(object sender, EventArgs e)
{
if (!listDataGrid.CurrentCell.IsEditing)
{
Close();
}
}
}
}
| 24.526718 | 80 | 0.641145 | [
"MIT"
] | izhal27/rumah_scarlett | src/RumahScarlett/RumahScarlett.Presentation/Views/Pembelian/ReturnPembelianView.cs | 3,215 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal class CSharpStructuredTriviaFormatEngine : AbstractFormatEngine
{
public static IFormattingResult Format(
SyntaxTrivia trivia,
int initialColumn,
OptionSet optionSet,
ChainedFormattingRules formattingRules,
CancellationToken cancellationToken)
{
var root = trivia.GetStructure();
var formatter = new CSharpStructuredTriviaFormatEngine(trivia, initialColumn, optionSet, formattingRules, root.GetFirstToken(includeZeroWidth: true), root.GetLastToken(includeZeroWidth: true));
return formatter.Format(cancellationToken);
}
private CSharpStructuredTriviaFormatEngine(
SyntaxTrivia trivia,
int initialColumn,
OptionSet optionSet,
ChainedFormattingRules formattingRules,
SyntaxToken token1,
SyntaxToken token2) :
base(TreeData.Create(trivia, initialColumn),
optionSet,
formattingRules,
token1,
token2,
TaskExecutor.Synchronous)
{
}
protected override AbstractTriviaDataFactory CreateTriviaFactory()
{
return new TriviaDataFactory(this.TreeData, this.OptionSet);
}
protected override FormattingContext CreateFormattingContext(TokenStream tokenStream, CancellationToken cancellationToken)
{
return new FormattingContext(this, tokenStream, LanguageNames.CSharp);
}
protected override NodeOperations CreateNodeOperationTasks(CancellationToken cancellationToken)
{
// ignore all node operations for structured trivia since it is not possible for this to have any impact currently.
return NodeOperations.Empty;
}
protected override AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream)
{
return new FormattingResult(this.TreeData, tokenStream, this.SpanToFormat, this.TaskExecutor);
}
}
}
| 39.772727 | 205 | 0.690667 | [
"ECL-2.0",
"Apache-2.0"
] | binsys/roslyn_java | Src/Workspaces/CSharp/Formatting/Engine/CSharpStructuredTriviaFormatEngine.cs | 2,627 | C# |
namespace Spark.Engine.Service.FhirServiceExtensions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Hl7.Fhir.Language;
using Hl7.Fhir.Model;
using Hl7.FhirPath;
using Expression = System.Linq.Expressions.Expression;
using fhirExpression = Hl7.FhirPath.Expressions;
public class PatchService : IPatchService
{
private readonly FhirPathCompiler _compiler;
public PatchService()
{
_compiler = new FhirPathCompiler();
}
public Resource Apply(Resource resource, Parameters patch)
{
foreach (var component in patch.Parameter.Where(x => x.Name == "operation"))
{
var operationType = component.Part.First(x => x.Name == "type").Value.ToString();
var path = component.Part.First(x => x.Name == "path").Value.ToString();
var name = component.Part.FirstOrDefault(x => x.Name == "name")?.Value.ToString();
var value = component.Part.FirstOrDefault(x => x.Name == "value")?.Value ?? component.Part.FirstOrDefault(x => x.Name == "value")?.Part[0].Value;
var parameterExpression = Expression.Parameter(resource.GetType(), "x");
var expression = operationType == "add" ? _compiler.Parse($"{path}.{name}") : _compiler.Parse(path);
var result = expression.Accept(
new ResourceVisitor(parameterExpression),
new fhirExpression.SymbolTable());
var valueExpression = CreateValueExpression(value, result);
switch (operationType)
{
case "add":
result = AddValue(result, valueExpression);
break;
case "insert":
result = InsertValue(result, valueExpression);
break;
case "replace":
result = Expression.Assign(result, valueExpression);
break;
case "delete":
result = DeleteValue(result);
break;
case "move":
var source = int.Parse(component.Part.First(x => x.Name == "source").Value.ToString()!);
var destination = int.Parse(component.Part.First(x => x.Name == "destination").Value.ToString()!);
result = MoveItem(result, source, destination);
break;
}
var compiled = Expression.Lambda(result!, parameterExpression).Compile();
compiled.DynamicInvoke(resource);
}
return resource;
}
private static Expression CreateValueExpression(DataType value, Expression result)
{
return value switch
{
Code code => result is MemberExpression me
? (Expression)Expression.MemberInit(
Expression.New(me.Type.GetConstructor(Array.Empty<Type>())),
Expression.Bind(
me.Type.GetProperty("ObjectValue"),
Expression.Constant(code.Value)))
: Expression.Constant(value),
_ => Expression.Constant(value)
};
}
private static Expression MoveItem(Expression result, int source, int destination)
{
var propertyInfo = GetProperty(result.Type, "Item");
var variable = Expression.Variable(propertyInfo.PropertyType, "item");
var block = Expression.Block(
new[] { variable },
Expression.Assign(
variable,
Expression.MakeIndex(result, propertyInfo, new[] { Expression.Constant(source) })),
Expression.Call(result, GetMethod(result.Type, "RemoveAt"), Expression.Constant(source)),
Expression.Call(
result,
GetMethod(result.Type, "Insert"),
Expression.Constant(Math.Max(0, destination - 1)),
variable));
return block;
}
private static Expression InsertValue(Expression result, Expression valueExpression)
{
return result switch
{
IndexExpression indexExpression => Expression.Call(
indexExpression.Object,
GetMethod(indexExpression.Object!.Type, "Insert"),
new[] { indexExpression.Arguments[0], valueExpression }),
_ => result
};
}
private static Expression AddValue(Expression result, Expression value)
{
return result switch
{
MemberExpression me when me.Type.IsGenericType
&& GetMethod(me.Type, "Add") != null =>
Expression.Block(
Expression.IfThen(
Expression.Equal(me, Expression.Default(result.Type)),
Expression.Throw(Expression.New(typeof(InvalidOperationException)))),
Expression.Call(me, GetMethod(me.Type, "Add"), value)),
MemberExpression me => Expression.Block(
Expression.IfThen(
Expression.NotEqual(me, Expression.Default(result.Type)),
Expression.Throw(Expression.New(typeof(InvalidOperationException)))),
Expression.Assign(me, value)),
_ => result
};
}
private static Expression DeleteValue(Expression result)
{
return result switch
{
IndexExpression indexExpression => Expression.Call(
indexExpression.Object,
GetMethod(indexExpression.Object!.Type, "RemoveAt"),
indexExpression.Arguments),
MemberExpression me when me.Type.IsGenericType
&& typeof(List<>).IsAssignableFrom(me.Type.GetGenericTypeDefinition()) =>
Expression.Call(me, GetMethod(me.Type, "Clear")),
MemberExpression me => Expression.Assign(me, Expression.Default(me.Type)),
_ => result
};
}
private static MethodInfo GetMethod(Type constantType, string methodName)
{
var propertyInfos = constantType.GetMethods();
var property =
propertyInfos.FirstOrDefault(p => p.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase));
return property;
}
private static PropertyInfo GetProperty(Type constantType, string propertyName)
{
var propertyInfos = constantType.GetProperties();
var property =
propertyInfos.FirstOrDefault(p => p.Name.Equals(propertyName + "Element", StringComparison.OrdinalIgnoreCase))
?? propertyInfos.FirstOrDefault(x => x.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase));
return property;
}
private class ResourceVisitor : fhirExpression.ExpressionVisitor<Expression>
{
private readonly ParameterExpression _parameter;
public ResourceVisitor(ParameterExpression parameter)
{
_parameter = parameter;
}
/// <inheritdoc />
public override Expression VisitConstant(
fhirExpression.ConstantExpression expression,
fhirExpression.SymbolTable scope)
{
if (expression.ExpressionType == TypeSpecifier.Integer)
{
return Expression.Constant((int)expression.Value);
}
if (expression.ExpressionType == TypeSpecifier.String)
{
var propertyName = expression.Value.ToString();
var property = GetProperty(_parameter.Type, propertyName);
return property == null
? (Expression)_parameter
: Expression.Property(_parameter, property);
}
return null;
}
/// <inheritdoc />
public override Expression VisitFunctionCall(
fhirExpression.FunctionCallExpression expression,
fhirExpression.SymbolTable scope)
{
switch (expression)
{
case fhirExpression.IndexerExpression indexerExpression:
{
var index = indexerExpression.Index.Accept(this, scope);
var property = indexerExpression.Focus.Accept(this, scope);
var itemProperty = GetProperty(property.Type, "Item");
return Expression.MakeIndex(property, itemProperty, new[] { index });
}
case fhirExpression.ChildExpression child:
{
return child.Arguments.First().Accept(this, scope);
}
default:
return _parameter;
}
}
/// <inheritdoc />
public override Expression VisitNewNodeListInit(
fhirExpression.NewNodeListInitExpression expression,
fhirExpression.SymbolTable scope)
{
return _parameter;
}
/// <inheritdoc />
public override Expression VisitVariableRef(fhirExpression.VariableRefExpression expression, fhirExpression.SymbolTable scope)
{
return _parameter;
}
}
}
}
| 42.779661 | 161 | 0.5313 | [
"BSD-3-Clause"
] | fbaham/spark | src/Spark.Engine/Service/FhirServiceExtensions/PatchService.cs | 10,098 | C# |
using ESFA.DC.ESF.Database.EF.Interfaces;
namespace ESFA.DC.ESF.Database.EF
{
public partial class ESF_DataStoreEntities : IESF_DataStoreEntities
{
public ESF_DataStoreEntities(string connectionString)
: base(connectionString)
{
}
}
} | 23.666667 | 71 | 0.676056 | [
"MIT"
] | SkillsFundingAgency/DC-ESF | src/ESFA.DC.ESF.Database.EF/ESF_DataStoreEntities.cs | 286 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NumberGenerator.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute( "System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0" )]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" )]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute( global::System.ComponentModel.EditorBrowsableState.Advanced )]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ( ( resourceMan == null ) )
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager( "NumberGenerator.Properties.Resources", typeof( Resources ).Assembly );
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute( global::System.ComponentModel.EditorBrowsableState.Advanced )]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 37.319444 | 180 | 0.626721 | [
"MIT"
] | alexwnovak/TF2Maps | jump_mirage/src/NumberGenerator/NumberGenerator/Properties/Resources.Designer.cs | 2,689 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Cloud.Core.Storage.AzureCosmos.Tests")]
[assembly: InternalsVisibleTo("Cloud.Core.Storage.AzureCosmos.Tests.Profiler")] | 47.75 | 79 | 0.827225 | [
"MIT"
] | m-knet/Cloud.Core.Storage.AzureCosmos | src/Cloud.Core.Storage.AzureCosmos/Properties/AssemblyInfo.cs | 193 | 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 billingconductor-2021-07-30.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.BillingConductor.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.BillingConductor.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListPricingPlans operation
/// </summary>
public class ListPricingPlansResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListPricingPlansResponse response = new ListPricingPlansResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("BillingPeriod", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.BillingPeriod = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("PricingPlans", targetDepth))
{
var unmarshaller = new ListUnmarshaller<PricingPlanListElement, PricingPlanListElementUnmarshaller>(PricingPlanListElementUnmarshaller.Instance);
response.PricingPlans = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException"))
{
return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonBillingConductorException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListPricingPlansResponseUnmarshaller _instance = new ListPricingPlansResponseUnmarshaller();
internal static ListPricingPlansResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListPricingPlansResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.798507 | 199 | 0.635083 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/BillingConductor/Generated/Model/Internal/MarshallTransformations/ListPricingPlansResponseUnmarshaller.cs | 5,467 | C# |
using System.Collections.Generic;
using System.Security.Claims;
using BrockAllen.MembershipReboot;
using Fulcrum.Core.Concepts;
using FulcrumSeed.Components.UserAccounts.Domain.Entities;
using FulcrumSeed.Components.UserAccounts.Domain.Repositories;
using FulcrumSeed.Infrastructure.MembershipReboot;
namespace FulcrumSeed.Components.UserAccounts.Domain.Services
{
public class AppUserService : UserAccountService<AppUser>, IDomainService
{
public AppUserService(MembershipConfig config, UserAccountRepository repo)
: base(config, repo)
{
}
public override IEnumerable<Claim> MapClaims(AppUser account)
{
var results = base.MapClaims(account);
var firstName = string.IsNullOrWhiteSpace(account.FirstName) ? "(First)" : account.FirstName;
var claims = new List<Claim>(results)
{
new Claim("name", account.Username),
new Claim("firstName", firstName),
new Claim("lastName", string.IsNullOrWhiteSpace(account.LastName) ? "(Last)" : account.LastName),
//new Claim(ClaimTypes.Name, string.IsNullOrWhiteSpace(account.LastName) ? "(Last)" : account.LastName),
};
return claims;
}
}
}
| 30.783784 | 109 | 0.761194 | [
"BSD-3-Clause"
] | smhinsey/Fulcrum | seed/FulcrumSeed/Components/UserAccounts/Domain/Services/AppUserService.cs | 1,139 | C# |
#region Copyright © 2015 Couchcoding
// File: FrmLogSearch.cs
// Package: Logbert
// Project: Logbert
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Couchcoding
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Windows.Forms;
using Couchcoding.Logbert.Helper;
using Couchcoding.Logbert.Properties;
using System.Text.RegularExpressions;
using Couchcoding.Logbert.Interfaces;
using System.Collections.Specialized;
using System.Drawing;
using System.ComponentModel;
namespace Couchcoding.Logbert.Dialogs
{
/// <summary>
/// Implements a find window to search for text.
/// </summary>
public partial class FrmLogSearch : Form
{
#region Private Consts
/// <summary>
/// Defines the count of last searches to remember.
/// </summary>
private const int MAX_SEARCH_STRINGS_TO_REMEMBER = 10;
#endregion
#region Private Fields
private readonly ISearchable mSearchable;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the font of the text displayed by the control.
/// </summary>
/// <returns>The <see cref="T:System.Drawing.Font"/> to apply to the text displayed by the control. The default is the value of the <see cref="P:System.Windows.Forms.Control.DefaultFont"/> property.</returns>
[AmbientValue(null)]
[Localizable(true)]
public sealed override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
}
}
/// <summary>
/// Gets the current selected search value.
/// </summary>
public string CurrentSearchValue
{
get
{
return cmbFindWhat.Text;
}
}
#endregion
#region Private Methods
/// <summary>
/// Handles the FormClosing event of the <see cref="FrmLogSearch"/> <see cref="Form"/>.
/// </summary>
private void FrmLogSearchFormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
// Just hide the window.
Hide();
// Ensure it won't be realy closed.
e.Cancel = true;
}
}
/// <summary>
/// Handles the Load event of the <see cref="FrmLogSearch"/> <see cref="Form"/>.
/// </summary>
private void FrmLogSearchLoad(object sender, EventArgs e)
{
chkMatchCase.Checked = Settings.Default.FrmFindSearchMatchCase;
chkMatchWholeWord.Checked = Settings.Default.FrmFindSearchMatchWholeWord;
chkUse.Checked = Settings.Default.FrmFindSearchUseRegex ||
Settings.Default.FrmFindSearchUseWildcard;
cmbRegexWildcard.SelectedIndex = Settings.Default.FrmFindSearchUseWildcard
? 1 // Wildcard
: 0; // Regular Expression (.NET)
}
/// <summary>
/// Gets the last used search <see cref="String"/>s as an <see cref="Array"/>.
/// </summary>
/// <returns>An <see cref="Array"/> of <see cref="String"/>s that contains the last used search values.</returns>
private static string[] GetLastUsedSearchValues()
{
StringCollection strValues =
Settings.Default.FrmFindSearchValue
?? new StringCollection();
if (strValues.Count == 0 || !strValues.Contains(string.Empty))
{
// Ensure the very first entry is an empty string.
strValues.Insert(0, string.Empty);
}
string[] lastSearchValues = new string[strValues.Count];
strValues.CopyTo(lastSearchValues, 0);
return lastSearchValues;
}
/// <summary>
/// Handles the CheckedChanged event of the use regex or wildcard <see cref="CheckBox"/>.
/// </summary>
private void ChkUseCheckedChanged(object sender, EventArgs e)
{
cmbRegexWildcard.Enabled = chkUse.Checked;
CmbRegexWildcardSelectedIndexChanged(
sender
, e);
}
/// <summary>
/// Handles the CheckedChanged event of the match whole word <see cref="CheckBox"/>.
/// </summary>
private void ChkMatchWholeWordCheckedChanged(object sender, EventArgs e)
{
Settings.Default.FrmFindSearchMatchWholeWord = chkMatchWholeWord.Checked;
Settings.Default.SaveSettings();
}
/// <summary>
/// Handles the CheckedChanged event of the match case <see cref="CheckBox"/>.
/// </summary>
private void ChkMatchCaseCheckedChanged(object sender, EventArgs e)
{
Settings.Default.FrmFindSearchMatchCase = chkMatchCase.Checked;
Settings.Default.SaveSettings();
}
/// <summary>
/// Handles the TextUpdate event of the search <see cref="ComboBox"/>.
/// </summary>
private void CmbFindWhatTextUpdate(object sender, EventArgs e)
{
bool valueValid = !string.IsNullOrEmpty(cmbFindWhat.Text);
btnFindNext.Enabled = valueValid;
btnFindPrevious.Enabled = valueValid;
}
/// <summary>
/// Handles the SelectedIndexChanged event of the search <see cref="ComboBox"/>.
/// </summary>
private void CmbFindWhatSelectedIndexChanged(object sender, EventArgs e)
{
CmbFindWhatTextUpdate(sender, e);
}
/// <summary>
/// Handles the SelectedIndexChanged event of the regex or wildcard <see cref="ComboBox"/>.
/// </summary>
private void CmbRegexWildcardSelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRegexWildcard.SelectedIndex == -1)
{
return;
}
Settings.Default.FrmFindSearchUseRegex = chkUse.Checked && cmbRegexWildcard.SelectedIndex == 0;
Settings.Default.FrmFindSearchUseWildcard = chkUse.Checked && cmbRegexWildcard.SelectedIndex == 1;
Settings.Default.SaveSettings();
}
/// <summary>
/// Rebuilds the list of last used search values.
/// </summary>
private void RebuildSearchValuesList()
{
if (Settings.Default.FrmFindSearchValue == null)
{
// The list may be null on very first search.
Settings.Default.FrmFindSearchValue = new StringCollection();
}
// Ensure only the last 10 search strings are saved.
if (!Settings.Default.FrmFindSearchValue.Contains(cmbFindWhat.Text))
{
Settings.Default.FrmFindSearchValue.Insert(0, cmbFindWhat.Text);
if (Settings.Default.FrmFindSearchValue.Count > MAX_SEARCH_STRINGS_TO_REMEMBER)
{
StringCollection newStrCollection = new StringCollection();
for (int srcStrCnt = 0; srcStrCnt < MAX_SEARCH_STRINGS_TO_REMEMBER; ++srcStrCnt)
{
if (string.IsNullOrEmpty(Settings.Default.FrmFindSearchValue[srcStrCnt]))
{
continue;
}
newStrCollection.Add(Settings.Default.FrmFindSearchValue[srcStrCnt]);
}
Settings.Default.FrmFindSearchValue = newStrCollection;
}
Settings.Default.SaveSettings();
cmbFindWhat.Items.Clear();
cmbFindWhat.Items.AddRange(GetLastUsedSearchValues());
}
}
/// <summary>
/// Looks for the next match of the entered search value.
/// </summary>
private void BtnFindNextClick(object sender, EventArgs e)
{
PerformSearch(cmbFindWhat.Text);
}
/// <summary>
/// Looks for the previous match of the entered search value.
/// </summary>
private void BtnFindPreviousClick(object sender, EventArgs e)
{
PerformSearch(cmbFindWhat.Text, true);
}
/// <summary>
/// Processes a command key.
/// </summary>
/// <returns><c>True</c> if the keystroke was processed and consumed by the control; otherwise, <c>False</c> to allow further processing.</returns>
/// <param name="msg">A <see cref="T:System.Windows.Forms.Message"/>, passed by reference, that represents the Win32 message to process. </param><param name="keyData">One of the <see cref="T:System.Windows.Forms.Keys"/> values that represents the key to process. </param>
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
// Close the window.
Close();
// The key is handled.
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
#endregion
#region Public Methods
/// <summary>
/// Performs a search for the given string value.
/// </summary>
/// <param name="searchString">The value to search for.</param>
/// <param name="previous">Determines whether the previous value should be searched, ot the next one.</param>
internal void PerformSearch(string searchString, bool previous = false)
{
if (string.IsNullOrEmpty(searchString) || mSearchable == null)
{
// Nothing to search for.
return;
}
if (Settings.Default.FrmFindSearchUseWildcard)
{
searchString = searchString.ToRegex();
}
if (!Settings.Default.FrmFindSearchUseWildcard
&& !Settings.Default.FrmFindSearchUseRegex)
{
searchString = string.Format(
"{1}{0}{1}"
, Regex.Escape(searchString)
, Settings.Default.FrmFindSearchMatchWholeWord
? "\\b"
: string.Empty);
}
using (new WaitCursor(Cursors.Default, Settings.Default.WaitCursorTimeout))
{
mSearchable.SearchLogMessage(
searchString
, !previous
, cmbLookIn.SelectedIndex == 1);
RebuildSearchValuesList();
}
}
#endregion
#region Constructor
/// <summary>
/// Creates a new instance of the <see cref="FrmLogSearch"/> window.
/// </summary>
public FrmLogSearch(ISearchable searchable)
{
InitializeComponent();
Font = SystemFonts.MessageBoxFont;
mSearchable = searchable;
cmbLookIn.SelectedIndex = 0;
cmbFindWhat.Items.AddRange(GetLastUsedSearchValues());
}
#endregion
}
}
| 30.77591 | 275 | 0.651315 | [
"MIT"
] | Deb-BornToLearn/Logbert | src/Logbert/Dialogs/FrmLogSearch.cs | 10,990 | C# |
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.Json.Serialization;
using NetRpc.Contract;
namespace NetRpc;
public class PPInfo
{
public PropertyInfo? PropertyInfo { get; }
public ParameterInfo? ParameterInfo { get; }
public Type Type { get; }
public string Name { get; }
public string DefineName { get; }
public CustomAttributeBuilder? JsonCustomAttributeBuilder { get; }
public PPInfo(PropertyInfo propertyInfo)
{
var jsonP = propertyInfo.GetCustomAttribute<JsonPropertyNameAttribute>();
if (jsonP != null)
{
DefineName = jsonP.Name;
JsonCustomAttributeBuilder = GetJsonBuilder(DefineName);
}
else
DefineName = propertyInfo.Name;
Name = propertyInfo.Name;
PropertyInfo = propertyInfo;
Type = propertyInfo.PropertyType;
}
public PPInfo(ParameterInfo parameterInfo)
{
var jpn = parameterInfo.GetCustomAttribute<JsonParamNameAttribute>();
if (jpn != null)
{
JsonCustomAttributeBuilder = GetJsonBuilder(jpn.Name);
DefineName = jpn.Name;
}
DefineName ??= parameterInfo.Name!;
Name = parameterInfo.Name!;
ParameterInfo = parameterInfo;
Type = parameterInfo.ParameterType;
}
public PPInfo(string name, Type type)
{
Type = type;
Name = name;
DefineName = name;
}
private static CustomAttributeBuilder GetJsonBuilder(string name)
{
Type[] ctorParams = {typeof(string)};
var classCtorInfo = typeof(JsonPropertyNameAttribute).GetConstructor(ctorParams);
return new CustomAttributeBuilder(
classCtorInfo!,
new object[] {name});
}
} | 25.478873 | 89 | 0.637922 | [
"MIT"
] | newshadowk/Nrpc | src/NetRpc/Model/PPInfo.cs | 1,811 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Xalendar.View.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CalendarDay : ContentView
{
public CalendarDay()
{
InitializeComponent();
}
}
}
| 18.363636 | 53 | 0.69802 | [
"MIT"
] | brendonbarreto/Xalendar | src/Xalendar.View/Controls/CalendarDay.xaml.cs | 404 | C# |
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace MSBuild.Community.Tasks
{
/// <summary>
///
/// </summary>
public class RemoveDuplicatesAssemblies : Task
{
/// <summary>
///
/// </summary>
[Required]
public string SourceFolder
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override bool Execute()
{
try
{
Log.LogMessage("Remove duplicates assemblies from '{0}'", SourceFolder);
if (Path.DirectorySeparatorChar == '/')
{
SourceFolder = SourceFolder.Replace('\\', Path.DirectorySeparatorChar);
}
var fullSource = Path.GetFullPath(SourceFolder).TrimEnd(Path.DirectorySeparatorChar);
var mainBinFiles = Directory.GetFiles(Path.Combine(fullSource, "bin"), "*.dll", SearchOption.AllDirectories);
foreach (var f in Directory.GetFiles(fullSource, "*.dll", SearchOption.AllDirectories))
{
if (Array.Exists(mainBinFiles, (s) => f == s))
{
continue;
}
if (Array.Exists(mainBinFiles, (s) => Path.GetFileName(f) == Path.GetFileName(s)))
{
Log.LogMessage("Remove duplicate files '{0}'", f);
File.Delete(f);
}
}
return true;
}
catch (Exception err)
{
Log.LogErrorFromException(err);
return false;
}
}
}
}
| 28.772727 | 125 | 0.478146 | [
"Apache-2.0"
] | Ektai-Solution-Pty-Ltd/CommunityServer | redistributable/MSBuild.Community.Tasks/MSBuild.Community.Tasks/RemoveDuplicatesAssemblies.cs | 1,901 | C# |
/*
JSON Syntax Validator
(C) Torres Frederic 2013
Based on code from: How do I write my own parser? (for JSON) By Patrick van Bergen http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
My library heavily change Patrick van Bergen's code.
The library is release under the Mit Style License
*/
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using DynamicSugar;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace JSON.SyntaxValidator
{
public class Tokenizer
{
protected static Dictionary<TOKENS, string> TOKEN_STRING = new Dictionary<TOKENS, string>() {
{ TOKENS.NONE , "" },
{ TOKENS.CURLY_OPEN , "{" },
{ TOKENS.CURLY_CLOSE , "}" },
{ TOKENS.SQUARED_OPEN , "[" },
{ TOKENS.SQUARED_CLOSE, "]" },
{ TOKENS.COLON , ":" },
{ TOKENS.COMA , "," },
{ TOKENS.STRING , "" },
{ TOKENS.NUMBER , "" },
{ TOKENS.TRUE , "true" },
{ TOKENS.FALSE , "false"},
{ TOKENS.NULL , "null" },
{ TOKENS.ID , "Id" },
};
private static Regex _JsonDateRegEx_UTCTimeNoMilliSecond = new Regex(@"^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ", System.Text.RegularExpressions.RegexOptions.Compiled);
private static Regex _JsonDateRegEx_UTCTimeWithMilliSecond = new Regex(@"^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{1,3}Z", System.Text.RegularExpressions.RegexOptions.Compiled);
private static Regex _JsonDateRegEx_LocalTimeNoMilliSecondNoTimeZone = new Regex(@"^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d$", System.Text.RegularExpressions.RegexOptions.Compiled);
private static Regex _JsonDateRegEx_LocalTimeWithMilliSecondNoTimeZone = new Regex(@"^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d{1,3}$", System.Text.RegularExpressions.RegexOptions.Compiled);
private static Regex _JsonDateRegEx_LocalTimeWithMilliSecondWithTimeZone = new Regex(@"^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d{1,3}-\d\d:\d\d$", System.Text.RegularExpressions.RegexOptions.Compiled);
public static bool IsJsonDate(string v)
{
if (v.StartsWith("\""))
v = v.Substring(1);
if (v.EndsWith("\""))
v = v.Substring(0, v.Length - 1);
if(_JsonDateRegEx_UTCTimeNoMilliSecond.IsMatch(v))
return true;
if(_JsonDateRegEx_UTCTimeWithMilliSecond.IsMatch(v))
return true;
if(_JsonDateRegEx_LocalTimeNoMilliSecondNoTimeZone.IsMatch(v))
return true;
if(_JsonDateRegEx_LocalTimeWithMilliSecondNoTimeZone.IsMatch(v))
return true;
if(_JsonDateRegEx_LocalTimeWithMilliSecondWithTimeZone.IsMatch(v))
return true;
return false;
}
protected static int ValidateIntOrThrowError(string v, string errorMessage)
{
int i;
if (int.TryParse(v, out i))
return i;
throw new ArgumentException(String.Format(errorMessage, v));
}
/// <summary>
/// http://en.wikipedia.org/wiki/ISO_8601
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
protected static DateTime ParseJsonDateTime(string s)
{
// Torres Frederic
// Added Support for new Date("2012-09-17T22:33:03Z");
// Z mean UTC date according NODEJS
if (s.Contains("T") && s.EndsWith("Z"))
{
var parts = s.Split('T');
var dateParts = parts[0].Split('-');
var timeParts = parts[1].Replace("Z", "").Split(':');
var year = ValidateIntOrThrowError(dateParts[0], "Invalid Date (year):" + s);
var mon = ValidateIntOrThrowError(dateParts[1], "Invalid Date (month):" + s);
var mday = ValidateIntOrThrowError(dateParts[2], "Invalid Date (day):" + s);
var hour = ValidateIntOrThrowError(timeParts[0], "Invalid Date (hour)" + s);
var min = ValidateIntOrThrowError(timeParts[1], "Invalid Date (minute)" + s);
int milli = 0;
int sec = 0;
if (timeParts[2].Contains("."))
{
var SecMillParts = timeParts[2].Split('.');
sec = ValidateIntOrThrowError(SecMillParts[0], "Invalid Date (second)" + s);
milli = ValidateIntOrThrowError(SecMillParts[1], "Invalid Date (milli-second)" + s);
}
else
{
sec = ValidateIntOrThrowError(timeParts[2], "Invalid Date (second)" + s);
}
DateTime d = new DateTime(year, mon, mday, hour, min, sec, milli, DateTimeKind.Utc);
return d;
}
else if (s.Contains("T") && (!s.EndsWith("Z")))
{
// It is local time with possible a timezone defintion
// "2013-04-20T11:59:48.5820883-04:00"
var parts = s.Split('T');
var dateParts = parts[0].Split('-');
var timeParts = parts[1].Replace("Z", "").Split(':');
var year = ValidateIntOrThrowError(dateParts[0], "Invalid Date (year):" + s);
var mon = ValidateIntOrThrowError(dateParts[1], "Invalid Date (month):" + s);
var mday = ValidateIntOrThrowError(dateParts[2], "Invalid Date (day):" + s);
var hour = ValidateIntOrThrowError(timeParts[0], "Invalid Date (hour)" + s);
var min = ValidateIntOrThrowError(timeParts[1], "Invalid Date (minute)" + s);
// Analyse Second.millisecond-TimeZone
var secondsString = timeParts[2];
int milli = 0;
int sec = 0;
int timeZoneHours = 0;
int timeZoneMinutes = 0;
if (secondsString.Contains("."))
{
var secMillParts = secondsString.Split('.');
sec = ValidateIntOrThrowError(secMillParts[0], "Invalid Date (second)" + s);
var milliSeconds = secMillParts[1];
if(milliSeconds.Contains("-")) { // We are having a time zone
var milliParts = milliSeconds.Split('-');
milli = ValidateIntOrThrowError(milliParts[0], "Invalid Date (milli second)" + s);
var timeZoneParts = milliParts[1].Split(':');
timeZoneHours = ValidateIntOrThrowError(timeZoneParts[0], "Invalid Date (milli second)" + s);
timeZoneMinutes = ValidateIntOrThrowError(timeZoneParts[1], "Invalid Date (milli second)" + s);
}
else {
milli = ValidateIntOrThrowError(milliSeconds, "Invalid Date (milli-second)" + s);
}
}
else
{
sec = ValidateIntOrThrowError(secondsString, "Invalid Date (second)" + s);
}
var d = new DateTime(year, mon, mday, hour, min, sec, milli, DateTimeKind.Local);
return d;
}
else
throw new ArgumentException("Invalid JSON date:{0}".format(s));
}
protected static bool IsIdChar(char c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
(c == '_') || (c == '$');
}
protected static bool IsIdForFirstChar(char c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c == '_') || (c == '$');
}
protected static string ParseID(char[] json, ref int index, ref bool success, bool supportStarsComment, bool supportSlashComment)
{
EatWhitespace(json, ref index, supportStarsComment, supportSlashComment);
var b = new StringBuilder(100);
if (!IsIdForFirstChar(json[index]))
{
return null;
}
while (IsIdChar(json[index]))
{
b.Append(json[index]);
index++;
}
if (b.ToString().Length == 0)
return null;
return b.ToString();
}
protected static double ParseNumber(char[] json, ref int index, ref bool success, bool supportStarsComment , bool supportSlashComment)
{
EatWhitespace(json, ref index, supportStarsComment, supportSlashComment);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
double number;
success = Double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
index = lastIndex + 1;
return number;
}
protected static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++)
{
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1)
{
break;
}
}
return lastIndex - 1;
}
protected static void EatWhitespace(char[] json, ref int index, bool supportStarsComment, bool supportSlashComment)
{
for (; index < json.Length; index++)
{
if (" \t\n\r".IndexOf(json[index]) == -1)
{
if(supportStarsComment)
EatComment(json, ref index, supportStarsComment, supportSlashComment);
break;
}
}
}
protected static int GetLine(char [] charArray,int index)
{
int lineCounter = 0;
for (int i = 0; i < index; i++)
{
if (charArray[i] == '\n')
lineCounter++;
}
return lineCounter + 1;
}
protected static int GetColumn(char [] charArray, int index)
{
int i = index;
if (i >= charArray.Length)
{
i = charArray.Length - 1;
}
while (i >= 0 && charArray[i] != '\n')
{
i--;
}
if (i == -1)
{
i = 0;
}
else
{
i++;
}
var col = index - i;
return col;
}
private static bool IsCrOrLf(char c)
{
return c == '\r' || c == '\n';
}
protected static void EatComment(char[] json, ref int index, bool supportStarsComment, bool supportSlashComment)
{
if (index < json.Length - 1)
{
if(supportStarsComment) {
if (index < json.Length-1 && json[index] == '/' && json[index + 1] == '*')
{
while (index < json.Length && (!(json[index] == '*' && json[index + 1] == '/')))
{
index++;
}
index += 2;
EatWhitespace(json, ref index, supportStarsComment, supportSlashComment);
}
}
if(supportSlashComment)
{
if (index < json.Length-1 && json[index] == '/' && json[index + 1] == '/')
{
while (index < json.Length && (!IsCrOrLf(json[index])))
{
index++;
}
index += 2;
EatWhitespace(json, ref index, supportStarsComment, supportSlashComment);
}
}
else
{
if (index < json.Length-1 && json[index] == '/' && json[index + 1] == '/')
{
throw new JSON.SyntaxValidator.ParserException(JSON.SyntaxValidator.Compiler.SYNTAX_ERROR_019, GetLine(json, index), GetColumn(json, index), index);
}
}
}
}
protected static bool LookAheadForId(char[] json, int index, bool supportStarsComments , bool supportSlashComment)
{
int saveIndex = index;
bool success = false;
return ParseID(json, ref saveIndex, ref success, supportStarsComments, supportSlashComment) != null;
}
protected static TOKENS LookAhead(char[] json, int index, bool supportStarsComment , bool supportSlashComment)
{
int saveIndex = index;
return NextToken(json, ref saveIndex, supportStarsComment, supportSlashComment);
}
protected static TOKENS NextToken(char[] json, ref int index, bool supportStarsComment , bool supportSlashComment)
{
EatWhitespace(json, ref index, supportStarsComment, supportSlashComment);
if (index == json.Length)
{
return TOKENS.NONE;
}
char c = json[index];
index++;
switch (c)
{
case '{':
return TOKENS.CURLY_OPEN;
case '}':
return TOKENS.CURLY_CLOSE;
case '[':
return TOKENS.SQUARED_OPEN;
case ']':
return TOKENS.SQUARED_CLOSE;
case ',':
return TOKENS.COMA;
case '"':
return TOKENS.STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKENS.NUMBER;
case ':':
return TOKENS.COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5)
{
if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
{
index += 5;
return TOKENS.FALSE;
}
}
// true
if (remainingLength >= 4)
{
if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
{
index += 4;
return TOKENS.TRUE;
}
}
// null
if (remainingLength >= 4)
{
if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
{
index += 4;
return TOKENS.NULL;
}
}
if (LookAheadForId(json, index, supportStarsComment, supportSlashComment))
{
return TOKENS.ID;
}
return TOKENS.NONE;
}
}
}
| 40.0175 | 205 | 0.467171 | [
"Apache-2.0"
] | fredericaltorres/TextHighlighterExtension | JSON.SyntaxValidator/JSON.SyntaxValidator.Tokenizer.cs | 16,007 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Input
{
public class KeyboardSettings : SettingsSubsection
{
protected override string Header => "Keyboard";
public KeyboardSettings(KeyBindingOverlay keyConfig)
{
Children = new Drawable[]
{
new SettingsButton
{
Text = "Key Configuration",
Action = keyConfig.ToggleVisibility
},
};
}
}
}
| 28.44 | 93 | 0.561181 | [
"MIT"
] | StefanYohansson/osu | osu.Game/Overlays/Settings/Sections/Input/KeyboardSettings.cs | 713 | C# |
using System.Web.Mvc;
namespace IGCV_Protokoll.Areas.Session
{
public class SessionAreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "Session"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "Session_default",
url: "Session/{controller}/{action}/{id}",
defaults: new { controller = "Master", action = "Index", id = UrlParameter.Optional }
);
}
}
} | 22.47619 | 89 | 0.694915 | [
"MIT"
] | jfheins/IGCV-Protokoll | IGCV-Protokoll/Areas/Session/SessionAreaRegistration.cs | 474 | C# |
/************************************************************************
* Copyright (c) 2006-2008, Jason Whitehorn (jason.whitehorn@gmail.com)
* All rights reserved.
*
* Source code and binaries distributed under the terms of the included
* license, see license.txt for details.
************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using aspNETserve;
namespace IntegrationTests.NetServeTests {
/// <summary>
/// battery of test to verify that the HttpRequest object
/// of the running servers Context is behaving correctly.
/// </summary>
[TestFixture]
public class HttpRequestObjectTests : BaseTest{
[Test]
[Ignore]
public void AcceptTypesTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void AnonymousIDTest() {
throw new NotImplementedException();
}
[Test]
public void ApplicationPathTest() {
string value = GetServerVariable("Context.Request.ApplicationPath");
Assert.AreEqual("/", value);
}
[Test]
public void ApplicationPathVirtualPathTest(){
string value = GetServerVariable("Context.Request.ApplicationPath", "/vDir");
Assert.AreEqual("/vDir", value);
}
[Test]
public void AppRelativeCurrentExecutionFilePathTest() {
string value = GetServerVariable("Context.Request.AppRelativeCurrentExecutionFilePath");
Assert.AreEqual("~/GetServerVariable.aspx", value);
}
[Test]
[Ignore]
public void BrowserTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void ClientCertificateTest() {
throw new NotImplementedException();
}
[Test]
public void ContentEncodingTest() {
string value = GetServerVariable("Context.Request.ContentEncoding");
Assert.AreEqual("System.Text.UTF8Encoding", value);
}
[Test]
public void ContentLengthTest() {
string value = GetServerVariable("Context.Request.ContentLength");
Assert.AreEqual("0", value);
}
[Test]
[Ignore]
public void ContentTypeTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void CookiesTest() {
throw new NotImplementedException();
}
[Test]
public void CurrentExecutionFilePathTest() {
string value = GetServerVariable("Context.Request.CurrentExecutionFilePath");
Assert.AreEqual("/GetServerVariable.aspx", value);
}
[Test]
public void FilePathTest() {
string value = GetServerVariable("Context.Request.FilePath");
Assert.AreEqual("/GetServerVariable.aspx", value);
}
[Test]
[Ignore]
public void FilesTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void FilterTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void FormTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void HeadersTest() {
throw new NotImplementedException();
}
[Test]
public void HttpMethodTest() {
string value = GetServerVariable("Context.Request.HttpMethod");
Assert.AreEqual("GET", value);
}
[Test]
[Ignore]
public void InputStreamTest() {
throw new NotImplementedException();
}
[Test]
public void IsAuthenticatedTest() {
string value = GetServerVariable("Context.Request.IsAuthenticated");
Assert.AreEqual("False", value);
}
[Test]
public void IsLocalTest() {
string value = GetServerVariable("Context.Request.IsLocal");
Assert.AreEqual("True", value);
}
[Test]
public void IsSecureConnectionTest() {
string value = GetServerVariable("Context.Request.IsSecureConnection");
Assert.AreEqual("False", value);
}
[Test]
[Ignore]
public void ItemTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void LogonUserIdentityTest() {
throw new NotImplementedException();
}
[Test]
[Ignore]
public void ParamsTest() {
throw new NotImplementedException();
}
[Test]
public void PathTest() {
string value = GetServerVariable("Context.Request.Path");
Assert.AreEqual("/GetServerVariable.aspx", value);
}
[Test]
public void PathInfoTest() {
using (Server s = new Server(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }), "/", PhysicalPath, _port)) {
s.Start();
string url = string.Format("http://localhost:{0}/Tail.aspx", _port);
Console.WriteLine("Getting: " + url);
string page = GetPage(url);
Console.WriteLine(page);
Assert.AreEqual(true, page.Contains("<span id=\"lblTail\"></span>"));
url = string.Format("http://localhost:{0}/Tail.aspx/foo", _port);
Console.WriteLine("Getting: " + url);
page = GetPage(url);
Console.WriteLine(page);
Assert.AreEqual(true, page.Contains("<span id=\"lblTail\">/foo</span>"));
s.Stop();
}
}
[Test]
public void PhysicalApplicationPathTest() {
string value = GetServerVariable("Context.Request.PhysicalApplicationPath");
Assert.AreEqual(PhysicalPath, value);
}
[Test]
public void PhysicalPathTest() {
string value = GetServerVariable("Context.Request.PhysicalPath");
Assert.AreEqual(PhysicalPath + "GetServerVariable.aspx", value);
}
[Test]
public void QueryStringTest() {
string value = GetServerVariable("Context.Request.QueryString");
Assert.AreEqual("var=Context.Request.QueryString", value);
}
[Test]
public void RawUrlTest() {
string value = GetServerVariable("Context.Request.RawUrl");
Assert.AreEqual(@"/GetServerVariable.aspx?var=Context.Request.RawUrl", value);
}
[Test]
public void RequestTypeTest() {
string value = GetServerVariable("Context.Request.RequestType");
Assert.AreEqual("GET", value);
}
[Test]
[Ignore]
public void ServerVariablesTest() {
throw new NotImplementedException();
}
[Test]
public void TotalBytesTest() {
string value = GetServerVariable("Context.Request.TotalBytes");
Assert.AreEqual("0", value);
}
[Test]
public void UrlTest() {
string value = GetServerVariable("Context.Request.Url");
Assert.AreEqual("http://localhost:" + _port + "/GetServerVariable.aspx?var=Context.Request.Url", value);
}
[Test]
[Ignore]
public void UrlReferrerTest() {
throw new NotImplementedException();
}
[Test]
public void UserAgentTest() {
string value = GetServerVariable("Context.Request.UserAgent");
Assert.AreEqual(_userAgent, value);
}
[Test]
public void UserHostAddressTest() {
string value = GetServerVariable("Context.Request.UserHostAddress");
Assert.AreEqual("127.0.0.1", value);
}
[Test]
public void UserHostNameTest() {
string value = GetServerVariable("Context.Request.UserHostName");
Assert.AreEqual("127.0.0.1", value);
}
[Test]
[Ignore]
public void UserLanguagesTest() {
throw new NotImplementedException();
}
}
}
| 35.271186 | 124 | 0.556343 | [
"BSD-3-Clause"
] | crayse1/aspNETserve | IntegrationTests/NetServeTests/HttpRequestObjectTests.cs | 8,324 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osuTK;
namespace osu.Game.Rulesets.Osu.Difficulty.Preprocessing
{
public class OsuDifficultyHitObject : DifficultyHitObject
{
private const int normalized_radius = 52;
protected new OsuHitObject BaseObject => (OsuHitObject)base.BaseObject;
/// <summary>
/// Milliseconds elapsed since the start time of the previous <see cref="OsuDifficultyHitObject"/>, with a minimum of 25ms to account for simultaneous <see cref="OsuDifficultyHitObject"/>s.
/// </summary>
public double StrainTime { get; private set; }
/// <summary>
/// Normalized distance from the end position of the previous <see cref="OsuDifficultyHitObject"/> to the start position of this <see cref="OsuDifficultyHitObject"/>.
/// </summary>
public double JumpDistance { get; private set; }
/// <summary>
/// Normalized distance between the start and end position of the previous <see cref="OsuDifficultyHitObject"/>.
/// </summary>
public double TravelDistance { get; private set; }
/// <summary>
/// Angle the player has to take to hit this <see cref="OsuDifficultyHitObject"/>.
/// Calculated as the angle between the circles (current-2, current-1, current).
/// </summary>
public double? Angle { get; private set; }
private readonly OsuHitObject lastLastObject;
private readonly OsuHitObject lastObject;
public OsuDifficultyHitObject(HitObject hitObject, HitObject lastLastObject, HitObject lastObject, double clockRate)
: base(hitObject, lastObject, clockRate)
{
this.lastLastObject = (OsuHitObject)lastLastObject;
this.lastObject = (OsuHitObject)lastObject;
setDistances();
// Capped to 25ms to prevent difficulty calculation breaking from simulatenous objects.
StrainTime = Math.Max(DeltaTime, 25);
}
private void setDistances()
{
// We don't need to calculate either angle or distance when one of the last->curr objects is a spinner
if (BaseObject is Spinner || lastObject is Spinner)
return;
// We will scale distances by this factor, so we can assume a uniform CircleSize among beatmaps.
float scalingFactor = normalized_radius / (float)BaseObject.Radius;
if (BaseObject.Radius < 30)
{
float smallCircleBonus = Math.Min(30 - (float)BaseObject.Radius, 5) / 50;
scalingFactor *= 1 + smallCircleBonus;
}
if (lastObject is Slider lastSlider)
{
computeSliderCursorPosition(lastSlider);
TravelDistance = lastSlider.LazyTravelDistance * scalingFactor;
}
Vector2 lastCursorPosition = getEndCursorPosition(lastObject);
JumpDistance = (BaseObject.StackedPosition * scalingFactor - lastCursorPosition * scalingFactor).Length;
if (lastLastObject != null && !(lastLastObject is Spinner))
{
Vector2 lastLastCursorPosition = getEndCursorPosition(lastLastObject);
Vector2 v1 = lastLastCursorPosition - lastObject.StackedPosition;
Vector2 v2 = BaseObject.StackedPosition - lastCursorPosition;
float dot = Vector2.Dot(v1, v2);
float det = v1.X * v2.Y - v1.Y * v2.X;
Angle = Math.Abs(Math.Atan2(det, dot));
}
}
private void computeSliderCursorPosition(Slider slider)
{
if (slider.LazyEndPosition != null)
return;
slider.LazyEndPosition = slider.StackedPosition;
float approxFollowCircleRadius = (float)(slider.Radius * 3);
var computeVertex = new Action<double>(t =>
{
double progress = (t - slider.StartTime) / slider.SpanDuration;
if (progress % 2 >= 1)
progress = 1 - progress % 1;
else
progress %= 1;
// ReSharper disable once PossibleInvalidOperationException (bugged in current r# version)
var diff = slider.StackedPosition + slider.Path.PositionAt(progress) - slider.LazyEndPosition.Value;
float dist = diff.Length;
if (dist > approxFollowCircleRadius)
{
// The cursor would be outside the follow circle, we need to move it
diff.Normalize(); // Obtain direction of diff
dist -= approxFollowCircleRadius;
slider.LazyEndPosition += diff * dist;
slider.LazyTravelDistance += dist;
}
});
// Skip the head circle
var scoringTimes = slider.NestedHitObjects.Skip(1).Select(t => t.StartTime);
foreach (double time in scoringTimes)
computeVertex(time);
}
private Vector2 getEndCursorPosition(OsuHitObject hitObject)
{
Vector2 pos = hitObject.StackedPosition;
if (hitObject is Slider slider)
{
computeSliderCursorPosition(slider);
pos = slider.LazyEndPosition ?? pos;
}
return pos;
}
}
}
| 40.534722 | 198 | 0.590714 | [
"MIT"
] | DouglasMarq/osu | osu.Game.Rulesets.Osu/Difficulty/Preprocessing/OsuDifficultyHitObject.cs | 5,694 | C# |
/*
* Copyright (c) 2014, Furore (info@furore.com) and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the BSD 3-Clause license
* available at https://raw.githubusercontent.com/ewoutkramer/fhir-net-api/master/LICENSE
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hl7.Fhir.Model
{
public partial class ValueSet : Hl7.Fhir.Model.DomainResource
{
[Obsolete("This property was renamed in DSTU2 to CodeSystem", true)]
public ValueSetCodeSystemComponent Define { get; set; }
// public static bool CodeEquals(string code, string value, bool caseSensitive)
// {
// return String.Equals(code, value,
// caseSensitive ? StringComparison.Ordinal :
// StringComparison.OrdinalIgnoreCase);
// }
// public static IEnumerable<ValueSetDefineConceptComponent> GetFlattenedDefinedConcepts(
// IEnumerable<ValueSetDefineConceptComponent> concepts)
// {
// foreach (var concept in concepts)
// {
// yield return concept;
// if (concept.Concept != null)
// foreach (var childConcept in GetFlattenedDefinedConcepts(concept.Concept))
// yield return childConcept;
// }
// }
// internal static ValueSetDefineConceptComponent GetDefinedConceptForCode(
// IEnumerable<ValueSetDefineConceptComponent> concepts, string code, bool caseSensitive = true)
// {
// if (concepts != null)
// return GetFlattenedDefinedConcepts(concepts)
// .FirstOrDefault(c => CodeEquals(c.Code, code, caseSensitive));
// else
// return null;
// }
// /// <summary>
// /// Searches for a concept, defined in this ValueSet, using its code
// /// </summary>
// /// <param name="code"></param>
// /// <returns>The concept, or null if there was no concept found with that code</returns>
// /// <remarks>The search will search nested concepts as well.
// /// Whether the search is case-sensitive depends on the value of Define.CaseSensitive</remarks>
// public ValueSetDefineConceptComponent GetDefinedConceptForCode(string code)
// {
// if (this.Define != null && this.Define.Concept != null)
// {
// bool caseSensitive = Define.CaseSensitive.GetValueOrDefault();
// return GetDefinedConceptForCode(this.Define.Concept, code, caseSensitive);
// }
// else
// return null;
// }
// }
}
}
| 39.878378 | 119 | 0.560149 | [
"BSD-3-Clause"
] | ssharunas/fhir-net-api | src/Hl7.Fhir.Core/Model/ValueSet.cs | 2,953 | C# |
using System;
using System.Linq.Expressions;
using System.Security.Claims;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using NSubstitute;
using Sfa.Tl.Matching.Api.Clients.GeoLocations;
using Sfa.Tl.Matching.Api.Clients.GoogleMaps;
using Sfa.Tl.Matching.Application.Interfaces;
using Sfa.Tl.Matching.Application.Mappers;
using Sfa.Tl.Matching.Application.Mappers.Resolver;
using Sfa.Tl.Matching.Application.Services;
using Sfa.Tl.Matching.Application.UnitTests.Services.ProviderVenue.Builders;
using Sfa.Tl.Matching.Data.Interfaces;
using Sfa.Tl.Matching.Models.ViewModel;
using Xunit;
namespace Sfa.Tl.Matching.Application.UnitTests.Services.ProviderVenue
{
public class When_ProviderVenueService_Is_Called_To_Update_Venue_With_Postcode_For_Name
{
private readonly ILocationApiClient _locationApiClient;
private readonly IProviderVenueRepository _providerVenueRepository;
public When_ProviderVenueService_Is_Called_To_Update_Venue_With_Postcode_For_Name()
{
var httpContextAccessor = Substitute.For<IHttpContextAccessor>();
httpContextAccessor.HttpContext.Returns(new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.GivenName, "TestUser")
}))
});
var dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.UtcNow().Returns(new DateTime(2019, 1, 1));
_locationApiClient = Substitute.For<ILocationApiClient>();
_locationApiClient.IsValidPostcodeAsync(Arg.Any<string>(), Arg.Any<bool>())
.Returns(callinfo => callinfo.Arg<string>() == "CV1 2WT"
? (true, "CV1 2WT")
: (false, null));
var config = new MapperConfiguration(c =>
{
c.AddMaps(typeof(ProviderVenueMapper).Assembly);
c.ConstructServicesUsing(type =>
type.Name.Contains("LoggedInUserEmailResolver") ?
new LoggedInUserEmailResolver<ProviderVenueDetailViewModel, Domain.Models.ProviderVenue>(httpContextAccessor) :
type.Name.Contains("LoggedInUserNameResolver") ?
new LoggedInUserNameResolver<ProviderVenueDetailViewModel, Domain.Models.ProviderVenue>(httpContextAccessor) :
type.Name.Contains("UtcNowResolver") ?
new UtcNowResolver<ProviderVenueDetailViewModel, Domain.Models.ProviderVenue>(dateTimeProvider) :
type.Name.Contains("VenueNameResolver") ?
(object)new VenueNameResolver(_locationApiClient) :
null);
});
var mapper = new Mapper(config);
_providerVenueRepository = Substitute.For<IProviderVenueRepository>();
_providerVenueRepository.GetSingleOrDefaultAsync(Arg.Any<Expression<Func<Domain.Models.ProviderVenue, bool>>>())
.Returns(new ValidProviderVenueBuilder().Build());
var googleMapApiClient = Substitute.For<IGoogleMapApiClient>();
var locationService = Substitute.For<ILocationApiClient>();
var providerVenueService = new ProviderVenueService(mapper, _providerVenueRepository, locationService, googleMapApiClient);
var viewModel = new ProviderVenueDetailViewModel
{
Id = 1,
Postcode = "CV1 2WT",
Name = "CV1 2WT",
IsEnabledForReferral = true
};
providerVenueService.UpdateVenueAsync(viewModel).GetAwaiter().GetResult();
}
[Fact]
public void LocationApiClient_IsValidPostcode_Is_Called_Exactly_Once()
{
_locationApiClient
.Received(1)
.IsValidPostcodeAsync(Arg.Is<string>(s => s == "CV1 2WT"),
Arg.Is<bool>(b => b));
}
[Fact]
public void Then_ProviderVenueRepository_GetSingleOrDefault_Is_Called_Exactly_Once()
{
_providerVenueRepository.Received(1).GetSingleOrDefaultAsync(Arg.Any<Expression<Func<Domain.Models.ProviderVenue, bool>>>());
}
[Fact]
public void Then_ProviderVenueRepository_Update_Is_Called_Exactly_Once_With_Expected_Values()
{
_providerVenueRepository
.Received(1)
.UpdateAsync(Arg.Is<Domain.Models.ProviderVenue>(
pv => pv.Id == 1 &&
pv.Postcode == "CV1 2WT" &&
pv.Name == "CV1 2WT" &&
pv.IsEnabledForReferral &&
!pv.IsRemoved &&
pv.ModifiedBy == "TestUser" &&
pv.ModifiedOn == new DateTime(2019, 1, 1)));
}
}
} | 44.603604 | 138 | 0.621491 | [
"MIT"
] | SkillsFundingAgency/tl-matching | src/Sfa.Tl.Matching.Application.UnitTests/Services/ProviderVenue/When_ProviderVenueService_Is_Called_To_Update_Venue_With_Postcode_For_Name.cs | 4,953 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TPUM.Shared.NetworkModel.Core;
namespace TPUM.Client.Data.Core
{
public interface IHttpClient : IWebDataSource, IDisposable
{
Task<IEnumerable<IBook>> GetBooksAsync();
Task<IEnumerable<IAuthor>> GetAuthorsAsync();
Task<IAuthor> AddRandomAuthorAsync();
}
}
| 25.2 | 62 | 0.727513 | [
"MIT"
] | 210342/TPUM | Src/Client/Data/Core/IHttpClient.cs | 380 | C# |
// ***************************************************************************
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// 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 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.
//
// For more information, please refer to <http://unlicense.org>
// ***************************************************************************
using MyStromRestApiCSharp.DTOs.Bulb;
namespace MyStromRestApiCSharp.Devices
{
public class BulbAction
{
private BulbAction(string value)
{
Value = value;
}
public string Value { get; set; }
public static BulbAction On => new BulbAction("on");
public static BulbAction Off => new BulbAction("off");
public static BulbAction Toggle => new BulbAction("toggle");
}
public class MyStromBulb : MyStromDevice
{
public string MacAddress { get; set; }
public DeviceInformationResultJson UpdatedInfo { get; set; }
public MyStromBulb(string name, string ipAddress, string macAddress, string token) : base(name,
ipAddress,
token)
{
MacAddress = macAddress;
}
public ToggleResultJson SendToggle()
{
var response = HttpPostUrlEncoded($"api/v1/device/{MacAddress}", "action=toggle");
return MyStromUtil.UnwrapDefunctJson<ToggleResultWrapperJson>(response).Root[0];
}
public ToggleResultJson SendOn()
{
var response = HttpPostUrlEncoded($"api/v1/device/{MacAddress}", "action=on");
return MyStromUtil.UnwrapDefunctJson<ToggleResultWrapperJson>(response).Root[0];
}
public ToggleResultJson SendOff()
{
var response = HttpPostUrlEncoded($"api/v1/device/{MacAddress}", "action=off");
return MyStromUtil.UnwrapDefunctJson<ToggleResultWrapperJson>(response).Root[0];
}
public DeviceInformationResultJson GetDeviceInformation()
{
var response = HttpGet("api/v1/device");
return MyStromUtil.UnwrapDefunctJson<DeviceInformationResultWrapperJson>(response).Root[0];
}
/// <summary>
/// Sets the color to a given value.
/// </summary>
/// <param name="color">
/// If this field contains 3 semi-colon delimited integers, the mode is set to 'hsv'. Then this field contains the
/// integer values (hue 0-359;saturation 0-100;value 0-100).
/// If this field contains a string of 4 bytes hex-digits the mode is set to 'rgb'. Then this field contains the
/// hex-value of the WRGB color (white;red;green;blue). Example: white: 'color=FF000000', green: 'color=0000ff00'
/// If this field contains 2 semi-colon delimited integers, the mode is set to 'mono'. Then it contains the value for
/// the color temperature (from 1 to 18) and the brightness (from 0 to 100). Example: 'color=10;80'.
/// Failing to honor the int-limits or other inputs result in a bad request status code.
/// </param>
/// <param name="ramp">The time the bulb will take to change to that color (it will perform a fade).</param>
/// <param name="action">The action you want the bulb to do when it receives this message.</param>
/// <param name="notifyUrl">An URL that will be posted to from now on on every state-change until you set it to '' again.</param>
/// <returns></returns>
public ToggleResultJson SetColor(string color, int ramp = 0, BulbAction action = null, string notifyUrl = "")
{
var a = "";
if (action != null) a = $"&{action}";
var response = HttpPostUrlEncoded($"api/v1/device/{MacAddress}",
$"color={color}{a}&ramp={ramp}¬ifyurl={notifyUrl}");
return MyStromUtil.UnwrapDefunctJson<ToggleResultWrapperJson>(response).Root[0];
}
public override void Update()
{
UpdatedInfo = GetDeviceInformation();
base.Update();
}
}
} | 41.752212 | 131 | 0.695422 | [
"Unlicense"
] | UnterrainerInformatik/MyStromRestApiCSharp | MyStromRestApiCSharp/Devices/MyStromBulb.cs | 4,720 | C# |
// Copyright 2021 Niantic, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Niantic.ARDK.Networking;
using Niantic.ARDK.Utilities.Extensions;
using Niantic.ARDK.Utilities;
using Niantic.ARDK.Utilities.Logging;
using Niantic.ARDK.VirtualStudio.Remote;
using Niantic.ARDK.VirtualStudio.Remote.Data;
#if UNITY_EDITOR
using UnityEditor.Networking.PlayerConnection;
using UnityEditor;
#endif
using UnityEngine;
using UnityEngine.Networking.PlayerConnection;
using UnityEngine.Serialization;
using Object = UnityEngine.Object;
namespace Niantic.ARDK.VirtualStudio.Remote
{
/// TODO(bpeake): Make instantiatable type for testing.
/// Helper class for handling the remote connection with the player/editor.
internal static class _RemoteConnection
{
public enum ConnectionMethod
{
USB,
Internet,
}
private struct BufferedMessage
{
public Guid Tag;
public TransportType TransportType;
public byte[] Data;
}
// Messages that were sent while disconnected still.
private static readonly List<BufferedMessage> _bufferedMessages = new List<BufferedMessage>();
private static _IRemoteConnectionCompat _remoteConnectionImpl;
/// True if the remote connection is connected to another device.
public static bool IsConnected
{
get
{
return _remoteConnectionImpl != null && _remoteConnectionImpl.IsConnected;
}
}
/// True if the remote connection is ready to connect to another device.
public static bool IsReady
{
get
{
return _remoteConnectionImpl != null && _remoteConnectionImpl.IsReady;
}
}
public static bool IsEnabled
{
get
{
#if UNITY_EDITOR
var use = PlayerPrefs.GetInt(ARDKUseRemoteProperty, 0);
return use == 1;
#else
return true;
#endif
}
#if UNITY_EDITOR
set
{
if (!Application.isPlaying)
PlayerPrefs.SetInt(ARDKUseRemoteProperty, value ? 1 : 0);
}
#endif
}
private const string ARDKUseRemoteProperty = "ARDK_Use_Remote";
/// The secret that was used to connect devices together.
public static string Secret
{
get
{
if (_remoteConnectionImpl != null)
return _remoteConnectionImpl.DeviceGroupIdentifier;
return "";
}
}
/// The ID associated with the connection.
public static string ConnectionID
{
get
{
if (_remoteConnectionImpl != null)
return _remoteConnectionImpl.LocalDeviceIdentifier;
return "";
}
}
/// The version that is being used.
public static ConnectionMethod CurrentConnectionMethod
{
get
{
return _connectionMethod;
}
}
private static ConnectionMethod _connectionMethod;
/// <summary>
/// Initializes the remote connection using the version of remote connection that corresponds
/// with the given connection method.
/// </summary>
/// <param name="connectionMethod">The connection method to use.</param>
/// <exception cref="ArgumentOutOfRangeException">If an unknown connection method is given.</exception>
public static void InitIfNone(ConnectionMethod connectionMethod)
{
if (_remoteConnectionImpl != null)
{
ARLog._Debug("RemoteConnection was already initialized.");
return;
}
Init(connectionMethod);
}
private static void Init(ConnectionMethod connectionMethod)
{
Screen.orientation = ScreenOrientation.Portrait;
Screen.autorotateToPortrait = false;
Screen.autorotateToLandscapeLeft = false;
Screen.autorotateToLandscapeRight = false;
Screen.autorotateToPortraitUpsideDown = false;
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Application.runInBackground = true;
Platform.Init();
if (_remoteConnectionImpl != null)
_remoteConnectionImpl.Dispose();
_connectionMethod = connectionMethod;
switch (connectionMethod)
{
case ConnectionMethod.USB:
_remoteConnectionImpl = new _UsbRemoteConnection();
// TODO(awang): Because of different message handling flows, this will be called in
// different places for different implementations. Unify them somehow?
_EasyConnection.Initialize();
break;
case ConnectionMethod.Internet:
_remoteConnectionImpl = new _InternetRemoteConnectionCompat();
break;
default:
throw new ArgumentOutOfRangeException();
}
_CallbackQueue.ApplicationWillQuit += OnApplicationWillQuit;
_EasyConnection.Register<RemoteConnectionDestroyMessage>(Deinitialize);
#if !UNITY_EDITOR
_RemoteDeviceARSessionConstructor.RegisterForInitMessage();
_RemoteDeviceMultipeerNetworkingConstructor.RegisterForInitMessage();
_RemoteDeviceARNetworkingConstructor.RegisterForInitMessage();
#endif
}
public static void Deinitialize()
{
_EasyConnection.Send(new RemoteConnectionDestroyMessage());
Dispose();
}
private static void Deinitialize(RemoteConnectionDestroyMessage message)
{
// Dispose before raising error, in case Unity Editor is set to pause on errors
Dispose();
#if UNITY_EDITOR
ARLog._Error("Lost connection with the ARDK Remote Feed App.");
#endif
}
private static void Dispose()
{
var connection = _remoteConnectionImpl;
if (connection == null)
return;
var handler = Deinitialized;
if (handler != null)
handler();
_EasyConnection.Unregister<RemoteConnectionDestroyMessage>();
_remoteConnectionImpl = null;
connection.Dispose();
_RemoteDeviceARSessionConstructor._Deinitialize();
_RemoteDeviceMultipeerNetworkingConstructor._Deinitialize();
_RemoteDeviceARNetworkingConstructor._Deinitialize();
}
private static void OnApplicationWillQuit()
{
_CallbackQueue.ApplicationWillQuit -= OnApplicationWillQuit;
Deinitialize();
}
/// <summary>
/// Connects the remote connection to a specific pin.
/// </summary>
public static void Connect(string pin)
{
if (_remoteConnectionImpl != null)
_remoteConnectionImpl.Connect(pin);
}
/// <summary>
/// Registers a callback to be called whenever data is sent over the specific id.
/// </summary>
/// <param name="id">The id of the data.</param>
/// <param name="e">The event to fire when data of the specific id comes.</param>
public static void Register(Guid id, Action<MessageEventArgs> e)
{
if (_remoteConnectionImpl != null)
_remoteConnectionImpl.Register(id, e);
}
/// <summary>
/// Unregisters a callback.
/// </summary>
/// <param name="id">The id to unregister from.</param>
/// <param name="e">The callback to unregister.</param>
public static void Unregister(Guid id, Action<MessageEventArgs> e)
{
if (_remoteConnectionImpl != null)
_remoteConnectionImpl.Unregister(id, e);
}
/// <summary>
/// Sends data over the remote connection.
/// </summary>
/// <param name="id">The id to send with the data.</param>
/// <param name="data">The data to send.</param>
/// <param name="transportType">The protocol to send the data with.</param>
public static void Send(Guid id, byte[] data, TransportType transportType = TransportType.ReliableUnordered)
{
bool readyAndConnected =
_remoteConnectionImpl != null &&
_remoteConnectionImpl.IsReady &&
_remoteConnectionImpl.IsConnected;
if (readyAndConnected)
{
if (_bufferedMessages.Count != 0)
TryClearBuffer();
_remoteConnectionImpl.Send(id, data, transportType);
}
else
{
var message =
new BufferedMessage()
{
Tag = id,
TransportType = transportType,
Data = data,
};
_bufferedMessages.Add(message);
if (_bufferedMessages.Count == 1)
_CallbackQueue.QueueCallback(_tryClearBufferAction);
}
}
/// <summary>
/// Sends a message over remote connection.
/// </summary>
/// <param name="id">The id of the message.</param>
/// <param name="value">The value to send.</param>
/// <param name="transportType">The protocol to send the data with.</param>
public static void Send<TValue>(Guid id, TValue value, TransportType transportType = TransportType.ReliableUnordered)
{
Send(id, value.SerializeToArray(), transportType);
}
// Store the delegate once so we don't keep allocating new Action objects per call.
private static readonly Action _tryClearBufferAction = TryClearBuffer;
private static void TryClearBuffer()
{
bool readyAndConnected =
_remoteConnectionImpl != null &&
_remoteConnectionImpl.IsReady &&
_remoteConnectionImpl.IsConnected;
if (!readyAndConnected)
{
_CallbackQueue.QueueCallback(TryClearBuffer);
return;
}
var messages = _bufferedMessages.ToArray();
_bufferedMessages.Clear();
foreach (var bufferedMessage in messages)
Send(bufferedMessage.Tag, bufferedMessage.Data, bufferedMessage.TransportType);
}
public static Action Deinitialized;
}
}
| 28.404192 | 121 | 0.670075 | [
"MIT"
] | AmerAli94/ARSample_Niantic | Assets/ARDK/VirtualStudio/Remote/_RemoteConnection.cs | 9,487 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FxCopAnalyzers.Design;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.FxCopAnalyzers.Design;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class CA1008FixerTests : CodeFixTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new CA1008DiagnosticAnalyzer();
}
protected override CodeFixProvider GetBasicCodeFixProvider()
{
return new CA1008BasicCodeFixProvider();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CA1008DiagnosticAnalyzer();
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new CA1008CSharpCodeFixProvider();
}
[WorkItem(836193)]
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueFlagsRename()
{
var code = @"
[System.Flags]
private enum E
{
A = 0,
B = 3
}
[System.Flags]
public enum E2
{
A2 = 0,
B2 = 1
}
[System.Flags]
public enum E3
{
A3 = (ushort)0,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
A4 = 0,
B4 = (uint)2 // Not a constant
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
var expectedFixedCode = @"
[System.Flags]
private enum E
{
None = 0,
B = 3
}
[System.Flags]
public enum E2
{
None = 0,
B2 = 1
}
[System.Flags]
public enum E3
{
None = (ushort)0,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
None = 0,
B4 = (uint)2 // Not a constant
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueFlagsMultipleZero()
{
var code = @"// Some comment
[System.Flags]
private enum E
{
None = 0,
A = 0
}
// Some comment
[System.Flags]
internal enum E2
{
None = 0,
A = None
}";
var expectedFixedCode = @"// Some comment
[System.Flags]
private enum E
{
None = 0
}
// Some comment
[System.Flags]
internal enum E2
{
None = 0
}";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void CSharp_EnumsShouldZeroValueNotFlagsNoZeroValue()
{
var code = @"
private enum E
{
A = 1
}
private enum E2
{
None = 1,
A = 2
}
internal enum E3
{
None = 0,
A = 1
}
internal enum E4
{
None = 0,
A = 0
}
";
var expectedFixedCode = @"
private enum E
{
None,
A = 1
}
private enum E2
{
None,
A = 2
}
internal enum E3
{
None = 0,
A = 1
}
internal enum E4
{
None = 0,
A = 0
}
";
VerifyCSharpFix(code, expectedFixedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueFlagsRename()
{
var code = @"
<System.Flags>
Private Enum E
A = 0
B = 1
End Enum
<System.Flags>
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
<System.Flags>
Private Enum E
None = 0
B = 1
End Enum
<System.Flags>
Public Enum E2
None = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
None = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
[WorkItem(836193)]
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueFlagsRename_AttributeListHasTrivia()
{
var code = @"
<System.Flags> _
Private Enum E
A = 0
B = 1
End Enum
<System.Flags> _
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
<System.Flags> _
Private Enum E
None = 0
B = 1
End Enum
<System.Flags> _
Public Enum E2
None = 0
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
None = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueFlagsMultipleZero()
{
var code = @"
<System.Flags>
Private Enum E
None = 0
A = 0
End Enum
<System.Flags>
Friend Enum E2
None = 0
A = None
End Enum
<System.Flags>
Public Enum E3
A3 = 0
B3 = CUInt(0) ' Not a constant
End Enum";
var expectedFixedCode = @"
<System.Flags>
Private Enum E
None = 0
End Enum
<System.Flags>
Friend Enum E2
None = 0
End Enum
<System.Flags>
Public Enum E3
None
End Enum";
VerifyBasicFix(code, expectedFixedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
public void VisualBasic_EnumsShouldZeroValueNotFlagsNoZeroValue()
{
var code = @"
Private Enum E
A = 1
End Enum
Private Enum E2
None = 1
A = 2
End Enum
Friend Enum E3
None = 0
A = 1
End Enum
Friend Enum E4
None = 0
A = 0
End Enum
";
var expectedFixedCode = @"
Private Enum E
None
A = 1
End Enum
Private Enum E2
None
A = 2
End Enum
Friend Enum E3
None = 0
A = 1
End Enum
Friend Enum E4
None = 0
A = 0
End Enum
";
VerifyBasicFix(code, expectedFixedCode);
}
}
}
| 15.847666 | 184 | 0.611163 | [
"Apache-2.0"
] | enginekit/copy_of_roslyn | Src/Diagnostics/FxCop/Test/Design/CodeFixes/CA1008FixerTests.cs | 6,452 | 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.ContainerRegistry.V20170301.Outputs
{
[OutputType]
public sealed class RegistryPasswordResponseResult
{
/// <summary>
/// The password name.
/// </summary>
public readonly string? Name;
/// <summary>
/// The password value.
/// </summary>
public readonly string? Value;
[OutputConstructor]
private RegistryPasswordResponseResult(
string? name,
string? value)
{
Name = name;
Value = value;
}
}
}
| 24.638889 | 81 | 0.612176 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ContainerRegistry/V20170301/Outputs/RegistryPasswordResponseResult.cs | 887 | C# |
using ProtoBuf;
using System;
using System.ComponentModel;
namespace GameData
{
[ProtoContract(Name = "JunTuanZhanDou")]
[Serializable]
public class JunTuanZhanDou : IExtensible
{
private int _CollectionId;
private int _Occupy;
private int _AddOccupy;
private int _Multiple;
private int _CoordinateTime;
private int _Resource;
private int _AddResource;
private int _KillResource;
private int _People;
private int _Id;
private IExtension extensionObject;
[ProtoMember(2, IsRequired = true, Name = "CollectionId", DataFormat = DataFormat.TwosComplement)]
public int CollectionId
{
get
{
return this._CollectionId;
}
set
{
this._CollectionId = value;
}
}
[ProtoMember(3, IsRequired = false, Name = "Occupy", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int Occupy
{
get
{
return this._Occupy;
}
set
{
this._Occupy = value;
}
}
[ProtoMember(4, IsRequired = false, Name = "AddOccupy", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int AddOccupy
{
get
{
return this._AddOccupy;
}
set
{
this._AddOccupy = value;
}
}
[ProtoMember(6, IsRequired = false, Name = "Multiple", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int Multiple
{
get
{
return this._Multiple;
}
set
{
this._Multiple = value;
}
}
[ProtoMember(7, IsRequired = false, Name = "CoordinateTime", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int CoordinateTime
{
get
{
return this._CoordinateTime;
}
set
{
this._CoordinateTime = value;
}
}
[ProtoMember(8, IsRequired = false, Name = "Resource", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int Resource
{
get
{
return this._Resource;
}
set
{
this._Resource = value;
}
}
[ProtoMember(9, IsRequired = false, Name = "AddResource", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int AddResource
{
get
{
return this._AddResource;
}
set
{
this._AddResource = value;
}
}
[ProtoMember(10, IsRequired = false, Name = "KillResource", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int KillResource
{
get
{
return this._KillResource;
}
set
{
this._KillResource = value;
}
}
[ProtoMember(11, IsRequired = false, Name = "People", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int People
{
get
{
return this._People;
}
set
{
this._People = value;
}
}
[ProtoMember(12, IsRequired = false, Name = "Id", DataFormat = DataFormat.TwosComplement), DefaultValue(0)]
public int Id
{
get
{
return this._Id;
}
set
{
this._Id = value;
}
}
IExtension IExtensible.GetExtensionObject(bool createIfMissing)
{
return Extensible.GetExtensionObject(ref this.extensionObject, createIfMissing);
}
}
}
| 17.881657 | 120 | 0.65685 | [
"MIT"
] | corefan/tianqi_src | src/GameData/JunTuanZhanDou.cs | 3,022 | C# |
using System;
using Ckode.Dapper.Repository.Sql;
using Ckode.Dapper.Repository.UnitTests.Entities;
using Xunit;
namespace Ckode.Dapper.Repository.UnitTests.Sql
{
public class QueryGeneratorTests
{
#region Constructor
[Fact]
public void Constructor_TableNameIsNull_Throws()
{
// Arrange, act && assert
Assert.Throws<ArgumentNullException>(() => new SqlQueryGenerator<HeapEntity>("dbo", null!));
}
[Fact]
public void Constructor_SchemaIsNull_Throws()
{
// Arrange, act && assert
Assert.Throws<ArgumentNullException>(() => new SqlQueryGenerator<HeapEntity>(null!, "Users"));
}
[Fact]
public void Constructor_TableNameIsWhitespace_Throws()
{
// Arrange, act && assert
Assert.Throws<ArgumentException>(() => new SqlQueryGenerator<HeapEntity>("dbo", " "));
}
[Fact]
public void Constructor_SchemaIsWhitespace_Throws()
{
// Arrange, act && assert
Assert.Throws<ArgumentException>(() => new SqlQueryGenerator<HeapEntity>(" ", "Users"));
}
#endregion
#region Delete
[Fact]
public void GenerateDeleteQuery_CustomSchema_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<SinglePrimaryKeyEntity>("account", "Users");
// Act
var query = generator.GenerateDeleteQuery();
// Assert
Assert.Equal("DELETE FROM [account].[Users] OUTPUT [deleted].[Id], [deleted].[Username], [deleted].[Password] WHERE [account].[Users].[Id] = @Id;", query);
}
[Fact]
public void GenerateDeleteQuery_OnePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<SinglePrimaryKeyEntity>("dbo", "Users");
// Act
var deleteQuery = generator.GenerateDeleteQuery();
// Assert
Assert.Equal($"DELETE FROM [dbo].[Users] OUTPUT [deleted].[Id], [deleted].[Username], [deleted].[Password] WHERE [dbo].[Users].[Id] = @Id;", deleteQuery);
}
[Fact]
public void GenerateDeleteQuery_CompositePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CompositePrimaryKeyEntity>("dbo", "Users");
// Act
var deleteQuery = generator.GenerateDeleteQuery();
// Assert
Assert.Equal($"DELETE FROM [dbo].[Users] OUTPUT [deleted].[Username], [deleted].[Password], [deleted].[DateCreated] WHERE [dbo].[Users].[Username] = @Username AND [dbo].[Users].[Password] = @Password;", deleteQuery);
}
[Fact]
public void GenerateDeleteQuery_CustomColumnNames_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CustomColumnNamesEntity>("dbo", "Orders");
// Act
var deleteQuery = generator.GenerateDeleteQuery();
// Assert
Assert.Equal($"DELETE FROM [dbo].[Orders] OUTPUT [deleted].[OrderId] AS [Id], [deleted].[DateCreated] AS [Date] WHERE [dbo].[Orders].[OrderId] = @Id;", deleteQuery);
}
[Fact]
public void GenerateDeleteQuery_NoPrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<HeapEntity>("dbo", "Users");
// Act
var deleteQuery = generator.GenerateDeleteQuery();
// Assert
Assert.Equal($"DELETE FROM [dbo].[Users] OUTPUT [deleted].[Username], [deleted].[Password] WHERE [dbo].[Users].[Username] = @Username AND [dbo].[Users].[Password] = @Password;", deleteQuery);
}
#endregion
#region Insert
[Fact]
public void GenerateInsertQuery_CustomSchema_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<SinglePrimaryKeyEntity>("account", "Users");
// Act
var query = generator.GenerateInsertQuery(new SinglePrimaryKeyEntity());
// Assert
Assert.Equal("INSERT INTO [account].[Users] ([Username], [Password]) OUTPUT [inserted].[Id], [inserted].[Username], [inserted].[Password] VALUES (@Username, @Password);", query);
}
[Fact]
public void GenerateInsertQuery_ColumnHasDefaultConstraintAndDefaultValue_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<HasDefaultConstraintEntity>("dbo", "Users");
// Actj
var query = generator.GenerateInsertQuery(new HasDefaultConstraintEntity());
// Assert
Assert.Equal("INSERT INTO [dbo].[Users] ([Id]) OUTPUT [inserted].[Id], [inserted].[DateCreated] VALUES (@Id);", query);
}
[Fact]
public void GenerateInsertQuery_ColumnHasDefaultConstraintAndNonDefaultValue_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<HasDefaultConstraintEntity>("dbo", "Users");
var record = new HasDefaultConstraintEntity
{
Id = 42,
DateCreated = DateTime.Now
};
// Act
var query = generator.GenerateInsertQuery(record);
// Assert
Assert.Equal("INSERT INTO [dbo].[Users] ([Id], [DateCreated]) OUTPUT [inserted].[Id], [inserted].[DateCreated] VALUES (@Id, @DateCreated);", query);
}
[Fact]
public void GenerateInsertQuery_IdentityValuePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<SinglePrimaryKeyEntity>("dbo", "Users");
// Act
var insertQuery = generator.GenerateInsertQuery(new SinglePrimaryKeyEntity());
// Assert
Assert.Equal($"INSERT INTO [dbo].[Users] ([Username], [Password]) OUTPUT [inserted].[Id], [inserted].[Username], [inserted].[Password] VALUES (@Username, @Password);", insertQuery);
}
[Fact]
public void GenerateInsertQuery_MissingColumnValue_ContainsColumn()
{
// Arrange
var generator = new SqlQueryGenerator<CompositePrimaryKeyEntity>("dbo", "Users");
// Act
var insertQuery = generator.GenerateInsertQuery(new CompositePrimaryKeyEntity());
// Assert
Assert.Equal($"INSERT INTO [dbo].[Users] ([Username], [Password], [DateCreated]) OUTPUT [inserted].[Username], [inserted].[Password], [inserted].[DateCreated] VALUES (@Username, @Password, @DateCreated);", insertQuery);
}
[Fact]
public void GenerateInsertQuery_CompositePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CompositePrimaryKeyEntity>("dbo", "Users");
// Act
var insertQuery = generator.GenerateInsertQuery(new CompositePrimaryKeyEntity());
// Assert
Assert.Equal($"INSERT INTO [dbo].[Users] ([Username], [Password], [DateCreated]) OUTPUT [inserted].[Username], [inserted].[Password], [inserted].[DateCreated] VALUES (@Username, @Password, @DateCreated);", insertQuery);
}
[Fact]
public void GenerateInsertQuery_CustomColumnNames_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CustomColumnNamesEntity>("dbo", "Orders");
// Act
var insertQuery = generator.GenerateInsertQuery(new CustomColumnNamesEntity());
// Assert
Assert.Equal($"INSERT INTO [dbo].[Orders] ([DateCreated]) OUTPUT [inserted].[OrderId] AS [Id], [inserted].[DateCreated] AS [Date] VALUES (@Date);", insertQuery);
}
[Fact]
public void GenerateInsertQuery_NoPrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<HeapEntity>("dbo", "Users");
// Act
var insertQuery = generator.GenerateInsertQuery(new HeapEntity());
// Assert
Assert.Equal($"INSERT INTO [dbo].[Users] ([Username], [Password]) OUTPUT [inserted].[Username], [inserted].[Password] VALUES (@Username, @Password);", insertQuery);
}
#endregion
#region GetAll
[Fact]
public void GenerateGetAllQuery_ProperTableName_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<HeapEntity>("dbo", "Users");
// Act
var selectQuery = generator.GenerateGetAllQuery();
// Assert
Assert.Equal($"SELECT [dbo].[Users].[Username], [dbo].[Users].[Password] FROM [dbo].[Users];", selectQuery);
}
[Fact]
public void GenerateGetAllQuery_CustomColumnNames_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CustomColumnNamesEntity>("dbo", "Orders");
// Act
var selectQuery = generator.GenerateGetAllQuery();
// Assert
Assert.Equal($"SELECT [dbo].[Orders].[OrderId] AS [Id], [dbo].[Orders].[DateCreated] AS [Date] FROM [dbo].[Orders];", selectQuery);
}
#endregion
#region Get
[Fact]
public void GenerateGetQuery_SinglePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<SinglePrimaryKeyEntity>("dbo", "Users");
// Act
var selectQuery = generator.GenerateGetQuery();
// Assert
Assert.Equal($"SELECT [dbo].[Users].[Id], [dbo].[Users].[Username], [dbo].[Users].[Password] FROM [dbo].[Users] WHERE [dbo].[Users].[Id] = @Id;", selectQuery);
}
[Fact]
public void GenerateGetQuery_CompositePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CompositePrimaryKeyEntity>("dbo", "Users");
// Act
var selectQuery = generator.GenerateGetQuery();
// Assert
Assert.Equal($"SELECT [dbo].[Users].[Username], [dbo].[Users].[Password], [dbo].[Users].[DateCreated] FROM [dbo].[Users] WHERE [dbo].[Users].[Username] = @Username AND [dbo].[Users].[Password] = @Password;", selectQuery);
}
[Fact]
public void GenerateGetQuery_CustomColumnNames_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CustomColumnNamesEntity>("dbo", "Orders");
// Act
var selectQuery = generator.GenerateGetQuery();
// Assert
Assert.Equal($"SELECT [dbo].[Orders].[OrderId] AS [Id], [dbo].[Orders].[DateCreated] AS [Date] FROM [dbo].[Orders] WHERE [dbo].[Orders].[OrderId] = @Id;", selectQuery);
}
[Fact]
public void GenerateGetQuery_NoPrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<HeapEntity>("dbo", "Users");
// Act
var query = generator.GenerateGetQuery();
// Assert
Assert.Equal("SELECT [dbo].[Users].[Username], [dbo].[Users].[Password] FROM [dbo].[Users] WHERE [dbo].[Users].[Username] = @Username AND [dbo].[Users].[Password] = @Password;", query);
}
#endregion
#region Update
[Fact]
public void GenerateUpdateQuery_SinglePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<SinglePrimaryKeyEntity>("dbo", "Users");
// Act
var updateQuery = generator.GenerateUpdateQuery();
// Assert
Assert.Equal($"UPDATE [dbo].[Users] SET [dbo].[Users].[Username] = @Username, [dbo].[Users].[Password] = @Password OUTPUT [inserted].[Id], [inserted].[Username], [inserted].[Password] WHERE [dbo].[Users].[Id] = @Id;", updateQuery);
}
[Fact]
public void GenerateUpdateQuery_CompositePrimaryKey_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CompositePrimaryKeyEntity>("dbo", "Users");
// Act
var updateQuery = generator.GenerateUpdateQuery();
// Assert
Assert.Equal($"UPDATE [dbo].[Users] SET [dbo].[Users].[DateCreated] = @DateCreated OUTPUT [inserted].[Username], [inserted].[Password], [inserted].[DateCreated] WHERE [dbo].[Users].[Username] = @Username AND [dbo].[Users].[Password] = @Password;", updateQuery);
}
[Fact]
public void GenerateUpdateQuery_CustomColumnNames_Valid()
{
// Arrange
var generator = new SqlQueryGenerator<CustomColumnNamesEntity>("dbo", "Orders");
// Act
var updateQuery = generator.GenerateUpdateQuery();
// Assert
Assert.Equal($"UPDATE [dbo].[Orders] SET [dbo].[Orders].[DateCreated] = @Date OUTPUT [inserted].[OrderId] AS [Id], [inserted].[DateCreated] AS [Date] WHERE [dbo].[Orders].[OrderId] = @Id;", updateQuery);
}
[Fact]
public void GenerateUpdateQuery_NoPrimaryKey_Throws()
{
// Arrange
var generator = new SqlQueryGenerator<HeapEntity>("dbo", "Users");
// Act && Assert
Assert.Throws<InvalidOperationException>(() => generator.GenerateUpdateQuery());
}
[Fact]
public void GenerateUpdateQuery_AllColumnsHasNoSetter_Throws()
{
// Arrange
var generator = new SqlQueryGenerator<AllColumnsHasMissingSetterEntity>("dbo", "Users");
// Act && Assert
Assert.Throws<InvalidOperationException>(() => generator.GenerateUpdateQuery());
}
[Fact]
public void GenerateUpdateQuery_ColumnHasNoSetter_ColumnIsExcluded()
{
// Arrange
var generator = new SqlQueryGenerator<ColumnHasMissingSetterEntity>("dbo", "Users");
// Act
var query = generator.GenerateUpdateQuery();
// Assert
Assert.Equal("UPDATE [dbo].[Users] SET [dbo].[Users].[Age] = @Age OUTPUT [inserted].[Id], [inserted].[Age], [inserted].[DateCreated] WHERE [dbo].[Users].[Id] = @Id;", query);
}
#endregion
}
}
| 31.854497 | 264 | 0.690973 | [
"MIT"
] | NQbbe/Ckode.Dapper.Repository | Tests/Ckode.Dapper.Repository.UnitTests/Sql/SqlQueryGeneratorTests.cs | 12,041 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using ATBase.Validation;
using Newtonsoft.Json;
namespace CPI.Common.Domain.SettleDomain.Bill99.v1_0
{
/// <summary>
/// 个人账户提现绑卡请求类
/// </summary>
public class PersonalWithdrawBindCardRequestV1 : ValidateModel
{
/// <summary>
/// 分配给接入平台Id,必填
/// </summary>
[Required(ErrorMessage = "AppId字段必需")]
public String AppId { get; set; }
/// <summary>
/// 收款人Id,必填
/// </summary>
[Required(ErrorMessage = "UserId字段必需")]
public String UserId { get; set; }
/// <summary>
///
/// </summary>
[Required(ErrorMessage = "ApplyToken字段必需")]
public String ApplyToken { get; set; }
/// <summary>
/// 短信验证码,必填
/// </summary>
[Required(ErrorMessage = "SmsValidCode字段必需")]
public String SmsValidCode { get; set; }
/// <summary>
/// 银行名称,必填
/// </summary>
[Required(ErrorMessage = "BankName字段必需")]
public String BankName { get; set; }
/// <summary>
/// 银行卡号,必填
/// </summary>
[Required(ErrorMessage = "BankCardNo字段必需")]
public String BankCardNo { get; set; }
/// <summary>
/// 证件号码,必填
/// </summary>
[Required(ErrorMessage = "IDCardNo字段必需")]
public String IDCardNo { get; set; }
/// <summary>
/// 证件类型,必填
/// </summary>
[Required(ErrorMessage = "IDCardType字段必需")]
public String IDCardType { get; set; }
/// <summary>
/// 银行预留手机号,必填
/// </summary>
[Required(ErrorMessage = "Mobile字段必需")]
public String Mobile { get; set; }
/// <summary>
/// 真实姓名,必填
/// </summary>
[Required(ErrorMessage = "RealName字段必需")]
public String RealName { get; set; }
}
}
| 25.960526 | 66 | 0.533705 | [
"Apache-2.0"
] | SZarrow/CPI | src/CPI.Common/Domain/SettleDomain/Bill99/v1_0/PersonalWithdrawBindCardRequestV1.cs | 2,215 | C# |
// Copyright (c) 2019 Lykke Corp.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
namespace MarginTrading.AssetService.Core.Services
{
public interface ICqrsMessageSender
{
Task SendEvent<TEvent>(TEvent @event);
}
} | 23.75 | 65 | 0.729825 | [
"MIT-0"
] | LykkeBusiness/MarginTrading.AssetService | src/MarginTrading.AssetService.Core/Services/ICqrsMessageSender.cs | 285 | C# |
// generated cpptypeinfo-0.2.0
using System;
using System.Runtime.InteropServices;
using System.Numerics;
namespace SharpImGui
{
public struct ImGuiIO
{
public static implicit operator ImGuiIO(IntPtr p)
{
return new ImGuiIO(p);
}
readonly IntPtr m_p;
public ImGuiIO(IntPtr ptr)
{
m_p = ptr;
}
// offsetof: 0
public ImGuiConfigFlags ConfigFlags
{
get => (ImGuiConfigFlags)(Marshal.ReadInt32(IntPtr.Add(m_p, 0)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 0), (int)value);
}
// offsetof: 4
public ImGuiBackendFlags BackendFlags
{
get => (ImGuiBackendFlags)(Marshal.ReadInt32(IntPtr.Add(m_p, 4)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 4), (int)value);
}
// offsetof: 16
public float DeltaTime
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 16)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 16), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 20
public float IniSavingRate
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 20)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 20), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 24
public IntPtr IniFilename
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 24)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 24), value.ToInt64());
}
// offsetof: 32
public IntPtr LogFilename
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 32)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 32), value.ToInt64());
}
// offsetof: 40
public float MouseDoubleClickTime
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 40)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 40), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 44
public float MouseDoubleClickMaxDist
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 44)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 44), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 48
public float MouseDragThreshold
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 48)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 48), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 52
public IntPtr KeyMap
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 52)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 52), value.ToInt64());
}
// offsetof: 140
public float KeyRepeatDelay
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 140)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 140), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 144
public float KeyRepeatRate
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 144)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 144), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 152
public IntPtr UserData
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 152)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 152), value.ToInt64());
}
// offsetof: 160
public IntPtr Fonts
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 160)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 160), value.ToInt64());
}
// offsetof: 168
public float FontGlobalScale
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 168)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 168), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 176
public IntPtr FontDefault
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 176)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 176), value.ToInt64());
}
// offsetof: 208
public float ConfigWindowsMemoryCompactTimer
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 208)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 208), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 216
public IntPtr BackendPlatformName
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 216)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 216), value.ToInt64());
}
// offsetof: 224
public IntPtr BackendRendererName
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 224)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 224), value.ToInt64());
}
// offsetof: 232
public IntPtr BackendPlatformUserData
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 232)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 232), value.ToInt64());
}
// offsetof: 240
public IntPtr BackendRendererUserData
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 240)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 240), value.ToInt64());
}
// offsetof: 248
public IntPtr BackendLanguageUserData
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 248)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 248), value.ToInt64());
}
// offsetof: 272
public IntPtr ClipboardUserData
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 272)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 272), value.ToInt64());
}
// offsetof: 296
public IntPtr MouseDown
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 296)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 296), value.ToInt64());
}
// offsetof: 304
public float MouseWheel
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 304)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 304), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 308
public float MouseWheelH
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 308)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 308), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 320
public IntPtr KeysDown
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 320)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 320), value.ToInt64());
}
// offsetof: 832
public IntPtr NavInputs
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 832)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 832), value.ToInt64());
}
// offsetof: 928
public float Framerate
{
get => BitConverter.Int32BitsToSingle(Marshal.ReadInt32(IntPtr.Add(m_p, 928)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 928), BitConverter.SingleToInt32Bits(value));
}
// offsetof: 932
public int MetricsRenderVertices
{
get => (Marshal.ReadInt32(IntPtr.Add(m_p, 932)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 932), value);
}
// offsetof: 936
public int MetricsRenderIndices
{
get => (Marshal.ReadInt32(IntPtr.Add(m_p, 936)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 936), value);
}
// offsetof: 940
public int MetricsRenderWindows
{
get => (Marshal.ReadInt32(IntPtr.Add(m_p, 940)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 940), value);
}
// offsetof: 944
public int MetricsActiveWindows
{
get => (Marshal.ReadInt32(IntPtr.Add(m_p, 944)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 944), value);
}
// offsetof: 948
public int MetricsActiveAllocations
{
get => (Marshal.ReadInt32(IntPtr.Add(m_p, 948)));
set => Marshal.WriteInt32(IntPtr.Add(m_p, 948), value);
}
// offsetof: 968
public IntPtr MouseClickedPos
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 968)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 968), value.ToInt64());
}
// offsetof: 1008
public IntPtr MouseClickedTime
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1008)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1008), value.ToInt64());
}
// offsetof: 1048
public IntPtr MouseClicked
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1048)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1048), value.ToInt64());
}
// offsetof: 1053
public IntPtr MouseDoubleClicked
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1053)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1053), value.ToInt64());
}
// offsetof: 1058
public IntPtr MouseReleased
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1058)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1058), value.ToInt64());
}
// offsetof: 1063
public IntPtr MouseDownOwned
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1063)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1063), value.ToInt64());
}
// offsetof: 1068
public IntPtr MouseDownWasDoubleClick
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1068)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1068), value.ToInt64());
}
// offsetof: 1076
public IntPtr MouseDownDuration
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1076)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1076), value.ToInt64());
}
// offsetof: 1096
public IntPtr MouseDownDurationPrev
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1096)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1096), value.ToInt64());
}
// offsetof: 1116
public IntPtr MouseDragMaxDistanceAbs
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1116)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1116), value.ToInt64());
}
// offsetof: 1156
public IntPtr MouseDragMaxDistanceSqr
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1156)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1156), value.ToInt64());
}
// offsetof: 1176
public IntPtr KeysDownDuration
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 1176)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 1176), value.ToInt64());
}
// offsetof: 3224
public IntPtr KeysDownDurationPrev
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 3224)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 3224), value.ToInt64());
}
// offsetof: 5272
public IntPtr NavInputsDownDuration
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 5272)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 5272), value.ToInt64());
}
// offsetof: 5360
public IntPtr NavInputsDownDurationPrev
{
get => new IntPtr(Marshal.ReadInt64(IntPtr.Add(m_p, 5360)));
set => Marshal.WriteInt64(IntPtr.Add(m_p, 5360), value.ToInt64());
}
}
} | 39.728707 | 100 | 0.554947 | [
"MIT"
] | ousttrue/SharpImGui | sample/SharpImGui/ImGuiIO.cs | 12,594 | C# |
namespace TeaTime.Common.Exceptions
{
using System;
public class TeaTimeException : Exception
{
public TeaTimeException(string message ) : base(message)
{
}
}
}
| 16.916667 | 64 | 0.615764 | [
"MIT"
] | MrSmoke/TeaTime | src/TeaTime.Common/Exceptions/TeaTimeException.cs | 205 | C# |
using System.Collections.Generic;
using System.Linq;
using GenHTTP.Api.Content;
using GenHTTP.Api.Protocol;
using GenHTTP.Modules.Basics;
using GenHTTP.Modules.Controllers;
using $safeprojectname$.Model;
namespace $safeprojectname$.Controllers
{
public class BookController : AbstractController
{
private static readonly List<Book> _Books = new()
{
new Book(1, "Lord of The Rings")
};
public IHandlerBuilder Index()
{
return View("BookList.html", "Book List", _Books);
}
public IHandlerBuilder Create()
{
return View("BookCreation.html", "Add Book");
}
[ControllerAction(RequestMethod.POST)]
public IHandlerBuilder Create(string title)
{
var book = new Book(_Books.Max(b => b.ID) + 1, title);
_Books.Add(book);
return Redirect.To("{index}/", true);
}
public IHandlerBuilder Edit([FromPath] int id)
{
var book = _Books.Where(b => b.ID == id).First();
return View("BookEditor.html", book.Title, book);
}
[ControllerAction(RequestMethod.POST)]
public IHandlerBuilder Edit([FromPath] int id, string title)
{
var book = _Books.Where(b => b.ID == id).First();
var index = _Books.IndexOf(book);
_Books[index] = book with { Title = title };
return Redirect.To("{index}/", true);
}
[ControllerAction(RequestMethod.POST)]
public IHandlerBuilder Delete([FromPath] int id)
{
_Books.RemoveAll(b => b.ID == id);
return Redirect.To("{index}/", true);
}
}
}
| 25.408451 | 69 | 0.545455 | [
"MIT"
] | Kaliumhexacyanoferrat/GenHTTP.Templates | Templates/Website-MVC-Scriban/$safeprojectname$/Controllers/BookController.cs | 1,806 | C# |
/*----------------------------------------------------------------
Copyright (C) 2015 Senparc
文件名:ShelfApi.cs
文件功能描述:微小店货架接口
创建标识:Senparc - 20150827
----------------------------------------------------------------*/
/*
微小店接口,官方API:http://mp.weixin.qq.com/wiki/index.php?title=%E5%BE%AE%E4%BF%A1%E5%B0%8F%E5%BA%97%E6%8E%A5%E5%8F%A3
*/
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP.CommonAPIs;
namespace Senparc.Weixin.MP.AdvancedAPIs.MerChant
{
/// <summary>
/// 微小店货架接口
/// </summary>
public static class ShelfApi
{
/// <summary>
/// 增加货架
/// </summary>
/// <param name="accessToken"></param>
/// <param name="m1">控件1数据</param>
/// <param name="m2">控件2数据</param>
/// <param name="m3">控件3数据</param>
/// <param name="m4">控件4数据</param>
/// <param name="m5">控件5数据</param>
/// <param name="shelfBanner">货架招牌图片Url</param>
/// <param name="shelfName">货架名称</param>
/// <returns></returns>
public static AddShelfResult AddShelves(string accessToken, M1 m1, M2 m2, M3 m3, M4 m4, M5 m5,
string shelfBanner, string shelfName)
{
var urlFormat = "https://api.weixin.qq.com/merchant/shelf/add?access_token={0}";
var data = new
{
shelf_data = new
{
module_infos = new object[]
{
m1,
m2,
m3,
m4,
m5
}
},
shelf_banner = shelfBanner,
shelf_name = shelfName
};
return CommonJsonSend.Send<AddShelfResult>(accessToken, urlFormat, data);
}
/// <summary>
/// 删除货架
/// </summary>
/// <param name="accessToken"></param>
/// <param name="shelfId">货架Id</param>
/// <returns></returns>
public static WxJsonResult DeleteShelves(string accessToken, int shelfId)
{
var urlFormat = "https://api.weixin.qq.com/merchant/shelf/del?access_token={0}";
var data = new
{
shelf_id = shelfId
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data);
}
/// <summary>
/// 修改货架
/// </summary>
/// <param name="accessToken"></param>
/// <param name="m1">控件1数据</param>
/// <param name="m2">控件2数据</param>
/// <param name="m3">控件3数据</param>
/// <param name="m4">控件4数据</param>
/// <param name="m5">控件5数据</param>
/// <param name="shelfId">货架Id</param>
/// <param name="shelfBanner">货架招牌图片Url</param>
/// <param name="shelfName">货架名称</param>
/// <returns></returns>
public static WxJsonResult ModShelves(string accessToken, M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, int shelfId,
string shelfBanner, string shelfName)
{
var urlFormat = "https://api.weixin.qq.com/merchant/shelf/mod?access_token={0}";
var data = new
{
shelf_id = shelfId,
shelf_data = new
{
module_infos = new object[]
{
m1,
m2,
m3,
m4,
m5
}
},
shelf_banner = shelfBanner,
shelf_name = shelfName
};
return CommonJsonSend.Send<WxJsonResult>(accessToken, urlFormat, data);
}
/// <summary>
/// 获取所有货架
/// </summary>
/// <param name="accessToken"></param>
/// <returns></returns>
public static GetAllShelfResult GetAllShelves(string accessToken)
{
var urlFormat = "https://api.weixin.qq.com/merchant/shelf/getall?access_token=ACCESS_TOKEN";
return CommonJsonSend.Send<GetAllShelfResult>(accessToken, urlFormat, null, CommonJsonSendType.GET);
}
/// <summary>
/// 根据货架ID获取货架信息
/// </summary>
/// <param name="accessToken"></param>
/// <param name="shelfId">货架Id</param>
/// <returns></returns>
public static GetByIdShelfResult GetByIdShelves(string accessToken, int shelfId)
{
var urlFormat = "https://api.weixin.qq.com/merchant/shelf/getbyid?access_token={0}";
var data = new
{
shelf_id = shelfId
};
return CommonJsonSend.Send<GetByIdShelfResult>(accessToken, urlFormat, data);
}
}
} | 32.362416 | 114 | 0.480091 | [
"MIT"
] | timxing1987/git-tutorial | Source/Foundation/Wechat/Senparc.Weixin.MP/AdvancedAPIs/MerChant/Shelf/ShelfApi.cs | 5,090 | C# |
using Microsoft.AspNetCore.Mvc;
namespace Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Themes.Basic.Components.MainNavbar;
public class MainNavbarViewComponent : AbpViewComponent
{
public virtual IViewComponentResult Invoke()
{
return View("~/Themes/Basic/Components/MainNavbar/Default.cshtml");
}
}
| 26.416667 | 84 | 0.763407 | [
"Apache-2.0"
] | daridakr/ProgGuru | modules/Volo.BasicTheme/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic/Themes/Basic/Components/MainNavbar/MainNavbarViewComponent.cs | 319 | 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 elasticbeanstalk-2010-12-01.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.ElasticBeanstalk.Model
{
/// <summary>
/// Empty class reserved for future use.
/// </summary>
public partial class RebuildEnvironmentResponse : AmazonWebServiceResponse
{
}
} | 29.702703 | 114 | 0.734304 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/ElasticBeanstalk/Generated/Model/RebuildEnvironmentResponse.cs | 1,099 | C# |
using System;
using System.Diagnostics;
using System.Reflection;
using Godot;
using Sigil;
namespace GDMechanic.Wiring.CachedNodeInfos
{
/// <summary>
/// Wrapper for a cached node-related FieldInfo or PropertyInfo.
/// </summary>
public class CachedNodeStateInfo : CachedNodeMemberInfo
{
/// <summary>
/// The original FieldInfo or PropertyInfo that has been cached.
/// </summary>
public MemberInfo State { get; }
public Type StateType { get; }
private readonly Func<Node, object> _getValue;
private readonly Action<Node, object> _setValue;
public CachedNodeStateInfo(MemberInfo state, CachedNodeType declaringType) : base(state, declaringType)
{
State = state;
switch (state)
{
case FieldInfo field:
StateType = field.FieldType;
break;
case PropertyInfo property:
StateType = property.PropertyType;
break;
}
_getValue = CreateGetter();
_setValue = CreateSetter();
}
public object GetValue(Node node)
{
if (_getValue != null)
{
return _getValue(node);
}
switch (State)
{
case FieldInfo field:
return field.GetValue(node);
case PropertyInfo property:
return property.GetValue(node);
}
return null;
}
public void SetValue(Node node, object value)
{
if (_setValue != null)
{
_setValue(node, value);
}
else
{
switch (State)
{
case FieldInfo field:
field.SetValue(node, value);
break;
case PropertyInfo property:
property.SetValue(node, value);
break;
}
}
}
private Func<Node, object> CreateGetter()
{
Emit<Func<Node, object>> getterMethod;
Debug.Assert(State.ReflectedType != null, "state.ReflectedType != null");
string methodName = State.ReflectedType.FullName+".get_" + Name;
switch (State)
{
case FieldInfo field:
if (field.FieldType.GetTypeInfo().IsValueType)
{
// Code emission doesn't work on primitives.
return null;
}
else
{
getterMethod = Emit<Func<Node, object>>
.NewDynamicMethod(methodName)
.LoadArgument(0)
.CastClass(DeclaringType.Type)
.LoadField(field)
.Return();
}
break;
case PropertyInfo property:
if (property.PropertyType.GetTypeInfo().IsValueType
|| property.GetGetMethod(true) == null)
{
// Code emission doesn't work on primitives.
return null;
}
else
{
getterMethod = Emit<Func<Node, object>>
.NewDynamicMethod(methodName)
.LoadArgument(0)
.CastClass(DeclaringType.Type)
.Call(property.GetGetMethod(true))
.Return();
}
break;
default: throw new ArgumentException("MemberInfo must be either a FieldInfo or a PropertyInfo.");
}
return getterMethod.CreateDelegate();
}
private Action<Node, object> CreateSetter()
{
Emit<Action<Node, object>> setterMethod;
Debug.Assert(State.ReflectedType != null, "state.ReflectedType != null");
string methodName = State.ReflectedType.FullName+".set_" + Name;
switch (State)
{
case FieldInfo field:
if (field.FieldType.GetTypeInfo().IsValueType)
{
// Code emission doesn't work on primitives.
return null;
}
else
{
setterMethod = Emit<Action<Node, object>>
.NewDynamicMethod(methodName)
.LoadArgument(0)
.CastClass(DeclaringType.Type)
.LoadArgument(1)
.CastClass(field.FieldType)
.StoreField(field)
.Return();
}
break;
case PropertyInfo property:
if (property.PropertyType.GetTypeInfo().IsValueType
|| property.GetSetMethod(true) == null)
{
// Code emission doesn't work on primitives.
return null;
}
else
{
setterMethod = Emit<Action<Node, object>>
.NewDynamicMethod(methodName)
.LoadArgument(0)
.CastClass(DeclaringType.Type)
.LoadArgument(1)
.CastClass(property.PropertyType)
.Call(property.GetSetMethod(true))
.Return();
}
break;
default: throw new ArgumentException("MemberInfo must be either a FieldInfo or a PropertyInfo.");
}
return setterMethod.CreateDelegate();
}
}
} | 23.291209 | 105 | 0.63765 | [
"MIT"
] | 11clock/GDMechanic | GDMechanic/Wiring/CachedNodeInfos/CachedNodeStateInfo.cs | 4,241 | C# |
using System;
namespace Trowel.Providers
{
public class ProviderException : Exception
{
public ProviderException(string message, Exception innerException) : base(message, innerException)
{
}
public ProviderException()
{
}
public ProviderException(string message) : base(message)
{
}
}
}
| 18.75 | 106 | 0.602667 | [
"BSD-3-Clause"
] | mattiascibien/trowel | Trowel.Providers/ProviderException.cs | 377 | C# |
namespace Ordering.Application.Models
{
public class EmailSettings
{
public string ApiKey { get; set; }
public string FromAddress { get; set; }
public string FromName { get; set; }
}
} | 24.777778 | 47 | 0.61435 | [
"MIT"
] | kosmur/AspnetMicroservices | src/Services/Ordering/Ordering.Application/Models/EmailSettings.cs | 223 | C# |
// Copyright 2020 Energinet DataHub A/S
//
// Licensed under the Apache License, Version 2.0 (the "License2");
// 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 Energinet.DataHub.MeteringPoints.Infrastructure.Integration.IntegrationEvents.CreateMeteringPoint.Consumption
{
public record ConsumptionMeteringPointCreatedTopic(string Name) : Topic;
}
| 42.210526 | 119 | 0.775561 | [
"Apache-2.0"
] | Energinet-DataHub/geh-metering-point | source/Energinet.DataHub.MeteringPoints.Infrastructure/Integration/IntegrationEvents/CreateMeteringPoint/Consumption/ConsumptionMeteringPointCreatedTopic.cs | 804 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
public static class Languages
{
public static List<string> NewList() => new();
public static List<string> GetExistingLanguages()
=> new() {"C#", "Clojure", "Elm"};
public static List<string> AddLanguage(List<string> languages, string language)
=> languages.Concat(new[] { language }).ToList();
public static int CountLanguages(List<string> languages) => languages.Count;
public static bool HasLanguage(List<string> languages, string language)
=> languages.Contains(language);
public static List<string> ReverseList(List<string> languages)
=> languages.Select(language => language).Reverse().ToList();
public static bool IsExciting(List<string> languages)
=> (languages.FirstOrDefault() == "C#") || ((languages.Count is 2 or 3) && languages[1] == "C#");
public static List<string> RemoveLanguage(List<string> languages, string language)
=> languages.Select(element => element).Where(element => element != language).ToList();
public static bool IsUnique(List<string> languages)
{
foreach (var language in languages)
{
var occurrences = languages.Count(element => element == language);
if (occurrences > 1) return false;
}
return true;
}
}
| 35 | 105 | 0.657875 | [
"MIT"
] | victorh1590/exercism-csharp-track-solutions | tracks-on-tracks-on-tracks/TracksOnTracksOnTracks.cs | 1,365 | C# |
using System;
using NAudio.Wave;
namespace NAudioDemo.NetworkChatDemo
{
public interface INetworkChatCodec : IDisposable
{
/// <summary>
/// Friendly Name for this codec
/// </summary>
string Name { get; }
/// <summary>
/// Tests whether the codec is available on this system
/// </summary>
bool IsAvailable { get; }
/// <summary>
/// Bitrate
/// </summary>
int BitsPerSecond { get; }
/// <summary>
/// Preferred PCM format for recording in (usually 8kHz mono 16 bit)
/// </summary>
WaveFormat RecordFormat { get; }
/// <summary>
/// Encodes a block of audio
/// </summary>
byte[] Encode(byte[] data, int offset, int length);
/// <summary>
/// Decodes a block of audio
/// </summary>
byte[] Decode(byte[] data, int offset, int length);
}
}
| 28.794118 | 77 | 0.510725 | [
"MIT"
] | ArisAgnew/NAudio | NAudioDemo/NetworkChatDemo/INetworkChatCodec.cs | 981 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using ModernMarketTM.Models;
namespace ModernMarketTM.Web.Areas.Identity.Pages.Account.Manage
{
public class PersonalDataModel : PageModel
{
private readonly UserManager<User> _userManager;
private readonly ILogger<PersonalDataModel> _logger;
public PersonalDataModel(
UserManager<User> userManager,
ILogger<PersonalDataModel> logger)
{
_userManager = userManager;
_logger = logger;
}
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Не можахме да намерим потребител с номер '{_userManager.GetUserId(User)}'.");
}
return Page();
}
}
} | 29.382353 | 111 | 0.640641 | [
"MIT"
] | vesopk/ModernMarketTM | ModernMarketTM.Web/Areas/Identity/Pages/Account/Manage/PersonalData.cshtml.cs | 1,035 | 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 customer-profiles-2020-08-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CustomerProfiles.Model
{
/// <summary>
/// This is the response object from the GetDomain operation.
/// </summary>
public partial class GetDomainResponse : AmazonWebServiceResponse
{
private DateTime? _createdAt;
private string _deadLetterQueueUrl;
private string _defaultEncryptionKey;
private int? _defaultExpirationDays;
private string _domainName;
private DateTime? _lastUpdatedAt;
private DomainStats _stats;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property CreatedAt.
/// <para>
/// The timestamp of when the domain was created.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public DateTime CreatedAt
{
get { return this._createdAt.GetValueOrDefault(); }
set { this._createdAt = value; }
}
// Check to see if CreatedAt property is set
internal bool IsSetCreatedAt()
{
return this._createdAt.HasValue;
}
/// <summary>
/// Gets and sets the property DeadLetterQueueUrl.
/// <para>
/// The URL of the SQS dead letter queue, which is used for reporting errors associated
/// with ingesting data from third party applications.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=255)]
public string DeadLetterQueueUrl
{
get { return this._deadLetterQueueUrl; }
set { this._deadLetterQueueUrl = value; }
}
// Check to see if DeadLetterQueueUrl property is set
internal bool IsSetDeadLetterQueueUrl()
{
return this._deadLetterQueueUrl != null;
}
/// <summary>
/// Gets and sets the property DefaultEncryptionKey.
/// <para>
/// The default encryption key, which is an AWS managed key, is used when no specific
/// type of encryption key is specified. It is used to encrypt all data before it is placed
/// in permanent or semi-permanent storage.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=255)]
public string DefaultEncryptionKey
{
get { return this._defaultEncryptionKey; }
set { this._defaultEncryptionKey = value; }
}
// Check to see if DefaultEncryptionKey property is set
internal bool IsSetDefaultEncryptionKey()
{
return this._defaultEncryptionKey != null;
}
/// <summary>
/// Gets and sets the property DefaultExpirationDays.
/// <para>
/// The default number of days until the data within the domain expires.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1098)]
public int DefaultExpirationDays
{
get { return this._defaultExpirationDays.GetValueOrDefault(); }
set { this._defaultExpirationDays = value; }
}
// Check to see if DefaultExpirationDays property is set
internal bool IsSetDefaultExpirationDays()
{
return this._defaultExpirationDays.HasValue;
}
/// <summary>
/// Gets and sets the property DomainName.
/// <para>
/// The unique name of the domain.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=64)]
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedAt.
/// <para>
/// The timestamp of when the domain was most recently edited.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public DateTime LastUpdatedAt
{
get { return this._lastUpdatedAt.GetValueOrDefault(); }
set { this._lastUpdatedAt = value; }
}
// Check to see if LastUpdatedAt property is set
internal bool IsSetLastUpdatedAt()
{
return this._lastUpdatedAt.HasValue;
}
/// <summary>
/// Gets and sets the property Stats.
/// <para>
/// Usage-specific statistics about the domain.
/// </para>
/// </summary>
public DomainStats Stats
{
get { return this._stats; }
set { this._stats = value; }
}
// Check to see if Stats property is set
internal bool IsSetStats()
{
return this._stats != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// The tags used to organize, track, or control access for this resource.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=50)]
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 32.755 | 116 | 0.564799 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/CustomerProfiles/Generated/Model/GetDomainResponse.cs | 6,551 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VU_BYTE = System.Byte;
using VU_TIME = System.UInt64;
using VU_BOOL = System.Boolean;
using BIG_SCALAR = System.Single;
using SM_SCALAR = System.Single;
namespace FalconNet.VU
{
public class VuDriverSettings
{
public VuDriverSettings(SM_SCALAR x, SM_SCALAR y, SM_SCALAR z,
#if VU_USE_QUATERNION
SM_SCALAR quatDist,
#else // !VU_USE_QUATERNION
SM_SCALAR yaw, SM_SCALAR pitch, SM_SCALAR roll,
#endif
SM_SCALAR maxJumpDist, SM_SCALAR maxJumpAngle,
VU_TIME lookaheadTime
#if VU_QUEUE_DR_UPDATES
, VuFilter *filter = 0
#endif
) { throw new NotImplementedException(); }
//TODO public ~VuDriverSettings();
public SM_SCALAR xtol_, ytol_, ztol_; // fine tolerance values
#if VU_USE_QUATERNION
SM_SCALAR quattol_;
#else // !VU_USE_QUATERNION
public SM_SCALAR yawtol_, pitchtol_, rolltol_;
#endif
public SM_SCALAR maxJumpDist_;
public SM_SCALAR maxJumpAngle_;
public SM_SCALAR globalPosTolMod_;
public SM_SCALAR globalAngleTolMod_;
public VU_TIME lookaheadTime_;
#if VU_QUEUE_DR_UPDATES
public VuFifoQueue *updateQueue_;
public VuFifoQueue *roughUpdateQueue_;
#endif
}
//-----------------------------------------
public abstract class VuDriver
{
//TODO public virtual ~VuDriver();
public abstract int Type();
public abstract void NoExec(VU_TIME timestamp);
public abstract void Exec(VU_TIME timestamp);
public abstract void AutoExec(VU_TIME timestamp);
public abstract VU_ERRCODE Handle(VuEvent evnt);
public abstract VU_ERRCODE Handle(VuFullUpdateEvent evnt);
public abstract VU_ERRCODE Handle(VuPositionUpdateEvent evnt);
public abstract void AlignTimeAdd(VU_TIME timeDelta);
public abstract void AlignTimeSubtract(VU_TIME timeDelta);
public abstract void ResetLastUpdateTime(VU_TIME time);
// Accessor
public VuEntity Entity() { return entity_; }
// AI hooks
public virtual int AiType() // returns 0 if no AI is present
{ throw new NotImplementedException(); }
public virtual VU_BOOL AiExec() // executes Ai component
{ throw new NotImplementedException(); }
public virtual Object AiPointer() // returns pointer to Ai data (game specific)
{ throw new NotImplementedException(); }
// debug hooks
public virtual int DebugString(string str) { throw new NotImplementedException(); }
protected VuDriver(VuEntity entity) { throw new NotImplementedException(); }
// Data
protected VuEntity entity_;
}
//-----------------------------------------
public abstract class VuDeadReckon : VuDriver
{
public VuDeadReckon(VuEntity entity):base(entity) { throw new NotImplementedException(); }
//TODO public virtual ~VuDeadReckon();
//public abstract int Type() { throw new NotImplementedException(); }
//public abstract VU_ERRCODE Handle(VuEvent evnt) { throw new NotImplementedException(); }
//public abstract VU_ERRCODE Handle(VuFullUpdateEvent evnt) { throw new NotImplementedException(); }
//public abstract VU_ERRCODE Handle(VuPositionUpdateEvent evnt) { throw new NotImplementedException(); }
public override void AlignTimeAdd(VU_TIME timeDelta) { throw new NotImplementedException(); }
public override void AlignTimeSubtract(VU_TIME timeDelta) { throw new NotImplementedException(); }
public override void ResetLastUpdateTime(VU_TIME time) { throw new NotImplementedException(); }
public override void NoExec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override void Exec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override void AutoExec(VU_TIME timestamp) { throw new NotImplementedException(); }
public virtual void ExecDR(VU_TIME timestamp) { throw new NotImplementedException(); }
// DATA
// dead reckoning
protected BIG_SCALAR drx_, dry_, drz_;
protected SM_SCALAR drxdelta_, drydelta_, drzdelta_;
#if VU_USE_QUATERNION
protected VU_QUAT drquat_; // quaternion indicating current facing
protected VU_VECT drquatdelta_; // unit vector expressing quaternion delta
protected SM_SCALAR drtheta_; // scalar indicating rate of above delta
#else // !VU_USE_QUATERNION
protected SM_SCALAR dryaw_, drpitch_, drroll_;
//SM_SCALAR dryawdelta_, drpitchdelta_, drrolldelta_;
#endif
protected VU_TIME lastUpdateTime_;
}
//-----------------------------------------
public abstract class VuMaster : VuDeadReckon
{
public VuMaster(VuEntity entity) : base(entity){ throw new NotImplementedException(); }
//TODO public virtual ~VuMaster();
public override int Type() { throw new NotImplementedException(); }
public override void NoExec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override void Exec(VU_TIME timestamp) { throw new NotImplementedException(); }
public int CheckTolerance() { throw new NotImplementedException(); }
public SM_SCALAR CalcError() { throw new NotImplementedException(); }
public SM_SCALAR CheckForceUpd(VuSessionEntity session)//me123 010115
{ throw new NotImplementedException(); }
public VU_TIME lastFinePositionUpdateTime() { return lastFinePositionUpdateTime_; }
public void SetpendingUpdate(VU_BOOL pendingUpdate) { pendingUpdate_ = pendingUpdate; }//me123
public void SetpendingRoughUpdate(VU_BOOL pendingRoughUpdate) { pendingRoughUpdate_ = pendingRoughUpdate; }//me123
public void UpdateDrdata(VU_BOOL registrer)//me123
{ throw new NotImplementedException(); }
public void SetRoughPosTolerance(SM_SCALAR x, SM_SCALAR y, SM_SCALAR z) { throw new NotImplementedException(); }
public void SetPosTolerance(SM_SCALAR x, SM_SCALAR y, SM_SCALAR z) { throw new NotImplementedException(); }
#if VU_USE_QUATERNION
public void SetQuatTolerance(SM_SCALAR tol);
#else // !VU_USE_QUATERNION
public void SetRotTolerance(SM_SCALAR yaw, SM_SCALAR pitch, SM_SCALAR roll) { throw new NotImplementedException(); }
#endif
// ExecModel must update Pos, YPR & deltas
// returns whether model was run
public abstract VU_BOOL ExecModel(VU_TIME timestamp);
public void ExecModelWithDR() { throw new NotImplementedException(); }
public override VU_ERRCODE Handle(VuEvent evnt) { throw new NotImplementedException(); }
public override VU_ERRCODE Handle(VuFullUpdateEvent evnt) { throw new NotImplementedException(); }
public override VU_ERRCODE Handle(VuPositionUpdateEvent evnt) { throw new NotImplementedException(); }
public virtual VU_ERRCODE GeneratePositionUpdate(int oob, VU_TIME timestamp, VU_BOOL registrer, VuTargetEntity target) { throw new NotImplementedException(); }
// debug hooks
public override int DebugString(string str) { throw new NotImplementedException(); }
// DATA
protected VU_TIME lastPositionUpdateTime_;
protected VU_TIME lastFinePositionUpdateTime_;
// dead reckoning tolerances
protected VU_BOOL pendingUpdate_;
protected VU_BOOL pendingRoughUpdate_;
protected BIG_SCALAR xtol_, ytol_, ztol_;
#if VU_USE_QUATERNION
protected SM_SCALAR quattol_;
#else // !VU_USE_QUATERNION
protected SM_SCALAR yawtol_, pitchtol_, rolltol_;
#endif
}
//-----------------------------------------
public class VuSlave : VuDeadReckon
{
protected enum DeadReckonMode
{
ROUGH,
TRANSITION,
FINE,
}
public VU_TIME lastPositionUpdateTime_;
public VU_TIME lastFinePositionUpdateTime_;
public VU_BOOL pendingUpdate_;
public VU_BOOL pendingRoughUpdate_;
public int CheckTolerance() { throw new NotImplementedException(); }
public VU_TIME lastFinePositionUpdateTime() { return lastFinePositionUpdateTime_; }
public SM_SCALAR CheckForceUpd(VuSessionEntity sess)//me123 010115
{ throw new NotImplementedException(); }
public SM_SCALAR CalcError() { throw new NotImplementedException(); }
public void SetpendingUpdate(VU_BOOL pendingUpdate) { pendingUpdate_ = pendingUpdate; }//me123
public void SetpendingRoughUpdate(VU_BOOL pendingRoughUpdate) { pendingRoughUpdate_ = pendingRoughUpdate; }//me123
public void UpdateDrdata(VU_BOOL registrer)//me123
{ throw new NotImplementedException(); }
public virtual VU_ERRCODE GeneratePositionUpdate(int oob, VU_TIME timestamp, VU_BOOL registrer, VuTargetEntity target) { throw new NotImplementedException(); }
public VuSlave(VuEntity entity) :base(entity) { throw new NotImplementedException(); }
//TODO public virtual ~VuSlave();
public override int Type() { throw new NotImplementedException(); }
public BIG_SCALAR LinearError(BIG_SCALAR value, BIG_SCALAR truevalue) { throw new NotImplementedException(); }
public SM_SCALAR SmoothLinear(BIG_SCALAR value,
BIG_SCALAR truevalue, SM_SCALAR truedelta, SM_SCALAR timeInverse) { throw new NotImplementedException(); }
#if VU_USE_QUATERNION
public SM_SCALAR QuatError(VU_QUAT value, VU_QUAT truevalue);
#else // !VU_USE_QUATERNION
public SM_SCALAR AngleError(SM_SCALAR value, SM_SCALAR truevalue) { throw new NotImplementedException(); }
public SM_SCALAR SmoothAngle(SM_SCALAR value, SM_SCALAR truevalue,
SM_SCALAR truedelta, SM_SCALAR timeInverse) { throw new NotImplementedException(); }
#endif
public override void NoExec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override void Exec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override void AutoExec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override VU_ERRCODE Handle(VuEvent evnt) { throw new NotImplementedException(); }
public override VU_ERRCODE Handle(VuFullUpdateEvent evnt) { throw new NotImplementedException(); }
public override VU_ERRCODE Handle(VuPositionUpdateEvent evnt) { throw new NotImplementedException(); }
// debug hooks
public override int DebugString(string str) { throw new NotImplementedException(); }
protected virtual VU_BOOL DoSmoothing(VU_TIME lookahead, VU_TIME timestamp) { throw new NotImplementedException(); }
// DATA
// smoothing
protected BIG_SCALAR truex_, truey_, truez_;
protected SM_SCALAR truexdelta_, trueydelta_, truezdelta_;
#if VU_USE_QUATERNION
protected VU_QUAT truequat_; // quaternion indicating current facing
protected VU_VECT truequatdelta_; // unit vector expressing quaternion delta
protected SM_SCALAR truetheta_; // scalar indicating rate of above delta
#else // !VU_USE_QUATERNION
protected SM_SCALAR trueyaw_, truepitch_, trueroll_;
//SM_SCALAR trueyawdelta_, truepitchdelta_, truerolldelta_;
#endif
protected VU_TIME lastSmoothTime_;
protected VU_TIME lastRemoteUpdateTime_;
}
//-----------------------------------------
public class VuDelaySlave : VuSlave
{
public VuDelaySlave(VuEntity entity) :base(entity) { throw new NotImplementedException(); }
//TODO public virtual ~VuDelaySlave();
public override int Type() { throw new NotImplementedException(); }
public override void NoExec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override void Exec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override void AutoExec(VU_TIME timestamp) { throw new NotImplementedException(); }
public override VU_ERRCODE Handle(VuPositionUpdateEvent evnt) { throw new NotImplementedException(); }
protected override VU_BOOL DoSmoothing(VU_TIME lookahead, VU_TIME timestamp) { throw new NotImplementedException(); }
// DATA
protected SM_SCALAR ddrxdelta_, ddrydelta_, ddrzdelta_; // accel values
}
}
| 44.75 | 167 | 0.705125 | [
"MIT"
] | agustinsantos/FalconNet | VU/VuDriver.cs | 12,353 | 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.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleHeaderArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the query header to inspect. This setting must be provided as lower case characters.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
public WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleHeaderArgs()
{
}
}
}
| 36.576923 | 172 | 0.736067 | [
"ECL-2.0",
"Apache-2.0"
] | chivandikwa/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementAndStatementStatementAndStatementStatementOrStatementStatementXssMatchStatementFieldToMatchSingleHeaderArgs.cs | 951 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.IO;
using System.Linq;
using OpenMetaverse.StructuredData;
namespace OpenMetaverse.TestClient
{
public class ImportCommand : Command
{
private enum ImporterState
{
RezzingParent,
RezzingChildren,
Linking,
Idle
}
private class Linkset
{
public Primitive RootPrim;
public List<Primitive> Children = new List<Primitive>();
public Linkset()
{
RootPrim = new Primitive();
}
public Linkset(Primitive rootPrim)
{
RootPrim = rootPrim;
}
}
Primitive currentPrim;
Vector3 currentPosition;
AutoResetEvent primDone = new AutoResetEvent(false);
List<Primitive> primsCreated;
List<uint> linkQueue;
uint rootLocalID;
ImporterState state = ImporterState.Idle;
public ImportCommand(TestClient testClient)
{
Name = "import";
Description = "Import prims from an exported xml file. Usage: import inputfile.xml [usegroup]";
Category = CommandCategory.Objects;
testClient.Objects.ObjectUpdate += Objects_OnNewPrim;
}
public override string Execute(string[] args, UUID fromAgentID)
{
if (args.Length < 1)
return "Usage: import inputfile.xml [usegroup]";
string filename = args[0];
UUID GroupID = (args.Length > 1) ? Client.GroupID : UUID.Zero;
string xml;
List<Primitive> prims;
try { xml = File.ReadAllText(filename); }
catch (Exception e) { return e.Message; }
try { prims = Helpers.OSDToPrimList(OSDParser.DeserializeLLSDXml(xml)); }
catch (Exception e) { return "Failed to deserialize " + filename + ": " + e.Message; }
// Build an organized structure from the imported prims
Dictionary<uint, Linkset> linksets = new Dictionary<uint, Linkset>();
foreach (var prim in prims)
{
if (prim.ParentID == 0)
{
if (linksets.ContainsKey(prim.LocalID))
linksets[prim.LocalID].RootPrim = prim;
else
linksets[prim.LocalID] = new Linkset(prim);
}
else
{
if (!linksets.ContainsKey(prim.ParentID))
linksets[prim.ParentID] = new Linkset();
linksets[prim.ParentID].Children.Add(prim);
}
}
primsCreated = new List<Primitive>();
Console.WriteLine("Importing " + linksets.Count + " structures.");
foreach (Linkset linkset in linksets.Values)
{
if (linkset.RootPrim.LocalID != 0)
{
state = ImporterState.RezzingParent;
currentPrim = linkset.RootPrim;
// HACK: Import the structure just above our head
// We need a more elaborate solution for importing with relative or absolute offsets
linkset.RootPrim.Position = Client.Self.SimPosition;
linkset.RootPrim.Position.Z += 3.0f;
currentPosition = linkset.RootPrim.Position;
// Rez the root prim with no rotation
Quaternion rootRotation = linkset.RootPrim.Rotation;
linkset.RootPrim.Rotation = Quaternion.Identity;
Client.Objects.AddPrim(Client.Network.CurrentSim, linkset.RootPrim.PrimData, GroupID,
linkset.RootPrim.Position, linkset.RootPrim.Scale, linkset.RootPrim.Rotation);
if (!primDone.WaitOne(10000, false))
return "Rez failed, timed out while creating the root prim.";
Client.Objects.SetPosition(Client.Network.CurrentSim, primsCreated[^1].LocalID, linkset.RootPrim.Position);
state = ImporterState.RezzingChildren;
// Rez the child prims
foreach (Primitive prim in linkset.Children)
{
currentPrim = prim;
currentPosition = prim.Position + linkset.RootPrim.Position;
Client.Objects.AddPrim(Client.Network.CurrentSim, prim.PrimData, GroupID, currentPosition,
prim.Scale, prim.Rotation);
if (!primDone.WaitOne(10000, false))
return "Rez failed, timed out while creating child prim.";
Client.Objects.SetPosition(Client.Network.CurrentSim, primsCreated[^1].LocalID, currentPosition);
}
// Create a list of the local IDs of the newly created prims
List<uint> primIDs = new List<uint>(primsCreated.Count) { rootLocalID /*Root prim is first in list.*/ };
if (linkset.Children.Count != 0)
{
// Add the rest of the prims to the list of local IDs
primIDs.AddRange(from prim in primsCreated where prim.LocalID != rootLocalID select prim.LocalID);
linkQueue = new List<uint>(primIDs.Count);
linkQueue.AddRange(primIDs);
// Link and set the permissions + rotation
state = ImporterState.Linking;
Client.Objects.LinkPrims(Client.Network.CurrentSim, linkQueue);
if (primDone.WaitOne(1000 * linkset.Children.Count, false))
Client.Objects.SetRotation(Client.Network.CurrentSim, rootLocalID, rootRotation);
else
Console.WriteLine("Warning: Failed to link {0} prims", linkQueue.Count);
}
else
{
Client.Objects.SetRotation(Client.Network.CurrentSim, rootLocalID, rootRotation);
}
// Set permissions on newly created prims
Client.Objects.SetPermissions(Client.Network.CurrentSim, primIDs,
PermissionWho.Everyone | PermissionWho.Group | PermissionWho.NextOwner,
PermissionMask.All, true);
state = ImporterState.Idle;
}
else
{
// Skip linksets with a missing root prim
Console.WriteLine("WARNING: Skipping a linkset with a missing root prim");
}
// Reset everything for the next linkset
primsCreated.Clear();
}
return "Import complete.";
}
void Objects_OnNewPrim(object sender, PrimEventArgs e)
{
Primitive prim = e.Prim;
if ((prim.Flags & PrimFlags.CreateSelected) == 0)
return; // We received an update for an object we didn't create
switch (state)
{
case ImporterState.RezzingParent:
rootLocalID = prim.LocalID;
goto case ImporterState.RezzingChildren;
case ImporterState.RezzingChildren:
if (!primsCreated.Contains(prim))
{
Console.WriteLine("Setting properties for " + prim.LocalID);
// TODO: Is there a way to set all of this at once, and update more ObjectProperties stuff?
Client.Objects.SetPosition(e.Simulator, prim.LocalID, currentPosition);
Client.Objects.SetTextures(e.Simulator, prim.LocalID, currentPrim.Textures);
if (currentPrim.Light != null && currentPrim.Light.Intensity > 0)
{
Client.Objects.SetLight(e.Simulator, prim.LocalID, currentPrim.Light);
}
if (currentPrim.Flexible != null)
{
Client.Objects.SetFlexible(e.Simulator, prim.LocalID, currentPrim.Flexible);
}
if (currentPrim.Sculpt != null && currentPrim.Sculpt.SculptTexture != UUID.Zero)
{
Client.Objects.SetSculpt(e.Simulator, prim.LocalID, currentPrim.Sculpt);
}
if (currentPrim.Properties!= null && !string.IsNullOrEmpty(currentPrim.Properties.Name))
{
Client.Objects.SetName(e.Simulator, prim.LocalID, currentPrim.Properties.Name);
}
if (currentPrim.Properties != null && !string.IsNullOrEmpty(currentPrim.Properties.Description))
{
Client.Objects.SetDescription(e.Simulator, prim.LocalID, currentPrim.Properties.Description);
}
primsCreated.Add(prim);
primDone.Set();
}
break;
case ImporterState.Linking:
lock (linkQueue)
{
int index = linkQueue.IndexOf(prim.LocalID);
if (index != -1)
{
linkQueue.RemoveAt(index);
if (linkQueue.Count == 0)
primDone.Set();
}
}
break;
}
}
}
}
| 41.209877 | 127 | 0.50739 | [
"BSD-3-Clause"
] | mikelittman/libremetaverse | Programs/examples/TestClient/Commands/Prims/ImportCommand.cs | 10,014 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using SharpNeat.Core;
using SharpNeat.Decoders;
using SharpNeat.Decoders.Neat;
using SharpNeat.DistanceMetrics;
using SharpNeat.EvolutionAlgorithms;
using SharpNeat.EvolutionAlgorithms.ComplexityRegulation;
using SharpNeat.Genomes.Neat;
using SharpNeat.Phenomes;
using SharpNeat.SpeciationStrategies;
namespace UltimateTicTacToe
{
/// <summary>
/// Helper class that hides most of the details of setting up an experiment.
/// If you're just doing a simple console-based experiment, this is probably
/// what you want to inherit from. However, if you need more flexibility
/// (e.g., custom genome/phenome creation or performing complex population
/// evaluations) then you probably want to implement your own INeatExperiment
/// class.
/// </summary>
public abstract class SimpleNeatExperiment
{
NeatEvolutionAlgorithmParameters _eaParams;
NeatGenomeParameters _neatGenomeParams;
string _name;
int _populationSize;
int _specieCount;
NetworkActivationScheme _activationScheme;
string _description;
ParallelOptions _parallelOptions;
#region Abstract properties that subclasses must implement
public abstract IPhenomeEvaluator<IBlackBox> PhenomeEvaluator { get; }
public abstract int InputCount { get; }
public abstract int OutputCount { get; }
public abstract bool EvaluateParents { get; }
#endregion
#region INeatExperiment Members
public string Description
{
get { return _description; }
}
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets the default population size to use for the experiment.
/// </summary>
public int DefaultPopulationSize
{
get { return _populationSize; }
}
/// <summary>
/// Gets the NeatEvolutionAlgorithmParameters to be used for the experiment. Parameters on this object can be
/// modified. Calls to CreateEvolutionAlgorithm() make a copy of and use this object in whatever state it is in
/// at the time of the call.
/// </summary>
public NeatEvolutionAlgorithmParameters NeatEvolutionAlgorithmParameters
{
get { return _eaParams; }
}
/// <summary>
/// Gets the NeatGenomeParameters to be used for the experiment. Parameters on this object can be modified. Calls
/// to CreateEvolutionAlgorithm() make a copy of and use this object in whatever state it is in at the time of the call.
/// </summary>
public NeatGenomeParameters NeatGenomeParameters
{
get { return _neatGenomeParams; }
}
/// <summary>
/// Initialize the experiment with some optional XML configutation data.
/// </summary>
public void Initialize(string name)
{
_name = name;
_activationScheme = NetworkActivationScheme.CreateCyclicFixedTimestepsScheme(2);
_parallelOptions = new ParallelOptions();
_description = "Description";
_populationSize = 150;
_specieCount = 15;
_eaParams = new NeatEvolutionAlgorithmParameters();
_eaParams.SpecieCount = _specieCount;
_neatGenomeParams = new NeatGenomeParameters();
}
/// <summary>
/// Load a population of genomes from an XmlReader and returns the genomes in a new list.
/// The genome2 factory for the genomes can be obtained from any one of the genomes.
/// </summary>
//public List<NeatGenome> LoadPopulation(XmlReader xr)
//{
// return NeatGenomeUtils.LoadPopulation(xr, false, this.InputCount, this.OutputCount);
//}
/// <summary>
/// Save a population of genomes to an XmlWriter.
/// </summary>
//public void SavePopulation(XmlWriter xw, IList<NeatGenome> genomeList)
//{
// // Writing node IDs is not necessary for NEAT.
// NeatGenomeXmlIO.WriteComplete(xw, genomeList, false);
//}
/// <summary>
/// Create a genome2 factory for the experiment.
/// Create a genome2 factory with our neat genome2 parameters object and the appropriate number of input and output neuron genes.
/// </summary>
public IGenomeFactory<NeatGenome> CreateGenomeFactory()
{
return new NeatGenomeFactory(InputCount, OutputCount, _neatGenomeParams);
}
/// <summary>
/// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
/// of the algorithm are also constructed and connected up.
/// This overload requires no parameters and uses the default population size.
/// </summary>
public NeatEvolutionAlgorithm<NeatGenome> CreateEvolutionAlgorithm()
{
return CreateEvolutionAlgorithm(DefaultPopulationSize);
}
/// <summary>
/// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
/// of the algorithm are also constructed and connected up.
/// This overload accepts a population size parameter that specifies how many genomes to create in an initial randomly
/// generated population.
/// </summary>
public NeatEvolutionAlgorithm<NeatGenome> CreateEvolutionAlgorithm(int populationSize)
{
// Create a genome2 factory with our neat genome2 parameters object and the appropriate number of input and output neuron genes.
IGenomeFactory<NeatGenome> genomeFactory = CreateGenomeFactory();
// Create an initial population of randomly generated genomes.
List<NeatGenome> genomeList = genomeFactory.CreateGenomeList(populationSize, 0);
// Create evolution algorithm.
return CreateEvolutionAlgorithm(genomeFactory, genomeList);
}
/// <summary>
/// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
/// of the algorithm are also constructed and connected up.
/// This overload accepts a pre-built genome2 population and their associated/parent genome2 factory.
/// </summary>
public NeatEvolutionAlgorithm<NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory<NeatGenome> genomeFactory, List<NeatGenome> genomeList)
{
// Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
ISpeciationStrategy<NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy<NeatGenome>(distanceMetric, _parallelOptions);
// Create complexity regulation strategy.
IComplexityRegulationStrategy complexityRegulationStrategy = new DefaultComplexityRegulationStrategy(ComplexityCeilingType.Absolute, 50.0);
// Create the evolution algorithm.
NeatEvolutionAlgorithm<NeatGenome> ea = new NeatEvolutionAlgorithm<NeatGenome>(_eaParams, speciationStrategy, complexityRegulationStrategy);
// Create genome2 decoder.
IGenomeDecoder<NeatGenome, IBlackBox> genomeDecoder = new NeatGenomeDecoder(_activationScheme);
// Create a genome2 list evaluator. This packages up the genome2 decoder with the genome2 evaluator.
IGenomeListEvaluator<NeatGenome> genomeListEvaluator = new ParallelGenomeListEvaluator<NeatGenome, IBlackBox>(genomeDecoder, PhenomeEvaluator, _parallelOptions);
// Wrap the list evaluator in a 'selective' evaulator that will only evaluate new genomes. That is, we skip re-evaluating any genomes
// that were in the population in previous generations (elite genomes). This is determiend by examining each genome2's evaluation info object.
if(!EvaluateParents)
genomeListEvaluator = new SelectiveGenomeListEvaluator<NeatGenome>(genomeListEvaluator,
SelectiveGenomeListEvaluator<NeatGenome>.CreatePredicate_OnceOnly());
// Initialize the evolution algorithm.
ea.Initialize(genomeListEvaluator, genomeFactory, genomeList);
// Finished. Return the evolution algorithm
return ea;
}
/// <summary>
/// Creates a new genome decoder that can be used to convert a genome into a phenome.
/// </summary>
public IGenomeDecoder<NeatGenome, IBlackBox> CreateGenomeDecoder()
{
return new NeatGenomeDecoder(_activationScheme);
}
#endregion
}
} | 45.474747 | 173 | 0.671479 | [
"MIT"
] | FabianPetersen/HyperNEAT_UltimateTicTackToe | UltimateTicTacToe/SimpleNeatExperiment.cs | 9,006 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Bot.Builder.Prompts.Choices
{
/// <summary>
/// A value that can be sorted and still refer to its original position with a source array.
/// </summary>
public class SortedValue
{
///<summary>
/// The value that will be sorted.
///</summary>
public string Value { get; set; }
///<summary>
/// The values original position within its unsorted array.
///</summary>
public int Index { get; set; }
}
} | 28.714286 | 96 | 0.603648 | [
"MIT"
] | processsuccessinc/botbuilder-dotnet | libraries/Microsoft.Bot.Builder.Prompts/Choices/SortedValue.cs | 605 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace Microsoft.Docs.MarkdigExtensions.Tests;
public class CodeTest
{
private const string ContentCSharp = @"using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;
namespace TableSnippets
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
TableRowGroupsProperty();
}
void WindowLoaded(Object sender, RoutedEventArgs args)
{
TableColumnsProperty();
TableRowGroupsProperty();
TableRowGroupRows();
TableCellConst();
}
void TableColumnsProperty()
{
// <Snippet_Table_Columns_Add>
Table tbl = new Table();
int columnsToAdd = 4;
for (int x = 0; x < columnsToAdd; x++)
tbl.Columns.Add(new TableColumn());
// </Snippet_Table_Columns_Add>
// Insert a new first column.
// <Snippet_Table_Columns_Insert>
tbl.Columns.Insert(0, new TableColumn());
// </Snippet_Table_Columns_Insert>
// Manipulating columns.
#region Snippet_Table_Columns_Manip
tbl.Columns[0].Width = new GridLength(20);
tbl.Columns[1].Background = Brushes.AliceBlue;
tbl.Columns[2].Width = new GridLength(20);
tbl.Columns[3].Background = Brushes.AliceBlue;
#endregion
// Get a count of columns hosted by the table.
// <Snippet_Table_Columns_Count>
int columns = tbl.Columns.Count;
// </Snippet_Table_Columns_Count>
// Remove a particular column by reference (the 4th).
// <Snippet_Table_Columns_DelRef>
tbl.Columns.Remove(tbl.Columns[3]);
// </Snippet_Table_Columns_DelRef>
// Remove a particular column by index (the 3rd).
// <Snippet_Table_Columns_DelIndex>
tbl.Columns.RemoveAt(2);
// </Snippet_Table_Columns_DelIndex>
// Remove all columns from the table's columns collection.
// <Snippet_Table_Columns_Clear>
tbl.Columns.Clear();
// </Snippet_Table_Columns_Clear>
}
void TableRowGroupsProperty()
{
// Add rowgroups...
// <Snippet_Table_RowGroups_Add>
Table tbl = new Table();
// <Snippet_inner>
int rowGroupsToAdd = 4;
// </Snippet_inner>
for (int x = 0; x < rowGroupsToAdd; x++)
tbl.RowGroups.Add(new TableRowGroup());
// </Snippet_Table_RowGroups_Add>
// Insert rowgroup...
// <Snippet_Table_RowGroups_Insert>
tbl.RowGroups.Insert(0, new TableRowGroup());
// </Snippet_Table_RowGroups_Insert>
// Adding rows to a rowgroup...
{
// <Snippet_Table_RowGroups_AddRows>
int rowsToAdd = 10;
for (int x = 0; x < rowsToAdd; x++)
tbl.RowGroups[0].Rows.Add(new TableRow());
// </Snippet_Table_RowGroups_AddRows>
}
// Manipulating rows (through rowgroups)...
// <Snippet_Table_RowGroups_ManipRows>
// Alias the working TableRowGroup for ease in referencing.
TableRowGroup trg = tbl.RowGroups[0];
trg.Rows[0].Background = Brushes.CornflowerBlue;
trg.Rows[1].FontSize = 24;
trg.Rows[2].ToolTip = ""This row's tooltip"";
// </Snippet_Table_RowGroups_ManipRows>
// Adding cells to a row...
{
// <Snippet_Table_RowGroups_AddCells>
int cellsToAdd = 10;
for (int x = 0; x < cellsToAdd; x++)
tbl.RowGroups[0].Rows[0].Cells.Add(new TableCell(new Paragraph(new Run(""Cell "" + (x + 1)))));
// </Snippet_Table_RowGroups_AddCells>
}
// Manipulating cells (through rowgroups)...
// <Snippet_Table_RowGroups_ManipCells>
// Alias the working for for ease in referencing.
TableRow row = tbl.RowGroups[0].Rows[0];
row.Cells[0].Background = Brushes.PapayaWhip;
row.Cells[1].FontStyle = FontStyles.Italic;
// This call clears all of the content from this cell.
row.Cells[2].Blocks.Clear();
// </Snippet_Table_RowGroups_ManipCells>
// Count rowgroups...
// <Snippet_Table_RowGroups_Count>
int rowGroups = tbl.RowGroups.Count;
// </Snippet_Table_RowGroups_Count>
// Remove rowgroup by ref...
// <Snippet_Table_RowGroups_DelRef>
tbl.RowGroups.Remove(tbl.RowGroups[0]);
// </Snippet_Table_RowGroups_DelRef>
// Remove rowgroup by index...
// <Snippet_Table_RowGroups_DelIndex>
tbl.RowGroups.RemoveAt(0);
// </Snippet_Table_RowGroups_DelIndex>
// Remove all rowgroups...
// <Snippet_Table_RowGroups_Clear>
tbl.RowGroups.Clear();
// </Snippet_Table_RowGroups_Clear>
}
void TableRowGroupRows()
{
// <Snippet_TableRowGroup_Rows>
Table tbl = new Table();
TableRowGroup trg = new TableRowGroup();
tbl.RowGroups.Add(trg);
// Add rows to a TableRowGroup collection.
int rowsToAdd = 4;
for (int x = 0; x < rowsToAdd; x++)
trg.Rows.Add(new TableRow());
// Insert a new first row (at the zero-index position).
trg.Rows.Insert(0, new TableRow());
// Manipulate rows...
// Set the background on the first row.
trg.Rows[0].Background = Brushes.CornflowerBlue;
// Set the font size on the second row.
trg.Rows[1].FontSize = 24;
// Set a tooltip for the third row.
trg.Rows[2].ToolTip = ""This row's tooltip"";
// Adding cells to a row...
{
int cellsToAdd = 10;
for (int x = 0; x < cellsToAdd; x++)
trg.Rows[0].Cells.Add(new TableCell(new Paragraph(new Run(""Cell "" + (x + 1)))));
}
// Count rows.
int rows = trg.Rows.Count;
// Remove 1st row by reference.
trg.Rows.Remove(trg.Rows[0]);
// Remove all rows...
trg.Rows.Clear();
// </Snippet_TableRowGroup_Rows>
}
void TableCellConst()
{
// <Snippet_TableCell_Const1>
// A child Block element for the new TableCell element.
Paragraph para = new Paragraph(new Run(""A bit of text content...""));
// After this line executes, the new element ""cellx""
// contains the specified Block element, ""para"".
TableCell cellx = new TableCell(para);
// </Snippet_TableCell_Const1>
}
}
}";
private const string ContentCSharp2 = @"using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Fluent;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
namespace ChangeFeedSample
{
class Program
{
static async Task Main(string[] args)
{
IConfiguration configuration = BuildConfiguration();
CosmosClient cosmosClient = BuildCosmosClient(configuration);
await InitializeContainersAsync(cosmosClient, configuration);
ChangeFeedProcessor processor = await StartChangeFeedProcessorAsync(cosmosClient, configuration);
await GenerateItemsAsync(cosmosClient, processor, configuration);
}
// <Delegate>
/// <summary>
/// The delegate receives batches of changes as they are generated in the change feed and can process them.
/// </summary>
static async Task HandleChangesAsync(IReadOnlyCollection<ToDoItem> changes, CancellationToken cancellationToken)
{
Console.WriteLine(""Started handling changes..."");
foreach (ToDoItem item in changes)
{
Console.WriteLine($""Detected operation for item with id {item.id}, created at {item.creationTime}."");
// Simulate some asynchronous operation
await Task.Delay(10);
}
Console.WriteLine(""Finished handling changes."");
}
// </Delegate>
/// <summary>
/// Create required containers for the sample.
/// Change Feed processing requires a source container to read the Change Feed from, and a container to store the state on, called leases.
/// </summary>
private static async Task InitializeContainersAsync(
CosmosClient cosmosClient,
IConfiguration configuration)
{
string databaseName = configuration[""SourceDatabaseName""];
string sourceContainerName = configuration[""SourceContainerName""];
string leaseContainerName = configuration[""LeasesContainerName""];
if (string.IsNullOrEmpty(databaseName)
|| string.IsNullOrEmpty(sourceContainerName)
|| string.IsNullOrEmpty(leaseContainerName))
{
throw new ArgumentNullException(""'SourceDatabaseName', 'SourceContainerName', and 'LeasesContainerName' settings are required. Verify your configuration."");
}
Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName);
await database.CreateContainerIfNotExistsAsync(new ContainerProperties(sourceContainerName, ""/id""));
await database.CreateContainerIfNotExistsAsync(new ContainerProperties(leaseContainerName, ""/id""));
}
// <DefineProcessor>
/// <summary>
/// Start the Change Feed Processor to listen for changes and process them with the HandlerChangesAsync implementation.
/// </summary>
private static async Task<ChangeFeedProcessor> StartChangeFeedProcessorAsync(
CosmosClient cosmosClient,
IConfiguration configuration)
{
string databaseName = configuration[""SourceDatabaseName""];
string sourceContainerName = configuration[""SourceContainerName""];
string leaseContainerName = configuration[""LeasesContainerName""];
Container leaseContainer = cosmosClient.GetContainer(databaseName, leaseContainerName);
ChangeFeedProcessor changeFeedProcessor = cosmosClient.GetContainer(databaseName, sourceContainerName)
.GetChangeFeedProcessorBuilder<ToDoItem>(""changeFeedSample"", HandleChangesAsync)
.WithInstanceName(""consoleHost"")
.WithLeaseContainer(leaseContainer)
.Build();
Console.WriteLine(""Starting Change Feed Processor..."");
await changeFeedProcessor.StartAsync();
Console.WriteLine(""Change Feed Processor started."");
return changeFeedProcessor;
}
// </DefineProcessor>
/// <summary>
/// Generate sample items based on user input.
/// </summary>
private static async Task GenerateItemsAsync(
CosmosClient cosmosClient,
ChangeFeedProcessor changeFeedProcessor,
IConfiguration configuration)
{
string databaseName = configuration[""SourceDatabaseName""];
string sourceContainerName = configuration[""SourceContainerName""];
Container sourceContainer = cosmosClient.GetContainer(databaseName, sourceContainerName);
while(true)
{
Console.WriteLine(""Enter a number of items to insert in the container or 'exit' to stop:"");
string command = Console.ReadLine();
if (""exit"".Equals(command, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine();
break;
}
if (int.TryParse(command, out int itemsToInsert))
{
Console.WriteLine($""Generating {itemsToInsert} items..."");
for (int i = 0; i < itemsToInsert; i++)
{
string id = Guid.NewGuid().ToString();
await sourceContainer.CreateItemAsync<ToDoItem>(
new ToDoItem()
{
id = id,
creationTime = DateTime.UtcNow
},
new PartitionKey(id));
}
}
}
Console.WriteLine(""Stopping Change Feed Processor..."");
await changeFeedProcessor.StopAsync();
Console.WriteLine(""Stopped Change Feed Processor."");
}
private static IConfiguration BuildConfiguration()
{
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(""appsettings.json"", optional: true, reloadOnChange: true)
.Build();
}
private static CosmosClient BuildCosmosClient(IConfiguration configuration)
{
if (string.IsNullOrEmpty(configuration[""ConnectionString""]) || ""<Your-Connection-String>"".Equals(configuration[""ConnectionString""]))
{
throw new ArgumentNullException(""Missing 'ConnectionString' setting in configuration."");
}
return new CosmosClientBuilder(configuration[""ConnectionString""])
.Build();
}
}
}";
private const string ContentCSharpRegion = @"using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace TagHelpersBuiltIn
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
#region snippet_AllowAreas
services.AddMvc()
.AddRazorPagesOptions(options => options.AllowAreas = true);
#endregion
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(""/Error"");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
#region snippet_UseMvc
app.UseMvc(routes =>
{
// need route and attribute on controller: [Area(""Blogs"")]
routes.MapRoute(name: ""mvcAreaRoute"",
template: ""{area:exists}/{controller=Home}/{action=Index}"");
// default route for non-areas
#region inner
routes.MapRoute(
name: ""default"",
#endregion
template: ""{controller=Home}/{action=Index}/{id?}"");
});
#endregion
}
}
}";
private const string ContentASPNet = @"@{
ViewData[""Title""] = ""Anchor Tag Helper"";
}
<table class=""table table-hover"">
<caption>Anchor Tag Helper attribute examples</caption>
<thead>
<tr>
<th>Attribute</th>
<th>Markup</th>
<th>Result</th>
</tr>
</thead>
<!-- <snippet_BigSnippet> -->
<tbody>
<tr>
<td>asp-action</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-controller=""""Speaker"""" asp-action=""""Evaluations"""">Speaker Evaluations</a>""))
</code>
</td>
<td>
<!-- <snippet_AspAction> -->
<a asp-controller=""Speaker""
asp-action=""Evaluations"">Speaker Evaluations</a>
<!-- </snippet_AspAction> -->
</td>
</tr>
<tr>
<td>asp-all-route-data</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-route=""""speakerevalscurrent"""" asp-all-route-data=""""params"""">Speaker Evaluations</a>""))
</code>
</td>
<td>
<!-- <snippet_AspAllRouteData> -->
@{
var params = new Dictionary<string, string>
{
{ ""speakerId"", ""11"" },
{ ""currentYear"", ""true"" }
};
}
<a asp-route=""speakerevalscurrent""
asp-all-route-data=""params"">Speaker Evaluations</a>
<!-- </snippet_AspAllRouteData> -->
</td>
</tr>
<tr>
<td rowspan=""2"">asp-area</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-area=""""Blogs"""" asp-controller=""""Home"""" asp-action=""""AboutBlog"""">About Blog</a>""))
</code>
</td>
<td>
<!-- <snippet_AspArea> -->
<a asp-area=""Blogs""
asp-controller=""Home""
asp-action=""AboutBlog"">About Blog</a>
<!-- </snippet_AspArea> -->
</td>
</tr>
<tr>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-area=""""Sessions"""" asp-page=""""/Index"""">View Sessions</a>""))
</code>
</td>
<td>
<!-- <snippet_AspAreaRazorPages> -->
<a asp-area=""Sessions""
asp-page=""/Index"">View Sessions</a>
<!-- </snippet_AspAreaRazorPages> -->
</td>
</tr>
<tr>
<td>asp-controller</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-controller=""""Speaker"""" asp-action=""""Index"""">All Speakers</a>""))
</code>
</td>
<td>
<!-- <snippet_AspController> -->
<a asp-controller=""Speaker""
asp-action=""Index"">All Speakers</a>
<!-- </snippet_AspController> -->
</td>
</tr>
<tr>
<td>asp-fragment</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-controller=""""Speaker"""" asp-action=""""Evaluations"""" asp-fragment=""""SpeakerEvaluations"""">Speaker Evaluations</a>""))
</code>
</td>
<td>
<!-- <snippet_AspFragment> -->
<a asp-controller=""Speaker""
asp-action=""Evaluations""
asp-fragment=""SpeakerEvaluations"">Speaker Evaluations</a>
<!-- </snippet_AspFragment> -->
</td>
</tr>
<tr>
<td>asp-host</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-protocol=""""https"""" asp-host=""""microsoft.com"""" asp-controller=""""Home"""" asp-action=""""About"""">About</a>""))
</code>
</td>
<td>
<!-- <snippet_AspHost> -->
<a asp-protocol=""https""
asp-host=""microsoft.com""
asp-controller=""Home""
asp-action=""About"">About</a>
<!-- </snippet_AspHost> -->
</td>
</tr>
<tr>
<td>asp-page <span class=""badge"">RP</span></td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-page=""""/Attendee"""">All Attendees</a>""))
</code>
</td>
<td>
<!-- <snippet_AspPage> -->
<a asp-page=""/Attendee"">All Attendees</a>
<!-- </snippet_AspPage> -->
</td>
</tr>
<tr>
<td>asp-page-handler <span class=""badge"">RP</span></td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-page=""""/Attendee"""" asp-page-handler=""""Profile"""" asp-route-attendeeid=""""12"""">Attendee Profile</a>""))
</code>
</td>
<td>
<!-- <snippet_AspPageHandler> -->
<a asp-page=""/Attendee""
asp-page-handler=""Profile""
asp-route-attendeeid=""12"">Attendee Profile</a>
<!-- </snippet_AspPageHandler> -->
</td>
</tr>
<tr>
<td>asp-protocol</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-protocol=""""https"""" asp-controller=""""Home"""" asp-action=""""About"""">About</a>""))
</code>
</td>
<td>
<!-- <snippet_AspProtocol> -->
<a asp-protocol=""https""
asp-controller=""Home""
asp-action=""About"">About</a>
<!-- </snippet_AspProtocol> -->
</td>
</tr>
<tr>
<td>asp-route</td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-route=""""speakerevals"""">Speaker Evaluations</a>""))
</code>
</td>
<td>
<!-- <snippet_AspRoute> -->
<a asp-route=""speakerevals"">Speaker Evaluations</a>
<!-- </snippet_AspRoute> -->
</td>
</tr>
<tr>
<td>asp-route-<em>{value}</em></td>
<td>
<code>
@Html.Raw(Html.Encode(@""<a asp-page=""""/Attendee"""" asp-route-attendeeid=""""10"""">View Attendee</a>""))
</code>
</td>
<td>
<!-- <snippet_AspPageAspRouteId> -->
<a asp-page=""/Attendee""
asp-route-attendeeid=""10"">View Attendee</a>
<!-- </snippet_AspPageAspRouteId> -->
</td>
</tr>
</tbody>
<!-- </snippet_BigSnippet> -->
<tfoot>
<tr>
<td colspan=""3"">
<span class=""badge"">RP</span> Supported in Razor Pages only
</td>
</tr>
</tfoot>
</table>";
private const string ContentVB = @"'<Snippet1>
Class ADSetupInformation
Shared Sub Main()
Dim root As AppDomain = AppDomain.CurrentDomain
Dim setup As New AppDomainSetup()
setup.ApplicationBase = _
root.SetupInformation.ApplicationBase & ""MyAppSubfolder\""
Dim domain As AppDomain = AppDomain.CreateDomain(""MyDomain"", Nothing, setup)
Console.WriteLine(""Application base of {0}:"" & vbCrLf & vbTab & ""{1}"", _
root.FriendlyName, root.SetupInformation.ApplicationBase)
Console.WriteLine(""Application base of {0}:"" & vbCrLf & vbTab & ""{1}"", _
domain.FriendlyName, domain.SetupInformation.ApplicationBase)
AppDomain.Unload(domain)
End Sub
End Class
' This example produces output similar to the following:
'
'Application base of MyApp.exe:
' C:\Program Files\MyApp\
'Application base of MyDomain:
' C:\Program Files\MyApp\MyAppSubfolder\
'</Snippet1>
'<snippet2>
Imports System.Reflection
Class AppDomain1
Public Shared Sub Main()
Console.WriteLine(""Creating new AppDomain."")
Dim domain As AppDomain = AppDomain.CreateDomain(""MyDomain"")
Console.WriteLine(""Host domain: "" + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine(""child domain: "" + domain.FriendlyName)
End Sub
End Class
'</snippet2>
'<snippet3>
Imports System.Reflection
Class AppDomain2
Public Shared Sub Main()
'<snippet_Inner>
Console.WriteLine(""Creating new AppDomain."")
Dim domain As AppDomain = AppDomain.CreateDomain(""MyDomain"")
'</snippet_Inner>
Console.WriteLine(""Host domain: "" + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine(""child domain: "" + domain.FriendlyName)
End Sub
End Class
'</snippet3>
";
private const string ContentCPP = @"//<Snippet1>
using namespace System;
int main()
{
AppDomain^ root = AppDomain::CurrentDomain;
AppDomainSetup^ setup = gcnew AppDomainSetup();
setup->ApplicationBase =
root->SetupInformation->ApplicationBase + ""MyAppSubfolder\\"";
AppDomain^ domain = AppDomain::CreateDomain(""MyDomain"", nullptr, setup);
Console::WriteLine(""Application base of {0}:\r\n\t{1}"",
root->FriendlyName, root->SetupInformation->ApplicationBase);
Console::WriteLine(""Application base of {0}:\r\n\t{1}"",
domain->FriendlyName, domain->SetupInformation->ApplicationBase);
AppDomain::Unload(domain);
}
/* This example produces output similar to the following:
Application base of MyApp.exe:
C:\Program Files\MyApp\
Application base of MyDomain:
C:\Program Files\MyApp\MyAppSubfolder\
*/
//</Snippet1>
// <snippet2>
using namespace System;
using namespace System::Reflection;
ref class AppDomain4
{
public:
static void Main()
{
// Create application domain setup information.
AppDomainSetup^ domaininfo = gcnew AppDomainSetup();
domaininfo->ApplicationBase = ""f:\\work\\development\\latest"";
// Create the application domain.
AppDomain^ domain = AppDomain::CreateDomain(""MyDomain"", nullptr, domaininfo);
// Write application domain information to the console.
Console::WriteLine(""Host domain: "" + AppDomain::CurrentDomain->FriendlyName);
Console::WriteLine(""child domain: "" + domain->FriendlyName);
Console::WriteLine(""Application base is: "" + domain->SetupInformation->ApplicationBase);
// Unload the application domain.
AppDomain::Unload(domain);
}
};
int main()
{
AppDomain4::Main();
}
// </snippet2>";
private const string ContentCPP2 = @"//<Snippet1>
using namespace System;
using namespace System::Collections::Generic;
public ref class Example
{
public:
static void Main()
{
//<Snippet2>
// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<String^, String^>^ openWith =
gcnew Dictionary<String^, String^>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith->Add(""txt"", ""notepad.exe"");
openWith->Add(""bmp"", ""paint.exe"");
openWith->Add(""dib"", ""paint.exe"");
openWith->Add(""rtf"", ""wordpad.exe"");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith->Add(""txt"", ""winword.exe"");
}
catch (ArgumentException^)
{
Console::WriteLine(""An element with Key = \""txt\"" already exists."");
}
//</Snippet2>
//<Snippet3>
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console::WriteLine(""For key = \""rtf\"", value = {0}."",
openWith[""rtf""]);
// The indexer can be used to change the value associated
// with a key.
openWith[""rtf""] = ""winword.exe"";
Console::WriteLine(""For key = \""rtf\"", value = {0}."",
openWith[""rtf""]);
// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith[""doc""] = ""winword.exe"";
//</Snippet3>
//<Snippet4>
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
Console::WriteLine(""For key = \""tif\"", value = {0}."",
openWith[""tif""]);
}
catch (KeyNotFoundException^)
{
Console::WriteLine(""Key = \""tif\"" is not found."");
}
//</Snippet4>
//<Snippet5>
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
String^ value = """";
if (openWith->TryGetValue(""tif"", value))
{
Console::WriteLine(""For key = \""tif\"", value = {0}."", value);
}
else
{
Console::WriteLine(""Key = \""tif\"" is not found."");
}
//</Snippet5>
//<Snippet6>
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith->ContainsKey(""ht""))
{
openWith->Add(""ht"", ""hypertrm.exe"");
Console::WriteLine(""Value added for key = \""ht\"": {0}"",
openWith[""ht""]);
}
//</Snippet6>
//<Snippet7>
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console::WriteLine();
for each( KeyValuePair<String^, String^> kvp in openWith )
{
Console::WriteLine(""Key = {0}, Value = {1}"",
kvp.Key, kvp.Value);
}
//</Snippet7>
//<Snippet8>
// To get the values alone, use the Values property.
ICollection<String^>^ collection = openWith->Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in collection )
{
Console::WriteLine(""Value = {0}"", s);
}
//</Snippet8>
//<Snippet9>
// To get the keys alone, use the Keys property.
collection = openWith->Keys;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in collection )
{
Console::WriteLine(""Key = {0}"", s);
}
//</Snippet9>
//<Snippet10>
// Use the Remove method to remove a key/value pair.
Console::WriteLine(""\nRemove(\""doc\"")"");
openWith->Remove(""doc"");
if (!openWith->ContainsKey(""doc""))
{
Console::WriteLine(""Key \""doc\"" is not found."");
}
//</Snippet10>
}
};
int main()
{
Example::Main();
}
/* This code example produces the following output:
An element with Key = ""txt"" already exists.
For key = ""rtf"", value = wordpad.exe.
For key = ""rtf"", value = winword.exe.
Key = ""tif"" is not found.
Key = ""tif"" is not found.
Value added for key = ""ht"": hypertrm.exe
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove(""doc"")
Key ""doc"" is not found.
*/
//</ Snippet1 >";
private const string ContentCrazy = @"//<Snippet1>
using namespace System;
int main()
{
AppDomain^ root = AppDomain::CurrentDomain;
AppDomainSetup^ setup = gcnew AppDomainSetup();
setup->ApplicationBase =
root->SetupInformation->ApplicationBase + ""MyAppSubfolder\\"";
AppDomain^ domain = AppDomain::CreateDomain(""MyDomain"", nullptr, setup);
Console::WriteLine(""Application base of {0}:\r\n\t{1}"",
root->FriendlyName, root->SetupInformation->ApplicationBase);
Console::WriteLine(""Application base of {0}:\r\n\t{1}"",
domain->FriendlyName, domain->SetupInformation->ApplicationBase);
AppDomain::Unload(domain);
}
/* This example produces output similar to the following:
Application base of MyApp.exe:
C:\Program Files\MyApp\
Application base of MyDomain:
C:\Program Files\MyApp\MyAppSubfolder\
*/
//</Snippet1>
// <snippet2>
using namespace System;
using namespace System::Reflection;
ref class AppDomain4
{
public:
static void Main()
{
// Create application domain setup information.
AppDomainSetup^ domaininfo = gcnew AppDomainSetup();
domaininfo->ApplicationBase = ""f:\\work\\development\\latest"";
// Create the application domain.
AppDomain^ domain = AppDomain::CreateDomain(""MyDomain"", nullptr, domaininfo);
// Write application domain information to the console.
Console::WriteLine(""Host domain: "" + AppDomain::CurrentDomain->FriendlyName);
Console::WriteLine(""child domain: "" + domain->FriendlyName);
Console::WriteLine(""Application base is: "" + domain->SetupInformation->ApplicationBase);
// Unload the application domain.
AppDomain::Unload(domain);
}
};
int main()
{
AppDomain4::Main();
}
// </snippet2>";
private const string ContentSQL = @"-- <everything>
--<students>
SELECT * FROM Students
WHERE Grade = 12
AND Major = 'Math'
--</students>
--<teachers>
SELECT * FROM Teachers
WHERE Grade = 12
AND Class = 'Math'
--</teachers>
--</everything>";
private const string ContentPython = @"#<everything>
#<first>
from flask import Flask
app = Flask(__name__)
#</first>
#<second>
@app.route(""/"")
def hello():
return ""Hello World!""
#</second>
#</everything>
";
private const string ContentBatch = @"REM <snippet>
:Label1
:Label2
:: Comment line 3
REM </snippet>
:: Comment line 4
IF EXIST C:\AUTOEXEC.BAT REM AUTOEXEC.BAT exists";
private const string ContentErlang = @"-module(hello_world).
-compile(export_all).
% <snippet>
hello() ->
io:format(""hello world~n"").
% </snippet>";
private const string ContentLisp = @";<everything>
USER(64): (member 'b '(perhaps today is a good day to die)) ; test fails
NIL
;<inner>
USER(65): (member 'a '(perhaps today is a good day to die)) ; returns non-NIL
'(a good day to die)
; </inner>
;</everything>";
private const string ContentRuby = @"source 'https://rubygems.org'
git_source(:github) { |repo| ""https://github.com/#{repo}.git"" }
ruby '2.6.5'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.2', '>= 6.0.2.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', '~> 1.4'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
# <GemFileSnippet>
# OAuth
gem 'omniauth-oauth2', '~> 1.6'
# OmniAuth CSRF protection
gem 'omniauth-rails_csrf_protection', '~> 0.1.2'
# REST calls to Microsoft Graph
gem 'httparty', '~> 0.17.1'
# Session storage in database
gem 'activerecord-session_store', '~> 1.1'
# </GemFileSnippet>
";
private const string ContentCSS = @"body {
padding-top: 70px;
}
/*<Snippet1>*/
div {
padding-top: 70px;
}
/*</Snippet1>*/
";
[Theory]
[InlineData(@":::code source=""source.cs"" range=""9"" language=""csharp"":::", @"<pre>
<code class=""lang-csharp"">namespace TableSnippets
</code></pre>
")]
[InlineData(@":::code source=""source.cs"" range=""11 - 33, 40-44"" highlight=""6-7"" language=""azurecli"" interactive=""try-dotnet"":::", @"<pre>
<code class=""lang-azurecli"" data-interactive=""azurecli"" data-interactive-mode=""try-dotnet"" highlight-lines=""6-7"">/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
TableRowGroupsProperty();
}
void WindowLoaded(Object sender, RoutedEventArgs args)
{
TableColumnsProperty();
TableRowGroupsProperty();
TableRowGroupRows();
TableCellConst();
}
void TableColumnsProperty()
tbl.Columns.Add(new TableColumn());
// </Snippet_Table_Columns_Add>
// Insert a new first column.
// <Snippet_Table_Columns_Insert>
</code></pre>
")]
[InlineData(@":::code source=""source.cs"" range=""1-2"" language=""azurecli"" interactive=""try-dotnet"":::", @"<pre>
<code class=""lang-azurecli"" data-interactive=""azurecli"" data-interactive-mode=""try-dotnet"">using System;
using System.Windows;
</code></pre>
")]
[InlineData(@":::code source=""source.cs"" range=""1-2"" interactive=""try-dotnet"":::", @"<pre>
<code class=""lang-csharp"" data-interactive=""csharp"" data-interactive-mode=""try-dotnet"">using System;
using System.Windows;
</code></pre>
")]
[InlineData(@":::code source=""source.cs"" range=""1-2,205-"" highlight=""6-7"" language=""azurecli"" interactive=""try-dotnet"":::", @"<pre>
<code class=""lang-azurecli"" data-interactive=""azurecli"" data-interactive-mode=""try-dotnet"" highlight-lines=""6-7"">using System;
using System.Windows;
TableCell cellx = new TableCell(para);
// </Snippet_TableCell_Const1>
}
}
}
</code></pre>
")]
[InlineData(@":::code source=""source.cs"" id=""Snippet_Table_RowGroups_Add"" language=""azurecli"" interactive=""try-dotnet"":::", @"<pre>
<code class=""lang-azurecli"" data-interactive=""azurecli"" data-interactive-mode=""try-dotnet"">Table tbl = new Table();
int rowGroupsToAdd = 4;
for (int x = 0; x < rowGroupsToAdd; x++)
tbl.RowGroups.Add(new TableRowGroup());
</code></pre>
")]
[InlineData(@":::code source=""source.vb"" id=""snippet2"" interactive=""try-dotnet"":::", @"<pre>
<code class=""lang-vb"" data-interactive=""vb"" data-interactive-mode=""try-dotnet"">Imports System.Reflection
Class AppDomain1
Public Shared Sub Main()
Console.WriteLine("Creating new AppDomain.")
Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain")
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine("child domain: " + domain.FriendlyName)
End Sub
End Class
</code></pre>
")]
[InlineData(@":::code source=""source.vb"" id=""snippet1"" interactive=""try-dotnet"":::", @"<pre>
<code class=""lang-vb"" data-interactive=""vb"" data-interactive-mode=""try-dotnet"">Class ADSetupInformation
Shared Sub Main()
Dim root As AppDomain = AppDomain.CurrentDomain
Dim setup As New AppDomainSetup()
setup.ApplicationBase = _
root.SetupInformation.ApplicationBase & "MyAppSubfolder\"
Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain", Nothing, setup)
Console.WriteLine("Application base of {0}:" & vbCrLf & vbTab & "{1}", _
root.FriendlyName, root.SetupInformation.ApplicationBase)
Console.WriteLine("Application base of {0}:" & vbCrLf & vbTab & "{1}", _
domain.FriendlyName, domain.SetupInformation.ApplicationBase)
AppDomain.Unload(domain)
End Sub
End Class
' This example produces output similar to the following:
'
'Application base of MyApp.exe:
' C:\Program Files\MyApp\
'Application base of MyDomain:
' C:\Program Files\MyApp\MyAppSubfolder\
</code></pre>
")]
[InlineData(@":::code source=""source.cpp"" id=""snippet2"":::", @"<pre>
<code class=""lang-cpp"">using namespace System;
using namespace System::Reflection;
ref class AppDomain4
{
public:
static void Main()
{
// Create application domain setup information.
AppDomainSetup^ domaininfo = gcnew AppDomainSetup();
domaininfo->ApplicationBase = "f:\\work\\development\\latest";
// Create the application domain.
AppDomain^ domain = AppDomain::CreateDomain("MyDomain", nullptr, domaininfo);
// Write application domain information to the console.
Console::WriteLine("Host domain: " + AppDomain::CurrentDomain->FriendlyName);
Console::WriteLine("child domain: " + domain->FriendlyName);
Console::WriteLine("Application base is: " + domain->SetupInformation->ApplicationBase);
// Unload the application domain.
AppDomain::Unload(domain);
}
};
int main()
{
AppDomain4::Main();
}
</code></pre>
")]
[InlineData(
@":::code source=""source.cpp"" id=""snippet2"":::
hi
:::code source=""source.cpp"" id=""snippet1"":::
", @"<pre>
<code class=""lang-cpp"">using namespace System;
using namespace System::Reflection;
ref class AppDomain4
{
public:
static void Main()
{
// Create application domain setup information.
AppDomainSetup^ domaininfo = gcnew AppDomainSetup();
domaininfo->ApplicationBase = "f:\\work\\development\\latest";
// Create the application domain.
AppDomain^ domain = AppDomain::CreateDomain("MyDomain", nullptr, domaininfo);
// Write application domain information to the console.
Console::WriteLine("Host domain: " + AppDomain::CurrentDomain->FriendlyName);
Console::WriteLine("child domain: " + domain->FriendlyName);
Console::WriteLine("Application base is: " + domain->SetupInformation->ApplicationBase);
// Unload the application domain.
AppDomain::Unload(domain);
}
};
int main()
{
AppDomain4::Main();
}
</code></pre>
<p>hi</p>
<pre>
<code class=""lang-cpp"">using namespace System;
int main()
{
AppDomain^ root = AppDomain::CurrentDomain;
AppDomainSetup^ setup = gcnew AppDomainSetup();
setup->ApplicationBase =
root->SetupInformation->ApplicationBase + "MyAppSubfolder\\";
AppDomain^ domain = AppDomain::CreateDomain("MyDomain", nullptr, setup);
Console::WriteLine("Application base of {0}:\r\n\t{1}",
root->FriendlyName, root->SetupInformation->ApplicationBase);
Console::WriteLine("Application base of {0}:\r\n\t{1}",
domain->FriendlyName, domain->SetupInformation->ApplicationBase);
AppDomain::Unload(domain);
}
/* This example produces output similar to the following:
Application base of MyApp.exe:
C:\Program Files\MyApp\
Application base of MyDomain:
C:\Program Files\MyApp\MyAppSubfolder\
*/
</code></pre>
")]
[InlineData(
@":::code source=""source2.cs"" id=""snippet_UseMvc"":::
", @"<pre>
<code class=""lang-csharp"">app.UseMvc(routes =>
{
// need route and attribute on controller: [Area("Blogs")]
routes.MapRoute(name: "mvcAreaRoute",
template: "{area:exists}/{controller=Home}/{action=Index}");
// default route for non-areas
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
</code></pre>")]
[InlineData(
@":::code source=""source2.cs"" id=""snippet_AllowAreas"":::
", @"<pre>
<code class=""lang-csharp"">services.AddMvc()
.AddRazorPagesOptions(options => options.AllowAreas = true);
</code></pre>
")]
[InlineData(
@":::code source=""source.vb"" id=""snippet3"":::
", @"<pre>
<code class=""lang-vb"">Imports System.Reflection
Class AppDomain2
Public Shared Sub Main()
Console.WriteLine("Creating new AppDomain.")
Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain")
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName)
Console.WriteLine("child domain: " + domain.FriendlyName)
End Sub
End Class
</code></pre>
")]
[InlineData(
@":::code source=""asp.cshtml"" id=""snippet_BigSnippet"":::
", @"<pre>
<code class=""lang-cshtml""><tbody>
<tr>
<td>asp-action</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-controller=""Speaker"" asp-action=""Evaluations"">Speaker Evaluations</a>"))
</code>
</td>
<td>
<a asp-controller="Speaker"
asp-action="Evaluations">Speaker Evaluations</a>
</td>
</tr>
<tr>
<td>asp-all-route-data</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-route=""speakerevalscurrent"" asp-all-route-data=""params"">Speaker Evaluations</a>"))
</code>
</td>
<td>
@{
var params = new Dictionary<string, string>
{
{ "speakerId", "11" },
{ "currentYear", "true" }
};
}
<a asp-route="speakerevalscurrent"
asp-all-route-data="params">Speaker Evaluations</a>
</td>
</tr>
<tr>
<td rowspan="2">asp-area</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-area=""Blogs"" asp-controller=""Home"" asp-action=""AboutBlog"">About Blog</a>"))
</code>
</td>
<td>
<a asp-area="Blogs"
asp-controller="Home"
asp-action="AboutBlog">About Blog</a>
</td>
</tr>
<tr>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-area=""Sessions"" asp-page=""/Index"">View Sessions</a>"))
</code>
</td>
<td>
<a asp-area="Sessions"
asp-page="/Index">View Sessions</a>
</td>
</tr>
<tr>
<td>asp-controller</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-controller=""Speaker"" asp-action=""Index"">All Speakers</a>"))
</code>
</td>
<td>
<a asp-controller="Speaker"
asp-action="Index">All Speakers</a>
</td>
</tr>
<tr>
<td>asp-fragment</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-controller=""Speaker"" asp-action=""Evaluations"" asp-fragment=""SpeakerEvaluations"">Speaker Evaluations</a>"))
</code>
</td>
<td>
<a asp-controller="Speaker"
asp-action="Evaluations"
asp-fragment="SpeakerEvaluations">Speaker Evaluations</a>
</td>
</tr>
<tr>
<td>asp-host</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-protocol=""https"" asp-host=""microsoft.com"" asp-controller=""Home"" asp-action=""About"">About</a>"))
</code>
</td>
<td>
<a asp-protocol="https"
asp-host="microsoft.com"
asp-controller="Home"
asp-action="About">About</a>
</td>
</tr>
<tr>
<td>asp-page <span class="badge">RP</span></td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-page=""/Attendee"">All Attendees</a>"))
</code>
</td>
<td>
<a asp-page="/Attendee">All Attendees</a>
</td>
</tr>
<tr>
<td>asp-page-handler <span class="badge">RP</span></td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-page=""/Attendee"" asp-page-handler=""Profile"" asp-route-attendeeid=""12"">Attendee Profile</a>"))
</code>
</td>
<td>
<a asp-page="/Attendee"
asp-page-handler="Profile"
asp-route-attendeeid="12">Attendee Profile</a>
</td>
</tr>
<tr>
<td>asp-protocol</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-protocol=""https"" asp-controller=""Home"" asp-action=""About"">About</a>"))
</code>
</td>
<td>
<a asp-protocol="https"
asp-controller="Home"
asp-action="About">About</a>
</td>
</tr>
<tr>
<td>asp-route</td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-route=""speakerevals"">Speaker Evaluations</a>"))
</code>
</td>
<td>
<a asp-route="speakerevals">Speaker Evaluations</a>
</td>
</tr>
<tr>
<td>asp-route-<em>{value}</em></td>
<td>
<code>
@Html.Raw(Html.Encode(@"<a asp-page=""/Attendee"" asp-route-attendeeid=""10"">View Attendee</a>"))
</code>
</td>
<td>
<a asp-page="/Attendee"
asp-route-attendeeid="10">View Attendee</a>
</td>
</tr>
</tbody>
</code></pre>
")]
[InlineData(
@":::code source=""source.sql"" id=""teachers"":::
", @"<pre>
<code class=""lang-sql"">SELECT * FROM Teachers
WHERE Grade = 12
AND Class = 'Math'
</code></pre>
")]
[InlineData(
@":::code source=""source.sql"" id=""everything"":::
", @"<pre>
<code class=""lang-sql"">SELECT * FROM Students
WHERE Grade = 12
AND Major = 'Math'
SELECT * FROM Teachers
WHERE Grade = 12
AND Class = 'Math'
</code></pre>
")]
[InlineData(
@":::code source=""source.py"" id=""everything"":::
", @"<pre>
<code class=""lang-python"">from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
</code></pre>
")]
[InlineData(
@":::code source=""source.bat"" id=""snippet"":::
", @"<pre>
<code class=""lang-batchfile"">:Label1
:Label2
:: Comment line 3
</code></pre>")]
[InlineData(
@":::code source=""source.erl"" id=""snippet"":::
", @"<pre>
<code class=""lang-erlang"">hello() ->
io:format("hello world~n").
</code></pre>
")]
[InlineData(
@":::code source=""source.lsp"" id=""everything"":::
", @"<pre>
<code class=""lang-lisp"">USER(64): (member 'b '(perhaps today is a good day to die)) ; test fails
NIL
USER(65): (member 'a '(perhaps today is a good day to die)) ; returns non-NIL
'(a good day to die)
</code></pre>
")]
[InlineData(
@"An example of a delegate would be:
:::code language=""csharp"" source=""source3.cs"" id=""Delegate"":::", @"<p>An example of a delegate would be:</p>
<pre>
<code class=""lang-csharp"">/// <summary>
/// The delegate receives batches of changes as they are generated in the change feed and can process them.
/// </summary>
static async Task HandleChangesAsync(IReadOnlyCollection<ToDoItem> changes, CancellationToken cancellationToken)
{
Console.WriteLine("Started handling changes...");
foreach (ToDoItem item in changes)
{
Console.WriteLine($"Detected operation for item with id {item.id}, created at {item.creationTime}.");
// Simulate some asynchronous operation
await Task.Delay(10);
}
Console.WriteLine("Finished handling changes.");
}
</code></pre>
")]
[InlineData(@":::code source=""source2.cpp"" id=""Snippet1"":::", @"<pre>
<code class=""lang-cpp"">using namespace System;
using namespace System::Collections::Generic;
public ref class Example
{
public:
static void Main()
{
// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<String^, String^>^ openWith =
gcnew Dictionary<String^, String^>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith->Add("txt", "notepad.exe");
openWith->Add("bmp", "paint.exe");
openWith->Add("dib", "paint.exe");
openWith->Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console::WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]);
// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console::WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]);
// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
Console::WriteLine("For key = \"tif\", value = {0}.",
openWith["tif"]);
}
catch (KeyNotFoundException^)
{
Console::WriteLine("Key = \"tif\" is not found.");
}
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
String^ value = "";
if (openWith->TryGetValue("tif", value))
{
Console::WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console::WriteLine("Key = \"tif\" is not found.");
}
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith->ContainsKey("ht"))
{
openWith->Add("ht", "hypertrm.exe");
Console::WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console::WriteLine();
for each( KeyValuePair<String^, String^> kvp in openWith )
{
Console::WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
ICollection<String^>^ collection = openWith->Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in collection )
{
Console::WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
collection = openWith->Keys;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in collection )
{
Console::WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console::WriteLine("\nRemove(\"doc\")");
openWith->Remove("doc");
if (!openWith->ContainsKey("doc"))
{
Console::WriteLine("Key \"doc\" is not found.");
}
}
};
int main()
{
Example::Main();
}
/* This code example produces the following output:
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove("doc")
Key "doc" is not found.
*/
</code></pre>
")]
[InlineData(@":::code source=""GemFile"" id=""GemFileSnippet"" language=""ruby"":::", @"<pre>
<code class=""lang-ruby""># OAuth
gem 'omniauth-oauth2', '~> 1.6'
# OmniAuth CSRF protection
gem 'omniauth-rails_csrf_protection', '~> 0.1.2'
# REST calls to Microsoft Graph
gem 'httparty', '~> 0.17.1'
# Session storage in database
gem 'activerecord-session_store', '~> 1.1'
</code></pre>
")]
[InlineData(@":::code source=""styles.css"" id=""Snippet1"" language=""css"":::", @"<pre>
<code class=""lang-css"">div {
padding-top: 70px;
}
</code></pre>
")]
public void CodeTestBlockGeneral(string source, string expected)
{
var filename = "";
var content = "";
// arrange
if (source.Contains("source.cs"))
{
filename = "source.cs";
content = ContentCSharp;
}
else if (source.Contains("source2.cs"))
{
filename = "source2.cs";
content = ContentCSharpRegion;
}
else if (source.Contains("source3.cs"))
{
filename = "source3.cs";
content = ContentCSharp2;
}
else if (source.Contains("asp.cshtml"))
{
filename = "asp.cshtml";
content = ContentASPNet;
}
else if (source.Contains("source.vb"))
{
filename = "source.vb";
content = ContentVB;
}
else if (source.Contains("source.cpp"))
{
filename = "source.cpp";
content = ContentCPP;
}
else if (source.Contains("source2.cpp"))
{
filename = "source2.cpp";
content = ContentCPP2;
}
else if (source.Contains("source.sql"))
{
filename = "source.sql";
content = ContentSQL;
}
else if (source.Contains("source.py"))
{
filename = "source.py";
content = ContentPython;
}
else if (source.Contains("source.bat"))
{
filename = "source.bat";
content = ContentBatch;
}
else if (source.Contains("source.erl"))
{
filename = "source.erl";
content = ContentErlang;
}
else if (source.Contains("source.lsp"))
{
filename = "source.lsp";
content = ContentLisp;
}
else if (source.Contains("GemFile"))
{
filename = "GemFile";
content = ContentRuby;
}
else if (source.Contains("styles.css"))
{
filename = "styles.css";
content = ContentCSS;
}
// act
// assert
TestUtility.VerifyMarkup(source, expected, files: new Dictionary<string, string>
{
{ filename, content },
});
}
[Theory]
[InlineData(@":::code source=""source.cs"" badattribute=""ham"" range=""1-5"" language=""azurecli"" interactive=""try-dotnet"":::")]
[InlineData(@":::code range=""1-5"" language=""azurecli"" interactive=""try-dotnet"":::")]
[InlineData(@":::code source=""source.crazy"" range=""1-3"" interactive=""try-dotnet"":::")]
[InlineData(@":::code source=""source.missing"" range=""1-3"" interactive=""try-dotnet"" language=""azurecli"":::")]
public void CodeTestBlockGeneralCSharp_Error(string source)
{
// arrange
string filename;
string content;
if (source.Contains("source.cs"))
{
filename = "source.cs";
content = ContentCSharp;
}
else if (source.Contains("source.vb"))
{
filename = "source.vb";
content = ContentVB;
}
else if (source.Contains("source.cpp"))
{
filename = "source.cpp";
content = ContentCPP;
}
else if (source.Contains("source.crazy"))
{
filename = "source.crazy";
content = ContentCrazy;
}
else
{
filename = "source.missing";
content = "";
}
// act
// assert
TestUtility.VerifyMarkup(source, null, errors: new string[] { "invalid-code" }, files: new Dictionary<string, string>
{
{ filename, content },
});
}
}
| 34.354922 | 252 | 0.569474 | [
"MIT"
] | freewheel70/docfx | test/Microsoft.Docs.MarkdigExtensions.Tests/CodeTest.cs | 66,305 | C# |
using Newtonsoft.Json;
using Rg.Plugins.Popup.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamarinFormsWebAPI.Model;
namespace XamarinFormsWebAPI
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ClientView
{
//Receive information if you want to update
//public ClientView (string emailAdress,int clientId,string firtname,string lastName,bool gender,
// int title,DateTime dateOfBirth,int maritalStatus,string idNumber,string homeAdress,string homeSuburb
// ,string postalCode,string postalPhone, string mobilePhone,bool itcCheck,string occupation
// ,string category,bool sequestratedOrLiquidated,string city,
// string comment, int clientStatusId, string companyName, string PassportNumber,bool underDebtReview)
public ClientView (int id)
{
InitializeComponent ();
int clientID = id;
GetVehicleInfo(clientID);
//txtEmailAddress.Text = emailAdress.ToString();
//EntID.Text = clientId.ToString();
//txtFirstName.Text = firtname;
//txtLastName.Text = lastName;
//txtGender.Text = gender.ToString();
//txtTitle.Text = title.ToString();
//txtDateOfBirth.Text = dateOfBirth.ToString();
//txtMaritalStatus.Text = maritalStatus.ToString();
//txtIdNumber.Text = idNumber.ToString();
//txtHomeAdress.Text = homeAdress.ToString();
//txtHomeSuburg.Text = homeSuburb.ToString();
//txtHomePostalCode.Text = postalCode.ToString();
//txtBusinessPhone.Text = postalPhone.ToString();
//txtMobilePhone.Text = mobilePhone.ToString();
//txtITCCheck.Text = itcCheck.ToString();
//txtOccupation.Text = occupation.ToString();
//txtCategory.Text = category.ToString();
//txtSequestratedOrLiquidated.Text = sequestratedOrLiquidated.ToString();
//txtCity.Text = city.ToString();
//txtComment.Text = comment.ToString();
//txtClientStatusId.Text = clientStatusId.ToString();
//txtCompanyName.Text = companyName.ToString();
//txtPassportNumber.Text = PassportNumber.ToString();
//txtUnderDebtReview.Text = underDebtReview.ToString();
}
void Handle_Clicked(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAsync(true);
}
private async void GetVehicleInfo(int id)
{
HttpClient client = new HttpClient();
// int id = 2;
var response = await client.GetStringAsync(string.Concat("http://192.168.0.53:45455/Api/Vehicle/", id));
var currentUser = JsonConvert.DeserializeObject<List<Vehicle>>(response);
listVehicle.ItemsSource = currentUser;
await Navigation.PushAsync(new UserTabbedPage());
}
private async void BtnUpdate_Clicked(object sender, EventArgs e)
{
//tblUser clientinfo = new tblUser()
//{
// // Id = Convert.ToInt32(EntID.Text),
// //Username = usernameEntry.Text,
// //Password = passwordEntry.Text
// IsMale = Convert.ToBoolean(txtGender.Text),
// TitleId = Convert.ToInt32(txtTitle.Text),
// MaritalStatusId = Convert.ToInt32(txtMaritalStatus.Text),
// DateOfBirth = Convert.ToDateTime(txtDateOfBirth.Text),
// IdentityNo = txtIdNumber.Text,
// HomeAddress = txtHomeAdress.Text,
// HomeSurburb = txtHomeSuburg.Text,
// HomePostalCode = txtHomePostalCode.Text,
// BusinessPhone = txtBusinessPhone.Text,
// MobilePhone = txtMobilePhone.Text,
// ITCCheck = Convert.ToBoolean(txtITCCheck.Text),
// Occupation = txtOccupation.Text,
// Category = txtCategory.Text,
// SequestratedOrLiquidated = Convert.ToBoolean(txtSequestratedOrLiquidated.Text),
// City = txtCity.Text,
// Comment = txtComment.Text,
// CompanyName = txtCompanyName.Text,
// ClientStatusId = Convert.ToInt32(txtClientStatusId.Text),
// PassportNumber = txtPassportNumber.Text,
// UnderDebtReview = Convert.ToBoolean(txtUnderDebtReview.Text)
//};
//var json = JsonConvert.SerializeObject(clientinfo);
//var content = new StringContent(json, Encoding.UTF8, "application/json");
//HttpClient client = new HttpClient();
//var results = await client.PutAsync(string.Concat("http://192.168.0.53:45455/Api/ClientInfo/", EntID.Text), content);
////ClearText();
//if (results.IsSuccessStatusCode)
//{
// await DisplayAlert("Update", "Upadted Succeful", "OK");
//}
}
//public ClientView(string name,string surname)
//{
// txtClientID.Text = name;
// txtMake.Text = surname;
//}
}
} | 38.013793 | 132 | 0.588716 | [
"MIT"
] | Baadjie/XamarinFormsApp | XamarinFormsWebAPI/ClientView.xaml.cs | 5,514 | C# |
using Catalog.API.Entities;
using Catalog.API.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
namespace Catalog.API.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class CatalogController : ControllerBase
{
private readonly IProductRepository _productRepository;
private readonly ILogger<CatalogController> _logger;
public CatalogController(IProductRepository productRepository, ILogger<CatalogController> logger)
{
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
var products = await _productRepository.GetProducts();
return Ok(products);
}
[HttpGet("{id:length(24)}", Name = "GetProduct")]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<ActionResult<Product>> GetProduct(string id)
{
var product = await _productRepository.GetProduct(id);
if (product == null)
{
_logger.LogError($"Product with id: {id}, not found.");
return NotFound();
}
return Ok(product);
}
[Route("[action]/{name}", Name = "GetProductByName")]
[HttpGet]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<Product>>> GetProductByName(string name)
{
var items = await _productRepository.GetProductByName(name);
if (items == null)
{
_logger.LogError($"Products with name: {name} not found.");
return NotFound();
}
return Ok(items);
}
[Route("[action]/{category}", Name = "GetProductByCategory")]
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Product>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<Product>>> GetProductByCategory(string category)
{
var products = await _productRepository.GetProductByCategory(category);
return Ok(products);
}
[HttpPost]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task<ActionResult<Product>> CreateProduct([FromBody]Product product)
{
await _productRepository.CreateProduct(product);
return CreatedAtRoute("GetProduct", new { id = product.Id }, product);
}
[HttpPut]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task<IActionResult> UpdateProduct([FromBody] Product product)
{
return Ok(await _productRepository.UpdateProduct(product));
}
[HttpDelete("{id:length(24)}", Name = "DeleteProduct")]
[ProducesResponseType(typeof(Product), (int)HttpStatusCode.OK)]
public async Task<IActionResult> DeleteProduct(string id)
{
return Ok(await _productRepository.DeleteProduct(id));
}
}
}
| 36.464646 | 113 | 0.64072 | [
"MIT"
] | andrija-mitrovic/eShop-microservices | src/Services/Catalog/Catalog.API/Controllers/CatalogController.cs | 3,612 | C# |
using micro_c_app.ViewModels;
using MicroCLib.Models;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace micro_c_app.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class QuotePage : ContentPage
{
public QuotePage()
{
InitializeComponent();
if(BindingContext is QuotePageViewModel vm)
{
vm.Navigation = Navigation;
}
this.SetupActionButton();
KeyboardHelper.KeyboardChanged += KeyboardHelper_KeyboardChanged;
}
protected override void OnAppearing()
{
base.OnAppearing();
//list view does not update until touched after returning from batch scan
listView.BatchBegin();
listView.BatchCommit();
}
private void KeyboardHelper_KeyboardChanged(object sender, KeyboardHelperEventArgs e)
{
grid.RowDefinitions[2].Height = e.Visible ? e.Height : 0;
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if(Device.RuntimePlatform == "UWP")
{
//xamarin bug, shell does not pass correct width and height to contained pages on UWP
width = App.Current.MainPage.Width;
height = App.Current.MainPage.Height;
}
if (width > height)
{
Grid.SetRow(listView, 0);
Grid.SetRow(SecondaryStack, 0);
Grid.SetColumn(listView, 0);
Grid.SetColumn(SecondaryStack, 1);
SearchView.Orientation = "Vertical";
grid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star);
grid.RowDefinitions[2].Height = 0;
}
else
{
Grid.SetRow(listView, 0);
Grid.SetRow(SecondaryStack, 1);
Grid.SetColumn(listView, 0);
Grid.SetColumn(SecondaryStack, 0);
SearchView.Orientation = "Horizontal";
grid.ColumnDefinitions[1].Width = new GridLength(0);
}
}
private void ItemPriceChanged(object sender, TextChangedEventArgs e)
{
if(BindingContext is QuotePageViewModel vm)
{
Task.Delay(1000).ContinueWith((_) =>
{
vm.UpdateProperties();
});
}
}
Item? previousSelection;
private void listView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var newItem = e.Item;
if (previousSelection == newItem)
{
listView.SelectedItem = null;
previousSelection = null;
}
else
{
previousSelection = newItem as Item;
}
}
}
} | 31.33 | 102 | 0.522822 | [
"MIT"
] | blaxbb/Micro-C-App | micro-c-app/micro-c-app/Views/QuotePage.xaml.cs | 3,135 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using Microsoft.Templates.Core.Locations;
namespace Microsoft.Templates.Core.Test.Locations
{
public sealed class UnitTestsTemplatesSource : LocalTemplatesSource
{
public UnitTestsTemplatesSource(string installedPackagePath)
: base(installedPackagePath)
{
}
public override string Id => "UnitTest" + GetAgentName();
protected override string Origin => $@"..\..\TestData\{TemplatesFolderName}";
}
}
| 29.25 | 85 | 0.710826 | [
"MIT"
] | Acidburn0zzz/WindowsTemplateStudio | code/test/Core.Test/Locations/UnitTestsTemplatesSource.cs | 704 | C# |
using System;
using FunctionsRefSdkClassLib;
namespace FunctionAppNETFramework
{
// Uses references so compiler won't strip them out of the managed module.
class RefUser
{
public Type FunctionsRefSdkClassLibStandard { get => typeof(HttpTriggerRefSdkNETFramework); }
}
}
| 24.666667 | 101 | 0.743243 | [
"MIT"
] | AlexEyler/azure-functions-vs-build-sdk | sample/FunctionAppNETFramework/FunctionAppNETFramework/RefUser.cs | 298 | C# |
namespace MDW.Entity
{
public class Image
{
public string Name { get; set; }
public string Group { get; set; }
public byte[] Data { get; set; }
}
} | 17.818182 | 42 | 0.505102 | [
"MIT"
] | parameshg/markdownwiki | Entity/Image.cs | 198 | 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.
namespace System.Drawing.Drawing2D
{
/*
* Fill mode constants
*/
/// <include file='doc\FillMode.uex' path='docs/doc[@for="FillMode"]/*' />
/// <devdoc>
/// <para>
/// Specifies how the interior of a closed path
/// is filled.
/// </para>
/// </devdoc>
public enum FillMode
{
/**
* Odd-even fill rule
*/
/// <include file='doc\FillMode.uex' path='docs/doc[@for="FillMode.Alternate"]/*' />
/// <devdoc>
/// <para>
/// Specifies the alternate fill mode.
/// </para>
/// </devdoc>
Alternate = 0,
/**
* Non-zero winding fill rule
*/
/// <include file='doc\FillMode.uex' path='docs/doc[@for="FillMode.Winding"]/*' />
/// <devdoc>
/// <para>
/// Specifies the winding fill mode.
/// </para>
/// </devdoc>
Winding = 1
}
}
| 26.863636 | 92 | 0.502538 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/FillMode.cs | 1,182 | C# |
// -----------------------------------------------------------------------
// <copyright file="StringToVisibilityConverter.cs" company="OSharp开源团队">
// Copyright (c) 2014-2021 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2021-02-05 1:33</last-date>
// -----------------------------------------------------------------------
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace OSharp.Wpf.Converters
{
public class StringToVisibilityConverter : IValueConverter
{
/// <summary>转换值。</summary>
/// <param name="value">绑定源生成的值。</param>
/// <param name="targetType">绑定目标属性的类型。</param>
/// <param name="parameter">要使用的转换器参数。</param>
/// <param name="culture">要用在转换器中的区域性。</param>
/// <returns>转换后的值。 如果该方法返回 <see langword="null" />,则使用有效的 null 值。</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
{
return false;
}
string bindingValue = value.ToString();
string parameterValue = parameter.ToString();
bool flag = bindingValue != null && bindingValue.Equals(parameterValue, StringComparison.InvariantCultureIgnoreCase);
return flag ? Visibility.Visible : Visibility.Collapsed;
}
/// <summary>转换值。</summary>
/// <param name="value">绑定目标生成的值。</param>
/// <param name="targetType">要转换为的类型。</param>
/// <param name="parameter">要使用的转换器参数。</param>
/// <param name="culture">要用在转换器中的区域性。</param>
/// <returns>转换后的值。 如果该方法返回 <see langword="null" />,则使用有效的 null 值。</returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
{
return null;
}
Visibility visibility = (Visibility)value;
return visibility == Visibility.Visible ? parameter.ToString() : null;
}
}
} | 40.145455 | 129 | 0.566123 | [
"Apache-2.0"
] | 1051324354/osharp | src/OSharp.Wpf/Converters/StringToVisibilityConverter.cs | 2,486 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WanaKanaNet.Characters;
namespace WanaKanaNet.Checkers
{
internal static class JapaneseChecker
{
public static bool IsJapanese(string input, params char[] additionalAllowedChars)
{
if (input == null) throw new ArgumentNullException(nameof(input));
if (input == string.Empty) return false;
return input.All(c => IsJapanese(c) || additionalAllowedChars.Contains(c));
}
public static bool IsJapanese(string input, Regex additionalCharactersRegex)
{
if (input == null) throw new ArgumentNullException(nameof(input));
if (input == string.Empty) return false;
return input.All(c => IsJapanese(c) || additionalCharactersRegex.IsMatch(c.ToString()));
}
public static bool IsJapanese(char character) =>
CharacterRanges.JapaneseRanges.Any(range => range.Contains(character));
}
}
| 33.0625 | 100 | 0.670132 | [
"MIT"
] | MartinZikmund/WanaKana-net | src/WanaKanaNet/Checkers/JapaneseChecker.cs | 1,060 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GreyScaleMatrixFilter.cs" company="James South">
// Copyright (c) James South.
// Licensed under the Apache License, Version 2.0.
// </copyright>
// <summary>
// Encapsulates methods with which to add a greyscale filter to an image.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ImageProcessor.Imaging.Filters.Photo
{
using System.Drawing;
using System.Drawing.Imaging;
/// <summary>
/// Encapsulates methods with which to add a greyscale filter to an image.
/// </summary>
internal class GreyScaleMatrixFilter : MatrixFilterBase
{
/// <summary>
/// Gets the <see cref="T:System.Drawing.Imaging.ColorMatrix"/> for this filter instance.
/// </summary>
public override ColorMatrix Matrix
{
get { return ColorMatrixes.GreyScale; }
}
/// <summary>
/// Processes the image.
/// </summary>
/// <param name="source">The current image to process</param>
/// <param name="destination">The new Image to return</param>
/// <returns>
/// The processed <see cref="System.Drawing.Bitmap"/>.
/// </returns>
public override Bitmap TransformImage(Image source, Image destination)
{
using (Graphics graphics = Graphics.FromImage(destination))
{
using (ImageAttributes attributes = new ImageAttributes())
{
attributes.SetColorMatrix(this.Matrix);
Rectangle rectangle = new Rectangle(0, 0, source.Width, source.Height);
graphics.DrawImage(source, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);
}
}
return (Bitmap)destination;
}
}
}
| 36.927273 | 125 | 0.525357 | [
"Apache-2.0"
] | Jeavon/ImageProcessor | src/ImageProcessor/Imaging/Filters/Photo/GreyScaleMatrixFilter.cs | 2,033 | C# |
// MIT License
//
// Copyright (c) 2018 Tim Koopman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
// OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
namespace Koopman.CheckPoint.Common
{
/// <summary>
/// Identifies objects that can be assigned as members of a <see cref="Group" />
/// </summary>
public interface IGroupMember : IObjectSummary
{
}
} | 48 | 101 | 0.747768 | [
"MIT"
] | tkoopman/CheckPoint.NET | src/Common/IGroupMember.cs | 1,346 | C# |
/*
TUIO C# Library - part of the reacTIVision project
http://reactivision.sourceforge.net/
Copyright (c) 2005-2009 Martin Kaltenbrunner <mkalten@iua.upf.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections.Generic;
namespace TUIO
{
/**
* The abstract TuioContainer class defines common attributes that apply to both subclasses {@link TuioObject} and {@link TuioCursor}.
*
* @author Martin Kaltenbrunner
* @version 1.4
*/
public abstract class TuioContainer:TuioPoint {
/**
* The unique session ID number that is assigned to each TUIO object or cursor.
*/
protected long session_id;
/**
* The X-axis velocity value.
*/
protected float x_speed;
/**
* The Y-axis velocity value.
*/
protected float y_speed;
/**
* The motion speed value.
*/
protected float motion_speed;
/**
* The motion acceleration value.
*/
protected float motion_accel;
/**
* A Vector of TuioPoints containing all the previous positions of the TUIO component.
*/
protected List<TuioPoint> path;
/**
* Defines the ADDED state.
*/
public const int TUIO_ADDED = 0;
/**
* Defines the ACCELERATING state.
*/
public const int TUIO_ACCELERATING = 1;
/**
* Defines the DECELERATING state.
*/
public const int TUIO_DECELERATING = 2;
/**
* Defines the STOPPED state.
*/
public const int TUIO_STOPPED = 3;
/**
* Defines the REMOVED state.
*/
public const int TUIO_REMOVED = 4;
/**
* Reflects the current state of the TuioComponent
*/
protected int state;
/**
* This constructor takes a TuioTime argument and assigns it along with the provided
* Session ID, X and Y coordinate to the newly created TuioContainer.
*
* @param ttime the TuioTime to assign
* @param si the Session ID to assign
* @param xp the X coordinate to assign
* @param yp the Y coordinate to assign
*/
public TuioContainer(TuioTime ttime, long si, float xp, float yp):base(ttime,xp,yp) {
session_id = si;
x_speed = 0.0f;
y_speed = 0.0f;
motion_speed = 0.0f;
motion_accel = 0.0f;
path = new List<TuioPoint>();
path.Add(new TuioPoint(currentTime,xpos,ypos));
state = TUIO_ADDED;
}
/**
* This constructor takes the provided Session ID, X and Y coordinate
* and assigs these values to the newly created TuioContainer.
*
* @param si the Session ID to assign
* @param xp the X coordinate to assign
* @param yp the Y coordinate to assign
*/
public TuioContainer (long si, float xp, float yp):base(xp,yp) {
session_id = si;
x_speed = 0.0f;
y_speed = 0.0f;
motion_speed = 0.0f;
motion_accel = 0.0f;
path = new List<TuioPoint>();
path.Add(new TuioPoint(currentTime,xpos,ypos));
state = TUIO_ADDED;
}
/**
* This constructor takes the atttibutes of the provided TuioContainer
* and assigs these values to the newly created TuioContainer.
*
* @param tcon the TuioContainer to assign
*/
public TuioContainer (TuioContainer tcon):base(tcon) {
session_id = tcon.getSessionID();
x_speed = 0.0f;
y_speed = 0.0f;
motion_speed = 0.0f;
motion_accel = 0.0f;
path = new List<TuioPoint>();
path.Add(new TuioPoint(currentTime,xpos,ypos));
state = TUIO_ADDED;
}
/**
* Takes a TuioTime argument and assigns it along with the provided
* X and Y coordinate to the private TuioContainer attributes.
* The speed and accleration values are calculated accordingly.
*
* @param ttime the TuioTime to assign
* @param xp the X coordinate to assign
* @param yp the Y coordinate to assign
*/
public new void update(TuioTime ttime, float xp, float yp) {
TuioPoint lastPoint = path[path.Count-1];
base.update(ttime,xp,yp);
TuioTime diffTime = currentTime - lastPoint.getTuioTime();
float dt = diffTime.getTotalMilliseconds()/1000.0f;
float dx = this.xpos - lastPoint.getX();
float dy = this.ypos - lastPoint.getY();
float dist = (float)Math.Sqrt(dx*dx+dy*dy);
float last_motion_speed = this.motion_speed;
this.x_speed = dx/dt;
this.y_speed = dy/dt;
this.motion_speed = dist/dt;
this.motion_accel = (motion_speed - last_motion_speed)/dt;
path.Add(new TuioPoint(currentTime,xpos,ypos));
if (motion_accel>0) state = TUIO_ACCELERATING;
else if (motion_accel<0) state = TUIO_DECELERATING;
else state = TUIO_STOPPED;
}
/**
* This method is used to calculate the speed and acceleration values of
* TuioContainers with unchanged positions.
*/
public void stop(TuioTime ttime) {
update(ttime,this.xpos,this.ypos);
}
/**
* Takes a TuioTime argument and assigns it along with the provided
* X and Y coordinate, X and Y velocity and acceleration
* to the private TuioContainer attributes.
*
* @param ttime the TuioTime to assign
* @param xp the X coordinate to assign
* @param yp the Y coordinate to assign
* @param xs the X velocity to assign
* @param ys the Y velocity to assign
* @param ma the acceleration to assign
*/
public void update(TuioTime ttime, float xp,float yp,float xs,float ys,float ma) {
base.update(ttime,xp,yp);
x_speed = xs;
y_speed = ys;
motion_speed = (float)Math.Sqrt(x_speed*x_speed+y_speed*y_speed);
motion_accel = ma;
path.Add(new TuioPoint(currentTime,xpos,ypos));
if (motion_accel>0) state = TUIO_ACCELERATING;
else if (motion_accel<0) state = TUIO_DECELERATING;
else state = TUIO_STOPPED;
}
/**
* Assigns the provided X and Y coordinate, X and Y velocity and acceleration
* to the private TuioContainer attributes. The TuioTime time stamp remains unchanged.
*
* @param xp the X coordinate to assign
* @param yp the Y coordinate to assign
* @param xs the X velocity to assign
* @param ys the Y velocity to assign
* @param ma the acceleration to assign
*/
public void update (float xp,float yp,float xs,float ys,float ma) {
base.update(xp,yp);
x_speed = xs;
y_speed = ys;
motion_speed = (float)Math.Sqrt(x_speed*x_speed+y_speed*y_speed);
motion_accel = ma;
path.Add(new TuioPoint(currentTime,xpos,ypos));
if (motion_accel>0) state = TUIO_ACCELERATING;
else if (motion_accel<0) state = TUIO_DECELERATING;
else state = TUIO_STOPPED;
}
/**
* Takes the atttibutes of the provided TuioContainer
* and assigs these values to this TuioContainer.
* The TuioTime time stamp of this TuioContainer remains unchanged.
*
* @param tcon the TuioContainer to assign
*/
public void update (TuioContainer tcon) {
base.update(tcon.getX(),tcon.getY());
x_speed = tcon.getXSpeed();
y_speed = tcon.getYSpeed();
motion_speed = (float)Math.Sqrt(x_speed*x_speed+y_speed*y_speed);
motion_accel = tcon.getMotionAccel();
path.Add(new TuioPoint(currentTime,xpos,ypos));
if (motion_accel>0) state = TUIO_ACCELERATING;
else if (motion_accel<0) state = TUIO_DECELERATING;
else state = TUIO_STOPPED;
}
/**
* Assigns the REMOVE state to this TuioContainer and sets
* its TuioTime time stamp to the provided TuioTime argument.
*
* @param ttime the TuioTime to assign
*/
public void remove(TuioTime ttime) {
currentTime = ttime;
state = TUIO_REMOVED;
}
/**
* Returns the Session ID of this TuioContainer.
* @return the Session ID of this TuioContainer
*/
public long getSessionID() {
return session_id;
}
/**
* Returns the X velocity of this TuioContainer.
* @return the X velocity of this TuioContainer
*/
public float getXSpeed() {
return x_speed;
}
/**
* Returns the Y velocity of this TuioContainer.
* @return the Y velocity of this TuioContainer
*/
public float getYSpeed() {
return y_speed;
}
/**
* Returns the position of this TuioContainer.
* @return the position of this TuioContainer
*/
public TuioPoint getPosition() {
return new TuioPoint(xpos,ypos);
}
/**
* Returns the path of this TuioContainer.
* @return the path of this TuioContainer
*/
public List<TuioPoint> getPath() {
return path;
}
/**
* Returns the motion speed of this TuioContainer.
* @return the motion speed of this TuioContainer
*/
public float getMotionSpeed() {
return motion_speed;
}
/**
* Returns the motion acceleration of this TuioContainer.
* @return the motion acceleration of this TuioContainer
*/
public float getMotionAccel() {
return motion_accel;
}
/**
* Returns the TUIO state of this TuioContainer.
* @return the TUIO state of this TuioContainer
*/
public int getTuioState() {
return state;
}
/**
* Returns true of this TuioContainer is moving.
* @return true of this TuioContainer is moving
*/
public bool isMoving() {
if ((state==TUIO_ACCELERATING) || (state==TUIO_DECELERATING)) return true;
else return false;
}
}
}
| 27.727545 | 134 | 0.71137 | [
"MIT"
] | ElementMo/MarkerSort | Assets/TUIOConnector/TuioContainer.cs | 9,261 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EventServices : MonoBehaviour {
public UnityEvent OnStart = new UnityEvent();
// Use this for initialization
void Start()
{
if (OnStart != null) OnStart.Invoke();
}
public void Log(string target)
{
Debug.Log(target);
}
public void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
} | 20.103448 | 64 | 0.607204 | [
"MIT"
] | DooblyNoobly/Unity-ML-Training-Manager | Assets/Scripts/EventServices.cs | 585 | C# |
namespace Microsoft.MovieBooking.Models
{
public class RegisterViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int MobileNo { get; set; }
public string EmailId { get; set; }
public string? Address { get; set; }
}
}
| 27.076923 | 46 | 0.588068 | [
"Apache-2.0"
] | learningdevi/MovieBookingWithAngular | Microsoft.MovieBooking/Models/RegisterViewModel.cs | 354 | C# |
// OData .NET Libraries ver. 5.6.3
// Copyright (c) Microsoft Corporation
// 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.
namespace System.Data.Services.Client
{
/// <summary>
/// Describes the insert/update/delete state of an entity or link.
/// </summary>
/// <remarks>
/// Deleting an inserted resource will detach it.
/// After SaveChanges, deleted resources will become detached and Added & Modified resources will become unchanged.
/// </remarks>
[System.Flags()]
public enum EntityStates
{
/// <summary>
/// The resource is not tracked by the context.
/// </summary>
Detached = 0x00000001,
/// <summary>
/// The resource is tracked by a context with no changes.
/// </summary>
Unchanged = 0x00000002,
/// <summary>
/// The resource is tracked by a context for insert.
/// </summary>
Added = 0x00000004,
/// <summary>
/// The resource is tracked by a context for deletion.
/// </summary>
Deleted = 0x00000008,
/// <summary>
/// The resource is tracked by a context for update.
/// </summary>
Modified = 0x00000010
}
}
| 39.833333 | 124 | 0.644351 | [
"Apache-2.0"
] | tapika/choco | lib/Microsoft.Data.Services.Client/WCFDataService/Client/System/Data/Services/Client/EntityStates.cs | 2,390 | C# |
using System.Reflection;
namespace Abp.Resources.Embedded
{
/// <summary>
/// Stores needed informations of an embedded resource.
/// </summary>
public class EmbeddedResourceInfo
{
/// <summary>
/// Content of the resource file.
/// </summary>
public byte[] Content { get; set; }
/// <summary>
/// The assembly that contains the resource.
/// </summary>
public Assembly Assembly { get; set; }
internal EmbeddedResourceInfo(byte[] content, Assembly assembly)
{
Content = content;
Assembly = assembly;
}
}
} | 24.807692 | 72 | 0.55969 | [
"MIT"
] | Steffe1971/aspnetboilerplate | src/Abp/Resources/Embedded/EmbeddedResourceInfo.cs | 647 | C# |
namespace PAXTEU
{
public class ProdutoViewModel
{
public float Preco {get; set;}
public string Categoria {get; set;}
public string Descricao {get; set;}
}
}
| 14.066667 | 43 | 0.559242 | [
"MIT"
] | regiamariana/projetos | PAXTEU/ProdutoViewModel.cs | 211 | C# |
namespace Microsoft.Maui
{
/// <summary>
/// Provides the ability to create, configure, show, and manage Windows.
/// </summary>
public interface IWindow : IElement
{
/// <summary>
/// Gets or sets the current Page displayed in the Window.
/// </summary>
IView Content { get; }
/// <summary>
/// Gets or sets the title displayed in the Window.
/// </summary>
string? Title { get; }
void Created();
void Resumed();
void Activated();
void Deactivated();
void Stopped();
void Destroying();
}
} | 17.7 | 73 | 0.630885 | [
"MIT"
] | returnZro/maui | src/Core/src/Core/IWindow.cs | 531 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MOE.Common.Business.ActionLog
{
public class ChartData
{
public int Value { get; set; }
public string Description { get; set; }
public string Color { get; set; }
}
}
| 20.625 | 47 | 0.672727 | [
"Apache-2.0"
] | Derek-Lehrke/ATSPM | MOE.Common/Business/ActionLog/ChartData.cs | 332 | C# |
using System;
using Ayehu.Sdk.ActivityCreation.Interfaces;
using Ayehu.Sdk.ActivityCreation.Extension;
using Ayehu.Sdk.ActivityCreation.Helpers;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Collections.Generic;
namespace Ayehu.PagerDuty
{
public class PD_Create_an_escalation_policy : IActivityAsync
{
public string Jsonkeypath = "escalation_policies";
public string password1 = "";
public string From = "";
public string type_p = "";
public string name_p = "";
public string description_p = "";
public string num_loops = "";
public string on_call_handoff_notifications = "";
public string escalation_rules = "";
public string services = "";
public string teams = "";
private bool omitJsonEmptyorNull = true;
private string contentType = "application/json";
private string endPoint = "https://api.pagerduty.com";
private string httpMethod = "POST";
private string _uriBuilderPath;
private string _postData;
private System.Collections.Generic.Dictionary<string, string> _headers;
private System.Collections.Generic.Dictionary<string, string> _queryStringArray;
private string uriBuilderPath {
get {
if (string.IsNullOrEmpty(_uriBuilderPath)) {
_uriBuilderPath = "/escalation_policies";
}
return _uriBuilderPath;
}
set {
this._uriBuilderPath = value;
}
}
private string postData {
get {
if (string.IsNullOrEmpty(_postData)) {
_postData = string.Format("{{ \"escalation_policy\": {{ \"type\": \"{0}\", \"name\": \"{1}\", \"description\": \"{2}\", \"num_loops\": \"{3}\", \"on_call_handoff_notifications\": \"{4}\", \"escalation_rules\": {5}, \"services\": {6}, \"teams\": {7} }} }}",type_p,name_p,description_p,num_loops,on_call_handoff_notifications,escalation_rules,services,teams);
}
return _postData;
}
set {
this._postData = value;
}
}
private System.Collections.Generic.Dictionary<string, string> headers {
get {
if (_headers == null) {
_headers = new Dictionary<string, string>() { {"Authorization","Token token = " + password1},{"From",From} };
}
return _headers;
}
set {
this._headers = value;
}
}
private System.Collections.Generic.Dictionary<string, string> queryStringArray {
get {
if (_queryStringArray == null) {
_queryStringArray = new Dictionary<string, string>() { };
}
return _queryStringArray;
}
set {
this._queryStringArray = value;
}
}
public PD_Create_an_escalation_policy() {
}
public PD_Create_an_escalation_policy(string Jsonkeypath, string password1, string From, string type_p, string name_p, string description_p, string num_loops, string on_call_handoff_notifications, string escalation_rules, string services, string teams) {
this.Jsonkeypath = Jsonkeypath;
this.password1 = password1;
this.From = From;
this.type_p = type_p;
this.name_p = name_p;
this.description_p = description_p;
this.num_loops = num_loops;
this.on_call_handoff_notifications = on_call_handoff_notifications;
this.escalation_rules = escalation_rules;
this.services = services;
this.teams = teams;
}
public async System.Threading.Tasks.Task<ICustomActivityResult> Execute()
{
HttpClient client = new HttpClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
UriBuilder UriBuilder = new UriBuilder(endPoint);
UriBuilder.Path = uriBuilderPath;
UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray);
HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString());
if (contentType == "application/x-www-form-urlencoded")
myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData);
else
if (string.IsNullOrEmpty(postData) == false)
if (omitJsonEmptyorNull)
myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json");
else
myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType);
foreach (KeyValuePair<string, string> headeritem in headers)
client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value);
HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result;
switch (response.StatusCode)
{
case HttpStatusCode.NoContent:
case HttpStatusCode.Created:
case HttpStatusCode.Accepted:
case HttpStatusCode.OK:
{
if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
return this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath);
else
return this.GenerateActivityResult("Success");
}
default:
{
if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
throw new Exception(response.Content.ReadAsStringAsync().Result);
else if (string.IsNullOrEmpty(response.ReasonPhrase) == false)
throw new Exception(response.ReasonPhrase);
else
throw new Exception(response.StatusCode.ToString());
}
}
}
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
} | 37.384181 | 382 | 0.621581 | [
"MIT"
] | Ayehu/custom-activities | PagerDuty/Escalation Policies/PD Create an escalation policy/PD Create an escalation policy.cs | 6,617 | C# |
namespace M_Solution_1
{
public class LStereo : IStereo
{
public override string ToString()
{
return "luxury stereo";
}
}
} | 17.2 | 41 | 0.534884 | [
"MIT"
] | AshV/Design-Patterns | M-AbstractFactory And Builder Pattern/M Solution 1/LStereo.cs | 174 | C# |
//
// This file was auto-generated using the ChilliConnect SDK Generator.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tag Games Ltd
//
// 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.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using SdkCore;
namespace ChilliConnect
{
/// <summary>
/// A container for information on the response from a ConvertCurrencyRequest.
/// </summary>
public sealed class ConvertCurrencyResponse
{
/// <summary>
/// The amount of the From Currency that was converted. The Amount converted will be
/// rounded down to the nearest multiple defined in the Currency Conversion rule so
/// could be less than the Amount submitted. For example, if the Currency Conversion
/// defines a rule that states 10 of CurrencyOne can be converted to 1 of
/// CurrencyTwo, and a conversion request is submitted with an Amount of 24, only 20
/// of CurrencyOne will be converted to 2 of CurrencyTwo.
/// </summary>
public int AmountConverted { get; private set; }
/// <summary>
/// The final balance of the currency converted to.
/// </summary>
public CurrencyBalance ToBalance { get; private set; }
/// <summary>
/// The final balance of the currency converted to.
/// </summary>
public CurrencyBalance FromBalance { get; private set; }
/// <summary>
/// Initialises the response with the given json dictionary.
/// </summary>
///
/// <param name="jsonDictionary">The dictionary containing the JSON data.</param>
public ConvertCurrencyResponse(IDictionary<string, object> jsonDictionary)
{
ReleaseAssert.IsNotNull(jsonDictionary, "JSON dictionary cannot be null.");
ReleaseAssert.IsTrue(jsonDictionary.ContainsKey("AmountConverted"), "Json is missing required field 'AmountConverted'");
ReleaseAssert.IsTrue(jsonDictionary.ContainsKey("ToBalance"), "Json is missing required field 'ToBalance'");
ReleaseAssert.IsTrue(jsonDictionary.ContainsKey("FromBalance"), "Json is missing required field 'FromBalance'");
foreach (KeyValuePair<string, object> entry in jsonDictionary)
{
// Amount Converted
if (entry.Key == "AmountConverted")
{
ReleaseAssert.IsTrue(entry.Value is long, "Invalid serialised type.");
AmountConverted = (int)(long)entry.Value;
}
// To Balance
else if (entry.Key == "ToBalance")
{
ReleaseAssert.IsTrue(entry.Value is IDictionary<string, object>, "Invalid serialised type.");
ToBalance = new CurrencyBalance((IDictionary<string, object>)entry.Value);
}
// From Balance
else if (entry.Key == "FromBalance")
{
ReleaseAssert.IsTrue(entry.Value is IDictionary<string, object>, "Invalid serialised type.");
FromBalance = new CurrencyBalance((IDictionary<string, object>)entry.Value);
}
// An error has occurred.
else
{
#if DEBUG
throw new ArgumentException("Input Json contains an invalid field.");
#endif
}
}
}
}
}
| 39.254717 | 123 | 0.702235 | [
"MIT"
] | ChilliConnect/Samples | UnitySamples/CreatePlayer/Assets/ChilliConnect/GeneratedSource/Responses/ConvertCurrencyResponse.cs | 4,161 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Square;
using Square.Utilities;
namespace Square.Models
{
public class CustomerQuery
{
public CustomerQuery(Models.CustomerFilter filter = null,
Models.CustomerSort sort = null)
{
Filter = filter;
Sort = sort;
}
/// <summary>
/// Represents a set of `CustomerQuery` filters used to limit the set of
/// `Customers` returned by `SearchCustomers`.
/// </summary>
[JsonProperty("filter")]
public Models.CustomerFilter Filter { get; }
/// <summary>
/// Specifies how searched customers profiles are sorted, including the sort key and sort order.
/// </summary>
[JsonProperty("sort")]
public Models.CustomerSort Sort { get; }
public Builder ToBuilder()
{
var builder = new Builder()
.Filter(Filter)
.Sort(Sort);
return builder;
}
public class Builder
{
private Models.CustomerFilter filter;
private Models.CustomerSort sort;
public Builder() { }
public Builder Filter(Models.CustomerFilter value)
{
filter = value;
return this;
}
public Builder Sort(Models.CustomerSort value)
{
sort = value;
return this;
}
public CustomerQuery Build()
{
return new CustomerQuery(filter,
sort);
}
}
}
} | 27.028571 | 105 | 0.52537 | [
"Apache-2.0"
] | okenshields/test-dotnet | Fangkuai/Models/CustomerQuery.cs | 1,892 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.