content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
namespace SpecialOffers.SpecialOffers { using System; using System.Collections.Generic; using Events; using Microsoft.AspNetCore.Mvc; [Route("/offers")] public class SpecialOffersController : ControllerBase { private readonly IEventStore eventStore; private static readonly IDictionary<int, Offer> Offers = new Dictionary<int, Offer>(); public SpecialOffersController(IEventStore eventStore) => this.eventStore = eventStore; [HttpGet("{id:int}")] public ActionResult<Offer> GetOffer(int id) => Offers.ContainsKey(id) ? (ActionResult<Offer>) Ok(Offers[id]) : NotFound(); [HttpPost("")] public ActionResult<Offer> CreateOffer([FromBody] Offer offer) { var newUser = NewOffer(offer); return Created(new Uri($"/offers/{newUser.Id}", UriKind.Relative), newUser); } [HttpPut("{id:int}")] public Offer UpdateOffer(int id, [FromBody] Offer offer) { this.eventStore.RaiseEvent("SpecialOfferUpdated", new { OldOffer = Offers[id], NewOffer = offer }); return Offers[id] = offer; } [HttpDelete("{id:int}")] public ActionResult DeleteOffer(int id) { this.eventStore.RaiseEvent("SpecialOfferRemoved", new { Offer = Offers[id] }); Offers.Remove(id); return Ok(); } private Offer NewOffer(Offer offer) { var offerId = Offers.Count; var newOffer = offer with { Id = offerId}; this.eventStore.RaiseEvent("SpecialOfferCreated", newOffer); return Offers[offerId] = newOffer; } } public record Offer(string Description, int Id); }
29.327273
105
0.66212
[ "MIT" ]
horsdal/microservices-in-dotnet-book-second-edition
Chapter10/SpecialOffers/SpecialOffers/SpecialOffersController.cs
1,615
C#
// 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 Microsoft.Extensions.Logging; using Steeltoe.Messaging; using System; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; namespace Steeltoe.Integration.Channel { public abstract class AbstractMessageChannelWriter : ChannelWriter<IMessage> { protected AbstractMessageChannel channel; protected ILogger logger; protected AbstractMessageChannelWriter(AbstractMessageChannel channel, ILogger logger = null) { this.channel = channel ?? throw new ArgumentNullException(nameof(channel)); this.logger = logger; } public override bool TryComplete(Exception error = null) { return false; } public override bool TryWrite(IMessage message) { return channel.Send(message, 0); } public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default) { return cancellationToken.IsCancellationRequested ? new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken)) : new ValueTask<bool>(true); } public override ValueTask WriteAsync(IMessage message, CancellationToken cancellationToken = default) { if (TryWrite(message)) { return default; } return new ValueTask(Task.FromException(new MessageDeliveryException(message))); } } }
32.862745
155
0.677208
[ "Apache-2.0" ]
Chatina73/steeltoe
src/Integration/src/IntegrationBase/Channel/AbstractMessageChannelWriter.cs
1,678
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace eurorails.Core.Test { [TestFixture] public class TestBase { [Test] public void Works() { } } }
15.8
33
0.655063
[ "MIT" ]
eouw0o83hf/eurorails-on-clr
eurorails.Core.Test/TestBase.cs
318
C#
//----------------------------------------------------------------------- // Copyright 2016 Tobii AB (publ). All rights reserved. //----------------------------------------------------------------------- using System.Collections.Generic; using UnityEngine; namespace Tobii.Gaming.Internal { internal class MultiRaycastHistoricHitScore : IScorer { private static readonly float GainGazeDwellTime = 0.04f; private static readonly float LoseGazeDwellTime = 0.15f; private static readonly float Threshold = 0.06f; private readonly Dictionary<int, ScoredObject> _scoredObjects = new Dictionary<int, ScoredObject>(); private ScoredObject _focusedObject = ScoredObject.Empty(); private int _layerMask; public MultiRaycastHistoricHitScore() { MaximumDistance = GazeFocus.MaximumDistance; LayerMask = GazeFocus.LayerMask; } public MultiRaycastHistoricHitScore(float maximumDistance, int layerMask) { MaximumDistance = maximumDistance; LayerMask = layerMask; } private FocusedObject FocusedGameObject { get { if (_focusedObject.Equals(ScoredObject.Empty())) { return FocusedObject.Invalid; } return new FocusedObject(_focusedObject.GameObject); } } /// <summary> /// Maximum distance to detect gaze focus within. /// </summary> private float MaximumDistance { get; set; } /// <summary> /// Layers to detect gaze focus on. /// </summary> private LayerMask LayerMask { get { return _layerMask; } set { _layerMask = value.value; } } public FocusedObject GetFocusedObject(IEnumerable<GazePoint> lastGazePoints, Camera camera) { var gazePoints = new List<GazePoint>(); /*Note: Do not use LINQ here - too inefficient to be called every update.*/ foreach (var gazePoint in lastGazePoints) { if (gazePoint.IsValid) { gazePoints.Add(gazePoint); } } foreach (var gazePoint in gazePoints) { var objectsInGaze = FindObjectsInGaze(gazePoint.Screen, camera); UpdateFocusConfidenceScore(objectsInGaze); } var focusChallenger = FindFocusChallenger(); if (focusChallenger.GetScore() > _focusedObject.GetScore() + Threshold) { _focusedObject = focusChallenger; } return FocusedGameObject; } public IEnumerable<GameObject> GetObjectsInGaze(IEnumerable<GazePoint> lastGazePoints, Camera camera) { GetFocusedObject(lastGazePoints, camera); var objectsInGaze = new List<GameObject>(); /*Note: Do not use LINQ here - too inefficient to be called every update.*/ foreach (var scoredObject in _scoredObjects) { if (scoredObject.Value.GetScore() > 0.0f) { objectsInGaze.Add(scoredObject.Value.GameObject); } } return objectsInGaze; } public FocusedObject GetFocusedObject() { ClearFocusedObjectIfOld(); return FocusedGameObject; } public void Reconfigure(float maximumDistance, int layerMask) { Reset(); MaximumDistance = maximumDistance; LayerMask = layerMask; } public void RemoveObject(GameObject gameObject) { _scoredObjects.Remove(gameObject.GetInstanceID()); if (_focusedObject.GameObject.GetInstanceID() == gameObject.GetInstanceID()) { _focusedObject = ScoredObject.Empty(); } } public void Reset() { _scoredObjects.Clear(); } private IEnumerable<GameObject> FindObjectsInGaze(Vector2 gazePoint, Camera camera) { var objectsInGaze = new List<GameObject>(); float fovealAngle = 2.0f; float distanceGazeOriginToScreen_inches = 24f; // ~ 60 cm var dpi = Screen.dpi > 0 ? Screen.dpi : 100; float fovealRadius_inches = Mathf.Tan(fovealAngle * Mathf.Deg2Rad) * distanceGazeOriginToScreen_inches; int fovealRadius_pixels = Mathf.RoundToInt(fovealRadius_inches * dpi); var points = PatternGenerator.CreateCircularAreaUniformPattern(gazePoint, fovealRadius_pixels, 4); IEnumerable<RaycastHit> hitInfos; if (HitTestFromPoint.FindMultipleObjectsInWorldFromMultiplePoints(out hitInfos, points, camera, MaximumDistance, LayerMask)) { foreach (var raycastHit in hitInfos) { objectsInGaze.Add(raycastHit.collider.gameObject); } } return objectsInGaze; } private void UpdateFocusConfidenceScore(IEnumerable<GameObject> objectsInGaze) { foreach (var objectInGaze in objectsInGaze) { var instanceId = objectInGaze.GetInstanceID(); if (!_scoredObjects.ContainsKey(instanceId)) { if (!GazeFocus.IsFocusableObject(objectInGaze)) { continue; } _scoredObjects.Add(objectInGaze.GetInstanceID(), new ScoredObject(objectInGaze, GainGazeDwellTime, LoseGazeDwellTime)); } ScoredObject hitObject = _scoredObjects[instanceId]; hitObject.AddHit(Time.unscaledTime, Time.unscaledDeltaTime); } ClearFocusedObjectIfOld(); } private ScoredObject FindFocusChallenger() { ScoredObject topFocusChallenger = ScoredObject.Empty(); float topScore = 0.0f; foreach (var key in _scoredObjects.Keys) { ScoredObject scoredObject = _scoredObjects[key]; var score = scoredObject.GetScore(Time.unscaledTime - LoseGazeDwellTime, Time.unscaledTime - GainGazeDwellTime); if (score > topScore) { topScore = score; topFocusChallenger = scoredObject; } } return topFocusChallenger; } private void ClearFocusedObjectIfOld() { if (!_focusedObject.IsRecentlyHit()) { _focusedObject = ScoredObject.Empty(); } } } }
26.671569
124
0.701158
[ "Apache-2.0" ]
JJIKKYU/Text-Game-Project
2_Unity/CCMS/Assets/Tobii/Framework/Internal/MultiRaycastHistoricHitScore.cs
5,443
C#
namespace YourWaifu2x { public enum PageCategory { /// <summary> /// Reserved for samples placed on top with no category, eg: Home, Overview /// </summary> None, Theme, Components, Features, } }
18.642857
83
0.536398
[ "Apache-2.0" ]
Aloento/YourWaifu2x
YourWaifu2x.Shared/Entities/PageCategory.cs
261
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Livraria.Servico.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
47.220721
229
0.586521
[ "MIT" ]
sandrovasconcellos/Livraria_sql
Livraria/Livraria.Servico/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs
20,966
C#
using System; using System.Linq; namespace Chino { /// <summary> /// Summary information about recent exposures. /// /// This class is deprecated. /// no longer used with Exposure Window API. /// /// The client can get this information via ExposureNotificationClient.getExposureSummary(String). /// </summary> /// https://developers.google.com/android/reference/com/google/android/gms/nearby/exposurenotification/ExposureSummary public class ExposureSummary { /// <summary> /// Array of durations in milliseconds at certain radio signal attenuations. /// </summary> public int[] AttenuationDurationsInMillis { get; set; } /// <summary> /// Days since last match to a diagnosis key from the server. /// </summary> public int DaysSinceLastExposure { get; set; } /// <summary> /// Number of matched diagnosis keys. /// </summary> public ulong MatchedKeyCount { get; set; } /// <summary> /// The highest risk score of all exposure incidents, it will be a value 0-4096. /// </summary> public int MaximumRiskScore { get; set; } /// <summary> /// The summation of risk scores of all exposure incidents. /// </summary> public int SummationRiskScore { get; set; } public override bool Equals(object obj) { if (!(obj is ExposureSummary summary)) { return false; } bool attenuationDurationsInMillisEqual; if (AttenuationDurationsInMillis == summary.AttenuationDurationsInMillis) { attenuationDurationsInMillisEqual = true; } else if (AttenuationDurationsInMillis == null || summary.AttenuationDurationsInMillis == null) { attenuationDurationsInMillisEqual = false; } else { attenuationDurationsInMillisEqual = AttenuationDurationsInMillis.SequenceEqual(summary.AttenuationDurationsInMillis); } return attenuationDurationsInMillisEqual && DaysSinceLastExposure == summary.DaysSinceLastExposure && MatchedKeyCount == summary.MatchedKeyCount && MaximumRiskScore == summary.MaximumRiskScore && SummationRiskScore == summary.SummationRiskScore; } public override int GetHashCode() { return HashCode.Combine(AttenuationDurationsInMillis, DaysSinceLastExposure, MatchedKeyCount, MaximumRiskScore, SummationRiskScore); } } }
35.207792
144
0.603467
[ "MIT" ]
keiji/chino
Chino.Common/ExposureSummary.cs
2,713
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AnttechBlockchainDefinInsuranceApplyCreateResponse. /// </summary> public class AnttechBlockchainDefinInsuranceApplyCreateResponse : AopResponse { /// <summary> /// 保额 /// </summary> [XmlElement("amount")] public string Amount { get; set; } /// <summary> /// 投保单号 /// </summary> [XmlElement("apply_no")] public string ApplyNo { get; set; } /// <summary> /// 保险止期 /// </summary> [XmlElement("insure_end_date")] public string InsureEndDate { get; set; } /// <summary> /// 保险起期 /// </summary> [XmlElement("insure_start_date")] public string InsureStartDate { get; set; } /// <summary> /// 个性化参数 /// </summary> [XmlElement("parm")] public string Parm { get; set; } /// <summary> /// 保单号 /// </summary> [XmlElement("policy_no")] public string PolicyNo { get; set; } /// <summary> /// 保费 /// </summary> [XmlElement("premium")] public string Premium { get; set; } /// <summary> /// 请求交易流水号 /// </summary> [XmlElement("trade_no")] public string TradeNo { get; set; } } }
24.45
82
0.480573
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/AnttechBlockchainDefinInsuranceApplyCreateResponse.cs
1,529
C#
using Eaf.Reflection.Extensions; using Eaf.Resources.Embedded; using Shouldly; using System.Linq; using Xunit; namespace Eaf.Tests.Resources.Embedded { public class EmbeddedResourceTests { private readonly IEmbeddedResourceManager _embeddedResourceManager; public EmbeddedResourceTests() { var configuration = new EmbeddedResourcesConfiguration(); configuration.Sources.Add( new EmbeddedResourceSet( "/MyApp/MyResources/", GetType().GetAssembly(), "Eaf.Tests.Resources.Embedded.MyResources" ) ); _embeddedResourceManager = new EmbeddedResourceManager(configuration); } [Fact] public void Should_Define_And_Get_Embedded_Resources() { var filepath = "/MyApp/MyResources/js/MyScriptFile1.js"; var resource = _embeddedResourceManager.GetResource(filepath); var filename = System.IO.Path.GetFileName(filepath); var extension = System.IO.Path.GetExtension(filepath); resource.ShouldNotBeNull(); Assert.True(resource.Assembly == GetType().GetAssembly()); Assert.True(resource.Content.Length > 0); Assert.EndsWith(filename, resource.FileName); Assert.True(resource.FileExtension == extension.Substring(1)); // without dot } [Fact] public void Should_Get_Embedded_Resource_With_Begin_Digit_In_Folder() { var filepath = "/MyApp/MyResources/0.9/MyScriptFile.0.9.js"; var resource = _embeddedResourceManager.GetResource(filepath); var filename = System.IO.Path.GetFileName(filepath); var extension = System.IO.Path.GetExtension(filepath); resource.ShouldNotBeNull(); Assert.True(resource.Assembly == GetType().GetAssembly()); Assert.True(resource.Content.Length > 0); Assert.EndsWith(filename, resource.FileName); Assert.True(resource.FileExtension == extension.Substring(1)); // without dot } [Fact] public void Should_Get_Embedded_Resource_With_Dash_In_Name() { var filepath = "/MyApp/MyResources/js/MyScriptFile-2.js"; var resource = _embeddedResourceManager.GetResource(filepath); var filename = System.IO.Path.GetFileName(filepath); var extension = System.IO.Path.GetExtension(filepath); resource.ShouldNotBeNull(); Assert.True(resource.Assembly == GetType().GetAssembly()); Assert.True(resource.Content.Length > 0); Assert.EndsWith(filename, resource.FileName); Assert.True(resource.FileExtension == extension.Substring(1)); // without dot } [Fact] public void Should_Get_Embedded_Resource_With_Two_Dots_In_Name() { var filepath = "/MyApp/MyResources/js/MyScriptFile3.min.js"; var resource = _embeddedResourceManager.GetResource(filepath); var filename = System.IO.Path.GetFileName(filepath); var extension = System.IO.Path.GetExtension(filepath); resource.ShouldNotBeNull(); Assert.True(resource.Assembly == GetType().GetAssembly()); Assert.True(resource.Content.Length > 0); Assert.EndsWith(filename, resource.FileName); Assert.True(resource.FileExtension == extension.Substring(1)); // without dot } [Fact] public void Should_Get_Embedded_Resource_With_Underscore_In_Folder() { var filepath = "/MyApp/MyResources/js_underscore/MyScriptFile.js"; var resource = _embeddedResourceManager.GetResource(filepath); var filename = System.IO.Path.GetFileName(filepath); var extension = System.IO.Path.GetExtension(filepath); resource.ShouldNotBeNull(); Assert.True(resource.Assembly == GetType().GetAssembly()); Assert.True(resource.Content.Length > 0); Assert.EndsWith(filename, resource.FileName); Assert.True(resource.FileExtension == extension.Substring(1)); // without dot } [Fact] public void Should_Get_Embedded_Resource_With_Underscore_In_Name() { var filepath = "/MyApp/MyResources/js/MyScriptFile_4.js"; var resource = _embeddedResourceManager.GetResource(filepath); var filename = System.IO.Path.GetFileName(filepath); var extension = System.IO.Path.GetExtension(filepath); resource.ShouldNotBeNull(); Assert.True(resource.Assembly == GetType().GetAssembly()); Assert.True(resource.Content.Length > 0); Assert.EndsWith(filename, resource.FileName); Assert.True(resource.FileExtension == extension.Substring(1)); // without dot } [Fact] public void Should_Get_Embedded_Resources() { var filepath = "/MyApp/MyResources/js/"; var resources = _embeddedResourceManager.GetResources(filepath); resources.ShouldNotBeNull(); Assert.True(resources.Count() == 4); } [Fact] public void Should_Get_Embedded_Resources_With_Dash_In_folder() { var filepath = "/MyApp/MyResources/js-dash/MyScriptFile.js"; var resource = _embeddedResourceManager.GetResource(filepath); var filename = System.IO.Path.GetFileName(filepath); var extension = System.IO.Path.GetExtension(filepath); resource.ShouldNotBeNull(); Assert.True(resource.Assembly == GetType().GetAssembly()); Assert.True(resource.Content.Length > 0); Assert.EndsWith(filename, resource.FileName); Assert.True(resource.FileExtension == extension.Substring(1)); // without dot } } }
42.442857
110
0.636149
[ "MIT" ]
afonsoft/EAF
test/Eaf.Tests/Resources/Embedded/EmbeddedResourceTests.cs
5,944
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; #pragma warning disable CS0108 using UE4.UnrealEd.Native; using UE4.Engine; namespace UE4.UnrealEd { ///<summary>Polys Exporter OBJ</summary> public unsafe partial class PolysExporterOBJ : Exporter { static PolysExporterOBJ() { StaticClass = Main.GetClass("PolysExporterOBJ"); } internal unsafe PolysExporterOBJ_fields* PolysExporterOBJ_ptr => (PolysExporterOBJ_fields*) ObjPointer.ToPointer(); ///<summary>Convert from IntPtr to UObject</summary> public static implicit operator PolysExporterOBJ(IntPtr p) => UObject.Make<PolysExporterOBJ>(p); ///<summary>Get UE4 Class</summary> public static Class StaticClass {get; private set;} ///<summary>Get UE4 Default Object for this Class</summary> public static PolysExporterOBJ DefaultObject => Main.GetDefaultObject(StaticClass); ///<summary>Spawn an object of this class</summary> public static PolysExporterOBJ New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name); } }
40.058824
129
0.720264
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/UnrealEd/PolysExporterOBJ.cs
1,362
C#
using OfficeDevPnP.PowerShell.CmdletHelpAttributes; using OfficeDevPnP.PowerShell.Commands.Base; using Microsoft.SharePoint.Client; using System.Management.Automation; using System; namespace OfficeDevPnP.PowerShell.Commands { [Cmdlet(VerbsCommon.Add, "SPOFile")] [CmdletHelp("Uploads a file to Web")] [CmdletExample(Code = @" PS:> Add-SPOFile -Path c:\temp\company.master -Url /sites/")] public class AddFile : SPOWebCmdlet { [Parameter(Mandatory = true, HelpMessage = "The local file path.")] public string Path = string.Empty; [Parameter(Mandatory = true, HelpMessage = "The destination folder in the site")] public string Folder = string.Empty; [Parameter(Mandatory = false, HelpMessage = "If versioning is enabled, this will check out the file first if it exists, upload the file, then check it in again.")] public SwitchParameter Checkout; [Parameter(Mandatory = false, HelpMessage = "Will auto approve the uploaded file.")] public SwitchParameter Approve; [Parameter(Mandatory = false, HelpMessage = "The comment added to the approval.")] public string ApproveComment = string.Empty; [Parameter(Mandatory = false, HelpMessage = "Will auto publish the file.")] public SwitchParameter Publish; [Parameter(Mandatory = false, HelpMessage = "The comment added to the publish action.")] public string PublishComment = string.Empty; [Parameter(Mandatory = false)] public SwitchParameter UseWebDav; protected override void ExecuteCmdlet() { if (!this.SelectedWeb.IsPropertyAvailable("ServerRelativeUrl")) { ClientContext.Load(this.SelectedWeb, w => w.ServerRelativeUrl); ClientContext.ExecuteQuery(); } Folder folder = this.SelectedWeb.GetFolderByServerRelativeUrl(UrlUtility.Combine(this.SelectedWeb.ServerRelativeUrl, Folder)); ClientContext.Load(folder, f => f.ServerRelativeUrl); ClientContext.ExecuteQuery(); var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, System.IO.Path.GetFileName(Path)); // Check if the file exists if (Checkout) { try { var existingFile = this.SelectedWeb.GetFileByServerRelativeUrl(fileUrl); if (existingFile.Exists) { this.SelectedWeb.CheckOutFile(fileUrl); } } catch { // Swallow exception, file does not exist } } folder.UploadFile(Path, useWebDav: UseWebDav); if (Checkout) this.SelectedWeb.CheckInFile(fileUrl, CheckinType.MajorCheckIn, ""); if (Publish) this.SelectedWeb.PublishFile(fileUrl, PublishComment); if (Approve) this.SelectedWeb.ApproveFile(fileUrl, PublishComment); } } }
37.13253
171
0.620376
[ "Apache-2.0" ]
GeiloStylo/PnP
Solutions/PowerShell.Commands/Commands/Web/AddFile.cs
3,084
C#
using System; using System.Collections.Generic; using System.Dynamic; using Maths; namespace OperationSolver { class Program { static void Main(string[] args) { Console.WriteLine("Enter an expression to evaluate:"); string input; while ((input = Console.ReadLine()) != "exit") { try { if (string.IsNullOrEmpty(input)) continue; var split = input.Split('|'); if (split.Length == 1) { Console.WriteLine(Expression.EvaluateExpression(input)); } else if (split.Length > 1) { var expression = split[0]; var expandoArg = new ExpandoObject() as IDictionary<string, Object>; var rawVariables = split[1]; var splitVariables = rawVariables.Split(','); foreach (string splitVariable in splitVariables) { var splitVar = splitVariable.Split('='); var varName = splitVar[0].Trim(); var varValue = splitVar[1].Trim(); expandoArg.Add(varName, varValue); } Console.WriteLine(Expression.EvaluateExpression(expression, expandoArg)); } } catch (Exception e) { Console.WriteLine("An error occurred while attempting to evaluate the expression:\r\n\t{0}\r\n", e.Message); } } } } }
36.428571
128
0.438655
[ "Apache-2.0" ]
skeryl/maths
OperationSolver/Program.cs
1,787
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 04:58:03 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Collections.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using bytes = go.bytes_package; using binary = go.encoding.binary_package; using go; #nullable enable #pragma warning disable CS0660, CS0661 namespace go { namespace net { public static partial class http_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial interface sniffSig { [MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static sniffSig As<T>(in T target) => (sniffSig<T>)target!; [MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static sniffSig As<T>(ptr<T> target_ptr) => (sniffSig<T>)target_ptr; [MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static sniffSig? As(object target) => typeof(sniffSig<>).CreateInterfaceHandler<sniffSig>(target); } [GeneratedCode("go2cs", "0.1.0.0")] private class sniffSig<T> : sniffSig { private T m_target = default!; private readonly ptr<T>? m_target_ptr; private readonly bool m_target_is_ptr; public ref T Target { get { if (m_target_is_ptr && !(m_target_ptr is null)) return ref m_target_ptr.val; return ref m_target; } } public sniffSig(in T target) => m_target = target; public sniffSig(ptr<T> target_ptr) { m_target_ptr = target_ptr; m_target_is_ptr = true; } private delegate @string matchByPtr(ptr<T> value, slice<byte> data, long firstNonWS); private delegate @string matchByVal(T value, slice<byte> data, long firstNonWS); private static readonly matchByPtr? s_matchByPtr; private static readonly matchByVal? s_matchByVal; [DebuggerNonUserCode, MethodImpl(MethodImplOptions.AggressiveInlining)] public @string match(slice<byte> data, long firstNonWS) { T target = m_target; if (m_target_is_ptr && !(m_target_ptr is null)) target = m_target_ptr.val; if (s_matchByPtr is null || !m_target_is_ptr) return s_matchByVal!(target, data, firstNonWS); return s_matchByPtr(m_target_ptr, data, firstNonWS); } public string ToString(string? format, IFormatProvider? formatProvider) => format; [DebuggerStepperBoundary] static sniffSig() { Type targetType = typeof(T); Type targetTypeByPtr = typeof(ptr<T>); MethodInfo extensionMethod; extensionMethod = targetTypeByPtr.GetExtensionMethod("match"); if (!(extensionMethod is null)) s_matchByPtr = extensionMethod.CreateStaticDelegate(typeof(matchByPtr)) as matchByPtr; extensionMethod = targetType.GetExtensionMethod("match"); if (!(extensionMethod is null)) s_matchByVal = extensionMethod.CreateStaticDelegate(typeof(matchByVal)) as matchByVal; if (s_matchByPtr is null && s_matchByVal is null) throw new NotImplementedException($"{targetType.FullName} does not implement sniffSig.match method", new Exception("match")); } [MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static explicit operator sniffSig<T>(in ptr<T> target_ptr) => new sniffSig<T>(target_ptr); [MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static explicit operator sniffSig<T>(in T target) => new sniffSig<T>(target); // Enable comparisons between nil and sniffSig<T> interface instance [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(sniffSig<T> value, NilType nil) => Activator.CreateInstance<sniffSig<T>>().Equals(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(sniffSig<T> value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, sniffSig<T> value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, sniffSig<T> value) => value != nil; } } }} namespace go { public static class http_sniffSigExtensions { private static readonly ConcurrentDictionary<Type, MethodInfo> s_conversionOperators = new ConcurrentDictionary<Type, MethodInfo>(); [GeneratedCode("go2cs", "0.1.0.0"), MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static T _<T>(this go.net.http_package.sniffSig target) { try { return ((go.net.http_package.sniffSig<T>)target).Target; } catch (NotImplementedException ex) { throw new PanicException($"interface conversion: {GetGoTypeName(target.GetType())} is not {GetGoTypeName(typeof(T))}: missing method {ex.InnerException?.Message}"); } } [GeneratedCode("go2cs", "0.1.0.0"), MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static bool _<T>(this go.net.http_package.sniffSig target, out T result) { try { result = target._<T>(); return true; } catch (PanicException) { result = default!; return false; } } [GeneratedCode("go2cs", "0.1.0.0"), MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static object? _(this go.net.http_package.sniffSig target, Type type) { try { MethodInfo? conversionOperator = s_conversionOperators.GetOrAdd(type, _ => typeof(go.net.http_package.sniffSig<>).GetExplicitGenericConversionOperator(type)); if (conversionOperator is null) throw new PanicException($"interface conversion: failed to create converter for {GetGoTypeName(target.GetType())} to {GetGoTypeName(type)}"); dynamic? result = conversionOperator.Invoke(null, new object[] { target }); return result?.Target; } catch (NotImplementedException ex) { throw new PanicException($"interface conversion: {GetGoTypeName(target.GetType())} is not {GetGoTypeName(type)}: missing method {ex.InnerException?.Message}"); } } [GeneratedCode("go2cs", "0.1.0.0"), MethodImpl(MethodImplOptions.AggressiveInlining), DebuggerNonUserCode] public static bool _(this go.net.http_package.sniffSig target, Type type, out object? result) { try { result = target._(type); return true; } catch (PanicException) { result = type.IsValueType ? Activator.CreateInstance(type) : null; return false; } } } }
39.811881
180
0.598234
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/net/http/sniff_sniffSigInterface.cs
8,042
C#
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace EIS.Studio.SysFolder.DefFrame { public partial class ModelImport { /// <summary> /// Head1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlHead Head1; /// <summary> /// form1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// FileUpload1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.FileUpload FileUpload1; /// <summary> /// Button1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button Button1; /// <summary> /// Button2 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button Button2; } }
26.803279
81
0.444037
[ "MIT" ]
chen1993nian/CPMPlatform
Dev/SysFolder/DefFrame/ModelImport.aspx.designer.cs
2,139
C#
using Nethereum.BlockchainStore.Entities; using System.Data.Entity.ModelConfiguration; namespace Nethereum.BlockchainStore.EF.EntityBuilders { public class AddressTransactionEntityBuilder : EntityTypeConfiguration<AddressTransaction> { public AddressTransactionEntityBuilder() { ToTable("AddressTransactions"); HasKey(b => b.RowIndex); HasIndex(b => new {b.BlockNumber, b.Hash, b.Address}).IsUnique().HasName("IX_Transactions_BlockNumber_Hash_Address"); HasIndex(b => b.Hash); HasIndex(b => b.Address); Property(t => t.BlockNumber).IsBigInteger().IsRequired(); Property(b => b.Hash).IsHash().IsRequired(); Property(b => b.Address).IsAddress().IsRequired(); } } }
32.68
129
0.635251
[ "MIT" ]
ConsenSys/Nethereum.BlockchainProcessing
Storage/Nethereum.BlockchainStore.EF/EntityBuilders/AddressTransactionEntityBuilder.cs
819
C#
using System; using System.Reflection; using ExtendedXmlSerializer.ContentModel; using ExtendedXmlSerializer.ContentModel.Collections; using ExtendedXmlSerializer.ContentModel.Content; using ExtendedXmlSerializer.ContentModel.Format; using ExtendedXmlSerializer.ContentModel.Members; using ExtendedXmlSerializer.Core; namespace ExtendedXmlSerializer.ExtensionModel.Content { sealed class UnknownContentHandlingExtension : ISerializerExtension { readonly Action<IFormatReader> _action; public UnknownContentHandlingExtension(Action<IFormatReader> action) => _action = action; public IServiceRepository Get(IServiceRepository parameter) => parameter.RegisterInstance(_action) .Decorate<IInnerContentServices, Services>(); void ICommand<IServices>.Execute(IServices parameter) {} sealed class Services : IInnerContentServices { readonly IInnerContentServices _services; readonly Action<IFormatReader> _missing; public Services(IInnerContentServices services, Action<IFormatReader> missing) { _services = services; _missing = missing; } public bool IsSatisfiedBy(IInnerContent parameter) => _services.IsSatisfiedBy(parameter); public void Handle(IInnerContent contents, IMemberSerializer member) { _services.Handle(contents, member); } public void Handle(IListInnerContent contents, IReader reader) { _services.Handle(contents, reader); } public string Get(IFormatReader parameter) => _services.Get(parameter); public IReader Create(TypeInfo classification, IInnerContentHandler handler) => _services.Create(classification, new Handler(handler, _missing)); } sealed class Handler : IInnerContentHandler { readonly IInnerContentHandler _handler; readonly Action<IFormatReader> _command; public Handler(IInnerContentHandler handler, Action<IFormatReader> command) { _handler = handler; _command = command; } public bool IsSatisfiedBy(IInnerContent parameter) { var result = _handler.IsSatisfiedBy(parameter); if (!result) { var reader = parameter.Get(); switch (reader.Identifier) { case "http://www.w3.org/2000/xmlns/": case "https://extendedxmlserializer.github.io/v2": break; default: _command(reader); break; } } return result; } } } }
28.811765
93
0.720294
[ "MIT" ]
ExtendedXmlSerializer/NextRelease
src/ExtendedXmlSerializer/ExtensionModel/Content/UnknownContentHandlingExtension.cs
2,451
C#
using System.Collections.Generic; using System.Linq; namespace EnterpriseWebLibrary.EnterpriseWebFramework { public sealed class ElementAttribute { internal readonly string Name; internal readonly string Value; /// <summary> /// Creates an attribute. /// </summary> /// <param name="name">Do not pass null or the empty string.</param> /// <param name="value">Do not pass null.</param> public ElementAttribute( string name, string value ) { Name = name; Value = value; } /// <summary> /// Creates a boolean attribute. /// </summary> /// <param name="name">Do not pass null or the empty string.</param> public ElementAttribute( string name ) { Name = name; } } public static class ElementAttributeExtensionCreators { /// <summary> /// Concatenates attributes. /// </summary> public static IEnumerable<ElementAttribute> Concat( this ElementAttribute first, IEnumerable<ElementAttribute> second ) => second.Prepend( first ); /// <summary> /// Returns a sequence of two attributes. /// </summary> public static IEnumerable<ElementAttribute> Append( this ElementAttribute first, ElementAttribute second ) => Enumerable.Empty<ElementAttribute>().Append( first ).Append( second ); } }
32.075
150
0.682775
[ "MIT" ]
enduracode/enterprise-web-library
Core/EnterpriseWebFramework/Page Infrastructure/Page Structure/Nodes/ElementAttribute.cs
1,285
C#
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Store.Application.Integration.Test { using static Testing; public class TestBase { [SetUp] public async Task TestSetUp() { await ResetState(); } } }
17.190476
44
0.65097
[ "MIT" ]
srichatala/cleanarchitecture.store.app
tests/Store.Application.Integration.Test/TestBase.cs
363
C#
namespace Countries.Api.Cache { /// <summary> /// Local cache interface /// </summary> public interface ILocalCache { /// <summary> /// Gets the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns>The object</returns> T Get<T>(string key); /// <summary> /// Puts the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> void Put<T>(string key, T value); } }
24.73913
50
0.499121
[ "MIT" ]
sajohnstone/CountriesOfTheWorld
api/Countries.Api/Cache/ILocalCache.cs
571
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils { using System; using System.Collections.Generic; using System.Globalization; /// <summary> /// Base class for all disk image builders. /// </summary> public abstract class DiskImageBuilder { private static Dictionary<string, VirtualDiskFactory> s_typeMap; private SparseStream _content; private Geometry _geometry; private Geometry _biosGeometry; private GenericDiskAdapterType _adaptorType; /// <summary> /// Gets or sets the content for this disk, implying the size of the disk. /// </summary> public SparseStream Content { get { return _content; } set { _content = value; } } /// <summary> /// Gets or sets the geometry of this disk, will be implied from the content stream if not set. /// </summary> public Geometry Geometry { get { return _geometry; } set { _geometry = value; } } /// <summary> /// Gets or sets the geometry of this disk, as reported by the BIOS, will be implied from the content stream if not set. /// </summary> public Geometry BiosGeometry { get { return _biosGeometry; } set { _biosGeometry = value; } } /// <summary> /// Gets or sets the adapter type for created virtual disk, for file formats that encode this information. /// </summary> public virtual GenericDiskAdapterType GenericAdapterType { get { return _adaptorType; } set { _adaptorType = value; } } /// <summary> /// Gets a value indicating whether this file format preserves BIOS geometry information. /// </summary> public virtual bool PreservesBiosGeometry { get { return false; } } private static Dictionary<string, VirtualDiskFactory> TypeMap { get { if (s_typeMap == null) { InitializeMaps(); } return s_typeMap; } } /// <summary> /// Gets an instance that constructs the specified type (and variant) of virtual disk image. /// </summary> /// <param name="type">The type of image to build (VHD, VMDK, etc)</param> /// <param name="variant">The variant type (differencing/dynamic, fixed/static, etc).</param> /// <returns>The builder instance.</returns> public static DiskImageBuilder GetBuilder(string type, string variant) { VirtualDiskFactory factory; if (!TypeMap.TryGetValue(type, out factory)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown disk type '{0}'", type), "type"); } return factory.GetImageBuilder(variant); } /// <summary> /// Initiates the construction of the disk image. /// </summary> /// <param name="baseName">The base name for the disk images.</param> /// <returns>A set of one or more logical files that constitute the /// disk image. The first file is the 'primary' file that is normally attached to VMs.</returns> /// <remarks>The supplied <c>baseName</c> is the start of the file name, with no file /// extension. The set of file specifications will indicate the actual name corresponding /// to each logical file that comprises the disk image. For example, given a base name /// 'foo', the files 'foo.vmdk' and 'foo-flat.vmdk' could be returned.</remarks> public abstract DiskImageFileSpecification[] Build(string baseName); private static void InitializeMaps() { Dictionary<string, VirtualDiskFactory> typeMap = new Dictionary<string, VirtualDiskFactory>(); foreach (var type in typeof(VirtualDisk).Assembly.GetTypes()) { VirtualDiskFactoryAttribute attr = (VirtualDiskFactoryAttribute)Attribute.GetCustomAttribute(type, typeof(VirtualDiskFactoryAttribute), false); if (attr != null) { VirtualDiskFactory factory = (VirtualDiskFactory)Activator.CreateInstance(type); typeMap.Add(attr.Type, factory); } } s_typeMap = typeMap; } } }
39.903448
160
0.60318
[ "MIT" ]
jsakamoto/discutils
src/DiskImageBuilder.cs
5,786
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.S3.Model { /// <summary> /// Container for the parameters to the DeleteInventoryConfiguration operation. /// <para>Deletes an inventory configuration (identified by the inventory ID) from the bucket.</para> /// </summary> public partial class DeleteBucketInventoryConfigurationRequest : AmazonWebServiceRequest { private string bucketName; private string inventoryId; private string expectedBucketOwner; /// <summary> /// The name of the bucket containing the inventory configuration to delete. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } // Check to see if BucketName property is set internal bool IsSetBucketName() { return !(string.IsNullOrEmpty(this.bucketName)); } /// <summary> /// The ID used to identify the inventory configuration. /// </summary> public string InventoryId { get { return this.inventoryId; } set { this.inventoryId = value; } } // Check to see if InventoryId property is set internal bool IsSetInventoryId() { return !(string.IsNullOrEmpty(this.inventoryId)); } /// <summary> /// The account id of the expected bucket owner. /// If the bucket is owned by a different account, the request will fail with an HTTP 403 (Access Denied) error. /// </summary> public string ExpectedBucketOwner { get { return this.expectedBucketOwner; } set { this.expectedBucketOwner = value; } } /// <summary> /// Checks to see if ExpectedBucketOwner is set. /// </summary> /// <returns>true, if ExpectedBucketOwner property is set.</returns> internal bool IsSetExpectedBucketOwner() { return !String.IsNullOrEmpty(this.expectedBucketOwner); } } }
32.079545
120
0.63514
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/S3/Custom/Model/DeleteBucketInventoryConfigurationRequest.cs
2,823
C#
using Couchbase.Search.Sort; using Newtonsoft.Json; using Xunit; namespace Couchbase.UnitTests.Search { public class FieldSearchSortTests { [Fact] public void Outputs_Valid_Json() { var sort = new FieldSearchSort("foo", FieldType.String, FieldMode.Min, FieldMissing.First, true); var result = sort.Export().ToString(Formatting.None); var expected = JsonConvert.SerializeObject(new { by = "field", desc = true, field = "foo", type = "string", mode = "min", missing = "first" }, Formatting.None); Assert.Equal(expected, result); } [Fact] public void Omits_Type_If_Auto() { var sort = new FieldSearchSort("foo", FieldType.String, FieldMode.Min, FieldMissing.First); var result = sort.Export().ToString(Formatting.None); var expected = JsonConvert.SerializeObject(new { by = "field", field = "foo", type = "string", mode = "min", missing = "first" }, Formatting.None); Assert.Equal(expected, result); } [Fact] public void Omits_Mode_If_Default() { var sort = new FieldSearchSort("foo", FieldType.Auto, FieldMode.Min, FieldMissing.First, true); var result = sort.Export().ToString(Formatting.None); var expected = JsonConvert.SerializeObject(new { by = "field", desc = true, field = "foo", mode = "min", missing = "first" }, Formatting.None); Assert.Equal(expected, result); } [Fact] public void Omits_Missing_If_Last() { var sort = new FieldSearchSort("foo", FieldType.String, FieldMode.Default, FieldMissing.First, true); var result = sort.Export().ToString(Formatting.None); var expected = JsonConvert.SerializeObject(new { by = "field", desc = true, field = "foo", type = "string", missing = "first" }, Formatting.None); Assert.Equal(expected, result); } [Fact] public void Omits_Decending_If_False() { var sort = new FieldSearchSort("foo", FieldType.String, FieldMode.Min, FieldMissing.Last, true); var result = sort.Export().ToString(Formatting.None); var expected = JsonConvert.SerializeObject(new { by = "field", desc = true, field = "foo", type = "string", mode = "min" }, Formatting.None); Assert.Equal(expected, result); } } }
29.663366
113
0.496996
[ "Apache-2.0" ]
RiPont/couchbase-net-client
tests/Couchbase.UnitTests/Search/FieldSearchSortTests.cs
2,996
C#
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Spine.Unity.Examples { public class SkeletonGraphicMirror : MonoBehaviour { public SkeletonRenderer source; public bool mirrorOnStart = true; public bool restoreOnDisable = true; SkeletonGraphic skeletonGraphic; Skeleton originalSkeleton; bool originalFreeze; Texture2D overrideTexture; private void Awake () { skeletonGraphic = GetComponent<SkeletonGraphic>(); } void Start () { if (mirrorOnStart) StartMirroring(); } void LateUpdate () { skeletonGraphic.UpdateMesh(); } void OnDisable () { if (restoreOnDisable) RestoreIndependentSkeleton(); } /// <summary>Freeze the SkeletonGraphic on this GameObject, and use the source as the Skeleton to be rendered by the SkeletonGraphic.</summary> public void StartMirroring () { if (source == null) return; if (skeletonGraphic == null) return; skeletonGraphic.startingAnimation = string.Empty; if (originalSkeleton == null) { originalSkeleton = skeletonGraphic.Skeleton; originalFreeze = skeletonGraphic.freeze; } skeletonGraphic.Skeleton = source.skeleton; skeletonGraphic.freeze = true; if (overrideTexture != null) skeletonGraphic.OverrideTexture = overrideTexture; } /// <summary>Use a new texture for the SkeletonGraphic. Use this if your source skeleton uses a repacked atlas. </summary> public void UpdateTexture (Texture2D newOverrideTexture) { overrideTexture = newOverrideTexture; if (newOverrideTexture != null) skeletonGraphic.OverrideTexture = overrideTexture; } /// <summary>Stops mirroring the source SkeletonRenderer and allows the SkeletonGraphic to become an independent Skeleton component again.</summary> public void RestoreIndependentSkeleton () { if (originalSkeleton == null) return; skeletonGraphic.Skeleton = originalSkeleton; skeletonGraphic.freeze = originalFreeze; skeletonGraphic.OverrideTexture = null; originalSkeleton = null; } } }
35.809524
150
0.724202
[ "MIT" ]
ADA-NFT-Project/Best-Game
Assets/Spine Examples/Scripts/Sample Components/SkeletonGraphicMirror.cs
3,760
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetAccessControl.domain.enums { public enum Permission { NotSpecified = 0, Allow = 1, Deny = 2 } }
16.6875
42
0.666667
[ "MIT" ]
MostafaEsmaeili/AccessControl
src/domain/enums/Permission.cs
269
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.Attributes; namespace AWE_Tools.Purge_Unused { [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)] [Journaling(JournalingMode.UsingCommandData)] class PurgeUnused:IExternalCommand { public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var doc = commandData.Application.ActiveUIDocument.Document; //ICollection<Autodesk.Revit.DB.ElementId> purgeableElements = null; ////access the performance adviser //PerformanceAdviser perfAdviser = PerformanceAdviser.GetPerformanceAdviser(); ////create a list with all the rules //IList<PerformanceAdviserRuleId> allRulesList = perfAdviser.GetAllRuleIds(); //if (PurgeTool.GetPurgeableElements(doc, allRulesList) && purgeableElements.Count > 0) //{ using (var transaction = new Transaction(doc, "Purge Unused")) { transaction.Start(); PurgeTool.Purge(doc); //doc.Delete(purgeableElements); transaction.Commit(); } //} //else //{ // return Result.Failed; //} return Result.Succeeded; } } }
33.869565
103
0.606547
[ "MIT" ]
dodzikojo/P-W_Revit-Tools
AddPanel/Purge Unused/PurgeUnused.cs
1,560
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JWLibrary.Winform.Test { public partial class Form1 : Form { public Form1() { InitializeComponent(); Data d = new Data { Id = 0, Name = "test", Phone = "010", EDate = DateTime.Now }; IList<Data> datas = new List<Data> { d }; this.jwFlowLayoutPanel1.DataSource = d; this.jwDataGridView1.DataSource = datas; this.jwFlowLayoutPanel1.EndedControl += (s, e) => { this.button2.Focus(); //this.button2.Select(); }; } private void button1_Click(object sender, EventArgs e) { this.jwFlowLayoutPanel1.Clear(); } private void button2_Click(object sender, EventArgs e) { Data d = (Data)this.jwFlowLayoutPanel1.DataSource; MessageBox.Show(string.Format($"Id:{d.Id}, Name : {d.Name}, Phone : {d.Phone}, EDate : {d.EDate}")); } private void button3_Click(object sender, EventArgs e) { Data d = (Data)this.jwFlowLayoutPanel1.DataSource; d.Id = 99; if (this.jwFlowLayoutPanel1.LockControl) this.jwFlowLayoutPanel1.LockControl = false; else this.jwFlowLayoutPanel1.LockControl = true; } } public class Data : INotifyPropertyChanged { private int _id; public int Id { get { return _id; } set { _id = value; OnPropertyChanged("Id"); } } private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } private string _phone; public string Phone { get { return _phone; } set { _phone = value; OnPropertyChanged("Phone"); } } private DateTime _edate; public DateTime EDate { get { return _edate; } set { _edate = value; OnPropertyChanged("EDate"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, e); } protected void OnPropertyChanged(string propertyName) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } } }
29.858696
112
0.563524
[ "Unlicense" ]
GuyFawkesFromKorea/JWLibrary
JWLibrary.Winform.Test/Form1.cs
2,749
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Phonebook_Application.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Phonebook_Application.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap abouticon { get { object obj = ResourceManager.GetObject("abouticon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap addicon { get { object obj = ResourceManager.GetObject("addicon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap deleteicon { get { object obj = ResourceManager.GetObject("deleteicon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap editicon { get { object obj = ResourceManager.GetObject("editicon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap exit { get { object obj = ResourceManager.GetObject("exit", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap facebook { get { object obj = ResourceManager.GetObject("facebook", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap github { get { object obj = ResourceManager.GetObject("github", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap instagram { get { object obj = ResourceManager.GetObject("instagram", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap linkedin { get { object obj = ResourceManager.GetObject("linkedin", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap min { get { object obj = ResourceManager.GetObject("min", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap minimize { get { object obj = ResourceManager.GetObject("minimize", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap pk { get { object obj = ResourceManager.GetObject("pk", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap recordicon { get { object obj = ResourceManager.GetObject("recordicon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap saveicon { get { object obj = ResourceManager.GetObject("saveicon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap searchicon { get { object obj = ResourceManager.GetObject("searchicon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
38.813084
187
0.552492
[ "MIT" ]
sameem420/CSharp-PhonebookProject
Phonebook Application/Phonebook Application/Properties/Resources.Designer.cs
8,308
C#
using System; using System.Collections.Generic; using System.Text; namespace Weikio.ApiFramework.Plugins.Email { public class EmailSendingResult { public bool Success { get; set; } public string ErrorMessage { get; set; } } }
19.615385
48
0.690196
[ "MIT" ]
weikio/ApiFramework.Plugins.Email
src/Weikio.ApiFramework.Plugins.Email/EmailSendingResult.cs
255
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the comprehendmedical-2018-10-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ComprehendMedical.Model { /// <summary> /// Container for the parameters to the StartPHIDetectionJob operation. /// Starts an asynchronous job to detect protected health information (PHI). Use the <code>DescribePHIDetectionJob</code> /// operation to track the status of a job. /// </summary> public partial class StartPHIDetectionJobRequest : AmazonComprehendMedicalRequest { private string _clientRequestToken; private string _dataAccessRoleArn; private InputDataConfig _inputDataConfig; private string _jobName; private string _kmsKey; private LanguageCode _languageCode; private OutputDataConfig _outputDataConfig; /// <summary> /// Gets and sets the property ClientRequestToken. /// <para> /// A unique identifier for the request. If you don't set the client request token, Amazon /// Comprehend Medical generates one. /// </para> /// </summary> [AWSProperty(Min=1, Max=64)] public string ClientRequestToken { get { return this._clientRequestToken; } set { this._clientRequestToken = value; } } // Check to see if ClientRequestToken property is set internal bool IsSetClientRequestToken() { return this._clientRequestToken != null; } /// <summary> /// Gets and sets the property DataAccessRoleArn. /// <para> /// The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role /// that grants Amazon Comprehend Medical read access to your input data. For more information, /// see <a href="https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions-med.html#auth-role-permissions-med"> /// Role-Based Permissions Required for Asynchronous Operations</a>. /// </para> /// </summary> [AWSProperty(Required=true, Min=20, Max=2048)] public string DataAccessRoleArn { get { return this._dataAccessRoleArn; } set { this._dataAccessRoleArn = value; } } // Check to see if DataAccessRoleArn property is set internal bool IsSetDataAccessRoleArn() { return this._dataAccessRoleArn != null; } /// <summary> /// Gets and sets the property InputDataConfig. /// <para> /// Specifies the format and location of the input data for the job. /// </para> /// </summary> [AWSProperty(Required=true)] public InputDataConfig InputDataConfig { get { return this._inputDataConfig; } set { this._inputDataConfig = value; } } // Check to see if InputDataConfig property is set internal bool IsSetInputDataConfig() { return this._inputDataConfig != null; } /// <summary> /// Gets and sets the property JobName. /// <para> /// The identifier of the job. /// </para> /// </summary> [AWSProperty(Min=1, Max=256)] public string JobName { get { return this._jobName; } set { this._jobName = value; } } // Check to see if JobName property is set internal bool IsSetJobName() { return this._jobName != null; } /// <summary> /// Gets and sets the property KMSKey. /// <para> /// An AWS Key Management Service key to encrypt your output files. If you do not specify /// a key, the files are written in plain text. /// </para> /// </summary> [AWSProperty(Min=1, Max=2048)] public string KMSKey { get { return this._kmsKey; } set { this._kmsKey = value; } } // Check to see if KMSKey property is set internal bool IsSetKMSKey() { return this._kmsKey != null; } /// <summary> /// Gets and sets the property LanguageCode. /// <para> /// The language of the input documents. All documents must be in the same language. /// </para> /// </summary> [AWSProperty(Required=true)] public LanguageCode LanguageCode { get { return this._languageCode; } set { this._languageCode = value; } } // Check to see if LanguageCode property is set internal bool IsSetLanguageCode() { return this._languageCode != null; } /// <summary> /// Gets and sets the property OutputDataConfig. /// <para> /// Specifies where to send the output files. /// </para> /// </summary> [AWSProperty(Required=true)] public OutputDataConfig OutputDataConfig { get { return this._outputDataConfig; } set { this._outputDataConfig = value; } } // Check to see if OutputDataConfig property is set internal bool IsSetOutputDataConfig() { return this._outputDataConfig != null; } } }
33.347826
146
0.598435
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/ComprehendMedical/Generated/Model/StartPHIDetectionJobRequest.cs
6,136
C#
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // This implementation is a mix of works-stealing queue from .NET // and Helios.DedicatedThreadPool. // 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. // Copyright 2015-2016 Roger Alsing, Aaron Stannard, Jeff Cyr // Helios.DedicatedThreadPool - https://github.com/helios-io/DedicatedThreadPool using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; // ReSharper disable InconsistentNaming #pragma warning disable 420 namespace Spreads.Threading { [StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing internal sealed class ThreadPoolWorkQueue { [StructLayout(LayoutKind.Explicit, Size = CACHE_LINE_SIZE - sizeof(int))] internal struct PaddingFor32 { public const int CACHE_LINE_SIZE = 64; } private readonly SpreadsThreadPool _pool; private readonly UnfairSemaphore _semaphore = new UnfairSemaphore(); private static readonly int ProcessorCount = Environment.ProcessorCount; private const int CompletedState = 1; private int _isAddingCompleted; public bool IsAddingCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref _isAddingCompleted) == CompletedState; } } public void CompleteAdding() { int previousCompleted = Interlocked.Exchange(ref _isAddingCompleted, CompletedState); if (previousCompleted == CompletedState) return; // When CompleteAdding() is called, we fill up the _outstandingRequests and the semaphore // This will ensure that all threads will unblock and try to execute the remaining item in // the queue. When IsAddingCompleted is set, all threads will exit once the queue is empty. while (true) { int count = numOutstandingThreadRequests; int countToRelease = UnfairSemaphore.MaxWorker - count; int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, UnfairSemaphore.MaxWorker, count); if (prev == count) { _semaphore.Release((short)countToRelease); break; } } } internal static class WorkStealingQueueList { private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0]; public static WorkStealingQueue[] Queues => _queues; public static void Add(WorkStealingQueue queue) { Debug.Assert(queue != null); while (true) { WorkStealingQueue[] oldQueues = _queues; Debug.Assert(Array.IndexOf(oldQueues, queue) == -1); var newQueues = new WorkStealingQueue[oldQueues.Length + 1]; Array.Copy(oldQueues, 0, newQueues, 0, oldQueues.Length); newQueues[newQueues.Length - 1] = queue; if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues) { break; } } } public static void Remove(WorkStealingQueue queue) { Debug.Assert(queue != null); while (true) { WorkStealingQueue[] oldQueues = _queues; if (oldQueues.Length == 0) { return; } int pos = Array.IndexOf(oldQueues, queue); if (pos == -1) { Debug.Fail("Should have found the queue"); return; } var newQueues = new WorkStealingQueue[oldQueues.Length - 1]; if (pos == 0) { Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length); } else if (pos == oldQueues.Length - 1) { Array.Copy(oldQueues, 0, newQueues, 0, newQueues.Length); } else { Array.Copy(oldQueues, 0, newQueues, 0, pos); Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos); } if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues) { break; } } } } internal sealed class WorkStealingQueue { private const int INITIAL_SIZE = 32; internal volatile Action<object>[] m_array = new Action<object>[INITIAL_SIZE]; private volatile int m_mask = INITIAL_SIZE - 1; #if DEBUG // in debug builds, start at the end so we exercise the index reset logic. private const int START_INDEX = int.MaxValue; #else private const int START_INDEX = 0; #endif private volatile int m_headIndex = START_INDEX; private volatile int m_tailIndex = START_INDEX; private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void LocalPush(Action<object> obj) { int tail = m_tailIndex; // We're going to increment the tail; if we'll overflow, then we need to reset our counts if (tail == int.MaxValue) { bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); if (m_tailIndex == int.MaxValue) { // // Rather than resetting to zero, we'll just mask off the bits we don't care about. // This way we don't need to rearrange the items already in the queue; they'll be found // correctly exactly where they are. One subtlety here is that we need to make sure that // if head is currently < tail, it remains that way. This happens to just fall out from // the bit-masking, because we only do this if tail == int.MaxValue, meaning that all // bits are set, so all of the bits we're keeping will also be set. Thus it's impossible // for the head to end up > than the tail, since you can't set any more bits than all of // them. // m_headIndex = m_headIndex & m_mask; m_tailIndex = tail = m_tailIndex & m_mask; Debug.Assert(m_headIndex <= m_tailIndex); } } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: true); } } // When there are at least 2 elements' worth of space, we can take the fast path. if (tail < m_headIndex + m_mask) { Volatile.Write(ref m_array[tail & m_mask], obj); m_tailIndex = tail + 1; } else { // We need to contend with foreign pops, so we lock. bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); int head = m_headIndex; int count = m_tailIndex - m_headIndex; // If there is still space (one left), just add the element. if (count >= m_mask) { // We're full; expand the queue by doubling its size. var newArray = new Action<object>[m_array.Length << 1]; for (int i = 0; i < m_array.Length; i++) newArray[i] = m_array[(i + head) & m_mask]; // Reset the field values, incl. the mask. m_array = newArray; m_headIndex = 0; m_tailIndex = tail = count; m_mask = (m_mask << 1) | 1; } Volatile.Write(ref m_array[tail & m_mask], obj); m_tailIndex = tail + 1; } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: false); } } } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] public bool LocalFindAndPop(Action<object> obj) { // Fast path: check the tail. If equal, we can skip the lock. if (m_array[(m_tailIndex - 1) & m_mask] == obj) { Action<object> unused = LocalPop(); Debug.Assert(unused == null || unused == obj); return unused != null; } // Else, do an O(N) search for the work item. The theory of work stealing and our // inlining logic is that most waits will happen on recently queued work. And // since recently queued work will be close to the tail end (which is where we // begin our search), we will likely find it quickly. In the worst case, we // will traverse the whole local queue; this is typically not going to be a // problem (although degenerate cases are clearly an issue) because local work // queues tend to be somewhat shallow in length, and because if we fail to find // the work item, we are about to block anyway (which is very expensive). for (int i = m_tailIndex - 2; i >= m_headIndex; i--) { if (m_array[i & m_mask] == obj) { // If we found the element, block out steals to avoid interference. bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); // If we encountered a race condition, bail. if (m_array[i & m_mask] == null) return false; // Otherwise, null out the element. Volatile.Write(ref m_array[i & m_mask], null); // And then check to see if we can fix up the indexes (if we're at // the edge). If we can't, we just leave nulls in the array and they'll // get filtered out eventually (but may lead to superfluous resizing). if (i == m_tailIndex) m_tailIndex -= 1; else if (i == m_headIndex) m_headIndex += 1; return true; } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: false); } } } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Action<object> LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null; [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")] [MethodImpl(MethodImplOptions.AggressiveInlining)] private Action<object> LocalPopCore() { while (true) { int tail = m_tailIndex; if (m_headIndex >= tail) { return null; } // Decrement the tail using a fence to ensure subsequent read doesn't come before. tail -= 1; Interlocked.Exchange(ref m_tailIndex, tail); // If there is no interaction with a take, we can head down the fast path. if (m_headIndex <= tail) { int idx = tail & m_mask; Action<object> obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. if (obj == null) continue; m_array[idx] = null; return obj; } else { // Interaction with takes: 0 or 1 elements left. bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); if (m_headIndex <= tail) { // Element still available. Take it. int idx = tail & m_mask; Action<object> obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. if (obj == null) continue; m_array[idx] = null; return obj; } else { // If we encountered a race condition and element was stolen, restore the tail. m_tailIndex = tail + 1; return null; } } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: false); } } } } public bool CanSteal { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_headIndex < m_tailIndex; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Action<object> TrySteal(ref bool missedSteal) { while (true) { if (CanSteal) { bool taken = false; try { m_foreignLock.TryEnter(ref taken); if (taken) { // Increment head, and ensure read of tail doesn't move before it (fence). int head = m_headIndex; Interlocked.Exchange(ref m_headIndex, head + 1); if (head < m_tailIndex) { int idx = head & m_mask; Action<object> obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. if (obj == null) continue; m_array[idx] = null; return obj; } else { // Failed, restore head. m_headIndex = head; } } } finally { if (taken) m_foreignLock.Exit(useMemoryBarrier: false); } missedSteal = true; } return null; } } } internal readonly ConcurrentQueue<(Action<object>, ExecutionContext, object)> workItems = new ConcurrentQueue<(Action<object>, ExecutionContext, object)>(); #pragma warning disable 169 private readonly PaddingFor32 pad1; #pragma warning restore 169 private volatile int numOutstandingThreadRequests; #pragma warning disable 169 private readonly PaddingFor32 pad2; #pragma warning restore 169 public ThreadPoolWorkQueue(SpreadsThreadPool pool) { _pool = pool; } public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() => ThreadPoolWorkQueueThreadLocals.threadLocals ?? (ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this)); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void EnsureThreadRequested() { // There is a double counter here (_outstandingRequest and _semaphore) // Unfair semaphore does not support value bigger than short.MaxValue, // tring to Release more than short.MaxValue could fail miserably. // The _outstandingRequest counter ensure that we only request a // maximum of {ProcessorCount} to the semaphore. // It's also more efficient to have two counter, _outstandingRequests is // more lightweight than the semaphore. // This trick is borrowed from the .Net ThreadPool // https://github.com/dotnet/coreclr/blob/bc146608854d1db9cdbcc0b08029a87754e12b49/src/mscorlib/src/System/Threading/ThreadPool.cs#L568 int count = numOutstandingThreadRequests; while (count < ProcessorCount) { int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count); if (prev == count) { _semaphore.Release(); break; } count = prev; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void MarkThreadRequestSatisfied() { int count = numOutstandingThreadRequests; while (count > 0) { int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count); if (prev == count) { break; } count = prev; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Enqueue(Action<object> callback, ExecutionContext exCtx, object state, bool forceGlobal) { ThreadPoolWorkQueueThreadLocals tl = null; if (!forceGlobal) { tl = ThreadPoolWorkQueueThreadLocals.threadLocals; } if (null != tl) { tl.workStealingQueue.LocalPush(callback); } else { workItems.Enqueue((callback, exCtx, state)); } EnsureThreadRequested(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool LocalFindAndPop(Action<object> callback) { ThreadPoolWorkQueueThreadLocals tl = ThreadPoolWorkQueueThreadLocals.threadLocals; return tl != null && tl.workStealingQueue.LocalFindAndPop(callback); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public (Action<object>, ExecutionContext, object) Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal) { WorkStealingQueue localWsq = tl.workStealingQueue; (Action<object>, ExecutionContext, object) callback; if ((callback = (localWsq.LocalPop(), null, null)).Item1 == null && // first try the local queue !workItems.TryDequeue(out callback)) // then try the global queue { // finally try to steal from another thread's local queue WorkStealingQueue[] queues = WorkStealingQueueList.Queues; int c = queues.Length; Debug.Assert(c > 0, "There must at least be a queue for this thread."); int maxIndex = c - 1; int i = tl.random.Next(c); while (c > 0) { i = (i < maxIndex) ? i + 1 : 0; WorkStealingQueue otherQueue = queues[i]; if (otherQueue != localWsq && otherQueue.CanSteal) { callback = (otherQueue.TrySteal(ref missedSteal), null, null); if (callback.Item1 != null) { break; } } c--; } } return callback; } internal void Dispatch() { // Set up our thread-local data ThreadPoolWorkQueueThreadLocals tl = EnsureCurrentThreadHasQueue(); while (true) { bool missedSteal = false; var completableCtx = Dequeue(tl, ref missedSteal); if (completableCtx.Item1 == null) { if (IsAddingCompleted) { if (!missedSteal) { break; } } else { _semaphore.Wait(); MarkThreadRequestSatisfied(); } continue; } // this is called before Enqueue: EnsureThreadRequested(); try { if (completableCtx.Item2 == null) { completableCtx.Item1.Invoke(completableCtx.Item3); } else { ExecutionContext.Run(completableCtx.Item2, s => ((Action)s).Invoke(), completableCtx.Item1); } } catch (Exception ex) { _pool.Settings.ExceptionHandler(ex); } } } // Simple random number generator. We don't need great randomness, we just need a little and for it to be fast. internal struct FastRandom // xorshift prng { private uint _w, _x, _y, _z; [MethodImpl(MethodImplOptions.AggressiveInlining)] public FastRandom(int seed) { _x = (uint)seed; _w = 88675123; _y = 362436069; _z = 521288629; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Next(int maxValue) { Debug.Assert(maxValue > 0); uint t = _x ^ (_x << 11); _x = _y; _y = _z; _z = _w; _w = _w ^ (_w >> 19) ^ (t ^ (t >> 8)); return (int)(_w % (uint)maxValue); } } // Holds a WorkStealingQueue, and removes it from the list when this object is no longer referenced. internal sealed class ThreadPoolWorkQueueThreadLocals { [ThreadStatic] public static ThreadPoolWorkQueueThreadLocals threadLocals; public readonly ThreadPoolWorkQueue workQueue; public readonly WorkStealingQueue workStealingQueue; public FastRandom random = new FastRandom(Thread.CurrentThread.ManagedThreadId); // mutable struct, do not copy or make readonly public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq) { workQueue = tpq; workStealingQueue = new WorkStealingQueue(); WorkStealingQueueList.Add(workStealingQueue); } private void CleanUp() { if (null != workStealingQueue) { if (null != workQueue) { Action<object> cb; while ((cb = workStealingQueue.LocalPop()) != null) { Debug.Assert(null != cb); workQueue.Enqueue(cb, null, null, forceGlobal: true); } } WorkStealingQueueList.Remove(workStealingQueue); } } ~ThreadPoolWorkQueueThreadLocals() { // Since the purpose of calling CleanUp is to transfer any pending workitems into the global // queue so that they will be executed by another thread, there's no point in doing this cleanup // if we're in the process of shutting down or unloading the AD. In those cases, the work won't // execute anyway. And there are subtle race conditions involved there that would lead us to do the wrong // thing anyway. So we'll only clean up if this is a "normal" finalization. if (!(Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload())) CleanUp(); } } } /// <summary> /// The type of threads to use - either foreground or background threads. /// </summary> public enum ThreadType { Foreground, Background } /// <summary> /// Provides settings for a dedicated thread pool /// </summary> public class ThreadPoolSettings { /// <summary> /// Background threads are the default thread type /// </summary> public const ThreadType DefaultThreadType = ThreadType.Background; public ThreadPoolSettings(int numThreads, string name = null, ApartmentState apartmentState = ApartmentState.Unknown, Action<Exception> exceptionHandler = null, int threadMaxStackSize = 0, ThreadPriority threadPriority = ThreadPriority.Normal) : this(numThreads, DefaultThreadType, name, apartmentState, exceptionHandler, threadMaxStackSize, threadPriority) { } public ThreadPoolSettings(int numThreads, ThreadType threadType, string name = null, ApartmentState apartmentState = ApartmentState.Unknown, Action<Exception> exceptionHandler = null, int threadMaxStackSize = 0, ThreadPriority threadPriority = ThreadPriority.Normal) { Name = name ?? ("DedicatedThreadPool-" + Guid.NewGuid()); ThreadType = threadType; ThreadPriority = threadPriority; NumThreads = numThreads; ApartmentState = apartmentState; ExceptionHandler = exceptionHandler ?? (ex => { ThrowHelper.FailFast("Unhandled exception in dedicated thread pool: " + ex.ToString()); }); ThreadMaxStackSize = threadMaxStackSize; if (numThreads <= 0) throw new ArgumentOutOfRangeException("numThreads", string.Format("numThreads must be at least 1. Was {0}", numThreads)); } /// <summary> /// The total number of threads to run in this thread pool. /// </summary> public int NumThreads { get; } /// <summary> /// The type of threads to run in this thread pool. /// </summary> public ThreadType ThreadType { get; } public ThreadPriority ThreadPriority { get; } /// <summary> /// Apartment state for threads to run in this thread pool /// </summary> public ApartmentState ApartmentState { get; } public string Name { get; } public Action<Exception> ExceptionHandler { get; } /// <summary> /// Gets the thread stack size, 0 represents the default stack size. /// </summary> public int ThreadMaxStackSize { get; } } /// <summary> /// Non-allocating thread pool. /// </summary> public class SpreadsThreadPool { // it's shared and there is a comment from MSFT that the number should // be larger than intuition tells. By default ThreadPool has number // of workers equals to processor count. public static readonly int DefaultDedicatedWorkerThreads = 1 * 16 + 1 * 8 + Environment.ProcessorCount * 4; // Without accessing this namespace and class it is not created private static SpreadsThreadPool _default; public static SpreadsThreadPool Default { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_default == null) { InitDefault(); } return _default; } } [MethodImpl(MethodImplOptions.NoInlining)] private static void InitDefault() { lock (typeof(SpreadsThreadPool)) { if (_default == null) { var settings = new ThreadPoolSettings(DefaultDedicatedWorkerThreads, "DefaultSpinningThreadPool"); _default = new SpreadsThreadPool(settings); ThreadPool.SetMinThreads(settings.NumThreads, settings.NumThreads); } } } internal readonly ThreadPoolWorkQueue workQueue; public ThreadPoolSettings Settings { get; } private readonly PoolWorker[] _workers; public SpreadsThreadPool(ThreadPoolSettings settings) { workQueue = new ThreadPoolWorkQueue(this); Settings = settings; _workers = new PoolWorker[settings.NumThreads]; for (int i = 0; i < settings.NumThreads; i++) { _workers[i] = new PoolWorker(this, i); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void QueueCompletableItem(Action<object> completable, object state, bool preferLocal) { if (completable == null) { ThrowHelper.ThrowArgumentNullException(nameof(completable)); } ExecutionContext context = null; if (!preferLocal) { context = ExecutionContext.Capture(); } // after ctx logic if (state != null) { preferLocal = false; } workQueue.Enqueue(completable, context, state, forceGlobal: !preferLocal); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void UnsafeQueueCompletableItem(Action<object> completable, object state, bool preferLocal) { Debug.Assert(null != completable); if (state != null) { preferLocal = false; } workQueue.Enqueue(completable, null, state, forceGlobal: !preferLocal); } // Get all workitems. Called by TaskScheduler in its debugger hooks. internal IEnumerable<(Action<object>, ExecutionContext, object)> GetQueuedWorkItems() { // Enumerate global queue foreach (var workItem in workQueue.workItems) { yield return workItem; } // Enumerate each local queue foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues) { if (wsq != null && wsq.m_array != null) { Action<object>[] items = wsq.m_array; for (int i = 0; i < items.Length; i++) { Action<object> item = items[i]; if (item != null) { yield return (item, null, null); } } } } } internal IEnumerable<(Action<object>, ExecutionContext, object)> GetLocallyQueuedWorkItems() { ThreadPoolWorkQueue.WorkStealingQueue wsq = ThreadPoolWorkQueue.ThreadPoolWorkQueueThreadLocals.threadLocals.workStealingQueue; if (wsq != null && wsq.m_array != null) { Action<object>[] items = wsq.m_array; for (int i = 0; i < items.Length; i++) { Action<object> item = items[i]; if (item != null) yield return (item, null, null); } } } internal IEnumerable<(Action<object>, ExecutionContext, object)> GetGloballyQueuedWorkItems() => workQueue.workItems; private object[] ToObjectArray(IEnumerable<(Action<object>, ExecutionContext, object)> workitems) { int i = 0; foreach ((Action<object>, ExecutionContext, object) item in workitems) { i++; } object[] result = new object[i]; i = 0; foreach ((Action<object>, ExecutionContext, object) item in workitems) { if (i < result.Length) //just in case someone calls us while the queues are in motion result[i] = item; i++; } return result; } // This is the method the debugger will actually call, if it ends up calling // into ThreadPool directly. Tests can use this to simulate a debugger, as well. internal object[] GetQueuedWorkItemsForDebugger() => ToObjectArray(GetQueuedWorkItems()); internal object[] GetGloballyQueuedWorkItemsForDebugger() => ToObjectArray(GetGloballyQueuedWorkItems()); internal object[] GetLocallyQueuedWorkItemsForDebugger() => ToObjectArray(GetLocallyQueuedWorkItems()); public void Dispose() { workQueue.CompleteAdding(); } public void WaitForThreadsExit() { WaitForThreadsExit(Timeout.InfiniteTimeSpan); } public void WaitForThreadsExit(TimeSpan timeout) { Task.WaitAll(_workers.Select(worker => worker.ThreadExit).ToArray(), timeout); } #region Pool worker implementation private class PoolWorker { private readonly SpreadsThreadPool _pool; private readonly TaskCompletionSource<object> _threadExit; public Task ThreadExit { get { return _threadExit.Task; } } public PoolWorker(SpreadsThreadPool pool, int workerId) { _pool = pool; _threadExit = new TaskCompletionSource<object>(); var thread = new Thread(RunThread, pool.Settings.ThreadMaxStackSize); thread.IsBackground = pool.Settings.ThreadType == ThreadType.Background; thread.Priority = pool.Settings.ThreadPriority; if (pool.Settings.Name != null) thread.Name = string.Format("{0}_{1}", pool.Settings.Name, workerId); if (pool.Settings.ApartmentState != ApartmentState.Unknown) thread.SetApartmentState(pool.Settings.ApartmentState); thread.Start(); } private void RunThread() { try { _pool.workQueue.Dispatch(); } finally { _threadExit.TrySetResult(null); } } } #endregion Pool worker implementation } #region UnfairSemaphore implementation /// <summary> /// This class has been translated from: /// https://github.com/dotnet/coreclr/blob/97433b9d153843492008652ff6b7c3bf4d9ff31c/src/vm/win32threadpool.h#L124 /// /// UnfairSemaphore is a more scalable semaphore than Semaphore.It prefers to release threads that have more recently begun waiting, /// to preserve locality.Additionally, very recently-waiting threads can be released without an addition kernel transition to unblock /// them, which reduces latency. /// /// UnfairSemaphore is only appropriate in scenarios where the order of unblocking threads is not important, and where threads frequently /// need to be woken. /// </summary> [StructLayout(LayoutKind.Sequential)] public sealed class UnfairSemaphore { public const int MaxWorker = 0x7FFF; // We track everything we care about in A 64-bit struct to allow us to // do CompareExchanges on this for atomic updates. [StructLayout(LayoutKind.Explicit)] private struct SemaphoreState { //how many threads are currently spin-waiting for this semaphore? [FieldOffset(0)] public short Spinners; //how much of the semaphore's count is availble to spinners? [FieldOffset(2)] public short CountForSpinners; //how many threads are blocked in the OS waiting for this semaphore? [FieldOffset(4)] public short Waiters; //how much count is available to waiters? [FieldOffset(6)] public short CountForWaiters; [FieldOffset(0)] public long RawData; } [StructLayout(LayoutKind.Explicit, Size = 64)] private struct CacheLinePadding { } private readonly Semaphore m_semaphore; // padding to ensure we get our own cache line #pragma warning disable 169 private readonly CacheLinePadding m_padding1; private SemaphoreState m_state; private readonly CacheLinePadding m_padding2; #pragma warning restore 169 public UnfairSemaphore() { m_semaphore = new Semaphore(0, short.MaxValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Wait() { return Wait(Timeout.InfiniteTimeSpan); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Wait(TimeSpan timeout) { while (true) { SemaphoreState currentCounts = GetCurrentState(); SemaphoreState newCounts = currentCounts; // First, just try to grab some count. if (currentCounts.CountForSpinners > 0) { --newCounts.CountForSpinners; if (TryUpdateState(newCounts, currentCounts)) return true; } else { // No count available, become a spinner ++newCounts.Spinners; if (TryUpdateState(newCounts, currentCounts)) break; } } // // Now we're a spinner. // int numSpins = 0; const int spinLimitPerProcessor = 50; while (true) { SemaphoreState currentCounts = GetCurrentState(); SemaphoreState newCounts = currentCounts; if (currentCounts.CountForSpinners > 0) { --newCounts.CountForSpinners; --newCounts.Spinners; if (TryUpdateState(newCounts, currentCounts)) return true; } else { double spinnersPerProcessor = (double)currentCounts.Spinners / Environment.ProcessorCount; int spinLimit = (int)((spinLimitPerProcessor / spinnersPerProcessor) + 0.5); if (numSpins >= spinLimit) { --newCounts.Spinners; ++newCounts.Waiters; if (TryUpdateState(newCounts, currentCounts)) break; } else { // // We yield to other threads using Thread.Sleep(0) rather than the more traditional Thread.Yield(). // This is because Thread.Yield() does not yield to threads currently scheduled to run on other // processors. On a 4-core machine, for example, this means that Thread.Yield() is only ~25% likely // to yield to the correct thread in some scenarios. // Thread.Sleep(0) has the disadvantage of not yielding to lower-priority threads. However, this is ok because // once we've called this a few times we'll become a "waiter" and wait on the Semaphore, and that will // yield to anything that is runnable. // Thread.Sleep(0); numSpins++; } } } // // Now we're a waiter // bool waitSucceeded = m_semaphore.WaitOne(timeout); while (true) { SemaphoreState currentCounts = GetCurrentState(); SemaphoreState newCounts = currentCounts; --newCounts.Waiters; if (waitSucceeded) --newCounts.CountForWaiters; if (TryUpdateState(newCounts, currentCounts)) return waitSucceeded; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Release() { Release(1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Release(short count) { while (true) { SemaphoreState currentState = GetCurrentState(); SemaphoreState newState = currentState; short remainingCount = count; // First, prefer to release existing spinners, // because a) they're hot, and b) we don't need a kernel // transition to release them. short spinnersToRelease = Math.Max((short)0, Math.Min(remainingCount, (short)(currentState.Spinners - currentState.CountForSpinners))); newState.CountForSpinners += spinnersToRelease; remainingCount -= spinnersToRelease; // Next, prefer to release existing waiters short waitersToRelease = Math.Max((short)0, Math.Min(remainingCount, (short)(currentState.Waiters - currentState.CountForWaiters))); newState.CountForWaiters += waitersToRelease; remainingCount -= waitersToRelease; // Finally, release any future spinners that might come our way newState.CountForSpinners += remainingCount; // Try to commit the transaction if (TryUpdateState(newState, currentState)) { // Now we need to release the waiters we promised to release if (waitersToRelease > 0) m_semaphore.Release(waitersToRelease); break; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryUpdateState(SemaphoreState newState, SemaphoreState currentState) { if (Interlocked.CompareExchange(ref m_state.RawData, newState.RawData, currentState.RawData) == currentState.RawData) { Debug.Assert(newState.CountForSpinners <= MaxWorker, "CountForSpinners is greater than MaxWorker"); Debug.Assert(newState.CountForSpinners >= 0, "CountForSpinners is lower than zero"); Debug.Assert(newState.Spinners <= MaxWorker, "Spinners is greater than MaxWorker"); Debug.Assert(newState.Spinners >= 0, "Spinners is lower than zero"); Debug.Assert(newState.CountForWaiters <= MaxWorker, "CountForWaiters is greater than MaxWorker"); Debug.Assert(newState.CountForWaiters >= 0, "CountForWaiters is lower than zero"); Debug.Assert(newState.Waiters <= MaxWorker, "Waiters is greater than MaxWorker"); Debug.Assert(newState.Waiters >= 0, "Waiters is lower than zero"); Debug.Assert(newState.CountForSpinners + newState.CountForWaiters <= MaxWorker, "CountForSpinners + CountForWaiters is greater than MaxWorker"); return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SemaphoreState GetCurrentState() { // Volatile.Read of a long can get a partial read in x86 but the invalid // state will be detected in TryUpdateState with the CompareExchange. SemaphoreState state = new SemaphoreState(); state.RawData = Volatile.Read(ref m_state.RawData); return state; } } #endregion UnfairSemaphore implementation }
39.004112
164
0.508318
[ "MPL-2.0" ]
andviklar/Spreads
src/Spreads.Core/Threading/SpreadsThreadPool.cs
47,431
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NLog; using Sandbox; using Sandbox.Common.ObjectBuilders; using Sandbox.Game.Entities; using VRage; using VRage.Game; using VRage.Game.Entity; using VRage.ObjectBuilders; using VRageMath; namespace ALE_Core.GridExport { public class GridManager { public static readonly Logger Log = LogManager.GetCurrentClassLogger(); public static bool SaveGrid(string path, string filename, bool keepOriginalOwner, bool keepProjection, List<MyCubeGrid> grids) { List<MyObjectBuilder_CubeGrid> objectBuilders = new List<MyObjectBuilder_CubeGrid>(); foreach (MyCubeGrid grid in grids) { /* What else should it be? LOL? */ if (!(grid.GetObjectBuilder(true) is MyObjectBuilder_CubeGrid objectBuilder)) throw new ArgumentException(grid + " has a ObjectBuilder thats not for a CubeGrid"); objectBuilders.Add(objectBuilder); } return SaveGrid(path, filename, keepOriginalOwner, keepProjection, objectBuilders); } public static bool SaveGrid(string path, string filename, bool keepOriginalOwner, bool keepProjection, List<MyObjectBuilder_CubeGrid> objectBuilders) { MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ShipBlueprintDefinition>(); definition.Id = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), filename); definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray(); /* Reset ownership as it will be different on the new server anyway */ foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids) { foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks) { if(!keepOriginalOwner) { cubeBlock.Owner = 0L; cubeBlock.BuiltBy = 0L; } /* Remove Projections if not needed */ if(!keepProjection) if (cubeBlock is MyObjectBuilder_ProjectorBase projector) projector.ProjectedGrids = null; /* Remove Pilot and Components (like Characters) from cockpits */ if (cubeBlock is MyObjectBuilder_Cockpit cockpit) { cockpit.Pilot = null; if (cockpit.ComponentContainer != null) { var components = cockpit.ComponentContainer.Components; if (components != null) { for (int i = components.Count - 1; i >= 0; i--) { var component = components[i]; if (component.TypeId == "MyHierarchyComponentBase") { components.RemoveAt(i); continue; } } } } } } } MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Definitions>(); builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition }; return MyObjectBuilderSerializer.SerializeXML(path, false, builderDefinition); } public static GridImportResult LoadGrid(string path, Vector3D playerPosition, bool keepOriginalLocation, bool force = false) { if (!File.Exists(path)) return GridImportResult.FILE_NOT_FOUND; if (MyObjectBuilderSerializer.DeserializeXML(path, out MyObjectBuilder_Definitions myObjectBuilder_Definitions)) { var shipBlueprints = myObjectBuilder_Definitions.ShipBlueprints; if (shipBlueprints == null) { Log.Warn("No ShipBlueprints in File '" + path + "'"); return GridImportResult.NO_GRIDS_IN_FILE; } foreach(var shipBlueprint in shipBlueprints) { var result = LoadShipBlueprint(shipBlueprint, playerPosition, keepOriginalLocation, force); if (result != GridImportResult.OK) { Log.Warn("Error Loading ShipBlueprints from File '" + path + "'"); return result; } } return GridImportResult.OK; } Log.Warn("Error Loading File '" + path + "' check Keen Logs."); return GridImportResult.UNKNOWN_ERROR; } private static GridImportResult LoadShipBlueprint(MyObjectBuilder_ShipBlueprintDefinition shipBlueprint, Vector3D playerPosition, bool keepOriginalLocation, bool force = false) { var grids = shipBlueprint.CubeGrids; if(grids == null || grids.Length == 0) { Log.Warn("No grids in blueprint!"); return GridImportResult.NO_GRIDS_IN_BLUEPRINT; } List<MyObjectBuilder_EntityBase> objectBuilderList = new List<MyObjectBuilder_EntityBase>(grids.ToList()); if (!keepOriginalLocation) { /* Where do we want to paste the grids? Lets find out. */ var pos = FindPastePosition(grids, playerPosition); if (pos == null) { Log.Warn("No free Space found!"); return GridImportResult.NO_FREE_SPACE_AVAILABLE; } var newPosition = pos.Value; /* Update GridsPosition if that doesnt work get out of here. */ if (!UpdateGridsPosition(grids, newPosition)) return GridImportResult.NOT_COMPATIBLE; } else if (!force) { var sphere = FindBoundingSphere(grids); var position = grids[0].PositionAndOrientation.Value; sphere.Center = position.Position; List<MyEntity> entities = new List<MyEntity>(); MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref sphere, entities); foreach (var entity in entities) if (entity is MyCubeGrid) return GridImportResult.POTENTIAL_BLOCKED_SPACE; } /* Stop grids */ foreach (var grid in grids) { grid.AngularVelocity = new SerializableVector3(); grid.LinearVelocity = new SerializableVector3(); } /* Remapping to prevent any key problems upon paste. */ MyEntities.RemapObjectBuilderCollection(objectBuilderList); bool hasMultipleGrids = objectBuilderList.Count > 1; if (!hasMultipleGrids) { foreach (var ob in objectBuilderList) MyEntities.CreateFromObjectBuilderParallel(ob, true); } else { MyEntities.Load(objectBuilderList, out _); } return GridImportResult.OK; } private static bool UpdateGridsPosition(MyObjectBuilder_CubeGrid[] grids, Vector3D newPosition) { bool firstGrid = true; double deltaX = 0; double deltaY = 0; double deltaZ = 0; foreach (var grid in grids) { var position = grid.PositionAndOrientation; if (position == null) { Log.Warn("Position and Orientation Information missing from Grid in file."); return false; } var realPosition = position.Value; var currentPosition = realPosition.Position; if (firstGrid) { deltaX = newPosition.X - currentPosition.X; deltaY = newPosition.Y - currentPosition.Y; deltaZ = newPosition.Z - currentPosition.Z; currentPosition.X = newPosition.X; currentPosition.Y = newPosition.Y; currentPosition.Z = newPosition.Z; firstGrid = false; } else { currentPosition.X += deltaX; currentPosition.Y += deltaY; currentPosition.Z += deltaZ; } realPosition.Position = currentPosition; grid.PositionAndOrientation = realPosition; } return true; } private static Vector3D? FindPastePosition(MyObjectBuilder_CubeGrid[] grids, Vector3D playerPosition) { BoundingSphere sphere = FindBoundingSphere(grids); /* * Now we know the radius that can house all grids which will now be * used to determine the perfect place to paste the grids to. */ return MyEntities.FindFreePlace(playerPosition, sphere.Radius); } private static BoundingSphereD FindBoundingSphere(MyObjectBuilder_CubeGrid[] grids) { Vector3? vector = null; float radius = 0F; foreach (var grid in grids) { var gridSphere = grid.CalculateBoundingSphere(); /* If this is the first run, we use the center of that grid, and its radius as it is */ if (vector == null) { vector = gridSphere.Center; radius = gridSphere.Radius; continue; } /* * If its not the first run, we use the vector we already have and * figure out how far it is away from the center of the subgrids sphere. */ float distance = Vector3.Distance(vector.Value, gridSphere.Center); /* * Now we figure out how big our new radius must be to house both grids * so the distance between the center points + the radius of our subgrid. */ float newRadius = distance + gridSphere.Radius; /* * If the new radius is bigger than our old one we use that, otherwise the subgrid * is contained in the other grid and therefore no need to make it bigger. */ if (newRadius > radius) radius = newRadius; } return new BoundingSphereD(vector.Value, radius); } } }
37.446367
159
0.561449
[ "Apache-2.0" ]
LordTylus/SE-Torch-ALE-Core
ALE-Core/GridExport/GridManager.cs
10,824
C#
namespace GraphQL.Common.Request { /// <summary> /// Represents a Query that can be fetched to a GraphQL Server. /// For more information <see href="http://graphql.org/learn/serving-over-http/#post-request"/> /// </summary> public class GraphQLRequest { /// <summary> /// The Query /// </summary> public string Query { get; set; } /// <summary> /// If the provided <see cref="Query"/> contains multiple named operations, this specifies which operation should be executed. /// </summary> public string OperationName { get; set; } /// <summary> /// The Variables /// </summary> public dynamic Variables { get; set; } } }
25.153846
128
0.655963
[ "MIT" ]
jasmin-mistry/graphql-client
src/GraphQL.Common/Request/GraphQLRequest.cs
654
C#
using System.Threading.Tasks; using Confluent.Kafka; using KafkaWelcomeKit.Infra; namespace KafkaWelcomeKit.Produzir { class ProdutorAssincrono2 : ProdutorAbstrato { public ProdutorAssincrono2(BrokerHelper brokerHelper, IMessageWriter messageWriter) : base(brokerHelper, messageWriter) { } //Neste exemplo, como utilizamos awaiter, o processo é interrompido de forma a aguardar o resultado do broker. // Similar a produzir de forma síncrona // Neste exemplo, a mensagem é postada com Key e Value public async Task Produzir<TChave, TValor>(string topico, TChave chave, TValor valor) { using (var p = new ProducerBuilder<TChave, TValor>(_brokerHelper.ProducerConfig).Build()) { try { var deliveryReport = await p.ProduceAsync(topico, new Message<TChave, TValor> { Key = chave, Value = valor}); _messageWriter.Write($"Entregou a mensagem com key '{deliveryReport.Message.Key}', value '{deliveryReport.Message.Value}' na partição '{deliveryReport.Partition}' e offset '{deliveryReport.Offset}'", MessageType.Output); } catch (ProduceException<string, string> e) { _messageWriter.Write($"Falha na entrega: {e.Error.Reason}", MessageType.Output); } } } } }
44.25
240
0.636299
[ "MIT" ]
michaelcostabr/KafkaWelcomeKit
Produzir/ProdutorAssincrono2.cs
1,423
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace Nettiers.AdventureWorks.Windows.Forms { /// <summary> /// This is the edit form for the <see cref="Entities.WorkOrderRouting"/> entity. /// </summary> [System.ComponentModel.DesignerCategoryAttribute("designer")] [System.Drawing.ToolboxBitmap(typeof(System.Windows.Forms.TableLayoutPanel))] public class WorkOrderRoutingEditControl : WorkOrderRoutingEditControlBase { } }
28.8
83
0.765625
[ "MIT" ]
aqua88hn/netTiers
Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Windows.Forms/UI/WorkOrderRoutingEditControl.cs
578
C#
using Crash; using System; namespace CrashEdit { public abstract class ChunkController : Controller { private NSFController nsfcontroller; private Chunk chunk; public ChunkController(NSFController nsfcontroller,Chunk chunk) { this.nsfcontroller = nsfcontroller; this.chunk = chunk; AddMenu("Delete Chunk",Menu_Delete_Chunk); } public NSFController NSFController { get { return nsfcontroller; } } public Chunk Chunk { get { return chunk; } } private void Menu_Delete_Chunk() { nsfcontroller.NSF.Chunks.Remove(chunk); Dispose(); } } }
21.542857
71
0.558355
[ "MIT" ]
aliostad/deep-learning-lang-detection
data/train/csharp/4efc024cff13bf018bf30b58c4dfdd31bfee39bcChunkController.cs
754
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using System.Text; namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2Model.Adapter.Negotiate { /// <summary> /// The configuration of server for negotiate /// </summary> public struct NegotiateServerConfig { /// <summary> /// SMB 2.002 or SMB 2.1 or SMB 3.0 /// </summary> public DialectRevision MaxSmbVersionSupported; /// <summary> /// Override ToString method to output the state info /// </summary> /// <returns></returns> public override string ToString() { StringBuilder outputInfo = new StringBuilder(); outputInfo.AppendFormat("{0}: {1}", "NegotiateServerConfig State", System.Environment.NewLine); outputInfo.AppendFormat("{0}: {1} {2}", "MaxSmbVersionSupported", this.MaxSmbVersionSupported.ToString(), System.Environment.NewLine); return outputInfo.ToString(); } } }
35.454545
146
0.655556
[ "MIT" ]
0neb1n/WindowsProtocolTestSuites
TestSuites/FileServer/src/SMB2Model/Adapter/Negotiate/NegotiateModelDataTypes.cs
1,172
C#
/* * Copyright 1999-2012 Alibaba Group. * * 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. */ using System.Collections.Generic; namespace Tup.Cobar4Net.Parser.Ast.Expression.Primary.Function.Groupby { /// <author> /// <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a> /// </author> public class Variance : FunctionExpression { public Variance(IList<IExpression> arguments) : base("VARIANCE", arguments) { } public override FunctionExpression ConstructFunction(IList<IExpression> arguments) { return new Variance(arguments); } } }
31.5
90
0.69224
[ "Apache-2.0" ]
tupunco/Tup.Cobar4Net
Tup.Cobar4Net/Parser/Ast/Expression/Primary/Function/Groupby/Variance.cs
1,134
C#
namespace MappingSPO.Project.DL.Entities { public partial class WCalculationExplorer2Entity { public WCalculationExplorer2Entity() { InitializePartial(); } public long CalcId { get; set; } public string CalcTypeId { get; set; } public string CalcMayorTypeCode { get; set; } public string CalcType { get; set; } public int? CalcYear { get; set; } public int? CalcNumber { get; set; } public int? CalcStatus { get; set; } public string FullCalcNumber { get; set; } public string VersionCalcNumber { get; set; } public long? VersionOriginalCalcId { get; set; } public string VersionOriginalCalcTypeId { get; set; } public int? VersionOriginalCalcYear { get; set; } public int? VersieNr { get; set; } public int? OriginalCalcNumber { get; set; } public string VersieOpmerking { get; set; } public string CalcName { get; set; } public double? Tkp { get; set; } public double? Tvp { get; set; } public System.DateTime? CreatedDate { get; set; } public System.DateTime? LastSaveData { get; set; } public int? CreatorId { get; set; } public string Creator { get; set; } public int? LockedById { get; set; } public string LockedBy { get; set; } public System.DateTime? Datum1 { get; set; } public System.DateTime? Datum2 { get; set; } public System.DateTime? OfferteDatum { get; set; } public System.DateTime? VervalDatum { get; set; } public System.DateTime? IndienDatum { get; set; } public System.DateTime? ExtraDate1 { get; set; } public System.DateTime? ExtraDate2 { get; set; } public System.DateTime? ExtraDate3 { get; set; } public System.DateTime? ExtraDate4 { get; set; } public System.DateTime? ExtraDate5 { get; set; } public int? CompanyId { get; set; } public string Company { get; set; } public int? Code1Id { get; set; } public int? Code2Id { get; set; } public int? Code3Id { get; set; } public int? Code4Id { get; set; } public int? Code5Id { get; set; } public int? Code6Id { get; set; } public int? Code7Id { get; set; } public int? Code8Id { get; set; } public string Code1 { get; set; } public string Code2 { get; set; } public string Code3 { get; set; } public string Code4 { get; set; } public string Code5 { get; set; } public string Code6 { get; set; } public string Code7 { get; set; } public string Code8 { get; set; } public string Ref1 { get; set; } public string Ref2 { get; set; } public string Ref3 { get; set; } public string Ref4 { get; set; } public int? CalculatorId { get; set; } public string Calculator { get; set; } public long? WerfId { get; set; } public string WerfTypeId { get; set; } public int? WerfYear { get; set; } public string WerfNr { get; set; } public string WerfName { get; set; } public long? ProjectId { get; set; } public string ProjectNrText { get; set; } public string ProjectName { get; set; } public string ProjectType { get; set; } public int? WerfNumber { get; set; } public int? ProjectYear { get; set; } public int? ProjectNumber { get; set; } public string LoonEc { get; set; } public double? LoonAantal { get; set; } public bool MarkedForDeletion { get; set; } public string DeletionErrorRemark { get; set; } public string WhoMarkedForDeletion { get; set; } public int CalcSoort { get; set; } public string Domain { get; set; } public string ProjectUnit { get; set; } public int? UnitState { get; set; } public string VolgNrYearText { get; set; } public string Verantwoordelijke1 { get; set; } public string Verantwoordelijke2 { get; set; } public string Verantwoordelijke3 { get; set; } public int? Verantwoordelijke1Id { get; set; } public int? Verantwoordelijke2Id { get; set; } public int? Verantwoordelijke3Id { get; set; } public double? ExtraNum1 { get; set; } public double? ExtraNum2 { get; set; } public double? ExtraNum3 { get; set; } public double? ExtraNum4 { get; set; } public double? ExtraNum5 { get; set; } public double? ExtraNum6 { get; set; } public double? ExtraNum7 { get; set; } public double? ExtraNum8 { get; set; } public long? BaseCalcId { get; set; } public long? OnderaannemerRelationId { get; set; } public string OnderaannemerName { get; set; } public string OnderaannemerEmail1 { get; set; } public string OnderaannemerPhone1 { get; set; } public string OnderaannemerGsm { get; set; } public string InkoopCategory { get; set; } public string InkoopCategoryGroup { get; set; } public int UiVersion { get; set; } partial void InitializePartial(); } }
44.279661
61
0.594641
[ "MIT" ]
hmohcine/MappingSPO
MappingSPO.Project.DL/Entities/WCalculationExplorer2Entity.cs
5,225
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; var stopwatch = Stopwatch.StartNew(); var data = (from line in File.ReadAllLines("input.txt") where !string.IsNullOrWhiteSpace(line) select line).ToArray(); long GetPart1() { return 0L; } long GetPart2() { return 0L; } Console.WriteLine($"[{stopwatch.Elapsed}] Pre-compute"); stopwatch = Stopwatch.StartNew(); var part1Result = GetPart1(); Console.WriteLine($"[{stopwatch.Elapsed}] Part 1: {part1Result}"); stopwatch = Stopwatch.StartNew(); var part2Result = GetPart2(); Console.WriteLine($"[{stopwatch.Elapsed}] Part 2: {part2Result}");
20.060606
66
0.731118
[ "MIT" ]
bradwilson/advent-2020
_template/project/Program.cs
662
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqlOverExcelUI.Models { public class AppSettingsModel { public string AceVersion = ""; public string UILanguage = ""; } }
17.4375
38
0.698925
[ "MIT" ]
KohrAhr/ExcelSplitter
WpfApp/SqlOverExcelUI/Models/AppSettingsModel.cs
281
C#
using System; class Tim { public const int RUN = 32; public static void insertionSort(int[] lst, int left, int right) { for (int i = left + 1; i <= right; i++) { int temp = lst[i]; int j = i - 1; while (j >= left && lst[j] > temp) { lst[j+1] = lst[j]; j--; } lst[j+1] = temp; } } public static void merge(int[] lst, int l, int m, int r) { int len1 = m - l + 1, len2 = r - m; int[] left = new int[len1]; int[] right = new int[len2]; for (int x = 0; x < len1; x++) left[x] = lst[l + x]; for (int x = 0; x < len2; x++) right[x] = lst[m + 1 + x]; int i = 0; int j = 0; int k = l; while (i < len1 && j < len2) { if (left[i] <= right[j]) { lst[k] = left[i]; i++; } else { lst[k] = right[j]; j++; } k++; } while (i < len1) { lst[k] = left[i]; k++; i++; } while (j < len2) { lst[k] = right[j]; k++; j++; } } public static void timSort(int[] lst, int n) { for (int i = 0; i < n; i+=RUN) insertionSort(lst, i, Math.Min((i+31), (n-1))); for (int size = RUN; size < n; size = 2*size) { for (int left = 0; left < n; left += 2*size) { int mid = left + size - 1; int right = Math.Min((left + 2*size - 1), (n-1)); merge(lst, left, mid, right); } } } public static void printArray(int[] lst, int n) { for (int i = 0; i < n; i++) Console.Write(lst[i] + " "); Console.Write("\n"); } public static void Main() { int[] lst = {5, 21, 7, 23, 19}; //sample input int n = lst.Length; Console.Write("Given Array is\n"); printArray(lst, n); timSort(lst, n); Console.Write("After Sorting Array is\n"); printArray(lst, n); // sample output: 5 7 19 21 23 } //This code is contributed by tanishq67 } //space complexity O(n); //Time complexity O(nlog(n));
28.257732
71
0.336374
[ "MIT" ]
0xEnlighten/DS-Algo-Point
C#/Tim_sort.cs
2,741
C#
using UnityEngine; using System.Collections; using UnityStandardAssets.Characters.FirstPerson; [ExecuteInEditMode] public class FirstPersonCharacterCull : MonoBehaviour { private bool _stopCullingThingsForASecond = false; public bool StopCullingThingsForASecond { get { return this._stopCullingThingsForASecond; } set { this._stopCullingThingsForASecond = value; } } public MeshRenderer [] RenderersToHide; //Mesh renderer that you want this script's camera to cull public PhysicsRemoteFPSAgentController FPSController; //references to renderers for when Agent is in Tall mode public MeshRenderer [] TallRenderers; //references to renderers for when the Agent is in Bot mode public MeshRenderer [] BotRenderers; //references to renderers for when agent is in Drone mode public MeshRenderer [] DroneRenderers; public void SwitchRenderersToHide(string mode) { if(mode == "default") RenderersToHide = TallRenderers; else if(mode == "bot") RenderersToHide = BotRenderers; else if(mode == "drone") RenderersToHide = DroneRenderers; } void OnPreRender() //Just before this camera starts to render... { if(!StopCullingThingsForASecond) { if(FPSController != null && (RenderersToHide != null || RenderersToHide.Length != 0) && FPSController.IsVisible)//only do this if visibility capsule has been toggled on { foreach (MeshRenderer mr in RenderersToHide) { mr.enabled = false; //Turn off renderer } } } } void OnPostRender() //Immediately after this camera renders... { if(!StopCullingThingsForASecond) { if(FPSController != null && (RenderersToHide != null || RenderersToHide.Length != 0) && FPSController.IsVisible)//only do this if visibility capsule is toggled on { foreach (MeshRenderer mr in RenderersToHide) { mr.enabled = true; //Turn it back on } } } } }
30.133333
102
0.606637
[ "Apache-2.0" ]
maiae061/ai2thor
unity/Assets/Scripts/FirstPersonCharacterCull.cs
2,262
C#
using System; using System.Collections.Generic; using System.Data.Entity.Core; using System.Linq; using System.Threading.Tasks; using System.Web.Http; using EF.DbContextFactory.Examples.Data.Entity; using EF.DbContextFactory.Examples.Data.Repository; using Microsoft.VisualStudio.TestTools.UnitTesting; using StructureMap; using WebApi.StructureMap; namespace EF.DbContextFactory.IntegrationTest.StructureMap41.WebApi { [TestCategory("StructureMap.WebApi")] [TestClass] public class StructureMapTests { [ClassInitialize] public static void SetUp(TestContext context) { GlobalConfiguration.Configuration.UseStructureMap<CustomRegistry>(); } [TestMethod] public async Task StructureMapWebApi_add_orders_without_EF_DbContextFactory() { var container = new Container(); var repo = container.GetInstance<OrderRepository>(); var orderManager = new OrderManager(repo); await Assert.ThrowsExceptionAsync<EntityException>(async () => { try { var orders = new List<Order>(); await orderManager.Create(out orders); } catch (Exception ex) { throw new EntityException("Entity framework thread safe exception", ex); } }); } [TestMethod] public void StructureMapWebApi_add_orders_with_EF_DbContextFactory() { ResetDataBase(); var container = new Container(); var repo = container.GetInstance<OrderRepositoryWithFactory>(); var orderManager = new OrderManager(repo); var orders = new List<Order>(); var task = orderManager.Create(out orders); task.Wait(); Assert.AreEqual(TaskStatus.RanToCompletion, task.Status); Assert.AreEqual(3, repo.GetAllOrders().Count()); } [TestMethod] public async Task StructureMapWebApi_delete_orders_with_EF_DbContextFactory() { ResetDataBase(); var container = new Container(); var repo = container.GetInstance<OrderRepositoryWithFactory>(); var orderManager = new OrderManager(repo); var orders = new List<Order>(); await orderManager.Create(out orders); var task = orderManager.Delete(orders); task.Wait(); Assert.AreEqual(TaskStatus.RanToCompletion, task.Status); Assert.AreEqual(0, repo.GetAllOrders().Count()); } [TestMethod] public async Task StructureMapWebApi_delete_orders_without_EF_DbContextFactory() { ResetDataBase(); var container = new Container(); var repo = container.GetInstance<OrderRepository>(); var repoWithFactory = container.GetInstance<OrderRepositoryWithFactory>(); var orderManager = new OrderManager(repo); var orderManagerWithFactory = new OrderManager(repoWithFactory); var orders = new List<Order>(); await orderManagerWithFactory.Create(out orders); await Assert.ThrowsExceptionAsync<EntityException>(async () => { try { await orderManager.Delete(orders); } catch (Exception ex) { throw new EntityException("Entity framework thread safe exception", ex); } }); } private static void ResetDataBase() { var container = new Container(); var repo = container.GetInstance<OrderRepository>(); repo.DeleteAll(); } } }
34.330357
92
0.593238
[ "MIT" ]
Meberem/EF.DbContextFactory
src/Tests/EF.DbContextFactory.IntegrationTest.StructureMap41.WebApi/StructureMapTests.cs
3,847
C#
// ***************************************************************************** // 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; using System.Drawing; using System.Drawing.Design; using System.ComponentModel; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Represents a single ribbon quick access toolbar entry. /// </summary> [ToolboxItem(false)] [ToolboxBitmap(typeof(KryptonRibbonQATButton), "ToolboxBitmaps.KryptonRibbonQATButton.bmp")] [DefaultEvent("Click")] [DefaultProperty("Image")] [DesignerCategory("code")] [DesignTimeVisible(false)] public class KryptonRibbonQATButton : Component, IQuickAccessToolbarButton { #region Static Fields private static readonly Image _defaultImage = Properties.Resources.QATButtonDefault; #endregion #region Instance Fields private object _tag; private Image _image; private bool _visible; private bool _enabled; private string _text; private KryptonCommand _command; #endregion #region Events /// <summary> /// Occurs when the quick access toolbar button has been clicked. /// </summary> public event EventHandler Click; /// <summary> /// Occurs after the value of a property has changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Identity /// <summary> /// Initialise a new instance of the KryptonRibbonQATButton class. /// </summary> public KryptonRibbonQATButton() { // Default fields _image = _defaultImage; _visible = true; _enabled = true; _text = "QAT Button"; ShortcutKeys = Keys.None; ToolTipImageTransparentColor = Color.Empty; ToolTipTitle = string.Empty; ToolTipBody = string.Empty; ToolTipStyle = LabelStyle.ToolTip; } #endregion #region Public /// <summary> /// Gets access to the owning ribbon control. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public KryptonRibbon Ribbon { get; private set; } /// <summary> /// Gets and sets the application button image. /// </summary> [Bindable(true)] [Localizable(true)] [Category("Values")] [Description("Application button image.")] [RefreshPropertiesAttribute(RefreshProperties.All)] public Image Image { get => _image; set { if (_image != value) { if (value != null) { // The image must be 16x16 or less in order to be displayed on the // quick access toolbar. So we reject anything bigger than 16x16. if ((value.Width > 16) || (value.Height > 16)) { throw new ArgumentOutOfRangeException("Image must be 16x16 or smaller."); } } _image = value; OnPropertyChanged("Image"); // Only need to update display if we are visible if (Visible) { Ribbon?.PerformNeedPaint(false); } } } } private bool ShouldSerializeImage() { return Image != _defaultImage; } /// <summary> /// Gets and sets the visible state of the ribbon quick access toolbar entry. /// </summary> [Bindable(true)] [Category("Behavior")] [Description("Determines whether the ribbon quick access toolbar entry is visible or hidden.")] [DefaultValue(true)] public bool Visible { get => _visible; set { if (value != _visible) { _visible = value; OnPropertyChanged("Visible"); // Must try and layout to show change if (Ribbon != null) { Ribbon.PerformNeedPaint(true); Ribbon.UpdateQAT(); } } } } /// <summary> /// Make the ribbon tab visible. /// </summary> public void Show() { Visible = true; } /// <summary> /// Make the ribbon tab hidden. /// </summary> public void Hide() { Visible = false; } /// <summary> /// Gets and sets the enabled state of the ribbon quick access toolbar entry. /// </summary> [Bindable(true)] [Category("Behavior")] [Description("Determines whether the ribbon quick access toolbar entry is enabled.")] [DefaultValue(true)] public bool Enabled { get => _enabled; set { if (value != _enabled) { _enabled = value; OnPropertyChanged("Enabled"); // Must try and paint to show change if (Visible) { Ribbon?.PerformNeedPaint(false); } } } } /// <summary> /// Gets and sets the display text of the quick access toolbar button. /// </summary> [Bindable(true)] [Localizable(true)] [Category("Appearance")] [Description("QAT button text.")] [RefreshPropertiesAttribute(RefreshProperties.All)] [DefaultValue("QAT Button")] public string Text { get => _text; set { // We never allow an empty text value if (string.IsNullOrEmpty(value)) { value = "QAT Button"; } if (value != _text) { _text = value; OnPropertyChanged("Text"); } } } /// <summary> /// Gets and sets the shortcut key combination. /// </summary> [Localizable(true)] [Category("Behavior")] [Description("Shortcut key combination to fire click event of the quick access toolbar button.")] public Keys ShortcutKeys { get; set; } private bool ShouldSerializeShortcutKeys() { return (ShortcutKeys != Keys.None); } /// <summary> /// Resets the ShortcutKeys property to its default value. /// </summary> public void ResetShortcutKeys() { ShortcutKeys = Keys.None; } /// <summary> /// Gets and sets the tooltip label style for the quick access button. /// </summary> [Category("Appearance")] [Description("Tooltip style for the quick access toolbar button.")] [DefaultValue(typeof(LabelStyle), "ToolTip")] public LabelStyle ToolTipStyle { get; set; } /// <summary> /// Gets and sets the image for the item ToolTip. /// </summary> [Bindable(true)] [Category("Appearance")] [Description("Display image associated ToolTip.")] [DefaultValue(null)] [Localizable(true)] public Image ToolTipImage { get; set; } /// <summary> /// Gets and sets the color to draw as transparent in the ToolTipImage. /// </summary> [Bindable(true)] [Category("Appearance")] [Description("Color to draw as transparent in the ToolTipImage.")] [KryptonDefaultColorAttribute()] [Localizable(true)] public Color ToolTipImageTransparentColor { get; set; } /// <summary> /// Gets and sets the title text for the item ToolTip. /// </summary> [Bindable(true)] [Category("Appearance")] [Description("Title text for use in associated ToolTip.")] [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [DefaultValue("")] [Localizable(true)] public string ToolTipTitle { get; set; } /// <summary> /// Gets and sets the body text for the item ToolTip. /// </summary> [Bindable(true)] [Category("Appearance")] [Description("Body text for use in associated ToolTip.")] [Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [DefaultValue("")] [Localizable(true)] public string ToolTipBody { get; set; } /// <summary> /// Gets and sets the associated KryptonCommand. /// </summary> [Category("Behavior")] [Description("Command associated with the quick access toolbar button.")] [DefaultValue(null)] public KryptonCommand KryptonCommand { get => _command; set { if (_command != value) { if (_command != null) { _command.PropertyChanged -= OnCommandPropertyChanged; } _command = value; OnPropertyChanged("KryptonCommand"); if (_command != null) { _command.PropertyChanged += OnCommandPropertyChanged; } // Only need to update display if we are visible if (Visible) { Ribbon?.PerformNeedPaint(false); } } } } /// <summary> /// Gets and sets user-defined data associated with the object. /// </summary> [Category("Data")] [Description("User-defined data associated with the object.")] [TypeConverter(typeof(StringConverter))] [Bindable(true)] public object Tag { get => _tag; set { if (value != _tag) { _tag = value; OnPropertyChanged("Tag"); } } } private bool ShouldSerializeTag() { return (Tag != null); } private void ResetTag() { Tag = null; } #endregion #region IQuickAccessToolbarButton /// <summary> /// Provides a back reference to the owning ribbon control instance. /// </summary> /// <param name="ribbon">Reference to owning instance.</param> [EditorBrowsable(EditorBrowsableState.Advanced)] public void SetRibbon(KryptonRibbon ribbon) { Ribbon = ribbon; } /// <summary> /// Gets the entry image. /// </summary> /// <returns>Image value.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public Image GetImage() => KryptonCommand?.ImageSmall ?? Image; /// <summary> /// Gets the entry text. /// </summary> /// <returns>Text value.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public string GetText() => KryptonCommand?.TextLine1 ?? Text; /// <summary> /// Gets the entry enabled state. /// </summary> /// <returns>Enabled value.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public bool GetEnabled() => KryptonCommand?.Enabled ?? Enabled; /// <summary> /// Gets the entry shortcut keys state. /// </summary> /// <returns>ShortcutKeys value.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public Keys GetShortcutKeys() { return ShortcutKeys; } /// <summary> /// Gets the entry visible state. /// </summary> /// <returns>Visible value.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] public bool GetVisible() { return Visible; } /// <summary> /// Sets a new value for the visible state. /// </summary> /// <param name="visible"></param> [EditorBrowsable(EditorBrowsableState.Advanced)] public void SetVisible(bool visible) { Visible = visible; } /// <summary> /// Gets the tooltip label style. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public LabelStyle GetToolTipStyle() { return ToolTipStyle; } /// <summary> /// Gets and sets the image for the item ToolTip. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public Image GetToolTipImage() { return ToolTipImage; } /// <summary> /// Gets and sets the color to draw as transparent in the ToolTipImage. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public Color GetToolTipImageTransparentColor() { return ToolTipImageTransparentColor; } /// <summary> /// Gets and sets the title text for the item ToolTip. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public string GetToolTipTitle() { return ToolTipTitle; } /// <summary> /// Gets and sets the body text for the item ToolTip. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public string GetToolTipBody() { return ToolTipBody; } /// <summary> /// Generates a Click event for a button. /// </summary> public void PerformClick() { OnClick(EventArgs.Empty); } #endregion #region Protected /// <summary> /// Handles a change in the property of an attached command. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">A PropertyChangedEventArgs that contains the event data.</param> protected virtual void OnCommandPropertyChanged(object sender, PropertyChangedEventArgs e) { bool refresh = false; switch (e.PropertyName) { case "Text": refresh = true; OnPropertyChanged("Text"); break; case "ImageSmall": refresh = true; OnPropertyChanged("Image"); break; case "Enabled": refresh = true; OnPropertyChanged("Enabled"); break; } if (refresh) { // Only need to update display if we are visible if (Visible) { Ribbon?.PerformNeedPaint(false); } } } /// <summary> /// Raises the Click event. /// </summary> /// <param name="e">An EventArgs containing the event data.</param> protected virtual void OnClick(EventArgs e) { // Perform processing that is common to any action that would dismiss // any popup controls such as the showing minimized group popup Ribbon?.ActionOccured(); Click?.Invoke(this, e); // Clicking the button should execute the associated command KryptonCommand?.PerformExecute(); } /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">Name of property that has changed.</param> protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
31.959927
174
0.519036
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.400
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/Controls Ribbon/KryptonRibbonQATButton.cs
17,549
C#
using Serenity.Abstractions; using System; using System.ComponentModel; using System.Reflection; namespace Serenity.Localization { /// <summary> /// Contains initialization method for adding local text translations defined by /// Description attributes in enumeration classes. /// </summary> public static class EnumLocalTextRegistration { /// <summary> /// Adds local text translations defined implicitly by Description attributes in /// enumeration classes. Only enum values that has Description attribute are added as /// local text. By default, enums are registered in format: /// "Enums.{EnumerationTypeFullName}.{EnumValueName}". EnumerationTypeFullName, is /// fullname of the enumeration type. This can be overridden by attaching a EnumKey /// attribute. /// </summary> /// <param name="typeSource">Type source to search for enumeration classes in</param> /// <param name="languageID">Language ID texts will be added (default is invariant language)</param> /// <param name="registry">Registry</param> public static void AddEnumTexts(this ILocalTextRegistry registry, ITypeSource typeSource, string languageID = LocalText.InvariantLanguageID) { if (typeSource == null) throw new ArgumentNullException("assemblies"); var provider = registry ?? throw new ArgumentNullException(nameof(registry)); foreach (var type in typeSource.GetTypes()) { if (type.IsEnum) { var enumKey = EnumMapper.GetEnumTypeKey(type); foreach (var name in Enum.GetNames(type)) { var member = type.GetMember(name); if (member.Length == 0) continue; var descAttr = member[0].GetCustomAttribute<DescriptionAttribute>(); if (descAttr != null) provider.Add(languageID, "Enums." + enumKey + "." + name, descAttr.Description); } } } } } }
42.185185
109
0.575944
[ "MIT" ]
JarLob/Serenity
src/Serenity.Net.Core/Localization/EnumLocalTextRegistration.cs
2,280
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.IO; using System.Text; using Microsoft.Data.Sqlite.Properties; using SQLitePCL; namespace Microsoft.Data.Sqlite { /// <summary> /// Provides methods for reading the result of a command executed against a SQLite database. /// </summary> public class SqliteDataReader : DbDataReader { private readonly SqliteCommand _command; private readonly bool _closeConnection; private readonly Queue<(sqlite3_stmt stmt, bool)> _stmtQueue; private sqlite3_stmt _stmt; private SqliteDataRecord _record; private bool _hasRows; private bool _stepped; private bool _done; private bool _closed; internal SqliteDataReader( SqliteCommand command, Queue<(sqlite3_stmt, bool)> stmtQueue, int recordsAffected, bool closeConnection) { if (stmtQueue.Count != 0) { (_stmt, _hasRows) = stmtQueue.Dequeue(); _record = new SqliteDataRecord(_stmt, command.Connection); } _command = command; _stmtQueue = stmtQueue; RecordsAffected = recordsAffected; _closeConnection = closeConnection; } /// <summary> /// Gets the depth of nesting for the current row. Always zero. /// </summary> /// <value>The depth of nesting for the current row.</value> public override int Depth => 0; /// <summary> /// Gets the number of columns in the current row. /// </summary> /// <value>The number of columns in the current row.</value> public override int FieldCount => _closed ? throw new InvalidOperationException(Resources.DataReaderClosed(nameof(FieldCount))) : _record.FieldCount; /// <summary> /// Gets a handle to underlying prepared statement. /// </summary> /// <value>A handle to underlying prepared statement.</value> /// <seealso href="http://sqlite.org/c3ref/stmt.html">Prepared Statement Object</seealso> public virtual sqlite3_stmt Handle => _stmt; /// <summary> /// Gets a value indicating whether the data reader contains any rows. /// </summary> /// <value>A value indicating whether the data reader contains any rows.</value> public override bool HasRows => _hasRows; /// <summary> /// Gets a value indicating whether the data reader is closed. /// </summary> /// <value>A value indicating whether the data reader is closed.</value> public override bool IsClosed => _closed; /// <summary> /// Gets the number of rows inserted, updated, or deleted. -1 for SELECT statements. /// </summary> /// <value>The number of rows inserted, updated, or deleted.</value> public override int RecordsAffected { get; } /// <summary> /// Gets the value of the specified column. /// </summary> /// <param name="name">The name of the column. The value is case-sensitive.</param> /// <returns>The value.</returns> public override object this[string name] => _record[name]; /// <summary> /// Gets the value of the specified column. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value.</returns> public override object this[int ordinal] => _record[ordinal]; /// <summary> /// Gets an enumerator that can be used to iterate through the rows in the data reader. /// </summary> /// <returns>The enumerator.</returns> public override IEnumerator GetEnumerator() => new DbEnumerator(this, closeReader: false); /// <summary> /// Advances to the next row in the result set. /// </summary> /// <returns>true if there are more rows; otherwise, false.</returns> public override bool Read() { if (_closed) { throw new InvalidOperationException(Resources.DataReaderClosed(nameof(Read))); } if (!_stepped) { _stepped = true; return _hasRows; } var rc = raw.sqlite3_step(_stmt); SqliteException.ThrowExceptionForRC(rc, _command.Connection.Handle); _record.Clear(); _done = rc == raw.SQLITE_DONE; return !_done; } /// <summary> /// Advances to the next result set for batched statements. /// </summary> /// <returns>true if there are more result sets; otherwise, false.</returns> public override bool NextResult() { if (_stmtQueue.Count == 0) { return false; } raw.sqlite3_reset(_stmt); (_stmt, _hasRows) = _stmtQueue.Dequeue(); _record = new SqliteDataRecord(_stmt, _command.Connection); _stepped = false; _done = false; return true; } /// <summary> /// Closes the data reader. /// </summary> public override void Close() => Dispose(true); /// <summary> /// Releases any resources used by the data reader and closes it. /// </summary> /// <param name="disposing"> /// true to release managed and unmanaged resources; false to release only unmanaged resources. /// </param> protected override void Dispose(bool disposing) { if (!disposing) { return; } _command.DataReader = null; if (_stmt != null) { raw.sqlite3_reset(_stmt); _stmt = null; _record = null; } while (_stmtQueue.Count != 0) { raw.sqlite3_reset(_stmtQueue.Dequeue().stmt); } _closed = true; if (_closeConnection) { _command.Connection.Close(); } } /// <summary> /// Gets the name of the specified column. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The name of the column.</returns> public override string GetName(int ordinal) { if (_closed) { throw new InvalidOperationException(Resources.DataReaderClosed(nameof(GetName))); } return _record.GetName(ordinal); } /// <summary> /// Gets the ordinal of the specified column. /// </summary> /// <param name="name">The name of the column.</param> /// <returns>The zero-based column ordinal.</returns> public override int GetOrdinal(string name) => _record.GetOrdinal(name); /// <summary> /// Gets the declared data type name of the specified column. The storage class is returned for computed /// columns. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The data type name of the column.</returns> /// <remarks>Due to SQLite's dynamic type system, this may not reflect the actual type of the value.</remarks> /// <seealso href="http://sqlite.org/datatype3.html">Datatypes In SQLite Version 3</seealso> public override string GetDataTypeName(int ordinal) { if (_closed) { throw new InvalidOperationException(Resources.DataReaderClosed(nameof(GetDataTypeName))); } return _record.GetDataTypeName(ordinal); } /// <summary> /// Gets the data type of the specified column. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The data type of the column.</returns> public override Type GetFieldType(int ordinal) { if (_closed) { throw new InvalidOperationException(Resources.DataReaderClosed(nameof(GetFieldType))); } return _record.GetFieldType(ordinal); } /// <summary> /// Gets a value indicating whether the specified column is <see cref="DBNull" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>true if the specified column is <see cref="DBNull" />; otherwise, false.</returns> public override bool IsDBNull(int ordinal) => _closed ? throw new InvalidOperationException(Resources.DataReaderClosed(nameof(IsDBNull))) : !_stepped || _done ? throw new InvalidOperationException(Resources.NoData) : _record.IsDBNull(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="bool" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override bool GetBoolean(int ordinal) => _record.GetBoolean(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="byte" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override byte GetByte(int ordinal) => _record.GetByte(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="char" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override char GetChar(int ordinal) => _record.GetChar(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="DateTime" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override DateTime GetDateTime(int ordinal) => _record.GetDateTime(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="DateTimeOffset" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public virtual DateTimeOffset GetDateTimeOffset(int ordinal) => _record.GetDateTimeOffset(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="TimeSpan" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public virtual TimeSpan GetTimeSpan(int ordinal) => _record.GetTimeSpan(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="decimal" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override decimal GetDecimal(int ordinal) => _record.GetDecimal(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="double" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override double GetDouble(int ordinal) => _record.GetDouble(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="float" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override float GetFloat(int ordinal) => _record.GetFloat(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="Guid" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override Guid GetGuid(int ordinal) => _record.GetGuid(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="short" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override short GetInt16(int ordinal) => _record.GetInt16(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="int" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override int GetInt32(int ordinal) => _record.GetInt32(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="long" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override long GetInt64(int ordinal) => _record.GetInt64(ordinal); /// <summary> /// Gets the value of the specified column as a <see cref="string" />. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override string GetString(int ordinal) => _record.GetString(ordinal); /// <summary> /// Reads a stream of bytes from the specified column. Not supported. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <param name="dataOffset">The index from which to begin the read operation.</param> /// <param name="buffer">The buffer into which the data is copied.</param> /// <param name="bufferOffset">The index to which the data will be copied.</param> /// <param name="length">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read.</returns> public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) => _record.GetBytes(ordinal, dataOffset, buffer, bufferOffset, length); /// <summary> /// Reads a stream of characters from the specified column. Not supported. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <param name="dataOffset">The index from which to begin the read operation.</param> /// <param name="buffer">The buffer into which the data is copied.</param> /// <param name="bufferOffset">The index to which the data will be copied.</param> /// <param name="length">The maximum number of characters to read.</param> /// <returns>The actual number of characters read.</returns> public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) => _record.GetChars(ordinal, dataOffset, buffer, bufferOffset, length); /// <summary> /// Retrieves data as a Stream. If the reader includes rowid (or any of its aliases), a /// <see cref="SqliteBlob" /> is returned. Otherwise, the all of the data is read into memory and a /// <see cref="MemoryStream" /> is returned. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The returned object.</returns> public override Stream GetStream(int ordinal) => _record.GetStream(ordinal); /// <summary> /// Gets the value of the specified column. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override T GetFieldValue<T>(int ordinal) { if (typeof(T) == typeof(DBNull) && (!_stepped || _done)) { throw new InvalidOperationException(Resources.NoData); } return _record.GetFieldValue<T>(ordinal); } /// <summary> /// Gets the value of the specified column. /// </summary> /// <param name="ordinal">The zero-based column ordinal.</param> /// <returns>The value of the column.</returns> public override object GetValue(int ordinal) { if (_closed) { throw new InvalidOperationException(Resources.DataReaderClosed(nameof(GetValue))); } if (!_stepped || _done) { throw new InvalidOperationException(Resources.NoData); } return _record.GetValue(ordinal); } /// <summary> /// Gets the column values of the current row. /// </summary> /// <param name="values">An array into which the values are copied.</param> /// <returns>The number of values copied into the array.</returns> public override int GetValues(object[] values) => _record.GetValues(values); /// <summary> /// Returns a System.Data.DataTable that describes the column metadata of the System.Data.Common.DbDataReader. /// </summary> /// <returns>A System.Data.DataTable that describes the column metadata.</returns> public override DataTable GetSchemaTable() { var schemaTable = new DataTable("SchemaTable"); var ColumnName = new DataColumn(SchemaTableColumn.ColumnName, typeof(string)); var ColumnOrdinal = new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(int)); var ColumnSize = new DataColumn(SchemaTableColumn.ColumnSize, typeof(int)); var NumericPrecision = new DataColumn(SchemaTableColumn.NumericPrecision, typeof(short)); var NumericScale = new DataColumn(SchemaTableColumn.NumericScale, typeof(short)); var DataType = new DataColumn(SchemaTableColumn.DataType, typeof(Type)); var DataTypeName = new DataColumn("DataTypeName", typeof(string)); var IsLong = new DataColumn(SchemaTableColumn.IsLong, typeof(bool)); var AllowDBNull = new DataColumn(SchemaTableColumn.AllowDBNull, typeof(bool)); var IsUnique = new DataColumn(SchemaTableColumn.IsUnique, typeof(bool)); var IsKey = new DataColumn(SchemaTableColumn.IsKey, typeof(bool)); var IsAutoIncrement = new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool)); var BaseCatalogName = new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(string)); var BaseSchemaName = new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(string)); var BaseTableName = new DataColumn(SchemaTableColumn.BaseTableName, typeof(string)); var BaseColumnName = new DataColumn(SchemaTableColumn.BaseColumnName, typeof(string)); var BaseServerName = new DataColumn(SchemaTableOptionalColumn.BaseServerName, typeof(string)); var IsAliased = new DataColumn(SchemaTableColumn.IsAliased, typeof(bool)); var IsExpression = new DataColumn(SchemaTableColumn.IsExpression, typeof(bool)); var columns = schemaTable.Columns; columns.Add(ColumnName); columns.Add(ColumnOrdinal); columns.Add(ColumnSize); columns.Add(NumericPrecision); columns.Add(NumericScale); columns.Add(IsUnique); columns.Add(IsKey); columns.Add(BaseServerName); columns.Add(BaseCatalogName); columns.Add(BaseColumnName); columns.Add(BaseSchemaName); columns.Add(BaseTableName); columns.Add(DataType); columns.Add(DataTypeName); columns.Add(AllowDBNull); columns.Add(IsAliased); columns.Add(IsExpression); columns.Add(IsAutoIncrement); columns.Add(IsLong); for (var i = 0; i < FieldCount; i++) { var schemaRow = schemaTable.NewRow(); schemaRow[ColumnName] = GetName(i); schemaRow[ColumnOrdinal] = i; schemaRow[ColumnSize] = DBNull.Value; schemaRow[NumericPrecision] = DBNull.Value; schemaRow[NumericScale] = DBNull.Value; schemaRow[BaseServerName] = _command.Connection.DataSource; var databaseName = raw.sqlite3_column_database_name(_stmt, i); schemaRow[BaseCatalogName] = databaseName; var columnName = raw.sqlite3_column_origin_name(_stmt, i); schemaRow[BaseColumnName] = columnName; schemaRow[BaseSchemaName] = DBNull.Value; var tableName = raw.sqlite3_column_table_name(_stmt, i); schemaRow[BaseTableName] = tableName; schemaRow[DataType] = GetFieldType(i); schemaRow[DataTypeName] = GetDataTypeName(i); schemaRow[IsAliased] = columnName != GetName(i); schemaRow[IsExpression] = columnName == null; schemaRow[IsLong] = DBNull.Value; if (!string.IsNullOrEmpty(tableName) && !string.IsNullOrEmpty(columnName)) { using (var command = _command.Connection.CreateCommand()) { command.CommandText = new StringBuilder() .AppendLine("SELECT COUNT(*)") .AppendLine("FROM pragma_index_list($table) i, pragma_index_info(i.name) c") .AppendLine("WHERE \"unique\" = 1 AND c.name = $column AND") .AppendLine("NOT EXISTS (SELECT * FROM pragma_index_info(i.name) c2 WHERE c2.name != c.name);").ToString(); command.Parameters.AddWithValue("$table", tableName); command.Parameters.AddWithValue("$column", columnName); var cnt = (long)command.ExecuteScalar(); schemaRow[IsUnique] = cnt != 0; command.Parameters.Clear(); var columnType = "typeof(\"" + columnName.Replace("\"", "\"\"") + "\")"; command.CommandText = new StringBuilder() .AppendLine($"SELECT {columnType}") .AppendLine($"FROM \"{tableName}\"") .AppendLine($"WHERE {columnType} != 'null'") .AppendLine($"GROUP BY {columnType}") .AppendLine("ORDER BY count() DESC") .AppendLine("LIMIT 1;").ToString(); var type = (string)command.ExecuteScalar(); schemaRow[DataType] = SqliteDataRecord.GetFieldType(type); } if (!string.IsNullOrEmpty(databaseName)) { var rc = raw.sqlite3_table_column_metadata(_command.Connection.Handle, databaseName, tableName, columnName, out var dataType, out var collSeq, out var notNull, out var primaryKey, out var autoInc); SqliteException.ThrowExceptionForRC(rc, _command.Connection.Handle); schemaRow[IsKey] = primaryKey != 0; schemaRow[AllowDBNull] = notNull == 0; schemaRow[IsAutoIncrement] = autoInc != 0; } } schemaTable.Rows.Add(schemaRow); } return schemaTable; } } }
42.275042
221
0.571124
[ "Apache-2.0" ]
ahsonkhan/EntityFrameworkCore
src/Microsoft.Data.Sqlite.Core/SqliteDataReader.cs
24,902
C#
using System; using System.Collections.Generic; using System.Text; namespace COVIDHelp.Models { public class Diseases { public string Name { get; set; } public bool IsEnable { get; set; } } }
17.076923
42
0.648649
[ "MIT" ]
KemberlyMiliano/COVIDHelp
COVIDHelp/COVIDHelp/COVIDHelp/Models/Diseases.cs
224
C#
using Vintagestory.API.Common; using System.Collections.Generic; using Vintagestory.API.Common.Entities; using Vintagestory.API.MathTools; namespace ChaosLands { public class EntityBehaviorBossWaterRemoval : EntityBehavior { float timer; public override void OnGameTick(float deltaTime) { base.OnGameTick(deltaTime); timer += deltaTime; if (timer >= 10) { timer = 0; if (entity.FeetInLiquid) { for (int i = 0; i < 8; i++) { FloodFillAt(entity.SidedPos.AsBlockPos.X, entity.SidedPos.AsBlockPos.Y + i, entity.SidedPos.AsBlockPos.Z); } } } } public void FloodFillAt(int posX, int posY, int posZ) { Queue<Vec4i> bfsQueue = new Queue<Vec4i>(); HashSet<BlockPos> fillablePositions = new HashSet<BlockPos>(); bfsQueue.Enqueue(new Vec4i(posX, posY, posZ, 0)); fillablePositions.Add(new BlockPos(posX, posY, posZ)); float radius = 48; BlockFacing[] faces = BlockFacing.HORIZONTALS; BlockPos curPos = new BlockPos(); while (bfsQueue.Count > 0) { Vec4i bpos = bfsQueue.Dequeue(); foreach (BlockFacing facing in faces) { curPos.Set(bpos.X + facing.Normali.X, bpos.Y + facing.Normali.Y, bpos.Z + facing.Normali.Z); Block block = entity.World.BlockAccessor.GetBlock(curPos); bool inBounds = bpos.W < radius; if (inBounds) { if (block.IsLiquid() && !fillablePositions.Contains(curPos)) { bfsQueue.Enqueue(new Vec4i(curPos.X, curPos.Y, curPos.Z, bpos.W + 1)); fillablePositions.Add(curPos.Copy()); } } } } foreach (BlockPos p in fillablePositions) { entity.World.BlockAccessor.SetBlock(0, p); } } public EntityBehaviorBossWaterRemoval(Entity entity) : base(entity) { } public override string PropertyName() { return "watergone"; } } }
29.105882
130
0.490299
[ "MIT" ]
91loocekaj/vs-chaoslands
src/Entity Behavior/EntityBehaviorBossWaterRemoval.cs
2,476
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ewmsCsharp.Interfaces { public interface IItemStorage { double Quantity { get; set; } string Measurments { get; set; } string Location { get; set; } double Price { get; set; } string ToString(); } }
18.571429
40
0.628205
[ "MIT" ]
w3arthur/CSharp-Reference
ewmsCsharpUnDevelopVersion/ewmsCsharp/Interfaces/IItemStorage.cs
392
C#
using System; using System.Collections.Generic; using System.Linq; using Boc.Domain; using LaYumba.Functional; namespace Exercises.Chapter1 { static class Exercises { // 1. Write a function that negates a given predicate: whenever the given predicate // evaluates to `true`, the resulting function evaluates to `false`, and vice versa. // callback function example private static IEnumerable<Boolean> NegatePredicate<T>(IEnumerable<T> source, Func<T, Boolean> predicate) { foreach (T item in source) { if (predicate(item)) yield return false; else yield return true; } } // adaptor function example combined factory function example private static Func<T, Boolean> NegatePredicate<T>(this Func<T, Boolean> predicate) { return new Func<T, Boolean>(t => { if (predicate(t)) return false; return true; }); } // 2. Write a method that uses quicksort to sort a `List<int>` (return a new list, // rather than sorting it in place). public static List<Int32> NewList(List<Int32> initialList) { List<Int32> newList = null; return newList; } // 3. Generalize your implementation to take a `List<T>`, and additionally a // `Comparison<T>` delegate. // 4. In this chapter, you've seen a `Using` function that takes an `IDisposable` // and a function of type `Func<TDisp, R>`. Write an overload of `Using` that // takes a `Func<IDisposable>` as first // parameter, instead of the `IDisposable`. (This can be used to fix warnings // given by some code analysis tools about instantiating an `IDisposable` and // not disposing it.) private static R Using<TDisp, R>(Func<TDisp> createDisposable, Func<TDisp, R> f) where TDisp : IDisposable { using (TDisp disposable = createDisposable()) { return f(disposable); } } } }
30.826087
112
0.596615
[ "MIT" ]
adrd/functional-csharp-code
Exercises/Chapter01/Exercises.cs
2,129
C#
#region AuthorHeader // // Misc version 2.0 - utilities version 2.0, by Xanthos // // #endregion AuthorHeader using System; using System.Reflection; using System.Security; using Server; using Server.Items; using Server.Mobiles; using Server.Targeting; using Server.Commands; namespace Xanthos.Utilities { public class Misc { /// <summary> /// The hues used for gumps in the systems /// </summary> public static int kLabelHue = 0x480; public static int kGreenHue = 0x40; public static int kRedHue = 0x20; public static bool IsArtifact( Item item ) { if ( null == item ) return false; Type t = item.GetType(); PropertyInfo prop = null; try { prop = t.GetProperty( "ArtifactRarity" ); } catch {} if ( null == prop || (int)(prop.GetValue( item, null )) <= 0 ) return false; return true; } public static bool IsPlayerConstructed( Item item ) { if ( null == item ) return false; Type t = item.GetType(); PropertyInfo prop = null; try { prop = t.GetProperty( "PlayerConstructed" ); } catch {} if ( null == prop || true != (bool)(prop.GetValue( item, null ))) return false; return true; } // // Puts spaces before type name inner-caps // public static string GetFriendlyClassName( string typeName ) { for ( int index = 1; index < typeName.Length; index++ ) { if ( char.IsUpper( typeName, index ) ) { typeName.Insert( index++, " " ); } } return typeName; } public static object InvokeParameterlessMethod( object target, string method ) { object result = null; try { Type objectType = target.GetType(); MethodInfo methodInfo = objectType.GetMethod( method ); result = methodInfo.Invoke( target, null ); } catch ( SecurityException exc ) { Console.WriteLine( "SecurityException: " + exc.Message ); } return result; } public static void SendCommandDetails( Mobile player, string command ) { SendCommandDescription( player, command ); SendCommandUsage( player, command ); } public static void SendCommandUsage( Mobile player, string command ) { string message; CommandEntry entry = CommandSystem.Entries[ command ]; if ( null != entry ) { MethodInfo mi = entry.Handler.Method; object[] attrs = mi.GetCustomAttributes( typeof( UsageAttribute ), false ); UsageAttribute usage = attrs.Length > 0 ? attrs[ 0 ] as UsageAttribute : null; message = "Format: " + ( null == usage ? " - no usage" : usage.Usage ); } else message = command + " - unknown command"; player.SendMessage( kRedHue, message ); } public static void SendCommandDescription( Mobile player, string command ) { string message; CommandEntry entry = CommandSystem.Entries[ command ]; if ( null != entry ) { MethodInfo mi = entry.Handler.Method; object[] attrs = mi.GetCustomAttributes( typeof( DescriptionAttribute ), false ); DescriptionAttribute desc = attrs.Length > 0 ? attrs[ 0 ] as DescriptionAttribute : null; message = command + ": " + ( null == desc ? " - no description" : desc.Description ); } else message = command + " - unknown command"; player.SendMessage( kRedHue, message ); } } }
22.797203
93
0.648773
[ "BSD-2-Clause" ]
greeduomacro/vivre-uo
Scripts/Customs/Xanthos/Utilities/Misc.cs
3,260
C#
using Microsoft.Extensions.Options; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using Volo.Abp.MultiTenancy; namespace LY.MicroService.WebhooksManagement; public class TenantHeaderParamter : IOperationFilter { private readonly AbpMultiTenancyOptions _options; public TenantHeaderParamter( IOptions<AbpMultiTenancyOptions> options) { _options = options.Value; } public void Apply(OpenApiOperation operation, OperationFilterContext context) { if (_options.IsEnabled) { operation.Parameters = operation.Parameters ?? new List<OpenApiParameter>(); operation.Parameters.Add(new OpenApiParameter { Name = TenantResolverConsts.DefaultTenantKey, In = ParameterLocation.Header, Description = "Tenant Id/Name", Required = false }); } } }
31.40625
89
0.650746
[ "MIT" ]
geffzhang/abp-next-admin
aspnet-core/services/LY.MicroService.WebhooksManagement.HttpApi.Host/TenantHeaderParamter.cs
1,007
C#
using System; using System.Collections.Generic; using System.Windows; namespace ay.Wpf.Theme.Element { public class ElementStylesBase : ResourceDictionary { internal List<Type> MergedDatas { get; set; } public ElementStylesBase() { MergedDatas = new List<Type>(); } public ElementStylesBase(List<Type> mergedDatas) { MergedDatas = mergedDatas; } public virtual void Initialize() { } internal void EnsureResource(object key, object value) { if (Contains(key)) { Remove(key); } Add(key, value); } } }
14.842105
56
0.670213
[ "MIT" ]
WertherHu/AYUI8Community
Ay/ay.Wpf.Theme.Element/Common/ElementStylesBase.cs
564
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.AspNetCore.Mvc.Analyzers { public class HasAttribute_ReturnsTrueForAttributesOnOverriddenPropertiesAttribute : Attribute { } public class HasAttribute_ReturnsTrueForAttributesOnOverriddenPropertiesBase { [HasAttribute_ReturnsTrueForAttributesOnOverriddenPropertiesAttribute] public virtual string SomeProperty { get; set; } } public class HasAttribute_ReturnsTrueForAttributesOnOverriddenProperties : HasAttribute_ReturnsTrueForAttributesOnOverriddenPropertiesBase { public override string SomeProperty { get; set; } } }
35.666667
142
0.793057
[ "MIT" ]
48355746/AspNetCore
src/Mvc/Mvc.Analyzers/test/TestFiles/CodeAnalysisExtensionsTest/HasAttribute_ReturnsTrueForAttributesOnOverridenProperties.cs
751
C#
using System; using GuruComponents.Netrix.WebEditing.Elements; using GuruComponents.Netrix.HtmlFormatting; namespace GuruComponents.Netrix.WebEditing.Documents { /// <summary> /// This class represents a single frame in the frameset. /// </summary> /// <remarks> /// Its objects are stored together with /// the related Site to handle the events. /// </remarks> public interface IFrameWindow { /// <summary> /// Deactivate the frame designer and remove all attached behaviors. /// </summary> void DeactivateDesigner(); /// <summary> /// Add a behavior to this frame. /// </summary> /// <remarks> /// Binary behaviors are permanent drawings on the surface. Multiple /// behaviors are drawn in the order they are added. /// </remarks> /// <param name="behavior">The behavior that is used to change the frame area.</param> void AddBehavior(GuruComponents.Netrix.WebEditing.Behaviors.IBaseBehavior behavior); /// <summary> /// Remove a previously set binary behavior. See <see cref="AddBehavior"/>. /// </summary> /// <param name="behavior"></param> void RemoveBehavior(GuruComponents.Netrix.WebEditing.Behaviors.IBaseBehavior behavior); /// <summary> /// Removes all attached behaviors assigned to that frame. /// </summary> void RemoveAllBehaviors(); /// <summary> /// Make the content editable in the editor. Gets the current editable state. /// </summary> bool ContentEditable { get; set; } /// <summary> /// Gets true if content was changed snce last save operation. /// </summary> bool IsDirty { get; } /// <summary> /// Sets or gets the current encoding for that frame. /// </summary> /// <remarks> /// It is not necessary to set /// this property as it defaults to the global Encoding of the main document. /// </remarks> System.Text.Encoding Encoding { get; set; } /// <summary> /// Save the raw content into the file the frame was loaded from. Overwrites. /// </summary> void SaveRawContent(); /// <summary> /// Returns the full path to the document based on the relative path and the current position /// in file system. /// </summary> /// <remarks> /// If the Source is a HTTP URL this method returns the Url as is. /// The internally used URI format with file:// moniker is removed before returning. /// </remarks> /// <returns>Full path in file format, leading monikers are removed, URL coding is decoded.</returns> string GetFullPathUrl(); /// <summary> /// Save the formatted content into the file the frame was loaded from. /// </summary> /// <remarks> /// Overwrites an existing file. /// </remarks> /// <param name="fo">Formatter Options.</param> void SaveFormattedContent(IHtmlFormatterOptions fo); /// <summary> /// Returns the raw content. /// </summary> /// <remarks> /// Usable if the host application has its own save method. /// </remarks> /// <returns>String with raw content</returns> string GetRawContent(); /// <summary> /// Returns a well formatted representation of the frame content. /// </summary> /// <param name="fo">Formatter Options</param> /// <returns>String of well formatted and XHTML compatible content</returns> string GetFormattedContent(IHtmlFormatterOptions fo); /// <summary> /// Returns a string with the outer html of the body. /// </summary> /// <remarks> /// This is for further investigation only, /// not for saving, as it does not contain the full content. /// </remarks> /// <returns>String which contains the content of the frame.</returns> string GetBodyContent(); /// <summary> /// The name of the frame as it is in the name attribute of the frame definition. /// </summary> string FrameName { get; set; } /// <summary> /// The frame src attribute, mostly the filename and a relative path. URL format. /// </summary> string FrameSrc { get; set; } /// <summary> /// The native frame element object. Used for PropertyGrid to set various parameters. /// </summary> IElement NativeFrameElement { get; } } }
36.076923
109
0.587633
[ "MIT" ]
andydunkel/netrix
Netrix2.0/Core/WebEditing/Documents/IFrameWindow.cs
4,690
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the schemas-2019-12-02.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Schemas.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Schemas.Model.Internal.MarshallTransformations { /// <summary> /// TagResource Request Marshaller /// </summary> public class TagResourceRequestMarshaller : IMarshaller<IRequest, TagResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((TagResourceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(TagResourceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Schemas"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-12-02"; request.HttpMethod = "POST"; if (!publicRequest.IsSetResourceArn()) throw new AmazonSchemasException("Request object does not have required field ResourceArn set"); request.AddPathResource("{resource-arn}", StringUtils.FromString(publicRequest.ResourceArn)); request.ResourcePath = "/tags/{resource-arn}"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetTags()) { context.Writer.WritePropertyName("tags"); context.Writer.WriteObjectStart(); foreach (var publicRequestTagsKvp in publicRequest.Tags) { context.Writer.WritePropertyName(publicRequestTagsKvp.Key); var publicRequestTagsValue = publicRequestTagsKvp.Value; context.Writer.Write(publicRequestTagsValue); } context.Writer.WriteObjectEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static TagResourceRequestMarshaller _instance = new TagResourceRequestMarshaller(); internal static TagResourceRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static TagResourceRequestMarshaller Instance { get { return _instance; } } } }
36.798246
137
0.620024
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/Schemas/Generated/Model/Internal/MarshallTransformations/TagResourceRequestMarshaller.cs
4,195
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using System.Collections; using NetOffice; namespace NetOffice.ExcelApi { ///<summary> /// Interface ICalculatedItems /// SupportByVersion Excel, 9,10,11,12,14,15,16 ///</summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] [EntityTypeAttribute(EntityType.IsInterface)] public class ICalculatedItems : COMObject ,IEnumerable<NetOffice.ExcelApi.PivotItem> { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(ICalculatedItems); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public ICalculatedItems(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ICalculatedItems(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ICalculatedItems(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ICalculatedItems(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ICalculatedItems(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ICalculatedItems() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ICalculatedItems(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application; return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public Int32 Count { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Count", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <param name="field">object Field</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public NetOffice.ExcelApi.PivotItem this[object field] { get { object[] paramsArray = Invoker.ValidateParamsArray(field); object returnItem = Invoker.PropertyGet(this, "_Default", paramsArray); NetOffice.ExcelApi.PivotItem newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.PivotItem.LateBindingApiWrapperType) as NetOffice.ExcelApi.PivotItem; return newObject; } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// /// </summary> /// <param name="name">string Name</param> /// <param name="formula">string Formula</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.PivotItem Add(string name, string formula) { object[] paramsArray = Invoker.ValidateParamsArray(name, formula); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); NetOffice.ExcelApi.PivotItem newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.ExcelApi.PivotItem.LateBindingApiWrapperType) as NetOffice.ExcelApi.PivotItem; return newObject; } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// /// </summary> /// <param name="name">string Name</param> /// <param name="formula">string Formula</param> /// <param name="useStandardFormula">optional object UseStandardFormula</param> [SupportByVersionAttribute("Excel", 10,11,12,14,15,16)] public NetOffice.ExcelApi.PivotItem Add(string name, string formula, object useStandardFormula) { object[] paramsArray = Invoker.ValidateParamsArray(name, formula, useStandardFormula); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); NetOffice.ExcelApi.PivotItem newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.ExcelApi.PivotItem.LateBindingApiWrapperType) as NetOffice.ExcelApi.PivotItem; return newObject; } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15, 16 /// /// </summary> /// <param name="name">string Name</param> /// <param name="formula">string Formula</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Excel", 10,11,12,14,15,16)] public NetOffice.ExcelApi.PivotItem _Add(string name, string formula) { object[] paramsArray = Invoker.ValidateParamsArray(name, formula); object returnItem = Invoker.MethodReturn(this, "_Add", paramsArray); NetOffice.ExcelApi.PivotItem newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.ExcelApi.PivotItem.LateBindingApiWrapperType) as NetOffice.ExcelApi.PivotItem; return newObject; } #endregion #region IEnumerable<NetOffice.ExcelApi.PivotItem> Member /// <summary> /// SupportByVersionAttribute Excel, 9,10,11,12,14,15,16 /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] public IEnumerator<NetOffice.ExcelApi.PivotItem> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.ExcelApi.PivotItem item in innerEnumerator) yield return item; } #endregion #region IEnumerable Members /// <summary> /// SupportByVersionAttribute Excel, 9,10,11,12,14,15,16 /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsMethod(this); } #endregion #pragma warning restore } }
35.084942
193
0.706944
[ "MIT" ]
Engineerumair/NetOffice
Source/Excel/Interfaces/ICalculatedItems.cs
9,089
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901 { using static Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Extensions; /// <summary>Managed cluster Access Profile.</summary> public partial class ManagedClusterAccessProfile { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAccessProfile. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAccessProfile. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.IManagedClusterAccessProfile FromJson(Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject json ? new ManagedClusterAccessProfile(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject into a new instance of <see cref="ManagedClusterAccessProfile" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject instance to deserialize from.</param> internal ManagedClusterAccessProfile(Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } __resource = new Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.Resource(json); {_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Aks.Models.Api20200901.AccessProfile.FromJson(__jsonProperties) : Property;} AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="ManagedClusterAccessProfile" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="ManagedClusterAccessProfile" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } __resource?.ToJson(container, serializationMode); AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Aks.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); AfterToJson(ref container); return container; } } }
65.990291
264
0.681036
[ "MIT" ]
Amrinder-Singh29/azure-powershell
src/Aks/Aks.Autorest/generated/api/Models/Api20200901/ManagedClusterAccessProfile.json.cs
6,695
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com using System.Collections.Generic; namespace SUNRUSE.PatternMatchingActorSystems.Shared.Expressions { public sealed class IsArrayTests : TypeCheckTestBase { protected override IEnumerable<ExpressionMock.TestData> ReturnsTrueFor => new[] { ExpressionMock.TestData.EmptyArray, ExpressionMock.TestData.NonEmptyArray }; protected override IExpression CreateInstance(IExpression operand) { return new IsArray(operand); } } }
37.470588
166
0.734694
[ "MIT" ]
jameswilddev/SUNRUSE.PatternMatchingActorSystems
SUNRUSE.PatternMatchingActorSystems.Shared.Tests/Expressions/IsArrayTests.cs
637
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("StudentSystem.Models")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StudentSystem.Models")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c4a75bad-72af-475a-9eab-0adb201ee998")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.189189
84
0.746638
[ "MIT" ]
ivajlotokiew/Databases_Entity_Framework
Entity_Framework_Relations/StudentSystem/StudentSystem.Models/Properties/AssemblyInfo.cs
1,416
C#
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using AutoMapper.QueryableExtensions; using MediatR; using Microsoft.EntityFrameworkCore; using TwitterClone.Application.Common.Extensions; using TwitterClone.Application.Common.Interfaces; using TwitterClone.Domain.Entities; namespace TwitterClone.Application.Posts.Queries.GetPosts { public class GetPostsQueryHandler : IRequestHandler<GetPostsQuery, IEnumerable<PostDto>> { private readonly IMapper _mapper; private readonly IApplicationDbContext _context; private readonly ICurrentUserService _currentUser; public GetPostsQueryHandler(IApplicationDbContext context, IMapper mapper, ICurrentUserService currentUser) { _currentUser = currentUser; _mapper = mapper; _context = context; } public async Task<IEnumerable<PostDto>> Handle(GetPostsQuery request, CancellationToken cancellationToken) { var user = await _context.DomainUsers.FirstOrDefaultAsync(u => u.ApplicationUserId == _currentUser.UserId, cancellationToken); var postsQuery = _context.Posts.AsNoTracking().Where(p => !p.AnswerToId.HasValue); if(user != null) postsQuery = postsQuery.Where(Post.AuthorFollowedBy(user.Id) .Or(Post.LikedBySomeoneFollowedBy(user.Id) .Or(Post.RePostedBySomeoneFollowedBy(user.Id)) .Or(p => p.CreatedById == user.Id))); if(request.BeforeId.HasValue) postsQuery = postsQuery.Where(p => p.Id < request.BeforeId); return await postsQuery.OrderByDescending(p => p.Created) .Take(request.Count ?? 20) .ProjectTo<PostDto>(_mapper.ConfigurationProvider, new { userId = user?.Id ?? 0}) .ToListAsync(cancellationToken); } } }
41.833333
139
0.665837
[ "MIT" ]
wdesgardin/twitter-clone
src/Application/Posts/Queries/GetPosts/GetPostsQueryHandler.cs
2,008
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Общие сведения об этой сборке предоставляются следующим набором // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("Epam.Task11.UsersAndAwards.Entities")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Epam.Task11.UsersAndAwards.Entities")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми // для компонентов COM. Если необходимо обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("fae3b4d1-472c-42a7-adfe-a040632fb242")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номер сборки и номер редакции по умолчанию. // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.810811
99
0.767142
[ "MIT" ]
TimofeyRudometkin/XT-2018Q4
Epam.Task11/Epam.Task11.UsersAndAwards.Entities/Properties/AssemblyInfo.cs
2,053
C#
using System; namespace Moway.Simulator.Communications { /// <summary> /// Communication message from and for the communications module of the simulated MOway /// </summary> /// <LastRevision>08.06.2012</LastRevision> /// <Revisor>Jonathan Ruiz de Garibay</Revisor> public class Message { #region Attributes /// <summary> /// Receiver/Emitter Address /// </summary> private byte direction; /// <summary> /// Message data /// </summary> private byte[] data = new byte[8]; #endregion #region Properties /// <summary> /// Receiver/Transmitter Address /// </summary> public byte Direction { get { return this.direction; } } /// <summary> /// Message data /// </summary> public byte[] Data { get { return this.data; } } #endregion /// <summary> /// Builder /// </summary> /// <param name="direction">Receiver/Transmitter Address</param> /// <param name="data">Message data</param> public Message(byte direction, byte[] data) { this.direction = direction; this.data = data; } } }
25.24
91
0.53645
[ "MIT" ]
Bizintek/mOway_SW_mOwayWorld
mOway_SW_mOwayWorld/MowaySim/Communications/Message.cs
1,264
C#
using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Windows.Input; using Acr.UserDialogs; using Plugin.BluetoothLE; using Prism.Navigation; using ReactiveUI; using ReactiveUI.Fody.Helpers; using Samples.Infrastructure; namespace Samples { public class DeviceViewModel : ViewModel { IDevice device; public DeviceViewModel(IUserDialogs dialogs) { this.SelectCharacteristic = ReactiveCommand.Create<GattCharacteristicViewModel>(x => x.Select()); this.ConnectionToggle = ReactiveCommand.Create(() => { // don't cleanup connection - force user to d/c if (this.device.Status == ConnectionStatus.Disconnected) { this.device.Connect(); } else { this.device.CancelConnection(); } }); this.PairToDevice = ReactiveCommand.Create(() => { if (!this.device.Features.HasFlag(DeviceFeatures.PairingRequests)) { dialogs.Toast("Pairing is not supported on this platform"); } else if (this.device.PairingStatus == PairingStatus.Paired) { dialogs.Toast("Device is already paired"); } else { this.device .PairingRequest() .Subscribe(x => { var txt = x ? "Device Paired Successfully" : "Device Pairing Failed"; dialogs.Toast(txt); this.RaisePropertyChanged(nameof(this.PairingText)); }); } }); this.RequestMtu = ReactiveCommand.CreateFromTask( async x => { if (!this.device.Features.HasFlag(DeviceFeatures.MtuRequests)) { dialogs.Alert("MTU Request not supported on this platform"); } else { var result = await dialogs.PromptAsync(new PromptConfig() .SetTitle("MTU Request") .SetMessage("Range 20-512") .SetInputMode(InputType.Number) .SetOnTextChanged(args => { var len = args.Value?.Length ?? 0; if (len > 0) { if (len > 3) { args.Value = args.Value.Substring(0, 3); } else { var value = Int32.Parse(args.Value); args.IsValid = value >= 20 && value <= 512; } } }) ); if (result.Ok) { var actual = await this.device.RequestMtu(Int32.Parse(result.Text)); dialogs.Toast("MTU Changed to " + actual); } } }, this.WhenAny( x => x.ConnectText, x => x.GetValue().Equals("Disconnect") ) ); } public override void OnNavigatedTo(INavigationParameters parameters) { base.OnNavigatedTo(parameters); this.device = parameters.GetValue<IDevice>("device"); this.Name = this.device.Name; this.Uuid = this.device.Uuid; this.PairingText = this.device.PairingStatus == PairingStatus.Paired ? "Device Paired" : "Pair Device"; this.device .WhenReadRssiContinuously(TimeSpan.FromSeconds(3)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => this.Rssi = x) .DisposeWith(this.DeactivateWith); this.device .WhenStatusChanged() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(status => { switch (status) { case ConnectionStatus.Connecting: this.ConnectText = "Cancel Connection"; break; case ConnectionStatus.Connected: this.ConnectText = "Disconnect"; break; case ConnectionStatus.Disconnected: this.ConnectText = "Connect"; try { this.GattCharacteristics.Clear(); } catch (Exception ex) { Console.WriteLine(ex); } break; } }) .DisposeWith(this.DeactivateWith); this.device .WhenAnyCharacteristicDiscovered() .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(chs => { try { var service = this.GattCharacteristics.FirstOrDefault(x => x.ShortName.Equals(chs.Service.Uuid.ToString())); if (service == null) { service = new Group<GattCharacteristicViewModel>( $"{chs.Service.Description} ({chs.Service.Uuid})", chs.Service.Uuid.ToString() ); Debug.WriteLine(service.ShortName.ToString()); if (service.ShortName.ToUpper().Contains("0000FFE0")) { this.GattCharacteristics.Add(service); } } Debug.WriteLine(chs.Uuid.ToString()); if (chs.Uuid.ToString().ToUpper().Contains("0000FFE1")) { service.Add(new GattCharacteristicViewModel(chs)); } } catch (Exception ex) { // eat it Console.WriteLine(ex); } }) .DisposeWith(this.DeactivateWith); this.device.Connect(); // } public ICommand ConnectionToggle { get; } public ICommand PairToDevice { get; } public ICommand RequestMtu { get; } public ICommand SelectCharacteristic { get; } [Reactive] public string Name { get; private set; } [Reactive] public Guid Uuid { get; private set; } [Reactive] public string PairingText { get; private set; } public ObservableCollection<Group<GattCharacteristicViewModel>> GattCharacteristics { get; } = new ObservableCollection<Group<GattCharacteristicViewModel>>(); [Reactive] public string ConnectText { get; private set; } = "Connect"; [Reactive] public int Rssi { get; private set; } } }
38.062802
166
0.427212
[ "MIT" ]
nhoppasit/BluetoothLE-XF
src/BLE01/Samples/DeviceViewModel.cs
7,881
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DynamicAllocationServiceFixture.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, Inc. // // 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; using System.Collections.Generic; using System.Linq; using System.Reflection; using DynamicAllocation; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DynamicAllocationUnitTests { /// <summary> /// Test fixture for the DynamicAllocationService /// </summary> [TestClass] public class DynamicAllocationServiceFixture { /// <summary>Test allocation paramters</summary> private static AllocationParameters testAllocationParameters; /// <summary>Test measure map</summary> private static MeasureMap measureMap; /// <summary> /// Per test initialization /// </summary> /// <param name="context">text context</param> [ClassInitialize] public static void InitializeClass(TestContext context) { TestUtilities.AllocationParametersDefaults.Initialize(); testAllocationParameters = new AllocationParameters(); measureMap = new MeasureMap(new[] { new EmbeddedJsonMeasureSource(Assembly.GetExecutingAssembly(), "DynamicAllocationUnitTests.Resources.MeasureMap.js") }); } /// <summary> /// A test for the GetValuations method /// </summary> [TestMethod] public void GetValuationsTest() { // verfify that valuations get created var campaign = new CampaignDefinition { ExplicitValuations = new Dictionary<MeasureSet, decimal> { { new MeasureSet { 1 }, 2 }, { new MeasureSet { 2 }, 3 } }, MaxPersonaValuation = 10m, }; var actual = new DynamicAllocationEngine(measureMap).GetValuations(campaign); Assert.IsTrue(actual.ContainsKey(new MeasureSet { 1 })); Assert.AreEqual(2, actual[new MeasureSet(new long[] { 1 })]); Assert.IsTrue(actual.ContainsKey(new MeasureSet { 2 })); Assert.AreEqual(3, actual[new MeasureSet(new long[] { 2 })]); } /// <summary> /// A test for GetBudgetAllocations with History /// </summary> [TestMethod] public void GetBudgetAllocationsTestWithHistory() { var measureSets = new List<MeasureSet> { new MeasureSet { 1106006 } }; // verify we get budget allocations when there is a history var campaign = new BudgetAllocation { PerNodeResults = measureSets.ToDictionary( ms => ms, ms => new PerNodeBudgetAllocationResult { Valuation = (decimal)ms.Count, ExportCount = 1, }), NodeDeliveryMetricsCollection = new Dictionary<MeasureSet, IEffectiveNodeMetrics>(), AllocationParameters = testAllocationParameters, PeriodDuration = TimeSpan.FromDays(1) }; var actual = new DynamicAllocationEngine(measureMap).GetBudgetAllocations(campaign); Assert.IsNotNull(actual.PerNodeResults); Assert.AreNotEqual(0, actual.Phase); Assert.AreEqual(1, actual.PerNodeResults.Count); } /// <summary> /// A test for GetBudgetAllocations with History and forceInitial /// </summary> [TestMethod] public void GetInitialBudgetAllocationsTestWithHistory() { var measureSets = new List<MeasureSet> { new MeasureSet { 1106006 } }; // verify we get budget allocations when there is a history var campaign = new BudgetAllocation { PerNodeResults = measureSets.ToDictionary( ms => ms, ms => new PerNodeBudgetAllocationResult { Valuation = (decimal)ms.Count, ExportCount = 1, }), NodeDeliveryMetricsCollection = new Dictionary<MeasureSet, IEffectiveNodeMetrics>(), AllocationParameters = testAllocationParameters, PeriodDuration = TimeSpan.FromDays(1) }; var actual = new DynamicAllocationEngine(measureMap).GetBudgetAllocations(campaign, true); Assert.IsNotNull(actual.PerNodeResults); Assert.AreEqual(0, actual.Phase); Assert.AreEqual(1, actual.PerNodeResults.Count); } /// <summary> /// A test for GetBudgetAllocations without History /// </summary> [TestMethod] public void GetBudgetAllocationsTestWithoutHistory() { var measureSets = new List<MeasureSet> { new MeasureSet { 1106006 } }; // verify we get budget allocations when there is a history var campaign = new BudgetAllocation { PerNodeResults = measureSets.ToDictionary( ms => ms, ms => new PerNodeBudgetAllocationResult { Valuation = (decimal)ms.Count, }), NodeDeliveryMetricsCollection = new Dictionary<MeasureSet, IEffectiveNodeMetrics>(), AllocationParameters = testAllocationParameters, PeriodDuration = new TimeSpan(1, 0, 0, 0), CampaignStart = new DateTime(2011, 12, 31).AddDays(-3), CampaignEnd = new DateTime(2011, 12, 31), }; var actual = new DynamicAllocationEngine(measureMap).GetBudgetAllocations(campaign); Assert.IsNotNull(actual.PerNodeResults); Assert.AreEqual(0, actual.Phase); Assert.AreEqual(1, actual.PerNodeResults.Count); } /// <summary> /// A test for the IncrementExportCounts method /// </summary> [TestMethod] public void IncrementExportCounts() { var measureSets = new List<MeasureSet> { new MeasureSet { 1 }, new MeasureSet { 1, 2 }, new MeasureSet { 1, 2, 3 } }; var exportMeasureSets = new MeasureSet[] { new MeasureSet { 1 }, new MeasureSet { 1, 2 }, }; var campaign = new BudgetAllocation { PerNodeResults = measureSets.ToDictionary( ms => ms, ms => new PerNodeBudgetAllocationResult { Valuation = (decimal)ms.Count, ExportCount = 1, }) }; var actual = new DynamicAllocationEngine(measureMap).IncrementExportCounts(campaign, exportMeasureSets); Assert.IsTrue(actual .PerNodeResults .Where(pnr => exportMeasureSets.Contains(pnr.Key)) .All(pnr => pnr.Value.ExportCount == 2)); Assert.IsTrue(actual .PerNodeResults .Where(pnr => !exportMeasureSets.Contains(pnr.Key)) .All(pnr => pnr.Value.ExportCount == 1)); } /// <summary> /// A test for the IncrementExportCounts method /// </summary> [TestMethod] public void IncrementIncrementedExportCounts() { var measureSets = new List<MeasureSet> { new MeasureSet { 1 }, new MeasureSet { 1, 2 }, new MeasureSet { 2, 3 }, new MeasureSet { 1, 2, 3 } }; var exportMeasureSets = new MeasureSet[] { new MeasureSet { 1 }, new MeasureSet { 1, 2 }, }; var campaign = new BudgetAllocation { PerNodeResults = measureSets.ToDictionary( ms => ms, ms => new PerNodeBudgetAllocationResult { Valuation = (decimal)ms.Count, ExportCount = 0, }) }; var actual = new DynamicAllocationEngine(measureMap).IncrementExportCounts(campaign, exportMeasureSets); Assert.AreEqual(1, actual.PerNodeResults[measureSets[0]].ExportCount); Assert.AreEqual(1, actual.PerNodeResults[measureSets[1]].ExportCount); Assert.AreEqual(0, actual.PerNodeResults[measureSets[2]].ExportCount); Assert.AreEqual(0, actual.PerNodeResults[measureSets[3]].ExportCount); exportMeasureSets = new MeasureSet[] { new MeasureSet { 1, 2, 3 } }; actual = new DynamicAllocationEngine(measureMap).IncrementExportCounts(campaign, exportMeasureSets); Assert.AreEqual(1, actual.PerNodeResults[measureSets[0]].ExportCount); Assert.AreEqual(1, actual.PerNodeResults[measureSets[1]].ExportCount); Assert.AreEqual(0, actual.PerNodeResults[measureSets[2]].ExportCount); Assert.AreEqual(1, actual.PerNodeResults[measureSets[3]].ExportCount); exportMeasureSets = new MeasureSet[] { new MeasureSet { 1 }, new MeasureSet { 2, 3 }, }; actual = new DynamicAllocationEngine(measureMap).IncrementExportCounts(campaign, exportMeasureSets); Assert.AreEqual(2, actual.PerNodeResults[measureSets[0]].ExportCount); Assert.AreEqual(1, actual.PerNodeResults[measureSets[1]].ExportCount); Assert.AreEqual(1, actual.PerNodeResults[measureSets[2]].ExportCount); Assert.AreEqual(1, actual.PerNodeResults[measureSets[3]].ExportCount); } } }
41.908745
169
0.545727
[ "Apache-2.0" ]
bewood/OpenAdStack
DynamicAllocation/DynamicAllocationUnitTests/DynamicAllocationServiceFixture.cs
11,024
C#
using Newtonsoft.Json; namespace StarlingBank.Models { public class ScheduledSavingsPaymentRequestV2 { /// <summary> /// The schedule definition /// </summary> [JsonProperty("recurrenceRule")] public RecurrenceRuleV2 RecurrenceRule { get; set; } /// <summary> /// Representation of money /// </summary> [JsonProperty("amount")] public CurrencyAndAmount Amount { get; set; } } }
23.6
60
0.59322
[ "MIT" ]
Netizine/StarlingBankClient
StarlingBank/Models/ScheduledSavingsPaymentRequestV2.cs
472
C#
using System.Runtime.Serialization; namespace Docker.DotNet.Models { [DataContract] public class ConfigReferenceRuntimeTarget // (swarm.ConfigReferenceRuntimeTarget) { } }
18.9
85
0.751323
[ "MIT" ]
13750573877/Docker.DotNet
src/Docker.DotNet/Models/ConfigReferenceRuntimeTarget.Generated.cs
189
C#
using System; using System.Collections; using CookComputing.MetaWeblog; using CookComputing.XmlRpc; using umbraco.BusinessLogic; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.datatype; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using umbraco.presentation.channels.businesslogic; namespace umbraco.presentation.channels { /// <summary> /// the umbraco channels API is xml-rpc webservice based on the metaweblog and blogger APIs /// for editing umbraco data froom external clients /// </summary> [XmlRpcService( Name = "umbraco metablog api", Description = "For editing umbraco data from external clients", AutoDocumentation = true)] public class api : UmbracoMetaWeblogAPI, IRemixWeblogApi { /// <summary> /// Initializes a new instance of the <see cref="api"/> class. /// </summary> public api() { } /// <summary> /// Makes a new file to a designated blog using the metaWeblog API /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="file">The file.</param> /// <returns>Returns url as a string of a struct.</returns> [XmlRpcMethod("metaWeblog.newMediaObject", Description = "Makes a new file to a designated blog using the " + "metaWeblog API. Returns url as a string of a struct.")] public UrlData newMediaObject( string blogid, string username, string password, FileData file) { return newMediaObjectLogic(blogid, username, password, file); } #region IRemixWeblogApi Members /// <summary> /// Gets a summary of all the pages from the blog with the spefied blogId. /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns></returns> public wpPageSummary[] getPageList(string blogid, string username, string password) { if (User.validateCredentials(username, password, false)) { ArrayList blogPosts = new ArrayList(); ArrayList blogPostsObjects = new ArrayList(); User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else rootDoc = new Document(u.StartNodeId); //store children array here because iterating over an Array object is very inneficient. var c = rootDoc.Children; foreach (Document d in c) { int count = 0; blogPosts.AddRange( findBlogPosts(userChannel, d, u.Name, ref count, 999, userChannel.FullTree)); } blogPosts.Sort(new DocumentSortOrderComparer()); foreach (Object o in blogPosts) { Document d = (Document)o; wpPageSummary p = new wpPageSummary(); p.dateCreated = d.CreateDateTime; p.page_title = d.Text; p.page_id = d.Id; p.page_parent_id = d.Parent.Id; blogPostsObjects.Add(p); } return (wpPageSummary[])blogPostsObjects.ToArray(typeof(wpPageSummary)); } else { return null; } } /// <summary> /// Gets a specified number of pages from the blog with the spefied blogId /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="numberOfItems">The number of pages.</param> /// <returns></returns> public wpPage[] getPages(string blogid, string username, string password, int numberOfItems) { if (User.validateCredentials(username, password, false)) { ArrayList blogPosts = new ArrayList(); ArrayList blogPostsObjects = new ArrayList(); User u = new User(username); Channel userChannel = new Channel(u.Id); Document rootDoc; if (userChannel.StartNode > 0) rootDoc = new Document(userChannel.StartNode); else rootDoc = new Document(u.StartNodeId); //store children array here because iterating over an Array object is very inneficient. var c = rootDoc.Children; foreach (Document d in c) { int count = 0; blogPosts.AddRange( findBlogPosts(userChannel, d, u.Name, ref count, numberOfItems, userChannel.FullTree)); } blogPosts.Sort(new DocumentSortOrderComparer()); foreach (Object o in blogPosts) { Document d = (Document)o; wpPage p = new wpPage(); p.dateCreated = d.CreateDateTime; p.title = d.Text; p.page_id = d.Id; p.wp_page_parent_id = d.Parent.Id; p.wp_page_parent_title = d.Parent.Text; p.permalink = library.NiceUrl(d.Id); p.description = d.getProperty(userChannel.FieldDescriptionAlias).Value.ToString(); p.link = library.NiceUrl(d.Id); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "" && d.getProperty(userChannel.FieldCategoriesAlias) != null && ((string)d.getProperty(userChannel.FieldCategoriesAlias).Value) != "") { String categories = d.getProperty(userChannel.FieldCategoriesAlias).Value.ToString(); char[] splitter = { ',' }; String[] categoryIds = categories.Split(splitter); p.categories = categoryIds; } blogPostsObjects.Add(p); } return (wpPage[])blogPostsObjects.ToArray(typeof(wpPage)); } else { return null; } } /// <summary> /// Creates a new blog category / tag. /// </summary> /// <param name="blogid">The blogid.</param> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="category">The category.</param> /// <returns></returns> public string newCategory( string blogid, string username, string password, wpCategory category) { if (User.validateCredentials(username, password, false)) { Channel userChannel = new Channel(username); if (userChannel.FieldCategoriesAlias != null && userChannel.FieldCategoriesAlias != "") { // Find the propertytype via the document type ContentType blogPostType = ContentType.GetByAlias(userChannel.DocumentTypeAlias); PropertyType categoryType = blogPostType.getPropertyType(userChannel.FieldCategoriesAlias); interfaces.IUseTags tags = UseTags(categoryType); if (tags != null) { tags.AddTag(category.name); } else { PreValue pv = new PreValue(); pv.DataTypeId = categoryType.DataTypeDefinition.Id; pv.Value = category.name; pv.Save(); } } } return ""; } #endregion } }
39.304933
112
0.511238
[ "MIT" ]
AdrianJMartin/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/channels/api.cs
8,765
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.commerce.logistics.waybill.istddetail.query /// </summary> public class AlipayCommerceLogisticsWaybillIstddetailQueryRequest : IAopRequest<AlipayCommerceLogisticsWaybillIstddetailQueryResponse> { /// <summary> /// 查询即时配送运单详情 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.commerce.logistics.waybill.istddetail.query"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public void PutOtherTextParam(string key, string value) { if(this.udfParams == null) { this.udfParams = new Dictionary<string, string>(); } this.udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); if(udfParams != null) { parameters.AddAll(this.udfParams); } return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
26.354839
139
0.572827
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Request/AlipayCommerceLogisticsWaybillIstddetailQueryRequest.cs
3,288
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the workspaces-2015-04-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.WorkSpaces.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.WorkSpaces.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeWorkspaceBundles operation /// </summary> public class DescribeWorkspaceBundlesResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DescribeWorkspaceBundlesResponse response = new DescribeWorkspaceBundlesResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Bundles", targetDepth)) { var unmarshaller = new ListUnmarshaller<WorkspaceBundle, WorkspaceBundleUnmarshaller>(WorkspaceBundleUnmarshaller.Instance); response.Bundles = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("NextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValuesException")) { return InvalidParameterValuesExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonWorkSpacesException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DescribeWorkspaceBundlesResponseUnmarshaller _instance = new DescribeWorkspaceBundlesResponseUnmarshaller(); internal static DescribeWorkspaceBundlesResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeWorkspaceBundlesResponseUnmarshaller Instance { get { return _instance; } } } }
38.612069
193
0.652601
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/WorkSpaces/Generated/Model/Internal/MarshallTransformations/DescribeWorkspaceBundlesResponseUnmarshaller.cs
4,479
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using AngleSharp; using AngleSharp.Parser.Html; namespace MyBlog.Helpers { public static class ArticleContentHelper { public static ICollection<string> GetImageSrcs(string content) { if (string.IsNullOrEmpty(content)) { return new List<string>(); } var parser = new HtmlParser(); var document = parser.Parse(Markdig.Markdown.ToHtml(content)); return document.QuerySelectorAll("img,video,source") .Select(e => e.GetAttribute("src")) .Where(s => s != null) .ToList(); } } }
27.857143
74
0.601282
[ "MIT" ]
huww98/MyBlog
src/MyBlog/Helpers/ArticleContentHelper.cs
780
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MyLinkedList")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MyLinkedList")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("76aef9b7-11a3-45d3-98e2-f14a9ee97bff")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.756757
84
0.745168
[ "MIT" ]
Stanislav121/study-and-experiments
Education/MyLinkedList/Properties/AssemblyInfo.cs
1,400
C#
// Copyright (c) 2015 Augie R. Maddox, Guavaman Enterprises. All rights reserved. namespace Rewired.UI.ControlMapper { using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using Rewired; public partial class ControlMapper { private enum LayoutElementSizeType { MinSize = 0, PreferredSize = 1 } private enum WindowType { None = 0, ChooseJoystick, JoystickAssignmentConflict, ElementAssignment, ElementAssignmentPrePolling, ElementAssignmentPolling, ElementAssignmentResult, ElementAssignmentConflict, Calibration, CalibrateStep1, CalibrateStep2 } } }
24.6875
82
0.6
[ "MIT" ]
Joramt/NightMareAttack
Assets/Rewired/Extras/ControlMapper/Scripts/ControlMapper_Enums.cs
792
C#
namespace BookingsApi.Common.Configuration { public class AzureAdConfiguration { public string Authority { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public string TenantId { get; set; } } }
28.1
48
0.637011
[ "MIT" ]
hmcts/vh-bookings-api
BookingsApi/BookingsApi.Common/Configuration/AzureAdConfiguration.cs
281
C#
namespace MassTransit.Transports.InMemory.Topology { using MassTransit.Topology.Configuration; public interface IInMemoryConsumeTopologyConfigurator : IConsumeTopologyConfigurator, IInMemoryConsumeTopology { } }
23.272727
60
0.726563
[ "Apache-2.0" ]
andymac4182/MassTransit
src/MassTransit/Transports/InMemory/Topology/IInMemoryConsumeTopologyConfigurator.cs
258
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DLaB.Xrm.Entities { [System.Runtime.Serialization.DataContractAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")] public enum UserSettings_EntityFormMode { [System.Runtime.Serialization.EnumMemberAttribute()] Edit = 2, [System.Runtime.Serialization.EnumMemberAttribute()] Organizationdefault = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Readoptimized = 1, } }
29.851852
80
0.585608
[ "MIT" ]
ScottColson/XrmUnitTest
DLaB.Xrm.Entities/OptionSets/UserSettings_EntityFormMode.cs
806
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SixLabors.ImageSharp.Web.DependencyInjection; using SixLabors.ImageSharp.Web.Middleware; using Xunit; namespace SixLabors.ImageSharp.Web.Tests.TestUtilities { public abstract class TestServerFixture : IDisposable { private TestServer server; private bool isDisposed; protected TestServerFixture() { IConfigurationRoot configuration = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair<string, string>("webroot", string.Empty) }) .AddEnvironmentVariables() .Build(); IWebHostBuilder builder = new WebHostBuilder() .UseConfiguration(configuration) .Configure(this.Configure) .ConfigureServices(this.ConfigureServices); this.server = new TestServer(builder); this.Services = this.server.Host.Services; this.HttpClient = this.server.CreateClient(); } public HttpClient HttpClient { get; private set; } public IServiceProvider Services { get; private set; } protected void ConfigureServices(IServiceCollection services) { IImageSharpBuilder builder = services.AddImageSharp(options => { Func<ImageCommandContext, Task> onParseCommandsAsync = options.OnParseCommandsAsync; options.OnParseCommandsAsync = context => { Assert.NotNull(context); Assert.NotNull(context.Context); Assert.NotNull(context.Commands); Assert.NotNull(context.Parser); return onParseCommandsAsync.Invoke(context); }; Func<ImageProcessingContext, Task> onProcessedAsync = options.OnProcessedAsync; options.OnProcessedAsync = context => { Assert.NotNull(context); Assert.NotNull(context.Commands); Assert.NotNull(context.ContentType); Assert.NotNull(context.Context); Assert.NotNull(context.Extension); Assert.NotNull(context.Stream); return onProcessedAsync.Invoke(context); }; Func<FormattedImage, Task> onBeforeSaveAsync = options.OnBeforeSaveAsync; options.OnBeforeSaveAsync = context => { Assert.NotNull(context); Assert.NotNull(context.Format); Assert.NotNull(context.Encoder); Assert.NotNull(context.Image); return onBeforeSaveAsync.Invoke(context); }; Func<HttpContext, Task> onPrepareResponseAsync = options.OnPrepareResponseAsync; options.OnPrepareResponseAsync = context => { Assert.NotNull(context); Assert.NotNull(context.Response); return onPrepareResponseAsync.Invoke(context); }; }) .ClearProviders() .AddProcessor<CacheBusterWebProcessor>(); this.ConfigureCustomServices(services, builder); } protected virtual void Configure(IApplicationBuilder app) => app.UseImageSharp(); protected abstract void ConfigureCustomServices(IServiceCollection services, IImageSharpBuilder builder); protected virtual void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { this.server.Dispose(); this.HttpClient.Dispose(); } this.server = null; this.HttpClient = null; this.isDisposed = true; } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } } }
33.470149
113
0.579487
[ "Apache-2.0" ]
kroymann/ImageSharp.Web
tests/ImageSharp.Web.Tests/TestUtilities/TestServerFixture.cs
4,485
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2020-05-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for OriginGroupMembers Object /// </summary> public class OriginGroupMembersUnmarshaller : IUnmarshaller<OriginGroupMembers, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public OriginGroupMembers Unmarshall(XmlUnmarshallerContext context) { OriginGroupMembers unmarshalledObject = new OriginGroupMembers(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Items/OriginGroupMember", targetDepth)) { var unmarshaller = OriginGroupMemberUnmarshaller.Instance; unmarshalledObject.Items.Add(unmarshaller.Unmarshall(context)); continue; } if (context.TestExpression("Quantity", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Quantity = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } private static OriginGroupMembersUnmarshaller _instance = new OriginGroupMembersUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static OriginGroupMembersUnmarshaller Instance { get { return _instance; } } } }
36.565217
112
0.586801
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/OriginGroupMembersUnmarshaller.cs
3,364
C#
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; public class OvrAvatarProjectorRenderComponent : OvrAvatarRenderComponent { Material material; internal void InitializeProjectorRender(ovrAvatarRenderPart_ProjectorRender render, Shader shader, OvrAvatarRenderComponent target) { if (shader == null) { shader = Shader.Find("OvrAvatar/AvatarSurfaceShader"); } material = CreateAvatarMaterial(gameObject.name + "_projector", shader); material.EnableKeyword("PROJECTOR_ON"); Renderer renderer = target.GetComponent<Renderer>(); if (renderer != null) { List<Material> materials = new List<Material>(renderer.sharedMaterials); materials.Add(material); renderer.sharedMaterials = materials.ToArray(); } } internal void UpdateProjectorRender(OvrAvatarComponent component, ovrAvatarRenderPart_ProjectorRender render) { OvrAvatar.ConvertTransform(render.localTransform, this.transform); material.SetMatrix("_ProjectorWorldToLocal", this.transform.worldToLocalMatrix); component.UpdateAvatarMaterial(material, render.materialState); } void OnDrawGizmos() { Vector3 v000 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(-1.0f, -1.0f, -1.0f)); Vector3 v100 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(+1.0f, -1.0f, -1.0f)); Vector3 v010 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(-1.0f, +1.0f, -1.0f)); Vector3 v110 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(+1.0f, +1.0f, -1.0f)); Vector3 v001 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(-1.0f, -1.0f, +1.0f)); Vector3 v101 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(+1.0f, -1.0f, +1.0f)); Vector3 v011 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(-1.0f, +1.0f, +1.0f)); Vector3 v111 = transform.localToWorldMatrix.MultiplyPoint(new Vector3(+1.0f, +1.0f, +1.0f)); Gizmos.color = Color.gray; Gizmos.DrawLine(v000, v100); Gizmos.DrawLine(v000, v010); Gizmos.DrawLine(v010, v110); Gizmos.DrawLine(v100, v110); Gizmos.DrawLine(v000, v001); Gizmos.DrawLine(v100, v101); Gizmos.DrawLine(v010, v011); Gizmos.DrawLine(v110, v111); Gizmos.DrawLine(v001, v101); Gizmos.DrawLine(v001, v011); Gizmos.DrawLine(v011, v111); Gizmos.DrawLine(v101, v111); } }
40.151515
136
0.659623
[ "MIT" ]
Fangh/Guns-Golf
Assets/OvrAvatar/Scripts/OvrAvatarProjectorRenderComponent.cs
2,652
C#
// ----------------------------------------------------------------------- // <copyright file="IMessageAutoAck.cs" company="Asynkron AB"> // Copyright (C) 2015-2021 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- namespace Proto { public interface IAutoRespond { object GetAutoResponse(); } }
32.666667
74
0.415816
[ "Apache-2.0" ]
RagingKore/protoactor-dotnet
src/Proto.Actor/Messages/IAutoRespond.cs
392
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace PddOpenSdk.Models.Request.DdkTools { public partial class GenerateDdkOauthCmsPromUrlRequestModel : PddRequestModel { /// <summary> /// 0, "1.9包邮";1, "今日爆款"; 2, "品牌清仓"; 4,"PC端专属商城" /// </summary> [JsonProperty("channel_type")] public int? ChannelType { get; set; } /// <summary> /// 自定义参数,为链接打上自定义标签;自定义参数最长限制64个字节;格式为: {"uid":"11111","sid":"22222"} ,其中 uid 用户唯一标识,可自行加密后传入,每个用户仅且对应一个标识,必填; sid 上下文信息标识,例如sessionId等,非必填。该json字符串中也可以加入其他自定义的key /// </summary> [JsonProperty("custom_parameters")] public string CustomParameters { get; set; } /// <summary> /// 是否生成手机跳转链接。true-是,false-否,默认false /// </summary> [JsonProperty("generate_mobile")] public bool? GenerateMobile { get; set; } /// <summary> /// 是否返回 schema URL /// </summary> [JsonProperty("generate_schema_url")] public bool? GenerateSchemaUrl { get; set; } /// <summary> /// 是否生成短链接,true-是,false-否 /// </summary> [JsonProperty("generate_short_url")] public bool? GenerateShortUrl { get; set; } /// <summary> /// 是否唤起微信客户端, 默认false 否,true 是 /// </summary> [JsonProperty("generate_weapp_webview")] public bool? GenerateWeappWebview { get; set; } /// <summary> /// 单人团多人团标志。true-多人团,false-单人团 默认false /// </summary> [JsonProperty("multi_group")] public bool? MultiGroup { get; set; } /// <summary> /// 推广位列表,例如:["60005_612"] /// </summary> [JsonProperty("p_id_list")] public List<string> PIdList { get; set; } } }
34.705882
173
0.573446
[ "Apache-2.0" ]
rose-daniel/open-pdd-net-sdk
PddOpenSdk/PddOpenSdk/Models/Request/DdkTools/GenerateDdkOauthCmsPromUrlRequestModel.cs
2,156
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using UnityEditor; using UnityEditor.Build.Reporting; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Build.Editor { /// <summary> /// The Build Info defines common properties for a build. /// </summary> public interface IBuildInfo { /// <summary> /// Is this build being issued from the command line? /// </summary> bool IsCommandLine { get; } /// <summary> /// The directory to put the final build output. /// </summary> /// <remarks> /// Defaults to "<see href="https://docs.unity3d.com/ScriptReference/Application-dataPath.html">Application.dataPath</see>/Builds/Platform Target/" /// </remarks> string OutputDirectory { get; set; } /// <summary> /// The list of scenes to include in the build. /// </summary> IEnumerable<string> Scenes { get; set; } /// <summary> /// A pre-build action to raise before building the Unity player. /// </summary> Action<IBuildInfo> PreBuildAction { get; set; } /// <summary> /// A post-build action to raise after building the Unity player. /// </summary> Action<IBuildInfo, BuildReport> PostBuildAction { get; set; } /// <summary> /// Build options to include in the Unity player build pipeline. /// </summary> BuildOptions BuildOptions { get; set; } /// <summary> /// The build target. /// </summary> BuildTarget BuildTarget { get; } /// <summary> /// Optional parameter to set the player's <see cref="ColorSpace"/> /// </summary> ColorSpace? ColorSpace { get; set; } /// <summary> /// Optional parameter to set the scripting backend /// </summary> ScriptingImplementation? ScriptingBackend { get; set; } /// <summary> /// Should the build auto increment the build version number? /// </summary> bool AutoIncrement { get; set; } /// <summary> /// The symbols associated with this build. /// </summary> string BuildSymbols { get; set; } /// <summary> /// The build configuration (i.e. debug, release, or master) /// </summary> string Configuration { get; set; } /// <summary> /// The build platform (i.e. x86, x64) /// </summary> string BuildPlatform { get; set; } } }
32.717647
156
0.560949
[ "MIT" ]
AzureMentor/MapsSDK-Unity
SampleProject/Assets/MixedRealityToolkit/Utilities/BuildAndDeploy/IBuildInfo.cs
2,781
C#
using System; using System.Collections.Generic; using XamarinCleanApp.Core.Data.Repository; using XamarinCleanApp.Core.Model.Repository; namespace XamarinCleanApp.Core.Model.UseCase { public class GetAllCitiesUseCase : UseCase<List<City>, Params> { ICityRepository Repository = new CityRepository(); public override IObservable<List<City>> BuildUseCaseObservable(Params param) { return Repository.Cities(param.UseCache); } } public class Params { public bool UseCache { get; set; } } }
22.391304
78
0.761165
[ "Apache-2.0" ]
eincioch/xamarin-forms-clean-arquitecture
XamarinCleanApp/Core/Domain/GetAllCitiesUseCase.cs
517
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace App4.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
35.34375
100
0.654288
[ "MIT" ]
kflo/phylo
PHYLOGEN/App4/App4.iOS/AppDelegate.cs
1,133
C#
using Xunit; namespace Ztm.Threading.Tests { public sealed class ChannelFactoryTests { readonly ChannelFactory subject; public ChannelFactoryTests() { this.subject = new ChannelFactory(); } [Fact] public void Create_WhenInvoke_ShouldReturnNonNull() { var result = this.subject.Create<object>(); Assert.NotNull(result); } } }
19.173913
59
0.580499
[ "MIT" ]
firoorg/ztm
src/Ztm.Threading.Tests/ChannelFactoryTests.cs
441
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System { // ByReference<T> is meant to be used to represent "ref T" fields. It is working // around lack of first class support for byref fields in C# and IL. The JIT and // type loader has special handling for it that turns it into a thin wrapper around ref T. [NonVersionable] internal readonly ref struct ByReference<T> { // CS0169: The private field '{blah}' is never used #pragma warning disable 169 private readonly IntPtr _value; #pragma warning restore [Intrinsic] public ByReference(ref T value) { // Implemented as a JIT intrinsic - This default implementation is for // completeness and to provide a concrete error if called via reflection // or if intrinsic is missed. throw new PlatformNotSupportedException(); } public ref T Value { [Intrinsic] get { // Implemented as a JIT intrinsic - This default implementation is for // completeness and to provide a concrete error if called via reflection // or if the intrinsic is missed. throw new PlatformNotSupportedException(); } } } }
35.976744
94
0.639948
[ "MIT" ]
omajid/corefx
src/Common/src/CoreLib/System/ByReference.cs
1,547
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /* * Manages Debug controls. * * Created by GoldenWay on 7/21/2018 * Modified by GoldenWay on 7/21/2018 * */ public class ControlDebug : MonoBehaviour { public GameObject debugDisplay; bool togglePressed = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { DebugControlsManager (); } void DebugControlsManager () { if (Debug.isDebugBuild) { if (Input.GetAxisRaw ("Debug Toggle") == 1) { if (!togglePressed) { togglePressed = true; debugDisplay.SetActive (!debugDisplay.activeSelf); } } else { togglePressed = false; } } } }
17.309524
55
0.668501
[ "MIT" ]
Golden7ty8/Moral-Masks
src/Moral Masks/Assets/Scripts/ControlDebug.cs
729
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winnt.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="CFG_CALL_TARGET_INFO" /> struct.</summary> public static unsafe class CFG_CALL_TARGET_INFOTests { /// <summary>Validates that the <see cref="CFG_CALL_TARGET_INFO" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CFG_CALL_TARGET_INFO>(), Is.EqualTo(sizeof(CFG_CALL_TARGET_INFO))); } /// <summary>Validates that the <see cref="CFG_CALL_TARGET_INFO" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CFG_CALL_TARGET_INFO).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CFG_CALL_TARGET_INFO" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(CFG_CALL_TARGET_INFO), Is.EqualTo(16)); } else { Assert.That(sizeof(CFG_CALL_TARGET_INFO), Is.EqualTo(8)); } } } }
36.886364
145
0.643869
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/winnt/CFG_CALL_TARGET_INFOTests.cs
1,625
C#
/* * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ namespace com.opengamma.strata.product.swap { //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static com.opengamma.strata.collect.TestHelper.assertJodaConvert; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static com.opengamma.strata.collect.TestHelper.assertSerialization; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static com.opengamma.strata.collect.TestHelper.assertThrows; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static com.opengamma.strata.collect.TestHelper.coverEnum; //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.testng.Assert.assertEquals; using DataProvider = org.testng.annotations.DataProvider; using Test = org.testng.annotations.Test; /// <summary> /// Test. /// </summary> //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public class SwapLegTypeTest public class SwapLegTypeTest { //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @DataProvider(name = "name") public static Object[][] data_name() public static object[][] data_name() { return new object[][] { new object[] {SwapLegType.FIXED, "Fixed"}, new object[] {SwapLegType.IBOR, "Ibor"}, new object[] {SwapLegType.OVERNIGHT, "Overnight"}, new object[] {SwapLegType.OTHER, "Other"} }; } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(dataProvider = "name") public void test_toString(SwapLegType convention, String name) public virtual void test_toString(SwapLegType convention, string name) { assertEquals(convention.ToString(), name); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(dataProvider = "name") public void test_of_lookup(SwapLegType convention, String name) public virtual void test_of_lookup(SwapLegType convention, string name) { assertEquals(SwapLegType.of(name), convention); } public virtual void test_of_lookup_notFound() { assertThrows(() => SwapLegType.of("Rubbish"), typeof(System.ArgumentException)); } public virtual void test_of_lookup_null() { assertThrows(() => SwapLegType.of(null), typeof(System.ArgumentException)); } //------------------------------------------------------------------------- public virtual void test_isFixed() { assertEquals(SwapLegType.FIXED.Fixed, true); assertEquals(SwapLegType.IBOR.Fixed, false); assertEquals(SwapLegType.OVERNIGHT.Fixed, false); assertEquals(SwapLegType.INFLATION.Fixed, false); assertEquals(SwapLegType.OTHER.Fixed, false); } public virtual void test_isFloat() { assertEquals(SwapLegType.FIXED.Float, false); assertEquals(SwapLegType.IBOR.Float, true); assertEquals(SwapLegType.OVERNIGHT.Float, true); assertEquals(SwapLegType.INFLATION.Float, true); assertEquals(SwapLegType.OTHER.Float, false); } //------------------------------------------------------------------------- public virtual void coverage() { coverEnum(typeof(SwapLegType)); } public virtual void test_serialization() { assertSerialization(SwapLegType.FIXED); } public virtual void test_jodaConvert() { assertJodaConvert(typeof(SwapLegType), SwapLegType.IBOR); } } }
37.058252
109
0.714173
[ "Apache-2.0" ]
ckarcz/Strata.ConvertedToCSharp
modules/product/src/test/java/com/opengamma/strata/product/swap/SwapLegTypeTest.cs
3,819
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; using Microsoft.EntityFrameworkCore.Proxies.Internal; using Microsoft.EntityFrameworkCore.Utilities; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// EntityFrameworkCore.Proxies extension methods for <see cref="IServiceCollection" />. /// </summary> public static class ProxiesServiceCollectionExtensions { /// <summary> /// <para> /// Adds the services required for proxy support in Entity Framework. /// </para> /// <para> /// Calling this method is no longer necessary when building most applications, including those that /// use dependency injection in ASP.NET or elsewhere. /// It is only needed when building the internal service provider for use with /// the <see cref="DbContextOptionsBuilder.UseInternalServiceProvider" /> method. /// This is not recommend other than for some advanced scenarios. /// </para> /// </summary> /// <param name="serviceCollection">The <see cref="IServiceCollection" /> to add services to.</param> /// <returns> /// The same service collection so that multiple calls can be chained. /// </returns> public static IServiceCollection AddEntityFrameworkProxies( this IServiceCollection serviceCollection) { Check.NotNull(serviceCollection, nameof(serviceCollection)); new EntityFrameworkServicesBuilder(serviceCollection) .TryAdd<IConventionSetPlugin, ProxiesConventionSetPlugin>() .TryAddProviderSpecificServices( b => b.TryAddSingleton<IProxyFactory, ProxyFactory>()); return serviceCollection; } } }
44.8125
116
0.664342
[ "MIT" ]
KaloyanIT/efcore
src/EFCore.Proxies/ProxiesServiceCollectionExtensions.cs
2,151
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SourceCodeReader.Web.Models; namespace SourceCodeReader.Web.LanguageServices { public interface ISourceCodeQueryService { TokenResult FindExact(TokenParameter parameter); DocumentInfo GetFileDetails(string filePath); } }
21.5
56
0.770349
[ "MIT" ]
Mattlk13/SourceCodeReader
Web/LanguageServices/ISourceCodeQueryService.cs
346
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview { using static Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.Extensions; /// <summary>GuestConfiguration REST API operation</summary> public partial class Operation : Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperation, Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationInternal { /// <summary>Backing field for <see cref="Display" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplay _display; /// <summary>Provider, Resource, Operation and description values.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.OperationDisplay()); set => this._display = value; } /// <summary>Description about operation.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Inlined)] public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Description = value ?? null; } /// <summary>Operation type: Read, write, delete, etc.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Inlined)] public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Operation = value ?? null; } /// <summary>Service provider: Microsoft.GuestConfiguration</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Inlined)] public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Provider = value ?? null; } /// <summary>Resource on which the operation is performed: For ex.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Inlined)] public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplayInternal)Display).Resource = value ?? null; } /// <summary>Internal Acessors for Display</summary> Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.OperationDisplay()); set { {_display = value;} } } /// <summary>Internal Acessors for Property</summary> Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationProperties Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.OperationProperties()); set { {_property = value;} } } /// <summary>Backing field for <see cref="Name" /> property.</summary> private string _name; /// <summary> /// Operation name: For ex. providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/write or read /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Owned)] public string Name { get => this._name; set => this._name = value; } /// <summary>Backing field for <see cref="Property" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationProperties _property; /// <summary>Provider, Resource, Operation and description values.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.OperationProperties()); set => this._property = value; } /// <summary>Service provider: Microsoft.GuestConfiguration</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Origin(Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.PropertyOrigin.Inlined)] public string StatusCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationPropertiesInternal)Property).StatusCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationPropertiesInternal)Property).StatusCode = value ?? null; } /// <summary>Creates an new <see cref="Operation" /> instance.</summary> public Operation() { } } /// GuestConfiguration REST API operation public partial interface IOperation : Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.IJsonSerializable { /// <summary>Description about operation.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Description about operation.", SerializedName = @"description", PossibleTypes = new [] { typeof(string) })] string DisplayDescription { get; set; } /// <summary>Operation type: Read, write, delete, etc.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Operation type: Read, write, delete, etc.", SerializedName = @"operation", PossibleTypes = new [] { typeof(string) })] string DisplayOperation { get; set; } /// <summary>Service provider: Microsoft.GuestConfiguration</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Service provider: Microsoft.GuestConfiguration", SerializedName = @"provider", PossibleTypes = new [] { typeof(string) })] string DisplayProvider { get; set; } /// <summary>Resource on which the operation is performed: For ex.</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Resource on which the operation is performed: For ex. ", SerializedName = @"resource", PossibleTypes = new [] { typeof(string) })] string DisplayResource { get; set; } /// <summary> /// Operation name: For ex. providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/write or read /// </summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Operation name: For ex. providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/write or read", SerializedName = @"name", PossibleTypes = new [] { typeof(string) })] string Name { get; set; } /// <summary>Service provider: Microsoft.GuestConfiguration</summary> [Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Runtime.Info( Required = false, ReadOnly = false, Description = @"Service provider: Microsoft.GuestConfiguration", SerializedName = @"statusCode", PossibleTypes = new [] { typeof(string) })] string StatusCode { get; set; } } /// GuestConfiguration REST API operation internal partial interface IOperationInternal { /// <summary>Provider, Resource, Operation and description values.</summary> Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationDisplay Display { get; set; } /// <summary>Description about operation.</summary> string DisplayDescription { get; set; } /// <summary>Operation type: Read, write, delete, etc.</summary> string DisplayOperation { get; set; } /// <summary>Service provider: Microsoft.GuestConfiguration</summary> string DisplayProvider { get; set; } /// <summary>Resource on which the operation is performed: For ex.</summary> string DisplayResource { get; set; } /// <summary> /// Operation name: For ex. providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/write or read /// </summary> string Name { get; set; } /// <summary>Provider, Resource, Operation and description values.</summary> Microsoft.Azure.PowerShell.Cmdlets.GuestConfiguration.Models.Api20180630Preview.IOperationProperties Property { get; set; } /// <summary>Service provider: Microsoft.GuestConfiguration</summary> string StatusCode { get; set; } } }
72.18543
401
0.727523
[ "MIT" ]
AlanFlorance/azure-powershell
src/GuestConfiguration/generated/api/Models/Api20180630Preview/Operation.cs
10,750
C#
/* * The MIT License (MIT) * * Copyright (c) 2020 Futurewei Corp. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; using System.Diagnostics; using qpmodel.logic; using qpmodel.expr; namespace qpmodel.optimizer { public abstract class Rule { public static List<Rule> ruleset_ = new List<Rule>() { new CteAnchor2CteAnchor(), new CteConsumer2CteConsumer(), new CteSelect2CteSelect(), new JoinAssociativeRule(), new JoinCommutativeRule(), new AggSplitRule(), new Join2NLJoin(), new Join2HashJoin(), new Join2MarkJoin(), new Join2SingleJoin(), new Scan2Scan(), new Scan2IndexSeek(), new ScanFile2ScanFile(), new Filter2Filter(), new Agg2HashAgg(), new Agg2StreamAgg(), new Order2Sort(), new From2From(), new Limit2Limit(), new Seq2Seq(), new CteProd2CteProd(), new Append2Append(), new JoinBLock2Join(), new Gather2Gather(), new Bcast2Bcast(), new Redis2Redis(), new PSet2PSet(), new Sample2Sample(), new Result2Result(), new JoinCommutativeRule(), // intentionally add a duplicated rule new CteAnchor2CteProd(), new CteConsumer2CteSelect(), }; // TBD: besides static controls, we can examine the plan and quick trim rules impossible to apply public static void Init(ref List<Rule> ruleset, QueryOption option) { if (!option.optimize_.enable_indexseek_) ruleset.RemoveAll(x => x is Scan2IndexSeek); if (!option.optimize_.enable_hashjoin_) ruleset.RemoveAll(x => x is Join2HashJoin); if (!option.optimize_.enable_streamagg_) ruleset.RemoveAll(x => x is Agg2StreamAgg); if (!option.optimize_.enable_nljoin_) ruleset.RemoveAll(x => x is Join2NLJoin); if (!option.optimize_.memo_use_remoteexchange_) ruleset.RemoveAll(x => x is AggSplitRule); } public abstract bool Appliable(CGroupMember expr); public abstract CGroupMember Apply(CGroupMember expr); } public abstract class ExplorationRule : Rule { } // There are two join exploration rules are used: // 1. Join commutative rule: AB => BA // 2. Left Join association rule: A(BC) => (AB)C // // Above two is RS-B1 in https://anilshanbhag.in/static/papers/rsgraph_vldb14.pdf // It is complete to exhaust search space but with duplicates with // the condition cross-join shall not be suppressed. // Another more efficient complete and duplicates free set is RS-B2. // public class JoinCommutativeRule : ExplorationRule { public override bool Appliable(CGroupMember expr) { return expr.logic_ is LogicJoin lj && lj.IsInnerJoin(); } public override CGroupMember Apply(CGroupMember expr) { LogicJoin join = expr.logic_ as LogicJoin; var l = join.lchild_(); var r = join.rchild_(); var f = join.filter_; Debug.Assert(!l.LeftReferencesRight(r)); if (r.LeftReferencesRight(l)) return expr; LogicJoin newjoin = new LogicJoin(r, l, f); return new CGroupMember(newjoin, expr.group_); } } // A(BC) => (AB)C // // 1. There are other equvalent forms and we only use above form. // Say (AB)C-> (AC)B which is actually can be transformed via this rule: // (AB)C -> C(AB) -> (CA)B -> (AC)B // 2. There are also left or right association but we only use left association // since the right one can be transformed via commuative first. // (AB)C -> A(BC) ; A(BC) -> (AB)C // 3. Join filter shall be is handled by first pull up all join filters // then push them back to the new join plan. // // we do not generate Cartesian join unless input is Cartesian. // public class JoinAssociativeRule : ExplorationRule { public override bool Appliable(CGroupMember expr) { if (!(expr.logic_ is LogicJoin a_bc) || !a_bc.IsInnerJoin()) return false; var bc = (a_bc.rchild_() as LogicMemoRef).Deref(); if (bc is LogicJoin bcj) { if (!bcj.IsInnerJoin()) return false; // we only reject cases that logically impossible to apply // association rule, but leave anything may generate worse // plan (say Cartesian joins) to apply stage. return true; } return false; } public override CGroupMember Apply(CGroupMember expr) { LogicJoin a_bc = expr.logic_ as LogicJoin; LogicNode a = (a_bc.lchild_() as LogicMemoRef).Deref<LogicNode>(); LogicJoin bc = (a_bc.rchild_() as LogicMemoRef).Deref<LogicJoin>(); Expr bcfilter = bc.filter_; var ab = new LogicJoin(a_bc.lchild_(), bc.lchild_()); var c = bc.rchild_(); var ab_c = new LogicJoin(ab, c); Debug.Assert(!a.LeftReferencesRight(bc)); if (ab.LeftReferencesRight(c)) return expr; // pull up all join filters and re-push them back Expr allfilters = bcfilter; if (a_bc.filter_ != null) allfilters = allfilters.AddAndFilter(a_bc.filter_); if (allfilters != null) { var andlist = allfilters.FilterToAndList(); andlist.RemoveAll(e => ab_c.PushJoinFilter(e)); if (andlist.Count > 0) ab_c.filter_ = andlist.AndListToExpr(); } // Ideally if there is no cross join in the given plan but cross join // in the new plan, we shall return the original plan. However, stop // exploration now will prevent generating other promising plans. So // we have to return the new plan. // if (expr.QueryOption().optimize_.memo_disable_crossjoin_) { if (a_bc.filter_ != null && bcfilter != null) { if (ab_c.filter_ is null || ab.filter_ is null) return expr; } } return new CGroupMember(ab_c, expr.group_); } } public class AggSplitRule : ExplorationRule { public override bool Appliable(CGroupMember expr) { if (!(expr.logic_ is LogicAgg agg) || agg.isLocal_ || agg.isDerived_) return false; return true; } public override CGroupMember Apply(CGroupMember expr) { // for manually binding the expression void manualbindexpr(Expr e) { e.bounded_ = true; e.type_ = new BoolType(); } // for transforming original having according to the new agg func BinExpr processhaving(Expr e, Dictionary<Expr, Expr> dict) { var be = e as BinExpr; Debug.Assert(be != null); bool isreplace = false; List<Expr> children = new List<Expr>(); foreach (var child in be.children_) { if (dict.ContainsKey(child)) { children.Add(dict[child]); isreplace = true; } else children.Add(child); } Debug.Assert(isreplace); return new BinExpr(children[0], children[1], be.op_); } LogicAgg origAggNode = (expr.logic_ as LogicAgg); var childNode = (origAggNode.child_() as LogicMemoRef).Deref<LogicNode>(); var groupby = origAggNode.groupby_?.CloneList(); var having = origAggNode.having_?.Clone(); // process the aggregation functions origAggNode.GenerateAggrFns(false); List<AggFunc> aggfns = new List<AggFunc>(); origAggNode.aggrFns_.ForEach(x => aggfns.Add(x.Clone() as AggFunc)); // need to make aggrFns_ back to null list origAggNode.aggrFns_ = new List<AggFunc>(); var globalfns = new List<Expr>(); var localfns = new List<Expr>(); // record the processed aggregate functions var derivedAggFuncDict = new Dictionary<Expr, Expr>(); foreach (var func in aggfns) { Expr processed = func.SplitAgg(); // if splitagg is returning null, end the transformation process if (processed is null) return expr; // force the id to be equal. processed._ = func._; globalfns.Add(processed); derivedAggFuncDict.Add(func, processed); } var local = new LogicAgg(childNode, groupby, localfns, null) { isLocal_ = true }; // having is placed on the global agg and the agg func need to be processed var newhaving = having; if (having != null) { newhaving = processhaving(having, derivedAggFuncDict); manualbindexpr(newhaving); } // assuming having is an expression involving agg func, // it is only placed on the global agg var global = new LogicAgg(local, groupby, globalfns, newhaving) { isDerived_ = true }; global.Overridesign(origAggNode); global.deriveddict_ = derivedAggFuncDict; return new CGroupMember(global, expr.group_); } } public class CteAnchor2CteProd : ExplorationRule { public override bool Appliable(CGroupMember expr) { return expr.logic_ is LogicCteAnchor; } public override CGroupMember Apply(CGroupMember expr) { //LogicJoin log = expr.logic_ as LogicJoin; //// we expand the logic plan of CTE /// LogicCteAnchor cteAnchor = expr.logic_ as LogicCteAnchor; CteInfoEntry cteInfoEntry = cteAnchor.cteInfoEntry_; LogicCteProducer cteProducer = new LogicCteProducer(cteInfoEntry); // left is cteProducer and right is the child of cteAnchor LogicSequence ls = new LogicSequence(cteProducer, cteAnchor.child_(), cteAnchor); return new CGroupMember(ls, expr.group_); } } public class CteConsumer2CteSelect : ExplorationRule { public override bool Appliable(CGroupMember expr) { return expr.logic_ is LogicCteConsumer; } public override CGroupMember Apply(CGroupMember expr) { // create a group member CteSelect var memo = expr.group_.memo_; LogicCteConsumer cteConsumer = expr.logic_ as LogicCteConsumer; LogicSelectCte logicSelectCte = new LogicSelectCte(cteConsumer, memo); return new CGroupMember(logicSelectCte, expr.group_); } } }
37.508876
105
0.573513
[ "MIT" ]
zhouqingqing/qpmodel
qpmodel/RulesTrans.cs
12,680
C#
namespace Catel.Tests.IoC { using System.ComponentModel; public interface ITestInterface { string Name { get; set; } } public interface ITestInterface1 { } public interface ITestInterface2 { } public interface ITestInterface3 { ITestInterface1 TestInterface1 { get; } } public class TestClass1 : ITestInterface, ITestInterface1, INotifyPropertyChanged { public TestClass1() { Name = "created via injection"; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } public string Name { get; set; } public event PropertyChangedEventHandler PropertyChanged; } public class TestClass2 : ITestInterface, ITestInterface2 { public TestClass2() { Name = "created via injection"; } public string Name { get; set; } } public class TestClass3 : ITestInterface, ITestInterface3 { public TestClass3(ITestInterface1 testInterface1) { TestInterface1 = testInterface1; Name = "created via injection"; } public string Name { get; set; } public ITestInterface1 TestInterface1 { get; } } }
20.784615
85
0.583272
[ "MIT" ]
14632791/Catel
src/Catel.Tests/IoC/TestClasses.cs
1,353
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Reflection; namespace Rigol.DS1000Z { public partial class InfoPanel : UserControl { public InfoPanel( string lang = "" ) { InitializeComponent(); //set properties for panel and some of elements this.Anchor = AnchorStyles.Top | AnchorStyles.Left; this.Dock = DockStyle.Fill; //set language version and disable and enable some controls depends on options SetLanguage(lang); } //------------------------------------------------------------------------------------------------------------------------------------------- /// <summary> /// Set text elements in panel based on selected language /// </summary> /// <param name="lang">Selected language</param> public void SetLanguage(string lang) { if (lang == "") { System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(System.Globalization.CultureInfo.InstalledUICulture.Name); } else { System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang); } //change label in panel lbVersion.Text = "Version: v" + Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Build.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Revision.ToString(); } //----------------------------------------------------------------------------------------- public void ChangeLanguage(string lang) { SetLanguage(lang); } //----------------------------------------------------------------------------------------- private void llClick_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { LinkLabel label = (LinkLabel)sender; System.Diagnostics.Process.Start((string)label.Tag); } } }
37.626866
168
0.512098
[ "MIT" ]
ppudo/LabToysApp_CS
Devices/Rigol/DS1000Z/InfoPanel.cs
2,523
C#
using System; using System.Collections.Generic; #if MTOUCH || MMP || BUNDLER using Mono.Cecil; using Xamarin.Bundler; using Registrar; #endif using Xamarin.Utils; public class Framework { public string Namespace; public string Name; // this is the name to pass to the linker when linking. This can be an umbrella framework. public string SubFramework; // if Name is an umbrella framework, this is the name of the actual sub framework. public Version Version; public Version VersionAvailableInSimulator; public bool AlwaysWeakLinked; public bool Unavailable; public string LibraryPath { get { if (string.IsNullOrEmpty (SubFramework)) { return $"/System/Library/Frameworks/{Name}.framework/{Name}"; } else { return $"/System/Library/Frameworks/{Name}.framework/Versions/A/Frameworks/{SubFramework}.framework/{SubFramework}"; } } } #if MTOUCH || MMP || BUNDLER public bool IsFrameworkAvailableInSimulator (Application app) { if (VersionAvailableInSimulator == null) return false; if (VersionAvailableInSimulator > app.SdkVersion) return false; return true; } #endif } public class Frameworks : Dictionary <string, Framework> { public void Add (string @namespace, int major_version) { Add (@namespace, @namespace, new Version (major_version, 0)); } public void Add (string @namespace, string framework, int major_version) { Add (@namespace, framework, new Version (major_version, 0)); } public void Add (string @namespace, int major_version, int minor_version) { Add (@namespace, @namespace, new Version (major_version, minor_version)); } public void Add (string @namespace, int major_version, int minor_version, string subFramework = null) { Add (@namespace, @namespace, new Version (major_version, minor_version), subFramework: subFramework); } public void Add (string @namespace, string framework, int major_version, bool alwaysWeakLink) { Add (@namespace, framework, new Version (major_version, 0), null, alwaysWeakLink); } public void Add (string @namespace, string framework, int major_version, int minor_version) { Add (@namespace, framework, new Version (major_version, minor_version)); } public void Add (string @namespace, string framework, int major_version, int minor_version, string umbrellaFramework = null) { Add (@namespace, framework, new Version (major_version, minor_version), subFramework: umbrellaFramework); } public void Add (string @namespace, string framework, int major_version, int minor_version, int build_version) { Add (@namespace, framework, new Version (major_version, minor_version, build_version)); } public void Add (string @namespace, string framework, Version version, Version version_available_in_simulator = null, bool alwaysWeakLink = false, string subFramework = null) { var fr = new Framework () { Namespace = @namespace, Name = framework, Version = version, VersionAvailableInSimulator = version_available_in_simulator ?? version, AlwaysWeakLinked = alwaysWeakLink, SubFramework = subFramework, }; base.Add (fr.Namespace, fr); } public Framework Find (string framework) { foreach (var kvp in this) if (kvp.Value.Name == framework) return kvp.Value; return null; } static Version NotAvailableInSimulator = new Version (int.MaxValue, int.MaxValue); static Frameworks mac_frameworks; public static Frameworks MacFrameworks { get { if (mac_frameworks == null) { mac_frameworks = new Frameworks () { { "Accelerate", 10, 0 }, { "AppKit", 10, 0 }, { "CoreAudio", "CoreAudio", 10, 0 }, { "CoreFoundation", "CoreFoundation", 10, 0 }, { "CoreGraphics", "ApplicationServices", 10, 0, "CoreGraphics" }, // The CoreImage framework by itself was introduced in 10.11 // Up until 10.10 it was a sub framework in the QuartzCore umbrella framework // They both existed until 10.13, when the sub framework was removed. { "CoreImage", 10, 0 }, { "Foundation", 10, 0 }, { "ImageKit", "Quartz", 10, 0, "ImageKit" }, { "PdfKit", "Quartz", 10, 0, "PDFKit" }, { "Security", 10, 0 }, { "GSS", "GSS", 10, 1 }, { "AddressBook", 10, 2 }, { "AudioUnit", 10, 2 }, { "CoreMidi", "CoreMIDI", 10, 2 }, { "IOBluetooth", 10, 2 }, { "IOBluetoothUI", 10, 2 }, { "WebKit", 10, 2}, { "AudioToolbox", 10, 3 }, { "CoreServices", 10, 3 }, { "CoreVideo", 10, 3 }, { "MobileCoreServices", "CoreServices", 10, 3 }, { "OpenGL", 10, 3 }, { "SearchKit", "CoreServices", 10,3, "SearchKit" }, { "SystemConfiguration", 10, 3 }, { "CoreData", 10, 4 }, { "ImageIO", 10, 4 }, // it's own framework since at least 10.9 { "OpenAL", 10, 4 }, { "CoreAnimation", "QuartzCore", 10, 5 }, { "CoreText", 10, 5 }, // it's own framework since at least 10.9 { "InputMethodKit", 10, 5 }, { "PrintCore", "ApplicationServices", 10,5, "PrintCore" }, { "ScriptingBridge", 10, 5 }, { "QuickLook", 10, 5 }, { "QuartzComposer", "Quartz", 10, 5, "QuartzComposer" }, { "ImageCaptureCore", "ImageCaptureCore", 10,5 }, { "QTKit", 10, 6 }, { "QuickLookUI", "Quartz", 10, 6, "QuickLookUI" }, { "MediaToolbox", 10, 9 }, { "AVFoundation", 10, 7 }, { "CoreLocation", 10, 7 }, { "CoreMedia", 10, 7 }, { "CoreWlan", "CoreWLAN", 10, 7 }, { "StoreKit", 10, 7 }, { "Accounts", 10, 8 }, { "AudioVideoBridging", 10, 8 }, { "CFNetwork", 10, 8 }, { "EventKit", 10, 8 }, { "GameKit", 10, 8 }, { "GLKit", 10, 8 }, { "SceneKit", 10, 8 }, { "Social", 10, 8 }, { "VideoToolbox", 10, 8 }, { "AVKit", 10, 9 }, // The CoreBluetooth framework was added as a sub framework of the IOBluetooth framework in 10.7 // Then it was moved to its own top-level framework in 10.10 // and the sub framework was deleted in 10.12 { "CoreBluetooth", 10, 9 }, { "GameController", 10, 9 }, { "MapKit", 10, 9 }, { "MediaAccessibility", 10, 9 }, { "MediaLibrary", 10, 9 }, { "SpriteKit", 10, 9 }, { "JavaScriptCore", "JavaScriptCore", 10, 9 }, { "CloudKit", 10, 10 }, { "CryptoTokenKit", 10, 10 }, { "FinderSync", 10, 10 }, { "Hypervisor", 10, 10 }, { "LocalAuthentication", 10, 10 }, { "MultipeerConnectivity", 10, 10 }, { "NetworkExtension", 10, 10 }, { "NotificationCenter", 10, 10 }, { "Contacts", 10, 11 }, { "ContactsUI", 10, 11 }, { "CoreAudioKit", 10,11 }, { "GameplayKit", 10, 11 }, { "Metal", 10, 11 }, { "MetalKit", 10, 11 }, { "ModelIO", 10, 11 }, { "Intents", 10, 12 }, { "IntentsUI", 12, 0 }, { "IOSurface", "IOSurface", 10, 12 }, { "Photos", "Photos", 10,12 }, { "PhotosUI", "PhotosUI", 10,12 }, { "SafariServices", "SafariServices", 10, 12 }, { "MediaPlayer", "MediaPlayer", 10, 12, 1 }, { "CoreML", "CoreML", 10, 13 }, { "CoreSpotlight", "CoreSpotlight", 10,13 }, { "ExternalAccessory", "ExternalAccessory", 10, 13 }, { "MetalPerformanceShaders", "MetalPerformanceShaders", 10, 13 }, { "Vision", "Vision", 10, 13 }, { "BusinessChat", "BusinessChat", 10, 13, 4 }, { "AdSupport", "AdSupport", 10,14 }, { "NaturalLanguage", "NaturalLanguage", 10,14 }, { "Network", "Network", 10, 14 }, { "VideoSubscriberAccount", "VideoSubscriberAccount", 10,14 }, { "UserNotifications", "UserNotifications", 10,14 }, { "iTunesLibrary", "iTunesLibrary", 10,14 }, { "AuthenticationServices", "AuthenticationServices", 10,15 }, { "CoreMotion", "CoreMotion", 10,15 }, { "DeviceCheck", "DeviceCheck", 10,15 }, { "ExecutionPolicy", "ExecutionPolicy", 10,15 }, { "FileProvider", "FileProvider", 10,15 }, { "FileProviderUI", "FileProviderUI", 10,15 }, { "PushKit", "PushKit", 10,15 }, { "QuickLookThumbnailing", "QuickLookThumbnailing", 10,15 }, { "SoundAnalysis", "SoundAnalysis", 10,15 }, { "PencilKit", "PencilKit", 10,15 }, { "Speech", "Speech", 10,15 }, { "LinkPresentation", "LinkPresentation", 10,15 }, // not sure if the API is available, issue: https://github.com/xamarin/maccore/issues/1951 //{ "CoreHaptics", "CoreHaptics", 10,15 }, { "AutomaticAssessmentConfiguration", "AutomaticAssessmentConfiguration", 10,15,4 }, { "Accessibility", "Accessibility", 11,0 }, { "AppTrackingTransparency", "AppTrackingTransparency", 11,0 }, { "CallKit", "CallKit", 11,0 }, { "ClassKit", "ClassKit", 11,0 }, { "MLCompute", "MLCompute", 11,0 }, { "NearbyInteraction", "NearbyInteraction", 11,0 }, { "OSLog", "OSLog", 11,0 }, { "PassKit", "PassKit", 11,0 }, { "ReplayKit", "ReplayKit", 11,0 }, { "ScreenTime", "ScreenTime", 11,0 }, { "UniformTypeIdentifiers", "UniformTypeIdentifiers", 11,0 }, { "UserNotificationsUI", "UserNotificationsUI", 11,0 }, { "AdServices", "AdServices", 11,1 }, { "Chip", "CHIP", 12, 0 }, { "LocalAuthenticationEmbeddedUI", "LocalAuthenticationEmbeddedUI", 12, 0 }, { "MailKit", "MailKit", 12, 0 }, { "MetricKit", 12, 0 }, { "Phase", "PHASE", 12, 0 }, { "ShazamKit", "ShazamKit", 12,0 }, }; } return mac_frameworks; } } static Frameworks ios_frameworks; public static Frameworks GetiOSFrameworks (bool is_simulator_build) { if (ios_frameworks == null) ios_frameworks = CreateiOSFrameworks (is_simulator_build); return ios_frameworks; } public static Frameworks CreateiOSFrameworks (bool is_simulator_build) { return new Frameworks () { { "AddressBook", "AddressBook", 3 }, { "Security", "Security", 3 }, { "AudioUnit", "AudioToolbox", 3 }, { "AddressBookUI", "AddressBookUI", 3 }, { "AudioToolbox", "AudioToolbox", 3 }, { "AVFoundation", "AVFoundation", 3 }, { "CFNetwork", "CFNetwork", 3 }, { "CoreAnimation", "QuartzCore", 3 }, { "CoreAudio", "CoreAudio", 3 }, { "CoreData", "CoreData", 3 }, { "CoreFoundation", "CoreFoundation", 3 }, { "CoreGraphics", "CoreGraphics", 3 }, { "CoreLocation", "CoreLocation", 3 }, { "ExternalAccessory", "ExternalAccessory", 3 }, { "Foundation", "Foundation", 3 }, { "GameKit", "GameKit", 3 }, { "MapKit", "MapKit", 3 }, { "MediaPlayer", "MediaPlayer", 3 }, { "MessageUI", "MessageUI", 3 }, { "MobileCoreServices", "MobileCoreServices", 3 }, { "StoreKit", "StoreKit", 3 }, { "SystemConfiguration", "SystemConfiguration", 3 }, { "OpenGLES", "OpenGLES", 3 }, { "UIKit", "UIKit", 3 }, { "Accelerate", "Accelerate", 4 }, { "EventKit", "EventKit", 4 }, { "EventKitUI", "EventKitUI", 4 }, { "CoreMotion", "CoreMotion", 4 }, { "CoreMedia", "CoreMedia", 4 }, { "CoreVideo", "CoreVideo", 4 }, { "CoreTelephony", "CoreTelephony", 4 }, { "iAd", "iAd", 4 }, { "QuickLook", "QuickLook", 4 }, { "ImageIO", "ImageIO", 4 }, { "AssetsLibrary", "AssetsLibrary", 4 }, { "CoreText", "CoreText", 4 }, { "CoreMidi", "CoreMIDI", 4 }, { "Accounts", "Accounts", 5 }, { "GLKit", "GLKit", 5 }, { "NewsstandKit", "NewsstandKit", 5 }, { "CoreImage", "CoreImage", 5 }, { "CoreBluetooth", "CoreBluetooth", 5 }, { "Twitter", "Twitter", 5 }, { "GSS", "GSS", 5 }, { "MediaToolbox", "MediaToolbox", 6 }, { "PassKit", "PassKit", 6 }, { "Social", "Social", 6 }, { "AdSupport", "AdSupport", 6 }, { "GameController", "GameController", 7 }, { "JavaScriptCore", "JavaScriptCore", 7 }, { "MediaAccessibility", "MediaAccessibility", 7 }, { "MultipeerConnectivity", "MultipeerConnectivity", 7 }, { "SafariServices", "SafariServices", 7 }, { "SpriteKit", "SpriteKit", 7 }, { "HealthKit", "HealthKit", 8 }, { "HomeKit", "HomeKit", 8 }, { "LocalAuthentication", "LocalAuthentication", 8 }, { "NotificationCenter", "NotificationCenter", 8 }, { "PushKit", "PushKit", 8 }, { "Photos", "Photos", 8 }, { "PhotosUI", "PhotosUI", 8 }, { "SceneKit", "SceneKit", 8 }, { "CloudKit", "CloudKit", 8 }, { "AVKit", "AVKit", 8 }, { "CoreAudioKit", "CoreAudioKit", is_simulator_build ? 9 : 8 }, { "Metal", "Metal", new Version (8, 0), new Version (9, 0) }, { "WebKit", "WebKit", 8 }, { "NetworkExtension", "NetworkExtension", 8 }, { "VideoToolbox", "VideoToolbox", 8 }, // { "WatchKit", "WatchKit", 8,2 }, // Removed in Xcode 11 { "ReplayKit", "ReplayKit", 9 }, { "Contacts", "Contacts", 9 }, { "ContactsUI", "ContactsUI", 9 }, { "CoreSpotlight", "CoreSpotlight", 9 }, { "WatchConnectivity", "WatchConnectivity", 9 }, { "ModelIO", "ModelIO", 9 }, { "MetalKit", "MetalKit", 9 }, { "MetalPerformanceShaders", "MetalPerformanceShaders", new Version (9, 0), new Version (11, 0) /* MPS got simulator headers in Xcode 9 */ }, { "GameplayKit", "GameplayKit", 9 }, { "HealthKitUI", "HealthKitUI", 9,3 }, { "CallKit", "CallKit", 10 }, { "Messages", "Messages", 10 }, { "Speech", "Speech", 10 }, { "VideoSubscriberAccount", "VideoSubscriberAccount", 10 }, { "UserNotifications", "UserNotifications", 10 }, { "UserNotificationsUI", "UserNotificationsUI", 10 }, { "Intents", "Intents", 10 }, { "IntentsUI", "IntentsUI", 10 }, { "ARKit", "ARKit", 11 }, { "CoreNFC", "CoreNFC", new Version (11, 0), NotAvailableInSimulator, true }, /* not always present, e.g. iPad w/iOS 12, so must be weak linked; doesn't work in the simulator in Xcode 12 (https://stackoverflow.com/q/63915728/183422) */ { "DeviceCheck", "DeviceCheck", new Version (11, 0), new Version (13, 0) }, { "IdentityLookup", "IdentityLookup", 11 }, { "IOSurface", "IOSurface", new Version (11, 0), NotAvailableInSimulator /* Not available in the simulator (the header is there, but broken) */ }, { "CoreML", "CoreML", 11 }, { "Vision", "Vision", 11 }, { "FileProvider", "FileProvider", 11 }, { "FileProviderUI", "FileProviderUI", 11 }, { "PdfKit", "PDFKit", 11 }, { "BusinessChat", "BusinessChat", 11, 3 }, { "ClassKit", "ClassKit", 11,4 }, { "AuthenticationServices", "AuthenticationServices", 12,0 }, { "CarPlay", "CarPlay", 12,0 }, { "CoreServices", "MobileCoreServices", 12, 0 }, { "IdentityLookupUI", "IdentityLookupUI", 12,0 }, { "NaturalLanguage", "NaturalLanguage", 12,0 }, { "Network", "Network", 12, 0 }, { "BackgroundTasks", "BackgroundTasks", 13, 0 }, { "CoreHaptics", "CoreHaptics", 13, 0 }, { "LinkPresentation", "LinkPresentation", 13, 0 }, { "MetricKit", "MetricKit", 13, 0 }, { "PencilKit", "PencilKit", 13, 0 }, { "QuickLookThumbnailing", "QuickLookThumbnailing", 13,0 }, { "SoundAnalysis", "SoundAnalysis", 13, 0 }, { "VisionKit", "VisionKit", 13, 0 }, { "AutomaticAssessmentConfiguration", "AutomaticAssessmentConfiguration", 13, 4 }, { "Accessibility", "Accessibility", 14,0 }, { "AppClip", "AppClip", 14,0 }, { "AppTrackingTransparency", "AppTrackingTransparency", 14,0 }, { "MediaSetup", "MediaSetup", new Version (14, 0), NotAvailableInSimulator /* no headers in beta 3 */ }, { "MLCompute", "MLCompute", new Version (14,0), NotAvailableInSimulator }, { "NearbyInteraction", "NearbyInteraction", 14,0 }, { "ScreenTime", "ScreenTime", 14,0 }, { "SensorKit", "SensorKit", 14,0 }, { "UniformTypeIdentifiers", "UniformTypeIdentifiers", 14,0 }, { "AdServices", "AdServices", 14,3 }, { "CoreLocationUI", "CoreLocationUI", 15,0 }, { "Chip", "CHIP", new Version (15, 0), NotAvailableInSimulator /* no headers in beta 2 */ }, { "Phase", "PHASE", new Version (15,0), NotAvailableInSimulator /* no headers in beta 2 */ }, { "OSLog", "OSLog", 15,0 }, { "ShazamKit", "ShazamKit", new Version (15,0), NotAvailableInSimulator}, { "ThreadNetwork", "ThreadNetwork", new Version (15,0), NotAvailableInSimulator}, // the above MUST be kept in sync with simlauncher // see tools/mtouch/Makefile // please also keep it sorted to ease comparison // // The following tests also need to be updated: // // * RegistrarTest.MT4134 }; } static Frameworks watch_frameworks; public static Frameworks GetwatchOSFrameworks (bool is_simulator_build) { if (watch_frameworks == null) { watch_frameworks = new Frameworks { { "Accelerate", "Accelerate", 2 }, // The CFNetwork framework is in the SDK, but there are no headers inside the framework, so don't enable yet. // { "CFNetwork", "CFNetwork", 2 }, { "ClockKit", "ClockKit", 2 }, { "Contacts", "Contacts", 2 }, { "CoreAudio", "CoreAudio", 2 }, { "CoreData", "CoreData", 2 }, { "CoreFoundation", "CoreFoundation", 2 }, { "CoreGraphics", "CoreGraphics", 2 }, { "CoreLocation", "CoreLocation", 2 }, { "CoreMotion", "CoreMotion", 2 }, { "EventKit", "EventKit", 2 }, { "Foundation", "Foundation", 2 }, { "HealthKit", "HealthKit", 2 }, { "HomeKit", "HomeKit", 2 }, { "ImageIO", "ImageIO", 2 }, { "MapKit", "MapKit", 2 }, { "MobileCoreServices", "MobileCoreServices", 2 }, { "PassKit", "PassKit", 2 }, { "Security", "Security", 2 }, { "UIKit", "UIKit", 2 }, { "WatchConnectivity", "WatchConnectivity", 2 }, { "WatchKit", "WatchKit", 2 }, { "CoreText", "CoreText", 2,2 }, // AVFoundation was introduced in 3.0, but the simulator SDK was broken until 3.2. { "AVFoundation", "AVFoundation", 3, is_simulator_build ? 2 : 0 }, { "CloudKit", "CloudKit", 3 }, { "GameKit", "GameKit", new Version (3, 0), new Version (3, 2) /* No headers provided for watchOS/simulator until watchOS 3.2. */ }, { "SceneKit", "SceneKit", 3 }, { "SpriteKit", "SpriteKit", 3 }, { "UserNotifications", "UserNotifications", 3 }, { "Intents", "Intents", 3,2 }, { "CoreBluetooth", "CoreBluetooth", 4 }, { "CoreML", "CoreML", 4 }, { "CoreVideo", "CoreVideo", 4 }, { "NaturalLanguage", "NaturalLanguage", 5 }, { "MediaPlayer", "MediaPlayer", 5 }, { "AuthenticationServices", "AuthenticationServices", 6 }, { "Network", "Network", 6 }, { "PushKit", "PushKit", 6 }, { "SoundAnalysis", "SoundAnalysis", 6 }, { "CoreMedia", "CoreMedia", 6 }, { "StoreKit", "StoreKit", 6,2 }, { "Accessibility", "Accessibility", 7,0 }, { "UniformTypeIdentifiers", "UniformTypeIdentifiers", 7,0 }, { "Chip", "CHIP", new Version (8, 0), NotAvailableInSimulator /* no headers in beta 2 */ }, { "NearbyInteraction", "NearbyInteraction", 8,0 }, { "OSLog", "OSLog", 8,0 }, { "ShazamKit", "ShazamKit", new Version (8, 0), NotAvailableInSimulator}, }; } return watch_frameworks; } static Frameworks tvos_frameworks; public static Frameworks TVOSFrameworks { get { if (tvos_frameworks == null) { tvos_frameworks = new Frameworks () { { "AVFoundation", "AVFoundation", 9 }, { "AVKit", "AVKit", 9 }, { "Accelerate", "Accelerate", 9 }, { "AdSupport", "AdSupport", 9 }, { "AudioToolbox", "AudioToolbox", 9 }, { "AudioUnit", "AudioToolbox", 9 }, { "CFNetwork", "CFNetwork", 9 }, { "CloudKit", "CloudKit", 9 }, { "CoreAnimation", "QuartzCore", 9 }, { "CoreAudio", "CoreAudio", 9 }, { "CoreBluetooth", "CoreBluetooth", 9 }, { "CoreData", "CoreData", 9 }, { "CoreFoundation", "CoreFoundation", 9 }, { "CoreGraphics", "CoreGraphics", 9 }, { "CoreImage", "CoreImage", 9 }, { "CoreLocation", "CoreLocation", 9 }, { "CoreMedia", "CoreMedia", 9 }, { "CoreSpotlight", "CoreSpotlight", 9 }, { "CoreText", "CoreText", 9 }, { "CoreVideo", "CoreVideo", 9 }, { "Foundation", "Foundation", 9 }, { "GLKit", "GLKit", 9 }, { "GameController", "GameController", 9 }, { "GameKit", "GameKit", 9 }, { "GameplayKit", "GameplayKit", 9 }, { "ImageIO", "ImageIO", 9 }, { "JavaScriptCore", "JavaScriptCore", 9 }, { "MediaAccessibility", "MediaAccessibility", 9 }, { "MediaPlayer", "MediaPlayer", 9 }, { "MediaToolbox", "MediaToolbox", 9 }, { "Metal", "Metal", 9 }, { "MetalKit", "MetalKit", new Version (9, 0), new Version (10, 0) }, { "MetalPerformanceShaders", "MetalPerformanceShaders", new Version (9, 0), NotAvailableInSimulator /* not available in the simulator */ }, { "MobileCoreServices", "MobileCoreServices", 9 }, { "ModelIO", "ModelIO", 9 }, { "OpenGLES", "OpenGLES", 9 }, { "SceneKit", "SceneKit", 9 }, { "Security", "Security", 9 }, { "SpriteKit", "SpriteKit", 9 }, { "StoreKit", "StoreKit", 9 }, { "SystemConfiguration", "SystemConfiguration", 9 }, { "TVMLKit", "TVMLKit", 9 }, { "TVServices", "TVServices", 9 }, { "UIKit", "UIKit", 9 }, { "MapKit", "MapKit", 9, 2 }, { "ExternalAccessory", "ExternalAccessory", 10 }, { "HomeKit", "HomeKit", 10 }, { "MultipeerConnectivity", 10 }, { "Photos", "Photos", 10 }, { "PhotosUI", "PhotosUI", 10 }, { "ReplayKit", "ReplayKit", 10 }, { "UserNotifications", "UserNotifications", 10 }, { "VideoSubscriberAccount", "VideoSubscriberAccount", 10 }, { "VideoToolbox", "VideoToolbox", 10,2 }, { "DeviceCheck", "DeviceCheck", new Version (11, 0), new Version (13, 0) }, { "CoreML", "CoreML", 11 }, { "IOSurface", "IOSurface", new Version (11, 0), NotAvailableInSimulator /* Not available in the simulator (the header is there, but broken) */ }, { "Vision", "Vision", 11 }, { "CoreServices", "MobileCoreServices", 12 }, { "NaturalLanguage", "NaturalLanguage", 12,0 }, { "Network", "Network", 12, 0 } , { "TVUIKit", "TVUIKit", 12,0 }, { "AuthenticationServices", "AuthenticationServices", 13,0 }, { "SoundAnalysis", "SoundAnalysis", 13,0 }, { "BackgroundTasks", "BackgroundTasks", 13, 0 }, { "Accessibility", "Accessibility", 14,0 }, { "AppTrackingTransparency", "AppTrackingTransparency", 14,0 }, { "CoreHaptics", "CoreHaptics", 14, 0 }, { "LinkPresentation", "LinkPresentation", 14,0 }, { "MLCompute", "MLCompute", new Version (14,0), NotAvailableInSimulator }, { "UniformTypeIdentifiers", "UniformTypeIdentifiers", 14,0 }, { "Intents", "Intents", 14,0 }, { "Chip", "CHIP", new Version (15, 0), NotAvailableInSimulator /* no headers in beta 2 */ }, { "OSLog", "OSLog", 15,0 }, { "ShazamKit", "ShazamKit", new Version (15, 0), NotAvailableInSimulator}, }; } return tvos_frameworks; } } static Frameworks catalyst_frameworks; public static Frameworks GetMacCatalystFrameworks () { if (catalyst_frameworks == null) { catalyst_frameworks = CreateiOSFrameworks (false); // not present in iOS but present in catalyst catalyst_frameworks.Add ("CoreWlan", "CoreWLAN", 15, 0); var min = new Version (13, 0); var v14_2 = new Version (14, 2); foreach (var f in catalyst_frameworks.Values) { switch (f.Name) { // These frameworks were added to Catalyst after they were added to iOS, so we have to adjust the Versions fields case "AddressBook": case "ClassKit": case "UserNotificationsUI": f.Version = v14_2; f.VersionAvailableInSimulator = v14_2; break; // These frameworks are not available on Mac Catalyst case "OpenGLES": case "NewsstandKit": case "MediaSetup": case "NotificationCenter": case "GLKit": case "VideoSubscriberAccount": // The headers for FileProviderUI exist, but the native linker fails case "FileProviderUI": // The headers for Twitter are there, , but no documentation whatsoever online and the native linker fails too case "Twitter": // headers-based xtro reporting those are *all* unknown API for Catalyst case "AddressBookUI": case "AppClip": case "ARKit": case "AssetsLibrary": case "CarPlay": case "CoreTelephony": case "EventKitUI": case "HealthKit": case "HealthKitUI": case "iAd": case "IdentityLookupUI": case "Messages": case "MessageUI": case "VisionKit": case "WatchConnectivity": f.Unavailable = true; break; // and nothing existed before Catalyst 13.0 default: if (f.Version < min) f.Version = min; if (f.VersionAvailableInSimulator < min) f.VersionAvailableInSimulator = min; break; } } // Add frameworks that are not in iOS catalyst_frameworks.Add ("AppKit", 13, 0); } return catalyst_frameworks; } // returns null if the platform doesn't exist (the ErrorHandler machinery is heavy and this file is included in several projects, which makes throwing an exception complicated) public static Frameworks GetFrameworks (ApplePlatform platform, bool is_simulator_build) { switch (platform) { case ApplePlatform.iOS: return GetiOSFrameworks (is_simulator_build); case ApplePlatform.WatchOS: return GetwatchOSFrameworks (is_simulator_build); case ApplePlatform.TVOS: return TVOSFrameworks; case ApplePlatform.MacOSX: return MacFrameworks; case ApplePlatform.MacCatalyst: return GetMacCatalystFrameworks (); default: return null; } } #if MTOUCH || MMP || BUNDLER static void Gather (Application app, AssemblyDefinition product_assembly, HashSet<string> frameworks, HashSet<string> weak_frameworks, Func<Framework, bool> include_framework) { var namespaces = new HashSet<string> (); // Collect all the namespaces. foreach (ModuleDefinition md in product_assembly.Modules) foreach (TypeDefinition td in md.Types) namespaces.Add (td.Namespace); // Iterate over all the namespaces and check which frameworks we need to link with. var all_frameworks = GetFrameworks (app.Platform, app.IsSimulatorBuild); foreach (var nspace in namespaces) { if (!all_frameworks.TryGetValue (nspace, out var framework)) continue; if (!include_framework (framework)) continue; if (app.SdkVersion < framework.Version) { // We're building with an old sdk, and the framework doesn't exist there. continue; } if (app.IsSimulatorBuild && !framework.IsFrameworkAvailableInSimulator (app)) continue; var weak_link = framework.AlwaysWeakLinked || app.DeploymentTarget < framework.Version; var add_to = weak_link ? weak_frameworks : frameworks; add_to.Add (framework.Name); } // Make sure there are no duplicates between frameworks and weak frameworks. // Keep the weak ones. frameworks.ExceptWith (weak_frameworks); } static bool FilterFrameworks (Application app, Framework framework) { switch (app.Platform) { case ApplePlatform.iOS: case ApplePlatform.TVOS: case ApplePlatform.WatchOS: case ApplePlatform.MacCatalyst: break; // Include all frameworks by default case ApplePlatform.MacOSX: switch (framework.Name) { case "QTKit": #if MMP if (Driver.LinkProhibitedFrameworks) { ErrorHelper.Warning (5221, Errors.MM5221, framework.Name); } else { ErrorHelper.Warning (5220, Errors.MM5220, framework.Name); return false; } #endif return true; } return true; default: throw ErrorHelper.CreateError (71, Errors.MX0071 /* "Unknown platform: {0}. This usually indicates a bug in {1}; please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new with a test case." */, app.Platform, app.GetProductName ()); } return true; } public static void Gather (Application app, AssemblyDefinition product_assembly, HashSet<string> frameworks, HashSet<string> weak_frameworks) { Gather (app, product_assembly, frameworks, weak_frameworks, (framework) => FilterFrameworks (app, framework)); } #endif // MTOUCH || MMP || BUNDLER }
36.530263
257
0.622879
[ "BSD-3-Clause" ]
jonathanpeppers/xamarin-macios
tools/common/Frameworks.cs
27,764
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataBoxEdge.V20201201 { /// <summary> /// Compute role. /// </summary> [Obsolete(@"Please use one of the variants: CloudEdgeManagementRole, IoTRole, KubernetesRole, MECRole.")] [AzureNativeResourceType("azure-native:databoxedge/v20201201:Role")] public partial class Role : Pulumi.CustomResource { /// <summary> /// Role type. /// </summary> [Output("kind")] public Output<string> Kind { get; private set; } = null!; /// <summary> /// The object name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Role configured on ASE resource /// </summary> [Output("systemData")] public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!; /// <summary> /// The hierarchical type of the object. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a Role resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Role(string name, RoleArgs args, CustomResourceOptions? options = null) : base("azure-native:databoxedge/v20201201:Role", name, args ?? new RoleArgs(), MakeResourceOptions(options, "")) { } private Role(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:databoxedge/v20201201:Role", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20201201:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20190301:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190301:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20190701:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190701:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20190801:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190801:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20200501preview:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20200501preview:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20200901:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20200901:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20200901preview:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20200901preview:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20210201:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20210201:Role"}, new Pulumi.Alias { Type = "azure-native:databoxedge/v20210201preview:Role"}, new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20210201preview:Role"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Role resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Role Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Role(name, id, options); } } public sealed class RoleArgs : Pulumi.ResourceArgs { /// <summary> /// The device name. /// </summary> [Input("deviceName", required: true)] public Input<string> DeviceName { get; set; } = null!; /// <summary> /// Role type. /// </summary> [Input("kind", required: true)] public InputUnion<string, Pulumi.AzureNative.DataBoxEdge.V20201201.RoleTypes> Kind { get; set; } = null!; /// <summary> /// The role name. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The resource group name. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public RoleArgs() { } } }
43.71223
125
0.587558
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataBoxEdge/V20201201/Role.cs
6,076
C#
using System.Collections.Generic; using System.Security.Claims; using WT.Project.AdvancedDotNetCore.Services.Entities; namespace WT.Project.AdvancedDotNetCore.Services { public static class Extensions { public static ClaimsPrincipal AsPrincipal(this User user, string authenticationScheme) { var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Name), new Claim(CustomClaimTypes.TenantId, user.Tenant.Id.ToString()), new Claim(CustomClaimTypes.TenantName, user.Tenant.Name), }; var identity = new ClaimsIdentity(claims, authenticationScheme); return new ClaimsPrincipal(identity); } public static int TenantId(this ClaimsPrincipal principal) { return int.Parse(principal.FindFirstValue(CustomClaimTypes.TenantId)); } } }
36.148148
94
0.659836
[ "MIT" ]
farzin2171/WT.AdvancedDotNetCore
WT.Solution.AdvancedDotNetCore/WT.Project.AdvancedDotNetCore/Services/Extensions.cs
978
C#
using Microsoft.Extensions.Diagnostics.HealthChecks; using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Mercan.HealthChecks.Common { public class UrlChecker { private readonly Func<HttpResponseMessage, ValueTask<HealthCheckResult>> _checkFunc; private readonly string _url; public UrlChecker(Func<HttpResponseMessage, ValueTask<HealthCheckResult>> checkFunc, string url) { Guard.ArgumentNotNull(nameof(checkFunc), checkFunc); Guard.ArgumentNotNullOrEmpty(nameof(url), url); _checkFunc = checkFunc; _url = url; } public HealthStatus PartiallyHealthyStatus { get; set; } = HealthStatus.Degraded; public async Task<HealthCheckResult> CheckAsync() { using (HttpClient httpClient = CreateHttpClient()) { try { HttpResponseMessage response = await httpClient.GetAsync(_url).ConfigureAwait(false); return await _checkFunc(response); } catch (Exception ex) { Dictionary<string, object> data = new Dictionary<string, object> { { "url", _url } }; data.Add("type", "UrlChecker"); return HealthCheckResult.Unhealthy($"Exception during check: {ex.GetType().FullName}", null, data); } } } private HttpClient CreateHttpClient() { HttpClient httpClient = GetHttpClient(); httpClient.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true }; return httpClient; } public static async ValueTask<HealthCheckResult> DefaultUrlCheck(HttpResponseMessage response) { HealthStatus status = response.IsSuccessStatusCode ? HealthStatus.Healthy : HealthStatus.Unhealthy; Dictionary<string, object> data = new Dictionary<string, object> { { "url", response.RequestMessage.RequestUri.ToString()}, { "status", (int) response.StatusCode }, { "reason", response.ReasonPhrase }, { "body", await response.Content?.ReadAsStringAsync() }, { "type", "UrlChecker"} }; return new HealthCheckResult(status, $"status code {response.StatusCode} ({(int)response.StatusCode})", null, data); } public static async ValueTask<HealthCheckResult> ComposeHealthCheckStatus(HttpResponseMessage response) { HealthStatus status = response.IsSuccessStatusCode ? HealthStatus.Healthy : HealthStatus.Unhealthy; string responseContent = await response.Content?.ReadAsStringAsync(); Dictionary<string, object> data = new Dictionary<string, object> { { "url", response.RequestMessage.RequestUri.ToString()}, { "status", (int) response.StatusCode }, { "reason", response.ReasonPhrase }, { "body", responseContent }, { "type", "UrlChecker"} }; return new HealthCheckResult(status, $"status code {response.StatusCode} ({(int)response.StatusCode})", null, data); } protected virtual HttpClient GetHttpClient() { return new HttpClient(); } } }
41.172414
128
0.594082
[ "MIT" ]
mmercan/sentinel
HealthChecks/Mercan.HealthChecks.Common/Internal/UrlChecker.cs
3,584
C#
using System.Diagnostics; using Evergine.Common.Graphics; using Evergine.Framework; using Evergine.Framework.Graphics; using Evergine.Framework.Services; namespace AreaLightsDemo.Windows { class Program { static void Main(string[] args) { // Create app MyApplication application = new MyApplication(); // Create Services uint width = 1280; uint height = 720; WindowsSystem windowsSystem = new Evergine.Forms.FormsWindowsSystem(); application.Container.RegisterInstance(windowsSystem); var window = windowsSystem.CreateWindow("AreaLightsDemo - DX11", width, height); ConfigureGraphicsContext(application, window); // Creates XAudio device var xaudio = new Evergine.XAudio2.XAudioDevice(); application.Container.RegisterInstance(xaudio); Stopwatch clockTimer = Stopwatch.StartNew(); windowsSystem.Run( () => { application.Initialize(); }, () => { var gameTime = clockTimer.Elapsed; clockTimer.Restart(); application.UpdateFrame(gameTime); application.DrawFrame(gameTime); }); } private static void ConfigureGraphicsContext(Application application, Window window) { GraphicsContext graphicsContext = new Evergine.DirectX11.DX11GraphicsContext(); graphicsContext.CreateDevice(); SwapChainDescription swapChainDescription = new SwapChainDescription() { SurfaceInfo = window.SurfaceInfo, Width = window.Width, Height = window.Height, ColorTargetFormat = PixelFormat.R8G8B8A8_UNorm, ColorTargetFlags = TextureFlags.RenderTarget | TextureFlags.ShaderResource, DepthStencilTargetFormat = PixelFormat.D24_UNorm_S8_UInt, DepthStencilTargetFlags = TextureFlags.DepthStencil, SampleCount = TextureSampleCount.None, IsWindowed = true, RefreshRate = 60 }; var swapChain = graphicsContext.CreateSwapChain(swapChainDescription); swapChain.VerticalSync = true; var graphicsPresenter = application.Container.Resolve<GraphicsPresenter>(); var firstDisplay = new Display(window, swapChain); graphicsPresenter.AddDisplay("DefaultDisplay", firstDisplay); application.Container.RegisterInstance(graphicsContext); } } }
36.575342
92
0.61161
[ "MIT" ]
EvergineTeam/AreaLightsDemo
AreaLightsDemo.Windows/Program.cs
2,670
C#