source
stringclasses
1 value
id
stringlengths
40
40
language
stringclasses
2 values
date
stringclasses
1 value
author
stringclasses
1 value
url
stringclasses
1 value
title
stringclasses
1 value
extra
stringlengths
528
1.53k
quality_signals
stringlengths
139
178
text
stringlengths
6
1.05M
TheStack
e0164f2e94d0cd536b3de9df70c5177c1c1538d9
C#code:C#
{"size": 1371, "ext": "cs", "max_stars_repo_path": "MaxLib.WinForm/Console/ExtendedConsole/Windows/MainTargetWindow.cs", "max_stars_repo_name": "Garados007/MaxLib", "max_stars_repo_stars_event_min_datetime": "2017-11-15T16:56:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-06T19:16:39.000Z", "max_issues_repo_path": "MaxLib.WinForm/Console/ExtendedConsole/Windows/MainTargetWindow.cs", "max_issues_repo_name": "Garados007/MaxLib", "max_issues_repo_issues_event_min_datetime": "2017-11-15T18:45:00.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-15T18:48:19.000Z", "max_forks_repo_path": "MaxLib.WinForm/Console/ExtendedConsole/Windows/MainTargetWindow.cs", "max_forks_repo_name": "Garados007/MaxLib", "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:45:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:45:09.000Z"}
{"max_stars_count": 2.0, "max_issues_count": 4.0, "max_forks_count": 1.0, "avg_line_length": 30.4666666667, "max_line_length": 81, "alphanum_fraction": 0.5652808169}
namespace MaxLib.Console.ExtendedConsole.Windows { public class MainTargetWindow : Elements.BasicCountainerElement { public ImageViewer Background { get; private set; } public Forms.FormsContainer Forms { get; private set; } public override void Draw(Out.ClipWriterAsync writer) { Background.Width = Width = writer.Owner.Matrix.Width; Background.Height = Height = writer.Owner.Matrix.Height - 2; writer = writer.ownerWriter.CreatePartialWriter(0, 0, Width, Height); writer.BeginWrite(); Background.Draw(writer); base.Draw(writer); Forms.Draw(writer); writer.EndWrite(); } public override void OnMouseDown(int x, int y) { base.OnMouseDown(x, y); Forms.MouseDown(x, y); } public override void OnMouseMove(int x, int y) { base.OnMouseMove(x, y); Forms.MouseMove(x, y); } public override void OnMouseUp(int x, int y) { base.OnMouseUp(x, y); Forms.MouseUp(x, y); } public MainTargetWindow(ImageViewer Background) { this.Background = Background; Background.Changed += DoChange; Forms = new Forms.FormsContainer(); } } }
TheStack
e0187deb7f3a3e7bf840844c5ef728e7381dc43d
C#code:C#
{"size": 963, "ext": "cs", "max_stars_repo_path": "CoinRateScraper/Database.cs", "max_stars_repo_name": "Sweet-Coin-Market/Coin-Rate-Scraper", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CoinRateScraper/Database.cs", "max_issues_repo_name": "Sweet-Coin-Market/Coin-Rate-Scraper", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoinRateScraper/Database.cs", "max_forks_repo_name": "Sweet-Coin-Market/Coin-Rate-Scraper", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.3928571429, "max_line_length": 138, "alphanum_fraction": 0.6469366563}
using MySql.Data.MySqlClient; namespace CoinRateScraper { public class Database { private MySqlConnection Connection { get; } public Database(string host, string username, string password, string databaseName) { Connection = new MySqlConnection( $"Server={host};User={username};Password={password};Database={databaseName};SSL Mode=None"); Connection.Open(); } public void UpdateCoinRate(string buyingCoinRate, string sellingCoinRate) { var command = new MySqlCommand( "UPDATE information SET buyingCoinRate=@buyingCoinRate, sellingCoinRate=@sellingCoinRate LIMIT 1;", Connection); command.Parameters.AddWithValue("@buyingCoinRate", buyingCoinRate); command.Parameters.AddWithValue("@sellingCoinRate", sellingCoinRate); command.ExecuteNonQuery(); Connection.Dispose(); } } }
TheStack
e018e49ad83df8f7f9ad2ccc82eafc32485253e1
C#code:C#
{"size": 1524, "ext": "cs", "max_stars_repo_path": "XamarinNativeExamples.iOS/Views/Token/TokenStartSubView.cs", "max_stars_repo_name": "jeromemanzano/XamarinNativeExamples", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "XamarinNativeExamples.iOS/Views/Token/TokenStartSubView.cs", "max_issues_repo_name": "jeromemanzano/XamarinNativeExamples", "max_issues_repo_issues_event_min_datetime": "2020-10-08T02:55:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T07:34:38.000Z", "max_forks_repo_path": "XamarinNativeExamples.iOS/Views/Token/TokenStartSubView.cs", "max_forks_repo_name": "jeromemanzano/XamarinNativeExamples", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 12.0, "max_forks_count": null, "avg_line_length": 40.1052631579, "max_line_length": 113, "alphanum_fraction": 0.6850393701}
using UIKit; namespace XamarinNativeExamples.iOS.Views.Token { public class TokenStartSubView : UIView { public TokenStartSubView() { Initialize(); } public UILabel StartDescription { get; set; } private void Initialize() { var tokenStartImage = new UIImageView(); tokenStartImage.Image = UIImage.FromBundle("ApiTokenStart"); tokenStartImage.ContentMode = UIViewContentMode.ScaleAspectFit; StartDescription = new UILabel(); AddSubview(tokenStartImage); AddSubview(StartDescription); tokenStartImage.TranslatesAutoresizingMaskIntoConstraints = false; tokenStartImage.TopAnchor.ConstraintEqualTo(SafeAreaLayoutGuide.TopAnchor, 40).Active = true; tokenStartImage.LeadingAnchor.ConstraintEqualTo(LeadingAnchor, 40).Active = true; tokenStartImage.TrailingAnchor.ConstraintEqualTo(TrailingAnchor, -40).Active = true; StartDescription.TranslatesAutoresizingMaskIntoConstraints = false; StartDescription.BottomAnchor.ConstraintEqualTo(SafeAreaLayoutGuide.BottomAnchor, -60).Active = true; StartDescription.LeadingAnchor.ConstraintEqualTo(LeadingAnchor, 40).Active = true; StartDescription.TrailingAnchor.ConstraintEqualTo(TrailingAnchor, -40).Active = true; StartDescription.Lines = 0; StartDescription.LineBreakMode = UILineBreakMode.WordWrap; } } }
TheStack
e019bfeb01d6521bdcedcb7e19fd27d436e06425
C#code:C#
{"size": 244, "ext": "cs", "max_stars_repo_path": "LiveSplit/LiveSplit.Core/TimeFormatters/ITimeFormatter.cs", "max_stars_repo_name": "glacials/LiveSplit", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LiveSplit/LiveSplit.Core/TimeFormatters/ITimeFormatter.cs", "max_issues_repo_name": "glacials/LiveSplit", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LiveSplit/LiveSplit.Core/TimeFormatters/ITimeFormatter.cs", "max_forks_repo_name": "glacials/LiveSplit", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.4285714286, "max_line_length": 38, "alphanum_fraction": 0.737704918}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiveSplit.TimeFormatters { public interface ITimeFormatter { String Format(TimeSpan? time); } }
TheStack
e019fb65483eaf396d06bf789161d1851b60d1a9
C#code:C#
{"size": 7683, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Contracts/StandardTokenInterface/StandardTokenInterfaceService.cs", "max_stars_repo_name": "SurfingNerd/Galleass3D", "max_stars_repo_stars_event_min_datetime": "2019-12-02T14:36:39.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-02T14:36:39.000Z", "max_issues_repo_path": "Assets/Scripts/Contracts/StandardTokenInterface/StandardTokenInterfaceService.cs", "max_issues_repo_name": "SurfingNerd/Galleass3D", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/Contracts/StandardTokenInterface/StandardTokenInterfaceService.cs", "max_forks_repo_name": "SurfingNerd/Galleass3D", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 48.01875, "max_line_length": 245, "alphanum_fraction": 0.7266692698}
using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Numerics; using Nethereum.Hex.HexTypes; using Nethereum.ABI.FunctionEncoding.Attributes; using Nethereum.Web3; using Nethereum.RPC.Eth.DTOs; using Nethereum.Contracts.CQS; using Nethereum.Contracts.ContractHandlers; using Nethereum.Contracts; using System.Threading; using Galleass3D.Contracts.StandardTokenInterface.ContractDefinition; namespace Galleass3D.Contracts.StandardTokenInterface { public partial class StandardTokenInterfaceService { public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(Nethereum.Web3.Web3 web3, StandardTokenInterfaceDeployment standardTokenInterfaceDeployment, CancellationTokenSource cancellationTokenSource = null) { return web3.Eth.GetContractDeploymentHandler<StandardTokenInterfaceDeployment>().SendRequestAndWaitForReceiptAsync(standardTokenInterfaceDeployment, cancellationTokenSource); } public static Task<string> DeployContractAsync(Nethereum.Web3.Web3 web3, StandardTokenInterfaceDeployment standardTokenInterfaceDeployment) { return web3.Eth.GetContractDeploymentHandler<StandardTokenInterfaceDeployment>().SendRequestAsync(standardTokenInterfaceDeployment); } public static async Task<StandardTokenInterfaceService> DeployContractAndGetServiceAsync(Nethereum.Web3.Web3 web3, StandardTokenInterfaceDeployment standardTokenInterfaceDeployment, CancellationTokenSource cancellationTokenSource = null) { var receipt = await DeployContractAndWaitForReceiptAsync(web3, standardTokenInterfaceDeployment, cancellationTokenSource); return new StandardTokenInterfaceService(web3, receipt.ContractAddress); } protected Nethereum.Web3.Web3 Web3{ get; } public ContractHandler ContractHandler { get; } public StandardTokenInterfaceService(Nethereum.Web3.Web3 web3, string contractAddress) { Web3 = web3; ContractHandler = web3.Eth.GetContractHandler(contractAddress); } public Task<string> TransferFromRequestAsync(TransferFromFunction transferFromFunction) { return ContractHandler.SendRequestAsync(transferFromFunction); } public Task<TransactionReceipt> TransferFromRequestAndWaitForReceiptAsync(TransferFromFunction transferFromFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFromFunction, cancellationToken); } public Task<string> TransferFromRequestAsync(string returnValue1, string returnValue2, BigInteger returnValue3) { var transferFromFunction = new TransferFromFunction(); transferFromFunction.ReturnValue1 = returnValue1; transferFromFunction.ReturnValue2 = returnValue2; transferFromFunction.ReturnValue3 = returnValue3; return ContractHandler.SendRequestAsync(transferFromFunction); } public Task<TransactionReceipt> TransferFromRequestAndWaitForReceiptAsync(string returnValue1, string returnValue2, BigInteger returnValue3, CancellationTokenSource cancellationToken = null) { var transferFromFunction = new TransferFromFunction(); transferFromFunction.ReturnValue1 = returnValue1; transferFromFunction.ReturnValue2 = returnValue2; transferFromFunction.ReturnValue3 = returnValue3; return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFromFunction, cancellationToken); } public Task<string> TransferRequestAsync(TransferFunction transferFunction) { return ContractHandler.SendRequestAsync(transferFunction); } public Task<TransactionReceipt> TransferRequestAndWaitForReceiptAsync(TransferFunction transferFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFunction, cancellationToken); } public Task<string> TransferRequestAsync(string returnValue1, BigInteger returnValue2) { var transferFunction = new TransferFunction(); transferFunction.ReturnValue1 = returnValue1; transferFunction.ReturnValue2 = returnValue2; return ContractHandler.SendRequestAsync(transferFunction); } public Task<TransactionReceipt> TransferRequestAndWaitForReceiptAsync(string returnValue1, BigInteger returnValue2, CancellationTokenSource cancellationToken = null) { var transferFunction = new TransferFunction(); transferFunction.ReturnValue1 = returnValue1; transferFunction.ReturnValue2 = returnValue2; return ContractHandler.SendRequestAndWaitForReceiptAsync(transferFunction, cancellationToken); } public Task<string> ApproveRequestAsync(ApproveFunction approveFunction) { return ContractHandler.SendRequestAsync(approveFunction); } public Task<TransactionReceipt> ApproveRequestAndWaitForReceiptAsync(ApproveFunction approveFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(approveFunction, cancellationToken); } public Task<string> ApproveRequestAsync(string returnValue1, BigInteger returnValue2) { var approveFunction = new ApproveFunction(); approveFunction.ReturnValue1 = returnValue1; approveFunction.ReturnValue2 = returnValue2; return ContractHandler.SendRequestAsync(approveFunction); } public Task<TransactionReceipt> ApproveRequestAndWaitForReceiptAsync(string returnValue1, BigInteger returnValue2, CancellationTokenSource cancellationToken = null) { var approveFunction = new ApproveFunction(); approveFunction.ReturnValue1 = returnValue1; approveFunction.ReturnValue2 = returnValue2; return ContractHandler.SendRequestAndWaitForReceiptAsync(approveFunction, cancellationToken); } public Task<string> MintRequestAsync(MintFunction mintFunction) { return ContractHandler.SendRequestAsync(mintFunction); } public Task<TransactionReceipt> MintRequestAndWaitForReceiptAsync(MintFunction mintFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(mintFunction, cancellationToken); } public Task<string> MintRequestAsync(string returnValue1, BigInteger returnValue2) { var mintFunction = new MintFunction(); mintFunction.ReturnValue1 = returnValue1; mintFunction.ReturnValue2 = returnValue2; return ContractHandler.SendRequestAsync(mintFunction); } public Task<TransactionReceipt> MintRequestAndWaitForReceiptAsync(string returnValue1, BigInteger returnValue2, CancellationTokenSource cancellationToken = null) { var mintFunction = new MintFunction(); mintFunction.ReturnValue1 = returnValue1; mintFunction.ReturnValue2 = returnValue2; return ContractHandler.SendRequestAndWaitForReceiptAsync(mintFunction, cancellationToken); } } }
TheStack
e01a7dcb6055c3fdaa82a03fd41a05b5a86532c9
C#code:C#
{"size": 18411, "ext": "cs", "max_stars_repo_path": "sdk/search/Azure.Search.Documents/src/Indexes/FieldBuilder.cs", "max_stars_repo_name": "najagasi/azure-sdk-for-net", "max_stars_repo_stars_event_min_datetime": "2020-09-28T23:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T23:09:29.000Z", "max_issues_repo_path": "sdk/search/Azure.Search.Documents/src/Indexes/FieldBuilder.cs", "max_issues_repo_name": "najagasi/azure-sdk-for-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/search/Azure.Search.Documents/src/Indexes/FieldBuilder.cs", "max_forks_repo_name": "najagasi/azure-sdk-for-net", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 40.822616408, "max_line_length": 180, "alphanum_fraction": 0.5424474499}
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reflection; using Azure.Core; using Azure.Core.Serialization; using Azure.Search.Documents.Indexes.Models; #if EXPERIMENTAL_SPATIAL using Azure.Core.Spatial; #endif namespace Azure.Search.Documents.Indexes { /// <summary> /// Builds field definitions for a search index by reflecting over a user-defined model type. /// </summary> public class FieldBuilder { private const string HelpLink = "https://aka.ms/azsdk/net/search/fieldbuilder"; private static readonly IReadOnlyDictionary<Type, SearchFieldDataType> s_primitiveTypeMap = new ReadOnlyDictionary<Type, SearchFieldDataType>( new Dictionary<Type, SearchFieldDataType>() { [typeof(string)] = SearchFieldDataType.String, [typeof(int)] = SearchFieldDataType.Int32, [typeof(long)] = SearchFieldDataType.Int64, [typeof(double)] = SearchFieldDataType.Double, [typeof(bool)] = SearchFieldDataType.Boolean, [typeof(DateTime)] = SearchFieldDataType.DateTimeOffset, [typeof(DateTimeOffset)] = SearchFieldDataType.DateTimeOffset, #if EXPERIMENTAL_SPATIAL [typeof(PointGeometry)] = SearchFieldDataType.GeographyPoint, #endif }); private static readonly ISet<Type> s_unsupportedTypes = new HashSet<Type> { typeof(decimal), }; /// <summary> /// Initializes a new instance of the <see cref="FieldBuilder"/> class. /// </summary> public FieldBuilder() { } /// <summary> /// Gets or sets the <see cref="ObjectSerializer"/> to use to generate field names that match JSON property names. /// You should use hte same value as <see cref="SearchClientOptions.Serializer"/>. /// <see cref="JsonObjectSerializer"/> will be used if no value is provided. /// </summary> public ObjectSerializer Serializer { get; set; } /// <summary> /// Creates a list of <see cref="SearchField"/> objects corresponding to /// the properties of the type supplied. /// </summary> /// <param name="modelType"> /// The type for which fields will be created, based on its properties. /// </param> /// <returns>A collection of fields.</returns> /// <exception cref="ArgumentNullException"><paramref name="modelType"/>.</exception> public IList<SearchField> Build(Type modelType) { Argument.AssertNotNull(modelType, nameof(modelType)); ArgumentException FailOnNonObjectDataType() { string errorMessage = $"Type '{modelType}' does not have properties which map to fields of an Azure Search index. Please use a " + "class or struct with public properties."; throw new ArgumentException(errorMessage, nameof(modelType)); } Serializer ??= new JsonObjectSerializer(); IMemberNameConverter nameProvider = Serializer as IMemberNameConverter ?? DefaultSerializedNameProvider.Shared; if (ObjectInfo.TryGet(modelType, nameProvider, out ObjectInfo info)) { if (info.Properties.Length == 0) { throw FailOnNonObjectDataType(); } // Use Stack to avoid a dependency on ImmutableStack for now. return Build(modelType, info, nameProvider, new Stack<Type>(new[] { modelType })); } throw FailOnNonObjectDataType(); } private static IList<SearchField> Build( Type modelType, ObjectInfo info, IMemberNameConverter nameProvider, Stack<Type> processedTypes) { SearchField BuildField(ObjectPropertyInfo prop) { // The IMemberNameConverter will return null for implementation-specific ways of ignoring members. static bool ShouldIgnore(Attribute attribute) => attribute is FieldBuilderIgnoreAttribute; IList<Attribute> attributes = prop.GetCustomAttributes(true).Cast<Attribute>().ToArray(); if (attributes.Any(ShouldIgnore)) { return null; } SearchField CreateComplexField(SearchFieldDataType dataType, Type underlyingClrType, ObjectInfo info) { if (processedTypes.Contains(underlyingClrType)) { // Skip recursive types. return null; } processedTypes.Push(underlyingClrType); try { IList<SearchField> subFields = Build(underlyingClrType, info, nameProvider, processedTypes); if (prop.SerializedName is null) { // Member is unsupported or ignored. return null; } // Start with a ComplexField to make sure all properties default to language defaults. SearchField field = new ComplexField(prop.SerializedName, dataType); foreach (SearchField subField in subFields) { field.Fields.Add(subField); } return field; } finally { processedTypes.Pop(); } } SearchField CreateSimpleField(SearchFieldDataType SearchFieldDataType) { if (prop.SerializedName is null) { // Member is unsupported or ignored. return null; } // Start with a SimpleField to make sure all properties default to language defaults. SearchField field = new SimpleField(prop.SerializedName, SearchFieldDataType); foreach (Attribute attribute in attributes) { switch (attribute) { case SearchableFieldAttribute searchableFieldAttribute: ((ISearchFieldAttribute)searchableFieldAttribute).SetField(field); break; case SimpleFieldAttribute simpleFieldAttribute: ((ISearchFieldAttribute)simpleFieldAttribute).SetField(field); break; default: Type attributeType = attribute.GetType(); // Match on name to avoid dependency - don't want to force people not using // this feature to bring in the annotations component. // // Also, ignore key attributes on sub-fields. if (attributeType.FullName == "System.ComponentModel.DataAnnotations.KeyAttribute" && processedTypes.Count <= 1) { field.IsKey = true; } break; } } return field; } ArgumentException FailOnUnknownDataType() { string errorMessage = $"Property '{prop.Name}' is of type '{prop.PropertyType}', which does not map to an " + "Azure Search data type. Please use a supported data type or mark the property with [FieldBuilderIgnore] " + $"and define the field by creating a SearchField object. See {HelpLink} for more information."; return new ArgumentException(errorMessage, nameof(modelType)) { HelpLink = HelpLink, }; } IDataTypeInfo dataTypeInfo = GetDataTypeInfo(prop.PropertyType, nameProvider); return dataTypeInfo.Match( onUnknownDataType: () => throw FailOnUnknownDataType(), onSimpleDataType: CreateSimpleField, onComplexDataType: CreateComplexField); } return info.Properties.Select(BuildField).Where(field => field != null).ToList(); } private static IDataTypeInfo GetDataTypeInfo(Type propertyType, IMemberNameConverter nameProvider) { static bool IsNullableType(Type type) => type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); if (s_primitiveTypeMap.TryGetValue(propertyType, out SearchFieldDataType SearchFieldDataType)) { return DataTypeInfo.Simple(SearchFieldDataType); } else if (IsNullableType(propertyType)) { return GetDataTypeInfo(propertyType.GenericTypeArguments[0], nameProvider); } else if (TryGetEnumerableElementType(propertyType, out Type elementType)) { IDataTypeInfo elementTypeInfo = GetDataTypeInfo(elementType, nameProvider); return DataTypeInfo.AsCollection(elementTypeInfo); } else if (ObjectInfo.TryGet(propertyType, nameProvider, out ObjectInfo info)) { return DataTypeInfo.Complex(SearchFieldDataType.Complex, propertyType, info); } else { return DataTypeInfo.Unknown; } } private static bool TryGetEnumerableElementType(Type candidateType, out Type elementType) { static Type GetElementTypeIfIEnumerable(Type t) => t.IsConstructedGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>) ? t.GenericTypeArguments[0] : null; elementType = GetElementTypeIfIEnumerable(candidateType); if (elementType != null) { return true; } else { TypeInfo ti = candidateType.GetTypeInfo(); var listElementTypes = ti .ImplementedInterfaces .Select(GetElementTypeIfIEnumerable) .Where(p => p != null) .ToList(); if (listElementTypes.Count == 1) { elementType = listElementTypes[0]; return true; } else { return false; } } } private interface IDataTypeInfo { T Match<T>( Func<T> onUnknownDataType, Func<SearchFieldDataType, T> onSimpleDataType, Func<SearchFieldDataType, Type, ObjectInfo, T> onComplexDataType); } private static class DataTypeInfo { public static IDataTypeInfo Unknown { get; } = new UnknownDataTypeInfo(); public static IDataTypeInfo Simple(SearchFieldDataType SearchFieldDataType) => new SimpleDataTypeInfo(SearchFieldDataType); public static IDataTypeInfo Complex(SearchFieldDataType SearchFieldDataType, Type underlyingClrType, ObjectInfo info) => new ComplexDataTypeInfo(SearchFieldDataType, underlyingClrType, info); public static IDataTypeInfo AsCollection(IDataTypeInfo dataTypeInfo) => dataTypeInfo.Match( onUnknownDataType: () => Unknown, onSimpleDataType: SearchFieldDataType => Simple(SearchFieldDataType.Collection(SearchFieldDataType)), onComplexDataType: (SearchFieldDataType, underlyingClrType, info) => Complex(SearchFieldDataType.Collection(SearchFieldDataType), underlyingClrType, info)); private sealed class UnknownDataTypeInfo : IDataTypeInfo { public UnknownDataTypeInfo() { } public T Match<T>( Func<T> onUnknownDataType, Func<SearchFieldDataType, T> onSimpleDataType, Func<SearchFieldDataType, Type, ObjectInfo, T> onComplexDataType) => onUnknownDataType(); } private sealed class SimpleDataTypeInfo : IDataTypeInfo { private readonly SearchFieldDataType _dataType; public SimpleDataTypeInfo(SearchFieldDataType SearchFieldDataType) { _dataType = SearchFieldDataType; } public T Match<T>( Func<T> onUnknownDataType, Func<SearchFieldDataType, T> onSimpleDataType, Func<SearchFieldDataType, Type, ObjectInfo, T> onComplexDataType) => onSimpleDataType(_dataType); } private sealed class ComplexDataTypeInfo : IDataTypeInfo { private readonly SearchFieldDataType _dataType; private readonly Type _underlyingClrType; private readonly ObjectInfo _info; public ComplexDataTypeInfo(SearchFieldDataType SearchFieldDataType, Type underlyingClrType, ObjectInfo info) { _dataType = SearchFieldDataType; _underlyingClrType = underlyingClrType; _info = info; } public T Match<T>( Func<T> onUnknownDataType, Func<SearchFieldDataType, T> onSimpleDataType, Func<SearchFieldDataType, Type, ObjectInfo, T> onComplexDataType) => onComplexDataType(_dataType, _underlyingClrType, _info); } } private class ObjectInfo { private ObjectInfo(ObjectPropertyInfo[] properties) { Properties = properties; } public static bool TryGet(Type type, IMemberNameConverter nameProvider, out ObjectInfo info) { // Close approximation to Newtonsoft.Json.Serialization.DefaultContractResolver that was used in Microsoft.Azure.Search. if (!type.IsPrimitive && !type.IsEnum && !s_unsupportedTypes.Contains(type) && !s_primitiveTypeMap.ContainsKey(type) && !typeof(IEnumerable).IsAssignableFrom(type)) { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; List<ObjectPropertyInfo> properties = new List<ObjectPropertyInfo>(); foreach (PropertyInfo property in type.GetProperties(bindingFlags)) { string serializedName = nameProvider.ConvertMemberName(property); if (serializedName != null) { properties.Add(new ObjectPropertyInfo(property, serializedName)); } } foreach (FieldInfo field in type.GetFields(bindingFlags)) { string serializedName = nameProvider.ConvertMemberName(field); if (serializedName != null) { properties.Add(new ObjectPropertyInfo(field, serializedName)); } } if (properties.Count != 0) { info = new ObjectInfo(properties.ToArray()); return true; } } info = null; return false; } public ObjectPropertyInfo[] Properties { get; } } private struct ObjectPropertyInfo { private readonly MemberInfo _memberInfo; public ObjectPropertyInfo(PropertyInfo property, string serializedName) { Debug.Assert(serializedName != null, $"{nameof(serializedName)} cannot be null"); _memberInfo = property; SerializedName = serializedName; PropertyType = property.PropertyType; } public ObjectPropertyInfo(FieldInfo field, string serializedName) { Debug.Assert(serializedName != null, $"{nameof(serializedName)} cannot be null"); _memberInfo = field; SerializedName = serializedName; PropertyType = field.FieldType; } public string Name => _memberInfo.Name; public string SerializedName { get; } public Type PropertyType { get; } public static implicit operator MemberInfo(ObjectPropertyInfo property) => property._memberInfo; public object[] GetCustomAttributes(bool inherit) => _memberInfo.GetCustomAttributes(inherit); } private class DefaultSerializedNameProvider : IMemberNameConverter { public static IMemberNameConverter Shared { get; } = new DefaultSerializedNameProvider(); private DefaultSerializedNameProvider() { } public string ConvertMemberName(MemberInfo member) => member?.Name; } } }
TheStack
e01abf5d24d86d4b447b960b335a9bd717ce812a
C#code:C#
{"size": 2148, "ext": "cs", "max_stars_repo_path": "Scuti/Scripts/UI/Account/WalletWidget.cs", "max_stars_repo_name": "scuti-ai/scuti-sdk", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Scuti/Scripts/UI/Account/WalletWidget.cs", "max_issues_repo_name": "scuti-ai/scuti-sdk", "max_issues_repo_issues_event_min_datetime": "2022-03-05T20:38:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T20:38:59.000Z", "max_forks_repo_path": "Scuti/Scripts/UI/Account/WalletWidget.cs", "max_forks_repo_name": "scuti-ai/scuti-sdk", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 27.1898734177, "max_line_length": 111, "alphanum_fraction": 0.5912476723}
using Scuti; using Scuti.Net; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using UnityEngine; using UnityEngine.UI; public class WalletWidget : MonoBehaviour { public Text WalletLabel; public Image Icon; private void Start() { ScutiAPI.OnWalletUpdated += OnWalletUpdated; ScutiNetClient.Instance.OnAuthenticated += DoRefresh; #pragma warning disable 4014 Refresh(); #pragma warning restore 4014 } private void OnWalletUpdated(int balance) { WalletLabel.text = String.Format("{0:n0}", balance); } public void DoRefresh() { #pragma warning disable 4014 Refresh(); #pragma warning restore 4014 } private async Task Refresh() { if (ScutiNetClient.Instance.IsAuthenticated) { var rewards = await ScutiAPI.GetWallet(true); WalletLabel.text = String.Format("{0:n0}", ScutiUtils.GetTotalWallet(rewards)); } else { WalletLabel.text = "0"; } } internal async void RefreshOverTime(int reward, float animationDuration) { try { int startWalletAmount; int.TryParse(WalletLabel.text, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out startWalletAmount); if (animationDuration < 1) animationDuration = 1; var startTime = Time.time; var percent = 0f; int count = 0; while (percent < 1 && count < 100) { percent = (Time.time - startTime) / animationDuration; if (percent > 1) percent = 1; WalletLabel.text = String.Format("{0:n0}", (startWalletAmount + Math.Floor(reward * percent))); count++; await Task.Delay(30); } WalletLabel.text = String.Format("{0:n0}", startWalletAmount + reward); } catch(Exception e) { ScutiLogger.LogException(e); } // Sanity check await Refresh(); } }
TheStack
e0200233c6582414ebeef9c7473abf4972a204ac
C#code:C#
{"size": 460, "ext": "cs", "max_stars_repo_path": "pdu-dotnet-api/src/Com/Raritan/Idl/AsyncRpcResponse.cs", "max_stars_repo_name": "gregoa/raritan-pdu-json-rpc-sdk", "max_stars_repo_stars_event_min_datetime": "2021-04-29T23:04:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T23:04:17.000Z", "max_issues_repo_path": "pdu-dotnet-api/src/Com/Raritan/Idl/AsyncRpcResponse.cs", "max_issues_repo_name": "gregoa/raritan-pdu-json-rpc-sdk", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pdu-dotnet-api/src/Com/Raritan/Idl/AsyncRpcResponse.cs", "max_forks_repo_name": "gregoa/raritan-pdu-json-rpc-sdk", "max_forks_repo_forks_event_min_datetime": "2020-06-20T16:21:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T19:04:44.000Z"}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 21.9047619048, "max_line_length": 58, "alphanum_fraction": 0.7304347826}
// SPDX-License-Identifier: BSD-3-Clause // // Copyright 2018 Raritan Inc. All rights reserved. using System; using System.Collections.Generic; using System.Linq; using System.Text; #pragma warning disable 1591 namespace Com.Raritan.Idl { public static class AsyncRpcResponse { public delegate void FailureHandler(Exception ex); } public static class AsyncRpcResponse<T> { public delegate void SuccessHandler(T result); } }
TheStack
e02048bf5ccf4eac5ce4c68cabf96a409ba39cae
C#code:C#
{"size": 10325, "ext": "cs", "max_stars_repo_path": "J2i.Net.XInputWrapper/XboxController.cs", "max_stars_repo_name": "Toastee0/TcJoy", "max_stars_repo_stars_event_min_datetime": "2020-04-06T13:30:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T12:12:54.000Z", "max_issues_repo_path": "J2i.Net.XInputWrapper/XboxController.cs", "max_issues_repo_name": "Toastee0/TcJoy", "max_issues_repo_issues_event_min_datetime": "2018-12-30T17:51:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T08:15:12.000Z", "max_forks_repo_path": "J2i.Net.XInputWrapper/XboxController.cs", "max_forks_repo_name": "Toastee0/TcJoy", "max_forks_repo_forks_event_min_datetime": "2020-02-05T03:59:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T14:48:12.000Z"}
{"max_stars_count": 12.0, "max_issues_count": 9.0, "max_forks_count": 12.0, "avg_line_length": 30.7291666667, "max_line_length": 161, "alphanum_fraction": 0.5766585956}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace J2i.Net.XInputWrapper { public class XboxController { int _playerIndex; static bool keepRunning; static int updateFrequency; static int waitTime; static bool isRunning; static object SyncLock; static Thread pollingThread; bool _stopMotorTimerActive; DateTime _stopMotorTime; XInputBatteryInformation _batteryInformationGamepad; XInputBatteryInformation _batterInformationHeadset; //XInputCapabilities _capabilities; XInputState gamepadStatePrev = new XInputState(); XInputState gamepadStateCurrent = new XInputState(); public static int UpdateFrequency { get { return updateFrequency; } set { updateFrequency = value; waitTime = 1000 / updateFrequency; } } public XInputBatteryInformation BatteryInformationGamepad { get { return _batteryInformationGamepad; } internal set { _batteryInformationGamepad = value; } } public XInputBatteryInformation BatteryInformationHeadset { get { return _batterInformationHeadset; } internal set { _batterInformationHeadset = value; } } public const int MAX_CONTROLLER_COUNT = 4; public const int FIRST_CONTROLLER_INDEX = 0; public const int LAST_CONTROLLER_INDEX = MAX_CONTROLLER_COUNT-1; static XboxController[] Controllers; static XboxController() { Controllers = new XboxController[MAX_CONTROLLER_COUNT]; SyncLock = new object(); for (int i = FIRST_CONTROLLER_INDEX; i <= LAST_CONTROLLER_INDEX; ++i) { Controllers[i] = new XboxController(i); } UpdateFrequency = 25; } public event EventHandler<XboxControllerStateChangedEventArgs> StateChanged = null; public static XboxController RetrieveController(int index) { return Controllers[index]; } private XboxController(int playerIndex) { _playerIndex = playerIndex; gamepadStatePrev.Copy(gamepadStateCurrent); } public void UpdateBatteryState() { XInputBatteryInformation headset = new XInputBatteryInformation(), gamepad = new XInputBatteryInformation(); XInput.XInputGetBatteryInformation(_playerIndex, (byte)BatteryDeviceType.BATTERY_DEVTYPE_GAMEPAD, ref gamepad); XInput.XInputGetBatteryInformation(_playerIndex, (byte)BatteryDeviceType.BATTERY_DEVTYPE_HEADSET, ref headset); BatteryInformationHeadset = headset; BatteryInformationGamepad = gamepad; } protected void OnStateChanged() { if (StateChanged != null) StateChanged(this, new XboxControllerStateChangedEventArgs() { CurrentInputState = gamepadStateCurrent, PreviousInputState = gamepadStatePrev }); } public XInputCapabilities GetCapabilities() { XInputCapabilities capabilities = new XInputCapabilities(); XInput.XInputGetCapabilities(_playerIndex, XInputConstants.XINPUT_FLAG_GAMEPAD, ref capabilities); return capabilities; } #region Digital Button States public bool IsDPadUpPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_DPAD_UP); } } public bool IsDPadDownPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_DPAD_DOWN); } } public bool IsDPadLeftPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_DPAD_LEFT); } } public bool IsDPadRightPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_DPAD_RIGHT); } } public bool IsAPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_A); } } public bool IsBPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_B); } } public bool IsXPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_X); } } public bool IsYPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_Y); } } public bool IsBackPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_BACK); } } public bool IsStartPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_START); } } public bool IsLeftShoulderPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_LEFT_SHOULDER); } } public bool IsRightShoulderPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_RIGHT_SHOULDER); } } public bool IsLeftStickPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_LEFT_THUMB); } } public bool IsRightStickPressed { get { return gamepadStateCurrent.Gamepad.IsButtonPressed((int)ButtonFlags.XINPUT_GAMEPAD_RIGHT_THUMB); } } #endregion #region Analogue Input States public int LeftTrigger { get { return (int)gamepadStateCurrent.Gamepad.bLeftTrigger; } } public int RightTrigger { get { return (int)gamepadStateCurrent.Gamepad.bRightTrigger; } } public Point LeftThumbStick { get { Point p = new Point() { X = gamepadStateCurrent.Gamepad.sThumbLX, Y = gamepadStateCurrent.Gamepad.sThumbLY }; return p; } } public Point RightThumbStick { get { Point p = new Point() { X = gamepadStateCurrent.Gamepad.sThumbRX, Y = gamepadStateCurrent.Gamepad.sThumbRY }; return p; } } #endregion bool _isConnected; public bool IsConnected { get { return _isConnected; } internal set { _isConnected = value; } } #region Polling public static void StartPolling() { if (!isRunning) { lock (SyncLock) { if (!isRunning) { pollingThread = new Thread(PollerLoop); pollingThread.Start(); } } } } public static void StopPolling() { if (isRunning) keepRunning = false; } static void PollerLoop() { lock (SyncLock) { if (isRunning == true) return; isRunning = true; } keepRunning = true; while(keepRunning) { for (int i = FIRST_CONTROLLER_INDEX; i <= LAST_CONTROLLER_INDEX; ++i) { Controllers[i].UpdateState(); } Thread.Sleep(updateFrequency); } lock (SyncLock) { isRunning = false; } } public void UpdateState() { XInputCapabilities X = new XInputCapabilities(); int result = XInput.XInputGetState(_playerIndex, ref gamepadStateCurrent); IsConnected = (result == 0); UpdateBatteryState(); if (gamepadStateCurrent.PacketNumber!=gamepadStatePrev.PacketNumber) { OnStateChanged(); } gamepadStatePrev.Copy(gamepadStateCurrent); if (_stopMotorTimerActive && (DateTime.Now >= _stopMotorTime)) { XInputVibration stopStrength = new XInputVibration() { LeftMotorSpeed = 0, RightMotorSpeed = 0 }; XInput.XInputSetState(_playerIndex, ref stopStrength); } } #endregion #region Motor Functions public void Vibrate(double leftMotor, double rightMotor) { Vibrate(leftMotor, rightMotor, TimeSpan.MinValue); } public void Vibrate(double leftMotor, double rightMotor, TimeSpan length) { leftMotor = Math.Max(0d, Math.Min(1d, leftMotor)); rightMotor = Math.Max(0d, Math.Min(1d, rightMotor)); XInputVibration vibration = new XInputVibration() { LeftMotorSpeed = (ushort)(65535d * leftMotor), RightMotorSpeed = (ushort)(65535d * rightMotor) }; Vibrate(vibration, length); } public void Vibrate(XInputVibration strength) { _stopMotorTimerActive = false; XInput.XInputSetState(_playerIndex, ref strength); } public void Vibrate(XInputVibration strength, TimeSpan length) { XInput.XInputSetState(_playerIndex, ref strength); if (length != TimeSpan.MinValue) { _stopMotorTime = DateTime.Now.Add(length); _stopMotorTimerActive = true; } } #endregion public override string ToString() { return _playerIndex.ToString(); } } }
TheStack
e02101fb25161523f2475d9dd38842ff106cd9d8
C#code:C#
{"size": 5422, "ext": "cs", "max_stars_repo_path": "tests/src/CoreMangLib/cti/system/math/mathround4.cs", "max_stars_repo_name": "danmosemsft/coreclr", "max_stars_repo_stars_event_min_datetime": "2017-09-22T06:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T07:07:08.000Z", "max_issues_repo_path": "tests/src/CoreMangLib/cti/system/math/mathround4.cs", "max_issues_repo_name": "danmosemsft/coreclr", "max_issues_repo_issues_event_min_datetime": "2018-07-13T00:48:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-27T16:19:30.000Z", "max_forks_repo_path": "tests/src/CoreMangLib/cti/system/math/mathround4.cs", "max_forks_repo_name": "danmosemsft/coreclr", "max_forks_repo_forks_event_min_datetime": "2020-01-16T10:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-09T08:48:51.000Z"}
{"max_stars_count": 6.0, "max_issues_count": 2.0, "max_forks_count": 2.0, "avg_line_length": 28.5368421053, "max_line_length": 106, "alphanum_fraction": 0.5521947621}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// Round(System.Double,System.Int32) /// </summary> public class MathRound4 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Round(d, 0)"); try { int i = 0; if (Math.Round(3.4d, i) != 3 || Math.Round(3.5d, i) != 4 || Math.Round(3.6d, i) != 4) { TestLibrary.TestFramework.LogError("001.1", "Return value is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify Round(d, 1)"); try { if (Math.Round(3.44d, 1) != 3.4 || Math.Round(3.45d, 1) != 3.4 || Math.Round(3.46d, 1) != 3.5) { TestLibrary.TestFramework.LogError("002.1", "Return value is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest3: Verify Round(d, 15)"); try { double d1 = 1234567890.123454; double expectedResult1 = 1234567890.12345; double d2 = 1234567890.123455; double expectedResult2 = 1234567890.12346; double d3 = 1234567890.123456; double expectedResult3 = 1234567890.12346; int i = 15; if (Math.Round(d1, i).ToString() != expectedResult1.ToString() || Math.Round(d2, i).ToString() != expectedResult2.ToString() || Math.Round(d3, i).ToString() != expectedResult3.ToString()) { TestLibrary.TestFramework.LogError("003.1", "Return value is wrong!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException is not thrown."); try { double d = Math.Round(3.45, -1); TestLibrary.TestFramework.LogError("101.1", " OverflowException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException is not thrown."); try { double d = Math.Round(1234567890.1234567, 16); TestLibrary.TestFramework.LogError("102.1", " OverflowException is not thrown."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { MathRound4 test = new MathRound4(); TestLibrary.TestFramework.BeginTestCase("MathRound4"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
TheStack
e0212ed02b198968aca19c9bfd95f133d0fb9fdf
C#code:C#
{"size": 1252, "ext": "cs", "max_stars_repo_path": "Framework/Adxstudio.Xrm/Notes/CrmAnnotationFile.cs", "max_stars_repo_name": "emtea/xRM-Portals-Community-Edition", "max_stars_repo_stars_event_min_datetime": "2017-08-25T18:43:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:36:21.000Z", "max_issues_repo_path": "Framework/Adxstudio.Xrm/Notes/CrmAnnotationFile.cs", "max_issues_repo_name": "emtea/xRM-Portals-Community-Edition", "max_issues_repo_issues_event_min_datetime": "2017-08-28T20:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-15T00:25:15.000Z", "max_forks_repo_path": "Framework/Adxstudio.Xrm/Notes/CrmAnnotationFile.cs", "max_forks_repo_name": "emtea/xRM-Portals-Community-Edition", "max_forks_repo_forks_event_min_datetime": "2017-08-25T20:00:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T17:20:17.000Z"}
{"max_stars_count": 117.0, "max_issues_count": 113.0, "max_forks_count": 72.0, "avg_line_length": 25.5510204082, "max_line_length": 94, "alphanum_fraction": 0.7052715655}
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Threading; using System.Web; namespace Adxstudio.Xrm.Notes { internal class CrmAnnotationFile : AnnotationFile, ICrmAnnotationFile { private Lazy<byte[]> _document; public CrmAnnotationFile() { _document = new Lazy<byte[]>(() => null, LazyThreadSafetyMode.None); } public CrmAnnotationFile(HttpPostedFileBase file) : base(file) { _document = new Lazy<byte[]>(() => { var fileContent = new byte[file.ContentLength]; file.InputStream.Read(fileContent, 0, fileContent.Length); return fileContent; }, LazyThreadSafetyMode.None); } public CrmAnnotationFile(string fileName, string contentType, byte[] fileContent) : base(fileName, contentType, fileContent) { _document = new Lazy<byte[]>(() => fileContent, LazyThreadSafetyMode.None); } public byte[] Document { get { return _document.Value; } set { _document = new Lazy<byte[]>(() => value, LazyThreadSafetyMode.None); } } public void SetDocument(Func<byte[]> func) { _document = new Lazy<byte[]>(func, LazyThreadSafetyMode.None); } } }
TheStack
e023228c434782eab4f9fce69bdf3d9ca2dcb4c9
C#code:C#
{"size": 4863, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Skill/SkillImpactSpawner.cs", "max_stars_repo_name": "SardineFish/MAJIKA", "max_stars_repo_stars_event_min_datetime": "2019-04-28T14:56:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T08:29:38.000Z", "max_issues_repo_path": "Assets/Scripts/Skill/SkillImpactSpawner.cs", "max_issues_repo_name": "SardineFish/MAJIKA", "max_issues_repo_issues_event_min_datetime": "2019-04-28T15:00:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-28T15:36:33.000Z", "max_forks_repo_path": "Assets/Scripts/Skill/SkillImpactSpawner.cs", "max_forks_repo_name": "SardineFish/MAJIKA", "max_forks_repo_forks_event_min_datetime": "2019-01-17T08:41:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T10:18:45.000Z"}
{"max_stars_count": 30.0, "max_issues_count": 1.0, "max_forks_count": 7.0, "avg_line_length": 31.5779220779, "max_line_length": 129, "alphanum_fraction": 0.5897594078}
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public enum ImpactSpawnType { Default, OnGround, Barrage } public class SkillImpactSpawner : EntityBehaviour { public GameObject Prefab; public ImpactSpawnType SpawnType = ImpactSpawnType.Default; public Vector2 SpawnOffset; public float TimeOffset = 0; [SerializeField] List<SkillImpact> managedImpactInstances = new List<SkillImpact>(); [Range(1, 16)] public int SpawnAmount; public Vector2 SpawnSectorDirection = Vector2.right; [Range(0, 360)] public float SpawnAngle = 60; [HideInInspector] [MAJIKA.Utils.StatusEffect] public List<EffectInstance> AdditionalEffect = new List<EffectInstance>(); [HideInInspector] public Vector2[] SpawnDirections; private void Update() { managedImpactInstances = managedImpactInstances.Where(impact => impact && !impact.Detached).ToList(); } public void SpawnSubImpact() { var impact = GetComponent<SkillImpact>(); if (!impact) return; var dir = MathUtility.SignInt(impact.Direction.x); var target = impact.TargetEntity; var creator = impact.Creator; if (TimeOffset > 0) { StartCoroutine(SpawnCoroutine(AdditionalEffect.ToList(), transform.position, dir, target, creator)); } else { DoSpawn(AdditionalEffect.ToList(), transform.position, dir, target, creator); } } IEnumerator SpawnCoroutine(List<EffectInstance> effects, Vector2 position, float dir, GameEntity target, GameEntity creator) { yield return new WaitForSeconds(TimeOffset); DoSpawn(effects, position, dir, target, creator); } public virtual void Spawn(List<EffectInstance> effects, float dir = 1, GameEntity target = null) { dir = MathUtility.SignInt(dir); effects = effects.Union(AdditionalEffect).ToList(); if(TimeOffset>0) { StartCoroutine(SpawnCoroutine(effects, transform.position, dir, target, Entity)); } else { DoSpawn(effects, transform.position, dir, target, Entity); } } public virtual void SpawnAt(List<EffectInstance> effects, Vector2 position) { effects = effects.Union(AdditionalEffect).ToList(); if (TimeOffset > 0) { StartCoroutine(SpawnCoroutine(effects, position, 1, null, Entity)); } else { DoSpawn(effects, position, 1, null, Entity); } } private SkillImpact SpawnOne(Vector3 pos, Vector3 dir, List<EffectInstance> effects, GameEntity target, GameEntity creator) { var impact = Utility.Instantiate(Prefab, gameObject.scene).GetComponent<SkillImpact>(); impact.Creator = creator; impact.Effects = effects; if (SpawnType == ImpactSpawnType.OnGround) { RaycastHit2D[] hits = new RaycastHit2D[1]; var filter = new ContactFilter2D { layerMask = (1 << 8) | (1 << 9), useLayerMask = true }; if (Physics2D.Raycast(pos.ToVector2(), Vector2.down, filter, hits) > 0) { pos = hits[0].point.ToVector3(); } } impact.Activate(pos, dir, target); return impact; } private void DoSpawn(List<EffectInstance> effects, Vector2 position, float dir, GameEntity target, GameEntity creator) { if(SpawnType == ImpactSpawnType.Barrage) { SpawnDirections.ForEach(spawnDir => { var direction = spawnDir.ToVector3(); direction.x *= dir; var offset = SpawnOffset; offset.x *= dir; var spawnPos = position + SpawnOffset; managedImpactInstances.Add(SpawnOne(spawnPos, direction, effects, target, creator)); }); } else { Vector3 direction = Vector3.right * dir; var offset = SpawnOffset; offset.x *= dir; var pos = position + offset; managedImpactInstances.Add(SpawnOne(pos, direction, effects, target, creator)); } } public void DestoryImpactInstance() { managedImpactInstances.ForEach(impact => Destroy(impact.gameObject)); } public void Deactivate() { DestoryImpactInstance(); } private void OnDrawGizmosSelected() { Gizmos.color = Color.cyan; Gizmos.DrawWireSphere(transform.position + SpawnOffset.ToVector3(), 0.0625f); } }
TheStack
e024928a1d1365a6256b73873e77c3293b8dad94
C#code:C#
{"size": 3559, "ext": "cs", "max_stars_repo_path": "test/Voltaic.Serialization.Json.Tests/Dictionary.cs", "max_stars_repo_name": "RogueException/Voltaic.Serialization", "max_stars_repo_stars_event_min_datetime": "2018-08-30T02:07:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-25T05:55:53.000Z", "max_issues_repo_path": "test/Voltaic.Serialization.Json.Tests/Dictionary.cs", "max_issues_repo_name": "discord-net/Voltaic.Serialization", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Voltaic.Serialization.Json.Tests/Dictionary.cs", "max_forks_repo_name": "discord-net/Voltaic.Serialization", "max_forks_repo_forks_event_min_datetime": "2018-08-08T19:32:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-21T19:53:40.000Z"}
{"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 47.4533333333, "max_line_length": 132, "alphanum_fraction": 0.4610845743}
using System.Collections.Generic; using Voltaic.Serialization.Utf8.Tests; using Xunit; namespace Voltaic.Serialization.Json.Tests { public class DictionaryTests : BaseTest<Dictionary<string, int>> { private class Comparer : IEqualityComparer<Dictionary<string, int>> { public bool Equals(Dictionary<string, int> x, Dictionary<string, int> y) { if (x == null && y == null) return true; if (x == null || y == null) return false; foreach (var pair in x) { if (!y.ContainsKey(pair.Key) || y[pair.Key] != pair.Value) return false; } foreach (var pair in y) { if (!x.ContainsKey(pair.Key) || x[pair.Key] != pair.Value) return false; } return true; } public int GetHashCode(Dictionary<string, int> obj) => 0; // Ignore } public static IEnumerable<object[]> GetData() { yield return ReadWrite("null", null); yield return ReadWrite("{}", new Dictionary<string, int>()); yield return ReadWrite("{\"a\":1}", new Dictionary<string, int> { ["a"] = 1 }); yield return Read("{ \"a\":1}", new Dictionary<string, int> { ["a"] = 1 }); yield return Read("{\"a\":1 }", new Dictionary<string, int> { ["a"] = 1 }); yield return Read("{\"a\" :1}", new Dictionary<string, int> { ["a"] = 1 }); yield return Read("{\"a\": 1}", new Dictionary<string, int> { ["a"] = 1 }); yield return Read("{ \"a\" : 1 }", new Dictionary<string, int> { ["a"] = 1 }); yield return ReadWrite("{\"a\":1,\"b\":2,\"c\":3}", new Dictionary<string, int> { ["a"] = 1, ["b"] = 2, ["c"] = 3 }); yield return Read("{\"a\":1 ,\"b\":2 ,\"c\":3}", new Dictionary<string, int> { ["a"] = 1, ["b"] = 2, ["c"] = 3 }); yield return Read("{\"a\":1, \"b\":2, \"c\":3}", new Dictionary<string, int> { ["a"] = 1, ["b"] = 2, ["c"] = 3 }); yield return Read("{\"a\":1 , \"b\":2 , \"c\":3}", new Dictionary<string, int> { ["a"] = 1, ["b"] = 2, ["c"] = 3 }); yield return Read("{\"a\":1 , \"b\":2 , \"c\":3}", new Dictionary<string, int> { ["a"] = 1, ["b"] = 2, ["c"] = 3 }); yield return FailRead("{"); yield return FailRead("}"); yield return FailRead("{a}"); yield return FailRead("{a}:"); yield return FailRead("{\"a\"}"); yield return FailRead("{\"a\":}"); yield return FailRead("{1}"); yield return FailRead("{:1}"); yield return FailRead("{,1}"); yield return FailRead("{\"a\":1"); yield return FailRead("\"a\":1}"); yield return FailRead("{\"a\":1,\"b\":2,\"b\":3}"); // Duplicate Key yield return FailRead("{\"a\":1\"b\":2\"c\":3}"); yield return FailRead("{\"a\":1 \"b\":2 \"c\":3}"); yield return FailRead("{\"a\":1:\"b\":2:\"c\":3}"); yield return FailRead("[\"a\":1]"); yield return FailRead("{\"a\"1}"); yield return FailRead("{\"a\" 1}"); } public DictionaryTests() : base(new Comparer()) { } [Theory] [MemberData(nameof(GetData))] public void Object(TextTestData<Dictionary<string, int>> data) => RunTest(data); } }
TheStack
e024af7a27fc74a3ff9879ec43ed89d7c3ba273f
C#code:C#
{"size": 1952, "ext": "cs", "max_stars_repo_path": "src/Controls/samples/Controls.Sample/Pages/Core/FlyoutPageGallery.xaml.cs", "max_stars_repo_name": "abod1944/maui", "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:48:19.000Z", "max_issues_repo_path": "src/Controls/samples/Controls.Sample/Pages/Core/FlyoutPageGallery.xaml.cs", "max_issues_repo_name": "abod1944/maui", "max_issues_repo_issues_event_min_datetime": "2020-05-19T15:44:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:56:43.000Z", "max_forks_repo_path": "src/Controls/samples/Controls.Sample/Pages/Core/FlyoutPageGallery.xaml.cs", "max_forks_repo_name": "abod1944/maui", "max_forks_repo_forks_event_min_datetime": "2020-05-19T15:16:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:44:40.000Z"}
{"max_stars_count": 16061.0, "max_issues_count": 3625.0, "max_forks_count": 957.0, "avg_line_length": 24.7088607595, "max_line_length": 99, "alphanum_fraction": 0.7418032787}
using System; using Microsoft.Maui.Controls; namespace Maui.Controls.Sample.Pages { public partial class FlyoutPageGallery { FlyoutPage FlyoutPage => Application.Current.MainPage as FlyoutPage; public FlyoutPageGallery() { InitializeComponent(); flyoutBehaviorPicker.ItemsSource = Enum.GetNames(typeof(FlyoutLayoutBehavior)); flyoutBehaviorPicker.SelectedItem = FlyoutHeaderBehavior.Default.ToString(); flyoutBehaviorPicker.SelectedIndexChanged += OnFlyoutBehaviorPickerSelectedIndexChanged; } void OnGestureEnabledCheckChanged(object sender, CheckedChangedEventArgs e) { if (FlyoutPage == null) return; FlyoutPage.IsGestureEnabled = (sender as CheckBox).IsChecked; } protected override void OnNavigatedTo(NavigatedToEventArgs args) { if (FlyoutPage == null) return; base.OnNavigatedTo(args); UpdatePresentedLabel(); FlyoutPage.IsPresentedChanged += OnPresentedChanged; } private void OnPresentedChanged(object sender, EventArgs e) { UpdatePresentedLabel(); } protected override void OnNavigatedFrom(NavigatedFromEventArgs args) { if (FlyoutPage == null) return; base.OnNavigatedFrom(args); FlyoutPage.IsPresentedChanged -= OnPresentedChanged; } void UpdatePresentedLabel() { if (FlyoutPage == null) return; lblPresented.Text = $"Flyout Is Currently: {FlyoutPage.IsPresented}"; } void OnFlyoutBehaviorPickerSelectedIndexChanged(object sender, EventArgs e) { if (FlyoutPage == null) return; var behavior = Enum.Parse(typeof(FlyoutLayoutBehavior), $"{flyoutBehaviorPicker.SelectedItem}"); FlyoutPage.FlyoutLayoutBehavior = (FlyoutLayoutBehavior)behavior; } void ShowFlyout(object sender, EventArgs e) { if (FlyoutPage == null) return; FlyoutPage.IsPresented = true; } void CloseFlyout(object sender, EventArgs e) { if (FlyoutPage == null) return; FlyoutPage.IsPresented = false; } } }
TheStack
e0266be786adc2c70f412b89b3e4acc7aacd6fd7
C#code:C#
{"size": 464, "ext": "cs", "max_stars_repo_path": "Source/AlephNote.PluginInterface/Objects/ConflictResolutionStrategy.cs", "max_stars_repo_name": "bubdm/AlephNote", "max_stars_repo_stars_event_min_datetime": "2017-03-06T17:52:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T03:39:24.000Z", "max_issues_repo_path": "Source/AlephNote.PluginInterface/Objects/ConflictResolutionStrategy.cs", "max_issues_repo_name": "bubdm/AlephNote", "max_issues_repo_issues_event_min_datetime": "2017-03-07T08:09:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T20:07:00.000Z", "max_forks_repo_path": "Source/AlephNote.PluginInterface/Objects/ConflictResolutionStrategy.cs", "max_forks_repo_name": "bubdm/AlephNote", "max_forks_repo_forks_event_min_datetime": "2017-03-06T18:29:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T12:38:11.000Z"}
{"max_stars_count": 184.0, "max_issues_count": 193.0, "max_forks_count": 25.0, "avg_line_length": 22.0952380952, "max_line_length": 61, "alphanum_fraction": 0.7456896552}
namespace AlephNote.PluginInterface { public enum ConflictResolutionStrategy { // Use client version, override server UseClientVersion = 1, // Use server version, override client UseServerVersion = 2, // Use client version, create conflict note UseClientCreateConflictFile = 3, // Use server version, create conflict note UseServerCreateConflictFile = 4, // Initially use client version, but then show merge dialog ManualMerge = 5, } }
TheStack
e02708207f8daa0f4074b8b71ed2c826bd4b88c4
C#code:C#
{"size": 241, "ext": "cs", "max_stars_repo_path": "Cbn.Infrastructure.Common/Claims/Interfaces/IJwtConfig.cs", "max_stars_repo_name": "wakuwaku3/cbn.clean-sample", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cbn.Infrastructure.Common/Claims/Interfaces/IJwtConfig.cs", "max_issues_repo_name": "wakuwaku3/cbn.clean-sample", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cbn.Infrastructure.Common/Claims/Interfaces/IJwtConfig.cs", "max_forks_repo_name": "wakuwaku3/cbn.clean-sample", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.1, "max_line_length": 53, "alphanum_fraction": 0.6182572614}
namespace Cbn.Infrastructure.Common.Claims.Interfaces { public interface IJwtConfig { string JwtSecret { get; } int JwtExpiresDate { get; } string JwtAudience { get; } string JwtIssuer { get; } } }
TheStack
e0277116cfa99837ba9689e5ee2b2ab7dc04e568
C#code:C#
{"size": 167, "ext": "cs", "max_stars_repo_path": "goldfish.WebUI/Areas/Admin/Controllers/SiteNetsController.cs", "max_stars_repo_name": "simlex-titul2005/goldfish.pro", "max_stars_repo_stars_event_min_datetime": "2016-11-07T13:27:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-07T13:27:02.000Z", "max_issues_repo_path": "goldfish.WebUI/Areas/Admin/Controllers/SiteNetsController.cs", "max_issues_repo_name": "simlex-titul2005/goldfish.pro", "max_issues_repo_issues_event_min_datetime": "2016-09-26T07:15:23.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-21T12:25:08.000Z", "max_forks_repo_path": "goldfish.WebUI/Areas/Admin/Controllers/SiteNetsController.cs", "max_forks_repo_name": "simlex-titul2005/goldfish.pro", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 16.0, "max_forks_count": null, "avg_line_length": 18.5555555556, "max_line_length": 58, "alphanum_fraction": 0.7185628743}
using SX.WebCore.MvcControllers; namespace goldfish.WebUI.Areas.Admin.Controllers { public class SiteNetsController : SxSiteNetsController { } }
TheStack
e0285795f2e8c1a6b28401744129255fa86e2667
C#code:C#
{"size": 4333, "ext": "cs", "max_stars_repo_path": "Rx.NET/Source/System.Reactive.Core/Reactive/Concurrency/SchedulerWrapper.cs", "max_stars_repo_name": "hgGeorg/Rx.NET", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rx.NET/Source/System.Reactive.Core/Reactive/Concurrency/SchedulerWrapper.cs", "max_issues_repo_name": "hgGeorg/Rx.NET", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rx.NET/Source/System.Reactive.Core/Reactive/Concurrency/SchedulerWrapper.cs", "max_forks_repo_name": "hgGeorg/Rx.NET", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.1181102362, "max_line_length": 127, "alphanum_fraction": 0.6095084237}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; #if !NO_WEAKTABLE using System.Runtime.CompilerServices; #endif namespace System.Reactive.Concurrency { internal abstract class SchedulerWrapper : IScheduler, IServiceProvider { protected readonly IScheduler _scheduler; public SchedulerWrapper(IScheduler scheduler) { _scheduler = scheduler; #if !NO_WEAKTABLE _cache = new ConditionalWeakTable<IScheduler, IScheduler>(); #endif } public DateTimeOffset Now { get { return _scheduler.Now; } } public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return _scheduler.Schedule(state, Wrap(action)); } public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return _scheduler.Schedule(state, dueTime, Wrap(action)); } public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action) { if (action == null) throw new ArgumentNullException(nameof(action)); return _scheduler.Schedule(state, dueTime, Wrap(action)); } protected virtual Func<IScheduler, TState, IDisposable> Wrap<TState>(Func<IScheduler, TState, IDisposable> action) { return (self, state) => action(GetRecursiveWrapper(self), state); } #if !NO_WEAKTABLE private readonly ConditionalWeakTable<IScheduler, IScheduler> _cache; public SchedulerWrapper(IScheduler scheduler, ConditionalWeakTable<IScheduler, IScheduler> cache) { _scheduler = scheduler; _cache = cache; } protected IScheduler GetRecursiveWrapper(IScheduler scheduler) { return _cache.GetValue(scheduler, s => Clone(s, _cache)); } protected abstract SchedulerWrapper Clone(IScheduler scheduler, ConditionalWeakTable<IScheduler, IScheduler> cache); #else private readonly object _gate = new object(); private IScheduler _recursiveOriginal; private IScheduler _recursiveWrapper; protected IScheduler GetRecursiveWrapper(IScheduler scheduler) { var recursiveWrapper = default(IScheduler); lock (_gate) { // // Chances are the recursive scheduler will remain the same. In practice, this // single-shot caching scheme works out quite well. Notice we propagate our // mini-cache to recursive raw scheduler wrappers too. // if (!object.ReferenceEquals(scheduler, _recursiveOriginal)) { _recursiveOriginal = scheduler; var wrapper = Clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; _recursiveWrapper = wrapper; } recursiveWrapper = _recursiveWrapper; } return recursiveWrapper; } protected abstract SchedulerWrapper Clone(IScheduler scheduler); #endif public object GetService(Type serviceType) { var serviceProvider = _scheduler as IServiceProvider; if (serviceProvider == null) return null; var result = default(object); if (TryGetService(serviceProvider, serviceType, out result)) return result; return serviceProvider.GetService(serviceType); } protected abstract bool TryGetService(IServiceProvider provider, Type serviceType, out object service); } }
TheStack
e02a176f4d2bceaabb20d52ca448d5d3f91cdac0
C#code:C#
{"size": 1196, "ext": "cs", "max_stars_repo_path": "06. C# OOP Advanced - July 2017/04. Enums And Attributes/04. Enums And Attributes - Exercise/Exercises Enums and Attributes/11. Inferno Infinity/Core/Engine.cs", "max_stars_repo_name": "zrusev/SoftwareUniversity2016", "max_stars_repo_stars_event_min_datetime": "2019-11-15T18:22:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T19:02:05.000Z", "max_issues_repo_path": "06. C# OOP Advanced - July 2017/04. Enums And Attributes/04. Enums And Attributes - Exercise/Exercises Enums and Attributes/11. Inferno Infinity/Core/Engine.cs", "max_issues_repo_name": "zrusev/SoftUni_2016", "max_issues_repo_issues_event_min_datetime": "2019-12-27T19:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T12:27:02.000Z", "max_forks_repo_path": "06. C# OOP Advanced - July 2017/04. Enums And Attributes/04. Enums And Attributes - Exercise/Exercises Enums and Attributes/11. Inferno Infinity/Core/Engine.cs", "max_forks_repo_name": "zrusev/SoftUni_2016", "max_forks_repo_forks_event_min_datetime": "2019-09-21T15:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T18:22:52.000Z"}
{"max_stars_count": 2.0, "max_issues_count": 23.0, "max_forks_count": 2.0, "avg_line_length": 28.4761904762, "max_line_length": 98, "alphanum_fraction": 0.4113712375}
namespace _11.Inferno_Infinity.Core { using System; public class Engine { private CommandInterpreter interpreter; public Engine() { this.interpreter = new CommandInterpreter(); } public void Run() { string input = String.Empty; while ((input = Console.ReadLine()) != "END") { string[] inputData = input.Split(';'); switch (inputData[0]) { case "Add": this.interpreter.Add(inputData[1], int.Parse(inputData[2]), inputData[3]); break; case "Create": this.interpreter.Create(inputData[1], inputData[2]); break; case "Remove": this.interpreter.Remove(inputData[1], int.Parse(inputData[2])); break; case "Print": this.interpreter.Print(inputData[1]); break; default: break; } } } } }
TheStack
e02ab7908753d8aabbd955055326cdf118fe632f
C#code:C#
{"size": 1585, "ext": "cs", "max_stars_repo_path": "Lecture_09_StringAndTextProcessing/Ex04_CharacterMultiplier_var2/Ex04_CharacterMultiplier_var2.cs", "max_stars_repo_name": "AndreyKodzhabashev/CSharpProgrFundAllExercisesSolutions", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture_09_StringAndTextProcessing/Ex04_CharacterMultiplier_var2/Ex04_CharacterMultiplier_var2.cs", "max_issues_repo_name": "AndreyKodzhabashev/CSharpProgrFundAllExercisesSolutions", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture_09_StringAndTextProcessing/Ex04_CharacterMultiplier_var2/Ex04_CharacterMultiplier_var2.cs", "max_forks_repo_name": "AndreyKodzhabashev/CSharpProgrFundAllExercisesSolutions", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.8644067797, "max_line_length": 95, "alphanum_fraction": 0.4164037855}
using System; using System.Linq; namespace Ex04_CharacterMultiplier_var2 { // 80/100 - first test - wrong result class Ex04_CharacterMultiplier_var2 { static void Main() { string[] input = Console.ReadLine() .Split(); string firstWord = input[0]; string secondWord = input[1]; int lengthOfTheShorterWord = Math.Min(firstWord.Length, secondWord.Length); int result = 0; if (firstWord.Length == 0) { result = secondWord.Split("").Skip(1).SelectMany(x => x).ToArray().Sum(x => x); } else if (secondWord.Length == 0) { result = firstWord.Split("").Skip(1).SelectMany(x => x).ToArray().Sum(x => x); } else { for (int i = 0; i < lengthOfTheShorterWord; i++) { result += firstWord[i] * secondWord[i]; } if (firstWord.Length < secondWord.Length) { for (int i = firstWord.Length; i < secondWord.Length; i++) { result += secondWord[i]; } } else { for (int i = firstWord.Length; i < secondWord.Length; i++) { result += secondWord[i]; } } } Console.WriteLine(result); } } }
TheStack
e02aff69cd143df80f9bb95912d2f56bd840f0d8
C#code:C#
{"size": 1888, "ext": "cs", "max_stars_repo_path": "archive/Changesets/mbf-76446/Source/Framework/Bio/IO/SAM/SAMRecordField.cs", "max_stars_repo_name": "jdm7dv/Microsoft-Biology-Foundation", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "archive/Changesets/mbf-76446/Source/Framework/Bio/IO/SAM/SAMRecordField.cs", "max_issues_repo_name": "jdm7dv/Microsoft-Biology-Foundation", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archive/Changesets/mbf-76446/Source/Framework/Bio/IO/SAM/SAMRecordField.cs", "max_forks_repo_name": "jdm7dv/Microsoft-Biology-Foundation", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.4516129032, "max_line_length": 67, "alphanum_fraction": 0.5450211864}
// ********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License, Version 2.0. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // // ********************************************************* using System; using System.Collections.Generic; namespace Bio.IO.SAM { /// <summary> /// This class holds SAM record fields. /// Record fields are present in the SAM header. /// This class can hold one header line of the SAM header. /// For example, consider the following header line. /// @SQ SN:chr20 LN:62435964 /// In this example SQ is the Type code. /// SN:chr20 and LN:62435964 are SAMRecordFieldTags. /// </summary> [Serializable] public class SAMRecordField { #region Constructors /// <summary> /// Creates SAMRecordField instance. /// </summary> public SAMRecordField() { Tags = new List<SAMRecordFieldTag>(); } /// <summary> /// Creates SAMRecordField with the specified type code. /// </summary> /// <param name="typecode">Type code.</param> public SAMRecordField(string typecode) : this() { Typecode = typecode; } #endregion #region Properties /// <summary> /// Record field type code. /// for example. HD, SQ. /// </summary> public string Typecode { get; set; } /// <summary> /// List of SAM RecordFieldTags. /// </summary> public IList<SAMRecordFieldTag> Tags { get; private set; } #endregion } }
TheStack
e02b5ad340d544dda81a4c82a8940c5832db313d
C#code:C#
{"size": 3138, "ext": "cs", "max_stars_repo_path": "Conventional/Conventions/Cecil/MustNotUsePropertyGetterSpecification.cs", "max_stars_repo_name": "gkinsman/Conventional", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Conventional/Conventions/Cecil/MustNotUsePropertyGetterSpecification.cs", "max_issues_repo_name": "gkinsman/Conventional", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Conventional/Conventions/Cecil/MustNotUsePropertyGetterSpecification.cs", "max_forks_repo_name": "gkinsman/Conventional", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 36.9176470588, "max_line_length": 132, "alphanum_fraction": 0.5289993627}
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Mono.Cecil; using Mono.Cecil.Cil; namespace Conventional.Conventions.Cecil { public abstract class MustNotUsePropertyGetterSpecification<TClass, TMember> : ConventionSpecification { private class GetterDetails { public GetterDetails(string declaringType, string methodName) { DeclaringType = declaringType; MethodName = methodName; } public string DeclaringType { get; private set; } public string MethodName { get; private set; } } private readonly string _failureMessage; private readonly GetterDetails[] _getterDetails; protected MustNotUsePropertyGetterSpecification(Expression<Func<TClass, TMember>> expression, string failureMessage) :this(new[] {expression},failureMessage) { } protected MustNotUsePropertyGetterSpecification(Expression<Func<TClass, TMember>>[] expressions, string failureMessage) { _failureMessage = failureMessage; _getterDetails = expressions.Select(e => { var memberExpression = (MemberExpression) e.Body; var propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("Expression must be a memberexpression selecting a single property.", nameof(expressions)); } return new GetterDetails(typeof (TClass).FullName, propertyInfo.GetGetMethod().Name); }).ToArray(); } protected override string FailureMessage => _failureMessage; public override ConventionResult IsSatisfiedBy(Type type) { var assignments = type.ToTypeDefinition() .Methods .Where(method => method.HasBody) .SelectMany(method => method.Body.Instructions) .Where(x => x.OpCode == OpCodes.Call && x.Operand is MethodReference) .Join(_getterDetails, x=>new { DeclaringType = ((MethodReference)x.Operand).DeclaringType.FullName, MethodName = ((MethodReference)x.Operand).Name }, g=>new { g.DeclaringType, g.MethodName }, (x,g)=>x) .ToArray(); if (assignments.Any()) { return ConventionResult.NotSatisfied(type.FullName, FailureMessage.FormatWith(assignments.Count(), type.FullName)); } return ConventionResult.Satisfied(type.FullName); } } }
TheStack
e02c36377202b6ea778a347d0ed86dcda9a1d95e
C#code:C#
{"size": 371, "ext": "cs", "max_stars_repo_path": "Vue.Net/VOL.WebApi/Controllers/Order/Partial/SellOrderListController.cs", "max_stars_repo_name": "kissxic/Vue.NetCore", "max_stars_repo_stars_event_min_datetime": "2019-09-26T06:50:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:41:53.000Z", "max_issues_repo_path": "Vue.Net/VOL.WebApi/Controllers/Order/Partial/SellOrderListController.cs", "max_issues_repo_name": "linkdream1/Vue.NetCore", "max_issues_repo_issues_event_min_datetime": "2019-10-09T09:04:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:43:05.000Z", "max_forks_repo_path": "Vue.Net/VOL.WebApi/Controllers/Order/Partial/SellOrderListController.cs", "max_forks_repo_name": "linkdream1/Vue.NetCore", "max_forks_repo_forks_event_min_datetime": "2019-09-27T08:32:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:01:54.000Z"}
{"max_stars_count": 2694.0, "max_issues_count": 185.0, "max_forks_count": 894.0, "avg_line_length": 20.6111111111, "max_line_length": 79, "alphanum_fraction": 0.781671159}
/* *接口编写处... *如果接口需要做Action的权限验证,请在Action上使用属性 *如: [ApiActionPermission("SellOrderList",Enums.ActionPermissionOptions.Search)] */ using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using VOL.Entity.DomainModels; namespace VOL.Order.Controllers { public partial class SellOrderListController { } }
TheStack
e02c438cf891399210c212212360736289704fb9
C#code:C#
{"size": 1145, "ext": "cs", "max_stars_repo_path": "Engine.Content.FmtCollada/FX/TechniqueFX.cs", "max_stars_repo_name": "Selinux24/SharpDX-Tests", "max_stars_repo_stars_event_min_datetime": "2017-07-20T11:26:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-27T15:22:05.000Z", "max_issues_repo_path": "Engine.Content.FmtCollada/FX/TechniqueFX.cs", "max_issues_repo_name": "Selinux24/SharpDX-Tests", "max_issues_repo_issues_event_min_datetime": "2015-07-30T08:52:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T10:43:23.000Z", "max_forks_repo_path": "Engine.Content.FmtCollada/FX/TechniqueFX.cs", "max_forks_repo_name": "Selinux24/SharpDX-Tests", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2.0, "max_issues_count": 67.0, "max_forks_count": null, "avg_line_length": 31.8055555556, "max_line_length": 56, "alphanum_fraction": 0.5676855895}
using System; using System.Xml.Serialization; namespace Engine.Collada.FX { [Serializable] public class TechniqueFX { [XmlAttribute("id")] public string Id { get; set; } [XmlAttribute("sid")] public string SId { get; set; } [XmlElement("annotate", typeof(Annotate))] public Annotate[] Annotates { get; set; } [XmlElement("code", typeof(Code))] public Code[] Code { get; set; } [XmlElement("include", typeof(Include))] public Include[] Include { get; set; } [XmlElement("image", typeof(Image))] public Image[] Images { get; set; } [XmlElement("newparam", typeof(NewParam))] public NewParam[] NewParams { get; set; } [XmlElement("setparam", typeof(SetParam))] public SetParam[] SetParams { get; set; } [XmlElement("pass", typeof(Pass))] public Pass[] Passes { get; set; } [XmlElement("extra", typeof(Extra))] public Extra[] Extras { get; set; } public override string ToString() { return "Technique (FX); " + base.ToString(); } } }
TheStack
e02cdac592c9904d0cbd7d65ebc5049c4a100fa3
C#code:C#
{"size": 240, "ext": "cs", "max_stars_repo_path": "src/Nager.AmazonProductAdvertising/Model/Paapi/VariationDimension.cs", "max_stars_repo_name": "ianhoppes/Nager.AmazonProductAdvertising", "max_stars_repo_stars_event_min_datetime": "2016-03-30T13:32:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-10T11:49:48.000Z", "max_issues_repo_path": "src/Nager.AmazonProductAdvertising/Model/Paapi/VariationDimension.cs", "max_issues_repo_name": "ianhoppes/Nager.AmazonProductAdvertising", "max_issues_repo_issues_event_min_datetime": "2016-04-09T22:14:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T17:47:13.000Z", "max_forks_repo_path": "src/Nager.AmazonProductAdvertising/Model/Paapi/VariationDimension.cs", "max_forks_repo_name": "ianhoppes/Nager.AmazonProductAdvertising", "max_forks_repo_forks_event_min_datetime": "2016-04-18T20:41:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-09T22:24:20.000Z"}
{"max_stars_count": 114.0, "max_issues_count": 109.0, "max_forks_count": 75.0, "avg_line_length": 24.0, "max_line_length": 53, "alphanum_fraction": 0.6333333333}
namespace Nager.AmazonProductAdvertising.Model.Paapi { public class VariationDimension { public string DisplayName { get; set; } public string Name { get; set; } public string[] Values { get; set; } } }
TheStack
e02e7d28609abd6bfb066cbbcaa128009e232f75
C#code:C#
{"size": 723, "ext": "cs", "max_stars_repo_path": "ECORP/ECORP/Classes/Magazijn.cs", "max_stars_repo_name": "coenvc/ECORP", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ECORP/ECORP/Classes/Magazijn.cs", "max_issues_repo_name": "coenvc/ECORP", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ECORP/ECORP/Classes/Magazijn.cs", "max_forks_repo_name": "coenvc/ECORP", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.3225806452, "max_line_length": 69, "alphanum_fraction": 0.5905947441}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECORP.Classes { class Magazijn { public List<Product> Producten = new List<Product>(); public List<Medewerker> Medewerkers = new List<Medewerker>(); public Address Address { get; private set; } public string Naam {get; private set;} public int Id {get; set;} public Magazijn(string naam, int id,Address address) { this.Naam = naam; this.Id = id; this.Address = address; } public Magazijn(string naam, Address address) { this.Naam = naam; } } }
TheStack
e02ed27d8234d60c9725a2fc5ddc5ad98f515335
C#code:C#
{"size": 2536, "ext": "cs", "max_stars_repo_path": "Unity/Assets/Hotfix/GameGather/Common/UI/RecodPanel/RecodPanelComponent.cs", "max_stars_repo_name": "dingxing123/fivestar", "max_stars_repo_stars_event_min_datetime": "2019-07-28T02:44:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T15:21:28.000Z", "max_issues_repo_path": "Unity/Assets/Hotfix/GameGather/Common/UI/RecodPanel/RecodPanelComponent.cs", "max_issues_repo_name": "dingxing123/fivestar", "max_issues_repo_issues_event_min_datetime": "2020-08-28T06:14:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-07T01:46:00.000Z", "max_forks_repo_path": "Unity/Assets/Hotfix/GameGather/Common/UI/RecodPanel/RecodPanelComponent.cs", "max_forks_repo_name": "dingxing123/fivestar", "max_forks_repo_forks_event_min_datetime": "2019-07-28T07:25:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T02:35:39.000Z"}
{"max_stars_count": 121.0, "max_issues_count": 2.0, "max_forks_count": 72.0, "avg_line_length": 30.9268292683, "max_line_length": 103, "alphanum_fraction": 0.5465299685}
using System; using ETModel; using UnityEngine; using UnityEngine.UI; namespace ETHotfix { [UIComponent(UIType.RecodPanel)] public class RecodPanelComponent : ChildUIView { #region 脚本工具生成的代码 private GameObject mNormalGo; private GameObject mCancelGo; private GameObject mVolumeMaskGo; private Image mResidueTimeImage; public override void Awake() { base.Awake(); ReferenceCollector rc = this.GetParent<UI>().GameObject.GetComponent<ReferenceCollector>(); mNormalGo = rc.Get<GameObject>("NormalGo"); mCancelGo = rc.Get<GameObject>("CancelGo"); mVolumeMaskGo = rc.Get<GameObject>("VolumeMaskGo"); mResidueTimeImage = rc.Get<GameObject>("ResidueTimeImage").GetComponent<Image>(); InitPanel(); } #endregion private RectTransform _MaskRecTrm; public void InitPanel() { _MaskRecTrm = mVolumeMaskGo.GetComponent<RectTransform>(); fillMinus = 1.000f / (SpeexRecordMgr.Ins.SpeakMaxTime * 10); } private Vector2 _maskSizeData=new Vector2(39,0); private const int _maxHeight = 130; public async void VolumeBounce() { while (pViewState== ViewState.Show) { await ETModel.Game.Scene.GetComponent<TimerComponent>().WaitAsync(100); _maskSizeData.y += 20; if (_maskSizeData.y > _maxHeight) { _maskSizeData.y = 0; } _MaskRecTrm.sizeDelta = _maskSizeData; } } public void ShowNomalPanel() { Show(); mNormalGo.SetActive(true); mCancelGo.SetActive(false); } public void ShowCancelPanel() { Show(); mNormalGo.SetActive(false); mCancelGo.SetActive(true); } private float fillMinus; public override async void OnShow() { base.OnShow(); VolumeBounce(); mResidueTimeImage.fillAmount = 1; while (gameObject.activeInHierarchy) { mResidueTimeImage.fillAmount -= fillMinus; if (mResidueTimeImage.fillAmount <= 0) { Hide(); } await ETModel.Game.Scene.GetComponent<TimerComponent>().WaitAsync(100); } } } }
TheStack
e02ee084e954af71a49acc5daf02472476e76b29
C#code:C#
{"size": 3993, "ext": "cs", "max_stars_repo_path": "Editor/UtilitySettingsEditor.cs", "max_stars_repo_name": "oguzhalil/unityscripts", "max_stars_repo_stars_event_min_datetime": "2020-03-29T14:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T14:55:52.000Z", "max_issues_repo_path": "Editor/UtilitySettingsEditor.cs", "max_issues_repo_name": "oguzhalil/unityscripts", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Editor/UtilitySettingsEditor.cs", "max_forks_repo_name": "oguzhalil/unityscripts", "max_forks_repo_forks_event_min_datetime": "2021-01-09T08:47:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T08:47:36.000Z"}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 31.944, "max_line_length": 125, "alphanum_fraction": 0.5890308039}
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System; [CustomEditor( typeof( UtilitySettings ) )] public class UtilitySettingsEditor : Editor { private UtilitySettings settings; private string defineSymbols; public const string symbolAdmob = "ENABLE_ADMOB"; public const string symbolUnityAds = "ENABLE_UNITYADS"; public const string symbolGPGS = "ENABLE_GPGS"; public const string symbolPlayfab = "ENABLE_PLAYFAB"; public const string symbolLogger = "ENABLE_LOGS"; public const string symbolInApp = "ENABLE_INAPP"; public const string symbolLeanTween = "ENABLE_LEANTWEEN"; public override void OnInspectorGUI () { EditorGUI.BeginChangeCheck(); settings.googlePlayGameServices = EditorGUILayout.Toggle( "Google Play Services" , settings.googlePlayGameServices ); settings.playfabServices = EditorGUILayout.Toggle( "Playfab Services" , settings.playfabServices ); settings.admobServices = EditorGUILayout.Toggle( "Admob Services" , settings.admobServices ); settings.unityAdsServices = EditorGUILayout.Toggle( "Unity Ads Services" , settings.unityAdsServices ); settings.loggerEnabled = EditorGUILayout.Toggle( "Logger Enabled" , settings.loggerEnabled ); settings.inAppPurcases = EditorGUILayout.Toggle( "In App Purcases Enabled" , settings.inAppPurcases ); settings.leanTween = EditorGUILayout.Toggle( "Lean Tween Imported" , settings.leanTween ); if ( EditorGUI.EndChangeCheck() ) { ChangeSymbol( settings ); } serializedObject.ApplyModifiedProperties(); } private void OnEnable () { settings = target as UtilitySettings; } private void ChangeSymbol ( UtilitySettings settings ) // def CROSS_PLATFORM_INPUT;BCG_RCC { string symbols = PlayerSettings.GetScriptingDefineSymbolsForGroup( BuildTargetGroup.Android ); string [] seperatedSymbols = symbols.Split( ';' ); List<string> newSymbols = new List<string>(); if ( settings.googlePlayGameServices ) { newSymbols.Add( symbolGPGS ); } if ( settings.unityAdsServices ) { newSymbols.Add( symbolUnityAds ); } if ( settings.admobServices ) { newSymbols.Add( symbolAdmob ); } if ( settings.loggerEnabled ) { newSymbols.Add( symbolLogger ); } if ( settings.playfabServices ) { newSymbols.Add( symbolPlayfab ); } if ( settings.inAppPurcases ) { newSymbols.Add( symbolInApp ); } if ( settings.leanTween ) { newSymbols.Add( symbolLeanTween ); } foreach ( var seperatedSymbol in seperatedSymbols ) { switch ( seperatedSymbol ) { case symbolAdmob: break; case symbolUnityAds: break; case symbolGPGS: break; case symbolPlayfab: break; case symbolLogger: break; case symbolInApp: break; case symbolLeanTween: break; default: newSymbols.Add( seperatedSymbol ); break; } } if ( newSymbols.Count == 0 ) { PlayerSettings.SetScriptingDefineSymbolsForGroup( BuildTargetGroup.Android , string.Empty ); } else { string output = newSymbols [ 0 ]; for ( int i = 1; i < newSymbols.Count; i++ ) { output += ";" + newSymbols [ i ]; } PlayerSettings.SetScriptingDefineSymbolsForGroup( BuildTargetGroup.Android , output ); } } }
TheStack
e02f37bdd78d8d56d79b3c43cef0b8f540a14b44
C#code:C#
{"size": 593, "ext": "cs", "max_stars_repo_path": "NadekoBot.Core/Services/IImageCache.cs", "max_stars_repo_name": "Erencorn/Kotocorn", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NadekoBot.Core/Services/IImageCache.cs", "max_issues_repo_name": "Erencorn/Kotocorn", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NadekoBot.Core/Services/IImageCache.cs", "max_forks_repo_name": "Erencorn/Kotocorn", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.7666666667, "max_line_length": 38, "alphanum_fraction": 0.5092748735}
using Kotocorn.Core.Common; using System.Threading.Tasks; namespace Kotocorn.Core.Services { public interface IImageCache { ImageUrls ImageUrls { get; } byte[][] Heads { get; } byte[][] Tails { get; } byte[][] Dice { get; } byte[] SlotBackground { get; } byte[][] SlotEmojis { get; } byte[][] SlotNumbers { get; } byte[] WifeMatrix { get; } byte[] RategirlDot { get; } byte[] XpCard { get; } byte[] Rip { get; } byte[] FlowerCircle { get; } Task Reload(); } }
TheStack
e02f5caddcee904424d32bb40ac5376f680b1086
C#code:C#
{"size": 292, "ext": "cs", "max_stars_repo_path": "src/OneInch.Api/Configuration/BlockchainEnum.cs", "max_stars_repo_name": "0xDelco/1inch-api-v3", "max_stars_repo_stars_event_min_datetime": "2021-12-09T19:51:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T19:51:03.000Z", "max_issues_repo_path": "src/OneInch.Api/Configuration/BlockchainEnum.cs", "max_issues_repo_name": "0xDelco/1inch-api-v3", "max_issues_repo_issues_event_min_datetime": "2021-10-04T01:06:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T01:06:50.000Z", "max_forks_repo_path": "src/OneInch.Api/Configuration/BlockchainEnum.cs", "max_forks_repo_name": "0xDelco/1inch-api-v3", "max_forks_repo_forks_event_min_datetime": "2021-10-04T00:01:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T07:21:23.000Z"}
{"max_stars_count": 1.0, "max_issues_count": 1.0, "max_forks_count": 2.0, "avg_line_length": 19.4666666667, "max_line_length": 57, "alphanum_fraction": 0.5582191781}
namespace OneInch.Api { /// <summary> /// Enumeration that defines standard blockchain IDs. /// </summary> public enum BlockchainEnum { ETHEREUM = 1, OPTIMISM = 10, BINANCE_SMART_CHAIN = 56, POLYGON = 137, ARBITRUM = 42161 } }
TheStack
e0304e56a4ffe01d55e03d40ca48d1e5bbf00e60
C#code:C#
{"size": 2960, "ext": "cs", "max_stars_repo_path": "vpnStatus/VpnStatusApp.cs", "max_stars_repo_name": "rvaccarim/vpnStatus", "max_stars_repo_stars_event_min_datetime": "2021-07-15T17:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T13:25:09.000Z", "max_issues_repo_path": "vpnStatus/VpnStatusApp.cs", "max_issues_repo_name": "rvaccarim/vpnStatus", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vpnStatus/VpnStatusApp.cs", "max_forks_repo_name": "rvaccarim/vpnStatus", "max_forks_repo_forks_event_min_datetime": "2021-07-15T18:08:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T17:26:17.000Z"}
{"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 29.0196078431, "max_line_length": 76, "alphanum_fraction": 0.5344594595}
using System; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace vpnStatus { public class VpnStatusApp : ApplicationContext { private NotifyIcon vpnNotifyIcon; private ContextMenuStrip vpnMenu; private ToolStripMenuItem exitMenuItem; private Timer myTimer; private string vpnName; public VpnStatusApp() { Init(); ScanNetwork(vpnName); myTimer.Enabled = true; } private void Init() { vpnNotifyIcon = new NotifyIcon(); vpnMenu = new ContextMenuStrip(); exitMenuItem = new ToolStripMenuItem(); vpnMenu.ImageScalingSize = new Size(20, 20); vpnMenu.Items.AddRange(new ToolStripItem[] { exitMenuItem}); vpnMenu.Name = "vpnMenu"; vpnMenu.Size = new Size(103, 28); exitMenuItem.Name = "exitToolStripMenuItem"; exitMenuItem.Size = new Size(210, 24); exitMenuItem.Text = "Exit"; exitMenuItem.Click += new EventHandler(this.ExitMenuItem_Click); vpnNotifyIcon.ContextMenuStrip = this.vpnMenu; vpnNotifyIcon.Icon = Properties.Resources.Inactive; vpnNotifyIcon.Text = "VPN Status"; vpnNotifyIcon.Visible = true; myTimer = new Timer { Enabled = false, Interval = 3000 }; myTimer.Tick += new EventHandler(this.TimerElapsed); vpnName = Properties.Settings.Default.VpnName; } private void ScanNetwork(string vpnName) { var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "CMD.EXE", Arguments = "/C netsh interface show interface", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; bool found = false; proc.Start(); while (!proc.StandardOutput.EndOfStream) { string line = proc.StandardOutput.ReadLine(); if (line.Contains(vpnName) && line.Contains(" Connected")) { found = true; break; } } if (found) { this.vpnNotifyIcon.Icon = Properties.Resources.Active; } else { this.vpnNotifyIcon.Icon = Properties.Resources.Inactive; } } private void TimerElapsed(object sender, EventArgs e) { ScanNetwork(vpnName); } private void ExitMenuItem_Click(object sender, EventArgs e) { Exit(); } private void Exit() { vpnNotifyIcon.Visible = false; myTimer.Enabled = false; Application.Exit(); } } }
TheStack
e0322c6ef10e570fc6718d2ff25b07732b9308bd
C#code:C#
{"size": 2005, "ext": "cs", "max_stars_repo_path": "Src/SAEA.Audio.Net/Base/NAudio/Mixer/SignedMixerControl.cs", "max_stars_repo_name": "dsfop/SAEA", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Src/SAEA.Audio.Net/Base/NAudio/Mixer/SignedMixerControl.cs", "max_issues_repo_name": "dsfop/SAEA", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/SAEA.Audio.Net/Base/NAudio/Mixer/SignedMixerControl.cs", "max_forks_repo_name": "dsfop/SAEA", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.3815789474, "max_line_length": 173, "alphanum_fraction": 0.7341645885}
using System; using System.Runtime.InteropServices; namespace SAEA.Audio.Base.NAudio.Mixer { public class SignedMixerControl : MixerControl { private MixerInterop.MIXERCONTROLDETAILS_SIGNED signedDetails; public int Value { get { base.GetControlDetails(); return this.signedDetails.lValue; } set { this.signedDetails.lValue = value; this.mixerControlDetails.paDetails = Marshal.AllocHGlobal(Marshal.SizeOf(this.signedDetails)); Marshal.StructureToPtr(this.signedDetails, this.mixerControlDetails.paDetails, false); MmException.Try(MixerInterop.mixerSetControlDetails(this.mixerHandle, ref this.mixerControlDetails, MixerFlags.Mixer | this.mixerHandleType), "mixerSetControlDetails"); Marshal.FreeHGlobal(this.mixerControlDetails.paDetails); } } public int MinValue { get { return this.mixerControl.Bounds.minimum; } } public int MaxValue { get { return this.mixerControl.Bounds.maximum; } } public double Percent { get { return 100.0 * (double)(this.Value - this.MinValue) / (double)(this.MaxValue - this.MinValue); } set { this.Value = (int)((double)this.MinValue + value / 100.0 * (double)(this.MaxValue - this.MinValue)); } } internal SignedMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels) { this.mixerControl = mixerControl; this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; this.nChannels = nChannels; this.mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS); base.GetControlDetails(); } protected override void GetDetails(IntPtr pDetails) { this.signedDetails = (MixerInterop.MIXERCONTROLDETAILS_SIGNED)Marshal.PtrToStructure(this.mixerControlDetails.paDetails, typeof(MixerInterop.MIXERCONTROLDETAILS_SIGNED)); } public override string ToString() { return string.Format("{0} {1}%", base.ToString(), this.Percent); } } }
TheStack
e03247a8458ca80769c2b23ec93aa5b4aa359995
C#code:C#
{"size": 2040, "ext": "cs", "max_stars_repo_path": "src/Markalize.Core/NoTraceSource.cs", "max_stars_repo_name": "sandrock/Markalize", "max_stars_repo_stars_event_min_datetime": "2019-03-14T08:15:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T08:15:51.000Z", "max_issues_repo_path": "src/Markalize.Core/NoTraceSource.cs", "max_issues_repo_name": "sandrock/Markalize", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Markalize.Core/NoTraceSource.cs", "max_forks_repo_name": "sandrock/Markalize", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.1851851852, "max_line_length": 111, "alphanum_fraction": 0.4848039216}
 namespace Markalize.Core { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; /// <summary> /// Copy of <see cref="TraceSource"/> that uses <see cref="Trace"/> internaly. /// </summary> internal sealed class NoTraceSource { private readonly string name; private readonly bool prependDateTime; public NoTraceSource() { } public NoTraceSource(string name) : this(name, false) { } public NoTraceSource(string name, bool prependDateTime) { this.prependDateTime = prependDateTime; if (!string.IsNullOrEmpty(name)) { this.name = name + ": "; } } public void Write(StringBuilder sb) { if (sb == null) throw new ArgumentNullException("sb"); if (sb.Length == 0) return; var message = sb.ToString().Trim(); if (this.prependDateTime) { Trace.WriteLine(DateTime.UtcNow.ToString("o") + " " + this.name + message); } else { Trace.WriteLine(this.name + message); } } public void WriteLine(string message) { if (this.prependDateTime) { Trace.WriteLine(DateTime.UtcNow.ToString("o") + " " + this.name + message); } else { Trace.WriteLine(this.name + message); } } public void WriteLine(string format, params object[] args) { if (this.prependDateTime) { Trace.WriteLine(DateTime.UtcNow.ToString("o") + " " + this.name + string.Format(format, args)); } else { Trace.WriteLine(this.name + string.Format(format, args)); } } } }
TheStack
e032781daef2561be810fa6263d7521c2a44675d
C#code:C#
{"size": 10738, "ext": "cs", "max_stars_repo_path": "Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Base/PaletteRedirect/PaletteRedirectBorderEdge.cs", "max_stars_repo_name": "Krypton-Suite-Legacy/Krypton-NET-5.400", "max_stars_repo_stars_event_min_datetime": "2018-07-11T08:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-10T11:11:23.000Z", "max_issues_repo_path": "Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Base/PaletteRedirect/PaletteRedirectBorderEdge.cs", "max_issues_repo_name": "Krypton-Suite-Legacy/Krypton-NET-5.400", "max_issues_repo_issues_event_min_datetime": "2019-08-31T15:39:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-31T15:41:23.000Z", "max_forks_repo_path": "Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Base/PaletteRedirect/PaletteRedirectBorderEdge.cs", "max_forks_repo_name": "Krypton-Suite-Legacy/Krypton-NET-5.400", "max_forks_repo_forks_event_min_datetime": "2018-11-18T05:32:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-18T05:32:12.000Z"}
{"max_stars_count": 3.0, "max_issues_count": 5.0, "max_forks_count": 1.0, "avg_line_length": 40.6742424242, "max_line_length": 157, "alphanum_fraction": 0.599366735}
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.400) // Version 5.400.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Diagnostics; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Redirect border based on the incoming state of the request. /// </summary> public class PaletteRedirectBorderEdge : PaletteRedirect { #region Instance Fields private PaletteBorderEdge _disabled; private PaletteBorderEdge _normal; #endregion #region Identity /// <summary> /// Initialize a new instance of the PaletteRedirectBorderEdge class. /// </summary> /// <param name="target">Initial palette target for redirection.</param> public PaletteRedirectBorderEdge(IPalette target) : this(target, null, null) { } /// <summary> /// Initialize a new instance of the PaletteRedirectBorderEdge class. /// </summary> /// <param name="target">Initial palette target for redirection.</param> /// <param name="disabled">Redirection for disabled state requests.</param> /// <param name="normal">Redirection for normal state requests.</param> public PaletteRedirectBorderEdge(IPalette target, PaletteBorderEdge disabled, PaletteBorderEdge normal) : base(target) { // Remember state specific inheritance _disabled = disabled; _normal = normal; } #endregion #region SetRedirectStates /// <summary> /// Set the redirection states. /// </summary> /// <param name="disabled">Redirection for disabled state requests.</param> /// <param name="normal">Redirection for normal state requests.</param> public virtual void SetRedirectStates(PaletteBorderEdge disabled, PaletteBorderEdge normal) { _disabled = disabled; _normal = normal; } #endregion #region ResetRedirectStates /// <summary> /// Reset the redirection states to null. /// </summary> public virtual void ResetRedirectStates() { _disabled = null; _normal = null; } #endregion #region Border /// <summary> /// Gets a value indicating if border should be drawn. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>InheritBool value.</returns> public override InheritBool GetBorderDraw(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackDraw(state) ?? Target.GetBorderDraw(style, state); } /// <summary> /// Gets a value indicating which borders to draw. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>PaletteDrawBorders value.</returns> public override PaletteDrawBorders GetBorderDrawBorders(PaletteBorderStyle style, PaletteState state) { return Target.GetBorderDrawBorders(style, state); } /// <summary> /// Gets the graphics drawing hint for the border. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>PaletteGraphicsHint value.</returns> public override PaletteGraphicsHint GetBorderGraphicsHint(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackGraphicsHint(state) ?? Target.GetBorderGraphicsHint(style, state); } /// <summary> /// Gets the first border color. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color value.</returns> public override Color GetBorderColor1(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackColor1(state) ?? Target.GetBorderColor1(style, state); } /// <summary> /// Gets the second border color. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color value.</returns> public override Color GetBorderColor2(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackColor2(state) ?? Target.GetBorderColor2(style, state); } /// <summary> /// Gets the color border drawing style. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color drawing style.</returns> public override PaletteColorStyle GetBorderColorStyle(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackColorStyle(state) ?? Target.GetBorderColorStyle(style, state); } /// <summary> /// Gets the color border alignment. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Color alignment style.</returns> public override PaletteRectangleAlign GetBorderColorAlign(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackColorAlign(state) ?? Target.GetBorderColorAlign(style, state); } /// <summary> /// Gets the color border angle. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Angle used for color drawing.</returns> public override float GetBorderColorAngle(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackColorAngle(state) ?? Target.GetBorderColorAngle(style, state); } /// <summary> /// Gets the border width. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Integer width.</returns> public override int GetBorderWidth(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBorderWidth(state) ?? Target.GetBorderWidth(style, state); } /// <summary> /// Gets the border corner rounding. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Integer rounding.</returns> public override int GetBorderRounding(PaletteBorderStyle style, PaletteState state) { return Target.GetBorderRounding(style, state); } /// <summary> /// Gets a border image. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Image instance.</returns> public override Image GetBorderImage(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackImage(state) ?? Target.GetBorderImage(style, state); } /// <summary> /// Gets the border image style. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Image style value.</returns> public override PaletteImageStyle GetBorderImageStyle(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackImageStyle(state) ?? Target.GetBorderImageStyle(style, state); } /// <summary> /// Gets the image border alignment. /// </summary> /// <param name="style">Border style.</param> /// <param name="state">Palette value should be applicable to this state.</param> /// <returns>Image alignment style.</returns> public override PaletteRectangleAlign GetBorderImageAlign(PaletteBorderStyle style, PaletteState state) { PaletteBorderEdge inherit = GetInherit(state); return inherit?.GetBackImageAlign(state) ?? Target.GetBorderImageAlign(style, state); } #endregion #region Implementation private PaletteBorderEdge GetInherit(PaletteState state) { switch (state) { case PaletteState.Disabled: return _disabled; case PaletteState.Normal: return _normal; default: // Should never happen! Debug.Assert(false); return null; } } #endregion } }
TheStack
e034cf85df654a002a771f561a5fe3a9a64d9ba0
C#code:C#
{"size": 794, "ext": "cs", "max_stars_repo_path": "AzStorage/Core/Errors/Queue/QueueErrorCode.cs", "max_stars_repo_name": "cesarpv27/Azure.Repositories", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AzStorage/Core/Errors/Queue/QueueErrorCode.cs", "max_issues_repo_name": "cesarpv27/Azure.Repositories", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AzStorage/Core/Errors/Queue/QueueErrorCode.cs", "max_forks_repo_name": "cesarpv27/Azure.Repositories", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.7, "max_line_length": 76, "alphanum_fraction": 0.7430730479}
using System; using System.Collections.Generic; using System.Text; namespace AzStorage.Core.Errors.Queue { public class QueueErrorCode { public const string InvalidMarker = nameof(InvalidMarker); public const string MessageNotFound = nameof(MessageNotFound); public const string MessageTooLarge = nameof(MessageTooLarge); public const string PopReceiptMismatch = nameof(PopReceiptMismatch); public const string QueueAlreadyExists = nameof(QueueAlreadyExists); public const string QueueBeingDeleted = nameof(QueueBeingDeleted); public const string QueueDisabled = nameof(QueueDisabled); public const string QueueNotEmpty = nameof(QueueNotEmpty); public const string QueueNotFound = nameof(QueueNotFound); } }
TheStack
e035af00e4d2b6e462b8320040ce7aabfa199b87
C#code:C#
{"size": 6665, "ext": "cs", "max_stars_repo_path": "test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/Events/TSGestureDetector.cs", "max_stars_repo_name": "lavataste/TizenFX", "max_stars_repo_stars_event_min_datetime": "2020-12-09T07:31:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T07:31:17.000Z", "max_issues_repo_path": "test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/Events/TSGestureDetector.cs", "max_issues_repo_name": "lavataste/TizenFX", "max_issues_repo_issues_event_min_datetime": "2019-08-19T18:05:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-19T12:03:06.000Z", "max_forks_repo_path": "test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/Events/TSGestureDetector.cs", "max_forks_repo_name": "lavataste/TizenFX", "max_forks_repo_forks_event_min_datetime": "2019-08-26T07:58:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-24T13:04:44.000Z"}
{"max_stars_count": 1.0, "max_issues_count": 35.0, "max_forks_count": 9.0, "avg_line_length": 36.6208791209, "max_line_length": 123, "alphanum_fraction": 0.5867966992}
using NUnit.Framework; using NUnit.Framework.TUnit; using System; using Tizen.NUI; using Tizen.NUI.BaseComponents; namespace Tizen.NUI.Devel.Tests { using tlog = Tizen.Log; [TestFixture] [Description("public/Events/GestureDetector")] class PublicGestureDetectorTest { private const string tag = "NUITEST"; [SetUp] public void Init() { tlog.Info(tag, "Init() is called!"); } [TearDown] public void Destroy() { tlog.Info(tag, "Destroy() is called!"); } [Test] [Category("P1")] [Description("GestureDetector constructor")] [Property("SPEC", "Tizen.NUI.GestureDetector.GestureDetector C")] [Property("SPEC_URL", "-")] [Property("CRITERIA", "CONSTR")] [Property("AUTHOR", "[email protected]")] public void GestureDetectorConstructor() { tlog.Debug(tag, $"GestureDetectorConstructor START"); var testingTarget = new GestureDetector(); Assert.IsNotNull(testingTarget, "should be not null"); Assert.IsInstanceOf<GestureDetector>(testingTarget, "should be an instance of testing target class!"); testingTarget.Dispose(); tlog.Debug(tag, $"GestureDetectorConstructor END (OK)"); Assert.Pass("GestureDetectorConstructor"); } [Test] [Category("P1")] [Description("GestureDetector Attach")] [Property("SPEC", "Tizen.NUI.GestureDetector.Attach M")] [Property("SPEC_URL", "-")] [Property("CRITERIA", "MR")] [Property("AUTHOR", "[email protected]")] public void GestureDetectorAttach() { tlog.Debug(tag, $"GestureDetectorAttach START"); var testingTarget = new LongPressGestureDetector(); Assert.IsNotNull(testingTarget, "should be not null"); Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!"); using (View view = new View()) { Window.Instance.GetDefaultLayer().Add(view); testingTarget.Attach(view); testingTarget.Detach(view); Window.Instance.GetDefaultLayer().Remove(view); } testingTarget.Dispose(); tlog.Debug(tag, $"GestureDetectorAttach END (OK)"); Assert.Pass("GestureDetectorAttach"); } [Test] [Category("P1")] [Description("GestureDetector DetachAll")] [Property("SPEC", "Tizen.NUI.GestureDetector.DetachAll M")] [Property("SPEC_URL", "-")] [Property("CRITERIA", "MR")] [Property("AUTHOR", "[email protected]")] public void GestureDetectorDetachAll() { tlog.Debug(tag, $"GestureDetectorDetachAll START"); var testingTarget = new LongPressGestureDetector(); Assert.IsNotNull(testingTarget, "should be not null"); Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!"); using (View view = new View()) { testingTarget.Attach(view); testingTarget.DetachAll(); } testingTarget.Dispose(); tlog.Debug(tag, $"GestureDetectorDetachAll END (OK)"); Assert.Pass("GestureDetectorDetachAll"); } [Test] [Category("P1")] [Description("GestureDetector GetAttachedViewCount")] [Property("SPEC", "Tizen.NUI.GestureDetector.GetAttachedViewCount M")] [Property("SPEC_URL", "-")] [Property("CRITERIA", "MR")] [Property("AUTHOR", "[email protected]")] public void GestureDetectorGetAttachedViewCount() { tlog.Debug(tag, $"GestureDetectorGetAttachedViewCount START"); var testingTarget = new LongPressGestureDetector(); Assert.IsNotNull(testingTarget, "should be not null"); Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!"); using (View view = new View()) { testingTarget.Attach(view); tlog.Debug(tag, "AttachedViewCount : " + testingTarget.GetAttachedViewCount()); testingTarget.Detach(view); } testingTarget.Dispose(); tlog.Debug(tag, $"GestureDetectorGetAttachedViewCount END (OK)"); Assert.Pass("GestureDetectorGetAttachedViewCount"); } [Test] [Category("P1")] [Description("GestureDetector GetAttachedView")] [Property("SPEC", "Tizen.NUI.GestureDetector.GetAttachedView M")] [Property("SPEC_URL", "-")] [Property("CRITERIA", "MR")] [Property("AUTHOR", "[email protected]")] public void GestureDetectorGetAttachedView() { tlog.Debug(tag, $"GestureDetectorGetAttachedView START"); var testingTarget = new LongPressGestureDetector(); Assert.IsNotNull(testingTarget, "should be not null"); Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!"); using (View view = new View()) { testingTarget.Attach(view); testingTarget.GetAttachedView(0); testingTarget.Detach(view); } testingTarget.Dispose(); tlog.Debug(tag, $"GestureDetectorGetAttachedView END (OK)"); Assert.Pass("GestureDetectorGetAttachedView"); } [Test] [Category("P1")] [Description("GestureDetector DownCast")] [Property("SPEC", "Tizen.NUI.GestureDetector.DownCast M")] [Property("SPEC_URL", "-")] [Property("CRITERIA", "MR")] [Property("AUTHOR", "[email protected]")] public void GestureDetectorDownCast() { tlog.Debug(tag, $"GestureDetectorDownCast START"); using (GestureDetector detector = new GestureDetector()) { var testingTarget = GestureDetector.DownCast(detector); Assert.IsInstanceOf<GestureDetector>(testingTarget, "should be an instance of testing target class!"); testingTarget.Dispose(); } tlog.Debug(tag, $"GestureDetectorDownCast END (OK)"); Assert.Pass("GestureDetectorDownCast"); } } }
TheStack
e03696936b06278bb6137b7d97359191b1401bce
C#code:C#
{"size": 6769, "ext": "cs", "max_stars_repo_path": "src/FluentBuild/Publishing/NuGet/NuGetPublisherTests.cs", "max_stars_repo_name": "GotWoods/Fluent-Build", "max_stars_repo_stars_event_min_datetime": "2015-10-05T16:05:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-13T23:39:12.000Z", "max_issues_repo_path": "src/FluentBuild/Publishing/NuGet/NuGetPublisherTests.cs", "max_issues_repo_name": "GotWoods/Fluent-Build", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FluentBuild/Publishing/NuGet/NuGetPublisherTests.cs", "max_forks_repo_name": "GotWoods/Fluent-Build", "max_forks_repo_forks_event_min_datetime": "2015-04-02T02:43:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-24T09:44:11.000Z"}
{"max_stars_count": 8.0, "max_issues_count": null, "max_forks_count": 6.0, "avg_line_length": 44.8278145695, "max_line_length": 180, "alphanum_fraction": 0.6070320579}
using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using FluentBuild.Runners; using FluentBuild.Utilities; using NUnit.Framework; using Rhino.Mocks; using Directory = FluentFs.Core.Directory; namespace FluentBuild.Publishing.NuGet { [TestFixture] public class NuGetPublisherTests : TestBase { private NuGet.NuGetPublisher _subject; private NuGetOptionals _nuGetOptionals; private IFileSystemHelper _mockFileHelper; private IExecutable _mockExe; [SetUp] public void SetUp() { _mockFileHelper = MockRepository.GenerateStub<IFileSystemHelper>(); _mockExe = MockRepository.GenerateStub<IExecutable>(); _subject = new NuGetPublisher(_mockFileHelper, _mockExe); _nuGetOptionals = _subject.DeployFolder(new Directory("somedir")).ProjectId("FluentBuild").Version("1.2.3.4").Description("Project 1").Authors("author1").ApiKey("123"); } [Test] public void TestMandatoryFields() { Assert.That(_subject._deployFolder.ToString(), Is.EqualTo("somedir")); Assert.That(_subject._projectId, Is.EqualTo("FluentBuild")); Assert.That(_subject._version, Is.EqualTo("1.2.3.4")); Assert.That(_subject._description, Is.EqualTo("Project 1")); Assert.That(_subject._authors, Is.EqualTo("author1")); Assert.That(_subject._apiKey, Is.EqualTo("123")); } [Test] public void XML_TestDepenencyGroup() { var dependencyGroup = new DependencyGroup(); dependencyGroup.Add("SampleProject"); _nuGetOptionals.AddDependencyGroup(dependencyGroup); var schema = _subject.CreateSchema(); var xdoc = XDocument.Parse(schema); var ns = xdoc.Root.Name.Namespace; var depenencies = xdoc.Element(ns + "package").Element(ns + "metadata").Element(ns + "dependencies"); Assert.That(depenencies, Is.Not.Null); Assert.That(depenencies.Nodes().Count(), Is.EqualTo(1)); } [Test] public void XML_TestReferences() { _nuGetOptionals.AddReference("system.dll"); var schema = _subject.CreateSchema(); var xdoc = XDocument.Parse(schema); var ns = xdoc.Root.Name.Namespace; var depenencies = xdoc.Element(ns + "package").Element(ns + "metadata").Element(ns + "references"); Assert.That(depenencies, Is.Not.Null); Assert.That(depenencies.Nodes().Count(), Is.EqualTo(1)); } [Test] public void XML_TestAdditionalData() { _nuGetOptionals.AdditionalManifestData("<bears>are tough</bears>"); var schema = _subject.CreateSchema(); var xdoc = XDocument.Parse(schema); var ns = xdoc.Root.Name.Namespace; var depenencies = xdoc.Element(ns + "package").Element(ns + "metadata").Element(ns + "bears"); Assert.That(depenencies, Is.Not.Null); } [Test] public void XML_TestFrameworkAssembly() { _nuGetOptionals.AddFrameworkAssembly("system.core"); var schema = _subject.CreateSchema(); var xdoc = XDocument.Parse(schema); var ns = xdoc.Root.Name.Namespace; var depenencies = xdoc.Element(ns + "package").Element(ns + "metadata").Element(ns + "frameworkAssemblies"); Assert.That(depenencies, Is.Not.Null); Assert.That(depenencies.Nodes().Count(), Is.EqualTo(1)); } [Test, ExpectedException(typeof(FileNotFoundException))] public void InternalExecute_ShouldFailIfFileNotFound() { _mockFileHelper.Stub(x => x.Find("nuget.exe")).Return(null); _subject.InternalExecute(); } [Test] public void InternalExecute_ShouldRunNuGetAsExpected() { _mockFileHelper.Stub(x => x.Find("nuget.exe")).Return(@"c:\temp"); _mockFileHelper.Stub(x => x.CreateFile("")).IgnoreArguments().Return(new MemoryStream()); _mockExe.Stub(x => x.ExecutablePath(@"c:\temp")).Return(_mockExe).Repeat.Any(); _mockExe.Stub(x => x.UseArgumentBuilder(null)).IgnoreArguments().Return(_mockExe).Repeat.Any(); _mockExe.Stub(x => x.InWorkingDirectory(_subject._deployFolder)).Return(_mockExe).Repeat.Any(); _subject.InternalExecute(); //_mockExe.AssertWasCalled(x => x.WithArguments("Update -self")); //_mockExe.AssertWasCalled(x => x.WithArguments("setApiKey " + _subject._apiKey)); //_mockExe.AssertWasCalled(x => x.WithArguments("Pack " + _subject._projectId + ".nuspec")); //_mockExe.AssertWasCalled(x => x.WithArguments("Push " + _subject._projectId + "." + _subject._version + ".nupkg")); _mockExe.AssertWasCalled(x => x.Execute(), y=>y.Repeat.Times(4)); } [Test] public void XML_TestSimpleOptionalFields() { _nuGetOptionals.Copyright("copyright") .IconUrl("iconUrl") .Language("language") .LicenseUrl("licenseUrl") .Owners("owners") .ProjectUrl("projectUrl") .ReleaseNotes("release notes") .RequireLicenseAcceptance .Summary("summary") .Tags("tags") .Title("title"); var schema = _subject.CreateSchema(); var xdoc = XDocument.Parse(schema); var ns = xdoc.Root.Name.Namespace; var metadata = xdoc.Element(ns + "package").Element(ns + "metadata"); Assert.That(metadata.Element(ns + "copyright").Value, Is.EqualTo("copyright")); Assert.That(metadata.Element(ns + "iconUrl").Value, Is.EqualTo("iconUrl")); Assert.That(metadata.Element(ns + "language").Value, Is.EqualTo("language")); Assert.That(metadata.Element(ns + "licenseUrl").Value, Is.EqualTo("licenseUrl")); Assert.That(metadata.Element(ns + "owners").Value, Is.EqualTo("owners")); Assert.That(metadata.Element(ns + "projectUrl").Value, Is.EqualTo("projectUrl")); Assert.That(metadata.Element(ns + "releaseNotes").Value, Is.EqualTo("release notes")); Assert.That(metadata.Element(ns + "requireLicenseAcceptance").Value, Is.EqualTo("True")); Assert.That(metadata.Element(ns + "summary").Value, Is.EqualTo("summary")); Assert.That(metadata.Element(ns + "tags").Value, Is.EqualTo("tags")); Assert.That(metadata.Element(ns + "title").Value, Is.EqualTo("title")); } } }
TheStack
e038306781f5e6f57e3d459d4d015c6f183ce1b9
C#code:C#
{"size": 200, "ext": "cs", "max_stars_repo_path": "Asp net MVC/Exam MVC 2014 - Send/EasyPTC/EasyPTC.Contracts/IDeletableEntityRepository.cs", "max_stars_repo_name": "razsilev/TelerikAcademy_Homework", "max_stars_repo_stars_event_min_datetime": "2015-09-09T08:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T13:38:19.000Z", "max_issues_repo_path": "Asp net MVC/Exam MVC 2014 - Send/EasyPTC/EasyPTC.Contracts/IDeletableEntityRepository.cs", "max_issues_repo_name": "razsilev/TelerikAcademy_Homework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Asp net MVC/Exam MVC 2014 - Send/EasyPTC/EasyPTC.Contracts/IDeletableEntityRepository.cs", "max_forks_repo_name": "razsilev/TelerikAcademy_Homework", "max_forks_repo_forks_event_min_datetime": "2015-05-11T06:50:35.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-05T12:07:09.000Z"}
{"max_stars_count": 16.0, "max_issues_count": null, "max_forks_count": 3.0, "avg_line_length": 20.0, "max_line_length": 85, "alphanum_fraction": 0.68}
namespace EasyPTC.Data.Contracts { using System.Linq; public interface IDeletableEntityRepository<T> : IRepository<T> where T : IEntity { IQueryable<T> AllWithDeleted(); } }
TheStack
e03a1bfe3a41ce4de78e35f7c5f8afcf3a22d573
C#code:C#
{"size": 579, "ext": "cs", "max_stars_repo_path": "ConnectorRevit/ConnectorRevit/Revit/FamilyLoadOption.cs", "max_stars_repo_name": "pkratten/speckle-sharp", "max_stars_repo_stars_event_min_datetime": "2020-11-04T11:59:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:54:55.000Z", "max_issues_repo_path": "ConnectorRevit/ConnectorRevit/Revit/FamilyLoadOption.cs", "max_issues_repo_name": "pkratten/speckle-sharp", "max_issues_repo_issues_event_min_datetime": "2020-11-03T18:39:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:19:47.000Z", "max_forks_repo_path": "ConnectorRevit/ConnectorRevit/Revit/FamilyLoadOption.cs", "max_forks_repo_name": "pkratten/speckle-sharp", "max_forks_repo_forks_event_min_datetime": "2020-11-09T16:25:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T16:54:06.000Z"}
{"max_stars_count": 98.0, "max_issues_count": 612.0, "max_forks_count": 52.0, "avg_line_length": 23.16, "max_line_length": 134, "alphanum_fraction": 0.7340241796}
using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit.DB; namespace ConnectorRevit.Revit { class FamilyLoadOption : IFamilyLoadOptions { public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues) { overwriteParameterValues = true; return true; } public bool OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues) { source = FamilySource.Family; overwriteParameterValues = true; return true; } } }
TheStack
e03cc6bd23ce57252587f79b3f7174946d76f9ef
C#code:C#
{"size": 4614, "ext": "cs", "max_stars_repo_path": "Campaign/Gtmobj.cs", "max_stars_repo_name": "agustinsantos/FalconNet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Campaign/Gtmobj.cs", "max_issues_repo_name": "agustinsantos/FalconNet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Campaign/Gtmobj.cs", "max_forks_repo_name": "agustinsantos/FalconNet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.9571428571, "max_line_length": 142, "alphanum_fraction": 0.6413090594}
using System; using FalconNet.Common; using FalconNet.VU; using Objective=FalconNet.Campaign.ObjectiveClass; using Unit=FalconNet.Campaign.UnitClass; using FalconNet.FalcLib; namespace FalconNet.Campaign { // ==================================== // Primary and secondary objective data // ==================================== public class PrimaryObjectiveData { public VU_ID objective; // Id of the objective public short[] ground_priority = new short[(int)TeamDataEnum.NUM_TEAMS]; // It's calculated priority (per team) public short[] ground_assigned = new short[(int)TeamDataEnum.NUM_TEAMS]; // Combat factors assigned (per team) public short[] air_priority = new short[(int)TeamDataEnum.NUM_TEAMS]; // Air tasking manager's assessment of priority public short[] player_priority = new short[(int)TeamDataEnum.NUM_TEAMS]; // Player adjusted priorities (or ATM's if no modifications) public byte flags; } #if TODO typedef PrimaryObjectiveData* POData; #endif public class UnitScoreNode { public Unit unit; public int score; public int distance; public UnitScoreNode next; public UnitScoreNode() {throw new NotImplementedException();} public UnitScoreNode Insert(UnitScoreNode to_insert, int sort_by) {throw new NotImplementedException();} public UnitScoreNode Remove(UnitScoreNode to_remove) {throw new NotImplementedException();} public UnitScoreNode Remove(Unit u) {throw new NotImplementedException();} public UnitScoreNode Purge() {throw new NotImplementedException();} public UnitScoreNode Sort(int sort_by) {throw new NotImplementedException();} }; // TODO typedef UnitScoreNode USNode; public class GndObjDataType { public Objective obj; public int priority_score; public int unit_options; public UnitScoreNode unit_list; public GndObjDataType next; public GndObjDataType() {throw new NotImplementedException();} //TODO public ~GndObjDataType ( ); public GndObjDataType Insert(GndObjDataType to_insert, int sort_by) {throw new NotImplementedException();} public GndObjDataType Remove(GndObjDataType to_remove) {throw new NotImplementedException();} public GndObjDataType Remove(Objective o) {throw new NotImplementedException();} public GndObjDataType Purge() {throw new NotImplementedException();} public GndObjDataType Sort(int sort_by) {throw new NotImplementedException();} public void InsertUnit(Unit u, int s, int d) {throw new NotImplementedException();} public UnitScoreNode RemoveUnit(Unit u) {throw new NotImplementedException();} public void RemoveUnitFromAll(Unit u) {throw new NotImplementedException();} public void PurgeUnits() {throw new NotImplementedException();} // GndObjDataType FindWorstOption (Unit u); // int FindNewOptions (Unit u); } #if TODO typedef GndObjDataType GODNode; #endif public static class GtmobjStatic { // ==================================== // Flags // ==================================== public const int GTMOBJ_PLAYER_SET_PRIORITY = 0x01; // Player has modified priorities for this objective public const int GTMOBJ_SCRIPTED_PRIORITY = 0x02; // Priority set by script // ==================================== // GndObjDataType: // // Simple sorted list of objective data // with scores and unit assignment data // ==================================== public const int GODN_SORT_BY_PRIORITY = 1; public const int GODN_SORT_BY_OPTIONS = 2; public const int USN_SORT_BY_SCORE = 1; public const int USN_SORT_BY_DISTANCE = 2; // ========================================== // Global functions // ========================================== public static void CleanupObjList() {throw new NotImplementedException();} public static void DisposeObjList() {throw new NotImplementedException();} public static PrimaryObjectiveData GetPOData(Objective po) {throw new NotImplementedException();} public static void AddPODataEntry(Objective po) {throw new NotImplementedException();} public static void ResetObjectiveAssignmentScores() {throw new NotImplementedException();} public static int GetOptions(int score) {throw new NotImplementedException();} } }
TheStack
e03d3fd91171614c24370f8c88062572a3994fd8
C#code:C#
{"size": 4064, "ext": "cs", "max_stars_repo_path": "src/OpenTelemetry/Trace/ActivitySourceAdapter.cs", "max_stars_repo_name": "easel/opentelemetry-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OpenTelemetry/Trace/ActivitySourceAdapter.cs", "max_issues_repo_name": "easel/opentelemetry-dotnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OpenTelemetry/Trace/ActivitySourceAdapter.cs", "max_forks_repo_name": "easel/opentelemetry-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 36.2857142857, "max_line_length": 153, "alphanum_fraction": 0.6149114173}
// <copyright file="ActivitySourceAdapter.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System.Diagnostics; using OpenTelemetry.Resources; namespace OpenTelemetry.Trace { /// <summary> /// This class encapsulates the logic for performing ActivitySource actions /// on Activities that are created using default ActivitySource. /// All activities created without using ActivitySource will have a /// default ActivitySource assigned to them with their name as empty string. /// This class is to be used by instrumentation adapters which converts/augments /// activies created without ActivitySource, into something which closely /// matches the one created using ActivitySource. /// </summary> public class ActivitySourceAdapter { private readonly Sampler sampler; private readonly ActivityProcessor activityProcessor; private readonly Resource resource; internal ActivitySourceAdapter(Sampler sampler, ActivityProcessor activityProcessor, Resource resource) { this.sampler = sampler; this.activityProcessor = activityProcessor; this.resource = resource; } private ActivitySourceAdapter() { } /// <summary> /// Method that starts an <see cref="Activity"/>. /// </summary> /// <param name="activity"><see cref="Activity"/> to be started.</param> public void Start(Activity activity) { this.RunGetRequestedData(activity); if (activity.IsAllDataRequested) { activity.SetResource(this.resource); this.activityProcessor.OnStart(activity); } } /// <summary> /// Method that stops an <see cref="Activity"/>. /// </summary> /// <param name="activity"><see cref="Activity"/> to be stopped.</param> public void Stop(Activity activity) { if (activity.IsAllDataRequested) { this.activityProcessor.OnEnd(activity); } } private void RunGetRequestedData(Activity activity) { ActivityContext parentContext; if (string.IsNullOrEmpty(activity.ParentId)) { parentContext = default(ActivityContext); } else { if (activity.Parent != null) { parentContext = activity.Parent.Context; } else { parentContext = new ActivityContext(activity.TraceId, activity.ParentSpanId, activity.ActivityTraceFlags, activity.TraceStateString); // TODO: once IsRemote is exposed on ActivityContext set parentContext's IsRemote=true } } var samplingParameters = new SamplingParameters( parentContext, activity.TraceId, activity.DisplayName, activity.Kind, activity.TagObjects, activity.Links); var samplingDecision = this.sampler.ShouldSample(samplingParameters); activity.IsAllDataRequested = samplingDecision.IsSampled; if (samplingDecision.IsSampled) { activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded; } } } }
TheStack
e03d598827255a1c8201257a5bafe5dbf2ae2f86
C#code:C#
{"size": 263, "ext": "cs", "max_stars_repo_path": "src/TrimDB.Core/InMemory/MemoryIterator.cs", "max_stars_repo_name": "stevejgordon/TrimDB", "max_stars_repo_stars_event_min_datetime": "2020-04-29T18:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T19:10:20.000Z", "max_issues_repo_path": "src/TrimDB.Core/InMemory/MemoryIterator.cs", "max_issues_repo_name": "stevejgordon/TrimDB", "max_issues_repo_issues_event_min_datetime": "2020-05-02T04:50:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T07:38:10.000Z", "max_forks_repo_path": "src/TrimDB.Core/InMemory/MemoryIterator.cs", "max_forks_repo_name": "stevejgordon/TrimDB", "max_forks_repo_forks_event_min_datetime": "2020-05-02T08:41:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T16:50:39.000Z"}
{"max_stars_count": 53.0, "max_issues_count": 23.0, "max_forks_count": 10.0, "avg_line_length": 18.7857142857, "max_line_length": 41, "alphanum_fraction": 0.6463878327}
using System; using System.Collections.Generic; using System.Text; namespace TrimDB.Core.InMemory { public interface IMemoryItem { ReadOnlySpan<byte> Key { get; } ReadOnlySpan<byte> Value { get; } bool IsDeleted { get; } } }
TheStack
e044de7201fa30996bd4f7b032c34882c470516e
C#code:C#
{"size": 8103, "ext": "cs", "max_stars_repo_path": "HexaBike/Assets/CORE/Upgrades/Editor/UpgradesEditor.cs", "max_stars_repo_name": "sebad-git/unity-game-hexabike", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HexaBike/Assets/CORE/Upgrades/Editor/UpgradesEditor.cs", "max_issues_repo_name": "sebad-git/unity-game-hexabike", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HexaBike/Assets/CORE/Upgrades/Editor/UpgradesEditor.cs", "max_forks_repo_name": "sebad-git/unity-game-hexabike", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 42.203125, "max_line_length": 143, "alphanum_fraction": 0.7131926447}
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; [CustomEditor(typeof(PowerUps))] public class UpgradesEditor : Editor { private PowerUps upgradesFile; private Vector2 scrollPos; private static string subGroupStyle = "ObjectFieldThumb"; private static string titleStyle = "MeTransOffRight"; private static string rootGroupStyle = "GroupBox"; private static int achCounter; public void OnEnable(){ upgradesFile = (PowerUps)target; if (upgradesFile != null && upgradesFile.powerUps != null) { achCounter = upgradesFile.powerUps.Count; } } public override void OnInspectorGUI(){ scrollPos = EditorGUILayout.BeginScrollView(scrollPos); if (upgradesFile != null) { EditorGUILayout.BeginVertical(subGroupStyle); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(rootGroupStyle); GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("UPGRADES EDITOR",EditorStyles.boldLabel); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); if (upgradesFile.powerUps != null) { EditorGUILayout.BeginVertical(rootGroupStyle); EditorGUILayout.BeginHorizontal(subGroupStyle); GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("Upgrades"); GUILayout.FlexibleSpace(); if(StyledButton("Add Upgrade")){ Add(); } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); if (upgradesFile.powerUps.Count == 0) { EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label ("FILE EMPTY"); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); }else{ for(int a=0; a<upgradesFile.powerUps.Count;a++) { PowerUp pwp = upgradesFile.powerUps[a]; EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(subGroupStyle); pwp.active = EditorGUILayout.Foldout (pwp.active, pwp.powerUpName, EditorStyles.foldout); if (GUILayout.Button ("Remove")) { remove(a); } EditorGUILayout.EndHorizontal(); if (pwp.active) { EditorGUILayout.BeginHorizontal(subGroupStyle); pwp.powerUpName = EditorGUILayout.TextField ("Upgrade name:", pwp.powerUpName.Trim()); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginVertical(subGroupStyle); pwp.icon = (Sprite)EditorGUILayout.ObjectField(pwp.icon, typeof(Sprite), false); pwp.pwpID = EditorGUILayout.TextField("ID:", pwp.pwpID.Trim()); pwp.price = EditorGUILayout.IntField("Price:", pwp.price); pwp.category = (UpgradeCategory)EditorGUILayout.EnumPopup ("Category:", pwp.category); pwp.type = (UpgradeType)EditorGUILayout.EnumPopup ("Type:", pwp.type); pwp.prefab = (GameObject)EditorGUILayout.ObjectField(pwp.prefab, typeof(GameObject),false); pwp.value1 = EditorGUILayout.FloatField("Value:", pwp.value1); pwp.maxUpgrade = EditorGUILayout.FloatField("Max upgrade:", pwp.maxUpgrade); if (pwp.type == UpgradeType.ONE_USE) { pwp.useAchievment = EditorGUILayout.TextField("One use achievement:", pwp.useAchievment); } if (pwp.type == UpgradeType.UPGRADABLE) { pwp.upgradeAchievment = EditorGUILayout.TextField("Upgrade achievement:", pwp.upgradeAchievment); } EditorGUILayout.BeginVertical(rootGroupStyle); EditorGUILayout.BeginHorizontal(subGroupStyle); EditorGUILayout.Space(); pwp.showTitles = EditorGUILayout.Foldout (pwp.showTitles, "Titles", EditorStyles.foldout); if (GUILayout.Button ("Add")) { addTitle(a); } EditorGUILayout.EndHorizontal(); if (pwp.showTitles) { if(pwp.titles!=null){ for(int t=0; t<pwp.titles.Count; t++){ EditorGUILayout.BeginHorizontal(subGroupStyle); UpgradeTranslation trans=pwp.titles[t]; trans.text = EditorGUILayout.TextField(trans.text.Trim()); trans.language = (UpgradeLanguages)EditorGUILayout.EnumPopup(trans.language); if (GUILayout.Button ("Remove")) { removeTitle(a,t); } EditorGUILayout.EndHorizontal(); } } } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(rootGroupStyle); EditorGUILayout.BeginHorizontal(subGroupStyle); EditorGUILayout.Space(); pwp.showDescriptions = EditorGUILayout.Foldout(pwp.showDescriptions, "Descriptions", EditorStyles.foldout); if (GUILayout.Button ("Add")) { addDescription(a); } EditorGUILayout.EndHorizontal(); if (pwp.showDescriptions) { if(pwp.descriptions!=null){ for(int d=0; d<pwp.descriptions.Count; d++){ EditorGUILayout.BeginHorizontal(subGroupStyle); UpgradeTranslation trans=pwp.descriptions[d]; trans.text = EditorGUILayout.TextField(trans.text.Trim()); trans.language = (UpgradeLanguages)EditorGUILayout.EnumPopup(trans.language); if (GUILayout.Button ("Remove")) { removeDescription(a,d); } EditorGUILayout.EndHorizontal(); } } } EditorGUILayout.EndVertical(); EditorGUILayout.BeginHorizontal(titleStyle); if (GUILayout.Button ("Duplicate")) { duplicate(a); } if (GUILayout.Button ("Move Up")) { moveUp(a); } if (GUILayout.Button ("Move Down")) { moveDown(a); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } } GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace(); EditorGUILayout.EndVertical(); } }else{ upgradesFile.powerUps = new List<PowerUp>(); } GUILayout.FlexibleSpace(); EditorGUILayout.EndVertical(); } else { GUILayout.Label("No file selected."); } EditorGUILayout.EndScrollView(); EditorUtility.SetDirty(upgradesFile); } public void duplicate(int index){ PowerUp pwp = upgradesFile.powerUps[index]; PowerUp npwp = new PowerUp(); npwp.pwpID = "UPG"+(achCounter+1); npwp.powerUpName = pwp.powerUpName; npwp.titles = pwp.titles; npwp.descriptions = pwp.descriptions; npwp.price = pwp.price; npwp.category = pwp.category; npwp.type = pwp.type; npwp.prefab = pwp.prefab; npwp.value1 = pwp.value1; npwp.maxUpgrade = pwp.maxUpgrade; npwp.useAchievment = pwp.useAchievment; npwp.upgradeAchievment = pwp.useAchievment; npwp.icon = pwp.icon; upgradesFile.powerUps.Add(npwp); achCounter=upgradesFile.powerUps.Count; } public void remove(int index){ upgradesFile.powerUps.RemoveAt(index); achCounter=upgradesFile.powerUps.Count; } public void Add(){ achCounter=upgradesFile.powerUps.Count; PowerUp pwp = new PowerUp(); pwp.powerUpName = "NEW UPGRADE"; pwp.pwpID = "UPG"+(achCounter+1); pwp.descriptions=new List<UpgradeTranslation>(); pwp.titles=new List<UpgradeTranslation>(); pwp.category = UpgradeCategory.CATEGORY_1; pwp.type= UpgradeType.UPGRADABLE; pwp.price = 0; pwp.value1 = 0; pwp.maxUpgrade = 5; upgradesFile.powerUps.Add(pwp); achCounter=upgradesFile.powerUps.Count; } public void moveUp(int index){ if (index > 0) { PowerUp pwp = upgradesFile.powerUps[index]; upgradesFile.powerUps.RemoveAt(index); upgradesFile.powerUps.Insert( (index-1), pwp); } achCounter=upgradesFile.powerUps.Count; } public void moveDown(int index){ if (index < upgradesFile.powerUps.Count) { PowerUp pwp = upgradesFile.powerUps[index]; upgradesFile.powerUps.RemoveAt(index); upgradesFile.powerUps.Insert ((index + 1), pwp); } } public void addTitle(int index){ upgradesFile.powerUps[index].titles.Add(new UpgradeTranslation()); } public void removeTitle(int achIndex,int transIndex){ upgradesFile.powerUps[achIndex].titles.RemoveAt(transIndex); } public void addDescription(int index){ upgradesFile.powerUps[index].descriptions.Add(new UpgradeTranslation()); } public void removeDescription(int achIndex,int transIndex){ upgradesFile.powerUps[achIndex].descriptions.RemoveAt(transIndex); } public bool StyledButton (string label) { EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); bool clickResult = GUILayout.Button(label, "CN CountBadge"); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); return clickResult; } }
TheStack
e045af36c1f5d157a69b047e9a6edd17e06a7eb5
C#code:C#
{"size": 1683, "ext": "cs", "max_stars_repo_path": "SilverNote.DOM/CSS/Implementation/CSSSimpleSelectorSequence.cs", "max_stars_repo_name": "achapweske/silvernote", "max_stars_repo_stars_event_min_datetime": "2019-06-11T17:44:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-11T17:44:07.000Z", "max_issues_repo_path": "SilverNote.DOM/CSS/Implementation/CSSSimpleSelectorSequence.cs", "max_issues_repo_name": "achapweske/silvernote", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SilverNote.DOM/CSS/Implementation/CSSSimpleSelectorSequence.cs", "max_forks_repo_name": "achapweske/silvernote", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.0375, "max_line_length": 84, "alphanum_fraction": 0.5234699941}
/* * Copyright (c) Adam Chapweske * * Licensed under MIT (https://github.com/achapweske/silvernote/blob/master/LICENSE) */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace DOM.CSS.Internal { /// <summary> /// An ordered collection of simple selectors. /// /// The first item must be a universal selector or type selector. /// /// http://www.w3.org/TR/css3-selectors/#selector-syntax /// </summary> public class CSSSimpleSelectorSequence : List<CSSSimpleSelector> { #region Constructors public CSSSimpleSelectorSequence() { } #endregion #region Properties /// <summary> /// Get this sequence's specificity. /// /// http://www.w3.org/TR/css3-selectors/#specificity /// </summary> public int Specificity { get { return this.Sum((item) => item.Specificity); } } #endregion #region Methods /// <summary> /// Determine if node is a match for this sequence /// </summary> public bool Match(Node node) { for (int i = 0; i < Count; i++) { if (!this[i].Match(node)) { return false; } } return true; } #endregion #region Object public override string ToString() { return CSSFormatter.FormatSimpleSelectorSequence(this); } #endregion } }
TheStack
e045f04d2a6a2444a44a0de6c8024f011297a3be
C#code:C#
{"size": 315, "ext": "cs", "max_stars_repo_path": "ExportToExcelConsoleApp/IRawData.cs", "max_stars_repo_name": "sumit002/ASP.NETCore.ExcexExport", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ExportToExcelConsoleApp/IRawData.cs", "max_issues_repo_name": "sumit002/ASP.NETCore.ExcexExport", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ExportToExcelConsoleApp/IRawData.cs", "max_forks_repo_name": "sumit002/ASP.NETCore.ExcexExport", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.6875, "max_line_length": 45, "alphanum_fraction": 0.5682539683}
using System.Data; namespace ExportToExcelConsoleApp { internal interface IRawData { /// <summary> /// Get DataSet Raw Data /// </summary> /// <returns>Sample DataSet</returns> DataSet GetDataSet(); string GetJson(); object GetDataObject(); } }
TheStack
e0466f68f0a759f1e4298ddff2786cf25780d1f3
C#code:C#
{"size": 1611, "ext": "cs", "max_stars_repo_path": "src/Controls/tests/Xaml.UnitTests/Issues/Gh11334.xaml.cs", "max_stars_repo_name": "abod1944/maui", "max_stars_repo_stars_event_min_datetime": "2022-03-03T14:55:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T14:55:31.000Z", "max_issues_repo_path": "src/Controls/tests/Xaml.UnitTests/Issues/Gh11334.xaml.cs", "max_issues_repo_name": "abod1944/maui", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Controls/tests/Xaml.UnitTests/Issues/Gh11334.xaml.cs", "max_forks_repo_name": "abod1944/maui", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.4090909091, "max_line_length": 77, "alphanum_fraction": 0.7225325885}
using System; using System.Collections.Generic; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Core.UnitTests; using Microsoft.Maui.Controls.Xaml.Diagnostics; using NUnit.Framework; namespace Microsoft.Maui.Controls.Xaml.UnitTests { public partial class Gh11334 : ContentPage { public Gh11334() { InitializeComponent(); } public Gh11334(bool useCompiledXaml) { //this stub will be replaced at compile time } void Remove(object sender, EventArgs e) => stack.Children.Remove(label); void Add(object sender, EventArgs e) { int index = stack.Children.IndexOf(label); Label newLabel = new Label { Text = "New Inserted Label" }; stack.Children.Insert(index + 1, newLabel); } [TestFixture] class Tests { bool _debuggerinitialstate; [SetUp] public void Setup() { _debuggerinitialstate = DebuggerHelper._mockDebuggerIsAttached; DebuggerHelper._mockDebuggerIsAttached = true; } [TearDown] public void TearDown() { DebuggerHelper._mockDebuggerIsAttached = _debuggerinitialstate; VisualDiagnostics.VisualTreeChanged -= OnVTChanged; } void OnVTChanged(object sender, VisualTreeChangeEventArgs e) { Assert.That(e.ChangeType, Is.EqualTo(VisualTreeChangeType.Remove)); Assert.That(e.ChildIndex, Is.EqualTo(0)); Assert.Pass(); } [Test] public void ChildIndexOnRemove([Values(false, true)] bool useCompiledXaml) { var layout = new Gh11334(useCompiledXaml); VisualDiagnostics.VisualTreeChanged += OnVTChanged; layout.Remove(null, EventArgs.Empty); Assert.Fail(); } } } }
TheStack
e046dea39d73a571d2db240adbb2a12784cc0537
C#code:C#
{"size": 1021, "ext": "cs", "max_stars_repo_path": "tests/Core/XLabs.Core.NUnit.Shared/HelpersTests/GroupedListSourceTests.cs", "max_stars_repo_name": "eComanda/Xamarin-Forms-Labs", "max_stars_repo_stars_event_min_datetime": "2015-01-04T18:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:12:13.000Z", "max_issues_repo_path": "tests/Core/XLabs.Core.NUnit.Shared/HelpersTests/GroupedListSourceTests.cs", "max_issues_repo_name": "eComanda/Xamarin-Forms-Labs", "max_issues_repo_issues_event_min_datetime": "2015-01-01T01:04:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-26T10:03:27.000Z", "max_forks_repo_path": "tests/Core/XLabs.Core.NUnit.Shared/HelpersTests/GroupedListSourceTests.cs", "max_forks_repo_name": "eComanda/Xamarin-Forms-Labs", "max_forks_repo_forks_event_min_datetime": "2015-01-01T16:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T05:14:24.000Z"}
{"max_stars_count": 1407.0, "max_issues_count": 755.0, "max_forks_count": 1151.0, "avg_line_length": 29.1714285714, "max_line_length": 114, "alphanum_fraction": 0.7326150833}
using System; using NUnit.Framework; using XLabs.Helpers; using System.Collections.Generic; namespace Xlabs.Core.HelpersTests { /// <summary> /// Grouped list source is just some extended type aware constructors for Observable Collection. /// </summary> [TestFixture] public class GroupedListSourceTests { class dataClass{} [Test] public void GroupedListSourceEmptyConstructorTests () { GroupedListSource<string,dataClass> list = new GroupedListSource<string,dataClass>(); var myDataClass = new dataClass (); list.Add (new ListGroup<string, dataClass> (){ myDataClass, new dataClass () }); Assert.Contains (myDataClass, list[0]); } [Test] public void GroupedListSourceConstructorTests () { var myDataClass = new dataClass (); GroupedListSource<string,dataClass> list = new GroupedListSource<string,dataClass>( new List<ListGroup<string, dataClass>>{new ListGroup<string, dataClass> (){ myDataClass, new dataClass () }}); Assert.Contains (myDataClass, list[0]); } } }
TheStack
e048a150d38af1a65a52ad7025037584fe9d8a27
C#code:C#
{"size": 769, "ext": "cs", "max_stars_repo_path": "Rafy/Rafy/Domain/ORM/Query/IColumnNode.cs", "max_stars_repo_name": "zgynhqf/trunk", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rafy/Rafy/Domain/ORM/Query/IColumnNode.cs", "max_issues_repo_name": "zgynhqf/trunk", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rafy/Rafy/Domain/ORM/Query/IColumnNode.cs", "max_forks_repo_name": "zgynhqf/trunk", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.7179487179, "max_line_length": 66, "alphanum_fraction": 0.4980494148}
/******************************************************* * * 作者:胡庆访 * 创建日期:20131212 * 说明:此文件只包含一个类,具体内容见类型注释。 * 运行环境:.NET 4.0 * 版本号:1.0.0 * * 历史记录: * 创建文件 胡庆访 20131212 10:48 * *******************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Rafy.Domain.ORM.SqlTree; using Rafy.ManagedProperty; namespace Rafy.Domain.ORM.Query { /// <summary> /// 一个列节点 /// </summary> public interface IColumnNode : IQueryNode, ISqlSelectionColumn { /// <summary> /// 本列属于指定的数据源 /// </summary> IHasName Owner { get; } /// <summary> /// 本属性对应一个实体的托管属性 /// </summary> IProperty Property { get; } } }
TheStack
e048d580cb66deccd4a9bb10b0f7bd3eb0c51653
C#code:C#
{"size": 2869, "ext": "cs", "max_stars_repo_path": "aliyun-net-sdk-schedulerx2/Schedulerx2/Transform/V20190430/GetWorkerListResponseUnmarshaller.cs", "max_stars_repo_name": "pengweiqhca/aliyun-openapi-net-sdk", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aliyun-net-sdk-schedulerx2/Schedulerx2/Transform/V20190430/GetWorkerListResponseUnmarshaller.cs", "max_issues_repo_name": "pengweiqhca/aliyun-openapi-net-sdk", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aliyun-net-sdk-schedulerx2/Schedulerx2/Transform/V20190430/GetWorkerListResponseUnmarshaller.cs", "max_forks_repo_name": "pengweiqhca/aliyun-openapi-net-sdk", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 47.8166666667, "max_line_length": 173, "alphanum_fraction": 0.761589404}
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.schedulerx2.Model.V20190430; namespace Aliyun.Acs.schedulerx2.Transform.V20190430 { public class GetWorkerListResponseUnmarshaller { public static GetWorkerListResponse Unmarshall(UnmarshallerContext _ctx) { GetWorkerListResponse getWorkerListResponse = new GetWorkerListResponse(); getWorkerListResponse.HttpResponse = _ctx.HttpResponse; getWorkerListResponse.RequestId = _ctx.StringValue("GetWorkerList.RequestId"); getWorkerListResponse.Code = _ctx.IntegerValue("GetWorkerList.Code"); getWorkerListResponse.Message = _ctx.StringValue("GetWorkerList.Message"); getWorkerListResponse.Success = _ctx.BooleanValue("GetWorkerList.Success"); GetWorkerListResponse.GetWorkerList_Data data = new GetWorkerListResponse.GetWorkerList_Data(); List<GetWorkerListResponse.GetWorkerList_Data.GetWorkerList_WorkerInfo> data_workerInfos = new List<GetWorkerListResponse.GetWorkerList_Data.GetWorkerList_WorkerInfo>(); for (int i = 0; i < _ctx.Length("GetWorkerList.Data.WorkerInfos.Length"); i++) { GetWorkerListResponse.GetWorkerList_Data.GetWorkerList_WorkerInfo workerInfo = new GetWorkerListResponse.GetWorkerList_Data.GetWorkerList_WorkerInfo(); workerInfo.Ip = _ctx.StringValue("GetWorkerList.Data.WorkerInfos["+ i +"].Ip"); workerInfo.Port = _ctx.IntegerValue("GetWorkerList.Data.WorkerInfos["+ i +"].Port"); workerInfo.WorkerAddress = _ctx.StringValue("GetWorkerList.Data.WorkerInfos["+ i +"].WorkerAddress"); workerInfo.Label = _ctx.StringValue("GetWorkerList.Data.WorkerInfos["+ i +"].Label"); workerInfo.Version = _ctx.StringValue("GetWorkerList.Data.WorkerInfos["+ i +"].Version"); workerInfo.Starter = _ctx.StringValue("GetWorkerList.Data.WorkerInfos["+ i +"].Starter"); data_workerInfos.Add(workerInfo); } data.WorkerInfos = data_workerInfos; getWorkerListResponse.Data = data; return getWorkerListResponse; } } }
TheStack
e049beaeba745b8b3464b5d85e59786a352d7c08
C#code:C#
{"size": 516, "ext": "cs", "max_stars_repo_path": "OE-NIK-ImPro/UI/UI.Desktop/MainWindow.xaml.cs", "max_stars_repo_name": "danijanos/OE-NIK-ImPro", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OE-NIK-ImPro/UI/UI.Desktop/MainWindow.xaml.cs", "max_issues_repo_name": "danijanos/OE-NIK-ImPro", "max_issues_repo_issues_event_min_datetime": "2017-12-13T23:13:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-14T06:40:16.000Z", "max_forks_repo_path": "OE-NIK-ImPro/UI/UI.Desktop/MainWindow.xaml.cs", "max_forks_repo_name": "danijanos/OE-NIK-ImPro", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 22.4347826087, "max_line_length": 69, "alphanum_fraction": 0.5523255814}
using System.Windows; using OE.NIK.ImPro.Logic.UI; namespace OE.NIK.ImPro.UI.Desktop { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Closed(object sender, System.EventArgs e) { // Application.Current.Shutdown(); ViewModelLocator.Cleanup(); } } }
TheStack
e04aaa2ba43fd8f124f1b09bde8d38ccea2b149f
C#code:C#
{"size": 2529, "ext": "cs", "max_stars_repo_path": "Jint/Expressions/JsonExpression.cs", "max_stars_repo_name": "cosh/Jint", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Jint/Expressions/JsonExpression.cs", "max_issues_repo_name": "cosh/Jint", "max_issues_repo_issues_event_min_datetime": "2015-03-16T07:27:26.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-17T02:10:02.000Z", "max_forks_repo_path": "Jint/Expressions/JsonExpression.cs", "max_forks_repo_name": "cosh/Jint", "max_forks_repo_forks_event_min_datetime": "2015-03-13T00:40:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-11T08:47:03.000Z"}
{"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": 5.0, "avg_line_length": 42.15, "max_line_length": 117, "alphanum_fraction": 0.5500197707}
using System; using System.Collections.Generic; using System.Text; namespace Jint.Expressions { [Serializable] public class JsonExpression : Expression { public JsonExpression() { Values = new Dictionary<string, Expression>(); } public Dictionary<string, Expression> Values { get; set; } [System.Diagnostics.DebuggerStepThrough] public override void Accept(IStatementVisitor visitor) { visitor.Visit(this); } internal void Push(PropertyDeclarationExpression propertyExpression) { if (propertyExpression.Name == null) { propertyExpression.Name = propertyExpression.Mode.ToString().ToLower(); propertyExpression.Mode = PropertyExpressionType.Data; } if (Values.ContainsKey(propertyExpression.Name)) { PropertyDeclarationExpression exp = Values[propertyExpression.Name] as PropertyDeclarationExpression; if (exp == null) throw new JintException("A property cannot be both an accessor and data"); switch (propertyExpression.Mode) { case PropertyExpressionType.Data: if (propertyExpression.Mode == PropertyExpressionType.Data) Values[propertyExpression.Name] = propertyExpression.Expression; else throw new JintException("A property cannot be both an accessor and data"); break; case PropertyExpressionType.Get: exp.SetGet(propertyExpression); break; case PropertyExpressionType.Set: exp.SetSet(propertyExpression); break; } } else { Values.Add(propertyExpression.Name, propertyExpression); switch (propertyExpression.Mode) { case PropertyExpressionType.Data: Values[propertyExpression.Name] = propertyExpression; break; case PropertyExpressionType.Get: propertyExpression.SetGet(propertyExpression); break; case PropertyExpressionType.Set: propertyExpression.SetSet(propertyExpression); break; } } } } }
TheStack
e04b71c7ef5c46954f6899eac81484ada2b19012
C#code:C#
{"size": 5535, "ext": "cs", "max_stars_repo_path": "v2/Arduino Servo Cont. v2/AppSettings.Designer.cs", "max_stars_repo_name": "souris-dev/Arduino-servo-controller", "max_stars_repo_stars_event_min_datetime": "2017-08-28T23:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-30T00:51:18.000Z", "max_issues_repo_path": "v2/Arduino Servo Cont. v2/AppSettings.Designer.cs", "max_issues_repo_name": "souris-dev/Arduino-servo-controller", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "v2/Arduino Servo Cont. v2/AppSettings.Designer.cs", "max_forks_repo_name": "souris-dev/Arduino-servo-controller", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.8113207547, "max_line_length": 155, "alphanum_fraction": 0.5279132791}
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17929 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Arduino_Servo_Cont.v2 { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class AppSettings : global::System.Configuration.ApplicationSettingsBase { private static AppSettings defaultInstance = ((AppSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new AppSettings()))); public static AppSettings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S1 { get { return ((string)(this["S1"])); } set { this["S1"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S2 { get { return ((string)(this["S2"])); } set { this["S2"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S3 { get { return ((string)(this["S3"])); } set { this["S3"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S4 { get { return ((string)(this["S4"])); } set { this["S4"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S5 { get { return ((string)(this["S5"])); } set { this["S5"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S6 { get { return ((string)(this["S6"])); } set { this["S6"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S7 { get { return ((string)(this["S7"])); } set { this["S7"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S8 { get { return ((string)(this["S8"])); } set { this["S8"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S9 { get { return ((string)(this["S9"])); } set { this["S9"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("000")] public string S10 { get { return ((string)(this["S10"])); } set { this["S10"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("COM14")] public string PORT { get { return ((string)(this["PORT"])); } set { this["PORT"] = value; } } } }
TheStack
e0505d5a418609030a4730bcfee6a166de18afd6
C#code:C#
{"size": 993, "ext": "cs", "max_stars_repo_path": "OneOf.PerfTests/Program.cs", "max_stars_repo_name": "DiscU/DiscU", "max_stars_repo_stars_event_min_datetime": "2018-01-24T22:33:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T14:41:55.000Z", "max_issues_repo_path": "OneOf.PerfTests/Program.cs", "max_issues_repo_name": "DiscU/DiscU", "max_issues_repo_issues_event_min_datetime": "2018-01-25T00:36:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-17T12:30:01.000Z", "max_forks_repo_path": "OneOf.PerfTests/Program.cs", "max_forks_repo_name": "DiscU/DiscU", "max_forks_repo_forks_event_min_datetime": "2018-04-30T02:53:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-04T22:35:48.000Z"}
{"max_stars_count": 30.0, "max_issues_count": 3.0, "max_forks_count": 2.0, "avg_line_length": 24.825, "max_line_length": 83, "alphanum_fraction": 0.5911379658}
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace OneOf.PerfTests { extern alias DiscU; /// <summary> /// Performance tests. Assumes OneOf is working correctly, per the Unit Tests. /// </summary> class Program { static void Main(string[] args) { #if DEBUG Console.WriteLine("Debug build, tests will run much slower."); Console.WriteLine(""); #endif Console.WriteLine("Running DiscU Tests"); DiscUPerfTests.TestCtor(); Console.WriteLine("Running OneOf Tests"); OneOfPerfTests.TestCtor(); Console.WriteLine("Running DiscU Tests"); DiscUPerfTests.TestMatch(); Console.WriteLine("Running OneOf Tests"); OneOfPerfTests.TestMatch(); Console.WriteLine(""); Console.WriteLine("Press any key to end."); Console.ReadKey(); } } }
TheStack
e05181e9f4a59cd2539c703a505bf4ea3a04f67c
C#code:C#
{"size": 1477, "ext": "cs", "max_stars_repo_path": "src/coolc/4CodeGenerator/AST(Handed)/WhileNode.cs", "max_stars_repo_name": "matcom-compilers-2019/cool-compiler-david-rafael", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/coolc/4CodeGenerator/AST(Handed)/WhileNode.cs", "max_issues_repo_name": "matcom-compilers-2019/cool-compiler-david-rafael", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/coolc/4CodeGenerator/AST(Handed)/WhileNode.cs", "max_forks_repo_name": "matcom-compilers-2019/cool-compiler-david-rafael", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.4255319149, "max_line_length": 147, "alphanum_fraction": 0.5971563981}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member #pragma warning disable CS3021 // Type or member does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute namespace CodeGenerator { internal class WhileNode : Node { private CoolParser.WhileExpContext context; private Node s; public WhileNode(CoolParser.WhileExpContext context, Node s) : base(s.Childs) { this.context = context; this.s = s; this.Cond = s.Childs[0]; this.Body = s.Childs[1]; } public Node Cond { get; private set; } public Node Body { get; private set; } public override string GenerateCode() { MIPS.whileCount++; string code = ""; string whileName = "while" + MIPS.whileCount.ToString(); string whileEnd = "whileEnd" + MIPS.whileCount.ToString(); code += whileName + ":\n"; code += Cond.GenerateCode(); string condEval = MIPS.LastReg(); code += MIPS.Emit(MIPS.Opcodes.bne, condEval, "1", whileEnd); code += Body.GenerateCode(); code += MIPS.Emit(MIPS.Opcodes.j, whileName); code += whileEnd + ":\n"; return code; } } }
TheStack
e05288bed60a3528fa360e4a069c02fb37e802b8
C#code:C#
{"size": 2515, "ext": "cs", "max_stars_repo_path": "src/Ng/Json/RegistrationBaseUrlRewritingJsonReader.cs", "max_stars_repo_name": "zhhyu/NuGet.Services.Metadata", "max_stars_repo_stars_event_min_datetime": "2019-01-05T03:17:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-05T03:17:44.000Z", "max_issues_repo_path": "src/Ng/Json/RegistrationBaseUrlRewritingJsonReader.cs", "max_issues_repo_name": "DalavanCloud/NuGet.Services.Metadata", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Ng/Json/RegistrationBaseUrlRewritingJsonReader.cs", "max_forks_repo_name": "DalavanCloud/NuGet.Services.Metadata", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.6623376623, "max_line_length": 129, "alphanum_fraction": 0.5566600398}
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace Ng.Json { public class RegistrationBaseUrlRewritingJsonReader : InterceptingJsonReader { private readonly List<KeyValuePair<string, string>> _replacements; private static readonly string[] RegistrationPathsToIntercept = new[] { // Replace in index.json + {version}.json "@id", // Replace in index.json: "registration", // Replace in {version}.json: "items[*].@id", // Replace in {version}.json: "items[*].parent", // Replace in {version}.json: "items[*].items[*].@id", // Replace in {version}.json: "items[*].items[*].registration", // Replace in {version}.json: "items[*].items[*].catalogEntry.dependencyGroups[*].dependencies[*].registration", // Replace in page/*/{version}.json: "parent", // Replace in page/*/{version}.json: "items[*].@id", // Replace in page/*/{version}.json: "items[*].registration", // Replace in page/*/{version}.json: "items[*].catalogEntry.dependencyGroups[*].dependencies[*].registration" }; public RegistrationBaseUrlRewritingJsonReader(JTokenReader innerReader, List<KeyValuePair<string, string>> replacements) : base(innerReader, RegistrationPathsToIntercept) { _replacements = replacements; } protected override bool OnReadInterceptedPropertyName() { var tokenReader = InnerReader as JTokenReader; var currentProperty = tokenReader?.CurrentToken as JProperty; if (currentProperty != null) { var propertyValue = (string)currentProperty.Value; // Run replacements foreach (var replacement in _replacements) { propertyValue = propertyValue.Replace(replacement.Key, replacement.Value); } // Set new property value currentProperty.Value.Replace(propertyValue); } return true; } } }
TheStack
e052913c04a4efe1c9a123141fda3e3c24964d9d
C#code:C#
{"size": 708, "ext": "cs", "max_stars_repo_path": "C# DB Fundamentals/DB Advanced - EF Core/Prep1/11. DB-Advanced-EF-Core-Exam-Preparation-1-Instagraph-Skeleton/Instagraph.Data/ModelConfigurations/UserConfiguration.cs", "max_stars_repo_name": "jackofdiamond5/Software-University", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C# DB Fundamentals/DB Advanced - EF Core/Prep1/11. DB-Advanced-EF-Core-Exam-Preparation-1-Instagraph-Skeleton/Instagraph.Data/ModelConfigurations/UserConfiguration.cs", "max_issues_repo_name": "jackofdiamond5/Software-University", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C# DB Fundamentals/DB Advanced - EF Core/Prep1/11. DB-Advanced-EF-Core-Exam-Preparation-1-Instagraph-Skeleton/Instagraph.Data/ModelConfigurations/UserConfiguration.cs", "max_forks_repo_name": "jackofdiamond5/Software-University", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.32, "max_line_length": 67, "alphanum_fraction": 0.5988700565}
using Instagraph.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Instagraph.Data.ModelConfigurations { public class UserConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.HasKey(e => e.Id); builder.Property(e => e.Username) .IsRequired() .HasMaxLength(30); builder.HasIndex(e => e.Username) .IsUnique(); builder.HasOne(e => e.ProfilePicture) .WithMany(pp => pp.Users) .HasForeignKey(e => e.ProfilePictureId); } } }
TheStack
e0543f7df4c61b81bbd9782bb2e69282c16a80d8
C#code:C#
{"size": 986, "ext": "cs", "max_stars_repo_path": "src/Booma.Instance.NetworkObject.Objects/Objects/NetworkDoor.cs", "max_stars_repo_name": "BoomaNation/Booma.Instance", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Booma.Instance.NetworkObject.Objects/Objects/NetworkDoor.cs", "max_issues_repo_name": "BoomaNation/Booma.Instance", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Booma.Instance.NetworkObject.Objects/Objects/NetworkDoor.cs", "max_forks_repo_name": "BoomaNation/Booma.Instance", "max_forks_repo_forks_event_min_datetime": "2020-03-14T00:46:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-14T00:46:04.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 21.9111111111, "max_line_length": 81, "alphanum_fraction": 0.6855983773}
using GladBehaviour.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Booma.Entity.Identity; using SceneJect.Common; using UnityEngine; using UnityEngine.Events; namespace Booma.Instance.NetworkObject { /// <summary> /// Base Type for any Door networked <see cref="GameObject"/>. /// </summary> [Injectee] public abstract class NetworkDoor : NetworkGameObject<NetworkDoor.DoorState> { [SerializeField] [Tooltip("Event subscription for when the" + nameof(NetworkDoor) + "unlocks.")] private UnityEvent onDoorUnlocked; /// <summary> /// Event subscription list for a Door Opening Event. /// </summary> protected UnityEvent OnDoorUnlocked => onDoorUnlocked; /// <summary> /// Enumeration of all states. /// </summary> public enum DoorState : byte { /// <summary> /// Unlocked state. /// </summary> Unlocked = 0, /// <summary> /// Locked state. /// </summary> Locked = 1, } } }
TheStack
e0552f85322908d1cd581e83a752482d3afcf76a
C#code:C#
{"size": 679, "ext": "cs", "max_stars_repo_path": "src/SoftwarePioniere/Messaging/ResponseBase.cs", "max_stars_repo_name": "JTOne123/SoftwarePioniere.Fx", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SoftwarePioniere/Messaging/ResponseBase.cs", "max_issues_repo_name": "JTOne123/SoftwarePioniere.Fx", "max_issues_repo_issues_event_min_datetime": "2018-11-01T16:00:29.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T16:00:29.000Z", "max_forks_repo_path": "src/SoftwarePioniere/Messaging/ResponseBase.cs", "max_forks_repo_name": "JTOne123/SoftwarePioniere.Fx", "max_forks_repo_forks_event_min_datetime": "2020-06-25T10:40:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T10:40:14.000Z"}
{"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": 1.0, "avg_line_length": 24.25, "max_line_length": 68, "alphanum_fraction": 0.6082474227}
using System.Collections.Generic; using J = Newtonsoft.Json.JsonPropertyAttribute; using J1 = System.Text.Json.Serialization.JsonPropertyNameAttribute; namespace SoftwarePioniere.Messaging { public abstract class ResponseBase { protected ResponseBase() { Properties = new Dictionary<string, string>(); } [J("is_error")] [J1("is_error")] public bool IsError => !string.IsNullOrEmpty(Error); [J( "error")] [J1( "error")] public string Error { get; set; } [J("properties")] [J1("properties")] public Dictionary<string, string> Properties { get; set; } } }
TheStack
e0579883c3b5ee47665cc530c82e8373099d0138
C#code:C#
{"size": 1982, "ext": "cs", "max_stars_repo_path": "OOP/ExamPreparation/1.SoftwareAcademy/SoftwareAcademy-MySolution/Course.cs", "max_stars_repo_name": "iliantrifonov/TelerikAcademy", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OOP/ExamPreparation/1.SoftwareAcademy/SoftwareAcademy-MySolution/Course.cs", "max_issues_repo_name": "iliantrifonov/TelerikAcademy", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OOP/ExamPreparation/1.SoftwareAcademy/SoftwareAcademy-MySolution/Course.cs", "max_forks_repo_name": "iliantrifonov/TelerikAcademy", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.7246376812, "max_line_length": 186, "alphanum_fraction": 0.4974772957}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SoftwareAcademy { public abstract class Course : ICourse { private string name; private IList<string> topics; public Course(string name, ITeacher teacher = null) { this.Name = name; this.Teacher = teacher; this.topics = new List<string>(); } public string Name { get { return this.name; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("The name of the course cannot be null or empty"); } this.name = value; } } public IList<string> Topics { get { return new List<string>(this.topics); } } public ITeacher Teacher { get; set; } public void AddTopic(string topic) { if (string.IsNullOrEmpty(topic)) { throw new ArgumentNullException("The topic cannot be null or empty"); } this.topics.Add(topic); } public override string ToString() { //(course type): Name=(course name); Teacher=(teacher name); Topics=[(course topics – comma separated)]; Lab=(lab name – when applicable); Town=(town name – when applicable); StringBuilder sb = new StringBuilder(); sb.Append(string.Format("{0}: Name={1}; ", this.GetType().Name, this.Name)); if (this.Teacher != null) { sb.Append(string.Format("Teacher={0}; ", this.Teacher.Name)); } if (this.Topics.Count != 0) { sb.Append(string.Format("Topics=[{0}]; ", string.Join(", ", this.Topics))); } return sb.ToString(); } } }
TheStack
e0580e3c54f063ac0a74c3676dba2fae93b2297e
C#code:C#
{"size": 425, "ext": "cs", "max_stars_repo_path": "Assets/Plugins/StansAssets/NativePlugins/IOSNativePro/Runtime/API/CloudKit/Enum/ISN_CKResultType.cs", "max_stars_repo_name": "Alnirel/com.stansassets.running-dinosaur-clone", "max_stars_repo_stars_event_min_datetime": "2021-05-12T16:20:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T08:49:33.000Z", "max_issues_repo_path": "Assets/Plugins/StansAssets/NativePlugins/IOSNativePro/Runtime/API/CloudKit/Enum/ISN_CKResultType.cs", "max_issues_repo_name": "Alnirel/com.stansassets.running-dinosaur-clone", "max_issues_repo_issues_event_min_datetime": "2021-05-14T15:59:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T09:25:12.000Z", "max_forks_repo_path": "Assets/Plugins/StansAssets/NativePlugins/IOSNativePro/Runtime/API/CloudKit/Enum/ISN_CKResultType.cs", "max_forks_repo_name": "Alnirel/com.stansassets.running-dinosaur-clone", "max_forks_repo_forks_event_min_datetime": "2021-05-13T07:04:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T11:09:57.000Z"}
{"max_stars_count": 2.0, "max_issues_count": 10.0, "max_forks_count": 2.0, "avg_line_length": 20.2380952381, "max_line_length": 73, "alphanum_fraction": 0.5505882353}
using System; namespace SA.iOS.CloudKit { /// <summary> /// Constants indicating the type of CloudKit operation state result. /// </summary> public enum ISN_CKResultType { /// <summary> /// We got an error during CloudKit operation. /// </summary> Error, /// <summary> /// CloudKit operation was successful. /// </summary> Success } }
TheStack
e0584b746cf2f21abd341a08198d3f0a7af4ad3b
C#code:C#
{"size": 3211, "ext": "cs", "max_stars_repo_path": "Source/EasyCNTK/Learning/Optimizers/AdaGrad.cs", "max_stars_repo_name": "StanislavGrigoriev/EasyCNTK", "max_stars_repo_stars_event_min_datetime": "2019-06-05T17:09:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T11:11:37.000Z", "max_issues_repo_path": "Source/EasyCNTK/Learning/Optimizers/AdaGrad.cs", "max_issues_repo_name": "StanislavGrigoriev/EasyCNTK", "max_issues_repo_issues_event_min_datetime": "2019-08-25T18:52:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:17:37.000Z", "max_forks_repo_path": "Source/EasyCNTK/Learning/Optimizers/AdaGrad.cs", "max_forks_repo_name": "StanislavGrigoriev/EasyCNTK", "max_forks_repo_forks_event_min_datetime": "2019-07-08T23:27:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T11:16:28.000Z"}
{"max_stars_count": 19.0, "max_issues_count": 5.0, "max_forks_count": 11.0, "avg_line_length": 48.6515151515, "max_line_length": 224, "alphanum_fraction": 0.6954219869}
// // Copyright (c) Stanislav Grigoriev. All rights reserved. // [email protected] // https://github.com/StanislavGrigoriev/EasyCNTK // // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // using System.Collections; using System.Collections.Generic; using CNTK; namespace EasyCNTK.Learning.Optimizers { /// <summary> /// Оптимизатор AdaGrad. Хорош для работы с разряженными данными. /// </summary> public sealed class AdaGrad : Optimizer { private double _l1RegularizationWeight; private double _l2RegularizationWeight; private double _gradientClippingThresholdPerSample; public override double LearningRate { get; } public override int MinibatchSize { get; set; } /// <summary> /// Инициализирует оптимизатор AdaGrad /// </summary> /// <param name="learningRate">Скорость обучения</param> /// <param name="minibatchSize">Размер минипакета, требуется CNTK чтобы масштабировать параметры оптимизатора для более эффективного обучения. Если равен 0, то будет использован размер митибатча при обучении.</param> /// <param name="l1RegularizationWeight">Коэффициент L1 нормы, если 0 - регуляризация не применяется</param> /// <param name="l2RegularizationWeight">Коэффициент L2 нормы, если 0 - регуляризация не применяется</param> /// <param name="gradientClippingThresholdPerSample">Порог отсечения градиента на каждый пример обучения, используется преимущественно для борьбы с взрывным градиентом в глубоких реккурентных сетях. /// По умолчанию установлен в <seealso cref="double.PositiveInfinity"/> - отсечение не используется. Для использования установите необходимый порог.</param> public AdaGrad(double learningRate, int minibatchSize = 0, double l1RegularizationWeight = 0, double l2RegularizationWeight = 0, double gradientClippingThresholdPerSample = double.PositiveInfinity) { LearningRate = learningRate; MinibatchSize = minibatchSize; _l1RegularizationWeight = l1RegularizationWeight; _l2RegularizationWeight = l2RegularizationWeight; _gradientClippingThresholdPerSample = gradientClippingThresholdPerSample; } public override Learner GetOptimizer(IList<Parameter> learningParameters) { var learningOptions = new AdditionalLearningOptions() { l1RegularizationWeight = _l1RegularizationWeight, l2RegularizationWeight = _l2RegularizationWeight, gradientClippingWithTruncation = _gradientClippingThresholdPerSample != double.PositiveInfinity, gradientClippingThresholdPerSample = _gradientClippingThresholdPerSample }; return CNTKLib.AdaGradLearner(new ParameterVector((ICollection)learningParameters), new TrainingParameterScheduleDouble(LearningRate, (uint)MinibatchSize), false, learningOptions); } } }
TheStack
e058ed1dfb07a4490d3bd553810b07ed9163df55
C#code:C#
{"size": 344, "ext": "cs", "max_stars_repo_path": "NetStandardSample/ConsoleApp1DotnetCore/Program.cs", "max_stars_repo_name": "CNinnovation/WPFOct2018", "max_stars_repo_stars_event_min_datetime": "2018-10-24T07:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-24T07:06:41.000Z", "max_issues_repo_path": "NetStandardSample/ConsoleApp1DotnetCore/Program.cs", "max_issues_repo_name": "CNinnovation/WPFOct2018", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetStandardSample/ConsoleApp1DotnetCore/Program.cs", "max_forks_repo_name": "CNinnovation/WPFOct2018", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 20.2352941176, "max_line_length": 53, "alphanum_fraction": 0.5697674419}
using NetStandardSample; using System; namespace ConsoleApp1DotnetCore { class Program { static void Main(string[] args) { var std = new MyDotnetStandard(); string result = std.JustAMethod("hello"); Console.WriteLine(result); std.ShowMessage("hello"); } } }
TheStack
e05951e8eedf1841dddfb455cc6d716ccc73a054
C#code:C#
{"size": 416, "ext": "cs", "max_stars_repo_path": "src/ZigbeeClient/Smartenit/CidPacket.cs", "max_stars_repo_name": "dotMorten/ZigbeeNet", "max_stars_repo_stars_event_min_datetime": "2016-01-19T19:39:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-20T06:50:06.000Z", "max_issues_repo_path": "src/ZigbeeClient/Smartenit/CidPacket.cs", "max_issues_repo_name": "kevinmiles/ZigbeeNet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ZigbeeClient/Smartenit/CidPacket.cs", "max_forks_repo_name": "kevinmiles/ZigbeeNet", "max_forks_repo_forks_event_min_datetime": "2016-01-31T18:17:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T09:57:24.000Z"}
{"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": 6.0, "avg_line_length": 18.0869565217, "max_line_length": 48, "alphanum_fraction": 0.6225961538}
using System; namespace ZigbeeNet.Smartenit { /// <summary> /// A base CID packet for sending to the device /// </summary> public class CidPacket { public CidPacket(byte[] cmd, byte[] body) { if (cmd == null || cmd.Length != 2) throw new ArgumentException("cmd"); Command = cmd; Body = body; } public byte[] Command { get; private set; } public byte[] Body { get; private set; } } }
TheStack
e059a701c9fb2ae1eccfd4e26898cd2e751711ea
C#code:C#
{"size": 5206, "ext": "cs", "max_stars_repo_path": "Assets/scripts/ChoiceManager.cs", "max_stars_repo_name": "diqksrk/2D-game-unity", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/scripts/ChoiceManager.cs", "max_issues_repo_name": "diqksrk/2D-game-unity", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/scripts/ChoiceManager.cs", "max_forks_repo_name": "diqksrk/2D-game-unity", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.2139534884, "max_line_length": 66, "alphanum_fraction": 0.5190165194}
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ChoiceManager : MonoBehaviour { public static ChoiceManager instance; #region Singleton private void Awake() { if (instance == null) { DontDestroyOnLoad(this.gameObject); instance = this; } else { Destroy(this.gameObject); } } #endregion Singleton private AudioManager theAudio;//사운드 재생 private string question; private List<string> answerList; public GameObject go; //평소에 비활성화 시킬 목적으로 서언 초이스매니저 자체를 //set actiove로 public Text question_Text; public Text[] answer_Text; public GameObject[] answer_Panel; //텍스트 밑에 선택된것만 짙게 표현위해서. public Animator anim; public string keySound; public string enterSound; public bool choiceIng; //선택지 이루어지기 전에 다른 대화 대기 //()=> !choiceing; public bool keyInput; //키처리 활성화. private int count; //배열의 크기 private int result; //선택한 선택창 1,2,3,4 private WaitForSeconds waitTime = new WaitForSeconds(0.01f); // Use this for initialization void Start () { theAudio = FindObjectOfType<AudioManager>(); answerList = new List<string>(); for (int i=0; i<=3; i++) { answer_Text[i].text = ""; answer_Panel[i].SetActive(false); } question_Text.text = ""; } public void ShowChocie(Choice _choice) { choiceIng = true; go.SetActive(true); result = 0; question = _choice.question; for (int i=0; i<_choice.answers.Length; i++) { answerList.Add(_choice.answers[i]); answer_Panel[i].SetActive(true); count = i; } anim.SetBool("Appear", true); Selection(); StartCoroutine(ChoiceCoroutine()); } public int GetResult() { return result; } public void ExitChoice() { question_Text.text = ""; for (int i=0; i<count; i++) { answer_Text[i].text = ""; answer_Panel[i].SetActive(false); } anim.SetBool("Appear", false); choiceIng = false; go.SetActive(false); answerList.Clear(); } IEnumerator ChoiceCoroutine() { yield return new WaitForSeconds(0.2f); StartCoroutine(TypingQuestion()); StartCoroutine(TypingAnswer_0()); if (count>=1) StartCoroutine(TypingAnswer_1()); if (count >= 2) StartCoroutine(TypingAnswer_2()); if (count >= 3) StartCoroutine(TypingAnswer_3()); yield return new WaitForSeconds(0.2f); keyInput = true; } IEnumerator TypingQuestion() { for (int i=0; i<question.Length; i++) { question_Text.text += question[i]; yield return waitTime; } } IEnumerator TypingAnswer_0() { yield return new WaitForSeconds(0.4f); for (int i = 0; i < answerList[0].Length; i++) { answer_Text[0].text += answerList[0][i]; yield return waitTime; } } IEnumerator TypingAnswer_1() { yield return new WaitForSeconds(0.5f); for (int i = 0; i < answerList[1].Length; i++) { answer_Text[1].text += answerList[1][i]; yield return waitTime; } } IEnumerator TypingAnswer_2() { yield return new WaitForSeconds(0.6f); for (int i = 0; i < answerList[2].Length; i++) { answer_Text[2].text += answerList[2][i]; yield return waitTime; } } IEnumerator TypingAnswer_3() { yield return new WaitForSeconds(0.7f); for (int i = 0; i < answerList[3].Length; i++) { answer_Text[3].text += answerList[3][i]; yield return waitTime; } } // Update is called once per frame void Update () { if (keyInput) { if (Input.GetKeyDown(KeyCode.UpArrow)) { theAudio.Play(keySound); if (result > 0) result--; else result = count; Selection(); } else if (Input.GetKeyDown(KeyCode.DownArrow)) { Selection(); theAudio.Play(keySound); if (result < count) result++; else result = 0; Selection(); } else if (Input.GetKeyDown(KeyCode.Z)) { theAudio.Play(enterSound); keyInput = false; ExitChoice(); } } } public void Selection() { Color color = answer_Panel[0].GetComponent<Image>().color; color.a = 0.75f; for (int i=0; i<=count; i++) { answer_Panel[i].GetComponent<Image>().color = color; } color.a = 1f; answer_Panel[result].GetComponent<Image>().color = color; } }
TheStack
e05b9d7d36ceaae3038cbacb504163c11df79306
C#code:C#
{"size": 1241, "ext": "cs", "max_stars_repo_path": "DatasetStats/SummaryStatDetails.cs", "max_stars_repo_name": "PNNL-Comp-Mass-Spec/MS-File-Info-Scanner", "max_stars_repo_stars_event_min_datetime": "2019-11-25T18:57:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T09:15:48.000Z", "max_issues_repo_path": "DatasetStats/SummaryStatDetails.cs", "max_issues_repo_name": "PNNL-Comp-Mass-Spec/MS-File-Info-Scanner", "max_issues_repo_issues_event_min_datetime": "2020-02-11T03:28:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-07T19:40:12.000Z", "max_forks_repo_path": "DatasetStats/SummaryStatDetails.cs", "max_forks_repo_name": "PNNL-Comp-Mass-Spec/MS-File-Info-Scanner", "max_forks_repo_forks_event_min_datetime": "2017-10-12T15:12:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-06T01:15:07.000Z"}
{"max_stars_count": 4.0, "max_issues_count": 1.0, "max_forks_count": 2.0, "avg_line_length": 21.7719298246, "max_line_length": 63, "alphanum_fraction": 0.4133763094}
 namespace MSFileInfoScanner.DatasetStats { public class SummaryStatDetails { /// <summary> /// Scan count /// </summary> public int ScanCount { get; set; } /// <summary> /// Max TIC /// </summary> public double TICMax { get; set; } /// <summary> /// Max BPI /// </summary> public double BPIMax { get; set; } /// <summary> /// Median TIC /// </summary> public double TICMedian { get; set; } /// <summary> /// Median BPI /// </summary> public double BPIMedian { get; set; } /// <summary> /// Constructor /// </summary> public SummaryStatDetails() { Clear(); } public void Clear() { ScanCount = 0; TICMax = 0; BPIMax = 0; TICMedian = 0; BPIMedian = 0; } /// <summary> /// Display the scan count /// </summary> public override string ToString() { return string.Format("ScanCount: {0}", ScanCount); } } }
TheStack
e05bbefccb64ca0c4f0c4742d2563c5d5b6617e2
C#code:C#
{"size": 11381, "ext": "cs", "max_stars_repo_path": "test/Microsoft.Health.Fhir.Shared.Tests.E2E/Rest/CustomConvertDataTests.cs", "max_stars_repo_name": "marodev/fhir-server", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Microsoft.Health.Fhir.Shared.Tests.E2E/Rest/CustomConvertDataTests.cs", "max_issues_repo_name": "marodev/fhir-server", "max_issues_repo_issues_event_min_datetime": "2021-07-12T05:17:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T05:16:22.000Z", "max_forks_repo_path": "test/Microsoft.Health.Fhir.Shared.Tests.E2E/Rest/CustomConvertDataTests.cs", "max_forks_repo_name": "marodev/fhir-server", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 16.0, "max_forks_count": null, "avg_line_length": 46.643442623, "max_line_length": 208, "alphanum_fraction": 0.6715578596}
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Threading; using Hl7.Fhir.Model; using Hl7.Fhir.Rest; using Hl7.Fhir.Serialization; using Microsoft.Azure.ContainerRegistry; using Microsoft.Azure.ContainerRegistry.Models; using Microsoft.Extensions.Options; using Microsoft.Health.Fhir.Core.Configs; using Microsoft.Health.Fhir.Core.Features.Operations; using Microsoft.Health.Fhir.TemplateManagement; using Microsoft.Health.Fhir.Tests.Common; using Microsoft.Health.Fhir.Tests.Common.FixtureParameters; using Microsoft.Health.Fhir.Tests.E2E.Common; using Microsoft.Health.Fhir.Tests.E2E.Rest; using Microsoft.Health.Test.Utilities; using Microsoft.Rest; using Xunit; using Task = System.Threading.Tasks.Task; namespace Microsoft.Health.Fhir.Shared.Tests.E2E.Rest { /// <summary> /// Tests using customized template set will not run without extra container registry info /// since there is no acr emulator. /// </summary> [Trait(Traits.Category, Categories.CustomConvertData)] [HttpIntegrationFixtureArgumentSets(DataStore.All, Format.Json)] public class CustomConvertDataTests : IClassFixture<HttpIntegrationTestFixture> { private const string TestRepositoryName = "conversiontemplatestest"; private const string TestRepositoryTag = "test1.0"; private readonly TestFhirClient _testFhirClient; private readonly ConvertDataConfiguration _convertDataConfiguration; public CustomConvertDataTests(HttpIntegrationTestFixture fixture) { _testFhirClient = fixture.TestFhirClient; _convertDataConfiguration = ((IOptions<ConvertDataConfiguration>)(fixture.TestFhirServer as InProcTestFhirServer)?.Server?.Services?.GetService(typeof(IOptions<ConvertDataConfiguration>)))?.Value; } [SkippableFact] public async Task GivenAValidRequestWithCustomizedTemplateSet_WhenConvertData_CorrectResponseShouldReturn() { var registry = GetTestContainerRegistryInfo(); // Here we skip local E2E test since we need Managed Identity for container registry token. // We also skip the case when environmental variable is not provided (not able to upload templates) Skip.If(_convertDataConfiguration != null || registry == null); await PushTemplateSet(registry, TestRepositoryName, TestRepositoryTag); var parameters = GetConvertDataParams(Samples.SampleHl7v2Message, "hl7v2", $"{registry.Server}/{TestRepositoryName}:{TestRepositoryTag}", "ADT_A01"); var requestMessage = GenerateConvertDataRequest(parameters); HttpResponseMessage response = await _testFhirClient.HttpClient.SendAsync(requestMessage); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var bundleContent = await response.Content.ReadAsStringAsync(); var setting = new ParserSettings() { AcceptUnknownMembers = true, PermissiveParsing = true, }; var parser = new FhirJsonParser(setting); var bundleResource = parser.Parse<Bundle>(bundleContent); Assert.NotEmpty(bundleResource.Entry.ByResourceType<Patient>().First().Id); } [SkippableTheory] [InlineData("template:1234567890")] [InlineData("wrongtemplate:default")] [InlineData("template@sha256:592535ef52d742f81e35f4d87b43d9b535ed56cf58c90a14fc5fd7ea0fbb8695")] public async Task GivenAValidRequest_ButTemplateSetIsNotFound_WhenConvertData_ShouldReturnError(string imageReference) { var registry = GetTestContainerRegistryInfo(); // Here we skip local E2E test since we need Managed Identity for container registry token. // We also skip the case when environmental variable is not provided (not able to upload templates) Skip.If(_convertDataConfiguration != null || registry == null); await PushTemplateSet(registry, TestRepositoryName, TestRepositoryTag); var parameters = GetConvertDataParams(Samples.SampleHl7v2Message, "hl7v2", $"{registry.Server}/{imageReference}", "ADT_A01"); var requestMessage = GenerateConvertDataRequest(parameters); HttpResponseMessage response = await _testFhirClient.HttpClient.SendAsync(requestMessage); var responseContent = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Contains($"Image Not Found.", responseContent); } private ContainerRegistryInfo GetTestContainerRegistryInfo() { var containerRegistry = new ContainerRegistryInfo { Server = Environment.GetEnvironmentVariable("TestContainerRegistryServer"), Username = Environment.GetEnvironmentVariable("TestContainerRegistryServer")?.Split('.')[0], Password = Environment.GetEnvironmentVariable("TestContainerRegistryPassword"), }; if (string.IsNullOrEmpty(containerRegistry.Server) || string.IsNullOrEmpty(containerRegistry.Password)) { return null; } return containerRegistry; } private async Task PushTemplateSet(ContainerRegistryInfo registry, string repository, string tag) { AzureContainerRegistryClient acrClient = new AzureContainerRegistryClient(registry.Server, new AcrBasicToken(registry)); int schemaV2 = 2; string mediatypeV2Manifest = "application/vnd.docker.distribution.manifest.v2+json"; string mediatypeV1Manifest = "application/vnd.oci.image.config.v1+json"; string emptyConfigStr = "{}"; // Upload config blob byte[] originalConfigBytes = Encoding.UTF8.GetBytes(emptyConfigStr); using var originalConfigStream = new MemoryStream(originalConfigBytes); string originalConfigDigest = ComputeDigest(originalConfigStream); await UploadBlob(acrClient, originalConfigStream, repository, originalConfigDigest); // Upload memory blob var defaultTemplateResourceName = $"{typeof(OCIFileManager).Namespace}.Hl7v2DefaultTemplates.tar.gz"; using Stream byteStream = typeof(OCIFileManager).Assembly.GetManifestResourceStream(defaultTemplateResourceName); var blobLength = byteStream.Length; string blobDigest = ComputeDigest(byteStream); await UploadBlob(acrClient, byteStream, repository, blobDigest); // Push manifest List<Descriptor> layers = new List<Descriptor> { new Descriptor("application/vnd.oci.image.layer.v1.tar", blobLength, blobDigest), }; var v2Manifest = new V2Manifest(schemaV2, mediatypeV2Manifest, new Descriptor(mediatypeV1Manifest, originalConfigBytes.Length, originalConfigDigest), layers); await acrClient.Manifests.CreateAsync(repository, tag, v2Manifest); } private async Task UploadBlob(AzureContainerRegistryClient acrClient, Stream stream, string repository, string digest) { stream.Position = 0; var uploadInfo = await acrClient.Blob.StartUploadAsync(repository); var uploadedLayer = await acrClient.Blob.UploadAsync(stream, uploadInfo.Location); await acrClient.Blob.EndUploadAsync(digest, uploadedLayer.Location); } private static string ComputeDigest(Stream s) { s.Position = 0; StringBuilder sb = new StringBuilder(); using (var hash = SHA256.Create()) { byte[] result = hash.ComputeHash(s); foreach (byte b in result) { sb.Append(b.ToString("x2")); } } return "sha256:" + sb.ToString(); } private HttpRequestMessage GenerateConvertDataRequest( Parameters inputParameters, string path = "$convert-data", string acceptHeader = ContentType.JSON_CONTENT_HEADER, string preferHeader = "respond-async", Dictionary<string, string> queryParams = null) { var request = new HttpRequestMessage { Method = HttpMethod.Post, }; request.Content = new StringContent(inputParameters.ToJson(), System.Text.Encoding.UTF8, "application/json"); request.RequestUri = new Uri(_testFhirClient.HttpClient.BaseAddress, path); return request; } private static Parameters GetConvertDataParams(string inputData, string inputDataType, string templateSetReference, string rootTemplate) { var parametersResource = new Parameters(); parametersResource.Parameter = new List<Parameters.ParameterComponent>(); parametersResource.Parameter.Add(new Parameters.ParameterComponent() { Name = ConvertDataProperties.InputData, Value = new FhirString(inputData) }); parametersResource.Parameter.Add(new Parameters.ParameterComponent() { Name = ConvertDataProperties.InputDataType, Value = new FhirString(inputDataType) }); parametersResource.Parameter.Add(new Parameters.ParameterComponent() { Name = ConvertDataProperties.TemplateCollectionReference, Value = new FhirString(templateSetReference) }); parametersResource.Parameter.Add(new Parameters.ParameterComponent() { Name = ConvertDataProperties.RootTemplate, Value = new FhirString(rootTemplate) }); return parametersResource; } internal class ContainerRegistryInfo { public string Server { get; set; } public string Username { get; set; } public string Password { get; set; } } internal class AcrBasicToken : ServiceClientCredentials { private ContainerRegistryInfo _registry; public AcrBasicToken(ContainerRegistryInfo registry) { _registry = registry; } public override void InitializeServiceClient<T>(ServiceClient<T> client) { base.InitializeServiceClient(client); } public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var basicToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_registry.Username}:{_registry.Password}")); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", basicToken); return base.ProcessHttpRequestAsync(request, cancellationToken); } } } }
TheStack
e05c9638dce5ce9253703b5707cb8086bedc08f6
C#code:C#
{"size": 2067, "ext": "cs", "max_stars_repo_path": "test/DryIoc.IssuesTests/Issue339_GenericDecoratorWithConstraints.cs", "max_stars_repo_name": "SeriousM/DryIoc", "max_stars_repo_stars_event_min_datetime": "2018-06-02T16:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:53:13.000Z", "max_issues_repo_path": "test/DryIoc.IssuesTests/Issue339_GenericDecoratorWithConstraints.cs", "max_issues_repo_name": "SeriousM/DryIoc", "max_issues_repo_issues_event_min_datetime": "2018-06-06T20:29:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:01:48.000Z", "max_forks_repo_path": "test/DryIoc.IssuesTests/Issue339_GenericDecoratorWithConstraints.cs", "max_forks_repo_name": "SeriousM/DryIoc", "max_forks_repo_forks_event_min_datetime": "2018-08-16T00:46:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:52:50.000Z"}
{"max_stars_count": 736.0, "max_issues_count": 421.0, "max_forks_count": 115.0, "avg_line_length": 34.45, "max_line_length": 113, "alphanum_fraction": 0.6656990808}
using NUnit.Framework; namespace DryIoc.IssuesTests { [TestFixture] public class Issue339_GenericDecoratorWithConstraints { [Test] public void Test() { var container = new Container(); container.Register(typeof(IAsyncRequestHandler<,>), typeof(Decorator<,>), setup: Setup.Decorator); container.Register<IAsyncRequestHandler<GetStringRequest, string>, GetStringRequestHandler>(); container.Register<IActionHandler, TransactionActionHandler>(); var result = container.Resolve<IAsyncRequestHandler<GetStringRequest, string>>(); Assert.IsInstanceOf<Decorator<GetStringRequest, string>>(result); Assert.IsInstanceOf<TransactionActionHandler>(((Decorator<GetStringRequest, string>)result).Handler); Assert.IsInstanceOf<GetStringRequestHandler>(((Decorator<GetStringRequest, string>)result).Inner); } // API public interface IAsyncRequest<out TResponse> { } public interface IAsyncRequestHandler<in TRequest, out TResponse> where TRequest : IAsyncRequest<TResponse> { } public interface IActionHandler { } // Samples public interface IBusinessLayerCommand { } public class GetStringRequest : IAsyncRequest<string>, IBusinessLayerCommand { } public class GetStringRequestHandler : IAsyncRequestHandler<GetStringRequest, string> { } public class TransactionActionHandler : IActionHandler { } public class Decorator<TRequest, TResponse> : IAsyncRequestHandler<TRequest, TResponse> where TRequest : IAsyncRequest<TResponse>, IBusinessLayerCommand { public Decorator(IActionHandler handler, IAsyncRequestHandler<TRequest, TResponse> inner) { Handler = handler; Inner = inner; } public readonly IActionHandler Handler; public readonly IAsyncRequestHandler<TRequest, TResponse> Inner; } } }
TheStack
e0608bfb6483b9737efb155c3f96ce92b1c62321
C#code:C#
{"size": 2795, "ext": "cs", "max_stars_repo_path": "QuickStart2.Pg/QuickStart2.Pg/Startup.cs", "max_stars_repo_name": "argentsea/quickstarts", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuickStart2.Pg/QuickStart2.Pg/Startup.cs", "max_issues_repo_name": "argentsea/quickstarts", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuickStart2.Pg/QuickStart2.Pg/Startup.cs", "max_forks_repo_name": "argentsea/quickstarts", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.0853658537, "max_line_length": 123, "alphanum_fraction": 0.5953488372}
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.OpenApi.Models; using ArgentSea.Pg; using Microsoft.AspNetCore.Http; namespace QuickStart2.Pg { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddLogging(); services.AddPgServices<short>(this.Configuration); services.AddSingleton<ShardSets>(); services.AddTransient<Stores.CustomerStore>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(o => { o.SwaggerDoc("v1", new OpenApiInfo() { Title = "ArgentSea Sharded WebService", Version = "v1" }); o.DescribeAllEnumsAsStrings(); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseExceptionHandler(options => { options.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; var contextFeature = context.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>(); if (!(contextFeature is null)) { await context.Response.WriteAsync(ErrorResult.CaptureToJSON(500, contextFeature.Error)); } }); }); app.UseHttpsRedirection(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(o => { o.SwaggerEndpoint("/swagger/v1/swagger.json", "ArgentSea QuickStart 2"); o.RoutePrefix = "swagger"; //default }); } } }
TheStack
e061bc7bbf3f1048edefc0f03e66959dbae60b8d
C#code:C#
{"size": 2605, "ext": "cs", "max_stars_repo_path": "sdk/postgresql/Microsoft.Azure.Management.PostgreSQL/tests/ScenarioTests/CRUDDBForPostgreSQLTestsBase.cs", "max_stars_repo_name": "jessicl-ms/azure-sdk-for-net", "max_stars_repo_stars_event_min_datetime": "2019-07-29T09:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-21T06:12:47.000Z", "max_issues_repo_path": "sdk/postgresql/Microsoft.Azure.Management.PostgreSQL/tests/ScenarioTests/CRUDDBForPostgreSQLTestsBase.cs", "max_issues_repo_name": "jessicl-ms/azure-sdk-for-net", "max_issues_repo_issues_event_min_datetime": "2019-09-27T03:14:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-14T23:22:19.000Z", "max_forks_repo_path": "sdk/postgresql/Microsoft.Azure.Management.PostgreSQL/tests/ScenarioTests/CRUDDBForPostgreSQLTestsBase.cs", "max_forks_repo_name": "jessicl-ms/azure-sdk-for-net", "max_forks_repo_forks_event_min_datetime": "2019-10-07T23:32:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-08T22:28:40.000Z"}
{"max_stars_count": 3.0, "max_issues_count": 154.0, "max_forks_count": 3.0, "avg_line_length": 34.2763157895, "max_line_length": 98, "alphanum_fraction": 0.6199616123}
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using PostgreSQL.Tests.Helpers; using Microsoft.Azure.Management.PostgreSQL; using Microsoft.Azure.Management.PostgreSQL.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; namespace PostgreSQL.Tests.ScenarioTests { public class CRUDPostgreSQLTestsBase : TestBase { protected static string ResourceGroupName; protected static string ServerName; protected static string DmsProjectName; protected static string DmsTaskName; public CRUDPostgreSQLTestsBase() { ResourceGroupName = "pgsdkrg"; ServerName = "pgsdkserver"; } protected Server CreatePostgreSQLInstance(MockContext context, PostgreSQLManagementClient client, ResourceGroup resourceGroup, string serverName) { return client.Servers.Create( resourceGroup.Name, serverName, new ServerForCreate( properties: new ServerPropertiesForDefaultCreate( administratorLogin: "testUser", administratorLoginPassword: "testPassword1!"), location: resourceGroup.Location, sku: new Microsoft.Azure.Management.PostgreSQL.Models.Sku(name: "B_Gen5_1"))); } protected ResourceGroup CreateResourceGroup(MockContext context, RecordedDelegatingHandler handler, string resourceGroupName, string location) { var resourcesClient = Utilities.GetResourceManagementClient( context, handler); var resourceGroup = resourcesClient.ResourceGroups.CreateOrUpdate( resourceGroupName, new ResourceGroup { Location = location }); return resourceGroup; } protected void DeleteResourceGroup(MockContext context, RecordedDelegatingHandler handler, string resourceGroupName) { var resourcesClient = Utilities.GetResourceManagementClient( context, handler); resourcesClient.ResourceGroups.Delete(resourceGroupName); } } }
TheStack
e06258977c671e7561f7e4bff59a1276f1a4499b
C#code:C#
{"size": 2821, "ext": "cs", "max_stars_repo_path": "cldbSql.cs", "max_stars_repo_name": "JeloH/RegisterManagment", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cldbSql.cs", "max_issues_repo_name": "JeloH/RegisterManagment", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cldbSql.cs", "max_forks_repo_name": "JeloH/RegisterManagment", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.3140495868, "max_line_length": 212, "alphanum_fraction": 0.5037220844}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using System.Configuration; using System.Windows.Forms; namespace Applictaion_Ozviat { class cldbSql { public SqlConnection con; public SqlDataAdapter da; public DataView dv; public DataSet ds; Form f1 = new Form(); private static string cmdAccess5; public static string CmdAccess5 { get { return cldbSql.cmdAccess5; } set { cldbSql.cmdAccess5 = value; } } public static void CallDB(string strCodeSql) { Form f1 = new Form(); SqlConnection con = new SqlConnection(); try { // string s3 = "Data Source=.;Initial Catalog=db2;Integrated Security=true;"; //string s3 = @"provider=microsoft.jet.oledb.4.0;" + @"data source=..\\Debug\\db\\db2.mdb"; string str1 = ""; str1 = ConfigurationManager.ConnectionStrings["cn1"].ConnectionString; con = new SqlConnection(str1); SqlCommand cmd = new SqlCommand(strCodeSql, con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } catch (Exception er) { MsgBox.ShowMessage(f1.Handle.ToInt32(), er.Message.ToString(), "خطا", "تایید", "", "", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign); } } public DataView vt (string strd){ try { string str1 = ""; str1 = ConfigurationManager.ConnectionStrings["cn1"].ConnectionString; con = new SqlConnection(str1); SqlCommand com = con.CreateCommand(); com.CommandText = strd; com.CommandType = CommandType.Text; con.Open(); ds = new DataSet(); da = new SqlDataAdapter(com); SqlCommandBuilder comb = new SqlCommandBuilder(da); da.Fill(ds); dv = new DataView(ds.Tables[0]); con.Close(); } catch(Exception ex){ MsgBox.ShowMessage(f1.Handle.ToInt32(), ex.Message.ToString(), "خطا", "تایید", "", "", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign); } return dv; } } }
TheStack
e0643edc02bb6985fc145fb4b044123cffae70e4
C#code:C#
{"size": 340, "ext": "cs", "max_stars_repo_path": "Source/Infrastructure/EtAlii.Ubigia.Infrastructure.Transport/Authentication/Verification/HttpContext/IHttpContextAuthenticationIdentityProvider.cs", "max_stars_repo_name": "vrenken/EtAlii.Ubigia", "max_stars_repo_stars_event_min_datetime": "2021-07-14T22:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T00:24:28.000Z", "max_issues_repo_path": "Source/Infrastructure/EtAlii.Ubigia.Infrastructure.Transport/Authentication/Verification/HttpContext/IHttpContextAuthenticationIdentityProvider.cs", "max_issues_repo_name": "vrenken/EtAlii.Ubigia", "max_issues_repo_issues_event_min_datetime": "2021-06-23T22:04:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T10:01:13.000Z", "max_forks_repo_path": "Source/Infrastructure/EtAlii.Ubigia.Infrastructure.Transport/Authentication/Verification/HttpContext/IHttpContextAuthenticationIdentityProvider.cs", "max_forks_repo_name": "vrenken/EtAlii.Ubigia", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2.0, "max_issues_count": 49.0, "max_forks_count": null, "avg_line_length": 30.9090909091, "max_line_length": 113, "alphanum_fraction": 0.7676470588}
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia namespace EtAlii.Ubigia.Infrastructure.Transport { using Microsoft.AspNetCore.Http; internal interface IHttpContextAuthenticationIdentityProvider { AuthenticationIdentity Get(HttpContext context); } }
TheStack
e064fd7183105d865e0c0aacd3c6f36d4899c9e9
C#code:C#
{"size": 10472, "ext": "cs", "max_stars_repo_path": "src/Infrastructure/src/Emulator/Main/Peripherals/PCI/PCIeBasePeripheral.cs", "max_stars_repo_name": "UPBIoT/renode-iot", "max_stars_repo_stars_event_min_datetime": "2020-11-30T08:22:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T00:57:12.000Z", "max_issues_repo_path": "src/Infrastructure/src/Emulator/Main/Peripherals/PCI/PCIeBasePeripheral.cs", "max_issues_repo_name": "UPBIoT/renode-iot", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Infrastructure/src/Emulator/Main/Peripherals/PCI/PCIeBasePeripheral.cs", "max_forks_repo_name": "UPBIoT/renode-iot", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 47.6, "max_line_length": 261, "alphanum_fraction": 0.599025974}
// // Copyright (c) 2010-2020 Antmicro // // This file is licensed under the MIT License. // Full license text is available in 'licenses/MIT.txt'. // using System; using System.Collections.Generic; using System.Linq; using Antmicro.Renode.Core; using Antmicro.Renode.Core.Structure; using Antmicro.Renode.Core.Structure.Registers; using Antmicro.Renode.Exceptions; using Antmicro.Renode.Logging; using Antmicro.Renode.Peripherals.Bus; using Antmicro.Renode.Peripherals.PCI.BAR; using Antmicro.Renode.Peripherals.PCI.Capabilities; using Antmicro.Renode.Utilities; namespace Antmicro.Renode.Peripherals.PCI { public abstract class PCIeBasePeripheral : IPCIePeripheral { protected PCIeBasePeripheral(IPCIeRouter parent, HeaderType headerType) { if(!IsHeaderAcceptable(headerType)) { throw new ConstructionException($"Currently only devices of type {HeaderType.Bridge} or {HeaderType.Endpoint} are supported."); } this.parent = parent; this.HeaderType = headerType; this.baseAddressRegisters = new BaseAddressRegister[headerType.MaxNumberOfBARs()]; var registerMap = new Dictionary<long, DoubleWordRegister> { {(long)Registers.DeviceAndVendorId, new DoubleWordRegister(this) .WithValueField(0, 16, FieldMode.Read, valueProviderCallback: _ => VendorId) .WithValueField(16, 16, FieldMode.Read, valueProviderCallback: _ => DeviceId) }, {(long)Registers.StatusAndConfiguration, new DoubleWordRegister(this) //unsupported fields do not have to be implemented. Maybe we should move it to inheriting classes? //First 16 bits: command register. RW. Writing 0 to these fields should effectively disable all accesses but the configuration accesses .WithTaggedFlag("I/O Space", 0) .WithTaggedFlag("Memory Space", 1) .WithTaggedFlag("Bus Master", 2) .WithTaggedFlag("Special Cycles", 3) .WithTaggedFlag("Memory Write and Invalidate Enable", 4) .WithTaggedFlag("VGA Palette Snoop", 5) .WithTaggedFlag("Parity Error Response", 6) .WithReservedBits(7, 1) .WithTaggedFlag("SERR# Enable", 8) .WithTaggedFlag("Fast Back-to-Back Enable", 9) .WithTaggedFlag("Interrupt Disable", 10) .WithReservedBits(11, 8) //Second 16 bits: status register. W1C. .WithTaggedFlag("Interrupt Status", 19) .WithFlag(20, FieldMode.Read, valueProviderCallback: _ => capabilities.Any(), name: "Capabilities List") .WithTaggedFlag("66 MHz Capabale", 21) .WithReservedBits(22, 1) .WithTaggedFlag("Fast Back-to-Back capable", 23) .WithTaggedFlag("Master Data Parity Error", 24) .WithTag("DEVSEL Timing", 25, 2) .WithTaggedFlag("Signaled Target Abort", 27) .WithTaggedFlag("Received Target Abort", 28) .WithTaggedFlag("Received Master Abort", 29) .WithTaggedFlag("Signaled System Error", 30) .WithTaggedFlag("Detected Parity Error", 31) }, {(long)Registers.ClassCode, new DoubleWordRegister(this) .WithValueField(0, 8, FieldMode.Read, valueProviderCallback: _ => RevisionId) .WithValueField(16, 16, FieldMode.Read, valueProviderCallback: _ => ClassCode) }, {(long)Registers.Header, new DoubleWordRegister(this) .WithTag("Cacheline Size", 0, 8) .WithTag("Latency Timer", 8, 8) .WithEnumField(16, 8, FieldMode.Read, valueProviderCallback: (HeaderType _) => headerType) .WithTag("BIST", 24, 8) }, {(long)Registers.Capabilities, new DoubleWordRegister(this) .WithValueField(0, 8, FieldMode.Read, valueProviderCallback: _ => capabilities.FirstOrDefault().Key) }, }; registers = new DoubleWordRegisterCollection(this, registerMap); AddCapability(0x80, new PCIeCapability(this)); } public virtual uint ConfigurationReadDoubleWord(long offset) { var value = registers.Read(offset); this.Log(LogLevel.Noisy, "Accessing Configuration space, reading from {0} (0x{1:X}), read 0x{2:X}.", (Registers)offset, offset, value); return value; } public virtual void Reset() { registers.Reset(); } public virtual void ConfigurationWriteDoubleWord(long offset, uint value) { this.Log(LogLevel.Noisy, "Accessing Configuration space, writing to {0} (0x{1:X}), value {2:X}.", (Registers)offset, offset, value); registers.Write(offset, value); } public uint MemoryReadDoubleWord(uint bar, long offset) { if(bar >= baseAddressRegisters.Length || baseAddressRegisters[bar] == null) { this.Log(LogLevel.Warning, "Trying to read from unimplemented BAR {0}, offset 0x{1:X}.", bar, offset); return 0; } if(baseAddressRegisters[bar].RequestedSize < offset) { this.Log(LogLevel.Error, "Trying to read outside the limits of BAR {0}, offset 0x{1:X}. The BAR requested 0x{2:X} bytes. This may indicate a problem in PCIe routing.", bar, offset, baseAddressRegisters[bar].RequestedSize); return 0; } return ReadDoubleWordFromBar(bar, offset); } public void MemoryWriteDoubleWord(uint bar, long offset, uint value) { if(bar >= baseAddressRegisters.Length || baseAddressRegisters[bar] == null) { this.Log(LogLevel.Warning, "Trying to write to unimplemented BAR {0}, offset 0x{1:X}, value 0x{2:X}.", bar, offset, value); return; } if(baseAddressRegisters[bar].RequestedSize < offset) { this.Log(LogLevel.Error, "Trying to write outside the limits of BAR {0}, offset 0x{1:X}, value 0x{2:X}. The BAR requested 0x{3:X} bytes. This may indicate a problem in PCIe routing.", bar, offset, value, baseAddressRegisters[bar].RequestedSize); return; } WriteDoubleWordToBar(bar, offset, value); } public ushort DeviceId { get; set; } public ushort VendorId { get; set; } public byte RevisionId { get; set; } public uint ClassCode { get; set; } public HeaderType HeaderType { get; } protected virtual void WriteDoubleWordToBar(uint bar, long offset, uint value) { this.Log(LogLevel.Warning, "Unhandled write to BAR {0}, offset 0x{1:X}, value 0x{2:X}.", bar, offset, value); } protected virtual uint ReadDoubleWordFromBar(uint bar, long offset) { this.Log(LogLevel.Warning, "Unhandled read from BAR {0}, offset 0x{1:X}.", bar, offset); return 0; } protected void AddBaseAddressRegister(uint i, BaseAddressRegister register) { if(i > HeaderType.MaxNumberOfBARs()) { throw new ConstructionException($"Cannot add Base address register {i} as it exceeds the maximum amount of these registers for this type of peripheral."); } if(baseAddressRegisters[i] != null) { throw new ConstructionException($"Base address register number at {i} is already registered."); } baseAddressRegisters[i] = register; registers.AddRegister((long)Registers.BaseAddressRegister0 + 4 * i, new DoubleWordRegister(this) .WithValueField(0, 32, changeCallback: (_, value) => baseAddressRegisters[i].Value = value, valueProviderCallback: _ => baseAddressRegisters[i].Value, name: $"BAR{i}")) .WithWriteCallback((_, value) => parent.RegisterBar(new Range(baseAddressRegisters[i].BaseAddress, baseAddressRegisters[i].RequestedSize), this, i)); } protected void AddCapability(byte offset, Capability capability) { if(offset < CapabilitiesOffset) { throw new ConstructionException($"Capability offset (0x{offset:X}) is below the minimal address (0x{CapabilitiesOffset:X})"); } if(capabilities.ContainsKey(offset)) { throw new ConstructionException($"Capability already registered at 0x{offset}"); } if(capabilities.Any()) { var lastCapability = capabilities.Last(); lastCapability.Value.NextCapability = offset; } capabilities.Add(offset, capability); foreach(var register in capability.Registers) { registers.AddRegister(offset, register); offset += 4; } } protected readonly DoubleWordRegisterCollection registers; private bool IsHeaderAcceptable(HeaderType header) { var headerWithoutMultiFunctionFlag = header & ~HeaderType.MultiFunctionDevice; //we do not check "HasFlag, because a) Endpoint == 0, b) they are mutually exclusive return headerWithoutMultiFunctionFlag == HeaderType.Bridge || headerWithoutMultiFunctionFlag == HeaderType.Endpoint; } private readonly IPCIeRouter parent; private readonly BaseAddressRegister[] baseAddressRegisters; private readonly Dictionary<byte, Capability> capabilities = new Dictionary<byte, Capability>(); private const byte CapabilitiesOffset = 0x40; private enum Registers { DeviceAndVendorId = 0x0, StatusAndConfiguration = 0x4, ClassCode = 0x8, Header = 0xc, BaseAddressRegister0 = 0x10, BaseAddressRegister1 = 0x14, //missing offsets are type-specific Capabilities = 0x34, } } }
TheStack
e065f26e6e5346f039da946e471b6ddf30b00546
C#code:C#
{"size": 180, "ext": "cs", "max_stars_repo_path": "vs/SecurET/App.xaml.cs", "max_stars_repo_name": "cogengiti/securet", "max_stars_repo_stars_event_min_datetime": "2015-11-13T15:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-13T15:39:49.000Z", "max_issues_repo_path": "vs/SecurET/App.xaml.cs", "max_issues_repo_name": "cogengiti/securet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vs/SecurET/App.xaml.cs", "max_forks_repo_name": "cogengiti/securet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 15.0, "max_line_length": 42, "alphanum_fraction": 0.6}
using System.Windows; namespace SecurET { /// <summary> /// Logic of interaction for App.xaml /// </summary> public partial class App : Application { } }
TheStack
e0660038e9c7b6ef1d8e781a758e30b713dbf7a4
C#code:C#
{"size": 16340, "ext": "cs", "max_stars_repo_path": "SOURCE/base/Kernel/Singularity/V1/Services/ChannelService.cs", "max_stars_repo_name": "pmache/singularityrdk", "max_stars_repo_stars_event_min_datetime": "2020-05-30T09:57:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-30T10:01:47.000Z", "max_issues_repo_path": "SOURCE/base/Kernel/Singularity/V1/Services/ChannelService.cs", "max_issues_repo_name": "pmache/singularityrdk", "max_issues_repo_issues_event_min_datetime": "2020-05-29T08:14:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-29T08:14:06.000Z", "max_forks_repo_path": "SOURCE/base/Kernel/Singularity/V1/Services/ChannelService.cs", "max_forks_repo_name": "pmache/singularityrdk", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 3.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 38.8123515439, "max_line_length": 140, "alphanum_fraction": 0.5653610771}
//////////////////////////////////////////////////////////////////////////////// // // Microsoft Research Singularity - Singularity ABI Implementation // Copyright (c) Microsoft Corporation. All rights reserved. // // File: EndpointCore.cs // // Note: // using System; using System.Threading; using System.Runtime.CompilerServices; using Microsoft.Singularity; using Microsoft.Singularity.Channels; using Microsoft.Singularity.Security; using Microsoft.Singularity.Memory; using Microsoft.Singularity.V1.Security; using Microsoft.Singularity.V1.Threads; using Microsoft.Singularity.V1.Types; namespace Microsoft.Singularity.V1.Services { using Allocation = SharedHeapService.Allocation; using EndpointCoreImplementation = Microsoft.Singularity.Channels.EndpointCore; [CLSCompliant(false)] public enum ChannelServiceEvent : ushort { TransferBlockOwnership = 1, TransferContentOwnership = 2, } [CLSCompliant(false)] unsafe public struct EndpointCore { //////////////////////////////////////////////////////////////////// // Fields //////////////////////////////////////////////////////////////////// // // NOTE: The fields specified here must match those in: // Kernel/Singularity/Channels/EndpointCore.cs // Kernel/Singularity/V1/Services/ChannelServices.cs // Libraries/Singuarity.V1/Services/ChannelServices.cs /// <summary> /// Handle to the actual message delivery mechanism /// </summary> private DeliveryHandle deliveryHandle; /// <summary> /// Event handle in case this endpoint is part of a collection /// </summary> private AutoResetEventHandle collectionEvent; // // These "cached" fields are directly accessable by user programs, // but are not trusted by the kernel (as they could be modified by untrusted // code). The kernel relies on the trusted shadow copies held in the // deliveryImpl object, but updates these fields to reflect any changes to user // apps. // /// <summary> /// Event on which sends are signaled to this endpoint. /// The handle is owned by the kernel, since the endpoint can move. /// The kernel deallocates the handle when the channel is deallocated. /// NOTE: stays valid until the entire channel gets collected. /// </summary> private AutoResetEventHandle cachedMessageEvent; /// <summary> /// Closed flag /// </summary> private bool cachedClosed; /// <summary> /// Contains the process id of the process currently owning this end of the /// channel. /// </summary> private int cachedOwnerProcessId; /// <summary> /// Contains the channelId (positive on the EXP endpoint, negative on the imp endpoint) /// </summary> private int cachedChannelId; /// <summary> /// Whether to marshall or not /// </summary> private bool cachedMarshall; /// <summary> /// Points to the peer endpoint /// </summary> private Allocation* /*EndpointCore* opt(ExHeap)*/ cachedPeer; /// <summary> /// If true then the peer state can be queried directly from cachedPeer /// </summary> private bool peerStateValid; //////////////////////////////////////////////////////////////////// // Methods //////////////////////////////////////////////////////////////////// /// <summary> /// Used to allocate a channel endpoint. The size must be correctly computed by /// the trusted caller (currently trusted code NewChannel) /// </summary> [ExternalEntryPoint] public static Allocation* //EndpointCore* opt(ExHeap)! Allocate(uint size, SystemType st) { Allocation* ep = (Allocation*) SharedHeap.CurrentProcessSharedHeap.Allocate( size, st.id, 0, SharedHeap.CurrentProcessSharedHeap.EndpointOwnerId); if (ep == null) { throw new ApplicationException("SharedHeap.Allocate returned null"); } return ep; } /// <summary> /// Closes this end of the channel and frees associated resources, EXCEPT the block /// of memory for this endpoint. It must be released by the caller. Sing# does this /// for the programmer. /// Returns true for success, false for failure. /// </summary> [ExternalEntryPoint] public static bool Dispose(ref EndpointCore endpoint) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->Dispose(); } } /// <summary> /// Deallocates this end of the channel. If other end is also /// deallocated, the entire channel is deallocated. /// </summary> [ExternalEntryPoint] public static void Free(Allocation* /* EndpointCore* opt(ExHeap) */ endpoint) { EndpointCoreImplementation.Free((SharedHeap.Allocation*)endpoint); } /// <summary> /// Performs the initialization of the core part of each endpoint and cross links /// them to form a channel. /// </summary> [ExternalEntryPoint] public static void Connect( Allocation* /*EndpointCore* opt(ExHeap)!*/ imp, Allocation* /*EndpointCore* opt(ExHeap)!*/ exp, Allocation* /*EndpointCore* opt(ExHeap) */ ep) { EndpointCoreImplementation.Connect((SharedHeap.Allocation*)imp, (SharedHeap.Allocation*)exp, (SharedHeap.Allocation*)ep); } /// <summary> /// Indicates if this endpoint is closed /// </summary> [NoHeapAllocation] public static bool Closed(ref EndpointCore endpoint) { // kernel methods always access the shadowed copy in deliveryImpl // not the user accessable copy in EndpointCore fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->Closed(); } } /// <summary> /// Indicates if the peer endpoint is closed /// </summary> public static bool PeerClosed(ref EndpointCore ep) { // kernel methods always access the shadowed copy in deliveryImpl // not the user accessable copy in EndpointCore return PeerClosedABI(ref ep); } /// <summary> /// Indicates if the peer endpoint is closed (ABI call) /// </summary> [ExternalEntryPoint] public static bool PeerClosedABI(ref EndpointCore endpoint) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->PeerClosed(); } } /// <summary> /// Set this end to closed /// </summary> [ExternalEntryPoint] public static void Close(ref EndpointCore endpoint) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; epimp->Close(); } } /// <summary> /// The endpoint to which this endpoint is connected. /// </summary> public static Allocation* /*EndpointCore* opt(ExHeap) */ GetPeer(ref EndpointCore ep, out bool marshall) { // kernel methods always access the shadowed copy in deliveryImpl // not the user accessable copy in EndpointCore return GetPeerABI(ref ep, out marshall); } [ExternalEntryPoint] public static Allocation* /*EndpointCore* opt(ExHeap) */ GetPeerABI(ref EndpointCore endpoint, out bool marshall) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return (Allocation*) epimp->Peer(out marshall); } } /// <summary> /// The event to wait for messages on this endpoint. Used by Select. /// </summary> public static SyncHandle GetWaitHandle(ref EndpointCore endpoint) { // kernel methods always access the shadowed copy in deliveryImpl // not the user accessable copy in EndpointCore fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->GetWaitHandle(); } } /// <summary> /// Notify the owner of this endpoint that a message is ready. /// Notifies the set owner if this endpoint is part of a set. /// </summary> [ExternalEntryPoint] public static void NotifyPeer(ref EndpointCore endpoint) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; epimp->NotifyPeer(); } } /// <summary> /// Wait for a message to arrive on this endpoint. /// </summary> public static void Wait(ref EndpointCore ep) { SyncHandle.WaitOne(GetWaitHandle(ref ep)); } /// <summary> /// Transfer the given Allocation block to the target endpoint /// </summary> [ExternalEntryPoint] public static void TransferBlockOwnership(Allocation* ptr, ref EndpointCore target) { fixed (EndpointCore* ep = &target) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; EndpointCoreImplementation.TransferBlockOwnership((SharedHeap.Allocation*)ptr, ref *epimp); } } /// <summary> /// Transfer any contents that needs to be adjusted from the transferee to the target /// endpoint. Currently, this means setting the ownerProcessId of the /// transferee to that of the target. /// </summary> [ExternalEntryPoint] public static void TransferContentOwnership( ref EndpointCore transferee, ref EndpointCore target) { fixed (EndpointCore* ep1 = &transferee, ep2 = &target) { EndpointCoreImplementation* epimp1 = (EndpointCoreImplementation*)ep1; EndpointCoreImplementation* epimp2 = (EndpointCoreImplementation*)ep2; EndpointCoreImplementation.TransferContentOwnership(ref *epimp1, ref *epimp2); } } [NoHeapAllocation] public static int GetChannelID(ref EndpointCore endpoint) { // kernel methods always access the shadowed copy in deliveryImpl // not the user accessable copy in EndpointCore fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->ChannelId; } } [NoHeapAllocation] public static int GetOwnerProcessID(ref EndpointCore endpoint) { // kernel methods always access the shadowed copy in deliveryImpl // not the user accessable copy in EndpointCore fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->ProcessId; } } [NoHeapAllocation] public static int GetPeerProcessID(ref EndpointCore ep) { // kernel methods always access the shadowed copy in deliveryImpl // not the user accessable copy in EndpointCore return GetPeerProcessIDABI(ref ep); } [ExternalEntryPoint] [NoHeapAllocation] public static int GetPeerProcessIDABI(ref EndpointCore endpoint) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->PeerProcessId; } } [ExternalEntryPoint] public static void AcceptDelegation(Allocation* /*EndpointCore* opt(ExHeap)!*/ imp, Allocation* /*EndpointCore* opt(ExHeap)!*/ exp, Allocation* /*EndpointCore* opt(ExHeap)!*/ ep) { EndpointCoreImplementation.AcceptDelegation((SharedHeap.Allocation*)imp, (SharedHeap.Allocation*)exp, (SharedHeap.Allocation*)ep); } [ExternalEntryPoint] public static void EnableDelegation(ref EndpointCore endpoint, bool allowMediation) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; epimp->EnableDelegation(allowMediation); } } [ExternalEntryPoint] [NoHeapAllocation] public static PrincipalHandle GetPeerPrincipalHandle(ref EndpointCore endpoint) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->PeerPrincipalHandle; } } [ExternalEntryPoint] [NoHeapAllocation] public static PrincipalHandle GetOwnerPrincipalHandle(ref EndpointCore endpoint) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; return epimp->OwnerPrincipalHandle; } } /// <summary> /// Instruct the selectable object to signal events on the given AutoResetEvent /// rather than its normal event in order to aggregate signalling into a set. /// A selectable object need only support being part of a single collection at /// any point in time. /// </summary> public static void LinkIntoCollection(ref EndpointCore ep, AutoResetEventHandle ev) { ep.collectionEvent = ev; } /// <summary> /// Instruct the selectable object to stop signalling events on the given /// AutoResetEvent. /// </summary> public static void UnlinkFromCollection(ref EndpointCore ep, AutoResetEventHandle ev) { ep.collectionEvent = new AutoResetEventHandle(); } [ExternalEntryPoint] unsafe public static void MarshallMessage(ref EndpointCore endpoint, byte* basep, byte* source, int* tagAddress, int msgSize) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; epimp->BeginUpdate(basep, source, tagAddress, msgSize); } } [ExternalEntryPoint] public static void MarshallPointer(ref EndpointCore endpoint, byte* basep, byte** target, SystemType type, byte* parent, int offset) { fixed (EndpointCore* ep = &endpoint) { EndpointCoreImplementation* epimp = (EndpointCoreImplementation*)ep; epimp->MarshallPointer(basep, target, type, parent, offset); } } } }
TheStack
e06612cd990daa93cc500d2ef6e310d81216ee65
C#code:C#
{"size": 782, "ext": "cs", "max_stars_repo_path": "CWMII.lib/Enums/Win32_NetworkLoginProfile.cs", "max_stars_repo_name": "jcapellman/LWWMIW", "max_stars_repo_stars_event_min_datetime": "2021-01-21T05:32:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T10:16:36.000Z", "max_issues_repo_path": "CWMII.lib/Enums/Win32_NetworkLoginProfile.cs", "max_issues_repo_name": "jcapellman/LWWMIW", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CWMII.lib/Enums/Win32_NetworkLoginProfile.cs", "max_forks_repo_name": "jcapellman/LWWMIW", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.55, "max_line_length": 176, "alphanum_fraction": 0.76342711}
namespace CWMII.lib.Enums { public enum Win32_NetworkLoginProfile { Caption, Description, SettingID, AccountExpires, AuthorizationFlags, BadPasswordCount, CodePage, Comment, CountryCode, Flags, FullName, HomeDirectory, HomeDirectoryDrive, LastLogoff, LastLogon, LogonHours, LogonServer, MaximumStorage, Name, NumberOfLogons, Parameters, PasswordAge, PasswordExpires, PrimaryGroupId, Privileges, Profile, ScriptPath, UnitsPerWeek, UserComment, UserId, UserType, Workstations } public static class Win32_NetworkLoginProfileExtension { public static string GetWMIValue(this Win32_NetworkLoginProfile enumOption) => lib.CWMII.GetSingleProperty($"SELECT * FROM Win32_NetworkLoginProfile", enumOption.ToString()); } }
TheStack
e066f67e0fcfe50a7bcb204abb1760a12d3254c6
C#code:C#
{"size": 112, "ext": "cs", "max_stars_repo_path": "Assets/YarnSpinner/Scripts/Culture.cs", "max_stars_repo_name": "somas95/Leave", "max_stars_repo_stars_event_min_datetime": "2020-06-04T06:00:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T10:23:03.000Z", "max_issues_repo_path": "Assets/YarnSpinner/Scripts/Culture.cs", "max_issues_repo_name": "somas95/Leave", "max_issues_repo_issues_event_min_datetime": "2020-06-04T08:33:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T05:15:36.000Z", "max_forks_repo_path": "Assets/YarnSpinner/Scripts/Culture.cs", "max_forks_repo_name": "somas95/Leave", "max_forks_repo_forks_event_min_datetime": "2020-06-16T16:20:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T04:01:29.000Z"}
{"max_stars_count": 256.0, "max_issues_count": 141.0, "max_forks_count": 43.0, "avg_line_length": 14.0, "max_line_length": 30, "alphanum_fraction": 0.7232142857}
using System; [Serializable] public struct Culture { public string Name; public string DisplayName; }
TheStack
e06747b08fba1ca2cb39fd748230c3ffd958025b
C#code:C#
{"size": 1586, "ext": "cs", "max_stars_repo_path": "NJection.LambdaConverter/Ast/Expressions/CaseLabel/CaseLabel.cs", "max_stars_repo_name": "sagifogel/NJection.LambdaConverter", "max_stars_repo_stars_event_min_datetime": "2015-12-20T09:51:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T04:29:43.000Z", "max_issues_repo_path": "NJection.LambdaConverter/Ast/Expressions/CaseLabel/CaseLabel.cs", "max_issues_repo_name": "sagifogel/NJection.LambdaConverter", "max_issues_repo_issues_event_min_datetime": "2016-01-11T07:20:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-07T19:39:18.000Z", "max_forks_repo_path": "NJection.LambdaConverter/Ast/Expressions/CaseLabel/CaseLabel.cs", "max_forks_repo_name": "sagifogel/NJection.LambdaConverter", "max_forks_repo_forks_event_min_datetime": "2016-12-12T04:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T15:52:14.000Z"}
{"max_stars_count": 22.0, "max_issues_count": 3.0, "max_forks_count": 10.0, "avg_line_length": 33.7446808511, "max_line_length": 121, "alphanum_fraction": 0.630517024}
using System.Linq.Expressions; using NJection.LambdaConverter.Visitors; using NJection.Scope; using NRefactory = ICSharpCode.NRefactory.CSharp; namespace NJection.LambdaConverter.Expressions { public class CaseLabel : AstExpression { private NRefactory.CaseLabel _caseLabel = null; protected internal CaseLabel(NRefactory.CaseLabel caseLabel, IScope scope, INRefcatoryExpressionVisitor visitor) : base(scope, visitor) { var expression = caseLabel.Expression; _caseLabel = caseLabel; DefaultValue = expression.AcceptVisitor(Visitor, ParentScope); InternalType = DefaultValue.Type; } public LabelTarget Target { get; private set; } public Expression DefaultValue { get; private set; } public string Name { get; set; } public override AstExpressionType AstNodeType { get { return AstExpressionType.CaseLabel; } } public override Expression Reduce() { return Expression.Label( Expression.Label(InternalType)); } public override Expression Accept(NJectionExpressionVisitor visitor) { return visitor.VisitCaseLabel(this); } public Expression Update(LabelTarget target, Expression defaultValue) { if (Target.Equals(target) && DefaultValue == defaultValue) { return this; } return AstExpression.Label(_caseLabel, ParentScope, Visitor); } } }
TheStack
e06833bac1c05557f6a58eee79f5a59039a4226f
C#code:C#
{"size": 649, "ext": "cs", "max_stars_repo_path": "Source/Reddnet.DataAccess/Configurations/UserConfiguration.cs", "max_stars_repo_name": "cuno92/Reddnet", "max_stars_repo_stars_event_min_datetime": "2019-08-17T09:04:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T20:56:56.000Z", "max_issues_repo_path": "Source/Reddnet.DataAccess/Configurations/UserConfiguration.cs", "max_issues_repo_name": "cuno92/Reddnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Reddnet.DataAccess/Configurations/UserConfiguration.cs", "max_forks_repo_name": "cuno92/Reddnet", "max_forks_repo_forks_event_min_datetime": "2019-07-16T05:34:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T20:49:24.000Z"}
{"max_stars_count": 80.0, "max_issues_count": null, "max_forks_count": 16.0, "avg_line_length": 29.5, "max_line_length": 71, "alphanum_fraction": 0.6702619414}
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Reddnet.Domain.Entities; namespace Reddnet.DataAccess.Configurations; internal class UserConfiguration : IEntityTypeConfiguration<UserEntity> { public void Configure(EntityTypeBuilder<UserEntity> builder) { builder.HasMany(x => x.Posts) .WithOne(x => x.User) .HasForeignKey(x => x.UserId) .OnDelete(DeleteBehavior.SetNull); builder.HasMany(x => x.Replies) .WithOne(x => x.User) .HasForeignKey(x => x.UserId) .OnDelete(DeleteBehavior.SetNull); } }
TheStack
e069879cb186f04acc2538b648a4334b9a09d9d1
C#code:C#
{"size": 524, "ext": "cs", "max_stars_repo_path": "Mitigate/Enumerations/ToolDetected.cs", "max_stars_repo_name": "moullos/Mitigate", "max_stars_repo_stars_event_min_datetime": "2020-07-10T13:31:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T18:56:43.000Z", "max_issues_repo_path": "Mitigate/Enumerations/ToolDetected.cs", "max_issues_repo_name": "moullos/Mitigate", "max_issues_repo_issues_event_min_datetime": "2020-11-04T17:13:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T13:18:24.000Z", "max_forks_repo_path": "Mitigate/Enumerations/ToolDetected.cs", "max_forks_repo_name": "moullos/Mitigate", "max_forks_repo_forks_event_min_datetime": "2021-03-15T15:04:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T23:41:50.000Z"}
{"max_stars_count": 30.0, "max_issues_count": 4.0, "max_forks_count": 3.0, "avg_line_length": 20.1538461538, "max_line_length": 51, "alphanum_fraction": 0.5591603053}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Mitigate.Enumerations { public class ToolDetected : EnumerationResults { public ToolDetected(string ToolName) { this.Info = ToolName; } public override string ToString() { return $"{Info} was detected"; } public override ResultType ToResultType() { return ResultType.True; } } }
TheStack
e06a64cee3cccffea7a0205aa853b2c27f49fda7
C#code:C#
{"size": 310, "ext": "cs", "max_stars_repo_path": "Elfie/Elfie/Model/EmptyArray.cs", "max_stars_repo_name": "mattk09/elfie-arriba", "max_stars_repo_stars_event_min_datetime": "2019-05-07T06:43:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T23:41:25.000Z", "max_issues_repo_path": "Elfie/Elfie/Model/EmptyArray.cs", "max_issues_repo_name": "mattk09/elfie-arriba", "max_issues_repo_issues_event_min_datetime": "2020-07-13T01:20:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-11T22:14:59.000Z", "max_forks_repo_path": "Elfie/Elfie/Model/EmptyArray.cs", "max_forks_repo_name": "mattk09/elfie-arriba", "max_forks_repo_forks_event_min_datetime": "2019-05-21T22:37:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-10T10:36:21.000Z"}
{"max_stars_count": 20.0, "max_issues_count": 11.0, "max_forks_count": 14.0, "avg_line_length": 28.1818181818, "max_line_length": 101, "alphanum_fraction": 0.7129032258}
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.CodeAnalysis.Elfie.Model { internal static class EmptyArray<T> { public static readonly T[] Instance = new T[0]; } }
TheStack
e06c94c9fb28250990f51a7b8202eb8faaba6558
C#code:C#
{"size": 3299, "ext": "cs", "max_stars_repo_path": "Source/InTheHand/Storage/Pickers/FileSavePicker.Win32.cs", "max_stars_repo_name": "inthehand/Pontoon", "max_stars_repo_stars_event_min_datetime": "2016-10-08T10:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T14:07:26.000Z", "max_issues_repo_path": "Source/InTheHand/Storage/Pickers/FileSavePicker.Win32.cs", "max_issues_repo_name": "inthehand/charming", "max_issues_repo_issues_event_min_datetime": "2016-10-07T12:22:38.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-16T14:05:00.000Z", "max_forks_repo_path": "Source/InTheHand/Storage/Pickers/FileSavePicker.Win32.cs", "max_forks_repo_name": "inthehand/charming", "max_forks_repo_forks_event_min_datetime": "2016-11-14T21:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T20:19:39.000Z"}
{"max_stars_count": 32.0, "max_issues_count": 25.0, "max_forks_count": 7.0, "avg_line_length": 33.6632653061, "max_line_length": 111, "alphanum_fraction": 0.5101545923}
//----------------------------------------------------------------------- // <copyright file="FileSavePicker.Win32.cs" company="In The Hand Ltd"> // Copyright © 2016-17 In The Hand Ltd. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Threading.Tasks; using System.Collections.Generic; using System; using System.Runtime.InteropServices; using System.Text; using System.IO; namespace InTheHand.Storage.Pickers { partial class FileSavePicker { private async Task<StorageFile> DoPickSaveFileAsync() { NativeMethods.OPENFILENAME ofn = new FileSavePicker.NativeMethods.OPENFILENAME(); StringBuilder sb = new StringBuilder(); foreach(KeyValuePair<string,IList<string>> item in FileTypeChoices) { sb.Append(item.Key + "\0"); foreach (string filetype in item.Value) { sb.Append("*" + filetype + ";"); } if(sb[sb.Length-1] == ';') { sb.Length -= 1; } sb.Append('\0'); } sb.Append("\0"); ofn.lpstrFilter = sb.ToString(); ofn.lStructSize = Marshal.SizeOf(ofn); ofn.nMaxFile = 256; ofn.lpstrFile = new string('\0', ofn.nMaxFile); ofn.Flags = 0x02001000; if(!string.IsNullOrEmpty(DefaultFileExtension)) { ofn.lpstrDefExt = DefaultFileExtension.Substring(DefaultFileExtension.StartsWith(".") ? 1 : 0); } bool success = NativeMethods.GetSaveFileName(ref ofn); if(success) { File.Create(ofn.lpstrFile).Close(); return new StorageFile(ofn.lpstrFile); } return null; } private IDictionary<string, IList<string>> _filter = new Dictionary<string, IList<string>>(); private IDictionary<string,IList<string>> GetFileTypeChoices() { return _filter; } private static class NativeMethods { [DllImport("comdlg32")] internal static extern bool GetSaveFileName(ref OPENFILENAME lpofn); internal struct OPENFILENAME { internal int lStructSize; internal IntPtr hwndOwner; IntPtr hInstance; internal string lpstrFilter; IntPtr lpstrCustomFilter; uint nMaxCustFilter; uint nFilterIndex; internal string lpstrFile; internal int nMaxFile; IntPtr lpstrFileTitle; int nMaxFileTitle; internal string lpstrInitialDir; internal string lpstrTitle; internal uint Flags; internal ushort nFileOffset; internal ushort nFileExtension; internal string lpstrDefExt; IntPtr lCustData; IntPtr lpfnHook; IntPtr lpTemplateName; IntPtr pvReserved; int dwReserved; int FlagsEx; } } } }
TheStack
e06da1b2d334f60b93efd738d530bb526c3d8e43
C#code:C#
{"size": 1097, "ext": "cs", "max_stars_repo_path": "BotsController.Models/Commands/SpeechCommand.cs", "max_stars_repo_name": "DimaLupyak/ScrumPokerBot", "max_stars_repo_stars_event_min_datetime": "2022-01-29T15:19:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T15:19:32.000Z", "max_issues_repo_path": "BotsController.Models/Commands/SpeechCommand.cs", "max_issues_repo_name": "DimaLupyak/ScrumPokerBot", "max_issues_repo_issues_event_min_datetime": "2019-10-20T13:28:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-05T19:05:20.000Z", "max_forks_repo_path": "BotsController.Models/Commands/SpeechCommand.cs", "max_forks_repo_name": "DimaLupyak/ScrumPokerBot", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 32.2647058824, "max_line_length": 106, "alphanum_fraction": 0.5861440292}
using System; using System.IO; using System.Threading.Tasks; using BotsController.Core.Helpers; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.InputFiles; namespace BotsController.Core.Commands { public class SpeechCommand : Command { public override string Name => @"скажи"; public override Task ExecuteAsync(Message message, TelegramBotClient botClient) { try { var text = message.Text .ToLower() .Replace(Name, string.Empty) .Replace("\"", " "); var speechGenerator = new SpeechGenerator(); using var stream = new MemoryStream(speechGenerator.SynthesizeSpeech(text)); stream.Seek(0, SeekOrigin.Begin); return botClient.SendAudioAsync(message.Chat.Id, new InputOnlineFile(stream, text), text); } catch (Exception ex) { return botClient.SendTextMessageAsync(message.Chat.Id, ex.ToString()); } } } }
TheStack
e06ddaf4cfd29a2adec5e4a9f568a4bee4710bda
C#code:C#
{"size": 250, "ext": "cs", "max_stars_repo_path": "Main/DynamicGeometryLibrary/Extensibility/OrderAttribute.cs", "max_stars_repo_name": "KirillOsenkov/LiveGeometry", "max_stars_repo_stars_event_min_datetime": "2017-08-01T11:22:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T14:05:32.000Z", "max_issues_repo_path": "Main/DynamicGeometryLibrary/Extensibility/OrderAttribute.cs", "max_issues_repo_name": "KirillOsenkov/LiveGeometry", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Main/DynamicGeometryLibrary/Extensibility/OrderAttribute.cs", "max_forks_repo_name": "KirillOsenkov/LiveGeometry", "max_forks_repo_forks_event_min_datetime": "2017-11-14T22:31:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:35:51.000Z"}
{"max_stars_count": 25.0, "max_issues_count": null, "max_forks_count": 6.0, "avg_line_length": 16.6666666667, "max_line_length": 44, "alphanum_fraction": 0.532}
using System; namespace DynamicGeometry { public class OrderAttribute : Attribute { public double Order { get; set; } public OrderAttribute(double order) { Order = order; } } }
TheStack
e06ebbc02936b79e9ee4febc1303afb20f6fc78b
C#code:C#
{"size": 1650, "ext": "cs", "max_stars_repo_path": "Src/Shared/Tauron.Application.Common/ObservableExt/TypeSwitch.cs", "max_stars_repo_name": "Tauron1990/Project-Manager-Akka", "max_stars_repo_stars_event_min_datetime": "2021-02-22T13:39:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T13:39:28.000Z", "max_issues_repo_path": "Src/Shared/Tauron.Application.Common/ObservableExt/TypeSwitch.cs", "max_issues_repo_name": "Tauron1990/Project-Manager-Akka", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/Shared/Tauron.Application.Common/ObservableExt/TypeSwitch.cs", "max_forks_repo_name": "Tauron1990/Project-Manager-Akka", "max_forks_repo_forks_event_min_datetime": "2020-12-08T23:26:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-08T23:26:30.000Z"}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 32.3529411765, "max_line_length": 113, "alphanum_fraction": 0.7254545455}
using System; using System.Reactive.Linq; using JetBrains.Annotations; namespace Tauron.ObservableExt; [PublicAPI] public static class TypeSwitchExtension { public static TypeSwitchTypeConfig<TSource> TypeSwitch<TSource>(this IObservable<TSource> observable) => new(observable.ConditionalSelect()); } [PublicAPI] public readonly struct TypeSwitchTypeConfig<TSource> { private readonly ConditionalSelectTypeConfig<TSource> _observable; public TypeSwitchTypeConfig(ConditionalSelectTypeConfig<TSource> observable) => _observable = observable; public IObservable<TResult> ToResult<TResult>(Action<TypeSwitchSelectBuilder<TSource, TResult>> builder) { return _observable.ToResult<TResult>( selectBuilder => { var setup = new TypeSwitchSelectBuilder<TSource, TResult>(selectBuilder); builder(setup); }); } public IObservable<TSource> ToSame(Action<TypeSwitchSelectBuilder<TSource, TSource>> builder) => ToResult(builder); } [PublicAPI] public readonly struct TypeSwitchSelectBuilder<TSource, TResult> { private readonly ConditionalSelectBuilder<TSource, TResult> _registrations; public TypeSwitchSelectBuilder(ConditionalSelectBuilder<TSource, TResult> registrations) => _registrations = registrations; public TypeSwitchSelectBuilder<TSource, TResult> When<TType>( Func<IObservable<TType>, IObservable<TResult>> then) where TType : TSource { _registrations.Add(source => source is TType, observable => then(observable.Select(obj => (TType)obj!))); return this; } }
TheStack
e070ce903e116298936bdf421e4577e4a314cf4b
C#code:C#
{"size": 918, "ext": "cs", "max_stars_repo_path": "Programming/Programming/Model/Song.cs", "max_stars_repo_name": "Feedik111/programming", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Programming/Programming/Model/Song.cs", "max_issues_repo_name": "Feedik111/programming", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Programming/Programming/Model/Song.cs", "max_forks_repo_name": "Feedik111/programming", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 20.8636363636, "max_line_length": 93, "alphanum_fraction": 0.4281045752}
namespace Programming.Model { using System; public class Song { private int _durationSeconds; public Song() { } public Song(string artist, string name, int durationSeconds) { Artist = artist; Name = name; DurationSeconds = durationSeconds; } public string Artist { get; set; } public string Name { get; set; } public int DurationSeconds { get { return _durationSeconds; } set { if (value <= 0) { throw new ArgumentException( "the value of the Duration Seconds field must be greater than zero"); } _durationSeconds = value; } } } }
TheStack
e073c6edf7ddb48eac27ff9390e4cd72ac0d54f9
C#code:C#
{"size": 3737, "ext": "cs", "max_stars_repo_path": "DssApplicationPoster/MailConfig/EmailConstant.cs", "max_stars_repo_name": "IrsanIskandar/DSSApplication", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DssApplicationPoster/MailConfig/EmailConstant.cs", "max_issues_repo_name": "IrsanIskandar/DSSApplication", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DssApplicationPoster/MailConfig/EmailConstant.cs", "max_forks_repo_name": "IrsanIskandar/DSSApplication", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 64.4310344828, "max_line_length": 827, "alphanum_fraction": 0.6149317634}
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DssApplicationPoster.MailConfig { public static class EmailConstant { // Setting SMTP Server // If Error with GMail click this link https://myaccount.google.com/lesssecureapps public static readonly string SmtpServer = "smtp.gmail.com"; // Recomend Use STMP Server public static readonly int SmtpPort = 587; // Data Type Integer public static readonly string SmtpUsername = "[email protected]"; public static readonly string SmtpPassword = "bkbpfi987*"; // Setting Email To public static readonly string EmailAddress = "[email protected]"; public static readonly string Username = "Your-Username"; public static readonly string Password = "Your-Password"; public static string EmailTemplateHtml(string name, string attend, string guests, string description) { return $@"<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0, shrink-to-fit=no'> <title>{attend}</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css'> </head> <body> <div class='container shadow'> <div class='row'> <div class='col'> <div class='card'> <div class='card-header bg-primary'> <h1 class='mb-0'>{String.Concat(attend, " ", "[" + name + "]")}</h1> </div><div class='card-body'> <h5 class='card-title mb-0'>Fullname : {name}</h5> <h5 class='card-title mb-0'>Present Or Not : {attend}</h5> <h5 class='card-title mb-0'>Number Of Guests : {guests}</h5> <div class='row'> <div class='col'> <p>{description}</p></div></div></div></div></div></div></div></body> </html>"; } public static string AcctivationAccount(string preferredName, string urlSchema, string urlAuthhory, int userId, string accountCode) { return "<h1>Activation Your Email Account</h1>" + "<br />" + $"<h3> Welcome, {preferredName}.</h3 >" + "<p> Please click the following link to activate your account, <a href='"+ string.Format("{0}://{1}/Administrator/PrivilegedData/AccountActivation?accountCode={2}&confirmAccount={3}", urlSchema, urlAuthhory, userId, accountCode) +"'>Click here to activate.</a></p>" + "<br />" + "<p>Thanks by Administrator</p>"; } public static string AcctivationAccount(string preferredName, string urlCallback) { return "<h1>Activation Your Email Account</h1>" + "<br />" + $"<h3> Welcome, {preferredName}.</h3 >" + "<p> Please click the following link to activate your account, <a href=\""+ urlCallback +"\">Click here to activate.</a></p>" + "<br />" + "<p>Thanks by Administrator</p>"; } public static string ForgotPassword(string username, string urlSchema, string urlAuthhory, string userCode, string usernameEncrypt, string emailEncrypt) { return "<h1>Reset Your Password</h1>" + "<br />" + $"<h3> Hi, {username}.</h3 >" + "<p> Please click the following link to create new password, <a href='" + string.Format("{0}://{1}/Administrator/PrivilegedData/ConfirmForgotPassword?userCode={2}&usernameCode={3}&emailCode={4}", urlSchema, urlAuthhory, userCode, usernameEncrypt, emailEncrypt) + "'>Click here to reset password.</a></p>" + "<br />" + "<p>Thanks by Administrator</p>"; } } }
TheStack
e073febb9d264f092aa8b6fc47af278644cc95b7
C#code:C#
{"size": 451, "ext": "cs", "max_stars_repo_path": "src/GitLabApiClient/IIterationsClient.cs", "max_stars_repo_name": "nicolajbc/GitLabApiClient", "max_stars_repo_stars_event_min_datetime": "2017-09-15T21:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:08:42.000Z", "max_issues_repo_path": "src/GitLabApiClient/IIterationsClient.cs", "max_issues_repo_name": "nicolajbc/GitLabApiClient", "max_issues_repo_issues_event_min_datetime": "2017-10-05T11:44:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T21:04:30.000Z", "max_forks_repo_path": "src/GitLabApiClient/IIterationsClient.cs", "max_forks_repo_name": "nicolajbc/GitLabApiClient", "max_forks_repo_forks_event_min_datetime": "2017-10-05T11:05:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T10:04:55.000Z"}
{"max_stars_count": 201.0, "max_issues_count": 196.0, "max_forks_count": 155.0, "avg_line_length": 28.1875, "max_line_length": 91, "alphanum_fraction": 0.7716186253}
using System; using System.Collections.Generic; using System.Threading.Tasks; using GitLabApiClient.Internal.Paths; using GitLabApiClient.Models.Iterations.Requests; using GitLabApiClient.Models.Iterations.Responses; namespace GitLabApiClient { public interface IIterationsClient { Task<IList<Iteration>> GetAsync(ProjectId projectId = null, GroupId groupId = null, Action<IterationsQueryOptions> options = null); } }
TheStack
e073fec47740f33a901db963b1d5f283a3b16075
C#code:C#
{"size": 366, "ext": "cs", "max_stars_repo_path": "AxGridUnityTools/Base/Binder.cs", "max_stars_repo_name": "Deprion/AxGridTools", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AxGridUnityTools/Base/Binder.cs", "max_issues_repo_name": "Deprion/AxGridTools", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AxGridUnityTools/Base/Binder.cs", "max_forks_repo_name": "Deprion/AxGridTools", "max_forks_repo_forks_event_min_datetime": "2021-04-12T11:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T11:17:56.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 22.875, "max_line_length": 102, "alphanum_fraction": 0.6202185792}
using AxGrid.Model; using UnityEngine; namespace AxGrid.Base { public class Binder : MonoBehaviourExt { [Tooltip("Use Global Model")] public bool globalModel = false; /// <summary> /// Proxy /// </summary> protected override DynamicModel Model => globalModel ? Settings.GlobalModel : Settings.Model; } }
TheStack
e0747de47a52c068f006b905f5391609f6fbf1ff
C#code:C#
{"size": 1699, "ext": "cs", "max_stars_repo_path": "src/doteasy.rpc.core/Runtime/Communally/Entitys/ServiceDescriptorExtensions.cs", "max_stars_repo_name": "steveleeCN87/easy.rpc", "max_stars_repo_stars_event_min_datetime": "2018-12-04T08:39:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:10:14.000Z", "max_issues_repo_path": "src/doteasy.rpc.core/Runtime/Communally/Entitys/ServiceDescriptorExtensions.cs", "max_issues_repo_name": "steveleeCN87/easy.rpc", "max_issues_repo_issues_event_min_datetime": "2020-09-14T03:24:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-14T03:24:12.000Z", "max_forks_repo_path": "src/doteasy.rpc.core/Runtime/Communally/Entitys/ServiceDescriptorExtensions.cs", "max_forks_repo_name": "steveleeCN87/easy.rpc", "max_forks_repo_forks_event_min_datetime": "2018-12-12T01:10:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T01:08:36.000Z"}
{"max_stars_count": 65.0, "max_issues_count": 1.0, "max_forks_count": 31.0, "avg_line_length": 32.6730769231, "max_line_length": 108, "alphanum_fraction": 0.5779870512}
namespace DotEasy.Rpc.Core.Runtime.Communally.Entitys { /// <summary> /// 服务描述符扩展方法 /// </summary> public static class ServiceDescriptorExtensions { /// <summary> /// 获取组名称 /// </summary> /// <param name="descriptor">服务描述符</param> /// <returns>组名称</returns> public static string GroupName(this ServiceDescriptor descriptor) { return descriptor.GetMetadata<string>("GroupName"); } /// <summary> /// 设置组名称 /// </summary> /// <param name="descriptor">服务描述符</param> /// <param name="groupName">组名称</param> /// <returns>服务描述符</returns> public static ServiceDescriptor GroupName(this ServiceDescriptor descriptor, string groupName) { descriptor.Metadatas["GroupName"] = groupName; return descriptor; } /// <summary> /// 设置是否等待执行 /// </summary> /// <param name="descriptor">服务描述符</param> /// <param name="waitExecution">如果需要等待执行则为true,否则为false,默认为true</param> /// <returns></returns> public static ServiceDescriptor WaitExecution(this ServiceDescriptor descriptor, bool waitExecution) { descriptor.Metadatas["WaitExecution"] = waitExecution; return descriptor; } /// <summary> /// 获取释放等待执行的设置 /// </summary> /// <param name="descriptor">服务描述符</param> /// <returns>如果需要等待执行则为true,否则为false,默认为true</returns> public static bool WaitExecution(this ServiceDescriptor descriptor) { return descriptor.GetMetadata("WaitExecution", true); } } }
TheStack
e0747e91b7657d16b417f84496677310d8a3e944
C#code:C#
{"size": 1015, "ext": "cs", "max_stars_repo_path": "AuroraNative/Abstract/Groups/HonorListInfo.cs", "max_stars_repo_name": "fossabot/AuroraNative", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AuroraNative/Abstract/Groups/HonorListInfo.cs", "max_issues_repo_name": "fossabot/AuroraNative", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AuroraNative/Abstract/Groups/HonorListInfo.cs", "max_forks_repo_name": "fossabot/AuroraNative", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.5555555556, "max_line_length": 98, "alphanum_fraction": 0.5290640394}
using Newtonsoft.Json; namespace AuroraNative { /// <summary> /// 群荣誉详细信息 抽象类 /// </summary> public sealed class HonorListInfo { #region --属性-- /// <summary> /// QQ号 /// </summary> [JsonProperty(PropertyName = "user_id")] public long UserID; /// <summary> /// 昵称 /// </summary> [JsonProperty(PropertyName = "nickname")] public string NickName; /// <summary> /// 头像URL /// </summary> [JsonProperty(PropertyName = "avatar")] public string Avater; /// <summary> /// 荣誉描述 /// </summary> [JsonProperty(PropertyName = "description", NullValueHandling = NullValueHandling.Ignore)] public string Description; /// <summary> /// 持续天数 /// </summary> [JsonProperty(PropertyName = "day_count", NullValueHandling = NullValueHandling.Ignore)] public string DayCount; #endregion } }
TheStack
e076fc3c39c6cba366e32e8a0cfa16bb8adc5bf1
C#code:C#
{"size": 292, "ext": "cs", "max_stars_repo_path": "NWN.Toolbox/src/Blueprints/IBlueprint.cs", "max_stars_repo_name": "Canibaz/NWN.Toolbox", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NWN.Toolbox/src/Blueprints/IBlueprint.cs", "max_issues_repo_name": "Canibaz/NWN.Toolbox", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NWN.Toolbox/src/Blueprints/IBlueprint.cs", "max_forks_repo_name": "Canibaz/NWN.Toolbox", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 16.2222222222, "max_line_length": 50, "alphanum_fraction": 0.6849315068}
using Anvil.API; namespace Jorteck.Toolbox { public interface IBlueprint { public string FullName { get; } public string Name { get; } public string Category { get; } public BlueprintObjectType ObjectType { get; } public NwObject Create(Location location); } }
TheStack
e077011d9af27b27922c4a407f9629206c3006ec
C#code:C#
{"size": 4078, "ext": "cs", "max_stars_repo_path": "PartialClassSample.Api.Tests/RegisterService/AuthenticateUserAsyncUnitTests.cs", "max_stars_repo_name": "fossabot/partial-class-sample", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PartialClassSample.Api.Tests/RegisterService/AuthenticateUserAsyncUnitTests.cs", "max_issues_repo_name": "fossabot/partial-class-sample", "max_issues_repo_issues_event_min_datetime": "2021-04-27T06:24:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T00:48:06.000Z", "max_forks_repo_path": "PartialClassSample.Api.Tests/RegisterService/AuthenticateUserAsyncUnitTests.cs", "max_forks_repo_name": "fossabot/partial-class-sample", "max_forks_repo_forks_event_min_datetime": "2021-04-27T06:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T06:01:30.000Z"}
{"max_stars_count": null, "max_issues_count": 37.0, "max_forks_count": 1.0, "avg_line_length": 40.78, "max_line_length": 106, "alphanum_fraction": 0.6410004904}
using FluentAssertions; using Messages.Core; using Messages.Core.Enums; using Moq; using PartialClassSample.Api.Messages.RequestMessage; using PartialClassSample.Api.Messages.ResponseMessage; using System.Threading.Tasks; using Xunit; namespace PartialClassSample.Api.Tests.RegisterService { public class AuthenticateUserAsyncUnitTests : RegisterServiceUnitTests { protected override void BeforeCreateService() { _uow.Setup(_ => _.CommitAsync()); } [Fact] public async Task AuthenticateAsync_ShouldReturnBusinessError_PasswordIsEmpty() { _registerRepository.Setup(_ => _.FindAsync(It.IsAny<string>())); var requestMessage = AuthenticateUserRequestMessageFake(password: string.Empty); var response = await RegisterService.AuthenticateUserAsync(requestMessage); response.Should().NotBeNull(); response.HasError.Should().BeTrue(); response.Messages.Should().HaveCount(1); response.Messages.Should().Contain(message => message.Property.Equals("Password")); response.Data.HasValue.Should().BeFalse(); response.Data.Value.Should().BeNull(); _registerRepository.Verify(_ => _.AddAsync(It.IsAny<Models.Register>()), Times.Never); _uow.Verify(_ => _.CommitAsync(), Times.Never); } [Fact] public async Task AuthenticateAsync_ShouldReturnBusinessError_RegisterNotFound() { _registerRepository.Setup(_ => _.FindAsync(It.IsAny<string>())) .ReturnsAsync(Maybe<Models.Register>.Create()) .Verifiable(); var requestMessage = AuthenticateUserRequestMessageFake(); var response = await RegisterService.AuthenticateUserAsync(requestMessage); response.Should().NotBeNull(); response.HasError.Should().BeTrue(); response.Messages.Should().HaveCount(1); response.Messages.Should().Contain(message => message.Property.Equals("Email")); response.Data.HasValue.Should().BeFalse(); response.Data.Value.Should().BeNull(); _registerRepository.Verify(); _uow.Verify(_ => _.CommitAsync(), Times.Never); } [Fact] public async Task AuthenticateAsync_ShouldReturnBusinessError_InvalidPassword() { _registerRepository.Setup(_ => _.FindAsync(It.IsAny<string>())) .ReturnsAsync(Maybe<Models.Register>.Create(RegisterFake())) .Verifiable(); var requestMessage = AuthenticateUserRequestMessageFake(password: "abc123"); var response = await RegisterService.AuthenticateUserAsync(requestMessage); response.Should().NotBeNull(); response.HasError.Should().BeTrue(); response.Messages.Should().HaveCount(1); response.Messages.Should().Contain(message => message.Type.Equals(MessageType.BusinessError)); response.Data.HasValue.Should().BeFalse(); response.Data.Value.Should().BeNull(); _registerRepository.Verify(); _uow.Verify(_ => _.CommitAsync(), Times.Never); } [Fact] public async Task AuthenticateAsync_ShouldReturnSuccess() { _registerRepository.Setup(_ => _.FindAsync(It.IsAny<string>())) .ReturnsAsync(Maybe<Models.Register>.Create(RegisterFake())) .Verifiable(); var requestMessage = AuthenticateUserRequestMessageFake(); var response = await RegisterService.AuthenticateUserAsync(requestMessage); response.Should().NotBeNull(); response.HasError.Should().BeFalse(); response.Messages.Should().HaveCount(0); response.Data.HasValue.Should().BeTrue(); response.Data.Value.Should().BeOfType(typeof(RegisterResponseMessage)); _registerRepository.Verify(); _uow.Verify(_ => _.CommitAsync(), Times.Never); } } }
TheStack
e0770d42d660354ab12e6df190845bb96c889eda
C#code:C#
{"size": 3958, "ext": "cs", "max_stars_repo_path": "Library/PackageCache/[email protected]/Editor/Tools/Weaver/MonoBehaviourProcessor.cs", "max_stars_repo_name": "theDawckta/VRQuarterbackChallenge", "max_stars_repo_stars_event_min_datetime": "2019-12-16T20:54:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T11:29:35.000Z", "max_issues_repo_path": "Library/PackageCache/[email protected]/Editor/Tools/Weaver/MonoBehaviourProcessor.cs", "max_issues_repo_name": "theDawckta/VRQuarterbackChallenge", "max_issues_repo_issues_event_min_datetime": "2021-02-20T10:42:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-11T14:11:51.000Z", "max_forks_repo_path": "Library/PackageCache/[email protected]/Editor/Tools/Weaver/MonoBehaviourProcessor.cs", "max_forks_repo_name": "theDawckta/VRQuarterbackChallenge", "max_forks_repo_forks_event_min_datetime": "2019-12-19T14:57:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:59:59.000Z"}
{"max_stars_count": 461.0, "max_issues_count": 22.0, "max_forks_count": 186.0, "avg_line_length": 40.387755102, "max_line_length": 187, "alphanum_fraction": 0.4792824659}
using System; using System.Linq; using Mono.Cecil; namespace Unity.UNetWeaver { class MonoBehaviourProcessor { TypeDefinition m_td; Weaver m_Weaver; public MonoBehaviourProcessor(TypeDefinition td, Weaver weaver) { m_td = td; m_Weaver = weaver; } public void Process() { ProcessSyncVars(); ProcessMethods(); } void ProcessSyncVars() { // find syncvars foreach (FieldDefinition fd in m_td.Fields) { foreach (var ca in fd.CustomAttributes) { if (ca.AttributeType.FullName == m_Weaver.SyncVarType.FullName) { Log.Error("Script " + m_td.FullName + " uses [SyncVar] " + fd.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } } if (Helpers.InheritsFromSyncList(fd.FieldType, m_Weaver)) { Log.Error(string.Format("Script {0} defines field {1} with type {2}, but it's not a NetworkBehaviour", m_td.FullName, fd.Name, Helpers.PrettyPrintType(fd.FieldType))); m_Weaver.fail = true; } } } void ProcessMethods() { // find command and RPC functions foreach (MethodDefinition md in m_td.Methods) { foreach (var ca in md.CustomAttributes) { if (ca.AttributeType.FullName == m_Weaver.CommandType.FullName) { Log.Error("Script " + m_td.FullName + " uses [Command] " + md.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } if (ca.AttributeType.FullName == m_Weaver.ClientRpcType.FullName) { Log.Error("Script " + m_td.FullName + " uses [ClientRpc] " + md.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } if (ca.AttributeType.FullName == m_Weaver.TargetRpcType.FullName) { Log.Error("Script " + m_td.FullName + " uses [TargetRpc] " + md.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } var attrName = ca.Constructor.DeclaringType.ToString(); if (attrName == "UnityEngine.Networking.ServerAttribute") { Log.Error("Script " + m_td.FullName + " uses the attribute [Server] on the method " + md.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } else if (attrName == "UnityEngine.Networking.ServerCallbackAttribute") { Log.Error("Script " + m_td.FullName + " uses the attribute [ServerCallback] on the method " + md.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } else if (attrName == "UnityEngine.Networking.ClientAttribute") { Log.Error("Script " + m_td.FullName + " uses the attribute [Client] on the method " + md.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } else if (attrName == "UnityEngine.Networking.ClientCallbackAttribute") { Log.Error("Script " + m_td.FullName + " uses the attribute [ClientCallback] on the method " + md.Name + " but is not a NetworkBehaviour."); m_Weaver.fail = true; } } } } }; }
TheStack
e0794055cf5d96c832ac176c3ef3bb0e4630221c
C#code:C#
{"size": 3222, "ext": "cs", "max_stars_repo_path": "Hrimsoft.Core/Exceptions/ConfigurationException.cs", "max_stars_repo_name": "Basim108/hrimsoft.core", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hrimsoft.Core/Exceptions/ConfigurationException.cs", "max_issues_repo_name": "Basim108/hrimsoft.core", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hrimsoft.Core/Exceptions/ConfigurationException.cs", "max_forks_repo_name": "Basim108/hrimsoft.core", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 36.6136363636, "max_line_length": 122, "alphanum_fraction": 0.6139044072}
using System; using System.Runtime.Serialization; namespace Hrimsoft.Core.Exceptions { /// <inheritdoc /> /// <summary> /// Any error related to wrong or missed configuration /// </summary> public class ConfigurationException : ApplicationException { /// <inheritdoc /> public ConfigurationException() : base("Something wrong with application configuration") { } /// <inheritdoc /> public ConfigurationException(string message) : base(message) { } /// <inheritdoc /> public ConfigurationException(string message, Exception innerException) : base(message, innerException) { } /// <inheritdoc /> public ConfigurationException(string sectionName, string key) : base($"Configuration is wrong. Section name is '{sectionName ?? "root"}' key name is '{key}'") { this.ConfigurationSection = sectionName ?? "root"; this.ConfigurationKey = key; } /// <summary> /// Initializes a new instance of the <see cref="T:System.ApplicationException"></see> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> protected ConfigurationException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) throw new ArgumentNullException(nameof(info)); this.ConfigurationSection = info.GetString(nameof(this.Section)); this.ConfigurationKey = info.GetString(nameof(this.Key)); } /// <summary> /// Serialize current instance of exception /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); base.GetObjectData(info, context); info.AddValue(nameof(this.Section), this.Section); info.AddValue(nameof(this.Key), this.Key); } /// <summary> /// ConfigurationName of the section that is missing or contains wrong configuration /// </summary> protected string ConfigurationSection; /// <summary> /// ConfigurationName of the section that is missing or contains wrong configuration /// </summary> public string Section => ConfigurationSection; /// <summary> /// ConfigurationName of the configuration key that is missing or contains wrong value /// </summary> public string Key => ConfigurationKey; /// <summary> /// ConfigurationName of the configuration key that is missing or contains wrong value /// </summary> protected string ConfigurationKey; } }
TheStack
e07a02c9264c7e9e1ab8a387dd700483a3d3d6a8
C#code:C#
{"size": 5979, "ext": "cs", "max_stars_repo_path": "Website/DesktopModules/Hotcakes/Core/Admin/Parts/ContentBlocks/CategoryRotator/Editor.ascx.cs", "max_stars_repo_name": "puresystems/hotcakes-commerce-core", "max_stars_repo_stars_event_min_datetime": "2018-09-20T19:53:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T00:14:02.000Z", "max_issues_repo_path": "Website/DesktopModules/Hotcakes/Core/Admin/Parts/ContentBlocks/CategoryRotator/Editor.ascx.cs", "max_issues_repo_name": "puresystems/hotcakes-commerce-core", "max_issues_repo_issues_event_min_datetime": "2018-09-18T17:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T09:47:29.000Z", "max_forks_repo_path": "Website/DesktopModules/Hotcakes/Core/Admin/Parts/ContentBlocks/CategoryRotator/Editor.ascx.cs", "max_forks_repo_name": "puresystems/hotcakes-commerce-core", "max_forks_repo_forks_event_min_datetime": "2018-09-20T19:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T06:11:46.000Z"}
{"max_stars_count": 29.0, "max_issues_count": 177.0, "max_forks_count": 37.0, "avg_line_length": 35.5892857143, "max_line_length": 101, "alphanum_fraction": 0.5562803144}
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections.ObjectModel; using System.Linq; using System.Web.UI.WebControls; using Hotcakes.Commerce.Catalog; using Hotcakes.Commerce.Content; using Hotcakes.Modules.Core.Admin.AppCode; using Hotcakes.Web; namespace Hotcakes.Modules.Core.Admin.Parts.ContentBlocks.CategoryRotator { partial class Editor : HccContentBlockPart { private ContentBlock _block; private ContentBlock Block { get { return _block ?? (_block = HccApp.ContentServices.Columns.FindBlock(BlockId)); } } protected override void OnInit(EventArgs e) { base.OnInit(e); ucCategoryPicker.AddSelectedIds += ucCategoryPicker_AddSelectedIds; gvCategories.RowDataBound += gvCategories_RowDataBound; } private void gvCategories_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var bvin = (string) gvCategories.DataKeys[e.Row.DataItemIndex].Value; var settings = Block.Lists.FindList("Categories"); var item = settings.FirstOrDefault(s => s.Setting1 == bvin); e.Row.Attributes["id"] = item.Id; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!IsPostBack) { LoadData(); } } protected void ucCategoryPicker_AddSelectedIds(object sender, UIEventArgs<string> e) { var block = HccApp.ContentServices.Columns.FindBlock(BlockId); if (block != null) { var settings = block.Lists.FindList("Categories"); foreach (var category in e.Items) { var add = true; foreach (var item in settings) { if (item.Setting1 == category) { add = false; break; } } if (add) { var c = new ContentBlockSettingListItem { Setting1 = category, ListName = "Categories" }; block.Lists.AddItem(c); HccApp.ContentServices.Columns.UpdateBlock(block); } } BindCategoryGridView(block); } } protected void btnOK_Click(object sender, EventArgs e) { var b = HccApp.ContentServices.Columns.FindBlock(BlockId); if (b != null) { b.BaseSettings.SetBoolSetting("ShowInOrder", chkShowInOrder.Checked); HccApp.ContentServices.Columns.UpdateBlock(b); } NotifyFinishedEditing(); } protected void gvCategories_RowDeleting(object sender, GridViewDeleteEventArgs e) { var b = HccApp.ContentServices.Columns.FindBlock(BlockId); var settings = b.Lists.FindList("Categories"); foreach (var item in settings) { if (item.Setting1 == (string) gvCategories.DataKeys[e.RowIndex].Value) { b.Lists.RemoveItem(item.Id); } } HccApp.ContentServices.Columns.UpdateBlock(b); BindCategoryGridView(b); } private void BindCategoryGridView(ContentBlock b) { var settings = b.Lists.FindList("Categories"); var categories = new Collection<Category>(); foreach (var item in settings) { var category = HccApp.CatalogServices.Categories.Find(item.Setting1); if (category != null && category.Bvin != string.Empty) { categories.Add(category); } } gvCategories.DataSource = categories; gvCategories.DataBind(); ucCategoryPicker.ReservedIds = categories.Select(c => c.Bvin).ToList(); ucCategoryPicker.BindCategories(); } private void LoadData() { var b = HccApp.ContentServices.Columns.FindBlock(BlockId); if (b != null) { chkShowInOrder.Checked = b.BaseSettings.GetBoolSetting("ShowInOrder"); } BindCategoryGridView(b); } } }
TheStack
e07af19df0223cb5325af79b51c2d2e7f05f225d
C#code:C#
{"size": 2916, "ext": "cs", "max_stars_repo_path": "TencentCloud/Tiw/V20190919/Models/StreamLayout.cs", "max_stars_repo_name": "TencentCloud/tencentcloud-sdk-dotnet-intl-en", "max_stars_repo_stars_event_min_datetime": "2020-12-07T13:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T13:02:41.000Z", "max_issues_repo_path": "TencentCloud/Tiw/V20190919/Models/StreamLayout.cs", "max_issues_repo_name": "TencentCloud/tencentcloud-sdk-dotnet-intl-en", "max_issues_repo_issues_event_min_datetime": "2021-04-26T00:59:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T00:59:43.000Z", "max_forks_repo_path": "TencentCloud/Tiw/V20190919/Models/StreamLayout.cs", "max_forks_repo_name": "TencentCloud/tencentcloud-sdk-dotnet-intl-en", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 20.0, "max_forks_count": null, "avg_line_length": 39.9452054795, "max_line_length": 175, "alphanum_fraction": 0.6481481481}
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Tiw.V20190919.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class StreamLayout : AbstractModel { /// <summary> /// Stream layout configuration /// </summary> [JsonProperty("LayoutParams")] public LayoutParams LayoutParams{ get; set; } /// <summary> /// Video stream ID /// Description of the possible video stream ID values: /// 1. tic_record_user: the current picture is used to display the whiteboard video stream. /// 2. tic_substream: the current picture is used to display the auxiliary video stream. /// 3. Specific user ID: the current picture is used to display the video stream of a specific user. /// 4.Left empty: the current picture is vacant for new video stream. /// </summary> [JsonProperty("InputStreamId")] public string InputStreamId{ get; set; } /// <summary> /// Background color in RGB format, such as "#FF0000" for red. The default color is black. /// </summary> [JsonProperty("BackgroundColor")] public string BackgroundColor{ get; set; } /// <summary> /// Video filling mode. /// /// 0: self-adaption mode. Scales the video proportionally to completely display it in the specified area. In this mode, there may be black bars. /// 1: full-screen mode. Scales the video to make it fill the entire specified area. In this mode, no black bars will appear, but the video may not be displayed fully. /// </summary> [JsonProperty("FillMode")] public long? FillMode{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamObj(map, prefix + "LayoutParams.", this.LayoutParams); this.SetParamSimple(map, prefix + "InputStreamId", this.InputStreamId); this.SetParamSimple(map, prefix + "BackgroundColor", this.BackgroundColor); this.SetParamSimple(map, prefix + "FillMode", this.FillMode); } } }
TheStack
e07af27a91d5eaa4a3de60df695544819bddf1e8
C#code:C#
{"size": 3221, "ext": "cs", "max_stars_repo_path": "BALayer/BAL_Login.cs", "max_stars_repo_name": "ssbalakumar/HRM", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BALayer/BAL_Login.cs", "max_issues_repo_name": "ssbalakumar/HRM", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BALayer/BAL_Login.cs", "max_forks_repo_name": "ssbalakumar/HRM", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.7654320988, "max_line_length": 134, "alphanum_fraction": 0.3682086309}
using System; using System.Collections.Generic; using System.Data; using System.Linq; using DALayer; using EntityLayer; namespace BALayer { public class BAL_Login { private HRMDataContext dbcontext = new HRMDataContext(); public List<Entity_HRM> GetLoginDetails(string strType, DateTime startDate, DateTime enddate) { List<Entity_HRM> listLogin = new List<Entity_HRM>(); try { var qry = (from log in dbcontext.ctblLoginDetails join user in dbcontext.mtblUsers on log.intId equals user.intUserId join userrole in dbcontext.mtblUserRoles on user.intUserRoleId equals userrole.intUserRoleId where log.varType == "A" select new { Id = "-", Name = user.varUserName, UserType = userrole.varUserRole, log.varIPNo, log.dtDate }); if (!string.IsNullOrEmpty(strType)) { if (strType.Equals("E")) { qry = (from log in dbcontext.ctblLoginDetails join emp in dbcontext.mtblEmployees on log.intId equals emp.intEmpId where log.varType == "P" select new { Id = emp.varEmpId, Name = emp.varEmpName, UserType = "Employee", log.varIPNo, log.dtDate }); } var query = (from q in qry orderby Convert.ToDateTime(q.dtDate).Date descending where Convert.ToDateTime(q.dtDate).Date >= startDate && Convert.ToDateTime(q.dtDate).Date <= enddate select new { q.Id, q.Name, q.UserType, q.varIPNo, q.dtDate }).AsEnumerable(); foreach (var login in query) { listLogin.Add(new Entity_HRM { strUserId = login.Id, strLoginName = login.Name, UserType = login.UserType, dtDate = Convert.ToDateTime(login.dtDate), varIPNo = login.varIPNo }); } } } catch (Exception ex) { } return listLogin; } } }
TheStack
e07c94eefbea83436f198a932d952371abcb0dd6
C#code:C#
{"size": 7830, "ext": "cs", "max_stars_repo_path": "ENI_Projet_Sport/ENI_Projet_Sport/Controllers/RacesController.cs", "max_stars_repo_name": "Alexandre-Delaunay/ENI_Projet_Sport", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ENI_Projet_Sport/ENI_Projet_Sport/Controllers/RacesController.cs", "max_issues_repo_name": "Alexandre-Delaunay/ENI_Projet_Sport", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ENI_Projet_Sport/ENI_Projet_Sport/Controllers/RacesController.cs", "max_forks_repo_name": "Alexandre-Delaunay/ENI_Projet_Sport", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.3421052632, "max_line_length": 118, "alphanum_fraction": 0.5468710089}
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using BO.Models; using ENI_Projet_Sport.Models; using BO.Base; using BO.Services; using ENI_Projet_Sport.Extensions; using ENI_Projet_Sport.ViewModels; using Microsoft.AspNet.Identity.Owin; using Microsoft.AspNet.Identity; using System.Net.Http; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using ENI_Projet_Sport.Helpers; using System.Dynamic; using System.Web.Script.Serialization; namespace ENI_Projet_Sport.Controllers { public class RacesController : Controller { private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } private static ServiceLocator _serviceLocator = ServiceLocator.Instance; private static IServiceRace _serviceRace = _serviceLocator.GetService<IServiceRace>(); private static IServiceRaceType _serviceRaceType = _serviceLocator.GetService<IServiceRaceType>(); private static IServicePOI _servicePOI = _serviceLocator.GetService<IServicePOI>(); private static IServiceCategoryPOI _serviceCategoryPOI = _serviceLocator.GetService<IServiceCategoryPOI>(); // GET: Races public ActionResult Index() { var getAll = _serviceRace.GetAll().ToList().Select(e => e.Map<ViewModels.RaceViewModel>()).ToList(); var user = UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user.Result != null) { List<Race> UserRaces = user.Result.person.Races; var typeUnit = user.Result.displayConfiguration.TypeUnite; getAll.ForEach(r => { if (typeUnit.Equals(TypeUnit.Miles)) { r.Distance = (float)UniteHelper.MeterToMiles(r.Distance); } else { r.Distance = (float)UniteHelper.MeterToKm(r.Distance); } if (UserRaces.Select(race => race.Id).Contains(r.Id)) { r.isSubscribe = true; } }); } return View(getAll); } // GET: Races/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Race race = _serviceRace.GetById(id ?? 1); if (race == null) { return HttpNotFound(); } var raceVM = race.Map<RaceViewModel>(); var user = UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { var typeUnit = user.Result.displayConfiguration.TypeUnite; if (typeUnit.Equals(TypeUnit.Miles)) { raceVM.Distance = (float)UniteHelper.MeterToMiles(raceVM.Distance); } else { raceVM.Distance = (float)UniteHelper.MeterToKm(raceVM.Distance); } } return View(raceVM); } // GET: Races/Create public ActionResult Create() { return View(new CreateEditRaceViewModel()); } // POST: Races/Create [HttpPost] public ActionResult Create(CreateEditRaceViewModel raceVM) { dynamic errorObj = new ExpandoObject(); if (raceVM.POIs.Count() < 2) errorObj.POIs = "Le nombre de POI est insuffisant."; if (raceVM.City==null) errorObj.City = "Le champ Ville doit être renseigné."; if (DateTime.Compare(raceVM.DateRace, DateTime.Now) < 0) errorObj.DateRace = "La date de la course doit être supérieure ou égale à la date du jour."; if (raceVM.Name == null) errorObj.Name = "Le champ Nom de la course doit être renseigné."; if (raceVM.PlacesNumber <= 0) errorObj.PlacesNumber = "Le nombre de place doit être supérieur à 0."; if (raceVM.Price == 0) errorObj.Price = "Le prix de la course doit être supérieur à 0."; if (raceVM.RaceTypeId == null) errorObj.RaceTypeId = "Le champ Type de course doit être renseigné."; if (raceVM.ZipCode == null) errorObj.ZipCode = "Le champ Code postal doit être renseigné."; if (ModelState.IsValid) { raceVM.DateMAJ = DateTime.Now; Race race = raceVM.Map<Race>(); var category = _serviceCategoryPOI.GetAll().Where(c => c.Name.Equals("Checkpoint")).FirstOrDefault(); race.POIs.ForEach(p => { p.DateMAJ = DateTime.Now; p.CategoryPOI = category; }); category = _serviceCategoryPOI.GetAll().Where(c => c.Name.Equals("Départ")).FirstOrDefault(); race.POIs.First().CategoryPOI = category; category = _serviceCategoryPOI.GetAll().Where(c => c.Name.Equals("Arrivée")).FirstOrDefault(); race.POIs.Last().CategoryPOI = category; _serviceRace.Add(race); _serviceRace.Commit(); return View(raceVM); } string json = new JavaScriptSerializer().Serialize(errorObj); return new HttpStatusCodeResult(HttpStatusCode.BadRequest, json); } // GET: Races/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Race race = _serviceRace.GetById(id ?? 1); if (race == null) { return HttpNotFound(); } return View(race.Map<CreateEditRaceViewModel>()); } // POST: Races/Edit/5 [HttpPost] public ActionResult Edit(CreateEditRaceViewModel raceVM) { raceVM.DateMAJ = DateTime.Now; Race race_from_db = _serviceRace.GetById(raceVM.Id); raceVM.POIs = race_from_db.POIs.Select(s => s.Map<POIViewModel>()).ToList(); raceVM.Distance = race_from_db.Distance; raceVM.Map(race_from_db); _serviceRace.Commit(); return RedirectToAction("index"); return View(raceVM); } // GET: Races/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Race race = _serviceRace.GetById(id ?? 1); if (race == null) { return HttpNotFound(); } return View(race.Map<RaceViewModel>()); } // POST: Races/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Race race = _serviceRace.GetById(id); _serviceRace.Delete(race); _serviceRace.Commit(); return RedirectToAction("Index"); } } }
TheStack
e07ca7bb34284a8b6051dcb39ea67418aa4b1efb
C#code:C#
{"size": 5525, "ext": "cs", "max_stars_repo_path": "Tiled/LayerChunkedRenderer.cs", "max_stars_repo_name": "PokeD/PokeD.Client", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tiled/LayerChunkedRenderer.cs", "max_issues_repo_name": "PokeD/PokeD.Client", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tiled/LayerChunkedRenderer.cs", "max_forks_repo_name": "PokeD/PokeD.Client", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 41.2313432836, "max_line_length": 202, "alphanum_fraction": 0.570678733}
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using PokeD.CPGL.Components; namespace PokeD.CPGL.Tiled { public class LayerChunkedRenderer : BaseLayerRenderer { private class LayerChunk : DrawableComponent { public const int TileCount = 24; private MapWrapper Map { get; } private LayerWrapper Layer { get; } private SpriteBatch SpriteBatch { get; } private SpriteBatch ScalingSpriteBatch { get; } private RenderTarget2D RenderTarget { get; } private Point MinTilePoint { get; } private Point MaxTilePoint { get; } public Vector2 DrawPosition => MinTilePoint.ToVector2() * new Vector2(Map.TileWidth, Map.TileHeight) * Map.MapScale; public Vector2 DrawSize => new Vector2(TileCount) * new Vector2(Map.TileWidth, Map.TileHeight) * Map.MapScale; public Rectangle DrawRectangle => new Rectangle((int) DrawPosition.X, (int) DrawPosition.Y, (int) DrawSize.X, (int) DrawSize.Y); public LayerChunk(MapWrapper map, LayerWrapper layer, Point minTilePoint, SpriteBatch spriteBatch) : base(map) { Map = map; Layer = layer; MinTilePoint = minTilePoint; MaxTilePoint = MinTilePoint + new Point(TileCount, TileCount); SpriteBatch = spriteBatch; ScalingSpriteBatch = new SpriteBatch(GraphicsDevice); RenderTarget = new RenderTarget2D(GraphicsDevice, TileCount * Map.TileWidth, TileCount * Map.TileHeight, false, GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.None); Generate(); } private void Generate() { GraphicsDevice.SetRenderTarget(RenderTarget); GraphicsDevice.Clear(Color.Transparent); using (var spriteBatch = new SpriteBatch(GraphicsDevice)) { spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp); for (int x = MinTilePoint.X, pX = 0; x < MaxTilePoint.X; x++, pX += Map.TileWidth) for (int y = MinTilePoint.Y, pY = 0; y < MaxTilePoint.Y; y++, pY += Map.TileHeight) { var index = x + y * Map.WidthInTiles; if (index < Layer.Tiles.Count) { var tile = Layer.Tiles[index]; var drawPosition = new Vector2(pX, pY); if (tile.GID != 0) spriteBatch.Draw(tile.Texture, drawPosition, tile.TextureRectangle, Color.White); } } spriteBatch.End(); } GraphicsDevice.SetRenderTarget(null); } public override void Draw(GameTime gameTime) { /* GraphicsDevice.SetRenderTarget(ScaledRenderTarget); GraphicsDevice.Clear(Color.Transparent); effect.TextureSize = new Vector2(RenderTarget.Width, RenderTarget.Height); ScalingSpriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, effect, null); ScalingSpriteBatch.Draw(RenderTarget, new Rectangle(0, 0, ScaledRenderTarget.Width, ScaledRenderTarget.Height), Color.White); ScalingSpriteBatch.End(); GraphicsDevice.SetRenderTarget(null); */ SpriteBatch.Draw(RenderTarget, DrawPosition, RenderTarget.Bounds, Color.White, 0.0f, Vector2.Zero, Map.MapScale, SpriteEffects.None, 0.0f); } public override void Update(GameTime gameTime) { } protected override void Dispose(bool disposing) { RenderTarget?.Dispose(); base.Dispose(disposing); } } private IList<LayerChunk> Chunks { get; } = new List<LayerChunk>(); public LayerChunkedRenderer(MapWrapper map, LayerWrapper layer, SpriteBatch spriteBatch) : base(map, layer, spriteBatch) { Generate(); } private void Generate() { var xMax = (int) Math.Ceiling((double) (Map.WidthInTiles / (double) LayerChunk.TileCount)); var yMax = (int) Math.Ceiling((double) (Map.HeightInTiles / (double) LayerChunk.TileCount)); for (var x = 0; x < xMax; x++) for (var y = 0; y < yMax; y++) { Chunks.Add(new LayerChunk(Map, Layer, new Point(x * LayerChunk.TileCount, y * LayerChunk.TileCount), SpriteBatch)); } } public override void Draw(GameTime gameTime) { var boundingRectangle = Camera.BoundingRectangle; foreach (var chunk in Chunks.Where(chunk => chunk.DrawRectangle.Intersects(boundingRectangle))) chunk.Draw(gameTime); } public override void Update(GameTime gameTime) { foreach (var chunk in Chunks) chunk?.Update(gameTime); } protected override void Dispose(bool disposing) { foreach (var chunk in Chunks) chunk?.Dispose(); base.Dispose(disposing); } } }
TheStack
e07cc240742bf94b604ab9f590892e09f8c7c025
C#code:C#
{"size": 1409, "ext": "cs", "max_stars_repo_path": "sdk/dotnet/DataLoss/Outputs/PreventionJobTriggerInspectJobActionSaveFindingsOutputConfigTable.cs", "max_stars_repo_name": "sisisin/pulumi-gcp", "max_stars_repo_stars_event_min_datetime": "2018-06-18T19:16:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:06:48.000Z", "max_issues_repo_path": "sdk/dotnet/DataLoss/Outputs/PreventionJobTriggerInspectJobActionSaveFindingsOutputConfigTable.cs", "max_issues_repo_name": "sisisin/pulumi-gcp", "max_issues_repo_issues_event_min_datetime": "2018-06-22T19:41:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:33:53.000Z", "max_forks_repo_path": "sdk/dotnet/DataLoss/Outputs/PreventionJobTriggerInspectJobActionSaveFindingsOutputConfigTable.cs", "max_forks_repo_name": "sisisin/pulumi-gcp", "max_forks_repo_forks_event_min_datetime": "2018-06-19T01:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T22:43:37.000Z"}
{"max_stars_count": 121.0, "max_issues_count": 492.0, "max_forks_count": 43.0, "avg_line_length": 32.0227272727, "max_line_length": 116, "alphanum_fraction": 0.6479772889}
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.DataLoss.Outputs { [OutputType] public sealed class PreventionJobTriggerInspectJobActionSaveFindingsOutputConfigTable { /// <summary> /// Dataset ID of the table. /// </summary> public readonly string DatasetId; /// <summary> /// The Google Cloud Platform project ID of the project containing the table. /// </summary> public readonly string ProjectId; /// <summary> /// Name of the table. If is not set a new one will be generated for you with the following format: /// `dlp_googleapis_yyyy_mm_dd_[dlp_job_id]`. Pacific timezone will be used for generating the date details. /// </summary> public readonly string? TableId; [OutputConstructor] private PreventionJobTriggerInspectJobActionSaveFindingsOutputConfigTable( string datasetId, string projectId, string? tableId) { DatasetId = datasetId; ProjectId = projectId; TableId = tableId; } } }