language
stringclasses
1 value
repo
stringclasses
133 values
path
stringlengths
13
229
class_span
dict
source
stringlengths
14
2.92M
target
stringlengths
1
153
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types.Abstractions/Types/IEnumTypeDefinition.cs
{ "start": 628, "end": 907 }
public interface ____ : IOutputTypeDefinition , IInputTypeDefinition , ISyntaxNodeProvider<EnumTypeDefinitionNode> { /// <summary> /// Gets all possible values if this type. /// </summary> IReadOnlyEnumValueCollection Values { get; } }
IEnumTypeDefinition
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.Catalog/Data/ProductTemplateProductAttributeRepository.cs
{ "start": 315, "end": 780 }
public class ____ : IProductTemplateProductAttributeRepository { private readonly DbContext dbContext; public ProductTemplateProductAttributeRepository(SimplDbContext dbContext) { this.dbContext = dbContext; } public void Remove(ProductTemplateProductAttribute item) { dbContext.Set<ProductTemplateProductAttribute>().Remove(item); } } }
ProductTemplateProductAttributeRepository
csharp
AutoMapper__AutoMapper
src/IntegrationTests/Inheritance/ProjectToAbstractTypeWithInheritance.cs
{ "start": 870, "end": 1074 }
public class ____ { public int Id { get; set; } public int StepId { get; set; } public string Input { get; set; } public virtual Step Step { get; set; } }
StepInput
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/IntegrationTests/CachedMoviesService.cs
{ "start": 695, "end": 881 }
public class ____ : IReturn<MoviesResponse> { [DataMember] public string Genre { get; set; } } [Route("/cached-string/{Id}")]
CachedMoviesWithTimeoutAndRedis
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/Support/Services/FileUploadService.cs
{ "start": 652, "end": 1402 }
public class ____ : IHasResponseStatus { [DataMember] public string Name { get; set; } [DataMember] public string FileName { get; set; } [DataMember] public long ContentLength { get; set; } [DataMember] public string ContentType { get; set; } [DataMember] public string Contents { get; set; } [DataMember] public ResponseStatus ResponseStatus { get; set; } [DataMember] public string CustomerName { get; set; } [DataMember] public int? CustomerId { get; set; } [DataMember] public DateTime? CreatedDate { get; set; } } [Route("/multi-fileuploads", HttpMethods.Post)]
FileUploadResponse
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Data/Mapping/Builders/Catalog/CrossSellProductBuilder.cs
{ "start": 203, "end": 548 }
public partial class ____ : NopEntityBuilder<CrossSellProduct> { #region Methods /// <summary> /// Apply entity configuration /// </summary> /// <param name="table">Create table expression builder</param> public override void MapEntity(CreateTableExpressionBuilder table) { } #endregion }
CrossSellProductBuilder
csharp
smartstore__Smartstore
src/Smartstore.Web/Models/Customers/CustomerDownloadableProductsModel.cs
{ "start": 241, "end": 945 }
public partial class ____ : EntityModelBase { public Guid OrderItemGuid { get; set; } public int OrderId { get; set; } public int ProductId { get; set; } public LocalizedValue<string> ProductName { get; set; } public string ProductSeName { get; set; } public string ProductUrl { get; set; } public string ProductAttributes { get; set; } public int LicenseId { get; set; } public bool IsDownloadAllowed { get; set; } public DateTime CreatedOn { get; set; } public List<DownloadVersion> DownloadVersions { get; set; } = []; } }
DownloadableProductsModel
csharp
microsoft__PowerToys
src/modules/cmdpal/Tests/Microsoft.CmdPal.Ext.Bookmarks.UnitTests/BookmarkResolverTests.cs
{ "start": 531, "end": 3930 }
public partial class ____ { #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. private static string _testDirPath; private static string _userHomeDirPath; private static string _testDirName; #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring as nullable. [ClassInitialize] public static void ClassSetup(TestContext context) { _userHomeDirPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); _testDirName = "CmdPalBookmarkTests" + Guid.NewGuid().ToString("N"); _testDirPath = Path.Combine(_userHomeDirPath, _testDirName); Directory.CreateDirectory(_testDirPath); // test files in user home File.WriteAllText(Path.Combine(_userHomeDirPath, "file.txt"), "This is a test text file."); // test files in test dir File.WriteAllText(Path.Combine(_testDirPath, "file.txt"), "This is a test text file."); File.WriteAllText(Path.Combine(_testDirPath, "app.exe"), "This is a test text file."); } [ClassCleanup] public static void ClassCleanup() { if (Directory.Exists(_testDirPath)) { Directory.Delete(_testDirPath, true); } if (File.Exists(Path.Combine(_userHomeDirPath, "file.txt"))) { File.Delete(Path.Combine(_userHomeDirPath, "file.txt")); } } // must be public static to be used as DataTestMethod data source public static string FromCase(MethodInfo method, object[] data) => data is [PlaceholderClassificationCase c] ? c.Name : $"{method.Name}({string.Join(", ", data.Select(row => row.ToString()))})"; private static async Task RunShared(PlaceholderClassificationCase c) { // Arrange IBookmarkResolver resolver = new BookmarkResolver(new PlaceholderParser()); // Act var classification = await resolver.TryClassifyAsync(c.Input, CancellationToken.None); // Assert Assert.IsNotNull(classification); Assert.AreEqual(c.ExpectSuccess, classification.Success, "Success flag mismatch."); if (c.ExpectSuccess) { Assert.IsNotNull(classification.Result, "Result should not be null for successful classification."); Assert.AreEqual(c.ExpectedKind, classification.Result.Kind, $"CommandKind mismatch for input: {c.Input}"); Assert.AreEqual(c.ExpectedTarget, classification.Result.Target, StringComparer.OrdinalIgnoreCase, $"Target mismatch for input: {c.Input}"); Assert.AreEqual(c.ExpectedLaunch, classification.Result.Launch, $"LaunchMethod mismatch for input: {c.Input}"); Assert.AreEqual(c.ExpectedArguments, classification.Result.Arguments, $"Arguments mismatch for input: {c.Input}"); Assert.AreEqual(c.ExpectedIsPlaceholder, classification.Result.IsPlaceholder, $"IsPlaceholder mismatch for input: {c.Input}"); if (c.ExpectedDisplayName != null) { Assert.AreEqual(c.ExpectedDisplayName, classification.Result.DisplayName, $"DisplayName mismatch for input: {c.Input}"); } } }
BookmarkResolverTests
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.Dapper/Dapper-Extensions/Mapper/ReferenceProperty.cs
{ "start": 718, "end": 2041 }
public class ____<T> : IReferenceProperty<T> { public Guid Identity { get; set; } public Guid ParentIdentity { get; set; } public string Name { get; } public PropertyInfo PropertyInfo { get; } public Type EntityType { get; } public Comparator Comparator { get; private set; } public PropertyKey LeftProperty { get; private set; } public PropertyKey RightProperty { get; private set; } public string ComparatorSignal { get => Comparator.Description(); } public ReferenceProperty(PropertyInfo propertyInfo, Guid parentIdentity, Guid identity) { ParentIdentity = parentIdentity; PropertyInfo = propertyInfo; Name = propertyInfo.Name; EntityType = typeof(T); Identity = identity; } public void SetIdentity(Guid identity) { Identity = identity; } public void SetParentIdentity(Guid identity) { ParentIdentity = identity; } internal void Compare(PropertyKey leftProperty, PropertyKey rightProperty, Comparator comparator) { LeftProperty = leftProperty; RightProperty = rightProperty; Comparator = comparator; } } }
ReferenceProperty
csharp
files-community__Files
src/Files.App/Helpers/Layout/AdaptiveLayoutHelpers.cs
{ "start": 3309, "end": 3509 }
private enum ____ { None, // Don't decide. Another function to decide can be called afterwards if available. Detail, // Apply the layout Detail. Grid, // Apply the layout Grid. } } }
Layouts
csharp
neuecc__MessagePack-CSharp
src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Extension/UnsafeBlitFormatter.cs
{ "start": 5983, "end": 6278 }
public class ____ : UnsafeBlitFormatterBase<Rect, ReverseEndianessHelperSimpleRepeat<float>> { protected override sbyte TypeCode { get { return ReservedExtensionTypeCodes.UnityRect; } } }
RectArrayBlitFormatter
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Services/ShipmentViewModelService.cs
{ "start": 712, "end": 27281 }
public class ____ : IShipmentViewModelService { private readonly ICountryService _countryService; private readonly IDateTimeService _dateTimeService; private readonly IDownloadService _downloadService; private readonly IMeasureService _measureService; private readonly MeasureSettings _measureSettings; private readonly IOrderService _orderService; private readonly IProductService _productService; private readonly IShipmentService _shipmentService; private readonly ShippingProviderSettings _shippingProviderSettings; private readonly IShippingService _shippingService; private readonly ShippingSettings _shippingSettings; private readonly IStockQuantityService _stockQuantityService; private readonly ITranslationService _translationService; private readonly IWarehouseService _warehouseService; private readonly IContextAccessor _contextAccessor; public ShipmentViewModelService( IOrderService orderService, IContextAccessor contextAccessor, IProductService productService, IShipmentService shipmentService, IWarehouseService warehouseService, IMeasureService measureService, IDateTimeService dateTimeService, ICountryService countryService, ITranslationService translationService, IDownloadService downloadService, IShippingService shippingService, IStockQuantityService stockQuantityService, MeasureSettings measureSettings, ShippingSettings shippingSettings, ShippingProviderSettings shippingProviderSettings) { _orderService = orderService; _contextAccessor = contextAccessor; _productService = productService; _shipmentService = shipmentService; _warehouseService = warehouseService; _measureService = measureService; _dateTimeService = dateTimeService; _countryService = countryService; _translationService = translationService; _downloadService = downloadService; _shippingService = shippingService; _stockQuantityService = stockQuantityService; _measureSettings = measureSettings; _shippingSettings = shippingSettings; _shippingProviderSettings = shippingProviderSettings; } public virtual async Task<ShipmentModel> PrepareShipmentModel(Shipment shipment, bool prepareProducts, bool prepareShipmentEvent = false) { //measures var baseWeight = await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId); var baseWeightIn = baseWeight != null ? baseWeight.Name : ""; var baseDimension = await _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId); var baseDimensionIn = baseDimension != null ? baseDimension.Name : ""; var order = await _orderService.GetOrderById(shipment.OrderId); var model = new ShipmentModel { Id = shipment.Id, ShipmentNumber = shipment.ShipmentNumber, OrderId = shipment.OrderId, OrderNumber = order?.OrderNumber ?? 0, OrderCode = order != null ? order.Code : "", TrackingNumber = shipment.TrackingNumber, TotalWeight = shipment.TotalWeight.HasValue ? $"{shipment.TotalWeight:F2} [{baseWeightIn}]" : "", ShippedDate = shipment.ShippedDateUtc.HasValue ? _dateTimeService.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc) : new DateTime?(), ShippedDateUtc = shipment.ShippedDateUtc, CanShip = !shipment.ShippedDateUtc.HasValue, DeliveryDate = shipment.DeliveryDateUtc.HasValue ? _dateTimeService.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc) : new DateTime?(), DeliveryDateUtc = shipment.DeliveryDateUtc, CanDeliver = shipment.ShippedDateUtc.HasValue && !shipment.DeliveryDateUtc.HasValue, AdminComment = shipment.AdminComment, UserFields = shipment.UserFields }; if (prepareProducts) foreach (var shipmentItem in shipment.ShipmentItems) { var orderItem = order?.OrderItems.FirstOrDefault(x => x.Id == shipmentItem.OrderItemId); if (orderItem == null) continue; //quantities var qtyInThisShipment = shipmentItem.Quantity; var maxQtyToAdd = orderItem.OpenQty; var qtyOrdered = shipmentItem.Quantity; var qtyInAllShipments = orderItem.ShipQty; var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId); if (product != null) { var warehouse = await _warehouseService.GetWarehouseById(shipmentItem.WarehouseId); var shipmentItemModel = new ShipmentModel.ShipmentItemModel { Id = shipmentItem.Id, OrderItemId = orderItem.Id, ProductId = orderItem.ProductId, ProductName = product.Name, Sku = product.FormatSku(orderItem.Attributes), AttributeInfo = orderItem.AttributeDescription, ShippedFromWarehouse = warehouse?.Name, ShipSeparately = product.ShipSeparately, ItemWeight = orderItem.ItemWeight.HasValue ? $"{orderItem.ItemWeight:F2} [{baseWeightIn}]" : "", ItemDimensions = $"{product.Length:F2} x {product.Width:F2} x {product.Height:F2} [{baseDimensionIn}]", QuantityOrdered = qtyOrdered, QuantityInThisShipment = qtyInThisShipment, QuantityInAllShipments = qtyInAllShipments, QuantityToAdd = maxQtyToAdd }; model.Items.Add(shipmentItemModel); } } if (prepareShipmentEvent && !string.IsNullOrEmpty(shipment.TrackingNumber)) { var srcm = _shippingService.LoadShippingRateCalculationProviderBySystemName(order?.ShippingRateProviderSystemName); if (srcm != null && srcm.IsShippingRateMethodActive(_shippingProviderSettings)) { var shipmentTracker = srcm.ShipmentTracker; if (shipmentTracker != null) { model.TrackingNumberUrl = await shipmentTracker.GetUrl(shipment.TrackingNumber); if (_shippingSettings.DisplayShipmentEventsToStoreOwner) { var shipmentEvents = await shipmentTracker.GetShipmentEvents(shipment.TrackingNumber); if (shipmentEvents != null) foreach (var shipmentEvent in shipmentEvents) { var shipmentStatusEventModel = new ShipmentModel.ShipmentStatusEventModel(); var shipmentEventCountry = await _countryService.GetCountryByTwoLetterIsoCode(shipmentEvent.CountryCode); shipmentStatusEventModel.Country = shipmentEventCountry != null ? shipmentEventCountry.GetTranslation(x => x.Name, _contextAccessor.WorkContext.WorkingLanguage.Id) : shipmentEvent.CountryCode; shipmentStatusEventModel.Date = shipmentEvent.Date; shipmentStatusEventModel.EventName = shipmentEvent.EventName; shipmentStatusEventModel.Location = shipmentEvent.Location; model.ShipmentStatusEvents.Add(shipmentStatusEventModel); } } } } } return model; } public virtual async Task<int> GetStockQty(Product product, string warehouseId) { var _qty = new List<int>(); foreach (var item in product.BundleProducts) { var p1 = await _productService.GetProductById(item.ProductId); if (p1.UseMultipleWarehouses) { var stock = p1.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId); if (stock != null) _qty.Add(stock.StockQuantity / item.Quantity); } else { _qty.Add(p1.StockQuantity / item.Quantity); } } return _qty.Count > 0 ? _qty.Min() : 0; } public virtual async Task<int> GetReservedQty(Product product, string warehouseId) { var _qty = new List<int>(); foreach (var item in product.BundleProducts) { var p1 = await _productService.GetProductById(item.ProductId); if (p1.UseMultipleWarehouses) { var stock = p1.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId); if (stock != null) _qty.Add(stock.ReservedQuantity / item.Quantity); } } return _qty.Count > 0 ? _qty.Min() : 0; } public virtual async Task<IList<ShipmentModel.ShipmentNote>> PrepareShipmentNotes(Shipment shipment) { //shipment notes var shipmentNoteModels = new List<ShipmentModel.ShipmentNote>(); foreach (var shipmentNote in (await _shipmentService.GetShipmentNotes(shipment.Id)) .OrderByDescending(on => on.CreatedOnUtc)) { var download = await _downloadService.GetDownloadById(shipmentNote.DownloadId); shipmentNoteModels.Add(new ShipmentModel.ShipmentNote { Id = shipmentNote.Id, ShipmentId = shipment.Id, DownloadId = string.IsNullOrEmpty(shipmentNote.DownloadId) ? "" : shipmentNote.DownloadId, DownloadGuid = download?.DownloadGuid ?? Guid.Empty, DisplayToCustomer = shipmentNote.DisplayToCustomer, Note = shipmentNote.Note, CreatedOn = _dateTimeService.ConvertToUserTime(shipmentNote.CreatedOnUtc, DateTimeKind.Utc), CreatedByCustomer = shipmentNote.CreatedByCustomer }); } return shipmentNoteModels; } public virtual async Task InsertShipmentNote(Shipment shipment, string downloadId, bool displayToCustomer, string message) { var shipmentNote = new ShipmentNote { DisplayToCustomer = displayToCustomer, Note = message, DownloadId = downloadId, ShipmentId = shipment.Id }; await _shipmentService.InsertShipmentNote(shipmentNote); //new shipment note notification // TODO } public virtual async Task DeleteShipmentNote(Shipment shipment, string id) { var shipmentNote = (await _shipmentService.GetShipmentNotes(shipment.Id)).FirstOrDefault(on => on.Id == id); if (shipmentNote == null) throw new ArgumentException("No shipment note found with the specified id"); shipmentNote.ShipmentId = shipment.Id; await _shipmentService.DeleteShipmentNote(shipmentNote); //delete an old "attachment" file if (!string.IsNullOrEmpty(shipmentNote.DownloadId)) { var attachment = await _downloadService.GetDownloadById(shipmentNote.DownloadId); if (attachment != null) await _downloadService.DeleteDownload(attachment); } } public virtual async Task<(IEnumerable<Shipment> shipments, int totalCount)> PrepareShipments( ShipmentListModel model, int pageIndex, int pageSize) { DateTime? startDateValue = model.StartDate == null ? null : _dateTimeService.ConvertToUtcTime(model.StartDate.Value, _dateTimeService.CurrentTimeZone); DateTime? endDateValue = model.EndDate == null ? null : _dateTimeService.ConvertToUtcTime(model.EndDate.Value, _dateTimeService.CurrentTimeZone).AddDays(1); //load shipments var shipments = await _shipmentService.GetAllShipments( model.StoreId, model.VendorId, model.WarehouseId, model.CountryId, model.StateProvinceId, model.City, model.TrackingNumber, model.LoadNotShipped, startDateValue, endDateValue, pageIndex - 1, pageSize); return (shipments.ToList(), shipments.TotalCount); } public virtual async Task<ShipmentListModel> PrepareShipmentListModel() { var model = new ShipmentListModel(); //countries model.AvailableCountries.Add(new SelectListItem { Text = "*", Value = "" }); foreach (var c in await _countryService.GetAllCountries(showHidden: true)) model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id }); //states model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "" }); //warehouses model.AvailableWarehouses.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = "" }); foreach (var w in await _warehouseService.GetAllWarehouses()) model.AvailableWarehouses.Add(new SelectListItem { Text = w.Name, Value = w.Id }); return model; } public virtual async Task<ShipmentModel> PrepareShipmentModel(Order order) { var model = new ShipmentModel { OrderId = order.Id, OrderNumber = order.OrderNumber }; //measures var baseWeight = await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId); var baseWeightIn = baseWeight != null ? baseWeight.Name : ""; var baseDimension = await _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId); var baseDimensionIn = baseDimension != null ? baseDimension.Name : ""; foreach (var orderItem in order.OrderItems) { var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId); //we can ship only shippable products if (!product.IsShipEnabled) continue; //quantities var qtyInThisShipment = 0; var maxQtyToAdd = orderItem.OpenQty; var qtyOrdered = orderItem.Quantity; var qtyInAllShipments = orderItem.ShipQty; //ensure that this product can be added to a shipment if (maxQtyToAdd <= 0) continue; var shipmentItemModel = new ShipmentModel.ShipmentItemModel { OrderItemId = orderItem.Id, ProductId = orderItem.ProductId, ProductName = product.Name, WarehouseId = orderItem.WarehouseId, Sku = product.FormatSku(orderItem.Attributes), AttributeInfo = orderItem.AttributeDescription, ShipSeparately = product.ShipSeparately, ItemWeight = orderItem.ItemWeight.HasValue ? $"{orderItem.ItemWeight:F2} [{baseWeightIn}]" : "", ItemDimensions = $"{product.Length:F2} x {product.Width:F2} x {product.Height:F2} [{baseDimensionIn}]", QuantityOrdered = qtyOrdered, QuantityInThisShipment = qtyInThisShipment, QuantityInAllShipments = qtyInAllShipments, QuantityToAdd = maxQtyToAdd }; switch (product.ManageInventoryMethodId) { case ManageInventoryMethod.ManageStock when product.UseMultipleWarehouses: { //multiple warehouses supported shipmentItemModel.AllowToChooseWarehouse = true; foreach (var pwi in product.ProductWarehouseInventory .OrderBy(w => w.WarehouseId).ToList()) { var warehouse = await _warehouseService.GetWarehouseById(pwi.WarehouseId); if (warehouse != null) shipmentItemModel.AvailableWarehouses.Add( new ShipmentModel.ShipmentItemModel.WarehouseInfo { WarehouseId = warehouse.Id, WarehouseName = warehouse.Name, WarehouseCode = warehouse.Code, StockQuantity = pwi.StockQuantity, ReservedQuantity = pwi.ReservedQuantity }); } break; } case ManageInventoryMethod.ManageStock: { //multiple warehouses are not supported var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId); if (warehouse != null) shipmentItemModel.AvailableWarehouses.Add(new ShipmentModel.ShipmentItemModel.WarehouseInfo { WarehouseId = warehouse.Id, WarehouseName = warehouse.Name, WarehouseCode = warehouse.Code, StockQuantity = product.StockQuantity }); break; } case ManageInventoryMethod.ManageStockByAttributes when product.UseMultipleWarehouses: { //multiple warehouses supported shipmentItemModel.AllowToChooseWarehouse = true; var comb = product.FindProductAttributeCombination(orderItem.Attributes); if (comb != null) foreach (var pwi in comb.WarehouseInventory .OrderBy(w => w.WarehouseId).ToList()) { var warehouse = await _warehouseService.GetWarehouseById(pwi.WarehouseId); if (warehouse != null) shipmentItemModel.AvailableWarehouses.Add( new ShipmentModel.ShipmentItemModel.WarehouseInfo { WarehouseId = warehouse.Id, WarehouseName = warehouse.Name, StockQuantity = pwi.StockQuantity, WarehouseCode = warehouse.Code, ReservedQuantity = pwi.ReservedQuantity }); } break; } case ManageInventoryMethod.ManageStockByAttributes: { //multiple warehouses are not supported var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId); if (warehouse != null) shipmentItemModel.AvailableWarehouses.Add(new ShipmentModel.ShipmentItemModel.WarehouseInfo { WarehouseId = warehouse.Id, WarehouseName = warehouse.Name, WarehouseCode = warehouse.Code, StockQuantity = product.StockQuantity }); break; } } if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts) { if (!string.IsNullOrEmpty(orderItem.WarehouseId)) { var warehouse = await _warehouseService.GetWarehouseById(product.WarehouseId); if (warehouse != null) shipmentItemModel.AvailableWarehouses.Add(new ShipmentModel.ShipmentItemModel.WarehouseInfo { WarehouseId = warehouse.Id, WarehouseName = warehouse.Name, WarehouseCode = warehouse.Code, StockQuantity = await GetStockQty(product, orderItem.WarehouseId), ReservedQuantity = await GetReservedQty(product, orderItem.WarehouseId) }); } else { shipmentItemModel.AllowToChooseWarehouse = false; if (shipmentItemModel.AllowToChooseWarehouse) { var warehouses = await _warehouseService.GetAllWarehouses(); foreach (var warehouse in warehouses) shipmentItemModel.AvailableWarehouses.Add( new ShipmentModel.ShipmentItemModel.WarehouseInfo { WarehouseId = warehouse.Id, WarehouseName = warehouse.Name, WarehouseCode = warehouse.Code, StockQuantity = await GetStockQty(product, warehouse.Id), ReservedQuantity = await GetReservedQty(product, warehouse.Id) }); } } } model.Items.Add(shipmentItemModel); } return model; } public virtual async Task<(bool valid, string message)> ValidStockShipment(Shipment shipment) { foreach (var item in shipment.ShipmentItems) { var product = await _productService.GetProductById(item.ProductId); switch (product.ManageInventoryMethodId) { case ManageInventoryMethod.ManageStock: { var stock = _stockQuantityService.GetTotalStockQuantity(product, false, item.WarehouseId); if (stock - item.Quantity < 0) return (false, $"Out of stock for product {product.Name}"); break; } case ManageInventoryMethod.ManageStockByAttributes: { var combination = product.FindProductAttributeCombination(item.Attributes); if (combination == null) return (false, $"Can't find combination for product {product.Name}"); var stock = _stockQuantityService.GetTotalStockQuantityForCombination(product, combination, false, item.WarehouseId); if (stock - item.Quantity < 0) return (false, $"Out of stock for product {product.Name}"); break; } } } return (true, string.Empty); } public virtual async Task<(Shipment shipment, double? totalWeight)> PrepareShipment(Order order, IEnumerable<OrderItem> orderItems, AddShipmentModel model) { Shipment shipment = null; double? totalWeight = null; foreach (var orderItem in orderItems) { //is shippable if (!orderItem.IsShipEnabled) continue; //ensure that this product can be shipped (have at least one item to ship) if (orderItem.OpenQty <= 0) continue; var shipmentItemModel = model.Items.FirstOrDefault(x => x.OrderItemId == orderItem.Id); if (shipmentItemModel == null) continue; var product = await _productService.GetProductById(orderItem.ProductId); var warehouseId = ""; if (product != null && (((product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock || product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes) && product.UseMultipleWarehouses) || product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts)) //multiple warehouses supported //warehouse is chosen by a store owner warehouseId = shipmentItemModel.WarehouseId; else //multiple warehouses are not supported warehouseId = orderItem.WarehouseId; //validate quantity if (shipmentItemModel.QuantityToAdd <= 0) continue; if (shipmentItemModel.QuantityToAdd > orderItem.OpenQty) shipmentItemModel.QuantityToAdd = orderItem.OpenQty; //ok. we have at least one item. create a shipment (if it does not exist) var orderItemTotalWeight = orderItem.ItemWeight * shipmentItemModel.QuantityToAdd; if (orderItemTotalWeight.HasValue) { totalWeight ??= 0; totalWeight += orderItemTotalWeight.Value; } if (shipment == null) { var trackingNumber = model.TrackingNumber; var adminComment = model.AdminComment; shipment = new Shipment { OrderId = order.Id, SeId = order.SeId, TrackingNumber = trackingNumber, TotalWeight = null, ShippedDateUtc = null, DeliveryDateUtc = null, AdminComment = adminComment, StoreId = order.StoreId }; } //create a shipment item var shipmentItem = new ShipmentItem { ProductId = orderItem.ProductId, OrderItemId = orderItem.Id, Quantity = shipmentItemModel.QuantityToAdd, WarehouseId = warehouseId, Attributes = orderItem.Attributes }; shipment.ShipmentItems.Add(shipmentItem); } return (shipment, totalWeight); } }
ShipmentViewModelService
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/ModelBinding/Binders/ComplexTypeModelBinder.cs
{ "start": 20896, "end": 25288 }
struct ____ the Linq's NewExpression // compile fails to construct it. var modelType = bindingContext.ModelType; if (modelType.IsAbstract || modelType.GetConstructor(Type.EmptyTypes) == null) { // If the model is not a top-level object, we can't examine the defined constructor // to evaluate if the non-null property has been set so we do not provide this as a valid // alternative. if (!bindingContext.IsTopLevelObject) { throw new InvalidOperationException(Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForType(modelType.FullName)); } var metadata = bindingContext.ModelMetadata; switch (metadata.MetadataKind) { case ModelMetadataKind.Parameter: throw new InvalidOperationException( Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForParameter( modelType.FullName, metadata.ParameterName)); case ModelMetadataKind.Property: throw new InvalidOperationException( Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForProperty( modelType.FullName, metadata.PropertyName, bindingContext.ModelMetadata.ContainerType.FullName)); case ModelMetadataKind.Type: throw new InvalidOperationException( Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForType( modelType.FullName)); } } _modelCreator = Expression .Lambda<Func<object>>(Expression.New(bindingContext.ModelType)) .Compile(); } return _modelCreator(); } /// <summary> /// Updates a property in the current <see cref="ModelBindingContext.Model"/>. /// </summary> /// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param> /// <param name="modelName">The model name.</param> /// <param name="propertyMetadata">The <see cref="ModelMetadata"/> for the property to set.</param> /// <param name="result">The <see cref="ModelBindingResult"/> for the property's new value.</param> protected virtual void SetProperty( ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result) { ArgumentNullException.ThrowIfNull(bindingContext); ArgumentNullException.ThrowIfNull(modelName); ArgumentNullException.ThrowIfNull(propertyMetadata); if (!result.IsModelSet) { // If we don't have a value, don't set it on the model and trounce a pre-initialized value. return; } if (propertyMetadata.IsReadOnly) { // The property should have already been set when we called BindPropertyAsync, so there's // nothing to do here. return; } var value = result.Model; try { propertyMetadata.PropertySetter(bindingContext.Model, value); } catch (Exception exception) { AddModelError(exception, modelName, bindingContext); } } private static void AddModelError( Exception exception, string modelName, ModelBindingContext bindingContext) { var targetInvocationException = exception as TargetInvocationException; if (targetInvocationException?.InnerException != null) { exception = targetInvocationException.InnerException; } // Do not add an error message if a binding error has already occurred for this property. var modelState = bindingContext.ModelState; var validationState = modelState.GetFieldValidationState(modelName); if (validationState == ModelValidationState.Unvalidated) { modelState.AddModelError(modelName, exception, bindingContext.ModelMetadata); } } private static
as
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Linq/QueryLanguage.Concurrency.cs
{ "start": 303, "end": 1695 }
internal partial class ____ { #region + ObserveOn + public virtual IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, IScheduler scheduler) { return Synchronization.ObserveOn(source, scheduler); } public virtual IObservable<TSource> ObserveOn<TSource>(IObservable<TSource> source, SynchronizationContext context) { return Synchronization.ObserveOn(source, context); } #endregion #region + SubscribeOn + public virtual IObservable<TSource> SubscribeOn<TSource>(IObservable<TSource> source, IScheduler scheduler) { return Synchronization.SubscribeOn(source, scheduler); } public virtual IObservable<TSource> SubscribeOn<TSource>(IObservable<TSource> source, SynchronizationContext context) { return Synchronization.SubscribeOn(source, context); } #endregion #region + Synchronize + public virtual IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source) { return Synchronization.Synchronize(source); } public virtual IObservable<TSource> Synchronize<TSource>(IObservable<TSource> source, object gate) { return Synchronization.Synchronize(source, gate); } #endregion } }
QueryLanguage
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls.ColorPicker/ColorView/ColorView.Properties.cs
{ "start": 171, "end": 19638 }
public partial class ____ { /// <summary> /// Defines the <see cref="Color"/> property. /// </summary> public static readonly StyledProperty<Color> ColorProperty = AvaloniaProperty.Register<ColorView, Color>( nameof(Color), Colors.White, defaultBindingMode: BindingMode.TwoWay, coerce: CoerceColor) ; /// <summary> /// Defines the <see cref="ColorModel"/> property. /// </summary> public static readonly StyledProperty<ColorModel> ColorModelProperty = AvaloniaProperty.Register<ColorView, ColorModel>( nameof(ColorModel), ColorModel.Rgba); /// <summary> /// Defines the <see cref="ColorSpectrumComponents"/> property. /// </summary> public static readonly StyledProperty<ColorSpectrumComponents> ColorSpectrumComponentsProperty = AvaloniaProperty.Register<ColorView, ColorSpectrumComponents>( nameof(ColorSpectrumComponents), ColorSpectrumComponents.HueSaturation); /// <summary> /// Defines the <see cref="ColorSpectrumShape"/> property. /// </summary> public static readonly StyledProperty<ColorSpectrumShape> ColorSpectrumShapeProperty = AvaloniaProperty.Register<ColorView, ColorSpectrumShape>( nameof(ColorSpectrumShape), ColorSpectrumShape.Box); /// <summary> /// Defines the <see cref="HexInputAlphaPosition"/> property. /// </summary> public static readonly StyledProperty<AlphaComponentPosition> HexInputAlphaPositionProperty = AvaloniaProperty.Register<ColorView, AlphaComponentPosition>( nameof(HexInputAlphaPosition), AlphaComponentPosition.Leading); // By default match XAML and the WinUI control /// <summary> /// Defines the <see cref="HsvColor"/> property. /// </summary> public static readonly StyledProperty<HsvColor> HsvColorProperty = AvaloniaProperty.Register<ColorView, HsvColor>( nameof(HsvColor), Colors.White.ToHsv(), defaultBindingMode: BindingMode.TwoWay, coerce: CoerceHsvColor); /// <summary> /// Defines the <see cref="IsAccentColorsVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsAccentColorsVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsAccentColorsVisible), true); /// <summary> /// Defines the <see cref="IsAlphaEnabled"/> property. /// </summary> public static readonly StyledProperty<bool> IsAlphaEnabledProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsAlphaEnabled), true); /// <summary> /// Defines the <see cref="IsAlphaVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsAlphaVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsAlphaVisible), true); /// <summary> /// Defines the <see cref="IsColorComponentsVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsColorComponentsVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsColorComponentsVisible), true); /// <summary> /// Defines the <see cref="IsColorModelVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsColorModelVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsColorModelVisible), true); /// <summary> /// Defines the <see cref="IsColorPaletteVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsColorPaletteVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsColorPaletteVisible), true); /// <summary> /// Defines the <see cref="IsColorPreviewVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsColorPreviewVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsColorPreviewVisible), true); /// <summary> /// Defines the <see cref="IsColorSpectrumVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsColorSpectrumVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsColorSpectrumVisible), true); /// <summary> /// Defines the <see cref="IsColorSpectrumSliderVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsColorSpectrumSliderVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsColorSpectrumSliderVisible), true); /// <summary> /// Defines the <see cref="IsComponentSliderVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsComponentSliderVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsComponentSliderVisible), true); /// <summary> /// Defines the <see cref="IsComponentTextInputVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsComponentTextInputVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsComponentTextInputVisible), true); /// <summary> /// Defines the <see cref="IsHexInputVisible"/> property. /// </summary> public static readonly StyledProperty<bool> IsHexInputVisibleProperty = AvaloniaProperty.Register<ColorView, bool>( nameof(IsHexInputVisible), true); /// <summary> /// Defines the <see cref="MaxHue"/> property. /// </summary> public static readonly StyledProperty<int> MaxHueProperty = AvaloniaProperty.Register<ColorView, int>( nameof(MaxHue), 359); /// <summary> /// Defines the <see cref="MaxSaturation"/> property. /// </summary> public static readonly StyledProperty<int> MaxSaturationProperty = AvaloniaProperty.Register<ColorView, int>( nameof(MaxSaturation), 100); /// <summary> /// Defines the <see cref="MaxValue"/> property. /// </summary> public static readonly StyledProperty<int> MaxValueProperty = AvaloniaProperty.Register<ColorView, int>( nameof(MaxValue), 100); /// <summary> /// Defines the <see cref="MinHue"/> property. /// </summary> public static readonly StyledProperty<int> MinHueProperty = AvaloniaProperty.Register<ColorView, int>( nameof(MinHue), 0); /// <summary> /// Defines the <see cref="MinSaturation"/> property. /// </summary> public static readonly StyledProperty<int> MinSaturationProperty = AvaloniaProperty.Register<ColorView, int>( nameof(MinSaturation), 0); /// <summary> /// Defines the <see cref="MinValue"/> property. /// </summary> public static readonly StyledProperty<int> MinValueProperty = AvaloniaProperty.Register<ColorView, int>( nameof(MinValue), 0); /// <summary> /// Defines the <see cref="PaletteColors"/> property. /// </summary> public static readonly StyledProperty<IEnumerable<Color>?> PaletteColorsProperty = AvaloniaProperty.Register<ColorView, IEnumerable<Color>?>( nameof(PaletteColors), null); /// <summary> /// Defines the <see cref="PaletteColumnCount"/> property. /// </summary> public static readonly StyledProperty<int> PaletteColumnCountProperty = AvaloniaProperty.Register<ColorView, int>( nameof(PaletteColumnCount), 4); /// <summary> /// Defines the <see cref="Palette"/> property. /// </summary> public static readonly StyledProperty<IColorPalette?> PaletteProperty = AvaloniaProperty.Register<ColorView, IColorPalette?>( nameof(Palette), null); /// <summary> /// Defines the <see cref="SelectedIndex"/> property. /// </summary> public static readonly StyledProperty<int> SelectedIndexProperty = AvaloniaProperty.Register<ColorView, int>( nameof(SelectedIndex), (int)ColorViewTab.Spectrum); /// <inheritdoc cref="ColorSpectrum.Color"/> public Color Color { get => GetValue(ColorProperty); set => SetValue(ColorProperty, value); } /// <inheritdoc cref="ColorSlider.ColorModel"/> /// <remarks> /// This property is only applicable to the components tab. /// The spectrum tab must always be in HSV and the palette tab contains only pre-defined colors. /// </remarks> public ColorModel ColorModel { get => GetValue(ColorModelProperty); set => SetValue(ColorModelProperty, value); } /// <inheritdoc cref="ColorSpectrum.Components"/> public ColorSpectrumComponents ColorSpectrumComponents { get => GetValue(ColorSpectrumComponentsProperty); set => SetValue(ColorSpectrumComponentsProperty, value); } /// <inheritdoc cref="ColorSpectrum.Shape"/> public ColorSpectrumShape ColorSpectrumShape { get => GetValue(ColorSpectrumShapeProperty); set => SetValue(ColorSpectrumShapeProperty, value); } /// <summary> /// Gets or sets the position of the alpha component in the hexadecimal input box relative to /// all other color components. /// </summary> public AlphaComponentPosition HexInputAlphaPosition { get => GetValue(HexInputAlphaPositionProperty); set => SetValue(HexInputAlphaPositionProperty, value); } /// <inheritdoc cref="ColorSpectrum.HsvColor"/> public HsvColor HsvColor { get => GetValue(HsvColorProperty); set => SetValue(HsvColorProperty, value); } /// <inheritdoc cref="ColorPreviewer.IsAccentColorsVisible"/> public bool IsAccentColorsVisible { get => GetValue(IsAccentColorsVisibleProperty); set => SetValue(IsAccentColorsVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the alpha component is enabled. /// When disabled (set to false) the alpha component will be fixed to maximum and /// editing controls disabled. /// </summary> public bool IsAlphaEnabled { get => GetValue(IsAlphaEnabledProperty); set => SetValue(IsAlphaEnabledProperty, value); } /// <summary> /// Gets or sets a value indicating whether the alpha component editing controls /// (Slider(s) and TextBox) are visible. When hidden, the existing alpha component /// value is maintained. /// </summary> /// <remarks> /// Note that <see cref="IsComponentTextInputVisible"/> also controls the alpha /// component TextBox visibility. /// </remarks> public bool IsAlphaVisible { get => GetValue(IsAlphaVisibleProperty); set => SetValue(IsAlphaVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the color components tab/panel/page (subview) is visible. /// </summary> public bool IsColorComponentsVisible { get => GetValue(IsColorComponentsVisibleProperty); set => SetValue(IsColorComponentsVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the active color model indicator/selector is visible. /// </summary> public bool IsColorModelVisible { get => GetValue(IsColorModelVisibleProperty); set => SetValue(IsColorModelVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the color palette tab/panel/page (subview) is visible. /// </summary> public bool IsColorPaletteVisible { get => GetValue(IsColorPaletteVisibleProperty); set => SetValue(IsColorPaletteVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the color preview is visible. /// </summary> /// <remarks> /// Note that accent color visibility is controlled separately by /// <see cref="IsAccentColorsVisible"/>. /// </remarks> public bool IsColorPreviewVisible { get => GetValue(IsColorPreviewVisibleProperty); set => SetValue(IsColorPreviewVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the color spectrum tab/panel/page (subview) is visible. /// </summary> public bool IsColorSpectrumVisible { get => GetValue(IsColorSpectrumVisibleProperty); set => SetValue(IsColorSpectrumVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the color spectrum's third component slider /// is visible. /// </summary> public bool IsColorSpectrumSliderVisible { get => GetValue(IsColorSpectrumSliderVisibleProperty); set => SetValue(IsColorSpectrumSliderVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether color component sliders are visible. /// </summary> /// <remarks> /// All color components are controlled by this property but alpha can also be /// controlled with <see cref="IsAlphaVisible"/>. /// </remarks> public bool IsComponentSliderVisible { get => GetValue(IsComponentSliderVisibleProperty); set => SetValue(IsComponentSliderVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether color component text inputs are visible. /// </summary> /// <remarks> /// All color components are controlled by this property but alpha can also be /// controlled with <see cref="IsAlphaVisible"/>. /// </remarks> public bool IsComponentTextInputVisible { get => GetValue(IsComponentTextInputVisibleProperty); set => SetValue(IsComponentTextInputVisibleProperty, value); } /// <summary> /// Gets or sets a value indicating whether the hexadecimal color value text input /// is visible. /// </summary> public bool IsHexInputVisible { get => GetValue(IsHexInputVisibleProperty); set => SetValue(IsHexInputVisibleProperty, value); } /// <inheritdoc cref="ColorSpectrum.MaxHue"/> public int MaxHue { get => GetValue(MaxHueProperty); set => SetValue(MaxHueProperty, value); } /// <inheritdoc cref="ColorSpectrum.MaxSaturation"/> public int MaxSaturation { get => GetValue(MaxSaturationProperty); set => SetValue(MaxSaturationProperty, value); } /// <inheritdoc cref="ColorSpectrum.MaxValue"/> public int MaxValue { get => GetValue(MaxValueProperty); set => SetValue(MaxValueProperty, value); } /// <inheritdoc cref="ColorSpectrum.MinHue"/> public int MinHue { get => GetValue(MinHueProperty); set => SetValue(MinHueProperty, value); } /// <inheritdoc cref="ColorSpectrum.MinSaturation"/> public int MinSaturation { get => GetValue(MinSaturationProperty); set => SetValue(MinSaturationProperty, value); } /// <inheritdoc cref="ColorSpectrum.MinValue"/> public int MinValue { get => GetValue(MinValueProperty); set => SetValue(MinValueProperty, value); } /// <summary> /// Gets or sets the collection of individual colors in the palette. /// </summary> /// <remarks> /// This is not commonly set manually. Instead, it should be set automatically by /// providing an <see cref="IColorPalette"/> to the <see cref="Palette"/> property. /// <br/><br/> /// Also note that this property is what should be bound in the control template. /// <see cref="Palette"/> is too high-level to use on its own. /// </remarks> public IEnumerable<Color>? PaletteColors { get => GetValue(PaletteColorsProperty); set => SetValue(PaletteColorsProperty, value); } /// <summary> /// Gets or sets the number of colors in each row (section) of the color palette. /// Within a standard palette, rows are shades and columns are colors. /// </summary> /// <remarks> /// This is not commonly set manually. Instead, it should be set automatically by /// providing an <see cref="IColorPalette"/> to the <see cref="Palette"/> property. /// <br/><br/> /// Also note that this property is what should be bound in the control template. /// <see cref="Palette"/> is too high-level to use on its own. /// </remarks> public int PaletteColumnCount { get => GetValue(PaletteColumnCountProperty); set => SetValue(PaletteColumnCountProperty, value); } /// <summary> /// Gets or sets the color palette. /// </summary> /// <remarks> /// This will automatically set both <see cref="PaletteColors"/> and /// <see cref="PaletteColumnCount"/> overwriting any existing values. /// </remarks> public IColorPalette? Palette { get => GetValue(PaletteProperty); set => SetValue(PaletteProperty, value); } /// <summary> /// Gets or sets the index of the selected tab/panel/page (subview). /// </summary> /// <remarks> /// When using the default control theme, this property is designed to be used with the /// <see cref="ColorViewTab"/> enum. The <see cref="ColorViewTab"/>
ColorView
csharp
dotnet__orleans
src/AWS/Orleans.Reminders.DynamoDB/Reminders/DynamoDBReminderTable.cs
{ "start": 16879, "end": 19216 }
struct ____(Dictionary<string, AttributeValue> keys) { public override string ToString() => Utils.DictionaryToString(keys); } [LoggerMessage( EventId = (int)ErrorCode.ReminderServiceBase, Level = LogLevel.Warning, Message = "Intermediate error reading reminder entry {Keys} from table {TableName}." )] private static partial void LogWarningReadReminderEntry(ILogger logger, Exception exception, DictionaryLogRecord keys, string tableName); [LoggerMessage( EventId = (int)ErrorCode.ReminderServiceBase, Level = LogLevel.Warning, Message = "Intermediate error reading reminder entry {Entries} from table {TableName}." )] private static partial void LogWarningReadReminderEntries(ILogger logger, Exception exception, DictionaryLogRecord entries, string tableName); [LoggerMessage( EventId = (int)ErrorCode.ReminderServiceBase, Level = LogLevel.Warning, Message = "Intermediate error reading reminder entry {ExpressionValues} from table {TableName}." )] private static partial void LogWarningReadReminderEntryRange(ILogger logger, Exception exception, DictionaryLogRecord expressionValues, string tableName); [LoggerMessage( EventId = (int)ErrorCode.ReminderServiceBase, Level = LogLevel.Warning, Message = "Intermediate error removing reminder entries {Entries} from table {TableName}." )] private static partial void LogWarningRemoveReminderEntries(ILogger logger, Exception exception, DictionaryLogRecord entries, string tableName); [LoggerMessage( Level = LogLevel.Debug, Message = "UpsertRow entry = {Entry}, etag = {ETag}" )] private static partial void LogDebugUpsertRow(ILogger logger, ReminderEntry entry, string eTag); [LoggerMessage( EventId = (int)ErrorCode.ReminderServiceBase, Level = LogLevel.Warning, Message = "Intermediate error updating entry {Entry} to the table {TableName}." )] private static partial void LogWarningUpdateReminderEntry(ILogger logger, Exception exception, ReminderEntry entry, string tableName); } }
DictionaryLogRecord
csharp
dotnet__orleans
src/api/Orleans.Transactions.TestKit.Base/Orleans.Transactions.TestKit.Base.cs
{ "start": 262395, "end": 264558 }
partial class ____ : global::Orleans.Serialization.Codecs.IFieldCodec<global::Orleans.Transactions.TestKit.TransactionAttributionGrainExtensions.SuppressAttributionGrain>, global::Orleans.Serialization.Codecs.IFieldCodec, global::Orleans.Serialization.Serializers.IBaseCodec<global::Orleans.Transactions.TestKit.TransactionAttributionGrainExtensions.SuppressAttributionGrain>, global::Orleans.Serialization.Serializers.IBaseCodec { public Codec_SuppressAttributionGrain(global::Orleans.Serialization.Activators.IActivator<global::Orleans.Transactions.TestKit.TransactionAttributionGrainExtensions.SuppressAttributionGrain> _activator, global::Orleans.Serialization.Serializers.ICodecProvider codecProvider) { } public void Deserialize<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Transactions.TestKit.TransactionAttributionGrainExtensions.SuppressAttributionGrain instance) { } public global::Orleans.Transactions.TestKit.TransactionAttributionGrainExtensions.SuppressAttributionGrain ReadValue<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Serialization.WireProtocol.Field field) { throw null; } public void Serialize<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, global::Orleans.Transactions.TestKit.TransactionAttributionGrainExtensions.SuppressAttributionGrain instance) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } public void WriteField<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, global::Orleans.Transactions.TestKit.TransactionAttributionGrainExtensions.SuppressAttributionGrain value) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } } [System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public sealed
Codec_SuppressAttributionGrain
csharp
abpframework__abp
framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/ICurrentPrincipalAccessor.cs
{ "start": 83, "end": 221 }
public interface ____ { ClaimsPrincipal Principal { get; } IDisposable Change(ClaimsPrincipal principal); }
ICurrentPrincipalAccessor
csharp
duplicati__duplicati
Duplicati/Library/Common/IO/PosixFile.cs
{ "start": 10737, "end": 14713 }
public struct ____ { public readonly long UID; public readonly long GID; public readonly long Permissions; public readonly string OwnerName; public readonly string GroupName; internal FileInfo(Mono.Unix.UnixFileSystemInfo fse) { UID = fse.OwnerUserId; GID = fse.OwnerGroupId; Permissions = (long)fse.FileAccessPermissions; try { OwnerName = fse.OwnerUser.UserName; } catch (ArgumentException) { // Could not retrieve user name, possibly the user is not defined on the local system OwnerName = null; } try { GroupName = fse.OwnerGroup.GroupName; } catch (ArgumentException) { // Could not retrieve group name, possibly the group is not defined on the local system GroupName = null; } } } /// <summary> /// Gets the basic user/group/perm tuplet for a file or folder /// </summary> /// <returns>The basic user/group/perm tuplet for a file or folder</returns> /// <param name="path">The full path to look up</param> public static FileInfo GetUserGroupAndPermissions(string path) { return new FileInfo(Mono.Unix.UnixFileInfo.GetFileSystemEntry(path)); } /// <summary> /// Sets the basic user/group/perm tuplet for a file or folder /// </summary> /// <param name="path">The full path to look up</param> /// <param name="uid">The owner user id to set</param> /// <param name="gid">The owner group id to set</param> /// <param name="permissions">The file access permissions to set</param> public static void SetUserGroupAndPermissions(string path, long uid, long gid, long permissions) { Mono.Unix.UnixFileInfo.GetFileSystemEntry(path).SetOwner(uid, gid); Mono.Unix.UnixFileInfo.GetFileSystemEntry(path).FileAccessPermissions = (Mono.Unix.FileAccessPermissions)permissions; } /// <summary> /// Gets the UID from a user name /// </summary> /// <returns>The user ID.</returns> /// <param name="name">The user name.</param> public static long GetUserID(string name) { return new Mono.Unix.UnixUserInfo(name).UserId; } /// <summary> /// Gets the GID from a group name /// </summary> /// <returns>The user ID.</returns> /// <param name="name">The group name.</param> public static long GetGroupID(string name) { return new Mono.Unix.UnixGroupInfo(name).GroupId; } /// <summary> /// Gets the number of hard links for a file /// </summary> /// <returns>The hardlink count</returns> /// <param name="path">The full path to look up</param> public static long GetHardlinkCount(string path) { var fse = Mono.Unix.UnixFileInfo.GetFileSystemEntry(path); if (fse.IsRegularFile || fse.IsDirectory) return fse.LinkCount; else return 0; } /// <summary> /// Gets a unique ID for the path inode target, /// which is the device ID and inode ID /// joined with a &quot;:&quot; /// </summary> /// <returns>The inode target ID.</returns> /// <param name="path">The full path to look up</param> public static string GetInodeTargetID(string path) { var fse = Mono.Unix.UnixFileInfo.GetFileSystemEntry(path); return fse.Device + ":" + fse.Inode; } } }
FileInfo
csharp
dotnet__aspnetcore
src/Shared/test/Shared.Tests/PropertyHelperTest.cs
{ "start": 22079, "end": 22165 }
private class ____ : Point { public int Z { get; set; } }
ThreeDPoint
csharp
protobuf-net__protobuf-net
src/protobuf-net.FSharp/FSharpSetSerializer.cs
{ "start": 1651, "end": 1901 }
public static class ____ { /// <summary>Create a map serializer that operates on FSharp Maps</summary> public static RepeatedSerializer<FSharpSet<T>, T> Create<T>() => new FSharpSetSerializer<T>(); } }
FSharpSetFactory
csharp
ServiceStack__ServiceStack
ServiceStack/tests/CheckWeb/SwaggerTestService.cs
{ "start": 7163, "end": 7656 }
public sealed class ____ : ApiResponseAttribute { private static int errCode = 402; public CustomApiResponseAttribute() : base(++errCode, Guid.NewGuid().ToString()) {} } [ApiResponse(400, "Code 1")] [CustomApiResponse()] [ApiResponse(402, "Code 2")] [CustomApiResponse()] [CustomApiResponse()] [ApiResponse(401, "Code 3")] [Route("/swagger/multiattrtest", Verbs = "POST", Summary = "Sample request")]
CustomApiResponseAttribute
csharp
ServiceStack__ServiceStack
ServiceStack/tests/NorthwindBlazor/Migrations/20240109034115_CreateIdentitySchema.Designer.cs
{ "start": 407, "end": 10116 }
partial class ____ { /// <inheritdoc /> protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder.HasAnnotation("ProductVersion", "8.0.0"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("TEXT"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex"); b.ToTable("AspNetRoles", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("TEXT"); b.Property<string>("ProviderKey") .HasColumnType("TEXT"); b.Property<string>("ProviderDisplayName") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("RoleId") .HasColumnType("TEXT"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("LoginProvider") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<string>("Value") .HasColumnType("TEXT"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens", (string)null); }); modelBuilder.Entity("MyApp.Data.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("TEXT"); b.Property<int>("AccessFailedCount") .HasColumnType("INTEGER"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("DisplayName") .HasColumnType("TEXT"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<bool>("EmailConfirmed") .HasColumnType("INTEGER"); b.Property<string>("FirstName") .HasColumnType("TEXT"); b.Property<string>("LastName") .HasColumnType("TEXT"); b.Property<bool>("LockoutEnabled") .HasColumnType("INTEGER"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("TEXT"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("TEXT"); b.Property<string>("PasswordHash") .HasColumnType("TEXT"); b.Property<string>("PhoneNumber") .HasColumnType("TEXT"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("INTEGER"); b.Property<string>("ProfileUrl") .HasColumnType("TEXT"); b.Property<string>("RefreshToken") .HasColumnType("TEXT"); b.Property<DateTime?>("RefreshTokenExpiry") .HasColumnType("TEXT"); b.Property<string>("SecurityStamp") .HasColumnType("TEXT"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("INTEGER"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex"); b.ToTable("AspNetUsers", (string)null); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("MyApp.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("MyApp.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("MyApp.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("MyApp.Data.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
CreateIdentitySchema
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Transforms/TypeConverting.cs
{ "start": 1713, "end": 2709 }
internal static class ____ { [TlcModule.EntryPoint(Name = "Transforms.ColumnTypeConverter", Desc = TypeConvertingTransformer.Summary, UserName = TypeConvertingTransformer.UserName, ShortName = TypeConvertingTransformer.ShortName)] public static CommonOutputs.TransformOutput Convert(IHostEnvironment env, TypeConvertingTransformer.Options input) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(input, nameof(input)); var h = EntryPointUtils.CheckArgsAndCreateHost(env, "Convert", input); var view = TypeConvertingTransformer.Create(h, input, input.Data); return new CommonOutputs.TransformOutput() { Model = new TransformModelImpl(h, view, input.Data), OutputData = view }; } } /// <summary> /// <see cref="ITransformer"/> resulting from fitting a <see cref="TypeConvertingEstimator"/>. /// </summary>
TypeConversion
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Razor/Html/AntiXsrf/AntiForgeryToken.cs
{ "start": 364, "end": 1589 }
internal sealed class ____ { internal const int SecurityTokenBitLength = 128; internal const int ClaimUidBitLength = 256; private string _additionalData; private BinaryBlob _securityToken; private string _username; public string AdditionalData { get { return _additionalData ?? String.Empty; } set { _additionalData = value; } } public BinaryBlob ClaimUid { get; set; } public bool IsSessionToken { get; set; } public BinaryBlob SecurityToken { get { if (_securityToken == null) { _securityToken = new BinaryBlob(SecurityTokenBitLength); } return _securityToken; } set { _securityToken = value; } } public string Username { get { return _username ?? String.Empty; } set { _username = value; } } } } #endif
AntiForgeryToken
csharp
nuke-build__nuke
source/Nuke.Build/ParameterAttribute.cs
{ "start": 3143, "end": 3338 }
public class ____ : Attribute { public ParameterPrefixAttribute(string prefix) { Prefix = prefix.TrimEnd("Prefix"); } public string Prefix { get; } }
ParameterPrefixAttribute
csharp
dotnet__aspnetcore
src/Components/Endpoints/src/FormMapping/Factories/ComplexTypeConverterFactory.cs
{ "start": 485, "end": 4261 }
internal class ____(FormDataMapperOptions options, ILoggerFactory loggerFactory) : IFormDataConverterFactory { internal FormDataMetadataFactory MetadataFactory { get; } = new FormDataMetadataFactory(options.Factories, loggerFactory); [RequiresDynamicCode(FormMappingHelpers.RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(FormMappingHelpers.RequiresUnreferencedCodeMessage)] public bool CanConvert(Type type, FormDataMapperOptions options) { // Create the metadata for the type. This walks the graph and creates metadata for all the types // in the reference graph, detecting and identifying recursive types. var metadata = MetadataFactory.GetOrCreateMetadataFor(type, options); // If we can create metadata for the type, then we can convert it. return metadata != null; } // We are going to compile a function that maps all the properties for the type. // Beware that the code below is not the actual exact code, just a simplification to understand what is happening at a high level. // The general flow is as follows. For a type like Address { Street, City, CountryRegion, ZipCode } // we will generate a function that looks like: // public bool TryRead(ref FormDataReader reader, Type type, FormDataSerializerOptions options, out Address? result, out bool found) // { // bool foundProperty; // bool succeeded = true; // string street; // string city; // string countryRegion; // string zipCode; // FormDataConveter<string> streetConverter; // FormDataConveter<string> cityConverter; // FormDataConveter<string> countryRegionConverter; // FormDataConveter<string> zipCodeConverter; // var streetConverter = options.ResolveConverter(typeof(string)); // reader.PushPrefix("Street"); // succeeded &= streetConverter.TryRead(ref reader, typeof(string), options, out street, out foundProperty); // found ||= foundProperty; // reader.PopPrefix("Street"); // // var cityConverter = options.ResolveConverter(typeof(string)); // reader.PushPrefix("City"); // succeeded &= ciryConverter.TryRead(ref reader, typeof(string), options, out street, out foundProperty); // found ||= foundProperty; // reader.PopPrefix("City"); // // var countryRegionConverter = options.ResolveConverter(typeof(string)); // reader.PushPrefix("CountryRegion"); // succeeded &= countryRegionConverter.TryRead(ref reader, typeof(string), options, out street, out foundProperty); // found ||= foundProperty; // reader.PopPrefix("CountryRegion"); // // var zipCodeConverter = options.ResolveConverter(typeof(string)); // reader.PushPrefix("ZipCode"); // succeeded &= zipCodeConverter.TryRead(ref reader, typeof(string), options, out street, out foundProperty); // found ||= foundProperty; // reader.PopPrefix("ZipCode"); // // if(found) // { // result = new Address(); // result.Street = street; // result.City = city; // result.CountryRegion = countryRegion; // result.ZipCode = zipCode; // } // else // { // result = null; // } // // return succeeded; // } // // The actual blocks above are going to be generated using System.Linq.Expressions. // Instead of resolving the property converters every time, we might consider caching the converters in a dictionary and passing an // extra parameter to the function with them in it. // The final converter is something like //
ComplexTypeConverterFactory
csharp
Cysharp__ZLogger
src/ZLogger/ZLoggerInterpolatedStringHandler.cs
{ "start": 15376, "end": 17976 }
struct ____ : IEquatable<LiteralList> { readonly List<string?> literals; public LiteralList(List<string?> literals) { this.literals = literals; } #if NET8_0_OR_GREATER // literals are all const string, in .NET 8 it is allocated in Non-GC Heap so can compare by address. // https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-8/#non-gc-heap static ReadOnlySpan<byte> AsBytes(ReadOnlySpan<string?> literals) { return MemoryMarshal.CreateSpan( ref Unsafe.As<string?, byte>(ref MemoryMarshal.GetReference(literals)), literals.Length * Unsafe.SizeOf<string>()); } public override int GetHashCode() { return unchecked((int)XxHash3.HashToUInt64(AsBytes(CollectionsMarshal.AsSpan(literals)))); } public bool Equals(LiteralList other) { var xs = CollectionsMarshal.AsSpan(literals); var ys = CollectionsMarshal.AsSpan(other.literals); return AsBytes(xs).SequenceEqual(AsBytes(ys)); } #else [ThreadStatic] static XxHash3? xxhash; public override int GetHashCode() { var h = xxhash; if (h == null) { h = xxhash = new XxHash3(); } else { h.Reset(); } var span = CollectionsMarshal.AsSpan(literals); foreach (var item in span) { h.Append(MemoryMarshal.AsBytes(item.AsSpan())); } // https://github.com/Cyan4973/xxHash/issues/453 // XXH3 64bit -> 32bit, okay to simple cast answered by XXH3 author. return unchecked((int)h.GetCurrentHashAsUInt64()); } public bool Equals(LiteralList other) { var xs = CollectionsMarshal.AsSpan(literals); var ys = CollectionsMarshal.AsSpan(other.literals); if (xs.Length == ys.Length) { for (int i = 0; i < xs.Length; i++) { if (xs[i] != ys[i]) return false; } return true; } return false; } #endif } } internal readonly
LiteralList
csharp
duplicati__duplicati
Duplicati/Library/Snapshots/MacOS/MacOSPhotosNative.cs
{ "start": 9040, "end": 10322 }
private struct ____ { /// <summary> /// The unique identifier of the asset /// </summary> internal IntPtr Identifier; /// <summary> /// The original file name /// </summary> internal IntPtr FileName; /// <summary> /// The Uniform Type Identifier of the asset /// </summary> internal IntPtr UniformTypeIdentifier; /// <summary> /// The size of the asset in bytes /// </summary> internal long Size; /// <summary> /// The media type of the asset /// </summary> internal int MediaType; /// <summary> /// The pixel width of the asset /// </summary> internal int PixelWidth; /// <summary> /// The pixel height of the asset /// </summary> internal int PixelHeight; /// <summary> /// The creation time in seconds since Unix epoch /// </summary> internal double CreationSeconds; /// <summary> /// The modification time in seconds since Unix epoch /// </summary> internal double ModificationSeconds; } /// <summary> /// Safe handle for a Photos asset /// </summary>
NativeAssetNative
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/DynamicEntityProperties/Extensions/DynamicEntityPropertyManagerExtensions.cs
{ "start": 148, "end": 4090 }
public static class ____ { public static List<DynamicEntityProperty> GetAll<TEntity, TPrimaryKey>(this IDynamicEntityPropertyManager manager) where TEntity : IEntity<TPrimaryKey> { return manager.GetAll(entityFullName: typeof(TEntity).FullName); } public static List<DynamicEntityProperty> GetAll<TEntity>(this IDynamicEntityPropertyManager manager) where TEntity : IEntity<int> { return manager.GetAll<TEntity, int>(); } public static Task<List<DynamicEntityProperty>> GetAllAsync<TEntity, TPrimaryKey>(this IDynamicEntityPropertyManager manager) where TEntity : IEntity<TPrimaryKey> { return manager.GetAllAsync(entityFullName: typeof(TEntity).FullName); } public static Task<List<DynamicEntityProperty>> GetAllAsync<TEntity>(this IDynamicEntityPropertyManager manager) where TEntity : IEntity<int> { return manager.GetAllAsync<TEntity, int>(); } public static DynamicEntityProperty Add<TEntity>(this IDynamicEntityPropertyManager manager, int dynamicPropertyId, int? tenantId) where TEntity : IEntity<int> { return manager.Add<TEntity, int>(dynamicPropertyId, tenantId); } public static DynamicEntityProperty Add<TEntity, TPrimaryKey>(this IDynamicEntityPropertyManager manager, int dynamicPropertyId, int? tenantId) where TEntity : IEntity<TPrimaryKey> { var entity = new DynamicEntityProperty() { DynamicPropertyId = dynamicPropertyId, EntityFullName = typeof(TEntity).FullName, TenantId = tenantId }; manager.Add(entity); return entity; } public static Task<DynamicEntityProperty> AddAsync<TEntity>(this IDynamicEntityPropertyManager manager, int dynamicPropertyId, int? tenantId) where TEntity : IEntity<int> { return manager.AddAsync<TEntity, int>(dynamicPropertyId, tenantId); } public static async Task<DynamicEntityProperty> AddAsync<TEntity, TPrimaryKey>(this IDynamicEntityPropertyManager manager, int dynamicPropertyId, int? tenantId) where TEntity : IEntity<TPrimaryKey> { var entity = new DynamicEntityProperty() { DynamicPropertyId = dynamicPropertyId, EntityFullName = typeof(TEntity).FullName, TenantId = tenantId }; await manager.AddAsync(entity); return entity; } public static DynamicEntityProperty Add<TEntity>(this IDynamicEntityPropertyManager manager, DynamicProperty dynamicProperty, int? tenantId) where TEntity : IEntity<int> { return manager.Add<TEntity>(dynamicProperty.Id, tenantId); } public static DynamicEntityProperty Add<TEntity, TPrimaryKey>(this IDynamicEntityPropertyManager manager, DynamicProperty dynamicProperty, int? tenantId) where TEntity : IEntity<TPrimaryKey> { return manager.Add<TEntity, TPrimaryKey>(dynamicProperty.Id, tenantId); } public static Task<DynamicEntityProperty> AddAsync<TEntity>(this IDynamicEntityPropertyManager manager, DynamicProperty dynamicProperty, int? tenantId) where TEntity : IEntity<int> { return manager.AddAsync<TEntity>(dynamicProperty.Id, tenantId); } public static Task<DynamicEntityProperty> AddAsync<TEntity, TPrimaryKey>(this IDynamicEntityPropertyManager manager, DynamicProperty dynamicProperty, int? tenantId) where TEntity : IEntity<TPrimaryKey> { return manager.AddAsync<TEntity, TPrimaryKey>(dynamicProperty.Id, tenantId); } } }
DynamicEntityPropertyManagerExtensions
csharp
OrchardCMS__OrchardCore
test/OrchardCore.Tests/Modules/OrchardCore.ContentFields/Settings/DisplayDriverTestHelper.cs
{ "start": 391, "end": 2095 }
public class ____ { public static ContentPartDefinition GetContentPartDefinition<TField>(Action<ContentPartFieldDefinitionBuilder> configuration) { return new ContentPartDefinitionBuilder() .Named("SomeContentPart") .WithField<TField>("SomeField", configuration) .Build(); } public static Task<ShapeResult> GetShapeResultAsync(IContentPartFieldDefinitionDisplayDriver driver, IShapeFactory factory, ContentPartDefinition contentDefinition) => GetShapeResultAsync(factory, contentDefinition, driver); public static Task<ShapeResult> GetShapeResultAsync<TDriver>(IShapeFactory factory, ContentPartDefinition contentDefinition) where TDriver : IContentPartFieldDefinitionDisplayDriver, new() => GetShapeResultAsync(factory, contentDefinition, new TDriver()); public static async Task<ShapeResult> GetShapeResultAsync(IShapeFactory factory, ContentPartDefinition contentDefinition, IContentPartFieldDefinitionDisplayDriver driver) { var partFieldDefinition = contentDefinition.Fields.First(); var partFieldDefinitionShape = await factory.CreateAsync("ContentPartFieldDefinition_Edit", () => ValueTask.FromResult<IShape>(new ZoneHolding(() => factory.CreateAsync("ContentZone")))); partFieldDefinitionShape.Properties["ContentField"] = partFieldDefinition; var editorContext = new BuildEditorContext(partFieldDefinitionShape, "", false, "", factory, null, null); var result = await driver.BuildEditorAsync(partFieldDefinition, editorContext); await result.ApplyAsync(editorContext); return (ShapeResult)result; } }
DisplayDriverTestHelper
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.Input.GazeInteraction/LowpassFilter.cs
{ "start": 397, "end": 967 }
internal class ____ { public LowpassFilter() { Previous = new Point(0, 0); } public LowpassFilter(Point initial) { Previous = initial; } public Point Previous { get; set; } public Point Update(Point point, Point alpha) { Point pt; pt.X = (alpha.X * point.X) + ((1 - alpha.X) * Previous.X); pt.Y = (alpha.Y * point.Y) + ((1 - alpha.Y) * Previous.Y); Previous = pt; return Previous; } } }
LowpassFilter
csharp
louthy__language-ext
LanguageExt.Core/Monads/Alternative Monads/Fin/Extensions/Fin.Extensions.Map.cs
{ "start": 79, "end": 1154 }
partial class ____ { /// <summary> /// Functor map operation /// </summary> /// <remarks> /// Unwraps the value within the functor, passes it to the map function `f` provided, and /// then takes the mapped value and wraps it back up into a new functor. /// </remarks> /// <param name="ma">Functor to map</param> /// <param name="f">Mapping function</param> /// <returns>Mapped functor</returns> public static Fin<B> Map<A, B>(this Func<A, B> f, K<Fin, A> ma) => Functor.map(f, ma).As(); /// <summary> /// Functor map operation /// </summary> /// <remarks> /// Unwraps the value within the functor, passes it to the map function `f` provided, and /// then takes the mapped value and wraps it back up into a new functor. /// </remarks> /// <param name="ma">Functor to map</param> /// <param name="f">Mapping function</param> /// <returns>Mapped functor</returns> public static Fin<B> Map<A, B>(this Func<A, B> f, Fin<A> ma) => Functor.map(f, ma).As(); }
FinExtensions
csharp
dotnet__orleans
src/api/Azure/Orleans.Streaming.EventHubs/Orleans.Streaming.EventHubs.cs
{ "start": 23992, "end": 24304 }
public partial class ____ { public Configuration.EventHubOptions Hub { get { throw null; } set { } } public string Partition { get { throw null; } set { } } public Configuration.EventHubReceiverOptions ReceiverOptions { get { throw null; } set { } } }
EventHubPartitionSettings
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Extensions/Mapping/ProductAttributeMappingMappingExtensions.cs
{ "start": 150, "end": 850 }
public static class ____ { public static ProductModel.ProductAttributeMappingModel ToModel(this ProductAttributeMapping entity) { return entity.MapTo<ProductAttributeMapping, ProductModel.ProductAttributeMappingModel>(); } public static ProductAttributeMapping ToEntity(this ProductModel.ProductAttributeMappingModel model) { return model.MapTo<ProductModel.ProductAttributeMappingModel, ProductAttributeMapping>(); } public static ProductAttributeMapping ToEntity(this ProductModel.ProductAttributeMappingModel model, ProductAttributeMapping destination) { return model.MapTo(destination); } }
ProductAttributeMappingMappingExtensions
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Data/CollectionViewGroup.cs
{ "start": 169, "end": 739 }
internal class ____ : ICollectionViewGroup { private readonly BindingPath _bindingPath; public CollectionViewGroup(object group, PropertyPath itemsPath) { Group = group; if (itemsPath != null) { _bindingPath = new BindingPath(itemsPath.Path, null); _bindingPath.DataContext = group; GroupItems = ObservableVectorWrapper.Create(_bindingPath.Value); } else { GroupItems = ObservableVectorWrapper.Create(group); } } public object Group { get; } public IObservableVector<object> GroupItems { get; } } }
CollectionViewGroup
csharp
ardalis__Result
tests/Ardalis.Result.UnitTests/PagedResultConstructor.cs
{ "start": 142, "end": 1145 }
public class ____ { private readonly PagedInfo _pagedInfo = new PagedInfo(0, 10, 1, 3); [Fact] public void InitializesStronglyTypedStringValue() { string expectedString = "test string"; var result = new PagedResult<string>(_pagedInfo, expectedString); Assert.Equal(expectedString, result.Value); Assert.Equal(_pagedInfo, result.PagedInfo); } [Fact] public void InitializesStronglyTypedIntValue() { int expectedInt = 123; var result = new PagedResult<int>(_pagedInfo, expectedInt); Assert.Equal(expectedInt, result.Value); Assert.Equal(_pagedInfo, result.PagedInfo); } [Fact] public void InitializesStronglyTypedObjectValue() { var expectedObject = new TestObject(); var result = new PagedResult<TestObject>(_pagedInfo, expectedObject); Assert.Equal(expectedObject, result.Value); Assert.Equal(_pagedInfo, result.PagedInfo); }
PagedResultConstructor
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/src/ServiceStack.OrmLite.SqlServer/Converters/SqlServerJsonStringConverters.cs
{ "start": 95, "end": 800 }
public class ____ : SqlServerStringConverter { // json string to object public override object FromDbValue(Type fieldType, object value) { if (value is string raw && fieldType.HasAttributeCached<SqlJsonAttribute>()) return JsonSerializer.DeserializeFromString(raw, fieldType); return base.FromDbValue(fieldType, value); } // object to json string public override object ToDbValue(Type fieldType, object value) { if (value?.GetType().HasAttributeCached<SqlJsonAttribute>() == true) return JsonSerializer.SerializeToString(value, value.GetType()); return base.ToDbValue(fieldType, value); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
SqlServerJsonStringConverter
csharp
dotnet__maui
src/Controls/tests/Xaml.UnitTests/Issues/Unreported006.xaml.cs
{ "start": 556, "end": 819 }
class ____ { [Test] public void CanAssignGenericBP([Values] XamlInflator inflator) { var page = new Unreported006(inflator); Assert.NotNull(page.GenericProperty); Assert.That(page.GenericProperty, Is.TypeOf<Compatibility.StackLayout>()); } } }
Tests
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.MicrosoftDI.Tests/ScopedExecutionStrategyTests.cs
{ "start": 1984, "end": 2099 }
private class ____ { public int Value([FromServices] Class1 class1) => class1.GetValue(); }
Widget
csharp
ChilliCream__graphql-platform
src/GreenDonut/src/GreenDonut.Data/Internal/ExpressionHelpers.cs
{ "start": 94, "end": 5226 }
internal static class ____ { public static Expression<Func<T, T>> Combine<T>( Expression<Func<T, T>> first, Expression<Func<T, T>> second) { var parameter = Expression.Parameter(typeof(T), "root"); var firstBody = ReplaceParameter(first.Body, first.Parameters[0], parameter); var secondBody = ReplaceParameter(second.Body, second.Parameters[0], parameter); var combinedBody = CombineExpressions(firstBody, secondBody); return Expression.Lambda<Func<T, T>>(combinedBody, parameter); } public static Expression<Func<T, bool>> And<T>( Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { var parameter = Expression.Parameter(typeof(T), "entity"); var firstBody = ReplaceParameter(first.Body, first.Parameters[0], parameter); var secondBody = ReplaceParameter(second.Body, second.Parameters[0], parameter); var combinedBody = Expression.AndAlso(firstBody, secondBody); return Expression.Lambda<Func<T, bool>>(combinedBody, parameter); } private static Expression ReplaceParameter( Expression body, ParameterExpression toReplace, Expression replacement) => new ParameterReplacer(toReplace, replacement).Visit(body); private static Expression CombineExpressions(Expression first, Expression second) { if (first is UnaryExpression { NodeType: ExpressionType.Convert } firstUnary) { return CombineWithConvertExpression(firstUnary, second); } if (first is MemberInitExpression firstInit && second is MemberInitExpression secondInit) { return CombineMemberInitExpressions(firstInit, secondInit); } if (first is ConditionalExpression firstCond && second is ConditionalExpression secondCond) { return CombineConditionalExpressions(firstCond, secondCond); } if (first is ConditionalExpression firstConditional && second is MemberInitExpression secondMemberInit) { return CombineConditionalAndMemberInit(firstConditional, secondMemberInit); } if (first is MemberInitExpression firstMemberInit && second is ConditionalExpression secondConditional) { return CombineConditionalAndMemberInit(secondConditional, firstMemberInit); } // as a fallback we return the second body, assuming it overwrites the first. return second; } private static Expression CombineWithConvertExpression(UnaryExpression first, Expression second) { if (second is MemberInitExpression otherMemberInit) { var combinedInit = CombineMemberInitExpressions((MemberInitExpression)first.Operand, otherMemberInit); return Expression.Convert(combinedInit, first.Type); } if (second is ConditionalExpression otherConditional) { var combinedCond = CombineConditionalExpressions((ConditionalExpression)first.Operand, otherConditional); return Expression.Convert(combinedCond, first.Type); } return Expression.Convert(second, first.Type); } private static MemberInitExpression CombineMemberInitExpressions( MemberInitExpression first, MemberInitExpression second) { var bindings = new Dictionary<string, MemberAssignment>(); foreach (var binding in first.Bindings.Cast<MemberAssignment>()) { bindings[binding.Member.Name] = binding; } var firstRootExpression = ExtractRootExpressionFromBindings(first.Bindings.Cast<MemberAssignment>()); var parameterToReplace = ExtractParameterExpression(firstRootExpression); if (firstRootExpression != null && parameterToReplace != null) { var replacer = new RootExpressionReplacerVisitor(parameterToReplace, firstRootExpression); foreach (var binding in second.Bindings.Cast<MemberAssignment>()) { var newBindingExpression = replacer.Visit(binding.Expression); bindings[binding.Member.Name] = Expression.Bind(binding.Member, newBindingExpression); } } else { foreach (var binding in second.Bindings.Cast<MemberAssignment>()) { bindings[binding.Member.Name] = binding; } } return Expression.MemberInit(first.NewExpression, bindings.Values); } private static Expression? ExtractRootExpressionFromBindings( IEnumerable<MemberAssignment> bindings) => bindings.FirstOrDefault()?.Expression is MemberExpression memberExpr ? memberExpr.Expression : null; private static ParameterExpression? ExtractParameterExpression(Expression? expression) => expression switch { UnaryExpression { NodeType: ExpressionType.Convert } expr => ExtractParameterExpression(expr.Operand), ParameterExpression paramExpr => paramExpr, _ => null };
ExpressionHelpers
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/MessageData/FileSystem_Specs.cs
{ "start": 202, "end": 1612 }
public class ____ { [Test] public async Task Should_generate_the_folder_and_file() { MessageData<string> property = await _repository.PutString(new string('8', 10000)); MessageData<string> loaded = await _repository.GetString(property.Address); await Assert.MultipleAsync(async () => { Assert.That(property.Address, Is.Not.Null); Assert.That(await loaded.Value, Is.Not.Null); }); } [Test] public async Task Should_generate_time_based_folder() { MessageData<string> property = await _repository.PutString(new string('8', 10000), TimeSpan.FromDays(30)); MessageData<string> loaded = await _repository.GetString(property.Address); Assert.That(await loaded.Value, Is.Not.Null); } IMessageDataRepository _repository; [OneTimeSetUp] public void Setup() { var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var messageDataPath = Path.Combine(baseDirectory, "MessageData"); var dataDirectory = new DirectoryInfo(messageDataPath); Console.WriteLine("Using data directory: {0}", dataDirectory); _repository = new FileSystemMessageDataRepository(dataDirectory); } } }
Storing_message_data_on_the_file_system
csharp
dotnet__aspire
src/Aspire.Hosting.Valkey/ValkeyResource.cs
{ "start": 351, "end": 3797 }
public class ____(string name) : ContainerResource(name), IResourceWithConnectionString { internal const string PrimaryEndpointName = "tcp"; private EndpointReference? _primaryEndpoint; /// <summary> /// Initializes a new instance of the <see cref="ValkeyResource"/> class. /// </summary> /// <param name="name">The name of the resource.</param> /// <param name="password">A parameter that contains the Valkey server password.</param> public ValkeyResource(string name, ParameterResource password) : this(name) { PasswordParameter = password; } /// <summary> /// Gets the parameter that contains the Valkey server password. /// </summary> public ParameterResource? PasswordParameter { get; } /// <summary> /// Gets the primary endpoint for the Valkey server. /// </summary> public EndpointReference PrimaryEndpoint => _primaryEndpoint ??= new(this, PrimaryEndpointName); /// <summary> /// Gets the host endpoint reference for this resource. /// </summary> public EndpointReferenceExpression Host => PrimaryEndpoint.Property(EndpointProperty.Host); /// <summary> /// Gets the port endpoint reference for this resource. /// </summary> public EndpointReferenceExpression Port => PrimaryEndpoint.Property(EndpointProperty.Port); /// <summary> /// Gets the connection string expression for the Valkey server. /// </summary> public ReferenceExpression ConnectionStringExpression { get { if (this.TryGetLastAnnotation<ConnectionStringRedirectAnnotation>(out var connectionStringAnnotation)) { return connectionStringAnnotation.Resource.ConnectionStringExpression; } return BuildConnectionString(); } } private ReferenceExpression BuildConnectionString() { var builder = new ReferenceExpressionBuilder(); builder.Append($"{PrimaryEndpoint.Property(EndpointProperty.HostAndPort)}"); if (PasswordParameter is not null) { builder.Append($",password={PasswordParameter}"); } return builder.Build(); } /// <summary> /// Gets the connection URI expression for the Valkey server. /// </summary> /// <remarks> /// Format: <c>valkey://[:{password}@]{host}:{port}</c>. The password segment is omitted when no password is configured. /// </remarks> public ReferenceExpression UriExpression { get { var builder = new ReferenceExpressionBuilder(); builder.AppendLiteral("valkey://"); if (PasswordParameter is not null) { builder.Append($":{PasswordParameter:uri}@"); } builder.Append($"{Host}"); builder.AppendLiteral(":"); builder.Append($"{Port}"); return builder.Build(); } } IEnumerable<KeyValuePair<string, ReferenceExpression>> IResourceWithConnectionString.GetConnectionProperties() { yield return new("Host", ReferenceExpression.Create($"{Host}")); yield return new("Port", ReferenceExpression.Create($"{Port}")); if (PasswordParameter is not null) { yield return new("Password", ReferenceExpression.Create($"{PasswordParameter}")); } yield return new("Uri", UriExpression); } }
ValkeyResource
csharp
abpframework__abp
framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/ExtensibleObject_Tests.cs
{ "start": 163, "end": 2669 }
public class ____ : AbpJsonSystemTextJsonTestBase { private readonly IJsonSerializer _jsonSerializer; public ExtensibleObject_Tests() { _jsonSerializer = GetRequiredService<IJsonSerializer>(); } [Fact] public void JsonConverter_Test() { var fooDto = new FooDto { Name = "foo-dto", BarDtos = new List<BarDto>() }; fooDto.SetProperty("foo", "foo-value"); var barDto = new BarDto { Name = "bar-dto" }; barDto.SetProperty("bar", "bar-value"); fooDto.BarDtos.Add(barDto); var json = _jsonSerializer.Serialize(fooDto); fooDto = _jsonSerializer.Deserialize<FooDto>(json); fooDto.ShouldNotBeNull(); fooDto.Name.ShouldBe("foo-dto"); fooDto.GetProperty("foo").ShouldBe("foo-value"); fooDto.BarDtos.Count.ShouldBe(1); fooDto.BarDtos.First().Name.ShouldBe("bar-dto"); fooDto.BarDtos.First().GetProperty("bar").ShouldBe("bar-value"); fooDto.Name = "new-foo-dto"; fooDto.SetProperty("foo", "new-foo-value"); fooDto.BarDtos.First().Name = "new-bar-dto"; fooDto.BarDtos.First().SetProperty("bar", "new-bar-value"); json = _jsonSerializer.Serialize(fooDto); fooDto = _jsonSerializer.Deserialize<FooDto>(json); fooDto.ShouldNotBeNull(); fooDto.Name.ShouldBe("new-foo-dto"); fooDto.GetProperty("foo").ShouldBe("new-foo-value"); fooDto.BarDtos.Count.ShouldBe(1); fooDto.BarDtos.First().Name.ShouldBe("new-bar-dto"); fooDto.BarDtos.First().GetProperty("bar").ShouldBe("new-bar-value"); } [Fact] public void SelfReference_Test() { var parentNodeDto = new NodeDto { Name = "parentNode", }; parentNodeDto.SetProperty("node", "parent-value"); var nodeDto = new NodeDto { Name = "node", Parent = parentNodeDto }; nodeDto.SetProperty("node", "node-value"); var json = _jsonSerializer.Serialize(nodeDto); nodeDto = _jsonSerializer.Deserialize<NodeDto>(json); nodeDto.ShouldNotBeNull(); nodeDto.Name.ShouldBe("node"); nodeDto.GetProperty("node").ShouldBe("node-value"); nodeDto.Parent.ShouldNotBeNull(); nodeDto.Parent.Name.ShouldBe("parentNode"); nodeDto.Parent.GetProperty("node").ShouldBe("parent-value"); } }
ExtensibleObject_Tests
csharp
dotnet__machinelearning
src/Microsoft.ML.EntryPoints/DataViewReference.cs
{ "start": 739, "end": 1389 }
public sealed class ____ { [TlcModule.Output(Desc = "The resulting data view", SortOrder = 1)] public IDataView Data; } [TlcModule.EntryPoint(Name = "Data.DataViewReference", Desc = "Pass dataview from memory to experiment")] public static Output ImportData(IHostEnvironment env, Input input) { Contracts.CheckValue(env, nameof(env)); var host = env.Register("DataViewReference"); env.CheckValue(input, nameof(input)); EntryPointUtils.CheckInputArgs(host, input); return new Output { Data = input.Data }; } } }
Output
csharp
smartstore__Smartstore
src/Smartstore/Engine/ILifetimeScopeAccessor.cs
{ "start": 51, "end": 2402 }
public interface ____ { /// <summary> /// Gets or sets the current lifetime scope that services can be resolved from. /// A new scope will be created when <c>HttpContext</c> is <c>null</c> or the current /// thread's context state does not contain any scope instance. You should NEVER dispose /// the instance returned by this property as you have no control over the scope instantiation. /// Instead, wrap the call within a <code>using (BeginContextAwareScope()) { ... }</code> block, /// which is smart enough to detect the current state and either dispose or not. /// </summary> /// <returns>A new or existing lifetime scope.</returns> ILifetimeScope LifetimeScope { get; set; } /// <summary> /// Ends the current lifetime scope, but only when <c>HttpContext</c> is <c>null</c>. /// </summary> void EndCurrentLifetimeScope(); /// <summary> /// Either creates a new lifetime scope when <c>HttpContext</c> is <c>null</c>, /// OR returns the current HTTP context scoped lifetime. /// </summary> /// <returns> /// A disposable object which does nothing when internal lifetime scope is bound to the HTTP context, /// OR ends the lifetime scope otherwise. /// </returns> /// <remarks> /// This method is intended for usage in background threads or tasks. There may be situations where HttpContext is present, /// especially when a task was started with <c>TaskScheduler.FromCurrentSynchronizationContext()</c>. In this case it may not be /// desirable to create a new scope, but use the existing, HTTP context bound scope instead. /// </remarks> IDisposable BeginContextAwareScope(out ILifetimeScope scope); /// <summary> /// Creates a new nested lifetime scope that services can be resolved from. /// </summary> /// <param name="configurationAction"> /// An optional configuration action that will execute during lifetime scope creation. /// </param> /// <returns> /// The new nested lifetime scope. /// </returns> ILifetimeScope CreateLifetimeScope(Action<ContainerBuilder> configurationAction = null); } }
ILifetimeScopeAccessor
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs
{ "start": 70978, "end": 72142 }
public sealed class ____ : AsyncTriggerBase<AsyncUnit> { void OnParticleTrigger() { RaiseEvent(AsyncUnit.Default); } public IAsyncOnParticleTriggerHandler GetOnParticleTriggerAsyncHandler() { return new AsyncTriggerHandler<AsyncUnit>(this, false); } public IAsyncOnParticleTriggerHandler GetOnParticleTriggerAsyncHandler(CancellationToken cancellationToken) { return new AsyncTriggerHandler<AsyncUnit>(this, cancellationToken, false); } public UniTask OnParticleTriggerAsync() { return ((IAsyncOnParticleTriggerHandler)new AsyncTriggerHandler<AsyncUnit>(this, true)).OnParticleTriggerAsync(); } public UniTask OnParticleTriggerAsync(CancellationToken cancellationToken) { return ((IAsyncOnParticleTriggerHandler)new AsyncTriggerHandler<AsyncUnit>(this, cancellationToken, true)).OnParticleTriggerAsync(); } } #endregion #region ParticleUpdateJobScheduled #if UNITY_2019_3_OR_NEWER && (!UNITY_2019_1_OR_NEWER || UNITASK_PARTICLESYSTEM_SUPPORT)
AsyncParticleTriggerTrigger
csharp
dotnet__maui
src/Templates/src/templates/maui-mobile/Pages/ManageMetaPage.xaml.cs
{ "start": 29, "end": 189 }
public partial class ____ : ContentPage { public ManageMetaPage(ManageMetaPageModel model) { InitializeComponent(); BindingContext = model; } }
ManageMetaPage
csharp
microsoft__PowerToys
src/modules/fancyzones/FancyZonesEditorCommon/Data/LayoutTemplates.cs
{ "start": 601, "end": 912 }
public struct ____ { public string Type { get; set; } public bool ShowSpacing { get; set; } public int Spacing { get; set; } public int ZoneCount { get; set; } public int SensitivityRadius { get; set; } }
TemplateLayoutWrapper
csharp
EventStore__EventStore
src/KurrentDB.Core.XUnit.Tests/Metrics/RecentMaxTests.cs
{ "start": 314, "end": 1613 }
public class ____ { private readonly RecentMax<long> _sut; private readonly FakeClock _clock = new(); public RecentMaxTests() { _sut = new RecentMax<long>(expectedScrapeIntervalSeconds: 15); } [Fact] public void record_now_returns_now() { _clock.SecondsSinceEpoch = 500; var now = Record(123); Assert.Equal(_clock.Now, now); } [Fact] public void no_records() { AssertObservedValue(0); } [Fact] public void one_record() { AssertObservedValue(0); Record(1); AssertObservedValue(1); } [Fact] public void two_records_instant() { AssertObservedValue(0); Record(1); AssertObservedValue(1); Record(2); AssertObservedValue(2); } [Fact] public void two_records_ascending() { AssertObservedValue(0); AdvanceSeconds(1); Record(1); AssertObservedValue(1); AdvanceSeconds(1); Record(2); AssertObservedValue(2); } [Fact] public void two_records_descending() { AssertObservedValue(0); AdvanceSeconds(1); Record(2); AssertObservedValue(2); AdvanceSeconds(1); Record(1); AssertObservedValue(2); } [Fact] public void removes_stale_data() { Record(1); AdvanceSeconds(19); AssertObservedValue(1); AdvanceSeconds(1); AssertObservedValue(0); } [Fact] public void removes_stale_data_incrementally() { //
RecentMaxTests
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json/Linq/JProperty.Async.cs
{ "start": 1361, "end": 6379 }
public partial class ____ { /// <summary> /// Writes this token to a <see cref="JsonWriter"/> asynchronously. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns> [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { Task task = writer.WritePropertyNameAsync(_name, cancellationToken); if (task.IsCompletedSuccessfully()) { return WriteValueAsync(writer, cancellationToken, converters); } return WriteToAsync(task, writer, cancellationToken, converters); } [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private async Task WriteToAsync(Task task, JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { await task.ConfigureAwait(false); await WriteValueAsync(writer, cancellationToken, converters).ConfigureAwait(false); } [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private Task WriteValueAsync(JsonWriter writer, CancellationToken cancellationToken, JsonConverter[] converters) { JToken value = Value; return value != null ? value.WriteToAsync(writer, cancellationToken, converters) : writer.WriteNullAsync(cancellationToken); } /// <summary> /// Asynchronously loads a <see cref="JProperty"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JProperty"/>.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> representing the asynchronous creation. The <see cref="Task{TResult}.Result"/> /// property returns a <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public new static Task<JProperty> LoadAsync(JsonReader reader, CancellationToken cancellationToken = default) { return LoadAsync(reader, null, cancellationToken); } /// <summary> /// Asynchronously loads a <see cref="JProperty"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JProperty"/>.</param> /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON. /// If this is <c>null</c>, default load settings will be used.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task{TResult}"/> representing the asynchronous creation. The <see cref="Task{TResult}.Result"/> /// property returns a <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public new static async Task<JProperty> LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { if (reader.TokenType == JsonToken.None) { if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) { throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader."); } } await reader.MoveToContentAsync(cancellationToken).ConfigureAwait(false); if (reader.TokenType != JsonToken.PropertyName) { throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } JProperty p = new JProperty((string)reader.Value!); p.SetLineInfo(reader as IJsonLineInfo, settings); await p.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); return p; } } } #endif
JProperty
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.Orders/Areas/Orders/Controllers/OrderHistoryApiController.cs
{ "start": 376, "end": 1341 }
public class ____ : Controller { private readonly IRepository<OrderHistory> _orderHistoryRepository; public OrderHistoryApiController(IRepository<OrderHistory> orderHistoryRepository) { _orderHistoryRepository = orderHistoryRepository; } [HttpGet("api/orders/{orderId}/history")] public async Task<IActionResult> Get(long orderId) { var histories = await _orderHistoryRepository.Query() .Where(x => x.OrderId == orderId) .Select(x => new { OldStatus = x.OldStatus.ToString(), NewStatus = x.NewStatus.ToString(), CreatedById = x.CreatedById, CreatedByFullName = x.CreatedBy.FullName, x.Note, x.CreatedOn }).ToListAsync(); return Ok(histories); } } }
OrderHistoryApiController
csharp
jellyfin__jellyfin
Jellyfin.Api/Helpers/AudioHelper.cs
{ "start": 586, "end": 6848 }
public class ____ { private readonly IUserManager _userManager; private readonly ILibraryManager _libraryManager; private readonly IMediaSourceManager _mediaSourceManager; private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IMediaEncoder _mediaEncoder; private readonly ITranscodeManager _transcodeManager; private readonly IHttpClientFactory _httpClientFactory; private readonly IHttpContextAccessor _httpContextAccessor; private readonly EncodingHelper _encodingHelper; /// <summary> /// Initializes a new instance of the <see cref="AudioHelper"/> class. /// </summary> /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param> /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param> /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param> /// <param name="transcodeManager">Instance of <see cref="ITranscodeManager"/> interface.</param> /// <param name="httpClientFactory">Instance of the <see cref="IHttpClientFactory"/> interface.</param> /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param> /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param> public AudioHelper( IUserManager userManager, ILibraryManager libraryManager, IMediaSourceManager mediaSourceManager, IServerConfigurationManager serverConfigurationManager, IMediaEncoder mediaEncoder, ITranscodeManager transcodeManager, IHttpClientFactory httpClientFactory, IHttpContextAccessor httpContextAccessor, EncodingHelper encodingHelper) { _userManager = userManager; _libraryManager = libraryManager; _mediaSourceManager = mediaSourceManager; _serverConfigurationManager = serverConfigurationManager; _mediaEncoder = mediaEncoder; _transcodeManager = transcodeManager; _httpClientFactory = httpClientFactory; _httpContextAccessor = httpContextAccessor; _encodingHelper = encodingHelper; } /// <summary> /// Get audio stream. /// </summary> /// <param name="transcodingJobType">Transcoding job type.</param> /// <param name="streamingRequest">Streaming controller.Request dto.</param> /// <returns>A <see cref="Task"/> containing the resulting <see cref="ActionResult"/>.</returns> public async Task<ActionResult> GetAudioStream( TranscodingJobType transcodingJobType, StreamingRequestDto streamingRequest) { if (_httpContextAccessor.HttpContext is null) { throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext)); } bool isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == System.Net.WebRequestMethods.Http.Head; // CTS lifecycle is managed internally. var cancellationTokenSource = new CancellationTokenSource(); using var state = await StreamingHelpers.GetStreamingState( streamingRequest, _httpContextAccessor.HttpContext, _mediaSourceManager, _userManager, _libraryManager, _serverConfigurationManager, _mediaEncoder, _encodingHelper, _transcodeManager, transcodingJobType, cancellationTokenSource.Token) .ConfigureAwait(false); if (streamingRequest.Static && state.DirectStreamProvider is not null) { var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfo(streamingRequest.LiveStreamId); if (liveStreamInfo is null) { throw new FileNotFoundException(); } var liveStream = new ProgressiveFileStream(liveStreamInfo.GetStream()); // TODO (moved from MediaBrowser.Api): Don't hardcode contentType return new FileStreamResult(liveStream, MimeTypes.GetMimeType("file.ts")); } // Static remote stream if (streamingRequest.Static && state.InputProtocol == MediaProtocol.Http) { var httpClient = _httpClientFactory.CreateClient(NamedClient.Default); return await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, httpClient, _httpContextAccessor.HttpContext).ConfigureAwait(false); } if (streamingRequest.Static && state.InputProtocol != MediaProtocol.File) { return new BadRequestObjectResult($"Input protocol {state.InputProtocol} cannot be streamed statically"); } var outputPath = state.OutputFilePath; // Static stream if (streamingRequest.Static) { var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath); if (state.MediaSource.IsInfiniteStream) { var stream = new ProgressiveFileStream(state.MediaPath, null, _transcodeManager); return new FileStreamResult(stream, contentType); } return FileStreamResponseHelpers.GetStaticFileResult( state.MediaPath, contentType); } // Need to start ffmpeg (because media can't be returned directly) var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, outputPath); return await FileStreamResponseHelpers.GetTranscodedFile( state, isHeadRequest, _httpContextAccessor.HttpContext, _transcodeManager, ffmpegCommandLineArguments, transcodingJobType, cancellationTokenSource).ConfigureAwait(false); } }
AudioHelper
csharp
aspnetboilerplate__aspnetboilerplate
test/Abp.EntityFrameworkCore.Tests/Tests/Repository_Resolve_Tests.cs
{ "start": 317, "end": 773 }
public class ____ : EntityFrameworkCoreModuleTestBase { [Fact] public void Should_Resolve_Custom_Repository_If_Registered() { var postRepository = Resolve<IRepository<Post, Guid>>(); postRepository.GetAllList().Any().ShouldBeTrue(); Assert.Throws<Exception>( () => postRepository.Count() ).Message.ShouldBe("can not get count of posts"); //Should also resolve by custom
Repository_Resolve_Tests
csharp
ServiceStack__ServiceStack
ServiceStack.Redis/tests/ServiceStack.Redis.Tests/RedisPipelineTests.cs
{ "start": 150, "end": 11633 }
public class ____ : RedisClientTestsBase { private const string Key = "pipemultitest"; private const string ListKey = "pipemultitest-list"; private const string SetKey = "pipemultitest-set"; private const string SortedSetKey = "pipemultitest-sortedset"; public override void OnAfterEachTest() { CleanMask = Key + "*"; base.OnAfterEachTest(); } [Test] public void Can_call_single_operation_in_pipeline() { Assert.That(Redis.GetValue(Key), Is.Null); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key)); var map = new Dictionary<string, int>(); pipeline.QueueCommand(r => r.Get<int>(Key), y => map[Key] = y); pipeline.Flush(); } Assert.That(Redis.GetValue(Key), Is.EqualTo("1")); } [Test] public void No_commit_of_atomic_pipelines_discards_all_commands() { Assert.That(Redis.GetValue(Key), Is.Null); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key)); } Assert.That(Redis.GetValue(Key), Is.Null); } [Test] public void Exception_in_atomic_pipelines_discards_all_commands() { Assert.That(Redis.GetValue(Key), Is.Null); try { using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key)); throw new NotSupportedException(); } } catch (NotSupportedException) { Assert.That(Redis.GetValue(Key), Is.Null); } } [Test] public void Can_call_single_operation_3_Times_in_pipeline() { Assert.That(Redis.GetValue(Key), Is.Null); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key)); pipeline.QueueCommand(r => r.IncrementValue(Key)); pipeline.QueueCommand(r => r.IncrementValue(Key)); pipeline.Flush(); } Assert.That(Redis.GetValue(Key), Is.EqualTo("3")); } [Test] public void Can_call_hash_operations_in_pipeline() { Assert.That(Redis.GetValue(Key), Is.Null); var fields = new[] { "field1", "field2", "field3" }; var values = new[] { "1", "2", "3" }; var fieldBytes = new byte[fields.Length][]; for (int i = 0; i < fields.Length; ++i) { fieldBytes[i] = GetBytes(fields[i]); } var valueBytes = new byte[values.Length][]; for (int i = 0; i < values.Length; ++i) { valueBytes[i] = GetBytes(values[i]); } byte[][] members = null; var pipeline = Redis.CreatePipeline(); pipeline.QueueCommand(r => ((RedisNativeClient)r).HMSet(Key, fieldBytes, valueBytes)); pipeline.QueueCommand(r => ((RedisNativeClient)r).HGetAll(Key), x => members = x); pipeline.Flush(); for (var i = 0; i < members.Length; i += 2) { Assert.AreEqual(members[i], fieldBytes[i / 2]); Assert.AreEqual(members[i + 1], valueBytes[i / 2]); } pipeline.Dispose(); } [Test] public void Can_call_multiple_setexs_in_pipeline() { Assert.That(Redis.GetValue(Key), Is.Null); var keys = new[] { Key + "key1", Key + "key2", Key + "key3" }; var values = new[] { "1", "2", "3" }; var pipeline = Redis.CreatePipeline(); for (int i = 0; i < 3; ++i) { int index0 = i; pipeline.QueueCommand(r => ((RedisNativeClient)r).SetEx(keys[index0], 100, GetBytes(values[index0]))); } pipeline.Flush(); pipeline.Replay(); for (int i = 0; i < 3; ++i) Assert.AreEqual(Redis.GetValue(keys[i]), values[i]); pipeline.Dispose(); } [Test] public void Can_call_single_operation_with_callback_3_Times_in_pipeline() { var results = new List<long>(); Assert.That(Redis.GetValue(Key), Is.Null); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key), results.Add); pipeline.QueueCommand(r => r.IncrementValue(Key), results.Add); pipeline.QueueCommand(r => r.IncrementValue(Key), results.Add); pipeline.Flush(); } Assert.That(Redis.GetValue(Key), Is.EqualTo("3")); Assert.That(results, Is.EquivalentTo(new List<long> { 1, 2, 3 })); } [Test] public void Supports_different_operation_types_in_same_pipeline() { var incrementResults = new List<long>(); var collectionCounts = new List<long>(); var containsItem = false; Assert.That(Redis.GetValue(Key), Is.Null); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult)); pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem1")); pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem2")); pipeline.QueueCommand(r => r.AddItemToSet(SetKey, "setitem")); pipeline.QueueCommand(r => r.SetContainsItem(SetKey, "setitem"), b => containsItem = b); pipeline.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem1")); pipeline.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem2")); pipeline.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem3")); pipeline.QueueCommand(r => r.GetListCount(ListKey), intResult => collectionCounts.Add(intResult)); pipeline.QueueCommand(r => r.GetSetCount(SetKey), intResult => collectionCounts.Add(intResult)); pipeline.QueueCommand(r => r.GetSortedSetCount(SortedSetKey), intResult => collectionCounts.Add(intResult)); pipeline.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult)); pipeline.Flush(); } Assert.That(containsItem, Is.True); Assert.That(Redis.GetValue(Key), Is.EqualTo("2")); Assert.That(incrementResults, Is.EquivalentTo(new List<long> { 1, 2 })); Assert.That(collectionCounts, Is.EquivalentTo(new List<int> { 2, 1, 3 })); Assert.That(Redis.GetAllItemsFromList(ListKey), Is.EquivalentTo(new List<string> { "listitem1", "listitem2" })); Assert.That(Redis.GetAllItemsFromSet(SetKey), Is.EquivalentTo(new List<string> { "setitem" })); Assert.That(Redis.GetAllItemsFromSortedSet(SortedSetKey), Is.EquivalentTo(new List<string> { "sortedsetitem1", "sortedsetitem2", "sortedsetitem3" })); } [Test] public void Can_call_multi_string_operations_in_pipeline() { string item1 = null; string item4 = null; var results = new List<string>(); Assert.That(Redis.GetListCount(ListKey), Is.EqualTo(0)); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem1")); pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem2")); pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem3")); pipeline.QueueCommand(r => r.GetAllItemsFromList(ListKey), x => results = x); pipeline.QueueCommand(r => r.GetItemFromList(ListKey, 0), x => item1 = x); pipeline.QueueCommand(r => r.GetItemFromList(ListKey, 4), x => item4 = x); pipeline.Flush(); } Assert.That(Redis.GetListCount(ListKey), Is.EqualTo(3)); Assert.That(results, Is.EquivalentTo(new List<string> { "listitem1", "listitem2", "listitem3" })); Assert.That(item1, Is.EqualTo("listitem1")); Assert.That(item4, Is.Null); } [Test] // Operations that are not supported in older versions will look at server info to determine what to do. // If server info is fetched each time, then it will interfer with pipeline public void Can_call_operation_not_supported_on_older_servers_in_pipeline() { var temp = new byte[1]; using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => ((RedisNativeClient)r).SetEx(Key + "key", 5, temp)); pipeline.Flush(); } } [Test] public void Pipeline_can_be_replayed() { string KeySquared = Key + Key; Assert.That(Redis.GetValue(Key), Is.Null); Assert.That(Redis.GetValue(KeySquared), Is.Null); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key)); pipeline.QueueCommand(r => r.IncrementValue(KeySquared)); pipeline.Flush(); Assert.That(Redis.GetValue(Key), Is.EqualTo("1")); Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1")); Redis.Del(Key); Redis.Del(KeySquared); Assert.That(Redis.GetValue(Key), Is.Null); Assert.That(Redis.GetValue(KeySquared), Is.Null); pipeline.Replay(); pipeline.Dispose(); Assert.That(Redis.GetValue(Key), Is.EqualTo("1")); Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1")); } } [Test] public void Pipeline_can_be_contain_watch() { string KeySquared = Key + Key; Assert.That(Redis.GetValue(Key), Is.Null); Assert.That(Redis.GetValue(KeySquared), Is.Null); using (var pipeline = Redis.CreatePipeline()) { pipeline.QueueCommand(r => r.IncrementValue(Key)); pipeline.QueueCommand(r => r.IncrementValue(KeySquared)); pipeline.QueueCommand(r => ((RedisNativeClient)r).Watch(Key + "FOO")); pipeline.Flush(); Assert.That(Redis.GetValue(Key), Is.EqualTo("1")); Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1")); } } [Test] public void Can_call_AddRangeToSet_in_pipeline() { using (var pipeline = Redis.CreatePipeline()) { var key = "pipeline-test"; pipeline.QueueCommand(r => r.Remove(key)); pipeline.QueueCommand(r => r.AddRangeToSet(key, new[] { "A", "B", "C" }.ToList())); pipeline.Flush(); } } } }
RedisPipelineTests
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/VirtualPathUtils.cs
{ "start": 273, "end": 3745 }
public static class ____ { public static Stack<string> TokenizeVirtualPath(this string str, IVirtualPathProvider pathProvider) { if (pathProvider == null) throw new ArgumentNullException(nameof(pathProvider)); return TokenizeVirtualPath(str, pathProvider.VirtualPathSeparator); } public static Stack<string> TokenizeVirtualPath(this string str, string virtualPathSeparator) { if (string.IsNullOrEmpty(str)) return new Stack<string>(); var tokens = str.Split([virtualPathSeparator], StringSplitOptions.RemoveEmptyEntries); return new Stack<string>(((IEnumerable<string>)tokens).Reverse()); } public static Stack<string> TokenizeResourcePath(this string str, char pathSeparator = '.') { if (string.IsNullOrEmpty(str)) return new Stack<string>(); var n = str.Count(c => c == pathSeparator); var tokens = str.Split([pathSeparator], n); return new Stack<string>(((IEnumerable<string>)tokens).Reverse()); } public static IEnumerable<IGrouping<string, string[]>> GroupByFirstToken(this IEnumerable<string> resourceNames, char pathSeparator = '.') { return resourceNames.Select(n => n.Split([pathSeparator], 2)) .GroupBy(t => t[0]); } public static byte[] ReadAllBytes(this IVirtualFile file) { using var stream = file.OpenRead(); var bytes = stream.ReadFully(); return bytes; } public static bool Exists(this IVirtualNode node) { return node != null; } public static bool IsFile(this IVirtualNode node) { return node is IVirtualFile; } public static bool IsDirectory(this IVirtualNode node) { return node is IVirtualDirectory; } public static IVirtualNode GetVirtualNode(this IVirtualPathProvider pathProvider, string virtualPath) { return (IVirtualNode)pathProvider.GetFile(virtualPath) ?? pathProvider.GetDirectory(virtualPath); } public static IVirtualFile GetDefaultDocument(this IVirtualDirectory dir, List<string> defaultDocuments) { foreach (var defaultDoc in defaultDocuments) { var defaultFile = dir.GetFile(defaultDoc); if (defaultFile == null) continue; return defaultFile; } return null; } public static TimeSpan MaxRetryOnExceptionTimeout { get; } = TimeSpan.FromSeconds(10); internal static void SleepBackOffMultiplier(this int i) { var nextTryMs = (2 ^ i) * 50; #if NETCORE System.Threading.Tasks.Task.Delay(nextTryMs).Wait(); #elif NETFX System.Threading.Thread.Sleep(nextTryMs); #endif } public static readonly HashSet<char> InvalidFileNameChars = new(Path.GetInvalidFileNameChars()) { ':' }; public static string SafeFileName(string uri) => new(uri.Where(c => !InvalidFileNameChars.Contains(c)).ToArray()); public static bool IsValidFileName(string path) => !string.IsNullOrEmpty(path) && path.All(c => !InvalidFileNameChars.Contains(c)); public static bool IsValidFilePath(string path) { if (string.IsNullOrEmpty(path)) return false; foreach (var c in path) { if (c == '/') continue; if (InvalidFileNameChars.Contains(c)) return false; } return true; } }
VirtualPathUtils
csharp
dotnet__orleans
test/DefaultCluster.Tests/Migration/MigrationTests.cs
{ "start": 17379, "end": 17590 }
public interface ____ : IGrainWithIntegerKey { ValueTask SetState(int state); ValueTask<int> GetState(); ValueTask<GrainAddress> GetGrainAddress(); }
IMigrationTestGrain_GrainOfT
csharp
microsoft__FASTER
cs/src/core/Epochs/EpochProtectedVersionScheme.cs
{ "start": 8587, "end": 9037 }
public enum ____ { /// <summary> /// execution successful /// </summary> OK, /// <summary> /// execution unsuccessful but may be retried /// </summary> RETRY, /// <summary> /// execution failed and should not be retried /// </summary> FAIL } /// <summary> /// Epoch Protected Version Scheme /// </summary>
StateMachineExecutionStatus
csharp
ShareX__ShareX
ShareX.UploadersLib/CustomUploader/Functions/CustomUploaderFunctionInputBox.cs
{ "start": 1186, "end": 1914 }
internal class ____ : CustomUploaderFunction { public override string Name { get; } = "inputbox"; public override string[] Aliases { get; } = new string[] { "prompt" }; public override string Call(ShareXCustomUploaderSyntaxParser parser, string[] parameters) { string title = "Input"; string defaultText = ""; if (parameters != null && parameters.Length > 0) { title = parameters[0]; if (parameters.Length > 1) { defaultText = parameters[1]; } } return InputBox.Show(title, defaultText); } } }
CustomUploaderFunctionInputBox
csharp
EventStore__EventStore
src/KurrentDB.Core/ExclusiveDbLock.cs
{ "start": 355, "end": 1899 }
public class ____ : IDisposable { private static readonly ILogger Log = Serilog.Log.ForContext<ExclusiveDbLock>(); public readonly string MutexName; public bool IsAcquired => _acquired; private Mutex _dbMutex; private bool _acquired; public ExclusiveDbLock(string dbPath) { Ensure.NotNullOrEmpty(dbPath, "dbPath"); MutexName = @"Global\ESDB-HASHED:" + GetDbPathHash(dbPath); } public bool Acquire() { if (_acquired) throw new InvalidOperationException($"DB mutex '{MutexName}' is already acquired."); try { _dbMutex?.Dispose(); _dbMutex = new Mutex(initiallyOwned: true, name: MutexName, createdNew: out _acquired); _dbMutex.WaitOne(TimeSpan.FromSeconds(5)); } catch (AbandonedMutexException exc) { Log.Warning(exc, "DB mutex '{mutex}' is said to be abandoned. " + "Probably previous instance of server was terminated abruptly.", MutexName); } return _acquired; } private static string GetDbPathHash(string dbPath) { using var memStream = new MemoryStream(Helper.UTF8NoBom.GetBytes(dbPath)); return BitConverter.ToString(MD5Hash.GetHashFor(memStream)).Replace("-", ""); } public void Release() { if (!_acquired) throw new InvalidOperationException($"DB mutex '{MutexName}' was not acquired."); try { _dbMutex.ReleaseMutex(); } catch (ApplicationException ex) { Log.Warning(ex, "Error occurred while releasing lock."); } finally { _acquired = false; } } public void Dispose() { if (_acquired) { Release(); } _dbMutex?.Dispose(); } }
ExclusiveDbLock
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Types/InputObjectGraphTypeTests.cs
{ "start": 3904, "end": 6038 }
public class ____ : InputObjectGraphType<MyInput3> { public MyInput3Type() { Field(x => x.Name); } public override void Initialize(ISchema schema) { } } [Fact] public async Task input_parser_works() { // demonstrates having a StringGraphType field that accepts a Uri as input // the string value is coerced to a Uri prior to beginning execution of the request var inputType = new InputObjectGraphType<Class1>(); inputType.Field(x => x.Url, type: typeof(StringGraphType)) .ParseValue(value => new Uri((string)value)); var queryType = new ObjectGraphType(); queryType.Field<StringGraphType>( "test", arguments: new QueryArguments( new QueryArgument(inputType) { Name = "input" }), resolve: context => { var input = context.GetArgument<Class1>("input"); return input.Url?.ToString(); }); var schema = new Schema { Query = queryType }; // check with valid url var result = await schema.ExecuteAsync(_ => _.Query = """{ test(input: { url: "http://www.google.com" }) }"""); result.ShouldBeSimilarTo("""{"data":{"test":"http://www.google.com/"}}"""); // check with invalid url result = await schema.ExecuteAsync(_ => _.Query = """{ test(input: { url: "abcd" }) }"""); result.ShouldBeSimilarTo( """ {"errors":[ { "message":"Invalid value for argument \u0027input\u0027 of field \u0027test\u0027. Invalid URI: The format of the URI could not be determined.", "locations":[{"line":1,"column":22}], "extensions":{ "code":"INVALID_VALUE", "codes":["INVALID_VALUE","URI_FORMAT"], "number":"5.6" } } ]} """); }
MyInput3Type
csharp
SixLabors__ImageSharp
tests/ImageSharp.Tests/Processing/Convolution/KernelSamplingMapTest.cs
{ "start": 237, "end": 11722 }
public class ____ { [Fact] public void KernalSamplingMap_Kernel5Image7x7RepeatBorder() { Size kernelSize = new(5, 5); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Repeat; int[] expected = [ 0, 0, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 6, 4, 5, 6, 6, 6 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image7x7BounceBorder() { Size kernelSize = new(5, 5); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Bounce; int[] expected = [ 2, 1, 0, 1, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 5, 4, 5, 6, 5, 4 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image7x7MirrorBorder() { Size kernelSize = new(5, 5); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Mirror; int[] expected = [ 1, 0, 0, 1, 2, 0, 0, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 6, 4, 5, 6, 6, 5 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image7x7WrapBorder() { Size kernelSize = new(5, 5); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Wrap; int[] expected = [ 5, 6, 0, 1, 2, 6, 0, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 0, 4, 5, 6, 0, 1 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image9x9BounceBorder() { Size kernelSize = new(5, 5); Rectangle bounds = new(1, 1, 9, 9); BorderWrappingMode mode = BorderWrappingMode.Bounce; int[] expected = [ 3, 2, 1, 2, 3, 2, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 6, 7, 8, 9, 8, 7, 8, 9, 8, 7 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image9x9MirrorBorder() { Size kernelSize = new(5, 5); Rectangle bounds = new(1, 1, 9, 9); BorderWrappingMode mode = BorderWrappingMode.Mirror; int[] expected = [ 2, 1, 1, 2, 3, 1, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 6, 7, 8, 9, 9, 7, 8, 9, 9, 8 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image9x9WrapBorder() { Size kernelSize = new(5, 5); Rectangle bounds = new(1, 1, 9, 9); BorderWrappingMode mode = BorderWrappingMode.Wrap; int[] expected = [ 8, 9, 1, 2, 3, 9, 1, 2, 3, 4, 1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 6, 7, 8, 9, 1, 7, 8, 9, 1, 2 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image7x7RepeatBorderTile() { Size kernelSize = new(5, 5); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Repeat; int[] expected = [ 2, 2, 2, 3, 4, 2, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 8, 6, 7, 8, 8, 8 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image7x7BounceBorderTile() { Size kernelSize = new(5, 5); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Bounce; int[] expected = [ 4, 3, 2, 3, 4, 3, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 7, 6, 7, 8, 7, 6 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image7x7MirrorBorderTile() { Size kernelSize = new(5, 5); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Mirror; int[] expected = [ 3, 2, 2, 3, 4, 2, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 8, 6, 7, 8, 8, 7 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel5Image7x7WrapBorderTile() { Size kernelSize = new(5, 5); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Wrap; int[] expected = [ 7, 8, 2, 3, 4, 8, 2, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7, 4, 5, 6, 7, 8, 5, 6, 7, 8, 2, 6, 7, 8, 2, 3 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7x7RepeatBorder() { Size kernelSize = new(3, 3); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Repeat; int[] expected = [ 0, 0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 6 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7x7BounceBorder() { Size kernelSize = new(3, 3); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Bounce; int[] expected = [ 1, 0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 5 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7x7MirrorBorder() { Size kernelSize = new(3, 3); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Mirror; int[] expected = [ 0, 0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 6 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7x7WrapBorder() { Size kernelSize = new(3, 3); Rectangle bounds = new(0, 0, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Wrap; int[] expected = [ 6, 0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 0 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7x7RepeatBorderTile() { Size kernelSize = new(3, 3); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Repeat; int[] expected = [ 2, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 8 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7BounceBorderTile() { Size kernelSize = new(3, 3); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Bounce; int[] expected = [ 3, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 7 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7MirrorBorderTile() { Size kernelSize = new(3, 3); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Mirror; int[] expected = [ 2, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 8 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7x7WrapBorderTile() { Size kernelSize = new(3, 3); Rectangle bounds = new(2, 2, 7, 7); BorderWrappingMode mode = BorderWrappingMode.Wrap; int[] expected = [ 8, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 2 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, expected, expected); } [Fact] public void KernalSamplingMap_Kernel3Image7x5WrapBorderTile() { Size kernelSize = new(3, 3); Rectangle bounds = new(2, 2, 7, 5); BorderWrappingMode mode = BorderWrappingMode.Wrap; int[] xExpected = [ 8, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 7, 6, 7, 8, 7, 8, 2 ]; int[] yExpected = [ 6, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6, 5, 6, 2 ]; this.AssertOffsets(kernelSize, bounds, mode, mode, xExpected, yExpected); } private void AssertOffsets(Size kernelSize, Rectangle bounds, BorderWrappingMode xBorderMode, BorderWrappingMode yBorderMode, int[] xExpected, int[] yExpected) { // Arrange KernelSamplingMap map = new(Configuration.Default.MemoryAllocator); // Act map.BuildSamplingOffsetMap(kernelSize.Height, kernelSize.Width, bounds, xBorderMode, yBorderMode); // Assert int[] xOffsets = map.GetColumnOffsetSpan().ToArray(); Assert.Equal(xExpected, xOffsets); int[] yOffsets = map.GetRowOffsetSpan().ToArray(); Assert.Equal(yExpected, yOffsets); } }
KernelSamplingMapTest
csharp
NLog__NLog
src/NLog/Internal/DictionaryEntryEnumerable.cs
{ "start": 2628, "end": 3536 }
struct ____ : IEnumerator<DictionaryEntry> { private readonly IDictionaryEnumerator _entryEnumerator; public DictionaryEntry Current => _entryEnumerator.Entry; public DictionaryEntryEnumerator(IDictionary? dictionary) { _entryEnumerator = dictionary?.Count > 0 ? dictionary.GetEnumerator() : EmptyDictionaryEnumerator.Default; } object IEnumerator.Current => Current; public void Dispose() { if (_entryEnumerator is IDisposable disposable) disposable.Dispose(); } public bool MoveNext() { return _entryEnumerator.MoveNext(); } public void Reset() { _entryEnumerator.Reset(); } }
DictionaryEntryEnumerator
csharp
exceptionless__Exceptionless
src/Exceptionless.Core/Models/UsageInfo.cs
{ "start": 290, "end": 510 }
public record ____ { public DateTime Date { get; init; } public int Total { get; set; } public int Blocked { get; set; } public int Discarded { get; set; } public int TooBig { get; set; } }
UsageHourInfo
csharp
microsoft__garnet
test/Garnet.test.cluster/RedirectTests/BaseCommand.cs
{ "start": 55987, "end": 56587 }
internal class ____ : BaseCommand { public override bool IsArrayCommand => false; public override bool ArrayResponse => false; public override string Command => nameof(LINSERT); public override string[] GetSingleSlotRequest() { var ssk = GetSingleSlotKeys; return [ssk[0], "BEFORE", "aaa", "bbb"]; } public override string[] GetCrossSlotRequest() => throw new NotImplementedException(); public override ArraySegment<string>[] SetupSingleSlotRequest() => throw new NotImplementedException(); }
LINSERT
csharp
microsoft__FASTER
cs/test/CompletePendingTests.cs
{ "start": 13048, "end": 13744 }
record ____ firstValue = 0; // same as key var keyStruct = new KeyStruct { kfield1 = firstValue, kfield2 = firstValue * valueMult }; var valueStruct = new ValueStruct { vfield1 = firstValue, vfield2 = firstValue * valueMult }; session.Upsert(ref keyStruct, ref valueStruct); // Flush to make the Read() go pending. fht.Log.FlushAndEvict(wait: true); ReadOptions readOptions = new() { StartAddress = startAddress }; var (status, outputStruct) = session.Read(keyStruct, ref readOptions); Assert.IsTrue(status.IsPending, $"Expected status.IsPending: {status}"); // Insert next
var
csharp
dotnet__extensions
src/Libraries/Microsoft.Extensions.AI.AzureAIInference/AzureAIInferenceChatClient.cs
{ "start": 875, "end": 1892 }
internal sealed class ____ : IChatClient { /// <summary>Gets the JSON schema transform cache conforming to OpenAI restrictions per https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas.</summary> private static AIJsonSchemaTransformCache SchemaTransformCache { get; } = new(new() { RequireAllProperties = true, DisallowAdditionalProperties = true, ConvertBooleanSchemas = true, MoveDefaultKeywordToDescription = true, }); /// <summary>Metadata about the client.</summary> private readonly ChatClientMetadata _metadata; /// <summary>The underlying <see cref="ChatCompletionsClient" />.</summary> private readonly ChatCompletionsClient _chatCompletionsClient; /// <summary>Gets a ChatRole.Developer value.</summary> private static ChatRole ChatRoleDeveloper { get; } = new("developer"); /// <summary>Initializes a new instance of the <see cref="AzureAIInferenceChatClient"/>
AzureAIInferenceChatClient
csharp
microsoft__semantic-kernel
dotnet/samples/Concepts/Memory/VectorStore_DynamicDataModel_Interop.cs
{ "start": 862, "end": 2355 }
public class ____(ITestOutputHelper output, VectorStoreQdrantContainerFixture qdrantFixture) : BaseTest(output), IClassFixture<VectorStoreQdrantContainerFixture> { private static readonly JsonSerializerOptions s_indentedSerializerOptions = new() { WriteIndented = true }; private static readonly VectorStoreCollectionDefinition s_definition = new() { Properties = new List<VectorStoreProperty> { new VectorStoreKeyProperty("Key", typeof(ulong)), new VectorStoreDataProperty("Term", typeof(string)), new VectorStoreDataProperty("Definition", typeof(string)), new VectorStoreVectorProperty("DefinitionEmbedding", typeof(ReadOnlyMemory<float>), 1536) } }; [Fact] public async Task UpsertWithDynamicRetrieveWithCustomAsync() { // Create an embedding generation service. var embeddingGenerator = new AzureOpenAIClient(new Uri(TestConfiguration.AzureOpenAIEmbeddings.Endpoint), new AzureCliCredential()) .GetEmbeddingClient(TestConfiguration.AzureOpenAIEmbeddings.DeploymentName) .AsIEmbeddingGenerator(1536); // Initiate the docker container and construct the vector store. await qdrantFixture.ManualInitializeAsync(); var vectorStore = new QdrantVectorStore(new QdrantClient("localhost"), ownsClient: true); // Get and create collection if it doesn't exist using the dynamic data model and
VectorStore_DynamicDataModel_Interop
csharp
pythonnet__pythonnet
src/testing/arraytest.cs
{ "start": 1951, "end": 2130 }
public class ____ { public long[] items; public Int64ArrayTest() { items = new long[5] { 0, 1, 2, 3, 4 }; } }
Int64ArrayTest
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Application/Services/Dto/IHasLongTotalCount.cs
{ "start": 185, "end": 351 }
public interface ____ { /// <summary> /// Total count of Items. /// </summary> long TotalCount { get; set; } } }
IHasLongTotalCount
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeResolverTests.cs
{ "start": 4716, "end": 4819 }
public class ____(string baz) { public string Baz { get; } = baz; } public readonly
Bar
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests/Firebird/Curd/FirebirdUpdateTest.cs
{ "start": 302, "end": 680 }
class ____ { [Column(IsIdentity = true, IsPrimary = true)] public int Id { get; set; } public int? Clicks { get; set; } public TestTypeInfo Type { get; set; } public string Title { get; set; } public DateTime CreateTime { get; set; } } [Table(Name = "tb_topic_setsource")]
Topic
csharp
EventStore__EventStore
src/SchemaRegistry/KurrentDB.SchemaRegistry.Tests/Modules/Schemas/Validators/RegisterSchemaRequestValidatorTests.cs
{ "start": 3367, "end": 3593 }
public class ____ : TestCaseGenerator<string> { // protected override IEnumerable<string> Data() { // yield return ""; // yield return " "; // } // } // //
EmptySchemaNameTestCases
csharp
StackExchange__StackExchange.Redis
tests/StackExchange.Redis.Tests/ConstraintsTests.cs
{ "start": 83, "end": 1443 }
public class ____(ITestOutputHelper output, SharedConnectionFixture fixture) : TestBase(output, fixture) { [Fact] public void ValueEquals() { RedisValue x = 1, y = "1"; Assert.True(x.Equals(y), "equals"); Assert.True(x == y, "operator"); } [Fact] public async Task TestManualIncr() { await using var conn = Create(syncTimeout: 120000); // big timeout while debugging var key = Me(); var db = conn.GetDatabase(); for (int i = 0; i < 10; i++) { db.KeyDelete(key, CommandFlags.FireAndForget); Assert.Equal(1, await ManualIncrAsync(db, key).ForAwait()); Assert.Equal(2, await ManualIncrAsync(db, key).ForAwait()); Assert.Equal(2, (long)db.StringGet(key)); } } public static async Task<long?> ManualIncrAsync(IDatabase connection, RedisKey key) { var oldVal = (long?)await connection.StringGetAsync(key).ForAwait(); var newVal = (oldVal ?? 0) + 1; var tran = connection.CreateTransaction(); { // check hasn't changed tran.AddCondition(Condition.StringEqual(key, oldVal)); _ = tran.StringSetAsync(key, newVal); if (!await tran.ExecuteAsync().ForAwait()) return null; // aborted return newVal; } } }
ConstraintsTests
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Media/TextFormatting/Unicode/Script.cs
{ "start": 54, "end": 4425 }
public enum ____ { Unknown, //Zzzz Common, //Zyyy Inherited, //Zinh Adlam, //Adlm CaucasianAlbanian, //Aghb Ahom, //Ahom Arabic, //Arab ImperialAramaic, //Armi Armenian, //Armn Avestan, //Avst Balinese, //Bali Bamum, //Bamu BassaVah, //Bass Batak, //Batk Bengali, //Beng Bhaiksuki, //Bhks Bopomofo, //Bopo Brahmi, //Brah Braille, //Brai Buginese, //Bugi Buhid, //Buhd Chakma, //Cakm CanadianAboriginal, //Cans Carian, //Cari Cham, //Cham Cherokee, //Cher Chorasmian, //Chrs Coptic, //Copt CyproMinoan, //Cpmn Cypriot, //Cprt Cyrillic, //Cyrl Devanagari, //Deva DivesAkuru, //Diak Dogra, //Dogr Deseret, //Dsrt Duployan, //Dupl EgyptianHieroglyphs, //Egyp Elbasan, //Elba Elymaic, //Elym Ethiopic, //Ethi Garay, //Gara Georgian, //Geor Glagolitic, //Glag GunjalaGondi, //Gong MasaramGondi, //Gonm Gothic, //Goth Grantha, //Gran Greek, //Grek Gujarati, //Gujr GurungKhema, //Gukh Gurmukhi, //Guru Hangul, //Hang Han, //Hani Hanunoo, //Hano Hatran, //Hatr Hebrew, //Hebr Hiragana, //Hira AnatolianHieroglyphs, //Hluw PahawhHmong, //Hmng NyiakengPuachueHmong, //Hmnp KatakanaOrHiragana, //Hrkt OldHungarian, //Hung OldItalic, //Ital Javanese, //Java KayahLi, //Kali Katakana, //Kana Kawi, //Kawi Kharoshthi, //Khar Khmer, //Khmr Khojki, //Khoj KhitanSmallScript, //Kits Kannada, //Knda KiratRai, //Krai Kaithi, //Kthi TaiTham, //Lana Lao, //Laoo Latin, //Latn Lepcha, //Lepc Limbu, //Limb LinearA, //Lina LinearB, //Linb Lisu, //Lisu Lycian, //Lyci Lydian, //Lydi Mahajani, //Mahj Makasar, //Maka Mandaic, //Mand Manichaean, //Mani Marchen, //Marc Medefaidrin, //Medf MendeKikakui, //Mend MeroiticCursive, //Merc MeroiticHieroglyphs, //Mero Malayalam, //Mlym Modi, //Modi Mongolian, //Mong Mro, //Mroo MeeteiMayek, //Mtei Multani, //Mult Myanmar, //Mymr NagMundari, //Nagm Nandinagari, //Nand OldNorthArabian, //Narb Nabataean, //Nbat Newa, //Newa Nko, //Nkoo Nushu, //Nshu Ogham, //Ogam OlChiki, //Olck OlOnal, //Onao OldTurkic, //Orkh Oriya, //Orya Osage, //Osge Osmanya, //Osma OldUyghur, //Ougr Palmyrene, //Palm PauCinHau, //Pauc OldPermic, //Perm PhagsPa, //Phag InscriptionalPahlavi, //Phli PsalterPahlavi, //Phlp Phoenician, //Phnx Miao, //Plrd InscriptionalParthian, //Prti Rejang, //Rjng HanifiRohingya, //Rohg Runic, //Runr Samaritan, //Samr OldSouthArabian, //Sarb Saurashtra, //Saur SignWriting, //Sgnw Shavian, //Shaw Sharada, //Shrd Siddham, //Sidd Khudawadi, //Sind Sinhala, //Sinh Sogdian, //Sogd OldSogdian, //Sogo SoraSompeng, //Sora Soyombo, //Soyo Sundanese, //Sund Sunuwar, //Sunu SylotiNagri, //Sylo Syriac, //Syrc Tagbanwa, //Tagb Takri, //Takr TaiLe, //Tale NewTaiLue, //Talu Tamil, //Taml Tangut, //Tang TaiViet, //Tavt Telugu, //Telu Tifinagh, //Tfng Tagalog, //Tglg Thaana, //Thaa Thai, //Thai Tibetan, //Tibt Tirhuta, //Tirh Tangsa, //Tnsa Todhri, //Todr Toto, //Toto TuluTigalari, //Tutg Ugaritic, //Ugar Vai, //Vaii Vithkuqi, //Vith WarangCiti, //Wara Wancho, //Wcho OldPersian, //Xpeo Cuneiform, //Xsux Yezidi, //Yezi Yi, //Yiii ZanabazarSquare, //Zanb } }
Script
csharp
AutoMapper__AutoMapper
src/UnitTests/ReverseMapping.cs
{ "start": 204, "end": 540 }
class ____ { public Guid Id { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(c=> c.CreateMap<Destination, Source>().ForMember(src => src.Id, opt => opt.MapFrom(_ => Guid.Empty)).ReverseMap()); [Fact] public void Validate() => AssertConfigurationIsValid(); }
Destination
csharp
dotnet__efcore
test/EFCore.Tests/Metadata/Internal/EntityTypeTest.cs
{ "start": 144518, "end": 145483 }
private class ____ : BaseType { public static readonly PropertyInfo IdProperty = typeof(Order).GetProperty(nameof(Id)); public static readonly PropertyInfo CustomerProperty = typeof(Order).GetProperty(nameof(Customer)); public static readonly PropertyInfo CustomerIdProperty = typeof(Order).GetProperty(nameof(CustomerId)); public static readonly PropertyInfo CustomerUniqueProperty = typeof(Order).GetProperty(nameof(CustomerUnique)); public static readonly PropertyInfo RelatedOrderProperty = typeof(Order).GetProperty(nameof(RelatedOrder)); public static readonly PropertyInfo ProductsProperty = typeof(Order).GetProperty(nameof(Products)); public int CustomerId { get; set; } public Guid CustomerUnique { get; set; } public Customer Customer { get; set; } public Order RelatedOrder { get; set; } public virtual ICollection<Product> Products { get; set; } }
Order
csharp
grandnode__grandnode2
src/Modules/Grand.Module.Api/DTOs/Catalog/CategoryDTO.cs
{ "start": 75, "end": 1244 }
public class ____ : BaseApiEntityModel { public string Name { get; set; } public string Description { get; set; } public string BottomDescription { get; set; } public string CategoryLayoutId { get; set; } public string MetaKeywords { get; set; } public string MetaDescription { get; set; } public string MetaTitle { get; set; } public string SeName { get; set; } public string ParentCategoryId { get; set; } public string PictureId { get; set; } public int PageSize { get; set; } public bool AllowCustomersToSelectPageSize { get; set; } public string PageSizeOptions { get; set; } public bool ShowOnHomePage { get; set; } public bool FeaturedProductsOnHomePage { get; set; } public bool IncludeInMenu { get; set; } public bool Published { get; set; } public int DisplayOrder { get; set; } public string ExternalId { get; set; } public string Flag { get; set; } public string FlagStyle { get; set; } public string Icon { get; set; } public bool HideOnCatalog { get; set; } public bool ShowOnSearchBox { get; set; } public int SearchBoxDisplayOrder { get; set; } }
CategoryDto
csharp
bitwarden__server
src/Infrastructure.EntityFramework/AdminConsole/Models/OrganizationIntegration.cs
{ "start": 250, "end": 487 }
public class ____ : Profile { public OrganizationIntegrationMapperProfile() { CreateMap<Core.AdminConsole.Entities.OrganizationIntegration, OrganizationIntegration>().ReverseMap(); } }
OrganizationIntegrationMapperProfile
csharp
EventStore__EventStore
src/KurrentDB.Core/LogV2/LogV2StreamExistenceFilterInitializer.cs
{ "start": 1066, "end": 1115 }
record ____ initialized /// on startup next time.
is
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Data/Migration/AutomaticDataMigrations.cs
{ "start": 339, "end": 1620 }
public sealed class ____ : ModularTenantEvents { private readonly ShellSettings _shellSettings; private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; /// <summary> /// Creates a new instance of the <see cref="AutomaticDataMigrations"/>. /// </summary> /// <param name="serviceProvider">The <see cref="IServiceProvider"/>.</param> /// <param name="shellSettings">The <see cref="ShellSettings"/>.</param> /// <param name="logger">The <see cref="ILogger"/>.</param> public AutomaticDataMigrations( IServiceProvider serviceProvider, ShellSettings shellSettings, ILogger<AutomaticDataMigrations> logger) { _serviceProvider = serviceProvider; _shellSettings = shellSettings; _logger = logger; } /// <inheritdocs /> public override Task ActivatingAsync() { if (!_shellSettings.IsUninitialized()) { _logger.LogDebug("Executing data migrations for shell '{Name}'", _shellSettings.Name); var dataMigrationManager = _serviceProvider.GetService<IDataMigrationManager>(); return dataMigrationManager.UpdateAllFeaturesAsync(); } return Task.CompletedTask; } }
AutomaticDataMigrations
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Media/Effects/DropShadowEffect.cs
{ "start": 1212, "end": 2174 }
public sealed class ____ : DropShadowEffectBase, IDropShadowEffect, IMutableEffect { public static readonly StyledProperty<double> OffsetXProperty = AvaloniaProperty.Register<DropShadowEffect, double>( nameof(OffsetX), 3.5355); public double OffsetX { get => GetValue(OffsetXProperty); set => SetValue(OffsetXProperty, value); } public static readonly StyledProperty<double> OffsetYProperty = AvaloniaProperty.Register<DropShadowEffect, double>( nameof(OffsetY), 3.5355); public double OffsetY { get => GetValue(OffsetYProperty); set => SetValue(OffsetYProperty, value); } static DropShadowEffect() { AffectsRender<DropShadowEffect>(OffsetXProperty, OffsetYProperty); } public IImmutableEffect ToImmutable() { return new ImmutableDropShadowEffect(OffsetX, OffsetY, BlurRadius, Color, Opacity); } } /// <summary> /// This
DropShadowEffect
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.OpenApi.Tests/Services/NativeTypesTestService.cs
{ "start": 53, "end": 5579 }
public class ____ : Service { public object Any(Hello request) { return new HelloResponse { Result = "Hello, {0}{1}!".Fmt( request.Title != null ? request.Title + ". " : "", request.Name) }; } public object Any(HelloAnnotated request) { return new HelloAnnotatedResponse { Result = request.Name }; } public object Any(HelloWithNestedClass request) { return new HelloResponse { Result = request.Name }; } public object Any(HelloList request) { return request.Names.Map(name => new ListResult { Result = name }); } public object Any(HelloArray request) { return request.Names.Map(name => new ArrayResult { Result = name }); } public object Any(HelloWithEnum request) { return request; } public object Any(HelloExternal request) { return request; } public object Any(RestrictedAttributes request) { return request; } public object Any(AllowedAttributes request) { return request; } public object Any(HelloAllTypes request) { return new HelloAllTypesResponse { AllTypes = request.AllTypes, AllCollectionTypes = request.AllCollectionTypes, Result = request.Name }; } public object Any(HelloAllTypesWithResult request) { return new HelloAllTypesResponse { AllTypes = request.AllTypes, AllCollectionTypes = request.AllCollectionTypes, Result = request.Name }; } public object Any(AllTypes request) { return request; } public object Any(HelloString request) { return request.Name; } public object Any(HelloDateTime request) { return request; } public void Any(HelloVoid request) { } public object Any(HelloWithDataContract request) { return new HelloWithDataContractResponse { Result = request.Name }; } public object Any(HelloWithDescription request) { return new HelloWithDescriptionResponse { Result = request.Name }; } public object Any(HelloWithInheritance request) { return new HelloWithInheritanceResponse { Result = request.Name }; } public object Any(HelloWithGenericInheritance request) { return request; } public object Any(HelloWithGenericInheritance2 request) { return request; } public object Any(HelloWithNestedInheritance request) { return request; } //public object Any(HelloWithListInheritance request) //{ // return request; //} public object Any(HelloWithReturn request) { return new HelloWithAlternateReturnResponse { Result = request.Name }; } public object Any(HelloWithRoute request) { return new HelloWithRouteResponse { Result = request.Name }; } public object Any(HelloWithType request) { return new HelloWithTypeResponse { Result = new HelloType { Result = request.Name } }; } public object Any(HelloInterface request) { return request; } public object Any(HelloInnerTypes request) { return new HelloInnerTypesResponse(); } //Uncomment to generate SS.Client built-in types //public object Any(GenerateBuiltInTypes request) //{ // return request; //} public object Any(HelloBuiltin request) { return request; } public object Any(HelloGet request) { return new HelloVerbResponse { Result = HttpMethods.Get }; } public object Any(HelloPost request) { return new HelloVerbResponse { Result = HttpMethods.Post }; } public object Any(HelloPut request) { return new HelloVerbResponse { Result = HttpMethods.Put }; } public object Any(HelloDelete request) { return new HelloVerbResponse { Result = HttpMethods.Delete }; } public object Any(HelloPatch request) { return new HelloVerbResponse { Result = HttpMethods.Patch }; } public void Any(HelloReturnVoid request) { } public object Any(EnumRequest request) { return new EnumResponse { Operator = request.Operator }; } public object Any(HelloTypes request) { return request; } public object Any(HelloZip request) { return request.Test == null ? new HelloZipResponse { Result = $"Hello, {request.Name} {base.Request.ContentLength}" } : new HelloZipResponse { Result = $"Hello, {request.Name} ({request.Test?.Count}) {base.Request.ContentLength}" }; } } }
NativeTypesTestService
csharp
restsharp__RestSharp
src/RestSharp.Serializers.Xml/DeserializeAsAttribute.cs
{ "start": 740, "end": 925 }
class ____ property names and values are deserialized by XmlAttributeDeserializer /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)]
and
csharp
microsoft__garnet
playground/ClusterStress/ReqGenUtilsCluster.cs
{ "start": 141, "end": 15028 }
partial class ____ { static readonly bool invalidateHLL = false; private bool WriteHeader(byte[] headerData, ref byte* curr, byte* vend) { byte* save = curr; if (curr + headerData.Length >= vend) return false; for (int i = 0; i < headerData.Length; i++) *curr++ = headerData[i]; return true; } private bool WriteBitfieldArgs(ref byte* curr, byte* vend, byte[] bitfieldOpType) { int offset = valueRandomGen.Next(0, (valueBuffer.Length << 3) - 64); int bitCount = valueRandomGen.Next(1, 64); long vset = RandomIntBitRange(bitCount, true); byte[] typeData = Encoding.ASCII.GetBytes("i" + bitCount.ToString()); WriteStringBytes(ref curr, vend, bitfieldOpType); WriteStringBytes(ref curr, vend, typeData); WriteInteger(offset, ref curr, vend); if (bitfieldOpType[0] == 'G') return true; WriteInteger(vset, ref curr, vend); return true; } private bool WriteInteger(int n, ref byte* curr, byte* vend) { int nd = NumUtils.NumDigits(n); int sign = ((n < 0) ? 1 : 0); int ndSize = NumUtils.NumDigits(nd + sign); int totalLen = 1 + ndSize + 2 + (nd + sign) + 2; if (curr + totalLen >= vend) return false; *curr++ = (byte)'$'; NumUtils.IntToBytes(nd + sign, ref curr); *curr++ = (byte)'\r'; *curr++ = (byte)'\n'; NumUtils.IntToBytes(n, nd, ref curr); *curr++ = (byte)'\r'; *curr++ = (byte)'\n'; return true; } private bool WriteInteger(long n, ref byte* curr, byte* vend) { int nd = NumUtils.NumDigitsInLong(n); int sign = ((n < 0) ? 1 : 0); int ndSize = NumUtils.NumDigits(nd + sign); int totalLen = 1 + ndSize + 2 + (nd + sign) + 2; if (curr + totalLen >= vend) return false; *curr++ = (byte)'$'; NumUtils.IntToBytes(nd + sign, ref curr); *curr++ = (byte)'\r'; *curr++ = (byte)'\n'; NumUtils.LongToBytes(n, nd, ref curr); *curr++ = (byte)'\r'; *curr++ = (byte)'\n'; return true; } private bool WriteStringBytes(ref byte* curr, byte* vend, byte[] data) { int digits = NumUtils.NumDigits(data.Length); int totalLen = 1 + digits + 2 + data.Length + 2; if (curr + totalLen >= vend) return false; *curr++ = (byte)'$'; NumUtils.IntToBytes(data.Length, ref curr); *curr++ = (byte)'\r'; *curr++ = (byte)'\n'; for (int i = 0; i < data.Length; i++) *curr++ = (byte)data[i]; *curr++ = (byte)'\r'; *curr++ = (byte)'\n'; return true; } private bool WriteOp(ref byte* curr, byte* vend, OpType opType) { int n; var bitopType = opType switch { OpType.BITOP_AND => Encoding.ASCII.GetBytes("AND"), OpType.BITOP_OR => Encoding.ASCII.GetBytes("OR"), OpType.BITOP_XOR => Encoding.ASCII.GetBytes("XOR"), OpType.BITOP_NOT => Encoding.ASCII.GetBytes("NOT"), _ => null }; byte[] keyData = null; //key switch (opType) { case OpType.ZADD: case OpType.ZREM: case OpType.ZCARD: case OpType.GEOADD: case OpType.PFADD: if (!WriteKey(ref curr, vend)) return false; break; case OpType.PFCOUNT: if (!WriteKey(ref curr, vend, out keyData)) return false; if (invalidateHLL) { //Try to invalidate PFCOUNT if (!WriteHeader(Encoding.ASCII.GetBytes($"*3\r\n$5\r\nPFADD\r\n"), ref curr, vend)) return false; if (!WriteStringBytes(ref curr, vend, keyData)) return false; RandomString(); if (!WriteStringBytes(ref curr, vend, valueBuffer)) return false; } break; case OpType.PFMERGE: int key = keyRandomGen.Next(0, hllDstMergeKeyCount); if (!WriteKey(ref curr, vend, key)) return false; if (invalidateHLL) { //Try to delete merge HLL if (!WriteHeader(Encoding.ASCII.GetBytes($"*2\r\n$3\r\nDEL\r\n"), ref curr, vend)) return false; if (!WriteKey(ref curr, vend, key)) return false; } break; case OpType.MSET: case OpType.INCR: case OpType.GET: case OpType.SET: case OpType.SETEX: case OpType.MGET: case OpType.SETBIT: case OpType.GETBIT: case OpType.BITCOUNT: case OpType.BITPOS: case OpType.SETIFPM: case OpType.MYDICTSET: case OpType.MYDICTGET: if (!WriteKey(ref curr, vend, out keyData)) return false; break; case OpType.BITOP_AND: case OpType.BITOP_OR: case OpType.BITOP_XOR: case OpType.BITOP_NOT: if (!WriteStringBytes(ref curr, vend, bitopType)) return false; break; case OpType.BITFIELD: case OpType.BITFIELD_GET: case OpType.BITFIELD_SET: case OpType.BITFIELD_INCR: if (!WriteKey(ref curr, vend)) return false; break; case OpType.PING: return true; default: break; } //arg1 switch (opType) { case OpType.ZADD: case OpType.ZREM: n = Start + r.Next(DbSize); if (!WriteInteger(n, ref curr, vend)) return false; break; case OpType.PFADD: case OpType.MSET: if (valueLen == 0) { if (!WriteStringBytes(ref curr, vend, keyData)) return false; } else { RandomString(); if (!WriteStringBytes(ref curr, vend, valueBuffer)) return false; } break; case OpType.MYDICTSET: if (!WriteStringBytes(ref curr, vend, keyData)) return false; if (valueLen == 0) { if (!WriteStringBytes(ref curr, vend, keyData)) return false; } else { RandomString(); if (!WriteStringBytes(ref curr, vend, valueBuffer)) return false; } break; case OpType.MYDICTGET: if (!WriteStringBytes(ref curr, vend, keyData)) return false; break; case OpType.SETIFPM: if (valueLen == 0) { if (!WriteStringBytes(ref curr, vend, keyData)) return false; } else { RandomString(); if (!WriteStringBytes(ref curr, vend, valueBuffer)) return false; } if (valueLen == 0) { if (!WriteStringBytes(ref curr, vend, keyData)) return false; } else { RandomString(); if (!WriteStringBytes(ref curr, vend, valueBuffer)) return false; } break; case OpType.MPFADD: case OpType.SET: RandomString(); if (!WriteStringBytes(ref curr, vend, valueBuffer)) return false; break; case OpType.SETEX: if (!WriteInteger(ttl, ref curr, vend)) return false; break; case OpType.PFMERGE: if (!WriteKey(ref curr, vend)) return false; break; case OpType.INCR: case OpType.GET: case OpType.MGET: break; case OpType.SETBIT: case OpType.GETBIT: n = valueRandomGen.Next(0, (valueLen << 3) - 1); if (!WriteInteger(n, ref curr, vend)) return false; break; case OpType.BITCOUNT: break; case OpType.BITPOS: if (!WriteInteger(valueRandomGen.Next(0, 1), ref curr, vend)) return false; break; case OpType.BITOP_AND: case OpType.BITOP_OR: case OpType.BITOP_XOR: case OpType.BITOP_NOT: if (!WriteKey(ref curr, vend)) return false; break; case OpType.BITFIELD: bitfieldOpCount = 3; if (!WriteBitfieldArgs(ref curr, vend, Encoding.ASCII.GetBytes("SET"))) return false; if (!WriteBitfieldArgs(ref curr, vend, Encoding.ASCII.GetBytes("INCRBY"))) return false; if (!WriteBitfieldArgs(ref curr, vend, Encoding.ASCII.GetBytes("GET"))) return false; break; case OpType.BITFIELD_GET: if (!WriteBitfieldArgs(ref curr, vend, Encoding.ASCII.GetBytes("GET"))) return false; break; case OpType.BITFIELD_SET: if (!WriteBitfieldArgs(ref curr, vend, Encoding.ASCII.GetBytes("SET"))) return false; break; case OpType.BITFIELD_INCR: if (!WriteBitfieldArgs(ref curr, vend, Encoding.ASCII.GetBytes("INCRBY"))) return false; break; case OpType.GEOADD: if (!WriteStringBytes(ref curr, vend, Encoding.ASCII.GetBytes(GeoUtils.GetValidGeo().lng))) return false; break; default: break; } //arg2 switch (opType) { case OpType.ZADD: n = Start + r.Next(DbSize); if (!WriteInteger(n, ref curr, vend)) return false; break; case OpType.ZREM: case OpType.PFADD: case OpType.MSET: case OpType.INCR: case OpType.GET: case OpType.MGET: break; case OpType.SETBIT: n = valueRandomGen.Next(0, 1); if (!WriteInteger(n, ref curr, vend)) return false; break; case OpType.GETBIT: case OpType.BITCOUNT: case OpType.BITPOS: break; case OpType.BITOP_AND: case OpType.BITOP_OR: case OpType.BITOP_XOR: for (int i = 0; i < bitOpSrckeyCount; i++) if (!WriteKey(ref curr, vend)) return false; break; case OpType.BITOP_NOT: if (!WriteKey(ref curr, vend)) return false; break; case OpType.BITFIELD: case OpType.BITFIELD_GET: case OpType.BITFIELD_SET: case OpType.BITFIELD_INCR: case OpType.GEOADD: if (!WriteStringBytes(ref curr, vend, Encoding.ASCII.GetBytes(GeoUtils.GetValidGeo().lat))) return false; break; case OpType.SETEX: RandomString(); if (!WriteStringBytes(ref curr, vend, valueBuffer)) return false; break; default: break; } // arg3 switch (opType) { case OpType.GEOADD: n = Start + r.Next(DbSize); if (!WriteInteger(n, ref curr, vend)) return false; break; default: break; } return true; } private bool WriteKey(ref byte* curr, byte* vend) { byte[] keyData = GetClusterKeyInterleaved(); return WriteStringBytes(ref curr, vend, keyData); } private bool WriteKey(ref byte* curr, byte* vend, out byte[] keyData) { keyData = GetClusterKeyInterleaved(); return WriteStringBytes(ref curr, vend, keyData); } private bool WriteKey(ref byte* curr, byte* vend, int key) { byte[] keyData = Encoding.ASCII.GetBytes(key.ToString().PadLeft(keyLen, 'X')); return WriteStringBytes(ref curr, vend, keyData); } } }
ReqGen
csharp
microsoft__semantic-kernel
dotnet/src/SemanticKernel.Core/Data/TextSearchStore/TextSearchStoreSourceRetrievalRequest.cs
{ "start": 284, "end": 1115 }
public sealed class ____ { /// <summary> /// Initializes a new instance of the <see cref="TextSearchStoreSourceRetrievalRequest"/> class. /// </summary> /// <param name="sourceId">The source ID of the document to retrieve.</param> /// <param name="sourceLink">The source link of the document to retrieve.</param> public TextSearchStoreSourceRetrievalRequest(string? sourceId, string? sourceLink) { this.SourceId = sourceId; this.SourceLink = sourceLink; } /// <summary> /// Gets or sets the source ID of the document to retrieve. /// </summary> public string? SourceId { get; set; } /// <summary> /// Gets or sets the source link of the document to retrieve. /// </summary> public string? SourceLink { get; set; } }
TextSearchStoreSourceRetrievalRequest
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Api.Analyzers/test/TestFiles/ApiConventionAnalyzerIntegrationTest/NoDiagnosticsAreReturned_ForReturnStatementsInLambdas.cs
{ "start": 323, "end": 1082 }
public class ____ : ControllerBase { [ProducesResponseType(typeof(string), 200)] [ProducesResponseType(typeof(string), 404)] public IActionResult Put(int id, object model) { Func<IActionResult> someLambda = () => { if (id < -1) { // We should not process this. return UnprocessableEntity(); } return null; }; if (id == 0) { return NotFound(); } if (id == 1) { return someLambda(); } return Ok(); } } }
NoDiagnosticsAreReturned_ForReturnStatementsInLambdas
csharp
duplicati__duplicati
Duplicati/Library/Backend/File/Win32.cs
{ "start": 2270, "end": 2459 }
private enum ____ : int { RESOURCETYPE_ANY, RESOURCETYPE_DISK, RESOURCETYPE_PRINT, RESOURCETYPE_RESERVED };
ResourceType
csharp
grandnode__grandnode2
src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs
{ "start": 309, "end": 4494 }
public class ____ { private Mock<ICacheBase> _cacheMock; private Mock<IMediator> _mediatorMock; private Mock<IRepository<Store>> _repository; private StoreService _service; [TestInitialize] public void Init() { _cacheMock = new Mock<ICacheBase>(); _mediatorMock = new Mock<IMediator>(); _repository = new Mock<IRepository<Store>>(); _service = new StoreService(_cacheMock.Object, _repository.Object, _mediatorMock.Object); } [TestMethod] public async Task InsertStore_ValidArgument_InvokeExpectedMethods() { await _service.InsertStore(new Store()); _repository.Verify(c => c.InsertAsync(It.IsAny<Store>()), Times.Once); _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Store>>(), default), Times.Once); _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once); } [TestMethod] public async Task UpdateStore_ValidArgument_InvokeExpectedMethods() { await _service.UpdateStore(new Store()); _repository.Verify(c => c.UpdateAsync(It.IsAny<Store>()), Times.Once); _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Store>>(), default), Times.Once); _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once); } [TestMethod] public async Task DeleteStore_ValidArgument_InvokeExpectedMethods() { _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>())) .Returns(Task.FromResult(new List<Store> { new(), new() })); await _service.DeleteStore(new Store()); _repository.Verify(c => c.DeleteAsync(It.IsAny<Store>()), Times.Once); _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Store>>(), default), Times.Once); _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once); } [TestMethod] public void DeleteStore_OnlyOneStore_ThrowException() { //can not remove store if it is only one _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>())) .Returns(Task.FromResult(new List<Store> { new() })); Assert.ThrowsExceptionAsync<Exception>(async () => await _service.DeleteStore(new Store())); } [TestMethod] public async Task GetStoreByHost_MatchingHost_ReturnsMatchingStore() { // Arrange var store1 = new Store { Url = "http://store1.com" }; store1.Domains = new List<DomainHost> { new DomainHost { HostName = "store1.com", Url = "http://store1.com", Primary = true } }; var store2 = new Store { Url = "http://store2.com" }; store2.Domains = new List<DomainHost> { new DomainHost { HostName = "store2.com", Url = "http://store2.com", Primary = true } }; var stores = new List<Store> { store1, store2 }; _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>())) .Returns(Task.FromResult(stores)); // Act var result = await _service.GetStoreByHost("store1.com"); // Assert Assert.AreEqual(store1, result); } [TestMethod] public async Task GetStoreByHost_NoMatchingHost_ReturnsNullStore() { // Arrange var store1 = new Store { Url = "http://store1.com" }; store1.Domains = new List<DomainHost> { new DomainHost { HostName = "store1.com", Url = "http://store1.com", Primary = true } }; var store2 = new Store { Url = "http://store2.com" }; store2.Domains = new List<DomainHost> { new DomainHost { HostName = "store2.com", Url = "http://store2.com", Primary = true } }; var stores = new List<Store> { store1, store2 }; _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>())) .Returns(Task.FromResult(stores)); // Act - host not found in any DomainHost var result = await _service.GetStoreByHost("nonexisting.com"); // Assert - returns first store Assert.IsNull(result); } }
StoreServiceTests
csharp
bitwarden__server
test/Infrastructure.IntegrationTest/AdminConsole/Repositories/CollectionRepository/CollectionRepositoryCreateTests.cs
{ "start": 233, "end": 4273 }
public class ____ { [DatabaseTheory, DatabaseData] public async Task CreateAsync_WithAccess_Works( IUserRepository userRepository, IOrganizationRepository organizationRepository, IOrganizationUserRepository organizationUserRepository, IGroupRepository groupRepository, ICollectionRepository collectionRepository) { // Arrange var organization = await organizationRepository.CreateTestOrganizationAsync(); var user1 = await userRepository.CreateTestUserAsync(); var orgUser1 = await organizationUserRepository.CreateTestOrganizationUserAsync(organization, user1); var user2 = await userRepository.CreateTestUserAsync(); var orgUser2 = await organizationUserRepository.CreateTestOrganizationUserAsync(organization, user2); var group1 = await groupRepository.CreateTestGroupAsync(organization); var group2 = await groupRepository.CreateTestGroupAsync(organization); var collection = new Collection { Name = "Test Collection Name", OrganizationId = organization.Id, }; // Act await collectionRepository.CreateAsync(collection, [ new CollectionAccessSelection { Id = group1.Id, Manage = true, HidePasswords = true, ReadOnly = false, }, new CollectionAccessSelection { Id = group2.Id, Manage = false, HidePasswords = false, ReadOnly = true, }, ], [ new CollectionAccessSelection { Id = orgUser1.Id, Manage = true, HidePasswords = false, ReadOnly = true }, new CollectionAccessSelection { Id = orgUser2.Id, Manage = false, HidePasswords = true, ReadOnly = false }, ] ); // Assert var (actualCollection, actualAccess) = await collectionRepository.GetByIdWithAccessAsync(collection.Id); Assert.NotNull(actualCollection); Assert.Equal("Test Collection Name", actualCollection.Name); var groups = actualAccess.Groups.ToArray(); Assert.Equal(2, groups.Length); Assert.Single(groups, g => g.Id == group1.Id && g.Manage && g.HidePasswords && !g.ReadOnly); Assert.Single(groups, g => g.Id == group2.Id && !g.Manage && !g.HidePasswords && g.ReadOnly); var users = actualAccess.Users.ToArray(); Assert.Equal(2, users.Length); Assert.Single(users, u => u.Id == orgUser1.Id && u.Manage && !u.HidePasswords && u.ReadOnly); Assert.Single(users, u => u.Id == orgUser2.Id && !u.Manage && u.HidePasswords && !u.ReadOnly); // Clean up data await userRepository.DeleteAsync(user1); await userRepository.DeleteAsync(user2); await organizationRepository.DeleteAsync(organization); await groupRepository.DeleteManyAsync([group1.Id, group2.Id]); await organizationUserRepository.DeleteManyAsync([orgUser1.Id, orgUser2.Id]); } /// <remarks> /// Makes sure that the sproc handles empty sets. /// </remarks> [DatabaseTheory, DatabaseData] public async Task CreateAsync_WithNoAccess_Works( IOrganizationRepository organizationRepository, ICollectionRepository collectionRepository) { // Arrange var organization = await organizationRepository.CreateTestOrganizationAsync(); var collection = new Collection { Name = "Test Collection Name", OrganizationId = organization.Id, }; // Act await collectionRepository.CreateAsync(collection, [], []); // Assert var (actualCollection, actualAccess) = await collectionRepository.GetByIdWithAccessAsync(collection.Id); Assert.NotNull(actualCollection); Assert.Equal("Test Collection Name", actualCollection.Name); Assert.Empty(actualAccess.Groups); Assert.Empty(actualAccess.Users); // Clean up await organizationRepository.DeleteAsync(organization); } }
CollectionRepositoryCreateTests
csharp
ShareX__ShareX
ShareX.MediaLib/DirectShowDevices.cs
{ "start": 1085, "end": 1255 }
public class ____ { public List<string> VideoDevices = new List<string>(); public List<string> AudioDevices = new List<string>(); } }
DirectShowDevices
csharp
MassTransit__MassTransit
src/Persistence/MassTransit.RedisIntegration/Exceptions/RedisSagaConcurrencyException.cs
{ "start": 67, "end": 604 }
public class ____ : ConcurrencyException { public RedisSagaConcurrencyException(string message, Type sagaType, Guid correlationId) : base(message, sagaType, correlationId) { } public RedisSagaConcurrencyException(string message, Type sagaType, Guid correlationId, Exception innerException) : base(message, sagaType, correlationId, innerException) { } public RedisSagaConcurrencyException() { } } }
RedisSagaConcurrencyException
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/Script/Blocks/WithScriptBlock.cs
{ "start": 331, "end": 1093 }
public class ____ : ScriptBlock { public override string Name => "with"; public override async Task WriteAsync(ScriptScopeContext scope, PageBlockFragment block, CancellationToken token) { var result = await block.Argument.GetJsExpressionAndEvaluateAsync(scope, ifNone: () => throw new NotSupportedException("'with' block does not have a valid expression")); if (result != null) { var resultAsMap = result.ToObjectDictionary(); var withScope = scope.ScopeWithParams(resultAsMap); await WriteBodyAsync(withScope, block, token); } else { await WriteElseAsync(scope, block.ElseBlocks, token); } } }
WithScriptBlock
csharp
cake-build__cake
src/Cake.Common/Build/GoCD/GoCDInfo.cs
{ "start": 302, "end": 389 }
class ____ to provide information about the Go.CD environment. /// </summary>
used
csharp
reactiveui__Akavache
src/Akavache.Tests/SecurityUtilitiesTests.cs
{ "start": 496, "end": 10374 }
public class ____ { /// <summary> /// Tests that ValidateCacheName rejects path traversal attempts. /// </summary> [Test] public void ValidateCacheName_ShouldRejectPathTraversalAttempts() { var pathTraversalAttempts = new[] { "test/../other", "test\\..\\other", "../../etc/passwd", "..\\..\\windows\\system32", "./test", ".\\test", "test/subdir", "test\\subdir" }; foreach (var maliciousName in pathTraversalAttempts) { var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(maliciousName)); // The validation should reject these for security reasons Assert.That(ex, Is.Not.Null); Assert.That(ex.Message, Does.Contain(maliciousName)); } } /// <summary> /// Tests that ValidateCacheName rejects reserved system names. /// </summary> [Test] public void ValidateCacheName_ShouldRejectReservedSystemNames() { var reservedNames = new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "con", "prn", "aux", "nul" // Test case insensitive }; foreach (var reservedName in reservedNames) { var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(reservedName)); Assert.That(ex.Message, Does.Contain("reserved system name")); } } /// <summary> /// Tests that ValidateCacheName rejects invalid filename characters. /// </summary> [Test] public void ValidateCacheName_ShouldRejectInvalidFilenameCharacters() { var invalidChars = Path.GetInvalidFileNameChars(); // Test first 5 to avoid excessive test time, but skip path separators since they're checked separately foreach (var invalidChar in invalidChars.Where(c => c != '/' && c != '\\').Take(5)) { var nameWithInvalidChar = $"test{invalidChar}cache"; var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(nameWithInvalidChar)); Assert.That(ex.Message, Does.Contain("invalid filename characters")); } } /// <summary> /// Tests that ValidateCacheName rejects names with problematic prefixes/suffixes. /// </summary> [Test] public void ValidateCacheName_ShouldRejectProblematicPrefixesSuffixes() { var problematicNames = new[] { ".hiddenfile", "normalfile.", "spacefile ", // trailing space "..." }; foreach (var problematicName in problematicNames) { var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(problematicName)); Assert.That(ex.Message, Does.Contain("cannot start or end with")); } // Test names that become empty after trimming var emptyAfterTrim = new[] { " ", " " }; foreach (var emptyName in emptyAfterTrim) { var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(emptyName)); Assert.That(ex.Message, Does.Contain("cannot be null or empty")); } } /// <summary> /// Tests that ValidateCacheName accepts valid cache names. /// </summary> [Test] public void ValidateCacheName_ShouldAcceptValidNames() { var validNames = new[] { "UserAccount", "LocalMachine", "Secure", "MyCache", "cache_with_underscore", "cache-with-dash", "cache123", "A", "CacheWithUpper", "cachewithlong123456789012345678901234567890" }; foreach (var validName in validNames) { var result = SecurityUtilities.ValidateCacheName(validName); Assert.That(result, Is.EqualTo(validName.Trim())); } } /// <summary> /// Tests that ValidateApplicationName rejects path traversal attempts. /// </summary> [Test] public void ValidateApplicationName_ShouldRejectPathTraversalAttempts() { var pathTraversalAttempts = new[] { "MyApp/../OtherApp", "App/SubApp", // Should reject paths with subdirectories "App\\SubApp" }; foreach (var maliciousName in pathTraversalAttempts) { var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateApplicationName(maliciousName)); Assert.That(ex, Is.Not.Null); } } /// <summary> /// Tests that ValidateApplicationName accepts valid application names. /// </summary> [Test] public void ValidateApplicationName_ShouldAcceptValidNames() { var validNames = new[] { "MyApplication", "App123", "app_name", "app-name", "SimpleApp", "AkavacheTestApp" }; foreach (var validName in validNames) { var result = SecurityUtilities.ValidateApplicationName(validName); Assert.That(result, Is.EqualTo(validName.Trim())); } } /// <summary> /// Tests that ValidateDatabaseName works identically to ValidateCacheName. /// </summary> [Test] public void ValidateDatabaseName_ShouldWorkLikeValidateCacheName() { // Test that it rejects the same things as ValidateCacheName var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateDatabaseName("./malicious")); Assert.That(ex.Message, Does.Contain("cannot")); // Test that it accepts valid names var result = SecurityUtilities.ValidateDatabaseName("ValidDatabase"); Assert.That(result, Is.EqualTo("ValidDatabase")); } /// <summary> /// Tests that SafePathCombine prevents directory traversal. /// </summary> [Test] public void SafePathCombine_ShouldPreventDirectoryTraversal() { var basePath = "/tmp/cache"; var maliciousPaths = new[] { "../../../etc/passwd", "subdir/../../../etc", "normal/../../etc/passwd" }; foreach (var maliciousPath in maliciousPaths) { var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.SafePathCombine(basePath, maliciousPath)); Assert.That(ex.Message, Does.Contain("outside the base directory")); } } /// <summary> /// Tests that SafePathCombine allows safe relative paths. /// </summary> [Test] public void SafePathCombine_ShouldAllowSafeRelativePaths() { var basePath = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar); var safePaths = new[] { "cache.db", "subdir", Path.Combine("subdir", "cache.db") }; foreach (var safePath in safePaths) { var result = SecurityUtilities.SafePathCombine(basePath, safePath); Assert.That(result, Does.StartWith(basePath)); Assert.That(result, Does.Contain(safePath.Replace('/', Path.DirectorySeparatorChar))); } } /// <summary> /// Tests error handling for null and empty inputs. /// </summary> [Test] public void SecurityUtilities_ShouldHandleNullAndEmptyInputs() { // Test ValidateCacheName Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(null!)); Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(string.Empty)); Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(" ")); // Test ValidateApplicationName Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateApplicationName(null!)); Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateApplicationName(string.Empty)); Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateApplicationName(" ")); // Test ValidateDatabaseName Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateDatabaseName(null!)); Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateDatabaseName(string.Empty)); // Test SafePathCombine Assert.Throws<ArgumentException>(() => SecurityUtilities.SafePathCombine(null!, "test")); Assert.Throws<ArgumentException>(() => SecurityUtilities.SafePathCombine(string.Empty, "test")); Assert.Throws<ArgumentException>(() => SecurityUtilities.SafePathCombine("/tmp", null!)); Assert.Throws<ArgumentException>(() => SecurityUtilities.SafePathCombine("/tmp", string.Empty)); } /// <summary> /// Tests that validation handles whitespace strictly. /// </summary> [Test] public void SecurityUtilities_ShouldRejectLeadingTrailingWhitespace() { // For security reasons, we don't want to allow trailing whitespace var namesWithTrailingWhitespace = new[] { "ValidCache " }; foreach (var nameWithWhitespace in namesWithTrailingWhitespace) { var ex = Assert.Throws<ArgumentException>(() => SecurityUtilities.ValidateCacheName(nameWithWhitespace)); Assert.That(ex.Message, Does.Contain("cannot start or end with")); } // But names without leading/trailing whitespace should work var validName = "ValidCache"; var result = SecurityUtilities.ValidateCacheName(validName); Assert.That(result, Is.EqualTo(validName)); } }
SecurityUtilitiesTests
csharp
dotnet__reactive
Ix.NET/Source/System.Linq.Async/System/Linq/Operators/Utilities.cs
{ "start": 323, "end": 1437 }
internal static class ____ { public static async ValueTask AddRangeAsync<T>(this List<T> list, IAsyncEnumerable<T> collection, CancellationToken cancellationToken) { if (collection is IEnumerable<T> enumerable) { list.AddRange(enumerable); return; } if (collection is IAsyncIListProvider<T> listProvider) { var count = await listProvider.GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false); if (count == 0) { return; } if (count > 0) { var newCount = list.Count + count; if (list.Capacity < newCount) { list.Capacity = newCount; } } } await foreach (var item in collection.WithCancellation(cancellationToken).ConfigureAwait(false)) { list.Add(item); } } } }
Utilities
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/test/EmptyResultTests.cs
{ "start": 301, "end": 818 }
public class ____ { [Fact] public void EmptyResult_ExecuteResult_IsANoOp() { // Arrange var emptyResult = new EmptyResult(); var httpContext = new Mock<HttpContext>(MockBehavior.Strict); var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var context = new ActionContext(httpContext.Object, routeData, actionDescriptor); // Act & Assert (does not throw) emptyResult.ExecuteResult(context); } }
EmptyResultTests
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 930143, "end": 931734 }
public partial class ____ : global::System.IEquatable<ShowClientCommandQuery_Node_FusionConfigurationDeployment>, IShowClientCommandQuery_Node_FusionConfigurationDeployment { public ShowClientCommandQuery_Node_FusionConfigurationDeployment() { } public virtual global::System.Boolean Equals(ShowClientCommandQuery_Node_FusionConfigurationDeployment? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return true; } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((ShowClientCommandQuery_Node_FusionConfigurationDeployment)obj); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; return hash; } } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
ShowClientCommandQuery_Node_FusionConfigurationDeployment
csharp
dotnetcore__CAP
src/DotNetCore.CAP/Internal/ISnowflakeId.Default.cs
{ "start": 308, "end": 3810 }
public class ____ : ISnowflakeId { /// <summary> /// Start time 2010-11-04 09:42:54 /// </summary> public const long Twepoch = 1288834974657L; /// <summary> /// The number of bits occupied by workerId /// </summary> private const int WorkerIdBits = 10; /// <summary> /// The number of bits occupied by timestamp /// </summary> private const int TimestampBits = 41; /// <summary> /// The number of bits occupied by sequence /// </summary> private const int SequenceBits = 12; /// <summary> /// Maximum supported machine id, the result is 1023 /// </summary> private const int MaxWorkerId = ~(-1 << WorkerIdBits); /// <summary> /// mask that help to extract timestamp and sequence from a long /// </summary> private const long TimestampAndSequenceMask = ~(-1L << (TimestampBits + SequenceBits)); private readonly object _lock = new(); /// <summary> /// timestamp and sequence mix in one Long /// highest 11 bit: not used /// middle 41 bit: timestamp /// lowest 12 bit: sequence /// </summary> private long _timestampAndSequence; public SnowflakeId() { if (!long.TryParse(Environment.GetEnvironmentVariable("CAP_WORKERID"), out var workerId)) workerId = Util.GenerateWorkerId(MaxWorkerId); Initialize(workerId); } public SnowflakeId(long workerId) { Initialize(workerId); } /// <summary> /// business meaning: machine ID (0 ~ 1023) /// actual layout in memory: /// highest 1 bit: 0 /// middle 10 bit: workerId /// lowest 53 bit: all 0 /// </summary> private long WorkerId { get; set; } public virtual long NextId() { lock (_lock) { WaitIfNecessary(); var timestampWithSequence = _timestampAndSequence & TimestampAndSequenceMask; return WorkerId | timestampWithSequence; } } /// <summary> /// init first timestamp and sequence immediately /// </summary> private void InitTimestampAndSequence() { var timestamp = GetNewestTimestamp(); var timestampWithSequence = timestamp << SequenceBits; _timestampAndSequence = timestampWithSequence; } /// <summary> /// block current thread if the QPS of acquiring UUID is too high /// that current sequence space is exhausted /// </summary> private void WaitIfNecessary() { var currentWithSequence = ++_timestampAndSequence; var current = currentWithSequence >> SequenceBits; var newest = GetNewestTimestamp(); if (current >= newest) Thread.Sleep(5); } /// <summary> /// Common method for initializing <see cref="SnowflakeId"/> /// </summary> /// <param name="workerId"></param> /// <exception cref="ArgumentException"></exception> private void Initialize(long workerId) { InitTimestampAndSequence(); // sanity check for workerId if (workerId is > MaxWorkerId or < 0) throw new ArgumentException($"worker Id can't be greater than {MaxWorkerId} or less than 0"); WorkerId = workerId << (TimestampBits + SequenceBits); } /// <summary> /// get newest timestamp relative to twepoch /// </summary> /// <returns></returns> private static long GetNewestTimestamp() { return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - Twepoch; } }
SnowflakeId
csharp
dotnet__aspnetcore
src/Http/Routing/src/Constraints/RegexErrorStubRouteConstraint.cs
{ "start": 394, "end": 1112 }
internal sealed class ____ : IRouteConstraint, IParameterPolicy #endif { public RegexErrorStubRouteConstraint(string _) { throw new InvalidOperationException(Resources.RegexRouteContraint_NotConfigured); } #if !COMPONENTS bool IRouteConstraint.Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) #else bool IRouteConstraint.Match(string routeKey, RouteValueDictionary values) #endif { // Should never get called, but is same as throw in constructor in case constructor is changed. throw new InvalidOperationException(Resources.RegexRouteContraint_NotConfigured); } }
RegexErrorStubRouteConstraint