content
stringlengths
23
1.05M
using T4CAGC.Model; namespace T4CAGC.Template { /// <summary> /// 业务接口类模板选项 /// </summary> public class InterfaceOptions { /// <summary> /// 版本 /// </summary> public string Version { get; set; } /// <summary> /// 表信息 /// </summary> public TableInfo Table { get; set; } } }
using Android.OS; using Android.Runtime; using Android.Support.V7.App; using Android.Support.V7.Widget; using Android.Views; using Android.Widget; using MvvmCross.Binding.Droid.BindingContext; using MvvmCross.Droid.Support.V4; using MvvmCross.Droid.Support.V7.RecyclerView; using MvvmCross.Droid.Views.Attributes; using SharedElement.Presenter.Core.ViewModels; using SharedElement.Presenter.Droid.Adapters; namespace SharedElement.Presenter.Droid.Views { [MvxFragmentPresentation(typeof(MainViewModel), Resource.Id.content_frame)] [Register(DroidConstants.SharedElement_Views_Namespace + nameof(ListFragment))] public class ListFragment : MvxFragment<ListViewModel> { public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { base.OnCreateView(inflater, container, savedInstanceState); var view = this.BindingInflate(Resource.Layout.fragment_list, null); var recyclerView = view.FindViewById<MvxRecyclerView>(Resource.Id.my_recycler_view); if (recyclerView != null) { recyclerView.HasFixedSize = true; var layoutManager = new LinearLayoutManager(Activity); recyclerView.SetLayoutManager(layoutManager); var adapter = new SelectedItemRecyclerAdapter(BindingContext as IMvxAndroidBindingContext); adapter.OnItemClick += Adapter_OnItemClick; recyclerView.Adapter = adapter; } return view; } public override void OnResume() { base.OnResume(); (Activity as AppCompatActivity)?.SupportActionBar.SetDisplayHomeAsUpEnabled(false); } private void Adapter_OnItemClick(object sender, SelectedItemRecyclerAdapter.SelectedItemEventArgs e) { Toast.MakeText(Activity, $"Selected item {e.Position + 1}", ToastLength.Short) .Show(); ImageView itemLogo = e.View.FindViewById<ImageView>(Resource.Id.img_logo); itemLogo.Tag = Activity.Resources.GetString(Resource.String.transition_list_item_icon); TextView itemName = e.View.FindViewById<TextView>(Resource.Id.txt_name); itemName.Tag = Activity.Resources.GetString(Resource.String.transition_list_item_name); ViewModel.SelectItemExecution(e.DataContext as ListItemViewModel); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cxc.SymbolicResolution { public class Scope { public Scope? parent; public Dictionary<string, Symbol> symbols = new Dictionary<string, Symbol>(); public Symbol? Lookup(string name) { if (symbols.ContainsKey(name)) return symbols[name]; if (parent != null) return parent.Lookup(name); return null; } } }
namespace MassTransit { /// <summary> /// Combines a message and a pipe which can be used to send/publish the message /// </summary> /// <typeparam name="T"></typeparam> public readonly struct SendTuple<T> where T : class { public readonly T Message; public readonly IPipe<SendContext<T>> Pipe; public SendTuple(T message, IPipe<SendContext<T>> pipe) { Message = message; Pipe = pipe.IsNotEmpty() ? pipe : MassTransit.Pipe.Empty<SendContext<T>>(); } public SendTuple(T message) { Message = message; Pipe = MassTransit.Pipe.Empty<SendContext<T>>(); } public void Deconstruct(out T message, out IPipe<SendContext<T>> pipe) { message = Message; pipe = Pipe; } } }
//--------------------------------------------------------------------- // <copyright file="ConcurrencyUtil.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using AstoriaUnitTests.Data; namespace System.Data.Test.Astoria { public static class ConcurrencyUtil { public const string WeakPrefix = "W/"; public const string IfMatchHeader = "If-Match"; public const string IfNoneMatchHeader = "If-None-Match"; public const string ETagHeader = "ETag"; public const string Wildcard = "*"; public const string Null = "null"; public static string PrimitiveToETagString(object value) { if (value == null) return Null; // only expect/use the D when its a v2 server bool useDLiteralForDouble = Versioning.Server.SupportsV2Features; string valueString = TypeData.FormatForKey(value, null, useDLiteralForDouble); // fixups for floating point types Type t = value.GetType(); if (t == typeof(Single)) { if (valueString.EndsWith(".0f")) valueString = valueString.Replace(".0f", "f"); } if (t == typeof(Double)) { if (valueString.EndsWith(".0D")) valueString = valueString.Replace(".0D", "D"); else if (!Versioning.Server.SupportsV2Features && valueString.EndsWith(".0")) valueString = valueString.Replace(".0", string.Empty); // for some silly reason, TypeData.FormatForKey does this for already for doubles UNLESS IT PUTS THE 'D' if (useDLiteralForDouble) valueString = Uri.EscapeDataString(valueString); } else { // for some silly reason, TypeData.FormatForKey does this for already for doubles UNLESS IT PUTS THE 'D' valueString = Uri.EscapeDataString(valueString); } return valueString; } public static string ConstructETag(ResourceContainer container, IDictionary<string, object> propertyValues) { ResourceType type = container.BaseType; List<NodeProperty> etagProperties = type.Properties.Where(p => p.Facets.ConcurrencyModeFixed).ToList(); string[] etagValues = etagProperties.Select(p => PrimitiveToETagString(propertyValues[p.Name])).ToArray(); return ConstructETag(etagValues); } public static KeyExpression ConstructKey(ResourceContainer container, PayloadObject entity) { Dictionary<string, object> properties = new Dictionary<string, object>(); ResourceType type = container.BaseType; if (entity.Type != type.Namespace + "." + type.Name) { type = container.ResourceTypes.SingleOrDefault(rt => rt.Namespace + "." + rt.Name == entity.Type); if (type == null) AstoriaTestLog.FailAndThrow("Could not find resource type for payload type value: " + entity.Type); } foreach (ResourceProperty property in type.Properties.OfType<ResourceProperty>()) { if (property.IsNavigation || property.IsComplexType) continue; string propertyName = property.Name; string valueString; if (entity.PayloadProperties.Any(p => p.Name == propertyName)) { PayloadSimpleProperty simpleProperty = entity[propertyName] as PayloadSimpleProperty; if (simpleProperty == null) continue; valueString = simpleProperty.Value; } else { continue; } object value = CommonPayload.DeserializeStringToObject(valueString, property.Type.ClrType, false, entity.Format); if (value is DateTime && entity.Format == SerializationFormatKind.JSON) { // TODO: this is because the server will make any JSON datetime into UTC, and currently we always send 'unspecified' values value = new DateTime(((DateTime)value).Ticks, DateTimeKind.Unspecified); } properties[propertyName] = value; } return new KeyExpression(container, type, properties); } public static string ConstructETag(ResourceContainer container, PayloadObject entity) { KeyExpression key = ConstructKey(container, entity); return key.ETag; } public static string ConstructETag(string[] values) { return ConstructETag(values, true); } public static string ConstructETag(string[] values, bool weak) { string strongETag; if (!values.Any()) strongETag = null; else strongETag = '"' + string.Join(",", values) + '"'; if (weak) return WeakPrefix + strongETag; else return strongETag; } public static string ConstructRandomETag(ResourceContainer container) { ResourceType type = container.BaseType; Dictionary<string, object> randomProperties = new Dictionary<string, object>(); foreach (NodeProperty p in type.Properties.Where(p => p.Facets.ConcurrencyModeFixed)) randomProperties[p.Name] = (p as ResourceProperty).CreateRandomResourceSimpleInstanceProperty().PropertyValue; return ConstructETag(container, randomProperties); } public static string ConstructEquivalentETag(ResourceType type, string ETag) { string[] pieces = SplitETag(ETag); List<NodeProperty> etagProperties = type.Properties.Where(p => p.Facets.ConcurrencyModeFixed).ToList(); for (int i = 0; i < pieces.Length; i++) { string piece = pieces[i]; if (piece == Null) continue; NodeProperty property = etagProperties[i]; NodeType propertyType = etagProperties[i].Type; if (propertyType == Clr.Types.String && property.Facets.FixedLength) { piece = piece.Trim('\''); if (piece.Length < property.Facets.MaxSize) piece = piece + " "; else if (piece.EndsWith(" ")) piece = piece.Remove(piece.Length - 1); piece = "'" + piece + "'"; } else if (propertyType.IsNumeric) { if (piece.Contains("INF") || piece.Contains("NaN")) continue; else if (piece.ToLower().Contains("e")) //must be a floating point { // add 0's and flip capitalization piece = piece.Replace("E%2b", "0e%2B0"); piece = piece.Replace("e%2b", "0E%2B0"); piece = piece.Replace("E%2B", "0e%2b0"); piece = piece.Replace("e%2B", "0E%2b0"); piece = piece.Replace("E+", "0e+0"); piece = piece.Replace("e+", "0E+0"); } else if (propertyType.ClrType == typeof(double) && !(piece.EndsWith("D") || piece.EndsWith("d"))) { if (!piece.Contains('.')) piece = piece + ".0"; else piece = piece + "0"; piece = piece + "E+0"; } else if (propertyType.ClrType == typeof(float) || propertyType.ClrType == typeof(Single) || propertyType.ClrType == typeof(double)) { if (!piece.Contains('.')) piece = piece.Insert(piece.Length - 1, ".0"); //just before the 'f' or 'D' else piece = piece.Insert(piece.Length - 1, "0"); //just before the 'f' or 'D' piece = piece.Insert(piece.Length - 1, "E+0"); } else if (propertyType.ClrType == typeof(decimal)) { if (!piece.Contains('.')) piece = piece.Insert(piece.Length - 1, ".0"); //just before the 'M' else piece = piece.Insert(piece.Length - 1, "0"); //just before the 'M' } if (piece.StartsWith("-")) piece = piece.Insert(1, "0"); else piece = "0" + piece; } pieces[i] = piece; } return ConstructETag(pieces); } public static string[] SplitETag(string ETag) { if (ETag.StartsWith(WeakPrefix)) ETag = ETag.Remove(0, WeakPrefix.Length); ETag = ETag.Trim('"'); string[] split = ETag.Split(','); return split; } public static Dictionary<string, string> ParseETag(ResourceType type, string ETag) { string[] values = SplitETag(ETag); List<string> etagProperties = type.Properties.Where(p => p.Facets.ConcurrencyModeFixed).Select(p => p.Name).ToList(); if (values.Length != etagProperties.Count) { AstoriaTestLog.FailAndThrow("Could not parse etag"); return null; } else { Dictionary<string, string> etagMap = new Dictionary<string, string>(); for (int i = 0; i < values.Length; i++) { etagMap[etagProperties[i]] = values[i]; } return etagMap; } } } }
using Lucid.Lib.Domain.SqlServer; namespace Lucid.Modules.AppFactory.Manufacturing.DbMigrations.V001.V000 { [MigrationOrder(major: 1, minor: 0, script: 0)] public class Rev0_Empty : SqlServerMigration { public override void Up() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace aiof.asset.data { public abstract class AssetEvent { public string EventType { get; set; } public EventSource Source { get; set; } = new EventSource(); public EventUser User { get; set; } = new EventUser(); public EventEntity Entity { get; set; } = new EventEntity(); } public class EventSource { public string Api { get; } = Constants.ApiName; public string Ip { get; set; } } public class EventUser { public int? Id { get; set; } public Guid? PublicKey { get; set; } } public class EventEntity { public int? Id { get; set; } public string Type { get; set; } public object Payload { get; set; } } #region Events public class AssetAddedEvent : AssetEvent { public AssetAddedEvent() { EventType = Constants.AssetAddedEvent; } } public class AssetUpdatedEvent : AssetEvent { public AssetUpdatedEvent() { EventType = Constants.AssetUpdatedEvent; } } public class AssetDeletedEvent : AssetEvent { public AssetDeletedEvent() { EventType = Constants.AssetDeletedEvent; } } #endregion }
using System.Collections.Generic; using System.Windows.Input; namespace Nodify.Calculator { public class ApplicationViewModel : ObservableObject { private readonly Stack<CalculatorViewModel> _calculators = new Stack<CalculatorViewModel>(); public ApplicationViewModel() { _calculators.Push(new CalculatorViewModel()); BackCommand = new RequeryCommand(() => { _calculators.Pop(); OnPropertyChanged(nameof(Current)); OnPropertyChanged(nameof(IsCalculatorOpen)); }, () => _calculators.Count > 1); OpenCalculatorCommand = new DelegateCommand<CalculatorViewModel>(calculator => { _calculators.Push(calculator); OnPropertyChanged(nameof(Current)); OnPropertyChanged(nameof(IsCalculatorOpen)); }); } public ICommand BackCommand { get; } public INodifyCommand OpenCalculatorCommand { get; } public CalculatorViewModel Current => _calculators.Peek(); public bool IsCalculatorOpen => _calculators.Count > 1; } }
using System; namespace JetBrains.SignatureVerifier.Tests { internal sealed class ConsoleLogger : ILogger { public static readonly ILogger Instance = new ConsoleLogger(); private ConsoleLogger() { } void ILogger.Info(string str) => Console.WriteLine($"INFO: {str}"); void ILogger.Warning(string str) => Console.Error.WriteLine($"WARNING: {str}"); void ILogger.Error(string str) => Console.Error.WriteLine($"ERROR: {str}"); void ILogger.Trace(string str) => Console.Error.WriteLine($"TRACE: {str}"); } }
using ProjetoDDD.Domain.Models; using System.Collections.Generic; namespace ProjetoDDD.Domain.Interfaces.Services { public interface ICategoriaDoProdutoService : IServiceBase<CategoriaDoProduto> { IList<CategoriaDoProduto> ObterCategoriasDoProdutoAtivas(IList<CategoriaDoProduto> categoriaDoProdutos); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using NUnit.Framework; using ProtoBuf.Meta; namespace Examples.Issues { [TestFixture] public class SO7686734 { [DataContract] public abstract class GatewayPageEvent { protected GatewayPageEvent() { On = DateTime.Now; } [DataMember(Order = 1)] public Guid GatewayPageId { get; set; } [DataMember(Order = 2)] public DateTime On { get; set; } } [DataContract] public class GatewayPageAddedToSite : GatewayPageEvent { [DataMember(Order = 3)] public string Url { get; set; } [DataMember(Order = 4)] public string SiteCode { get; set; } } public string Serialize(object t) { var memoryStream = new MemoryStream(); ProtoBuf.Serializer.Serialize(memoryStream, t); return Convert.ToBase64String(memoryStream.ToArray()); } public object Deserialize(string value, Type targetType) { var bytes = Convert.FromBase64String(value); var stream = new MemoryStream(bytes); return ProtoBuf.Serializer.NonGeneric.Deserialize(targetType, stream); } [Test] public void protobuf_serialization_can_deserialized_guids() { RuntimeTypeModel.Default[typeof(GatewayPageEvent)].AddSubType(3, typeof(GatewayPageAddedToSite)); var originalMessage = new GatewayPageAddedToSite {GatewayPageId = Guid.NewGuid(), SiteCode = "dls", Url = "test"}; var serializedMessage = Serialize(originalMessage); var @event = (GatewayPageAddedToSite) Deserialize(serializedMessage, typeof (GatewayPageAddedToSite)); Assert.AreEqual(originalMessage.GatewayPageId, @event.GatewayPageId); } [Test] public void guids_work_fine() { var original = Guid.NewGuid(); var serialized = Serialize(original); var deserialized = (Guid) Deserialize(serialized, typeof (Guid)); Assert.AreEqual(original, deserialized); } } }
namespace SolrExpress.Search.Parameter { /// <summary> /// Parameters necessary by system /// </summary> internal interface ISystemParameter<TDocument> : ISearchParameter where TDocument : Document { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Web.Http; using Newtonsoft.Json; namespace JhPrize.Core { public enum ApiOption { GetData, Select, Verify }; public class Api { private static Dictionary<ApiOption, string> dic = new Dictionary<ApiOption, string>() { { ApiOption.GetData, "prize/get_data" }, { ApiOption.Select,"prize/select" }, { ApiOption.Verify,"prize/verify" } }; public static string Pass { get; set; } = "123456"; public static string Domain { get; set; } = "http://localhost/"; public static string GetUrl(ApiOption option) { return $"{Domain}{dic[option]}"; } public async static Task<String> PostAsync(ApiOption option, params KeyValuePair<String,String>[] p) { var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(10)); var httpClient = new HttpClient(); var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri( GetUrl(option))); var responseMessage = await httpClient.PostAsync(new Uri(GetUrl(option)),new HttpFormUrlEncodedContent(p)); if(responseMessage.StatusCode == HttpStatusCode.Ok) { return await responseMessage.Content.ReadAsStringAsync(); } else { return null; } } public async static Task<ResponseModel<PrizeModel>> DrawPrizeAsync(string title, string no) { ResponseModel<PrizeModel> model = JsonConvert.DeserializeObject<ResponseModel<PrizeModel>>( await PostAsync(ApiOption.Select, new KeyValuePair<string, string>("pass", Pass), new KeyValuePair<string, string>("no", no), new KeyValuePair<string,string>("title",title) )); return model; } public async static Task<ResponseModel<PrizeModel>> AcceptPrizeAsync(string no) { ResponseModel<PrizeModel> model = JsonConvert.DeserializeObject<ResponseModel<PrizeModel>>( await PostAsync(ApiOption.Verify, new KeyValuePair<string, string>("pass", Pass), new KeyValuePair<string, string>("no", no) )); return model; } public async static Task<IEnumerable<PrizePool>> GetDataAsync() { ResponseModel<PrizePoolModel[]> model = JsonConvert.DeserializeObject<ResponseModel<PrizePoolModel[]>>( await PostAsync(ApiOption.GetData, new KeyValuePair<string, string>("pass", Pass))); List<PrizePool> result = new List<PrizePool>(); return model.data.Select((a) => a.ToPrizePool()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace osoba_text { class Program { static void Main(string[] args) { Osoba os1 = new Osoba("MarKo", "marULIĆ"); Osoba os2 = new Osoba("anica", "anić"); Osoba os3 = new Osoba("Perica", "Perić"); List<Osoba> osobe = new List<Osoba>(); osobe.Add(os1); osobe.Add(os2); osobe.Add(os3); Console.WriteLine("------"); foreach (var item in osobe) { Console.WriteLine("Pozdrav! " + item); } Console.ReadKey(); } } }
// Copyright 2016-2021, Pulumi Corporation using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; namespace Pulumi { /// <summary> /// A mapping of <see cref="string"/>s to values that can be passed in as the arguments to a /// <see cref="Resource"/>. The individual values are themselves <see cref="Input{T}"/>s. i.e. /// the individual values can be concrete values or <see cref="Output{T}"/>s. /// <para/> /// <see cref="InputMap{V}"/> differs from a normal <see cref="IDictionary{TKey,TValue}"/> in that it is /// itself an <see cref="Input{T}"/>. For example, a <see cref="Resource"/> that accepts an /// <see cref="InputMap{V}"/> will accept not just a dictionary but an <see cref="Output{T}"/> /// of a dictionary as well. This is important for cases where the <see cref="Output{T}"/> /// map from some <see cref="Resource"/> needs to be passed into another <see cref="Resource"/>. /// Or for cases where creating the map invariably produces an <see cref="Output{T}"/> because /// its resultant value is dependent on other <see cref="Output{T}"/>s. /// <para/> /// This benefit of <see cref="InputMap{V}"/> is also a limitation. Because it represents a /// list of values that may eventually be created, there is no way to simply iterate over, or /// access the elements of the map synchronously. /// <para/> /// <see cref="InputMap{V}"/> is designed to be easily used in object and collection /// initializers. For example, a resource that accepts a map of values can be written easily in /// this form: /// <para/> /// <code> /// new SomeResource("name", new SomeResourceArgs { /// MapProperty = { /// { Key1, Value1 }, /// { Key2, Value2 }, /// { Key3, Value3 }, /// }, /// }); /// </code> /// </summary> public sealed class InputMap<V> : Input<ImmutableDictionary<string, V>>, IEnumerable, IAsyncEnumerable<Input<KeyValuePair<string, V>>> { public InputMap() : this(Output.Create(ImmutableDictionary<string, V>.Empty)) { } private InputMap(Output<ImmutableDictionary<string, V>> values) : base(values) { } public void Add(string key, Input<V> value) { var inputDictionary = (Input<ImmutableDictionary<string, V>>)_outputValue; _outputValue = Output.Tuple(inputDictionary, value) .Apply(x => x.Item1.Add(key, x.Item2)); } /// <summary> /// Note: this is non-standard convenience for use with collection initializers. /// </summary> public void Add(InputMap<V> values) { AddRange(values); } public void AddRange(InputMap<V> values) { var inputDictionary = (Input<ImmutableDictionary<string, V>>)_outputValue; _outputValue = Output.Tuple(inputDictionary, values) .Apply(x => x.Item1.AddRange(x.Item2)); } public Input<V> this[string key] { set => Add(key, value); } /// <summary> /// Merge two instances of <see cref="InputMap{V}"/>. Returns a new <see cref="InputMap{V}"/> /// without modifying any of the arguments. /// <para/>If both maps contain the same key, the value from the second map takes over. /// </summary> /// <param name="first">The first <see cref="InputMap{V}"/>. Has lower priority in case of /// key clash.</param> /// <param name="second">The second <see cref="InputMap{V}"/>. Has higher priority in case of /// key clash.</param> /// <returns>A new instance of <see cref="InputMap{V}"/> that contains the items from /// both input maps.</returns> public static InputMap<V> Merge(InputMap<V> first, InputMap<V> second) { var output = Output.Tuple(first._outputValue, second._outputValue) .Apply(dicts => { var result = new Dictionary<string, V>(dicts.Item1); // Overwrite keys if duplicates are found foreach (var (k, v) in dicts.Item2) result[k] = v; return result; }); return output; } #region construct from dictionary types public static implicit operator InputMap<V>(Dictionary<string, V> values) => Output.Create(values); public static implicit operator InputMap<V>(ImmutableDictionary<string, V> values) => Output.Create(values); public static implicit operator InputMap<V>(Output<Dictionary<string, V>> values) => values.Apply(ImmutableDictionary.CreateRange); public static implicit operator InputMap<V>(Output<IDictionary<string, V>> values) => values.Apply(ImmutableDictionary.CreateRange); public static implicit operator InputMap<V>(Output<ImmutableDictionary<string, V>> values) => new InputMap<V>(values); #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException($"A {GetType().FullName} cannot be synchronously enumerated. Use {nameof(GetAsyncEnumerator)} instead."); public async IAsyncEnumerator<Input<KeyValuePair<string, V>>> GetAsyncEnumerator(CancellationToken cancellationToken) { var data = await _outputValue.GetValueAsync(whenUnknown: ImmutableDictionary<string, V>.Empty) .ConfigureAwait(false); foreach (var value in data) { yield return value; } } #endregion } }
namespace Alpaca.Markets; internal static class Validation { private const Int32 ClientOrderIdMaxLength = 128; private const Int32 WatchListNameMaxLength = 64; private const String WatchListNameShouldBe64CharactersLengthMessage = "Watch list name should be from 1 to 64 characters length."; private const String ListShouldContainsAtLeastOneItemMessage = "Symbols list should contains at least one item."; private const String RequestPageSizeTooBigOrTooSmallMessage = "Request page size too big or too small."; private const String OrderQuantityShouldBePositiveMessage = "Order quantity should be positive value."; private const String CollectionShouldNotBeEmptyMessage = "Collection should contains at least one item."; private const String IntervalShouldNotBeOpenMessage = "You should specify both start and end of the interval."; private const String SymbolShouldNotBeEmptyMessage = "Symbol shouldn't be empty."; internal interface IRequest { /// <summary> /// Gets all validation exceptions (inconsistent request data errors). /// </summary> /// <returns>Lazy-evaluated list of validation errors.</returns> IEnumerable<RequestValidationException?> GetExceptions(); } public static TRequest Validate<TRequest>( this TRequest request) where TRequest : class, IRequest { var exception = new AggregateException( request.GetExceptions().OfType<RequestValidationException>()); if (exception.InnerExceptions.Count != 0) { throw exception.InnerExceptions.Count == 1 ? exception.InnerExceptions[0] : exception; } return request; } public static RequestValidationException? TryValidateSymbolName( this String symbolName, [CallerArgumentExpression("symbolName")] String propertyName = "") => String.IsNullOrWhiteSpace(symbolName) ? new RequestValidationException(SymbolShouldNotBeEmptyMessage, propertyName) : null; public static RequestValidationException? TryValidateSymbolName( this IEnumerable<String> symbolNames, [CallerArgumentExpression("symbolNames")] String propertyName = "") => symbolNames.Any(String.IsNullOrWhiteSpace) ? new RequestValidationException(SymbolShouldNotBeEmptyMessage, propertyName) : null; public static RequestValidationException? TryValidateQuantity( this OrderQuantity quantity, [CallerArgumentExpression("quantity")] String propertyName = "") => quantity.Value <= 0M ? new RequestValidationException(OrderQuantityShouldBePositiveMessage, propertyName) : null; public static RequestValidationException? TryValidateQuantity( this Int64? quantity, [CallerArgumentExpression("quantity")] String propertyName = "") => quantity <= 0M ? new RequestValidationException(OrderQuantityShouldBePositiveMessage, propertyName) : null; public static RequestValidationException? TryValidatePageSize( this Pagination pagination, UInt32 maxPageSize, [CallerArgumentExpression("pagination")] String propertyName = "") => pagination.Size < Pagination.MinPageSize || pagination.Size > maxPageSize ? new RequestValidationException(RequestPageSizeTooBigOrTooSmallMessage, propertyName) : null; public static RequestValidationException? TryValidateSymbolsList( this IReadOnlyCollection<String> symbolNames, [CallerArgumentExpression("symbolNames")] String propertyName = "") => symbolNames.Count == 0 ? new RequestValidationException(ListShouldContainsAtLeastOneItemMessage, propertyName) : null; public static RequestValidationException? TryValidateWatchListName( this String? watchListName, [CallerArgumentExpression("watchListName")] String propertyName = "") => isWatchListNameInvalid(watchListName) ? new RequestValidationException(WatchListNameShouldBe64CharactersLengthMessage, propertyName) : null; public static RequestValidationException? TryValidateWatchListName<TKey>( this TKey watchListName, [CallerArgumentExpression("watchListName")] String propertyName = "") => watchListName is String stringKey && isWatchListNameInvalid(stringKey) ? new RequestValidationException(WatchListNameShouldBe64CharactersLengthMessage, propertyName) : null; public static RequestValidationException? TryValidateCollection<TItem>( this IReadOnlyCollection<TItem> collection, [CallerArgumentExpression("collection")] String propertyName = "") => collection.Count == 0 ? new RequestValidationException(CollectionShouldNotBeEmptyMessage, propertyName) : null; public static RequestValidationException? TryValidateInterval<TItem>( this Interval<TItem> interval, [CallerArgumentExpression("interval")] String propertyName = "") where TItem : struct, IComparable<TItem> => interval.IsOpen() ? new RequestValidationException(IntervalShouldNotBeOpenMessage, propertyName) : null; public static String? ValidateWatchListName( this String? watchListName, [CallerArgumentExpression("watchListName")] String propertyName = "") => isWatchListNameInvalid(watchListName) ? throw new ArgumentException(WatchListNameShouldBe64CharactersLengthMessage, propertyName) : watchListName; public static String? TrimClientOrderId( this String? clientOrderId) => clientOrderId?.Length > ClientOrderIdMaxLength ? clientOrderId[..ClientOrderIdMaxLength] : clientOrderId; private static Boolean isWatchListNameInvalid( this String? watchListName) => watchListName is null || #pragma warning disable CA1508 // Avoid dead conditional code String.IsNullOrEmpty(watchListName) || #pragma warning restore CA1508 // Avoid dead conditional code watchListName.Length > WatchListNameMaxLength; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nehta.VendorLibrary.CDAPackage { /// <summary> /// Represents a CDA signature approver. /// </summary> public class Approver { public Uri PersonId { get; set; } public List<string> PersonTitles { get; set; } public List<string> PersonGivenNames { get; set; } public string PersonFamilyName { get; set; } public List<string> PersonNameSuffixes { get; set; } public Approver() { } public Approver(Uri personId, string personFamilyName) { this.PersonId = personId; this.PersonFamilyName = personFamilyName; } /// <summary> /// Determines whether the specified Object is equal to the current Object. /// </summary> /// <param name="obj">The Object to compare with the current Object.</param> /// <returns>true if the specified Object is equal to the current Object; otherwise, false.</returns> public override bool Equals(object obj) { var compare = obj as Approver; if (compare == null) return false; if (Helper.HasNullDifference(PersonId, compare.PersonId)) return false; if (PersonId != null && (PersonId.ToString() != compare.PersonId.ToString())) return false; if (PersonFamilyName != compare.PersonFamilyName) return false; if (!StringListCompare(PersonGivenNames, compare.PersonGivenNames)) return false; if (!StringListCompare(PersonNameSuffixes, compare.PersonNameSuffixes)) return false; if (!StringListCompare(PersonTitles, compare.PersonTitles)) return false; return true; } private bool StringListCompare(List<string> array1, List<string> array2) { if (Helper.HasNullDifference(array1, array2)) return false; if (array1 != null) { array1.Sort((a, b) => a.CompareTo(b)); array2.Sort((a, b) => a.CompareTo(b)); for (int x = 0; x < array1.Count; x++) { if (array1[x] != array2[x]) return false; } } return true; } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using Keutmann.SharePointManager.Library; namespace Keutmann.SharePointManager.Components { class ListCollectionNode : ExplorerNodeBase { public WebNode WebNode = null; public ListCollectionNode(WebNode webNode, SPWeb web) { this.Text = SPMLocalization.GetString("Lists_Text"); this.ToolTipText = SPMLocalization.GetString("Lists_ToolTip"); this.Name = "Lists"; this.Tag = web.Lists; this.SPParent = web; this.WebNode = webNode; int index = Program.Window.Explorer.AddImage(this.ImageUrl()); this.ImageIndex = index; this.SelectedImageIndex = index; //this.ContextMenuStrip = SPMMenu.Strips.Refresh; if (web.Lists.Count > 0) { this.Nodes.Add(new ExplorerNodeBase("Dummy")); } else { this.HasChildrenLoaded = true; } } public override void LoadNodes() { base.LoadNodes(); SPWeb web = this.SPParent as SPWeb; foreach (SPList list in web.Lists) { if (!list.Hidden) { this.AddNode(NodeDisplayLevelType.Simple, new ListNode(WebNode, list)); } else { this.AddNode(NodeDisplayLevelType.Medium, new ListNode(WebNode, list)); } } } public override string ImageUrl() { return SPMPaths.ImageDirectory + "itgen.GIF"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; using ScriptEngine.HostedScript.Library; using ScriptEngine.HostedScript.Library.Binary; using ScriptEngine; using ScriptEngine.Environment; using ScriptEngine.HostedScript; namespace OneScript.DataProcessor { // Это класс менеджера обработки [ContextClass("ТестоваяОбработка", "TestDataProcessor")] public class Demo : AutoContext<Demo> { public Demo() { } // Метод платформы [ContextMethod("Создать", "Create")] public IValue Create() { // Создаем объект из модуля объекта return new DemoImpl(); } // Статический метод модуля менеджера [ContextMethod("ПолучитьТоЖеСамоеЧисло", "GetTheSameDigit")] public int GetTheSameDigit(int digit) { return digit; } } // Это класс модуля объекта обработки [ContextClass("ТестоваяОбработкаОбъект", "TestDataProcessorObject")] public class DemoImpl : AutoContext<DemoImpl> { public DemoImpl() { } [ContextProperty("Свойство", "Property")] public int Property { get; set; } [ContextMethod("Сложить", "Add")] public int Add(int number1, int number2) { return number1 + number2; } } }
@using UKHO.MaritimeSafetyInformation.Common.Models.NoticesToMariners @model List<ShowDailyFilesResponseModel> @{ Layout = "~/Views/Shared/_MSILayout.cshtml"; ViewData["Header"] = "Notices to Mariners"; } @section Scripts { <script type="text/javascript" src="@Url.Content("~/js/Custom/NoticesToMariners.js")"></script> } <partial name="_NMHorizontalTab" /> <div class="tab-content" id="nmTabContent"> <div class="tab-pane fade show active" id="daily" role="tabpanel" aria-labelledby="daily-tab"> <input type="hidden" id="hdnRequestType" value="Daily" /> @if (@Model != null) { <partial name="ShowDailyFilesList" model="@Model" /> } </div> <div class="tab-pane fade" id="cumulative" role="tabpanel" aria-labelledby="cumulative-tab"> <partial name="ShowCumulativeNMs" /> </div> <div class="tab-pane fade" id="annual" role="tabpanel" aria-labelledby="annual-tab"> <partial name="ShowAnnualNMs" /> </div> </div>
using System.Buffers; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using HotChocolate.Execution; using HotChocolate.Language; using HotChocolate.Utilities; #nullable enable namespace HotChocolate.Stitching.Utilities { internal class HttpQueryClient { private static readonly KeyValuePair<string, string> _contentTypeJson = new KeyValuePair<string, string>("Content-Type", "application/json"); private static readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, IgnoreNullValues = true, IgnoreReadOnlyProperties = false }; private static readonly JsonWriterOptions _jsonWriterOptions = new JsonWriterOptions { SkipValidation = true, Indented = false }; public async Task<QueryResult> FetchAsync( IReadOnlyQueryRequest request, HttpClient httpClient, IEnumerable<IHttpQueryRequestInterceptor>? interceptors = default, CancellationToken cancellationToken = default) { using var writer = new ArrayWriter(); using var jsonWriter = new Utf8JsonWriter(writer, _jsonWriterOptions); WriteJsonRequest(writer, jsonWriter, request); jsonWriter.Flush(); var requestBody = new ByteArrayContent(writer.GetInternalBuffer(), 0, writer.Length); requestBody.Headers.Add(_contentTypeJson.Key, _contentTypeJson.Value); // note: this one has to be awaited since byte array content uses a rented buffer // which is released as soon as writer is disposed. return await FetchAsync( request, requestBody, httpClient, interceptors, cancellationToken) .ConfigureAwait(false); } private async Task<QueryResult> FetchAsync( IReadOnlyQueryRequest request, HttpContent requestContent, HttpClient httpClient, IEnumerable<IHttpQueryRequestInterceptor>? interceptors, CancellationToken cancellationToken) { HttpResponseMessage message = await FetchInternalAsync(requestContent, httpClient).ConfigureAwait(false); using (Stream stream = await message.Content.ReadAsStreamAsync().ConfigureAwait(false)) { object response = await BufferHelper.ReadAsync( stream, (buffer, bytesBuffered) => ParseJson(buffer, bytesBuffered), cancellationToken) .ConfigureAwait(false); QueryResult queryResult = response is IReadOnlyDictionary<string, object> d ? HttpResponseDeserializer.Deserialize(d) : QueryResult.CreateError( ErrorBuilder.New() .SetMessage("Could not deserialize query response.") .Build()); if (interceptors is { }) { foreach (IHttpQueryRequestInterceptor interceptor in interceptors) { await interceptor.OnResponseReceivedAsync( request, message, queryResult) .ConfigureAwait(false); } } return queryResult; } } private static object ParseJson(byte[] buffer, int bytesBuffered) { var json = new ReadOnlySpan<byte>(buffer, 0, bytesBuffered); return Utf8GraphQLRequestParser.ParseJson(json); } public Task<(string, HttpResponseMessage)> FetchStringAsync( HttpQueryRequest request, HttpClient httpClient) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (httpClient == null) { throw new ArgumentNullException(nameof(httpClient)); } return FetchStringInternalAsync(request, httpClient); } private async Task<(string, HttpResponseMessage)> FetchStringInternalAsync( HttpQueryRequest request, HttpClient httpClient) { byte[] json = JsonSerializer.SerializeToUtf8Bytes(request, _jsonSerializerOptions); var content = new ByteArrayContent(json, 0, json.Length); content.Headers.Add(_contentTypeJson.Key, _contentTypeJson.Value); HttpResponseMessage response = await httpClient.PostAsync(default(Uri), content) .ConfigureAwait(false); response.EnsureSuccessStatusCode(); string responseContent = await response.Content.ReadAsStringAsync() .ConfigureAwait(false); return (responseContent, response); } private static async Task<HttpResponseMessage> FetchInternalAsync( HttpContent requestContent, HttpClient httpClient) { HttpResponseMessage response = await httpClient.PostAsync(default(Uri), requestContent) .ConfigureAwait(false); response.EnsureSuccessStatusCode(); return response; } private void WriteJsonRequest( IBufferWriter<byte> writer, Utf8JsonWriter jsonWriter, IReadOnlyQueryRequest request) { jsonWriter.WriteStartObject(); jsonWriter.WriteString("query", request.Query.ToString()); if (request.OperationName is { }) { jsonWriter.WriteString("operationName", request.OperationName); } WriteJsonRequestVariables(writer, jsonWriter, request.VariableValues); jsonWriter.WriteEndObject(); } private static void WriteJsonRequestVariables( IBufferWriter<byte> writer, Utf8JsonWriter jsonWriter, IReadOnlyDictionary<string, object> variables) { if (variables is { } && variables.Count > 0) { jsonWriter.WritePropertyName("variables"); jsonWriter.WriteStartObject(); foreach (KeyValuePair<string, object> variable in variables) { jsonWriter.WritePropertyName(variable.Key); WriteValue(writer, jsonWriter, variable.Value); } jsonWriter.WriteEndObject(); } } private static void WriteValue( IBufferWriter<byte> writer, Utf8JsonWriter jsonWriter, object value) { if (value is null || value is NullValueNode) { jsonWriter.WriteNullValue(); } else { switch (value) { case ObjectValueNode obj: jsonWriter.WriteStartObject(); foreach (ObjectFieldNode field in obj.Fields) { jsonWriter.WritePropertyName(field.Name.Value); WriteValue(writer, jsonWriter, field.Value); } jsonWriter.WriteEndObject(); break; case ListValueNode list: jsonWriter.WriteStartArray(); foreach (IValueNode item in list.Items) { WriteValue(writer, jsonWriter, item); } jsonWriter.WriteEndArray(); break; case StringValueNode s: jsonWriter.WriteStringValue(s.Value); break; case EnumValueNode e: jsonWriter.WriteStringValue(e.Value); break; case IntValueNode i: jsonWriter.WriteStringValue(i.Value); RemoveQuotes(writer, jsonWriter, i.Value.Length); break; case FloatValueNode f: jsonWriter.WriteStringValue(f.Value); RemoveQuotes(writer, jsonWriter, f.Value.Length); break; case BooleanValueNode b: jsonWriter.WriteBooleanValue(b.Value); break; default: throw new NotSupportedException( "Unknown variable value kind."); } } } private static void RemoveQuotes(IBufferWriter<byte> writer, Utf8JsonWriter jsonWriter, int length) { jsonWriter.Flush(); writer.Advance(-(length + 2)); Span<byte> span = writer.GetSpan(length + 2); span.Slice(1, length + 1).CopyTo(span); writer.Advance(length); } } }
using VSPropertyPages; namespace XSharp.ProjectSystem.VS.PropertyPages { /// <summary> /// Interaction logic for AssemblePropertyPageControl.xaml /// </summary> internal partial class AssemblePropertyPageControl : WpfPropertyPageUI { public AssemblePropertyPageControl() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DEM.Net.TestWinForm { public enum enumProgressionCouleurs { red, green, blue, greenVersRed } }
using AutoMapper; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.DSX.ProjectTemplate.Data; namespace Microsoft.DSX.ProjectTemplate.Command { /// <summary> /// Base class that all query handlers inherit from /// </summary> public abstract class QueryHandlerBase : HandlerBase { protected QueryHandlerBase( IMediator mediator, ProjectTemplateDbContext database, IMapper mapper, IAuthorizationService authorizationService) : base(mediator, database, mapper, authorizationService) { // queries do not make changes to the database so we do not need ChangeTracker database.ChangeTracker.QueryTrackingBehavior = EntityFrameworkCore.QueryTrackingBehavior.NoTracking; } } }
using System.Threading.Tasks; using Microsoft.Bot.Builder; using MicrosoftTeamsIntegration.Jira.Models; namespace MicrosoftTeamsIntegration.Jira.Services.Interfaces { public interface IActionableMessageService { Task<bool> HandleConnectorCardActionQuery(ITurnContext context, IntegratedUser user); } }
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2021 Senparc 文件名:CheckSignature.cs 文件功能描述:检测签名 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 修改标识:Senparc - 20151005 修改描述:v13.3.1 提供带PostModel参数的方法 修改标识:Senparc - 20151005 修改描述:v13.8.7 fixbug:Check(string signature, PostModel postModel)方法调用错误 ----------------------------------------------------------------*/ using System.Linq; using System.Security.Cryptography; using System.Text; using Senparc.Weixin.MP.Entities.Request; //using System.Web.Security; namespace Senparc.Weixin.MP { /// <summary> /// 签名验证类 /// </summary> public class CheckSignature { /// <summary> /// 在网站没有提供Token(或传入为null)的情况下的默认Token,建议在网站中进行配置。 /// </summary> public const string Token = "weixin"; /// <summary> /// 检查签名是否正确 /// </summary> /// <param name="signature"></param> /// <param name="postModel">需要提供:Timestamp、Nonce、Token</param> /// <returns></returns> public static bool Check(string signature, PostModel postModel) { return Check(signature, postModel.Timestamp, postModel.Nonce, postModel.Token); } /// <summary> /// 检查签名是否正确 /// </summary> /// <param name="signature"></param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <param name="token"></param> /// <returns></returns> public static bool Check(string signature, string timestamp, string nonce, string token = null) { return signature == GetSignature(timestamp, nonce, token); } /// <summary> /// 返回正确的签名 /// </summary> /// <param name="postModel">需要提供:Timestamp、Nonce、Token</param> /// <returns></returns> public static string GetSignature(PostModel postModel) { return GetSignature(postModel.Timestamp, postModel.Nonce, postModel.Token); } /// <summary> /// 返回正确的签名 /// </summary> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <param name="token"></param> /// <returns></returns> public static string GetSignature(string timestamp, string nonce, string token = null) { token = token ?? Token; var arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray(); var arrString = string.Join("", arr); //var enText = FormsAuthentication.HashPasswordForStoringInConfigFile(arrString, "SHA1");//使用System.Web.Security程序集 var sha1 = SHA1.Create(); var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString)); StringBuilder enText = new StringBuilder(); foreach (var b in sha1Arr) { enText.AppendFormat("{0:x2}", b); } return enText.ToString(); } } }
using System.IO; namespace LogRotate.Compression { public class NoCompression : CompressionScheme { public NoCompression(int value, string displayName) : base(value, displayName) { } public override string Extension { get { return ""; } } public override Stream GetCompressionStream(FileStream stream) { return stream; } } }
using System; namespace Streamiz.Kafka.Net.Stream { /// <summary> /// Hopping time windows are windows based on time intervals. /// They model fixed-sized, (possibly) overlapping windows. /// A hopping window is defined by two properties: the window’s size and its advance interval (aka “hop”). /// The advance interval specifies by how much a window moves forward relative to the previous one. /// For example, you can configure a hopping window with a size 5 minutes and an advance interval of 1 minute. /// Since hopping windows can overlap – and in general they do – a data record may belong to more than one such windows. /// </summary> public class HoppingWindowOptions : TimeWindowOptions { /// <summary> /// /// </summary> /// <param name="sizeMs"></param> /// <param name="advanceMs"></param> /// <param name="graceMs"></param> /// <param name="maintainDurationMs"></param> protected HoppingWindowOptions(long sizeMs, long advanceMs, long graceMs, long maintainDurationMs) : base(sizeMs, advanceMs, graceMs, maintainDurationMs) { } /// <summary> /// Static method to create <see cref="HoppingWindowOptions"/> with size windows and advance interval (aka “hop”) /// </summary> /// <param name="sizeMs">Size windows</param> /// <param name="advanceMs">Advance interval</param> /// <returns>Return a <see cref="HoppingWindowOptions"/> instance</returns> public static HoppingWindowOptions Of(long sizeMs, long advanceMs) => new HoppingWindowOptions(sizeMs, advanceMs, -1, DEFAULT_RETENTION_MS); /// <summary> /// Static method to create <see cref="HoppingWindowOptions"/> with size windows and advance interval (aka “hop”) /// </summary> /// <param name="size">TimeSpan size windows</param> /// <param name="advance">Advance interval</param> /// <returns>Return a <see cref="HoppingWindowOptions"/> instance</returns> public static HoppingWindowOptions Of(TimeSpan size, TimeSpan advance) => Of((long)size.TotalMilliseconds, (long)advance.TotalMilliseconds); } }
using SimpleClassCreator.Lib.Models; using SimpleClassCreator.Lib.Services; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace SimpleClassCreator.Ui { /// <summary> /// Interaction logic for DTOMakerControl.xaml /// </summary> public partial class DtoMakerControl : UserControl { private readonly IDtoGenerator _generator; private string AssemblyFullPath => txtAssemblyFullFilePath.Text; private string ClassFqdn => txtFullyQualifiedClassName.Text; public DtoMakerControl() { InitializeComponent(); //TODO: Need to use Dependency Injection here _generator = new DtoGenerator(); } private void btnAssemblyOpenDialog_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog(); if (!ofd.ShowDialog().Value) return; txtAssemblyFullFilePath.Text = ofd.FileName; lblAssemblyChosen.Content = System.IO.Path.GetFileName(ofd.FileName); } private void lblClassName_MouseEnter(object sender, MouseEventArgs e) { Cursor = Cursors.Help; } private void lblClassName_MouseLeave(object sender, MouseEventArgs e) { Cursor = Cursors.Arrow; } private void lblClassName_MouseDoubleClick(object sender, MouseButtonEventArgs e) { string strHelp = @"A Fully Qualified Class Name is providing the class name with its namespace separated by periods. Example: If you have a class named Product, but it exists in My.Project.Business, then enter: My.Project.Business.Product, in the text box below. Please keep in mind casing matters."; MessageBox.Show(strHelp, "What is a Fully Qualified Class Name?"); } private void btnLoadClass_Click(object sender, RoutedEventArgs e) { _generator.LoadAssembly(AssemblyFullPath); var asm = _generator.GetClassProperties(ClassFqdn); LoadTreeView(asm); } private void LoadTreeView(AssemblyInfo assembly) { var asm = new TreeViewItem(); asm.Header = assembly.Name; foreach(var ci in assembly.Classes) { var cls = new TreeViewItem(); cls.Header = ci.FullName; cls.IsExpanded = true; foreach(var pi in ci.Properties) cls.Items.Add(MakeOption(pi)); asm.Items.Add(cls); } tvAssebliesAndClasses.Items.Add(asm); } private StackPanel MakeOption(PropertyInfo info) { var cbx = new CheckBox(); cbx.Name = "cbx_" + info.Name; cbx.IsChecked = true; var lbl = new Label(); lbl.Name = "lbl_" + info.Name; lbl.Content = info.ToString(); var sp = new StackPanel(); sp.Orientation = Orientation.Horizontal; sp.Children.Add(cbx); sp.Children.Add(lbl); return sp; } private DtoMakerParameters GetParametersFromUi() { //Not every parameter will be in use yet var p = new DtoMakerParameters { IncludeCloneMethod = GetValue(cbxIncludeCloneMethod), ExcludeCollections = GetValue(cbxExcludeCollections), IncludeTranslateMethod = GetValue(cbxIncludeTranslateMethod), IncludeIEquatableOfTMethods = GetValue(cbxIncludeIEquatableOfTMethod) }; return p; } private bool GetValue(CheckBox cb) { var value = cb.IsChecked.GetValueOrDefault(); return value; } private void btnGenerate_Click(object sender, RoutedEventArgs e) { var p = GetParametersFromUi(); _generator.LoadAssembly(AssemblyFullPath); var win = new ResultWindow("Dto", _generator.MakeDto(ClassFqdn, p)); win.Show(); } } }
using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace AccidentalFish.ApplicationSupport.Repository.EntityFramework.Policies.Implementation { internal class NullDatabaseConfiguration : DbConfiguration, IDbConfiguration { public IDbExecutionStrategy ExecutionStrategy => new DefaultExecutionStrategy(); public bool SuspendExecutionStrategy { get; set; } } }
using System.Collections.Generic; using VRoidSDK.Examples.Core.View; using VRoidSDK.Examples.Core.Renderer; using VRoidSDK.Examples.Core.Localize; using VRoidSDK.Examples.ArtworkExample.View; using VRoidSDK.Examples.ArtworkExample.Model; namespace VRoidSDK.Examples.ArtworkExample.Renderer { public class ArtworksRenderer : IRenderer { private bool _panelActive; private List<Artwork> _artworks; private Account? _currentUser; private ApiLink? _next; public ArtworksRenderer(ArtworkModel model) { _panelActive = model.Active; _artworks = model.UserArtworks; _currentUser = model.CurrentUser; _next = model.Next.next; } public void Rendering(RootView root) { var artworkView = (ArtworkRootView)root; artworkView.ApiErrorMessage.Active = false; artworkView.artworksView.Active = _panelActive; if (_panelActive) { artworkView.artworksView.SetUserIcon(_currentUser.Value.user_detail.user.icon.sq170); artworkView.artworksView.SetArtworkThumbnails(_artworks); } artworkView.artworksView.seeMoreButton.Active = _next != null; } } }
using System.Collections; using UnityEngine; using UnityEngine.XR; namespace MecanimIKPlus { public class XR_Hand_Tracking_CS : MonoBehaviour { public bool isLeft; public Vector3 offsetAngles; Transform thisTransform; XRNode node; Vector3 targetPos; void Start () { thisTransform = transform; if (isLeft) { node = XRNode.LeftHand; } else { node = XRNode.RightHand; } } void Update () { thisTransform.localPosition = InputTracking.GetLocalPosition (node); thisTransform.localRotation = InputTracking.GetLocalRotation (node) * Quaternion.Euler (offsetAngles); } } }
using System; using System.Reflection; using Autofac; using GreenPipes; using LeanCode.Components; using LeanCode.DomainModels.MassTransitRelay.Inbox; using LeanCode.DomainModels.MassTransitRelay.Middleware; using LeanCode.DomainModels.MassTransitRelay.Outbox; using LeanCode.DomainModels.MassTransitRelay.Simple; using LeanCode.PeriodicService; using MassTransit; using MassTransit.AutofacIntegration; using Microsoft.Extensions.DependencyInjection; namespace LeanCode.DomainModels.MassTransitRelay { public class MassTransitRelayModule : AppModule { private readonly TypesCatalog consumersCatalog; private readonly TypesCatalog eventsCatalog; private readonly Action<IContainerBuilderBusConfigurator> busConfig; private readonly bool useInbox; private readonly bool useOutbox; public MassTransitRelayModule( TypesCatalog consumersCatalog, TypesCatalog eventsCatalog, Action<IContainerBuilderBusConfigurator>? busConfig = null, bool useInbox = true, bool useOutbox = true) { this.consumersCatalog = consumersCatalog; this.eventsCatalog = eventsCatalog; this.busConfig = busConfig ?? DefaultBusConfigurator; this.useInbox = useInbox; this.useOutbox = useOutbox; } protected override void Load(ContainerBuilder builder) { builder.RegisterGeneric(typeof(EventsPublisherElement<,,>)).AsSelf(); builder.RegisterGeneric(typeof(StoreAndPublishEventsElement<,,>)).AsSelf(); builder.RegisterType<EventPublisher>().AsImplementedInterfaces().SingleInstance(); builder.RegisterType<EventsStore>().AsSelf(); if (useInbox) { builder.RegisterType<ConsumedMessagesCleaner>().AsSelf(); builder.RegisterPeriodicAction<ConsumedMessagesCleaner>(); } if (useOutbox) { builder.RegisterType<PeriodicEventsPublisher>().AsSelf(); builder.RegisterType<PublishedEventsCleaner>().AsSelf(); builder.RegisterPeriodicAction<PeriodicEventsPublisher>(); builder.RegisterPeriodicAction<PublishedEventsCleaner>(); } builder.RegisterInstance(new NewtonsoftJsonEventsSerializer(eventsCatalog)) .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<AsyncEventsInterceptor>() .AsSelf() .OnActivated(a => a.Instance.Configure()) .SingleInstance(); builder.RegisterType<SimpleEventsExecutor>() .AsSelf() .SingleInstance() .WithParameter("useOutbox", useOutbox); builder.RegisterType<SimpleFinalizer>().AsSelf(); builder.AddMassTransit(cfg => { cfg.AddConsumers(consumersCatalog.Assemblies); busConfig(cfg); }); builder.RegisterType<MassTransitRelayHostedService>() .AsImplementedInterfaces() .SingleInstance(); } public static void DefaultBusConfigurator(IContainerBuilderBusConfigurator busCfg) { busCfg.UsingInMemory((context, config) => { var queueName = Assembly.GetEntryAssembly()!.GetName().Name; config.ReceiveEndpoint(queueName, rcv => { rcv.UseLogsCorrelation(); rcv.UseRetry(retryConfig => retryConfig.Incremental(5, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5))); rcv.UseConsumedMessagesFiltering(context); rcv.StoreAndPublishDomainEvents(context); rcv.ConfigureConsumers(context); rcv.ConnectReceiveEndpointObservers(context); }); config.ConnectBusObservers(context); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TrophyRoomControlScript : MonoBehaviour { // References to trophies game objects to control public GameObject cup1, cup2, cup3; // Variables to contain Player Prefs values int cup1Got, cup2Got, cup3Got; // Use this for initialization void Start () { // Getting Player Prefs values to make sure you got // particular trophy cup1Got = PlayerPrefs.GetInt ("Cup1Got"); cup2Got = PlayerPrefs.GetInt ("Cup2Got"); cup3Got = PlayerPrefs.GetInt ("Cup3Got"); // If you got trophy 1 if (cup1Got == 1) // then it is shown on the shelf cup1.SetActive (true); // if you don't get it else // then it is not shown cup1.SetActive (false); // Same for trophy 2 and 3 if (cup2Got == 1) cup2.SetActive (true); else cup2.SetActive (false); if (cup3Got == 1) cup3.SetActive (true); else cup3.SetActive (false); } }
using System; using System.Threading; namespace Upgrader { internal class MutexScope : IDisposable { private readonly Mutex mutex; public MutexScope(string name) { bool created; mutex = new Mutex(true, name, out created); if (created == false) { mutex.WaitOne(); } } public void Dispose() { mutex.ReleaseMutex(); } } }
using UnityEngine; using System.Collections; public class MatarSoldado : MonoBehaviour { public ControladorAnimator controladorAnimator; void Start () { } void Update () { } void OnTriggerEnter (Collider otro) { if (otro.CompareTag ("Enemy")) { Debug.Log (otro); //deshabilitando el cubo; //otro.GetComponentInParent <Transform>().GetChild (3).gameObject.SetActive (false); //deshabilitando los ojos; otro.gameObject.SetActive (false); //obteniendo el animator; controladorAnimator = otro.gameObject.GetComponentInParent <ControladorAnimator> (); controladorAnimator.Morir (); } } }
using System.Collections.Generic; namespace Shields.Renderer { public interface IRenderer { string Render(Shield shield); IEnumerable<string> SupportedFormats { get; } } }
using System.Threading.Tasks; using Abp.Application.Services.Dto; using TakTikan.Tailor.DynamicEntityProperties.Dto; namespace TakTikan.Tailor.DynamicEntityProperties { public interface IDynamicPropertyValueAppService { Task<DynamicPropertyValueDto> Get(int id); Task<ListResultDto<DynamicPropertyValueDto>> GetAllValuesOfDynamicProperty(EntityDto input); Task Add(DynamicPropertyValueDto dto); Task Update(DynamicPropertyValueDto dto); Task Delete(int id); } }
using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace VSBookmarks { [Export(typeof(IGlyphFactoryProvider))] [Name("VSBookmarks")] [Order(After = "VsTextMarker")] [ContentType("any")] [TagType(typeof(Tag))] class GlyphFactoryProvider: IGlyphFactoryProvider { public IGlyphFactory GetGlyphFactory(IWpfTextView view, IWpfTextViewMargin margin) { return new GlyphFactory(); } } }
using System; using System.Collections.Generic; namespace Xamarin.Services.Connectivity { public class ConnectivityTypeChangedEventArgs : EventArgs { public bool IsConnected { get; set; } public IEnumerable<ConnectionType> ConnectionTypes { get; set; } } }
namespace CursoCSharpCoder.Fundamentos { public class Comentarios { [Exercicio(numero: 2, nome: "Comentarios")] /// /// <summary> /// Executa o metodo principal do exericio comentarios /// </sumary> /// public static void Executa() { // uma linha /* multiplas linhas */ } } }
using System; using System.Text.RegularExpressions; using System.IO; namespace Xamarin.Android.Tools { class SatelliteAssembly { // culture match courtesy: http://stackoverflow.com/a/3962783/83444 static readonly Regex SatelliteChecker = new Regex ( Regex.Escape (Path.DirectorySeparatorChar.ToString ()) + "(?<culture>[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*)" + Regex.Escape (Path.DirectorySeparatorChar.ToString ()) + string.Format ("(?<file>[^{0}]+.resources.dll)$", Regex.Escape (Path.DirectorySeparatorChar.ToString ()))); public static bool TryGetSatelliteCultureAndFileName (string assemblyPath, out string culture, out string fileName) { culture = fileName = null; var m = SatelliteChecker.Match (assemblyPath); if (!m.Success) return false; culture = m.Groups ["culture"].Value; fileName = m.Groups ["file"].Value; return true; } } }
using System.Windows.Controls; namespace Examples.Conventions.Implementations { public partial class RadMaskedControlsView : UserControl { public RadMaskedControlsView() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pattern9.Visitor { /// <summary> /// The 'Element' class /// </summary> public abstract class AbstractLector { protected AbstractLector() { } protected AbstractLector(string name, decimal income, int vacationDays) { this.Name = name; this.Income = income; this.VacationDays = vacationDays; this.WorkFromHomeDays = 0; } public string Name { get; set; } public decimal Income { get; set; } public int VacationDays { get; set; } public int WorkFromHomeDays { get; set; } public void Accept(IVisitor visitor) { visitor.Visit(this); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; namespace HAF.Splash { public class SplashManager<T> where T : SplashWindow { private ManualResetEvent wait = new ManualResetEvent(false); private Thread worker; private T window; public SplashManager(string description = "", string status = "") { // setup splash thread this.worker = new Thread(() => { // show window this.window = Activator.CreateInstance<T>(); this.window.Description = description; this.window.Status = status; this.window.Show(); // indicate that window is open this.wait.Set(); // start dispatcher Dispatcher.Run(); }); this.worker.SetApartmentState(ApartmentState.STA); this.worker.IsBackground = true; #if DEBUG // disable splash in designe time if (ObservableObject.IsInDesignModeStatic) { return; } #endif this.worker.Start(); } public void SetStatus(string status) { this.wait.WaitOne(); this.window.Dispatcher.Invoke(() => this.window.Status = status); } public void SetDescription(string description) { this.wait.WaitOne(); this.window.Dispatcher.Invoke(() => this.window.Description = description); } public void SetProgress(int progress) { this.wait.WaitOne(); this.window.Dispatcher.Invoke(() => this.window.Progress = progress); } public void Close() { this.wait.WaitOne(); if(this.window.Dispatcher.CheckAccess()) { this.window.Close(); Dispatcher.ExitAllFrames(); } else { this.window.Dispatcher.Invoke(() => { this.window.Close(); Dispatcher.ExitAllFrames(); }); } this.worker.Abort(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Exercise10 { public class Program { static void Main(string[] args) { string userInput; do { Console.Write("Enter a string (press 'q' to exit): "); userInput = Console.ReadLine(); var dictionary = CountingWords(userInput); foreach (var word in dictionary.OrderBy(value => value.Key)) { Console.WriteLine("{0,-20}{1}", word.Key, word.Value); } } while (userInput != "q"); } public static SortedDictionary<string, int> CountingWords(string input) { SortedDictionary<string, int> dict = new SortedDictionary<string, int>(); string[] stringSeparators = new string[] { " ", ",", ".", ";", ":", "\n" }; string[] key = input.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (string element in key) { if (!dict.ContainsKey(element)) dict.Add(element, 1); else dict[element]++; } return dict; } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; public class OpenFileDialog : MonoBehaviour, IPointerDownHandler { public Renderer preview; public Text text; void Start() { Application.ExternalEval( @" document.addEventListener('click', function() { var fileuploader = document.getElementById('fileuploader'); if (!fileuploader) { fileuploader = document.createElement('input'); fileuploader.setAttribute('style','display:none;'); fileuploader.setAttribute('type', 'file'); fileuploader.setAttribute('id', 'fileuploader'); fileuploader.setAttribute('class', 'focused'); document.getElementsByTagName('body')[0].appendChild(fileuploader); fileuploader.onchange = function(e) { var files = e.target.files; for (var i = 0, f; f = files[i]; i++) { window.alert(URL.createObjectURL(f)); SendMessage('" + gameObject.name +@"', 'FileDialogResult', URL.createObjectURL(f)); } }; } if (fileuploader.getAttribute('class') == 'focused') { fileuploader.setAttribute('class', ''); fileuploader.click(); } }); "); } public void OnPointerDown(PointerEventData eventData) { Application.ExternalEval( @" var fileuploader = document.getElementById('fileuploader'); if (fileuploader) { fileuploader.setAttribute('class', 'focused'); } "); } public void FileDialogResult(string fileUrl) { Debug.Log(fileUrl); text.text = fileUrl; StartCoroutine(PreviewCoroutine(fileUrl)); } IEnumerator PreviewCoroutine(string url) { var www = new WWW(url); yield return www; preview.material.mainTexture = www.texture; } }
using System; namespace DotNetVault.Vaults { internal interface IBox<T> : IDisposable { bool IsDisposed { get; } ref T Value { get; } ref readonly T RoValue { get; } } }
using AutoMapper; namespace Lunchorder.Api.Configuration.Mapper { public class AddressMap : Profile { public AddressMap() { CreateMap<Domain.Entities.DocumentDb.Address, Domain.Dtos.Address>(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Mendz.Library.Conventions; using System; namespace UnitTest.Mendz.Library { [TestClass] public class UnitTestDateTimeStampedFileName { [TestMethod] public void TestDateTimeStampedFileName() { DateTimeStampedFileName dtsf; dtsf = new DateTimeStampedFileName("FileName.ext", new DateTime(2020, 1, 1, 1, 15, 30)); Assert.AreEqual(false, dtsf.StampAsExtension); Assert.AreEqual("20200101", dtsf.DateStamp); Assert.AreEqual("011530", dtsf.TimeStamp); Assert.AreEqual("FileName_20200101_011530.ext", dtsf.ToString()); dtsf = new DateTimeStampedFileName("FileName.ext", new DateTime(2020, 1, 1, 1, 15, 30), '_', true); Assert.AreEqual(true, dtsf.StampAsExtension); Assert.AreEqual("20200101", dtsf.DateStamp); Assert.AreEqual("011530", dtsf.TimeStamp); Assert.AreEqual("FileName.ext.20200101_011530", dtsf.ToString()); } [TestMethod] public void TestDateTimeStampedFileNameParse() { DateTimeStampedFileName dtsf; dtsf = DateTimeStampedFileName.Parse("FileName_20200101_011530.ext"); Assert.AreEqual(false, dtsf.StampAsExtension); Assert.AreEqual("FileName.ext", dtsf.FileName); Assert.AreEqual("20200101", dtsf.DateStamp); Assert.AreEqual("011530", dtsf.TimeStamp); dtsf = DateTimeStampedFileName.Parse("FileName.ext.20200101_011530"); Assert.AreEqual(true, dtsf.StampAsExtension); Assert.AreEqual("FileName.ext", dtsf.FileName); Assert.AreEqual("20200101", dtsf.DateStamp); Assert.AreEqual("011530", dtsf.TimeStamp); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ShaftView : MonoBehaviour { [SerializeField] private TextMesh _lvl; [SerializeField] private TextMesh _nextCosts; [SerializeField] private TextMesh _earnedCash; [SerializeField] private SpriteRenderer _managerSprite; [SerializeField] private GameObject _lvlBox; [SerializeField] private GameObject _lock; [SerializeField] private GameObject _manager; public void SetManagerSprite(Sprite managerSprite) { _managerSprite.sprite = managerSprite; } public void SetLvl(double value) { _lvl.text = value.ToString(); } public void SetNextCosts(double value) { _nextCosts.text = value.ToString(); } public void ShowEarnedCash(double value) { _earnedCash.text = value.ToString(); TextMesh show = Instantiate(_earnedCash, this.transform); Destroy(show.gameObject, 3.0f); } public void Unlock() { _lvlBox.SetActive(true); _manager.SetActive(true); _lock.SetActive(false); } }
namespace jiraflow.Workflowy { public class WorkflowyDataResponse { public ProjectTreeData ProjectTreeData { get; set; } public dynamic User { get; set; } public dynamic Global { get; set; } public dynamic Settings { get; set; } public dynamic Features { get; set; } } }
using System; namespace _15_Neighbour_Wars { class Program { static void Main(string[] args) { string pesho = "Pesho"; string gosho = "Gosho"; string peshoAttack = "Roundhouse kick"; string goshoAttack = "Thunderous fist"; int peshoDamage = int.Parse(Console.ReadLine()); int goshoDamage = int.Parse(Console.ReadLine()); int peshoHealth = 100; int goshoHealth = 100; int round = 1; while (peshoHealth > 0 && goshoHealth > 0) { if (round % 2 != 0) { goshoHealth -= peshoDamage; if (goshoHealth > 0) { Console.WriteLine($"{pesho} used {peshoAttack} and reduced {gosho} to {goshoHealth} health."); } } else { peshoHealth -= goshoDamage; if (peshoHealth > 0) { Console.WriteLine($"{gosho} used {goshoAttack} and reduced {pesho} to {peshoHealth} health."); } } if (round % 3 == 0 && peshoHealth > 0 && goshoHealth > 0) { goshoHealth += 10; peshoHealth += 10; } round++; } if (peshoHealth <= 0) { Console.WriteLine($"{gosho} won in {round - 1}th round."); } else if (goshoHealth <= 0) { Console.WriteLine($"{pesho} won in {round - 1}th round."); } } } }
// Copyright (c) 2017 Trevor Redfern // // This software is released under the MIT License. // https://opensource.org/licenses/MIT namespace SilverNeedle.Treasure { using SilverNeedle.Serialization; using SilverNeedle.Lexicon; [ObjectStoreSerializable] public class Gem : ILexiconGatewayObject { [ObjectStore("name")] public string Name { get; set; } public bool Matches(string name) { return Name.EqualsIgnoreCase(name); } } }
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace Dota2SentinelHost.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Accounts", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), AccountId = table.Column<string>(maxLength: 20, nullable: true), NewUser = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Accounts", x => x.Id); }); migrationBuilder.CreateTable( name: "OngoingMatches", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), CustomMapName = table.Column<string>(maxLength: 30, nullable: true), LastCheck = table.Column<DateTime>(nullable: false), LobbyId = table.Column<string>(maxLength: 20, nullable: true), RequestedBy = table.Column<string>(maxLength: 20, nullable: true), Started = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_OngoingMatches", x => x.Id); }); migrationBuilder.CreateTable( name: "AccountNames", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), AccountId = table.Column<int>(nullable: true), Name = table.Column<string>(maxLength: 200, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AccountNames", x => x.Id); table.ForeignKey( name: "FK_AccountNames_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Matches", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), Closed = table.Column<DateTime>(nullable: false), CustomMapName = table.Column<string>(maxLength: 30, nullable: true), MatchId = table.Column<string>(maxLength: 20, nullable: true), Registered = table.Column<DateTime>(nullable: false), RequestedById = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Matches", x => x.Id); table.ForeignKey( name: "FK_Matches_Accounts_RequestedById", column: x => x.RequestedById, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Players", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), AccountId = table.Column<string>(maxLength: 20, nullable: true), MatchId = table.Column<int>(nullable: true), Name = table.Column<string>(maxLength: 200, nullable: true) }, constraints: table => { table.PrimaryKey("PK_Players", x => x.Id); table.ForeignKey( name: "FK_Players_OngoingMatches_MatchId", column: x => x.MatchId, principalTable: "OngoingMatches", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "AccountMatches", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), AccountId = table.Column<int>(nullable: false), MatchId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AccountMatches", x => x.Id); table.ForeignKey( name: "FK_AccountMatches_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AccountMatches_Matches_MatchId", column: x => x.MatchId, principalTable: "Matches", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Bans", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), AccountId = table.Column<int>(nullable: true), Duration = table.Column<int>(nullable: false), Expires = table.Column<DateTime>(nullable: false), MatchId = table.Column<int>(nullable: true), Reason = table.Column<string>(nullable: true), Set = table.Column<DateTime>(nullable: false), Severity = table.Column<float>(nullable: false), Type = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Bans", x => x.Id); table.ForeignKey( name: "FK_Bans_Accounts_AccountId", column: x => x.AccountId, principalTable: "Accounts", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Bans_Matches_MatchId", column: x => x.MatchId, principalTable: "Matches", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PlayerMatches", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn), MatchId = table.Column<string>(maxLength: 20, nullable: true), PlayerId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_PlayerMatches", x => x.Id); table.ForeignKey( name: "FK_PlayerMatches_Players_PlayerId", column: x => x.PlayerId, principalTable: "Players", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_AccountMatches_AccountId", table: "AccountMatches", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_AccountMatches_MatchId", table: "AccountMatches", column: "MatchId"); migrationBuilder.CreateIndex( name: "IX_AccountNames_AccountId", table: "AccountNames", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Bans_AccountId", table: "Bans", column: "AccountId"); migrationBuilder.CreateIndex( name: "IX_Bans_MatchId", table: "Bans", column: "MatchId"); migrationBuilder.CreateIndex( name: "IX_Matches_RequestedById", table: "Matches", column: "RequestedById"); migrationBuilder.CreateIndex( name: "IX_Players_MatchId", table: "Players", column: "MatchId"); migrationBuilder.CreateIndex( name: "IX_PlayerMatches_PlayerId", table: "PlayerMatches", column: "PlayerId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AccountMatches"); migrationBuilder.DropTable( name: "AccountNames"); migrationBuilder.DropTable( name: "Bans"); migrationBuilder.DropTable( name: "PlayerMatches"); migrationBuilder.DropTable( name: "Matches"); migrationBuilder.DropTable( name: "Players"); migrationBuilder.DropTable( name: "Accounts"); migrationBuilder.DropTable( name: "OngoingMatches"); } } }
using System.Diagnostics; using System.Windows.Controls; using System.Windows.Navigation; using MsSqlToolBelt.ViewModel; namespace MsSqlToolBelt.View { /// <summary> /// Interaction logic for InfoControl.xaml /// </summary> public partial class InfoControl : UserControl { /// <summary> /// Creates a new instance of the <see cref="InfoControl"/> /// </summary> public InfoControl() { InitializeComponent(); } /// <summary> /// Init the control /// </summary> public void InitControl() { if (DataContext is InfoControlViewModel viewModel) viewModel.InitViewModel(); } /// <summary> /// Occurs when the user hits the link /// </summary> private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e) { Process.Start(e.Uri.ToString()); } } }
namespace ScriptService.Dto.Workflows { /// <summary> /// arguments used to create a new workflow /// </summary> public class WorkflowStructure : WorkflowData { /// <summary> /// nodes to create /// </summary> public NodeData[] Nodes { get; set; } /// <summary> /// transitions to create /// </summary> public IndexTransition[] Transitions { get; set; } } }
using DIGNDB.App.SmitteStop.Domain.Db; using DIGNDB.App.SmitteStop.Domain.Dto; namespace DIGNDB.App.SmitteStop.Core.Contracts { public interface IRiskCalculator { RiskLevel CalculateRiskLevel(TemporaryExposureKey exposureKey); } }
using System.CommandLine; namespace EventGrid.Publisher.ConsoleApp.Commands { internal class SendRootCommand : Command { internal SendRootCommand() : base("send", "Send events to the event grid.") { this.AddCommand(new SendFileCommand("Send messages, based on a file, to the event grid.")); this.AddCommand(new SendFolderCommand("Send all messages from a folder to the event grid.")); } } }
using System; using Nancy; using Nancy.LightningCache.Extensions; namespace Asp.Net.Example { public class ExampleModule : NancyModule { public ExampleModule() { Get["/"] = _ => { /*cache view*/ return View["hello.html"].AsCacheable(DateTime.Now.AddSeconds(30)); }; Get["/CachedResponse"] = _ => { /*cache response*/ return Response.AsText("hello").AsCacheable(DateTime.Now.AddSeconds(30)); }; } } }
namespace NServiceBus.Unicast.Transport.ServiceBroker { internal static class Constants { public const string NServiceBusTransportMessageContract = "NServiceBusTransportMessageContract"; public const string NServiceBusTransportMessage = "NServiceBusTransportMessage"; } }
using GovUkDesignSystem.Attributes; namespace GenderPayGap.WebUI.Models.AddOrganisation { public enum AddOrganisationSector { // "Public, then Private" is the order we want on the page /add-employer/choose-employer-type [GovUkRadioCheckboxLabelText(Text = "Public authority employer")] Public, [GovUkRadioCheckboxLabelText(Text = "Private or voluntary sector employer")] Private } }
namespace Hermes.API.Constants { public class HermesConstants { public class AuthorizationPolicy { public const string ApiScope = "ApiScope"; } } }
using System; using NUnit.Framework; using Wikiled.Arff.Logic; namespace Wikiled.Arff.Tests.Logic { [TestFixture] public class SparseInformationLineTests { [Test] public void Add() { SparseInformationLine line = new SparseInformationLine(); line.Add(null); line.Add("1"); line.Add("1"); Assert.AreEqual(3, line.Index); Assert.AreEqual("{1 1,2 1}", line.GenerateLine()); } [Test] public void MoveIndex() { SparseInformationLine line = new SparseInformationLine(); line.Add(null); Assert.AreEqual(1, line.Index); line.MoveIndex(10); Assert.AreEqual(10, line.Index); line.MoveIndex(1); Assert.AreEqual(10, line.Index); } [Test] public void AddIndex() { SparseInformationLine line = new SparseInformationLine(); line.Add(3, "1"); Assert.AreEqual(3, line.Index); Assert.AreEqual("{3 1}", line.GenerateLine()); } [Test] public void AddIndexOutOfRance() { SparseInformationLine line = new SparseInformationLine(); Assert.Throws<ArgumentOutOfRangeException>(() => line.Add(-1, "1")); } [Test] public void AddIndexExisting() { SparseInformationLine line = new SparseInformationLine(); line.Add(3, "1"); Assert.Throws<ArgumentOutOfRangeException>(() => line.Add(3, "1")); } } }
using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Rendering; namespace Grubo { [RequireComponent(typeof(Volume))] public sealed class VolumeWeightRandomizer : MonoBehaviour { [SerializeField] Key _randomizeKey = Key.None; [SerializeField] Key _resetKey = Key.None; Volume _volume; public void Randomize() { if (!enabled || !gameObject.activeInHierarchy) return; _volume.weight = Random.value; } public void SetWeight(float weight) { if (!enabled || !gameObject.activeInHierarchy) return; _volume.weight = weight; } void Start() { _volume = GetComponent<Volume>(); } void Update() { if (_randomizeKey != Key.None && Keyboard.current[_randomizeKey].wasPressedThisFrame) Randomize(); if (_resetKey != Key.None && Keyboard.current[_resetKey].wasPressedThisFrame) SetWeight(0); } } }
using FusionEngine.Data; namespace FusionEngine.Visuals { public class RenderLayer { public RenderLayer ( ) { Init ( ); } public virtual void Init ( ) { } public virtual void Bind ( Mesh3D m, Visualizer v ) { } public virtual void Render ( Mesh3D m, Visualizer v ) { } public virtual void Release ( Mesh3D m, Visualizer v ) { } } }
public static class BugReport { public const string BUG_REPORT_URL = "https://github.com/ConstellationLanguage/Constellation/issues"; }
// MIT License - Copyright (c) Callum McGing // This file is subject to the terms and conditions defined in // LICENSE, which is part of this source code package using System; using System.Numerics; using System.Collections.Generic; using System.Linq; using LibreLancer.Thorn; namespace LibreLancer { public enum PCurveType { Unknown, FreeForm, BumpIn, BumpOut, RampDown, RampUp, Step, Smooth, ThornL, //? Linear, CatmullRom } public class ParameterCurve { public string CLSID; public PCurveType Type = PCurveType.Unknown; public List<Vector4> Points; public float Period; public ParameterCurve() { } public ParameterCurve(PCurveType type, IEnumerable<Vector4> points) { Type = type; Points = points.ToList(); Period = -1; } public ParameterCurve(LuaTable table) { CLSID = (string)table["CLSID"]; switch (CLSID.ToLowerInvariant()) { case "freeformpcurve": Type = PCurveType.FreeForm; break; case "bumpinpcurve": Type = PCurveType.BumpIn; break; case "bumpoutpcurve": Type = PCurveType.BumpOut; break; case "rampdownpcurve": Type = PCurveType.RampDown; break; case "rampuppcurve": Type = PCurveType.RampUp; break; case "steppcurve": Type = PCurveType.Step; break; case "smoothpcurve": Type = PCurveType.Smooth; break; case "thornlpcurve": Type = PCurveType.ThornL; break; case "linearpcurve": Type = PCurveType.Linear; break; case "catmullrompcurve": Type = PCurveType.CatmullRom; break; } var points = (LuaTable)table["points"]; Points = new List<Vector4>(); for (int i = 0; i < points.Capacity; i++) { var p = (LuaTable)points[i]; var v = new Vector4((float)p[0], (float)p[1], (float)p[2], (float)p[3]); Points.Add(v); } } static float EvaluateFreeform(Vector4 pa, Vector4 pb, float time) { var period = (pb.X - pa.X); var aval = pa.Y; var bval = pb.Y; var bcontrol1 = pb.Z; var acontrol2 = pa.W; var x = (time - pa.X) / period; var x2 = x * x; var x3 = x2 * x; var _3x2 = 3 * x2; var _2x3 = 2 * x3; var _2x2 = 2 * x2; return (_3x2 - _2x3) * bval + (_2x3 - _3x2 + 1) * aval + (x3 - x2) * bcontrol1 * period + (x3 - _2x2 + x) * acontrol2 * period; } public float GetValue(float time, float duration) { float x = 0; var p = Period / 1000f; if (p < 0) x = time / duration; else x = (time % p) / p; Vector4 a = Vector4.Zero; Vector4 b = new Vector4(1,1,0,0); if (Points.Count >= 2) { if (x <= 0) return Points[0].Y; if (x >= 1) return Points[Points.Count - 1].Y; //X - time, Y - value, Z - in, W - out for (int i = 0; i < Points.Count - 1; i++) { if (x >= Points[i].X && x <= Points[i + 1].X) { a = Points[i]; b = Points[i + 1]; } } } switch (Type) { case PCurveType.FreeForm: return EvaluateFreeform(a, b, x); case PCurveType.Step: return a.Y; case PCurveType.BumpIn: case PCurveType.RampUp: return Utf.Ale.AlchemyEasing.Ease(Utf.Ale.EasingTypes.EaseIn, x, a.X, b.X, a.Y, b.Y); case PCurveType.BumpOut: case PCurveType.RampDown: return Utf.Ale.AlchemyEasing.Ease(Utf.Ale.EasingTypes.EaseOut, x, a.X, b.X, a.Y, b.Y); case PCurveType.Smooth: return Utf.Ale.AlchemyEasing.Ease(Utf.Ale.EasingTypes.EaseInOut, x, a.X, b.Y, a.Y, b.Y); default: return Utf.Ale.AlchemyEasing.Ease(Utf.Ale.EasingTypes.Linear, x, a.X, b.X, a.Y, b.Y); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameMaster : MonoBehaviour { [SerializeField] private bool gameOn; [SerializeField] private SpawnManager spawnManager; //[SerializeField] private UIController uiController; // Start is called before the first frame update void Start() { spawnManager = GameObject.Find("SpawnManager").GetComponent<SpawnManager>(); uiController = GameObject.Find("Canvas").GetComponent<UIController>(); if (spawnManager != null) { spawnManager.StartSpawn(); } } // Update is called once per frame void Update() { CheckIfGameWon(); } public bool IsGameOn() { return gameOn; } public void CheckIfGameWon() { if (uiController.timeLeft == 0) { uiController.GameOver(); } if (Mathf.RoundToInt(uiController.curHealth) == 0) { uiController.GameOver(); } if (Mathf.RoundToInt(uiController.curAcorn) == 0) { Debug.Log("checkgamewin" + uiController.curAcorn); uiController.GameWin(); } } public void EndsCurrentGame() { //if (uiController.timeLeft == 0) //{ gameOn = false; // } } }
using UnityEngine; using System.Collections; public class CubeSpeed : Cube { public override void AwakeChild() { // SET CUBE EFFECT IN YOUR AWAKE FUNCTION effect = Cube.CubeEffect_e.SPEED; } public override void setActiveChild(bool active_) { if (active_) { tag = "speed"; } else { tag = "Untagged"; } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | 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; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using ESRI.ArcLogistics.Data; namespace ESRI.ArcLogistics.App.Import { /// <summary> /// Implements <see cref="T:ESRI.ArcLogistics.App.Import.IDataObjectContainer`1[T]"/> /// </summary> /// <typeparam name="T"></typeparam> internal sealed class DataObjectContainer<T> : IDataObjectContainer<T> where T : DataObject { #region constructor /// <summary> /// Initializes a new instance of the DataObjectContainer class. /// </summary> /// <param name="source">The reference to the source collection of data objects.</param> public DataObjectContainer(IEnumerable<T> source) { Debug.Assert(source != null); Debug.Assert(source.All(item => item != null)); _data = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase); foreach (var item in source) { var key = _GetObjectName(item); if (_data.ContainsKey(key)) { continue; } _data.Add(key, item); } _newObjects = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase); } #endregion #region IDataObjectContainer<T> Members /// <summary> /// Checks if the data object with the specified name exists in the collection. /// </summary> /// <param name="objectName">The name of the object to check existence for.</param> /// <returns>True if and only if the object with the specified name exists in /// the collection.</returns> public bool Contains(string objectName) { Debug.Assert(objectName != null); return _data.ContainsKey(objectName); } /// <summary> /// Gets data object with the specified name. /// </summary> /// <param name="objectName">The name of the data object to be retrieved.</param> /// <param name="value">Contains reference to the data object with the specified /// name or null if no such object was found.</param> /// <returns>True if and only if the object with the specified name exists in /// the collection.</returns> public bool TryGetValue(string objectName, out T value) { Debug.Assert(objectName != null); return _data.TryGetValue(objectName, out value); } /// <summary> /// Gets reference to the collection of added data objects. /// </summary> /// <returns>A reference to the collection of added data objects.</returns> public IEnumerable<T> GetAddedObjects() { return _newObjects.Values; } #endregion #region ICollection<T> Members /// <summary> /// Gets number of data objects in the collection. /// </summary> public int Count { get { return _data.Count; } } /// <summary> /// Gets a value indicating if the collection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Adds the specified item to the collection. /// </summary> /// <param name="item">The reference to the data object to be added.</param> public void Add(T item) { var key = _GetObjectName(item); if (key == null) { return; } if (_data.ContainsKey(key)) { return; } _data.Add(key, item); _newObjects.Add(key, item); } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { _data.Clear(); _newObjects.Clear(); } /// <summary> /// Checks if the specified item exists in the collection. /// </summary> /// <param name="item">The item to check existence for.</param> /// <returns>True if and only if the specified item exists in the collection.</returns> public bool Contains(T item) { var key = _GetObjectName(item); if (key == null) { return false; } return this.Contains(key); } /// <summary> /// Copies collection elements to the specified array, starting at the specified index. /// </summary> /// <param name="array">The reference to an array to copy values to.</param> /// <param name="arrayIndex">A zero-based index in the <paramref name="array"/> to begin /// copying at.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="array"/> is a null /// reference.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is /// less than zero.</exception> /// <exception cref="T:System.ArgumentException">The number of elements in the collection /// is greater than the available space starting from <paramref name="arrayIndex"/> /// to the end of the destination <paramref name="array"/>.</exception> public void CopyTo(T[] array, int arrayIndex) { // Cast _data.Value to ICollection and rely on it to check method arguments. // We cannot use _data.Value.CopyTo since it has different parameter names. var collection = (ICollection<T>)_data.Values; collection.CopyTo(array, arrayIndex); } /// <summary> /// Removes the specified item from the collection. /// </summary> /// <param name="item">The reference to an item to be removed.</param> /// <returns>True if and only if the item existed in the collection before removal.</returns> public bool Remove(T item) { var key = _GetObjectName(item); if (key == null) { return false; } _newObjects.Remove(key); return _data.Remove(key); } #endregion #region IEnumerable<T> Members /// <summary> /// Gets enumerator to iterate over collection elements. /// </summary> /// <returns>A reference to the enumerator for iterating over collection elements.</returns> public IEnumerator<T> GetEnumerator() { return _data.Values.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Gets enumerator to iterate over collection elements. /// </summary> /// <returns>A reference to the enumerator for iterating over collection elements.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region private static methods /// <summary> /// Gets object name for the specified data object. /// </summary> /// <param name="dataObject">The reference to the data object to get name for.</param> /// <returns>A name of the specified data object or null if <paramref name="dataObject"/> /// is a null reference.</returns> private static string _GetObjectName(T dataObject) { if (object.ReferenceEquals(dataObject, null)) { return null; } return dataObject.ToString(); } #endregion #region private fields /// <summary> /// Stores all data objects. /// </summary> private Dictionary<string, T> _data; /// <summary> /// Stores new data objects. /// </summary> private Dictionary<string, T> _newObjects; #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using GameKit; namespace GameKit { public class AudioManager : SingletonBase<AudioManager> { private AudioSource globalMusicSource = null; public float musicVolume = 1; public float soundVolume = 1; private GameObject GlobalAudio = null; private List<AudioSource> soundList = new List<AudioSource>(); public AudioManager() { MonoManager.instance.AddUpdateListener(Update); } private void Update() { for (int i = soundList.Count - 1; i >= 0; --i) { if (!soundList[i].isPlaying) { this.StopSound(soundList[i]); } } } public void PlayMusic(string name) { if (globalMusicSource != null) { globalMusicSource.Play(); } else { GameObject obj = new GameObject(); obj.name = "GlobalMusic"; globalMusicSource = obj.AddComponent<AudioSource>(); ResourceManager.instance.LoadAsync<AudioClip>("Audio/GlobalMusicSource/" + name, (clip) => { globalMusicSource.clip = clip; globalMusicSource.loop = true; globalMusicSource.volume = musicVolume; globalMusicSource.Play(); }); } } public void PlaySound(string name, UnityAction<AudioSource> callback) { if (globalMusicSource != null) { globalMusicSource.Play(); } else { GlobalAudio = new GameObject(); GlobalAudio.name = "Sound"; ResourceManager.instance.LoadAsync<AudioClip>("Audio/Sound/" + name, (clip) => { AudioSource source = GlobalAudio.AddComponent<AudioSource>(); source.clip = clip; source.volume = soundVolume; source.Play(); soundList.Add(source); if (callback != null) callback(source); }); } } public void ChangeMusicVolume(float v) { musicVolume = v; if (globalMusicSource == null) return; globalMusicSource.volume = musicVolume; } public void ChangeSoundVolume(float v) { soundVolume = v; for (int i = 0; i < soundList.Count; ++i) soundList[i].volume = v; } public void ChangeMasterVolume(float v) { ChangeSoundVolume(v); ChangeMusicVolume(v); } public void PauseGlobalMusic() { if (globalMusicSource == null) return; globalMusicSource.Pause(); } public void StopGlobalMusic() { if (globalMusicSource == null) return; globalMusicSource.Stop(); } public void StopSound(AudioSource source) { if (soundList.Contains(source)) { soundList.Remove(source); source.Stop(); GameObject.Destroy(source); } } public void RegisterSound(AudioSource source) { if (!soundList.Contains(source)) soundList.Add(source); } public void RegisterMusic(AudioSource source) { if (globalMusicSource != null && !globalMusicSource.isPlaying) globalMusicSource = source; } public List<AudioSource> GetSoundList() { return soundList; } } }
using Alkahest.Core.Collections; using Alkahest.Core.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.ServiceModel.Channels; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace Alkahest.Core.Net { sealed class ServerListRequestHandler : DelegatingHandler { const string RemoteEndPointPropertyName = "System.ServiceModel.Channels.RemoteEndpointMessageProperty"; static readonly Log _log = new Log(typeof(ServerListRequestHandler)); readonly ServerListParameters _parameters; readonly string _servers; public ServerListRequestHandler(ServerListParameters parameters, out IReadOnlyList<ServerInfo> servers) { _parameters = parameters; _servers = GetAndAdjustServers(out servers); } string GetAndAdjustServers(out IReadOnlyList<ServerInfo> servers) { _log.Basic("Fetching official server list..."); HttpResponseMessage resp; using var client = new HttpClient { Timeout = _parameters.Timeout, }; var retriesSoFar = 0; while (true) { var uri = _parameters.Uri; using var req = new HttpRequestMessage(HttpMethod.Get, GetUri(uri.Scheme, uri.AbsolutePath, true)); req.Headers.Host = _parameters.Uri.Authority; try { resp = client.SendAsync(req).Result.EnsureSuccessStatusCode(); } catch (Exception e) when (IsHttpException(e) && retriesSoFar < _parameters.Retries) { _log.Error("Could not fetch official server list; retrying..."); retriesSoFar++; continue; } break; } var doc = XDocument.Parse(resp.Content.ReadAsStringAsync().Result); var servs = new List<ServerInfo>(); foreach (var elem in doc.Root.Descendants("server")) { var nameElem = elem.Element("name"); var rawNameAttr = nameElem.Attribute("raw_name"); var ipElem = elem.Element("ip"); var portElem = elem.Element("port"); var id = int.Parse(elem.Element("id").Value); var name = rawNameAttr.Value; var ip = IPAddress.Parse(ipElem.Value); var port = int.Parse(portElem.Value); var newPort = _parameters.GamePort; // Match tera-proxy's IP allocation scheme. This obviously won't // work for IPv6... var ipBytes = _parameters.GameBaseAddress.GetAddressBytes(); ipBytes[3] += (byte)servs.Count; var newIP = new IPAddress(ipBytes); nameElem.Value += " (Alkahest)"; rawNameAttr.Value += " (Alkahest)"; ipElem.Value = newIP.ToString(); portElem.Value = newPort.ToString(); servs.Add(new ServerInfo(id, name, new IPEndPoint(ip, port), new IPEndPoint(newIP, newPort))); _log.Info("Redirecting {0}: {1}:{2} -> {3}:{4}", name, ip, port, newIP, newPort); } servers = servs.OrderBy(x => x.Id).ToArray(); _log.Basic("Redirecting {0} game servers", servs.Count); return doc.ToString(); } static bool IsHttpException(Exception exception) { return exception is AggregateException || exception is HttpRequestException; } Uri GetUri(string scheme, string path, bool usn) { var uri = $"{scheme}://{_parameters.RealServerListAddress}:{_parameters.Uri.Port}{path}"; if (usn && _parameters.Region == Region.JP) uri += "?usn=0"; return new Uri(uri); } protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { var p = (RemoteEndpointMessageProperty)request.Properties[RemoteEndPointPropertyName]; var from = $"{p.Address}:{p.Port}"; var uri = request.RequestUri; var path = uri.PathAndQuery; _log.Debug("Received HTTP request at {0} from {1}", path, from); return base.SendAsync(request, cancellationToken).ContinueWith(t => { HttpResponseMessage resp; var handler = new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false, }; var client = new HttpClient(handler) { Timeout = _parameters.Timeout, }; var retriesSoFar = 0; while (true) { // We need to make a new request object or we'll get an // exception when attempting to send it below. var req = new HttpRequestMessage(request.Method, GetUri(uri.Scheme, path, false)) { Version = request.Version, }; req.Headers.Clear(); foreach (var (name, values) in request.Headers.Tuples()) req.Headers.Add(name, values); req.Headers.Host = _parameters.Uri.Authority; var content = request.Content.ReadAsByteArrayAsync().Result; if (content.Length != 0) req.Content = new ByteArrayContent(content); try { resp = client.SendAsync(req).Result; } catch (AggregateException) { if (retriesSoFar < _parameters.Retries) { _log.Error("Could not forward HTTP request at {0} from {1}; retrying...", path, from); retriesSoFar++; continue; } _log.Error("Gave up forwarding HTTP request at {0} from {1} after {2} retries", path, from, _parameters.Retries); // The official server seems dead. return new HttpResponseMessage(HttpStatusCode.GatewayTimeout); } break; } resp.Headers.TransferEncodingChunked = null; // Don't include the query string as TERA JP actually uses it. if (uri.AbsolutePath == _parameters.Uri.AbsolutePath) resp.Content = new StringContent(_servers); _log.Debug("Forwarded HTTP request at {0} from {1}: {2}", path, from, (int)resp.StatusCode); return resp; }); } } }
namespace EnvironmentAssessment.Common.VimApi { public class GatewayHostNotReachable : GatewayToHostConnectFault { } }
using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Function; using System; using Microsoft.AspNetCore.Http; public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.Run(async (context) => { if (context.Request.Path != "/") { context.Response.StatusCode = 404; await context.Response.WriteAsync("404 - Not Found"); return; } if (context.Request.Method != "POST") { context.Response.StatusCode = 405; await context.Response.WriteAsync("405 - Only POST method allowed"); return; } try { var (status, text) = await new FunctionHandler().Handle(context.Request); context.Response.StatusCode = status; if (!string.IsNullOrEmpty(text)) await context.Response.WriteAsync(text); } catch (NotImplementedException nie) { context.Response.StatusCode = 501; await context.Response.WriteAsync(nie.ToString()); } catch (Exception ex) { context.Response.StatusCode = 500; await context.Response.WriteAsync(ex.ToString()); } }); } }
using DragonSpark.Sources; using DragonSpark.Sources.Parameterized; using System.Reflection; namespace DragonSpark.ComponentModel { public sealed class TypeDefinitions : ParameterizedScope<TypeInfo, TypeInfo> { public static IParameterizedSource<TypeInfo, TypeInfo> Default { get; } = new TypeDefinitions(); TypeDefinitions() : base( Factory.GlobalCache<TypeInfo, TypeInfo>( Create ) ) {} static TypeInfo Create( TypeInfo parameter ) { foreach ( var provider in TypeSystem.Configuration.TypeDefinitionProviders.Get() ) { var info = provider.Get( parameter ); if ( info != null ) { return info; } } return null; } } }
interface Document : Node, GlobalEventHandlers, NodeSelector, DocumentEvent, ParentNode, DocumentOrShadowRoot { /** * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. */ [Export("write")] void write(params string[] content); /** * Writes one or more HTML expressions, followed by a carriage return, to a document in the specified window. * @param content The text and HTML tags to write. */ [Export("writeln")] void writeln(params string[] content); }
using System; namespace DepthCharge { /// <summary> /// Contains methods for displaying information to the user. /// </summary> static class View { public static void ShowBanner() { Console.WriteLine(" DEPTH CHARGE"); Console.WriteLine(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); } public static void ShowInstructions(int maximumGuesses) { Console.WriteLine("YOU ARE THE CAPTAIN OF THE DESTROYER USS COMPUTER"); Console.WriteLine("AN ENEMY SUB HAS BEEN CAUSING YOU TROUBLE. YOUR"); Console.WriteLine($"MISSION IS TO DESTROY IT. YOU HAVE {maximumGuesses} SHOTS."); Console.WriteLine("SPECIFY DEPTH CHARGE EXPLOSION POINT WITH A"); Console.WriteLine("TRIO OF NUMBERS -- THE FIRST TWO ARE THE"); Console.WriteLine("SURFACE COORDINATES; THE THIRD IS THE DEPTH."); Console.WriteLine(); } public static void ShowStartGame() { Console.WriteLine("GOOD LUCK !"); Console.WriteLine(); } public static void ShowGuessPlacement((int x, int y, int depth) actual, (int x, int y, int depth) guess) { Console.Write("SONAR REPORTS SHOT WAS "); if (guess.y > actual.y) Console.Write("NORTH"); if (guess.y < actual.y) Console.Write("SOUTH"); if (guess.x > actual.x) Console.Write("EAST"); if (guess.x < actual.x) Console.Write("WEST"); if (guess.y != actual.y || guess.x != actual.y) Console.Write(" AND"); if (guess.depth > actual.depth) Console.Write (" TOO LOW."); if (guess.depth < actual.depth) Console.Write(" TOO HIGH."); if (guess.depth == actual.depth) Console.Write(" DEPTH OK."); Console.WriteLine(); } public static void ShowGameResult((int x, int y, int depth) submarineLocation, (int x, int y, int depth) finalGuess, int trailNumber) { Console.WriteLine(); if (submarineLocation == finalGuess) { Console.WriteLine($"B O O M ! ! YOU FOUND IT IN {trailNumber} TRIES!"); } else { Console.WriteLine("YOU HAVE BEEN TORPEDOED! ABANDON SHIP!"); Console.WriteLine($"THE SUBMARINE WAS AT {submarineLocation.x}, {submarineLocation.y}, {submarineLocation.depth}"); } } public static void ShowFarewell() { Console.WriteLine ("OK. HOPE YOU ENJOYED YOURSELF."); } public static void ShowInvalidNumber() { Console.WriteLine("PLEASE ENTER A NUMBER"); } public static void ShowInvalidDimension() { Console.WriteLine("PLEASE ENTER A VALID DIMENSION"); } public static void ShowTooFewCoordinates() { Console.WriteLine("TOO FEW COORDINATES"); } public static void ShowTooManyCoordinates() { Console.WriteLine("TOO MANY COORDINATES"); } public static void ShowInvalidYesOrNo() { Console.WriteLine("PLEASE ENTER Y OR N"); } public static void PromptDimension() { Console.Write("DIMENSION OF SEARCH AREA? "); } public static void PromptGuess(int trailNumber) { Console.WriteLine(); Console.Write($"TRIAL #{trailNumber}? "); } public static void PromptPlayAgain() { Console.WriteLine(); Console.Write("ANOTHER GAME (Y OR N)? "); } } }
using System; using System.Collections.Generic; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Operations; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Config { public class RegionConfig : IOperationConfig { public string Key => Region.OperationName; public Guid Id => new Guid("3D33B3BF-F40E-43EB-A14D-F40516F880CD"); public IEnumerable<IOperationProvider> ConfigureFromJObject(JObject rawConfiguration, IDirectory templateRoot) { string id = rawConfiguration.ToString("id"); string start = rawConfiguration.ToString("start"); string end = rawConfiguration.ToString("end"); bool include = rawConfiguration.ToBool("include"); bool regionTrim = rawConfiguration.ToBool("trim"); bool regionWholeLine = rawConfiguration.ToBool("wholeLine"); yield return new Region(start, end, include, regionWholeLine, regionTrim, id); } } }
namespace Oliviann.Common.TestObjects.Xml { #region Usings using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Xml.Serialization; #endregion Usings /// <summary> /// Represents a /// </summary> [Serializable] [XmlRoot(ElementName = "catalog")] [ExcludeFromCodeCoverage] public class Catalog { #region Constructor/Destructor /// <summary> /// Initializes a new instance of the <see cref="Catalog"/> class. /// </summary> public Catalog() { this.Books = new List<Book>(); } #endregion Constructor/Destructor #region Properties [XmlArray("books")] [XmlArrayItem(ElementName = "book")] public List<Book> Books { get; set; } #endregion Properties } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Examples.GrpcStreaming { using System; using System.Collections.Generic; using System.Threading.Tasks; using Bond; using Bond.Grpc; using Grpc.Core; public static class GrpcStreaming { const string Address = "127.0.0.1"; const int Port = 50051; public static void Main() { var server = new Server { Services = { StreamingMethods.BindService(new StreamingService()) }, Ports = { new ServerPort(Address, Port, ServerCredentials.Insecure) } }; server.Start(); var channel = new Channel(Address, Port, ChannelCredentials.Insecure); var client = new StreamingMethods.StreamingMethodsClient(channel); MakeSumRequestAsync(client).Wait(); MakeCountdownRequestAsync(client).Wait(); MakeDuplexRequestAsync(client).Wait(); Task.WaitAll(channel.ShutdownAsync(), server.ShutdownAsync()); Console.WriteLine("\nDone with all requests."); } private static async Task MakeSumRequestAsync(StreamingMethods.StreamingMethodsClient client) { Console.WriteLine("Starting Sum"); using (var clientStream = client.SumAsync()) { for (uint i = 1; i <= 5; ++i) { await clientStream.RequestStream.WriteAsync(Message.From(Box.Create(i))); } await clientStream.RequestStream.CompleteAsync(); var response = await clientStream.ResponseAsync; Box<uint> result = response.Payload.Deserialize(); if (result.value != 15) { throw new Exception($"Expected '15' but got '{result.value}'"); } Console.WriteLine($"sum: correct response {result.value}"); } Console.WriteLine("Sum done"); Console.WriteLine(); } private static async Task MakeCountdownRequestAsync(StreamingMethods.StreamingMethodsClient client) { Console.WriteLine("Starting Countdown"); using (var responseStream = client.CountdownAsync(Box.Create(7u))) { while (await responseStream.ResponseStream.MoveNext()) { uint response = responseStream.ResponseStream.Current.Payload.Deserialize().value; Console.WriteLine(response); } } Console.WriteLine("Countdown done"); Console.WriteLine(); } private static async Task MakeDuplexRequestAsync(StreamingMethods.StreamingMethodsClient client) { Console.WriteLine("Starting Reverse"); using (var stream = client.ReverseAsync()) { foreach (var s in new[] { "how", "now", "brown", "cow"}) { await stream.RequestStream.WriteAsync(Message.From(Box.Create(s))); if (await stream.ResponseStream.MoveNext()) { var resp = stream.ResponseStream.Current.Payload.Deserialize().value; Console.WriteLine($"For '{s}' got '{resp}'"); } } await stream.RequestStream.CompleteAsync(); while (await stream.ResponseStream.MoveNext()) { var resp = stream.ResponseStream.Current.Payload.Deserialize().value; Console.WriteLine($"Extra: '{resp}'"); } } Console.WriteLine("Reverse done"); Console.WriteLine(); } } }
namespace Coosu.Storyboard.Common { public interface IAdjustable : ITimingAdjustable, IPositionAdjustable { } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery { using System.Diagnostics; using System.Text; internal static class StringBuilderExtensions { public static StringBuilder AppendIfNotEmpty(this StringBuilder input, string value) { Debug.Assert(input != null, "input != null"); return input.Length > 0 ? input.Append(value) : input; } } }
using System; using System.ComponentModel.DataAnnotations; namespace JoaoCarlosRezendeJunior.API.Model { public class Pedido { public Pedido() { } [Key] public int IdPedido { get; set; } public string NomeMedicamento { get; set; } public int QtdeMedicamento { get; set; } public DateTime DataEntrega { get; set; } public int CodCliente { get; set; } } }
namespace Tiler { public class TiledGroup { /// <summary> /// Unique ID of the layer. /// </summary> public int Id { get; set; } /// <summary> /// The name of the group layer. /// </summary> public string Name { get; set; } /// <summary> /// Rendering offset x for this layer in pixels. /// </summary> public int OffsetX { get; set; } /// <summary> /// Rendering offset y for this layer in pixels. /// </summary> public int OffsetY { get; set; } /// <summary> /// The opacity of the layer as a value from 0 to 1. Defaults to 1. /// </summary> public float Opacity { get; set; } /// <summary> /// Whether the layer is shown (1) or hidden (0). Defaults to 1. /// </summary> public bool Visible { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VottModel { public class Asset { /* "84169554c4e1a7e4655077a1209bc0a7": { "format": "png", "id": "84169554c4e1a7e4655077a1209bc0a7", "name": "637591970475059304.png", "path": "file:C:/Users/Ian/Documents/Projects/Output/StfcBot/Tagging/637591970475059304.png", "size": { "width": 1820, "height": 859 }, "state": 2, "type": 1 } */ public string id { get; set; } = Guid.NewGuid().ToString().Replace("-", ""); public string name { get; set; } public string format { get; set; } public string path { get; set; } public States state { get; set; } = States.NotVisited; public int type { get; set; } = 1; public Size size { get; set; } } }
using System; using UnityEngine; namespace Slantar.Services { public interface IEventService { /// <summary> /// Subscribes a method from gameobject for T event /// </summary> /// <typeparam name="T"> event type</typeparam> /// <param name="subscriberObject"> gameObject to subscribe </param> /// <param name="action"> method to execute </param> void Subscribe<T>(GameObject subscriberObject, Action<T> action); /// <summary> /// Subscribes a method for T event /// </summary> /// <typeparam name="T"> event type</typeparam> /// <param name="action"> method to execute </param> void Subscribe<T>(Action<T> action); /// <summary> /// Triggers the event T with default constructor /// </summary> /// <typeparam name="T">event type</typeparam> void Trigger<T>() where T : new(); /// <summary> /// Triggers the event T /// </summary> /// <typeparam name="T">event Type</typeparam> /// <param name="eventData">event data</param> void Trigger<T>(T eventData); /// <summary> /// Subscribes an event that returns another event that it will trigger it after (Event groups) /// </summary> /// <typeparam name="T">first event type</typeparam> /// <typeparam name="Q">second event type that triggers T after</typeparam> /// <param name="suscriberObject">gameObject to subscribe</param> void Chain<T, Q>(GameObject suscriberObject) where Q : new(); /// <summary> /// Subscribes a method event that returns another event that it will trigger it after (Event groups) /// </summary> /// <typeparam name="T">first event type</typeparam> /// <typeparam name="Q">second event type that triggers T after</typeparam> /// <param name="subscriberObject">gameObject to subscribe</param> /// <param name="Converter">Function that transforms event T to event Q</param> void Chain<T, Q>(GameObject subscriberObject, Func<T, Q> Converter) where Q : new(); /// <summary> /// Subscribes a method event that returns another event that it will trigger it after (Event groups) /// </summary> /// <typeparam name="T">first event type</typeparam> /// <typeparam name="Q">second event type that triggers T after</typeparam> /// <param name="Converter"></param> void Chain<T, Q>(Func<T, Q> Converter) where Q : new(); /// <summary> /// Subscribes a method event that returns another event that it will trigger it after (Event groups) /// </summary> /// <typeparam name="T">first event type</typeparam> /// <typeparam name="Q">second event type that triggers T after</typeparam> void Chain<T, Q>() where Q : new(); /// <summary> /// Unsubscribe the event T method from subscriberObject /// </summary> /// <typeparam name="T">first event type</typeparam> /// <param name="subscriberObject">gameObject to subscribe</param> /// <param name="Converter">Function that transforms event T to event Q</param> /// <returns>returns if the event is removed succesfully</returns> bool Unsubscribe<T>(GameObject subscriberObject, Action<T> action); /// <summary> /// Unsubscribe the event T method /// </summary> /// <typeparam name="T">first event type</typeparam> /// <param name="subscriberObject">gameObject to subscribe</param> /// <param name="Converter">Function that transforms event T to event Q</param> /// <returns>returns if the event is removed succesfully</returns> bool Unsubscribe<T>(Action<T> action); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using RepoDb.Attributes; using RepoDb.Enumerations; using System.Linq; using System.Reflection; namespace RepoDb.UnitTests.Enumerations { [TestClass] public class OrderTextTest { private TextAttribute GetOrderTextAttribute(Order order) { return typeof(Order) .GetMembers() .First(member => member.Name.ToLower() == order.ToString().ToLower()) .GetCustomAttribute<TextAttribute>(); } [TestMethod] public void TestOrderAscendingText() { // Prepare var operation = Order.Ascending; // Act var parsed = GetOrderTextAttribute(operation); // Assert Assert.AreEqual("ASC", parsed.Text); } [TestMethod] public void TestOrderDescendingText() { // Prepare var operation = Order.Descending; // Act var parsed = GetOrderTextAttribute(operation); // Assert Assert.AreEqual("DESC", parsed.Text); } } }
// This file was generated by a tool; you should avoid making direct changes. // Consider using 'partial classes' to extend these types // Input: extractor_config.proto #pragma warning disable 0612, 1591, 3021 [global::ProtoBuf.ProtoContract()] public partial class IoConfig : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public IoConfig() { OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1, IsRequired = true)] public string task_name { get; set; } [global::ProtoBuf.ProtoMember(2, IsRequired = true)] public string output_path { get; set; } [global::ProtoBuf.ProtoMember(3)] [global::System.ComponentModel.DefaultValue(@"FLOAT_MIN")] public string start_timestamp { get { return __pbn__start_timestamp ?? @"FLOAT_MIN"; } set { __pbn__start_timestamp = value; } } public bool ShouldSerializestart_timestamp() { return __pbn__start_timestamp != null; } public void Resetstart_timestamp() { __pbn__start_timestamp = null; } private string __pbn__start_timestamp; [global::ProtoBuf.ProtoMember(4)] [global::System.ComponentModel.DefaultValue(@"FLOAT_MAX")] public string end_timestamp { get { return __pbn__end_timestamp ?? @"FLOAT_MAX"; } set { __pbn__end_timestamp = value; } } public bool ShouldSerializeend_timestamp() { return __pbn__end_timestamp != null; } public void Resetend_timestamp() { __pbn__end_timestamp = null; } private string __pbn__end_timestamp; } [global::ProtoBuf.ProtoContract()] public partial class ChannelConfig : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public ChannelConfig() { OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] [global::System.ComponentModel.DefaultValue("")] public string descriptor { get { return __pbn__descriptor ?? ""; } set { __pbn__descriptor = value; } } public bool ShouldSerializedescriptor() { return __pbn__descriptor != null; } public void Resetdescriptor() { __pbn__descriptor = null; } private string __pbn__descriptor; [global::ProtoBuf.ProtoMember(2, IsRequired = true)] public string name { get; set; } [global::ProtoBuf.ProtoMember(3, IsRequired = true)] public uint extraction_rate { get; set; } } [global::ProtoBuf.ProtoContract()] public partial class Channels : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public Channels() { channel = new global::System.Collections.Generic.List<ChannelConfig>(); OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public global::System.Collections.Generic.List<ChannelConfig> channel { get; private set; } } [global::ProtoBuf.ProtoContract()] public partial class Records : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public Records() { record_path = new global::System.Collections.Generic.List<string>(); OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1)] public global::System.Collections.Generic.List<string> record_path { get; private set; } } [global::ProtoBuf.ProtoContract()] public partial class DataExtractionConfig : global::ProtoBuf.IExtensible { private global::ProtoBuf.IExtension __pbn__extensionData; global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) { return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing); } public DataExtractionConfig() { OnConstructor(); } partial void OnConstructor(); [global::ProtoBuf.ProtoMember(1, IsRequired = true)] public IoConfig io_config { get; set; } [global::ProtoBuf.ProtoMember(2, IsRequired = true)] public Channels channels { get; set; } [global::ProtoBuf.ProtoMember(3, IsRequired = true)] public Records records { get; set; } } #pragma warning restore 0612, 1591, 3021
using System.IO; namespace Plcway.Communication.Core.Net { /// <summary> /// 文件传送的异步对象 /// </summary> internal class FileStateObject : StateOneBase { /// <summary> /// 操作的流 /// </summary> public Stream Stream { get; set; } } }
using MathCore.WPF.ViewModels; namespace MathCore.WPF.WindowTest.ViewModels { class Link : ViewModel { public Node Start { get; } public Node End { get; } #region Weight : double - Вес /// <summary>Вес</summary> private double _Weight; /// <summary>Вес</summary> public double Weight { get => _Weight; set => Set(ref _Weight, value); } #endregion public Link(Node Start, Node End, double Weight = 1) { this.Start = Start; this.End = End; _Weight = Weight; } } }
using System; using System.Diagnostics; using System.IO; using IdSharp.Common.Utils; namespace IdSharp.Tagging.ID3v2.Frames { internal sealed class RelativeVolumeAdjustment : Frame, IRelativeVolumeAdjustment { private const byte _id3v24BitsRepresentingPeak = 16; private string _identification; private decimal _frontRightAdjustment; private decimal _frontLeftAdjustment; private decimal _backRightAdjustment; private decimal _backLeftAdjustment; private decimal _frontCenterAdjustment; private decimal _subwooferAdjustment; private decimal _backCenterAdjustment; private decimal _otherAdjustment; private decimal _masterAdjustment; private decimal _frontRightPeak; private decimal _frontLeftPeak; private decimal _backRightPeak; private decimal _backLeftPeak; private decimal _frontCenterPeak; private decimal _subwooferPeak; private decimal _backCenterPeak; private decimal _otherPeak; private decimal _masterPeak; public string Identification { get { return _identification; } set { _identification = value; RaisePropertyChanged("Identification"); } } public decimal FrontRightAdjustment { get { return _frontRightAdjustment; } set { _frontRightAdjustment = value; RaisePropertyChanged("FrontRightAdjustment"); } } public decimal FrontLeftAdjustment { get { return _frontLeftAdjustment; } set { _frontLeftAdjustment = value; RaisePropertyChanged("FrontLeftAdjustment"); } } public decimal BackRightAdjustment { get { return _backRightAdjustment; } set { _backRightAdjustment = value; RaisePropertyChanged("BackRightAdjustment"); } } public decimal BackLeftAdjustment { get { return _backLeftAdjustment; } set { _backLeftAdjustment = value; RaisePropertyChanged("BackLeftAdjustment"); } } public decimal FrontCenterAdjustment { get { return _frontCenterAdjustment; } set { _frontCenterAdjustment = value; RaisePropertyChanged("FrontCenterAdjustment"); } } public decimal SubwooferAdjustment { get { return _subwooferAdjustment; } set { _subwooferAdjustment = value; RaisePropertyChanged("SubwooferAdjustment"); } } public decimal BackCenterAdjustment { get { return _backCenterAdjustment; } set { _backCenterAdjustment = value; RaisePropertyChanged("BackCenterAdjustment"); } } public decimal OtherAdjustment { get { return _otherAdjustment; } set { _otherAdjustment = value; RaisePropertyChanged("OtherAdjustment"); } } public decimal MasterAdjustment { get { return _masterAdjustment; } set { _masterAdjustment = value; RaisePropertyChanged("MasterAdjustment"); } } public decimal FrontRightPeak { get { return _frontRightPeak; } set { _frontRightPeak = value; RaisePropertyChanged("FrontRightPeak"); } } public decimal FrontLeftPeak { get { return _frontLeftPeak; } set { _frontLeftPeak = value; RaisePropertyChanged("FrontLeftPeak"); } } public decimal BackRightPeak { get { return _backRightPeak; } set { _backRightPeak = value; RaisePropertyChanged("BackRightPeak"); } } public decimal BackLeftPeak { get { return _backLeftPeak; } set { _backLeftPeak = value; RaisePropertyChanged("BackLeftPeak"); } } public decimal FrontCenterPeak { get { return _frontCenterPeak; } set { _frontCenterPeak = value; RaisePropertyChanged("FrontCenterPeak"); } } public decimal SubwooferPeak { get { return _subwooferPeak; } set { _subwooferPeak = value; RaisePropertyChanged("SubwooferPeak"); } } public decimal BackCenterPeak { get { return _backCenterPeak; } set { _backCenterPeak = value; RaisePropertyChanged("BackCenterPeak"); } } public decimal OtherPeak { get { return _otherPeak; } set { _otherPeak = value; RaisePropertyChanged("OtherPeak"); } } public decimal MasterPeak { get { return _masterPeak; } set { _masterPeak = value; RaisePropertyChanged("MasterPeak"); } } public override string GetFrameID(ID3v2TagVersion tagVersion) { switch (tagVersion) { case ID3v2TagVersion.ID3v24: return "RVA2"; case ID3v2TagVersion.ID3v23: return "RVAD"; case ID3v2TagVersion.ID3v22: return "RVA"; default: throw new ArgumentException("Unknown tag version"); } } public override void Read(TagReadingInfo tagReadingInfo, Stream stream) { // RVAD/RVA2 /*Double original = -65534; Double newVal = Math.Log10(1 + original/65535.0)*20.0*512.0; Double original2 = Math.Pow(10, newVal/(20.0*512.0)); original2 = original2 - 1; original2 *= 65535.0;*/ /*Double original = 10000; Double newVal = Math.Log10(1 + original / 65535.0); Double original2 = Math.Pow(10, newVal); original2 = original2 - 1; original2 *= 65535.0;*/ _frameHeader.Read(tagReadingInfo, ref stream); int bytesLeft = _frameHeader.FrameSizeExcludingAdditions; if (bytesLeft > 0) { // todo: there needs to be some kind of a test to see if this is RVAD/RVA2 format, too // much varying implementation in 2.3 and 2.4 bool isRVA2 = (_frameHeader.TagVersion == ID3v2TagVersion.ID3v24); if (isRVA2) { // sometimes "identification" is completely ommitted... grr Identification = ID3v2Utils.ReadString(EncodingType.ISO88591, stream, ref bytesLeft); while (bytesLeft >= 3) { // TODO: Implementation not complete byte channelType = stream.Read1(ref bytesLeft); //if (channelType == 16) break; // Invalid, probably stored as an ID3v2.3 RVAD frame // TODO: some kind of switch.. maybe a new internal enum short volumeAdjustment = stream.ReadInt16(ref bytesLeft); if (bytesLeft > 0) { // sometimes represented as BITS representing peak.. seriously. byte bytesRepresentingPeak = stream.Read1(ref bytesLeft); if (bytesRepresentingPeak == 0) break; if (bytesLeft >= bytesRepresentingPeak) { // TODO: Finish implementation byte[] peakVolume = stream.Read(bytesRepresentingPeak); bytesLeft -= peakVolume.Length; } else { break; } } } if (bytesLeft > 0) { //Trace.WriteLine("Invalid RVA2 frame"); //stream.Seek(bytesLeft, SeekOrigin.Current); //bytesLeft = 0; // Try to read it like an ID3v2.3 RVAD frame stream.Seek(bytesLeft - _frameHeader.FrameSizeExcludingAdditions, SeekOrigin.Current); bytesLeft = _frameHeader.FrameSizeExcludingAdditions; isRVA2 = false; } else { // TODO //MessageBox.Show("valid RVA2 frame, omg!"); } } // ID3v2.2, ID3v2.3, or mal-formed ID3v2.4 if (isRVA2 == false) { byte incrementDecrement = stream.Read1(ref bytesLeft); if (bytesLeft > 0) { byte bitsUsedForVolumeDescription = stream.Read1(ref bytesLeft); int bytesUsedForVolumeDescription = bitsUsedForVolumeDescription / 8; // TODO: (may be useful for testing which implementation) // if bits used for volume description is > 64, don't bother // Relative volume change, right if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); FrontRightAdjustment = ByteUtils.ConvertToInt64(byteArray) * (ByteUtils.IsBitSet(incrementDecrement, 0) ? 1 : -1); } // Relative volume change, left if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); FrontLeftAdjustment = ByteUtils.ConvertToInt64(byteArray) * (ByteUtils.IsBitSet(incrementDecrement, 1) ? 1 : -1); } // Peak volume right if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); FrontRightPeak = ByteUtils.ConvertToInt64(byteArray); } // Peak volume left if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); FrontLeftPeak = ByteUtils.ConvertToInt64(byteArray); } // Relative volume change, right back if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); BackRightAdjustment = ByteUtils.ConvertToInt64(byteArray) * (ByteUtils.IsBitSet(incrementDecrement, 2) ? 1 : -1); } // Relative volume change, left back if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); BackLeftAdjustment = ByteUtils.ConvertToInt64(byteArray) * (ByteUtils.IsBitSet(incrementDecrement, 3) ? 1 : -1); } // Peak volume right back if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); BackRightPeak = ByteUtils.ConvertToInt64(byteArray); } // Peak volume left back if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); BackLeftPeak = ByteUtils.ConvertToInt64(byteArray); } // Relative volume change, center if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); FrontCenterAdjustment = ByteUtils.ConvertToInt64(byteArray) * (ByteUtils.IsBitSet(incrementDecrement, 4) ? 1 : -1); } // Peak volume center if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); FrontCenterPeak = ByteUtils.ConvertToInt64(byteArray); } // Relative volume change, bass if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); SubwooferAdjustment = ByteUtils.ConvertToInt64(byteArray) * (ByteUtils.IsBitSet(incrementDecrement, 5) ? 1 : -1); } // Peak volume bass if (bytesLeft >= bytesUsedForVolumeDescription) { byte[] byteArray = stream.Read(bytesUsedForVolumeDescription, ref bytesLeft); SubwooferPeak = ByteUtils.ConvertToInt64(byteArray); } } } // Skip past the rest of the frame if (bytesLeft > 0) { Trace.WriteLine("Invalid RVA2/RVAD/RVA frame"); stream.Seek(bytesLeft, SeekOrigin.Current); //bytesLeft = 0; } } } public override byte[] GetBytes(ID3v2TagVersion tagVersion) { // TODO return new byte[0]; // throw new NotImplementedException(); /* using (MemoryStream frameData = new MemoryStream()) { if (tagVersion == TagVersion.ID3v22 || tagVersion == TagVersion.ID3v23) { Byte adjustmentDirection = 0; decimal maxValue = 0; maxValue = Math.Max(maxValue, Math.Abs(_frontRightAdjustment)); maxValue = Math.Max(maxValue, Math.Abs(_frontLeftAdjustment)); maxValue = Math.Max(maxValue, Math.Abs(_frontRightPeak)); maxValue = Math.Max(maxValue, Math.Abs(_frontLeftPeak)); if (_frontRightAdjustment > 0) adjustmentDirection |= 0x01; if (_frontLeftAdjustment > 0) adjustmentDirection |= 0x02; if (tagVersion == TagVersion.ID3v23) { maxValue = Math.Max(maxValue, Math.Abs(_backRightAdjustment)); maxValue = Math.Max(maxValue, Math.Abs(_backLeftAdjustment)); maxValue = Math.Max(maxValue, Math.Abs(_backRightPeak)); maxValue = Math.Max(maxValue, Math.Abs(_backLeftPeak)); maxValue = Math.Max(maxValue, Math.Abs(_frontCenterAdjustment)); maxValue = Math.Max(maxValue, Math.Abs(_frontCenterPeak)); maxValue = Math.Max(maxValue, Math.Abs(_subwooferAdjustment)); maxValue = Math.Max(maxValue, Math.Abs(_subwooferPeak)); if (_backRightAdjustment > 0) adjustmentDirection |= 0x04; if (_backLeftAdjustment > 0) adjustmentDirection |= 0x08; if (_frontCenterAdjustment > 0) adjustmentDirection |= 0x10; if (_subwooferAdjustment > 0) adjustmentDirection |= 0x20; } int bitsForVolume; if (maxValue <= 0xFF) bitsForVolume = 8; else if (maxValue <= 0xFFFF) bitsForVolume = 16; else if (maxValue <= 0xFFFFFF) bitsForVolume = 24; else if (maxValue <= 0xFFFFFFFF) bitsForVolume = 32; else throw new InvalidOperationException("Maximum volume adjustment is 2^32"); int bytesForVolume = bitsForVolume / 8; frameData.WriteByte(adjustmentDirection); frameData.WriteByte((Byte)bitsForVolume); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_frontRightAdjustment), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_frontLeftAdjustment), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_frontRightPeak), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_frontLeftPeak), bytesForVolume)); if (tagVersion == TagVersion.ID3v23) { frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_backRightAdjustment), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_backLeftAdjustment), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_backRightPeak), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_backLeftPeak), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_frontCenterAdjustment), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_frontCenterPeak), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_subwooferAdjustment), bytesForVolume)); frameData.Write(ByteUtils.ConvertToByteArray(Math.Abs(_subwooferPeak), bytesForVolume)); } } else if (tagVersion == TagVersion.ID3v24) { // TODO: Test frameData.Write(ID3v2Utils.GetStringBytes(tagVersion, EncodingType.ISO_8859_1, Identification, true)); WriteID3v24ChannelItem(frameData, ChannelType.Other, _otherAdjustment, _otherPeak); WriteID3v24ChannelItem(frameData, ChannelType.MasterVolume, _masterAdjustment, _masterPeak); WriteID3v24ChannelItem(frameData, ChannelType.FrontRight, _frontRightAdjustment, _frontRightPeak); WriteID3v24ChannelItem(frameData, ChannelType.FrontLeft, _frontLeftAdjustment, _frontLeftPeak); WriteID3v24ChannelItem(frameData, ChannelType.BackRight, _backRightAdjustment, _backRightPeak); WriteID3v24ChannelItem(frameData, ChannelType.BackLeft, _backLeftAdjustment, _backLeftPeak); WriteID3v24ChannelItem(frameData, ChannelType.FrontCenter, _frontCenterAdjustment, _frontCenterPeak); WriteID3v24ChannelItem(frameData, ChannelType.BackCenter, _backCenterAdjustment, _backCenterPeak); WriteID3v24ChannelItem(frameData, ChannelType.Subwoofer, _subwooferAdjustment, _subwooferPeak); } else { throw new ArgumentException("Unknown tag version"); } return _frameHeader.GetBytes(frameData, tagVersion, GetFrameID(tagVersion)); } */ } private void WriteID3v24ChannelItem(MemoryStream memoryStream, ChannelType channelType, decimal adjustment, decimal peak) { if (adjustment != 0 || peak != 0) { memoryStream.WriteByte((byte)channelType); // TODO //Utils.Write(memoryStream, ByteUtils.ConvertDecimalToByteArray(adjustment)); if (adjustment <= 64 && adjustment >= -64) { } else { } throw new NotImplementedException(); /* memoryStream.WriteByte(_iD3v24BitsRepresentingPeak); ByteUtils.Write(memoryStream, ByteUtils.ConvertToByteArray(Math.Abs(peak), _iD3v24BitsRepresentingPeak/8)); */ } } } }
using System.Collections.Generic; using System.Diagnostics; namespace HoU.GuildBot.Shared.Objects { [DebuggerDisplay("{" + nameof(ToString) + "(),nq}")] public class AvailableGame { public string LongName { get; set; } public string ShortName { get; set; } public ulong? PrimaryGameDiscordRoleID { get; set; } public bool IncludeInGuildMembersStatistic { get; set; } public bool IncludeInGamesMenu { get; set; } public string GameInterestEmojiName { get; set; } public ulong? GameInterestRoleId { get; set; } public List<AvailableGameRole> AvailableRoles { get; } public AvailableGame() { AvailableRoles = new List<AvailableGameRole>(); } public AvailableGame Clone() { var c = new AvailableGame { LongName = LongName, ShortName = ShortName, PrimaryGameDiscordRoleID = PrimaryGameDiscordRoleID, IncludeInGuildMembersStatistic = IncludeInGuildMembersStatistic, IncludeInGamesMenu = IncludeInGamesMenu, GameInterestEmojiName = GameInterestEmojiName, GameInterestRoleId = GameInterestRoleId }; foreach (var role in AvailableRoles) { c.AvailableRoles.Add(role.Clone()); } return c; } public override string ToString() { return PrimaryGameDiscordRoleID == null ? $"{LongName} ({ShortName})" : $"{LongName} ({ShortName}) - {{{PrimaryGameDiscordRoleID.Value}}}"; } } }
using System.Linq; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ClaroTechTest1.Models; using ClaroTechTest1.Models.Prod; using ClaroTechTest1.Services; using ClaroTechTest1.Internal; namespace ClaroTechTest1.Controllers { [ApiController] [Route("api/v1/[controller]")] public class ProdController : ControllerBase { private string ControllerName = "Prod"; public ProdController(XorDbContext db, IGeneralService gs, IProdService ps){ this._db = db; this._gs = gs; this._ps = ps; } public XorDbContext _db { get; set; } public IGeneralService _gs { get; set; } public IProdService _ps { get; set; } //api/v1/prod/entities/Product [Route("entities/{entity}")] public IActionResult getEntity(string entity, Dictionary<string, object> filter){ var r = this._gs.GetEntity(ControllerName, entity, filter); return Ok(r); } //api/v1/prod/functions/getProducts [Route("functions/getProducts")] public IActionResult getProducts([FromBody] dynamic json){ var filter = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString()); var r = this._ps.GetProducts(this._db, filter); return Ok(r); } //api/v1/prod/functions/getFeatureDetails [Route("functions/getFeatureDetails")] public IActionResult getFeatureDetails([FromBody] dynamic json){ var filter = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString()); filter["Feature_ID"] = ((JArray)filter["Feature_ID"]).ToObject<int[]>(); var r = this._gs.GetEntity(ControllerName, "FeatureDetail", filter); return Ok(r); } //api/v1/prod/functions/getProductFeatures [Route("functions/getProductFeatures")] public IActionResult getProductFeatures([FromBody] dynamic json){ var filter = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString()); var r = this._ps.GetProductFeatures(this._db, filter); return Ok(r); } //api/v1/prod/process/saveFeature [Route("process/saveFeature")] public IActionResult saveFeature([FromBody] dynamic json){ var feature = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString()); feature["FeatureDetails"] = ((JArray)feature["FeatureDetails"]) .Select(jv => new FeatureDetail { FeatureDetail_ID = jv.Value<int>("FeatureDetail_ID"), FeatureDetailDisplay = jv.Value<string>("FeatureDetailDisplay"), Active = true }).ToArray(); Return r = new Return(); using (var transaction = this._db.Database.BeginTransaction()){ var cfr = this._ps.CreateFeature(this._db, feature); if(cfr?.Error?.Message != null){ transaction.Rollback(); return Ok(cfr); } feature["Feature_ID"] = cfr.Data.Feature_ID; var dr = this._ps.SetFeatureDetails(this._db, feature["Feature_ID"], feature["FeatureDetails"]); if(dr?.Error?.Message != null){ transaction.Rollback(); return Ok(dr); } transaction.Commit(); return Ok(r.SetSuccess("Característica registrada.").SetData(cfr)); } } //api/v1/prod/process/saveMerchandise [Route("process/saveMerchandise")] public IActionResult saveMerchandise([FromBody] dynamic json){ var merchandise = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString()); merchandise["FeatureSelections"] = ((JArray)merchandise["FeatureSelections"]).ToObject<int[]>(); Return r = new Return(); using (var transaction = this._db.Database.BeginTransaction()){ var cfr = this._ps.CreateMerchandise(this._db, merchandise); if(cfr?.Error?.Message != null){ transaction.Rollback(); return Ok(cfr); } merchandise["Merchandise_ID"] = cfr.Data.Merchandise_ID; var sbr = this._ps.SetFeatures(this._db, merchandise["Merchandise_ID"], merchandise["FeatureSelections"]); if(sbr?.Error?.Message != null){ transaction.Rollback(); return Ok(sbr); } transaction.Commit(); return Ok(r.SetSuccess("Característica registrada.").SetData(cfr)); } } //api/v1/prod/process/saveProduct [Route("process/saveProduct")] public IActionResult saveProduct([FromBody] dynamic json){ var product = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString()); product["ProductFeatures"] = ((JArray)product["ProductFeatures"]) .Select(jv => new ProductFeature { Merchandise_ID = jv.Value<int>("Merchandise_ID"), Feature_ID = jv.Value<int>("Feature_ID"), FeatureDetail_ID = jv.Value<int>("FeatureDetail_ID"), Active = true }).ToArray(); Return r = new Return(); using (var transaction = this._db.Database.BeginTransaction()){ var cfr = this._ps.CreateProduct(this._db, product); if(cfr?.Error?.Message != null){ transaction.Rollback(); return Ok(cfr); } product["Product_ID"] = cfr.Data.Product_ID; var sbr = this._ps.SetProductFeatures(this._db, product["Product_ID"], product["ProductFeatures"]); if(sbr?.Error?.Message != null){ transaction.Rollback(); return Ok(sbr); } transaction.Commit(); return Ok(r.SetSuccess("Producto registrada.").SetData(cfr)); } } } }
using System.Collections.Generic; namespace Application.Components.EmailSender { public class SendMultipleEmailsRequest { public List<string> Emails { get; set; } public string Subject { get; set; } public string Content { get; set; } public List<SendEmailRequestAttachment> Attachments { get; set; } } }
// <Snippet2> using System; using System.Globalization; using System.Threading; public class Example { public static void Main() { CultureInfo uiCulture1 = CultureInfo.CurrentUICulture; CultureInfo uiCulture2 = Thread.CurrentThread.CurrentUICulture; Console.WriteLine("The current UI culture is {0}", uiCulture1.Name); Console.WriteLine("The two CultureInfo objects are equal: {0}", uiCulture1 == uiCulture2); } } // The example displays output like the following: // The current UI culture is en-US // The two CultureInfo objects are equal: True // </Snippet2>
using commercetools.Sdk.Client; using commercetools.Sdk.Domain; using commercetools.Sdk.Domain.Categories; using commercetools.Sdk.HttpApi.Tokens; using Microsoft.AspNetCore.Mvc; namespace commercetools.Sdk.AnonymousSessionExample.Controllers { public class HomeController : Controller { private readonly IClient client; private readonly ITokenFlowRegister tokenFlowRegister; public HomeController(IClient client, ITokenFlowRegister tokenFlowRegister) { this.client = client; this.tokenFlowRegister = tokenFlowRegister; } public IActionResult Index() { PagedQueryResult<Category> category = this.client.ExecuteAsync(new QueryCommand<Category>()).Result; int count = category.Results.Count; return View(new { CategoryCount = count, TokenFlowRegister = this.tokenFlowRegister.TokenFlow }); } [HttpPost] public IActionResult Index(string username, string password) { this.tokenFlowRegister.TokenFlow = TokenFlow.Password; PagedQueryResult<Category> category = this.client.ExecuteAsync(new QueryCommand<Category>()).Result; int count = category.Results.Count; return View(new { CategoryCount = count, TokenFlowRegister = this.tokenFlowRegister.TokenFlow }); } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using ScriptPlayer.Shared.Converters; namespace ScriptPlayer.Shared { public class SeekBar : Control { public delegate void ClickedEventHandler(object sender, double relative, TimeSpan absolute, int downMoveUp); public static readonly DependencyProperty OverlayProperty = DependencyProperty.Register( "Overlay", typeof(Brush), typeof(SeekBar), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty OverlayOpacityProperty = DependencyProperty.Register( "OverlayOpacity", typeof(Brush), typeof(SeekBar), new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register( "Progress", typeof(TimeSpan), typeof(SeekBar), new PropertyMetadata(default(TimeSpan), OnVisualPropertyChanged)); public static readonly DependencyProperty DurationProperty = DependencyProperty.Register( "Duration", typeof(TimeSpan), typeof(SeekBar), new PropertyMetadata(default(TimeSpan), OnVisualPropertyChanged)); public static readonly DependencyProperty HoverPositionProperty = DependencyProperty.Register( "HoverPosition", typeof(TimeSpan), typeof(SeekBar), new PropertyMetadata(default(TimeSpan))); public TimeSpan HoverPosition { get { return (TimeSpan) GetValue(HoverPositionProperty); } set { SetValue(HoverPositionProperty, value); } } private bool _down; private Popup _popup; private TextBlock _txt; static SeekBar() { BackgroundProperty.OverrideMetadata(typeof(SeekBar), new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender)); } public SeekBar() { InitializePopup(); } public Brush Overlay { get => (Brush) GetValue(OverlayProperty); set => SetValue(OverlayProperty, value); } public Brush OverlayOpacity { get => (Brush) GetValue(OverlayOpacityProperty); set => SetValue(OverlayOpacityProperty, value); } public TimeSpan Duration { get => (TimeSpan) GetValue(DurationProperty); set => SetValue(DurationProperty, value); } public TimeSpan Progress { get => (TimeSpan) GetValue(ProgressProperty); set => SetValue(ProgressProperty, value); } public event ClickedEventHandler Seek; private static void OnVisualPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((SeekBar) d).InvalidateVisual(); } private void InitializePopup() { _txt = new TextBlock { Padding = new Thickness(3) }; BindText(_txt); Border border = new Border { Background = Brushes.White, BorderBrush = Brushes.Black, Child = _txt }; _popup = new Popup { IsOpen = false, Placement = PlacementMode.Top, PlacementTarget = this, Child = border }; } private void BindText(TextBlock txt) { MultiBinding binding = new MultiBinding{ Converter = new SeekBarPositionConverter()}; binding.Bindings.Add(new Binding { Source = this, Path = new PropertyPath(ProgressProperty) }); binding.Bindings.Add(new Binding { Source = this, Path = new PropertyPath(DurationProperty) }); binding.Bindings.Add(new Binding { Source = this, Path = new PropertyPath(HoverPositionProperty) }); BindingOperations.SetBinding(txt, TextBlock.TextProperty, binding); //TimeSpan progress = (TimeSpan)values[0]; //TimeSpan duration = (TimeSpan)values[1]; //TimeSpan hoverposition = (TimeSpan)values[2]; /*_txt.Text = Duration >= TimeSpan.FromHours(1) ? $"{absolutePosition.Hours:00}:{absolutePosition.Minutes:00}:{absolutePosition.Seconds:00}" : $"{absolutePosition.Minutes:00}:{absolutePosition.Seconds:00}";*/ } protected override void OnRender(DrawingContext dc) { Rect rect = new Rect(new Point(0, 0), new Size(ActualWidth, ActualHeight)); dc.PushClip(new RectangleGeometry(rect)); dc.DrawRectangle(Background, null, rect); dc.PushOpacityMask(OverlayOpacity); dc.DrawRectangle(Overlay, null, rect); dc.Pop(); if (Duration == TimeSpan.Zero) return; double linePosition = Progress.Divide(Duration) * ActualWidth; linePosition = Math.Round(linePosition - 0.5) + 0.5; dc.DrawLine(new Pen(Brushes.Black, 3), new Point(linePosition, 0), new Point(linePosition, ActualHeight)); dc.DrawLine(new Pen(Brushes.White, 1), new Point(linePosition, 0), new Point(linePosition, ActualHeight)); dc.Pop(); } protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { if (Duration == TimeSpan.Zero) return; if (!_down) return; ReleaseMouseCapture(); _down = false; Point p = e.GetPosition(this); if (IsMouseOver) UpdatePopup(p); else ClosePopup(); double relativePosition = GetRelativePosition(p.X); TimeSpan absolutePosition = Duration.Multiply(relativePosition); OnSeek(relativePosition, absolutePosition, 2); } private void ClosePopup() { _popup.IsOpen = false; } protected override void OnMouseMove(MouseEventArgs e) { Point p = e.GetPosition(this); UpdatePopup(p); if (!_down) return; if (Duration == TimeSpan.Zero) return; if (e.LeftButton != MouseButtonState.Pressed) return; double relativePosition = GetRelativePosition(p.X); TimeSpan absolutePosition = Duration.Multiply(relativePosition); OnSeek(relativePosition, absolutePosition, 1); } protected override void OnMouseEnter(MouseEventArgs e) { UpdatePopup(e.GetPosition(this)); } protected override void OnMouseLeave(MouseEventArgs e) { if (_down) return; ClosePopup(); } private void UpdatePopup(Point point) { if (Duration == TimeSpan.Zero) return; double relativePosition = GetRelativePosition(point.X); TimeSpan absolutePosition = Duration.Multiply(relativePosition); HoverPosition = absolutePosition; _popup.IsOpen = true; _popup.HorizontalOffset = relativePosition * ActualWidth - ((FrameworkElement) _popup.Child).ActualWidth / 2.0; } private double GetRelativePosition(double x) { double progress = x / Math.Max(1, ActualWidth); progress = Math.Min(1.0, Math.Max(0, progress)); return progress; } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { if (Duration == TimeSpan.Zero) return; _down = true; CaptureMouse(); Point p = e.GetPosition(this); UpdatePopup(p); double relativePosition = GetRelativePosition(p.X); TimeSpan absolutePosition = Duration.Multiply(relativePosition); OnSeek(relativePosition, absolutePosition, 0); } protected virtual void OnSeek(double relative, TimeSpan absolute, int downMoveUp) { Seek?.Invoke(this, relative, absolute, downMoveUp); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VW; using VW.Labels; using VW.Serializer.Attributes; namespace cs_unittest { [TestClass] public class TestNull { [TestMethod] [TestCategory("Vowpal Wabbit/Marshal")] public void TestNull1() { using (var vw = new VowpalWabbit<Context, ADF>("--cb_adf --rank_all --interact ab")) { var ctx = new Context() { ID = 25, Vector = null, ActionDependentFeatures = new[] { new ADF { ADFID = "23" } }.ToList() }; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, new ContextualBanditLabel() { Action = 1, Cost = 1, Probability = 0.2f }); var result = vw.Predict(ctx, ctx.ActionDependentFeatures); Assert.AreEqual(1, result.Length); } } [TestMethod] [TestCategory("Vowpal Wabbit/Marshal")] public void TestNull2() { using (var vw = new VowpalWabbit<Context, ADF>("--cb_adf --rank_all --interact ab")) { var ctx = new Context() { ID = 25, Vector = null, ActionDependentFeatures = new[] { new ADF { ADFID = "23", } }.ToList() }; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, new ContextualBanditLabel() { Action = 1, Cost= 1, Probability = 0.2f }); } } [TestMethod] [TestCategory("Vowpal Wabbit/Marshal")] public void TestNull3() { using (var vw = new VowpalWabbit<Context, ADF>("--cb_adf --rank_all --interact ac")) { var ctx = new Context() { ID = 25, Vector = new float[] { 3 }, VectorC = new float[] { 2, 2, 3 }, ActionDependentFeatures = new[] { new ADF { ADFID = "23", } }.ToList() }; var label = new ContextualBanditLabel() { Action = 1, Cost= 1, Probability = 0.2f }; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, label); ctx.Vector = null; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, label); ctx.Vector = new float[] { 2 }; ctx.VectorC = null; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, label); ctx.Vector = null; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, label); } } [TestMethod] [TestCategory("Vowpal Wabbit/Marshal")] public void TestNull4() { using (var vw = new VowpalWabbit<Context, ADF>("--cb_adf --rank_all --interact ab")) { var ctx = new Context() { ID = 25, Vector = null, ActionDependentFeatures = new[] { new ADF { ADFID = null } }.ToList() }; var label = new ContextualBanditLabel() { Action = 1, Cost= 1, Probability = 0.2f }; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, label); var result = vw.Predict(ctx, ctx.ActionDependentFeatures); Assert.AreEqual(1, result.Length); ctx.ID = null; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, label); result = vw.Predict(ctx, ctx.ActionDependentFeatures); Assert.AreEqual(1, result.Length); } } [TestMethod] [TestCategory("Vowpal Wabbit/Marshal")] public void TestNull5() { using (var vw = new VowpalWabbit<Context, ADF>("--cb_adf --rank_all --interact ab")) { var ctx = new Context() { ID = 25, ActionDependentFeatures = new[] { new ADF { ADFID = "123" }, new ADF(), new ADF(), new ADF { ADFID = "4"} }.ToList() }; var label = new ContextualBanditLabel() { Action = 1, Cost = 1, Probability = 0.2f }; vw.Learn(ctx, ctx.ActionDependentFeatures, 0, label); var result = vw.Predict(ctx, ctx.ActionDependentFeatures); Assert.AreEqual(4, result.Length); ctx.ActionDependentFeatures[0].ADFID = null; ctx.ActionDependentFeatures[3].ADFID = null; result = vw.Predict(ctx, ctx.ActionDependentFeatures); Assert.AreEqual(4, result.Length); } } } public class ADF { [Feature] public string ADFID { get; set; } [Feature(FeatureGroup = 'b', AddAnchor = true)] public float[] Vector { get; set; } public ILabel Label { get; set; } } public class Context { [Feature] public int? ID { get; set; } [Feature(FeatureGroup = 'a', AddAnchor = true)] public float[] Vector { get; set; } [Feature(FeatureGroup = 'c')] public float[] VectorC { get; set; } public IReadOnlyList<ADF> ActionDependentFeatures { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace FastCSV.Utils { [TestFixture] public class TextParserTests { [Test] public void NextTest() { var cursor = new TextParser("Hello"); Assert.AreEqual('H', cursor.Next().Value); Assert.AreEqual('e', cursor.Next().Value); Assert.AreEqual('l', cursor.Next().Value); Assert.AreEqual('l', cursor.Next().Value); Assert.AreEqual('o', cursor.Next().Value); } [Test] public void PeekTest() { var cursor = new TextParser("Hello"); Assert.AreEqual('H', cursor.Peek().Value); Assert.AreEqual('H', cursor.Peek().Value); cursor.Next(); Assert.AreEqual('e', cursor.Peek().Value); cursor.Next(); Assert.AreEqual('l', cursor.Peek().Value); cursor.Next(); Assert.AreEqual('l', cursor.Peek().Value); cursor.Next(); Assert.AreEqual('o', cursor.Peek().Value); cursor.Next(); Assert.False(cursor.Peek().HasValue); } [Test] public void RestTest() { var cursor = new TextParser("Hello"); Assert.AreEqual("Hello", cursor.Rest.ToString()); cursor.Next(); Assert.AreEqual("ello", cursor.Rest.ToString()); cursor.Next(); Assert.AreEqual("llo", cursor.Rest.ToString()); cursor.Next(); Assert.AreEqual("lo", cursor.Rest.ToString()); cursor.Next(); Assert.AreEqual("o", cursor.Rest.ToString()); cursor.Next(); Assert.AreEqual("", cursor.Rest.ToString()); } [Test] public void CanConsumeTest() { var cursor = new TextParser("Hello World"); cursor.CanConsume("Hello"); cursor.CanConsume("Hello World"); cursor.Next(); cursor.CanConsume("ello"); cursor.CanConsume("ello World"); cursor.Next(); cursor.Next(); cursor.Next(); cursor.Next(); cursor.Next(); cursor.CanConsume("World"); } [Test] public void ConsumeTest() { var cursor = new TextParser("Hello World"); cursor.Consume("Hello "); Assert.AreEqual("World", cursor.Rest.ToString()); } [Test] public void SliceStartTest() { var parser = new TextParser("Hello World"); Assert.AreEqual("World", parser.Slice(6).Rest.ToString()); Assert.AreEqual("Hello World", parser.Rest.ToString()); } [Test] public void SliceStartCountTest() { var parser = new TextParser("Hello to my World"); Assert.AreEqual("to my", parser.Slice(6, 5).Rest.ToString()); Assert.AreEqual("Hello to my World", parser.Rest.ToString()); } [Test] public void RangeIndexerTest() { var parser = new TextParser("Hello to my World"); Assert.AreEqual("to my", parser[6..11].Rest.ToString()); Assert.AreEqual("Hello to my World", parser.Rest.ToString()); } } }