content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
namespace Eva.eShop.Services.Marketing.API.IntegrationEvents.Handlers { using Marketing.API.IntegrationEvents.Events; using Marketing.API.Model; using Eva.BuildingBlocks.EventBus.Abstractions; using Eva.eShop.Services.Marketing.API.Infrastructure.Repositories; using Microsoft.Extensions.Logging; using Serilog.Context; using System; using System.Collections.Generic; using System.Threading.Tasks; public class UserLocationUpdatedIntegrationEventHandler : IIntegrationEventHandler<UserLocationUpdatedIntegrationEvent> { private readonly IMarketingDataRepository _marketingDataRepository; private readonly ILogger<UserLocationUpdatedIntegrationEventHandler> _logger; public UserLocationUpdatedIntegrationEventHandler( IMarketingDataRepository repository, ILogger<UserLocationUpdatedIntegrationEventHandler> logger) { _marketingDataRepository = repository ?? throw new ArgumentNullException(nameof(repository)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task Handle(UserLocationUpdatedIntegrationEvent @event) { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); var userMarketingData = await _marketingDataRepository.GetAsync(@event.UserId); userMarketingData = userMarketingData ?? new MarketingData() { UserId = @event.UserId }; userMarketingData.Locations = MapUpdatedUserLocations(@event.LocationList); await _marketingDataRepository.UpdateLocationAsync(userMarketingData); } } private List<Location> MapUpdatedUserLocations(List<UserLocationDetails> newUserLocations) { var result = new List<Location>(); newUserLocations.ForEach(location => { result.Add(new Location() { LocationId = location.LocationId, Code = location.Code, Description = location.Description }); }); return result; } } }
41.896552
170
0.662551
[ "MIT" ]
Liang-Zhinian/eShop
src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs
2,432
C#
using HarmonyLib; using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes.Spells; using Kingmaker.Blueprints.JsonSystem; using Kingmaker.EntitySystem.Entities; using Kingmaker.PubSubSystem; using Kingmaker.UI.MVVM._VM.CharGen.Phases.Spells; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Abilities.Blueprints; using Kingmaker.UnitLogic.Class.LevelUp; using Kingmaker.Utility; using System; using System.Collections.Generic; using System.Linq; using TabletopTweaks.Utilities; namespace TabletopTweaks.NewComponents { [TypeId("070fd2a4a2cb4f198a44ae036082818c")] public class AdditionalSpellSelection : UnitFactComponentDelegate, IUnitCompleteLevelUpHandler { private Spellbook SpellBook { get => Owner.DemandSpellbook(m_SpellCastingClass); } private BlueprintSpellList SpellList { get => ProxyList(m_SpellList ?? SpellBook?.Blueprint?.SpellList); } public int AdjustedMaxLevel { get { if (!UseOffset) { return MaxSpellLevel; } return Math.Max((SpellBook?.MaxSpellLevel ?? 0) - SpellLevelOffset, 1); } } public override void OnActivate() { LevelUpController controller = Kingmaker.Game.Instance?.LevelUpController; if (controller == null) { return; } if (SpellBook == null) { return; } var selectionCount = controller .State? .Selections? .Select(s => s.SelectedItem?.Feature) .Where(f => f == Fact.Blueprint) .Count(); int i = 0; for (; i < spellSelections.Count && i < selectionCount; i++) { controller.State.SpellSelections.Add(spellSelections[i]); spellSelections[i].SetExtraSpells(Count, AdjustedMaxLevel); } for (; i < selectionCount; i++) { if (i >= selectionCount) { continue; } var selection = controller.State.DemandSpellSelection(SpellBook.Blueprint, SpellList); selection.SetExtraSpells(Count, AdjustedMaxLevel); spellSelections.Add(selection); } } public override void OnTurnOff() { if (spellSelections.Empty()) { return; } LevelUpController controller = Kingmaker.Game.Instance?.LevelUpController; if (controller == null) { return; } if (SpellBook == null) { return; } spellSelections.ForEach(selection => controller.State.SpellSelections.Remove(selection)); } public void HandleUnitCompleteLevelup(UnitEntityData unit) { spellSelections.Clear(); } private BlueprintSpellList ProxyList(BlueprintSpellList referenced) { return Helpers.CreateCopy(referenced, bp => { bp.name = $"{bp.name}Proxy"; }); } private List<SpellSelectionData> spellSelections = new List<SpellSelectionData>(); public BlueprintSpellListReference m_SpellList; public BlueprintCharacterClassReference m_SpellCastingClass; public int MaxSpellLevel; public bool UseOffset; public int SpellLevelOffset; public int Count = 1; [HarmonyPatch(typeof(SpellSelectionData), nameof(SpellSelectionData.CanSelectAnything), new Type[] { typeof(UnitDescriptor) })] static class SpellSelectionData_CanSelectAnything_AdditionalSpellSelection_Patch { static void Postfix(SpellSelectionData __instance, ref bool __result, UnitDescriptor unit) { Spellbook spellbook = unit.Spellbooks.FirstOrDefault((Spellbook s) => s.Blueprint == __instance.Spellbook); if (spellbook == null) { __result = false; } if (!__instance.Spellbook.AllSpellsKnown) { return; } if (__instance.ExtraSelected != null && __instance.ExtraSelected.Length != 0) { if (__instance.ExtraSelected.HasItem((BlueprintAbility i) => i == null) && !__instance.ExtraByStat) { for (int level = 0; level <= __instance.ExtraMaxLevel; level++) { if (__instance.SpellList.SpellsByLevel[level].SpellsFiltered.HasItem((BlueprintAbility sb) => !sb.IsCantrip && !__instance.SpellbookContainsSpell(spellbook, level, sb) && !__instance.ExtraSelected.Contains(sb))) { __result = true; } } } } } } [HarmonyPatch(typeof(CharGenSpellsPhaseVM), nameof(CharGenSpellsPhaseVM.DefinePhaseMode), new Type[] { typeof(SpellSelectionData), typeof(SpellSelectionData.SpellSelectionState) })] static class CharGenSpellsPhaseVM_DefinePhaseMode_AdditionalSpellSelection_Patch { static void Postfix(CharGenSpellsPhaseVM __instance, ref CharGenSpellsPhaseVM.SpellSelectorMode __result, SpellSelectionData selectionData) { if (!selectionData.Spellbook.AllSpellsKnown) { return; } if (selectionData.ExtraSelected.Any<BlueprintAbility>() && !selectionData.ExtraByStat) { __result = CharGenSpellsPhaseVM.SpellSelectorMode.AnyLevels; } } } [HarmonyPatch(typeof(CharGenSpellsPhaseVM), nameof(CharGenSpellsPhaseVM.OrderPriority), MethodType.Getter)] static class CharGenSpellsPhaseVM_OrderPriority_AdditionalSpellSelection_Patch { static void Postfix(CharGenSpellsPhaseVM __instance, ref int __result) { if (__instance?.m_SelectionData == null) { return; } if (__instance.m_SelectionData.Spellbook?.SpellList?.AssetGuid != __instance.m_SelectionData.SpellList?.AssetGuid) { __result -= 500; } } } } }
49.773109
189
0.634138
[ "MIT" ]
1onepower/WrathMods-TabletopTweaks
TabletopTweaks/NewComponents/AdditionalSpellSelection.cs
5,925
C#
using System; using System.Data; using System.IO; using System.Text; using Zhoubin.Infrastructure.Common.Extent; namespace Zhoubin.Infrastructure.Common.Document { public class CsvDocumnet : DocumentBase<DataTable> { private Encoding _encoding; private string _file; private bool _firstRowForTitle; public CsvDocumnet(string file,Encoding encoding,bool firstRowForTitle) : base(true) { if (string.IsNullOrEmpty(file)) { throw new ArgumentNullException(nameof(file)); } if (!File.Exists(file)) { throw new FileNotFoundException(file); } _file = file; _firstRowForTitle = firstRowForTitle; _encoding = encoding; } public CsvDocumnet(DataTable csvData, Encoding encoding, bool firstRowForTitle) : base(false) { if (csvData == null) { throw new ArgumentNullException(nameof(csvData)); } _csvData = csvData; _firstRowForTitle = firstRowForTitle; _encoding = encoding; } protected override void DocumentInitialize() { } DataTable _csvData; protected override DataTable DocumentRead() { return _file.CsvToDataTable(_encoding, _firstRowForTitle); } protected override void DocumentOpen() { } protected override void DocumentSave(Stream stream) { StringBuilder builder = new StringBuilder(); if (_firstRowForTitle) { AppendLine(builder, _csvData.Columns, str => str); } if (_csvData.Rows.Count > 0) { builder.AppendLine(); } for (int i = 0; i < _csvData.Rows.Count; i++) { AppendLine(builder, _csvData.Columns, str => _csvData.Rows[i][str].ToString()); if (i < _csvData.Rows.Count - 1) { builder.AppendLine(); } } byte[] buffer = _encoding.GetBytes(builder.ToString()); stream.Write(buffer, 0, buffer.Length); } private void AppendLine(StringBuilder sb, DataColumnCollection dcc, Func<string, string> func) { bool firstColumn = true; for (int j = 0; j < dcc.Count; j++) { if (!firstColumn) sb.Append(','); sb.Append(CreateValue(func(dcc[j].ColumnName))); firstColumn = false; } } private string CreateValue(string str) { if (str.IndexOfAny(new char[] {'"', ','}) != -1) { return string.Format("\"{0}\"", str.Replace("\"", "\"\"")); } return str; } } }
30.520408
102
0.509194
[ "Apache-2.0" ]
cdzhoubin/Infrastructure.Net
Source/Common/Document/CsvDocumnet.cs
2,993
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.CloudIdentity.Inputs { public sealed class GroupGroupKeyArgs : Pulumi.ResourceArgs { /// <summary> /// The ID of the entity. /// For Google-managed entities, the id must be the email address of an existing /// group or user. /// For external-identity-mapped entities, the id must be a string conforming /// to the Identity Source's requirements. /// Must be unique within a namespace. /// </summary> [Input("id", required: true)] public Input<string> Id { get; set; } = null!; /// <summary> /// The namespace in which the entity exists. /// If not specified, the EntityKey represents a Google-managed entity /// such as a Google user or a Google Group. /// If specified, the EntityKey represents an external-identity-mapped group. /// The namespace must correspond to an identity source created in Admin Console /// and must be in the form of `identitysources/{identity_source_id}`. /// </summary> [Input("namespace")] public Input<string>? Namespace { get; set; } public GroupGroupKeyArgs() { } } }
36.547619
88
0.639739
[ "ECL-2.0", "Apache-2.0" ]
dimpu47/pulumi-gcp
sdk/dotnet/CloudIdentity/Inputs/GroupGroupKeyArgs.cs
1,535
C#
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Windows.Forms; namespace FlatUI { public class FlatProgressBar : Control { private int W; private int H; private int _Value = 0; private int _Maximum = 100; private bool _Pattern = true; private bool _ShowBalloon = true; private bool _PercentSign = false; [Category("Control")] public int Maximum { get { return _Maximum; } set { if (value < _Value) _Value = value; _Maximum = value; Invalidate(); } } [Category("Control")] public int Value { get { return _Value; /* switch (_Value) { case 0: return 0; Invalidate(); break; default: return _Value; Invalidate(); break; } */ } set { if (value > _Maximum) { value = _Maximum; Invalidate(); } _Value = value; Invalidate(); } } public bool Pattern { get { return _Pattern; } set { _Pattern = value; } } public bool ShowBalloon { get { return _ShowBalloon; } set { _ShowBalloon = value; } } public bool PercentSign { get { return _PercentSign; } set { _PercentSign = value; } } [Category("Colors")] public Color ProgressColor { get { return _ProgressColor; } set { _ProgressColor = value; } } [Category("Colors")] public Color DarkerProgress { get { return _DarkerProgress; } set { _DarkerProgress = value; } } protected override void OnResize(EventArgs e) { base.OnResize(e); Height = 42; } protected override void CreateHandle() { base.CreateHandle(); Height = 42; } public void Increment(int Amount) { Value += Amount; } private Color _BaseColor = Color.FromArgb(45, 47, 49); private Color _ProgressColor = Helpers.FlatColor; private Color _DarkerProgress = Color.FromArgb(23, 148, 92); public FlatProgressBar() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true); DoubleBuffered = true; BackColor = Color.FromArgb(60, 70, 73); Height = 42; } protected override void OnPaint(PaintEventArgs e) { this.UpdateColors(); Bitmap B = new Bitmap(Width, Height); Graphics G = Graphics.FromImage(B); W = Width - 1; H = Height - 1; Rectangle Base = new Rectangle(0, 24, W, H); GraphicsPath GP = new GraphicsPath(); GraphicsPath GP2 = new GraphicsPath(); GraphicsPath GP3 = new GraphicsPath(); var _with15 = G; _with15.SmoothingMode = SmoothingMode.HighQuality; _with15.PixelOffsetMode = PixelOffsetMode.HighQuality; _with15.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; _with15.Clear(BackColor); //-- Progress Value //int iValue = Convert.ToInt32(((float)_Value) / ((float)(_Maximum * Width))); float percent = ((float)_Value) / ((float)_Maximum); int iValue = (int)(percent * ((float)Width)); switch (Value) { case 0: //-- Base _with15.FillRectangle(new SolidBrush(_BaseColor), Base); //--Progress _with15.FillRectangle(new SolidBrush(_ProgressColor), new Rectangle(0, 24, iValue - 1, H - 1)); break; case 100: //-- Base _with15.FillRectangle(new SolidBrush(_BaseColor), Base); //--Progress _with15.FillRectangle(new SolidBrush(_ProgressColor), new Rectangle(0, 24, iValue - 1, H - 1)); break; default: //-- Base _with15.FillRectangle(new SolidBrush(_BaseColor), Base); //--Progress GP.AddRectangle(new Rectangle(0, 24, iValue - 1, H - 1)); _with15.FillPath(new SolidBrush(_ProgressColor), GP); if (_Pattern) { //-- Hatch Brush HatchBrush HB = new HatchBrush(HatchStyle.Plaid, _DarkerProgress, _ProgressColor); _with15.FillRectangle(HB, new Rectangle(0, 24, iValue - 1, H - 1)); } if (_ShowBalloon) { //-- Balloon Rectangle Balloon = new Rectangle(iValue - 18, 0, 34, 16); GP2 = Helpers.RoundRec(Balloon, 4); _with15.FillPath(new SolidBrush(_BaseColor), GP2); //-- Arrow GP3 = Helpers.DrawArrow(iValue - 9, 16, true); _with15.FillPath(new SolidBrush(_BaseColor), GP3); //-- Value > You can add "%" > value & "%" string text = (_PercentSign ? Value.ToString() + "%" : Value.ToString()); int wOffset = (_PercentSign ? iValue - 15 : iValue - 11); _with15.DrawString(text, new Font("Segoe UI", 10), new SolidBrush(_ProgressColor), new Rectangle(wOffset, -2, W, H), Helpers.NearSF); } break; } base.OnPaint(e); G.Dispose(); e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; e.Graphics.DrawImageUnscaled(B, 0, 0); B.Dispose(); } private void UpdateColors() { FlatColors colors = Helpers.GetColors(this); _ProgressColor = colors.Flat; } } }
23.088372
147
0.638598
[ "MIT" ]
BlueEyesDev/MultiAccount-DofusRetro
ThemeFlat/FlatProgressBar.cs
4,966
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Diagnostics; using System.Runtime.InteropServices; namespace KiepCommunication.Model { public class TextToSpeech : IDisposable { public Process _TextToSpeechProcess; public TextToSpeech() { _TextToSpeechProcess = new Process(); _TextToSpeechProcess.StartInfo.FileName = "cmd.exe"; _TextToSpeechProcess.StartInfo.RedirectStandardInput = true; _TextToSpeechProcess.StartInfo.RedirectStandardOutput = true; _TextToSpeechProcess.StartInfo.CreateNoWindow = true; _TextToSpeechProcess.StartInfo.UseShellExecute = false; _TextToSpeechProcess.Start(); _TextToSpeechProcess.StandardInput.WriteLine("set PATH=.;.\\lib\\etc"); _TextToSpeechProcess.StandardInput.WriteLine("set HOME=C:"); _TextToSpeechProcess.StandardInput.WriteLine("cd .\\FestivalBinaries\\nextens"); _TextToSpeechProcess.StandardInput.WriteLine("sh -c \"./bin/festival.exe --libdir ./lib"); } #region IDisposable Members public void Dispose() { _TextToSpeechProcess.StandardInput.WriteLine("(quit)"); _TextToSpeechProcess.StandardInput.WriteLine("exit"); _TextToSpeechProcess.WaitForExit(); GC.SuppressFinalize(this); } #endregion public void Say(string text) { if (!String.IsNullOrEmpty(text)) { _TextToSpeechProcess.StandardInput.WriteLine("(SayText \"" + text + "\");"); _TextToSpeechProcess.StandardInput.Flush(); } } } }
29.203125
102
0.648475
[ "MIT" ]
Joozt/KiepCommunicationSoftware
KiepCommunication/Model/TextToSpeech.cs
1,871
C#
using System; using System.Globalization; using System.Xml; namespace NewLife.Serialization { /// <summary>Xml基础类型处理器</summary> public class XmlGeneral : XmlHandlerBase { /// <summary>实例化</summary> public XmlGeneral() { Priority = 10; } /// <summary>写入一个对象</summary> /// <param name="value">目标对象</param> /// <param name="type">类型</param> /// <returns>是否处理成功</returns> public override Boolean Write(Object value, Type type) { if (value == null && type != typeof(String)) return false; var writer = Host.GetWriter(); // 枚举 写入字符串 if (type.IsEnum) { writer.WriteValue(value + ""); return true; } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: writer.WriteValue((Boolean)value); return true; case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Char: writer.WriteValue((Char)value); return true; case TypeCode.DBNull: case TypeCode.Empty: writer.WriteValue((Byte)0); return true; case TypeCode.DateTime: writer.WriteValue(((DateTime)value).ToFullString()); return true; case TypeCode.Decimal: writer.WriteValue((Decimal)value); return true; case TypeCode.Double: writer.WriteValue((Double)value); return true; case TypeCode.Single: writer.WriteValue((Single)value); return true; case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: writer.WriteValue((Int32)value); return true; case TypeCode.Int64: case TypeCode.UInt64: writer.WriteValue((Int64)value); return true; case TypeCode.String: writer.WriteValue(value + ""); return true; case TypeCode.Object: break; default: break; } if (type == typeof(Guid)) { writer.WriteValue(((Guid)value).ToString()); return true; } if (type == typeof(DateTimeOffset)) { writer.WriteValue((DateTimeOffset)value); return true; } if (type == typeof(TimeSpan)) { writer.WriteValue((TimeSpan)value); return true; } if (type == typeof(Byte[])) { var buf = value as Byte[]; writer.WriteBase64(buf, 0, buf.Length); return true; } if (type == typeof(Char[])) { writer.WriteValue(new String((Char[])value)); return true; } return false; } /// <summary>尝试读取</summary> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public override Boolean TryRead(Type type, ref Object value) { if (type == null) { if (value == null) return false; type = value.GetType(); } var reader = Host.GetReader(); if (type == typeof(Guid)) { value = new Guid(reader.ReadContentAsString()); return true; } else if (type == typeof(Byte[])) { // 用字符串长度作为预设缓冲区的长度 var buf = new Byte[reader.Value.Length]; var count = reader.ReadContentAsBase64(buf, 0, buf.Length); value = buf.ReadBytes(0, count); return true; } else if (type == typeof(Char[])) { value = reader.ReadContentAsString().ToCharArray(); return true; } else if (type == typeof(DateTimeOffset)) { value = reader.ReadContentAs(type, null); return true; } else if (type == typeof(TimeSpan)) { value = reader.ReadContentAs(type, null); return true; } var code = Type.GetTypeCode(type); if (code == TypeCode.Object) return false; // 读取异构Xml时可能报错 var v = (reader.NodeType == XmlNodeType.Element ? reader.ReadElementContentAsString() : reader.ReadContentAsString()) + ""; // 枚举 if (type.IsEnum) { value = Enum.Parse(type, v); return true; } switch (code) { case TypeCode.Boolean: value = v.ToBoolean(); return true; case TypeCode.Byte: value = Byte.Parse(v, NumberStyles.HexNumber); return true; case TypeCode.Char: if (v.Length > 0) value = v[0]; return true; case TypeCode.DBNull: value = DBNull.Value; return true; case TypeCode.DateTime: value = v.ToDateTime(); return true; case TypeCode.Decimal: value = (Decimal)v.ToDouble(); return true; case TypeCode.Double: value = v.ToDouble(); return true; case TypeCode.Empty: value = null; return true; case TypeCode.Int16: value = (Int16)v.ToInt(); return true; case TypeCode.Int32: value = v.ToInt(); return true; case TypeCode.Int64: value = Int64.Parse(v); return true; case TypeCode.Object: break; case TypeCode.SByte: value = SByte.Parse(v, NumberStyles.HexNumber); return true; case TypeCode.Single: value = (Single)v.ToDouble(); return true; case TypeCode.String: value = v; return true; case TypeCode.UInt16: value = (UInt16)v.ToInt(); return true; case TypeCode.UInt32: value = (UInt32)v.ToInt(); return true; case TypeCode.UInt64: value = UInt64.Parse(v); return true; default: break; } return false; } } }
33.208696
136
0.408615
[ "MIT" ]
NewLifeX/X_NET40
NewLife.Core/Serialization/Xml/XmlGeneral.cs
7,772
C#
// ********************************************************************* // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License // ********************************************************************* using System; using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.StreamProcessing.Internal; using Microsoft.StreamProcessing.Internal.Collections; namespace Microsoft.StreamProcessing { [DataContract] internal sealed class CompiledPartitionedAfaPipe_EventList<TKey, TPayload, TRegister, TAccumulator, TPartitionKey> : CompiledAfaPipeBase<TKey, TPayload, TRegister, TAccumulator> { private readonly Func<TKey, TPartitionKey> getPartitionKey = GetPartitionExtractor<TPartitionKey, TKey>(); [DataMember] private FastMap<GroupedActiveState<TKey, TRegister>> activeStates; private FastMap<GroupedActiveState<TKey, TRegister>>.FindTraverser activeFindTraverser; // The follow three fields' keys need to be updated in lock step [DataMember] private FastDictionary2<TPartitionKey, FastMap<SavedEventList<TKey, TPayload>>> currentTimestampEventList = new FastDictionary2<TPartitionKey, FastMap<SavedEventList<TKey, TPayload>>>(); [DataMember] private FastDictionary2<TPartitionKey, long> lastSyncTime = new FastDictionary2<TPartitionKey, long>(); // Field instead of local variable to avoid re-initializing it private readonly Stack<int> stack = new Stack<int>(); [Obsolete("Used only by serialization. Do not call directly.")] public CompiledPartitionedAfaPipe_EventList() { } public CompiledPartitionedAfaPipe_EventList(Streamable<TKey, TRegister> stream, IStreamObserver<TKey, TRegister> observer, object afa, long maxDuration) : base(stream, observer, afa, maxDuration) { this.activeStates = new FastMap<GroupedActiveState<TKey, TRegister>>(); this.activeFindTraverser = new FastMap<GroupedActiveState<TKey, TRegister>>.FindTraverser(this.activeStates); } public override int CurrentlyBufferedInputCount => this.activeStates.Count; private void ProcessCurrentTimestamp(int partitionIndex) { if (this.currentTimestampEventList.Count == 0) return; long synctime = this.lastSyncTime.entries[partitionIndex].value; var allEventListTraverser = new FastMap<SavedEventList<TKey, TPayload>>.VisibleTraverser(this.currentTimestampEventList.entries[partitionIndex].value) { currIndex = 0 }; while (allEventListTraverser.Next(out int el_index, out int el_hash)) { var currentList = this.currentTimestampEventList.entries[partitionIndex].value.Values[el_index]; /* (1) Process currently active states */ bool ended = true; if (this.activeFindTraverser.Find(el_hash)) { int orig_index; // Track which active states need to be inserted after the current traversal var newActiveStates = new List<GroupedActiveState<TKey, TRegister>>(); while (this.activeFindTraverser.Next(out int index)) { orig_index = index; var state = this.activeStates.Values[index]; if (!this.keyEqualityComparer(state.key, currentList.key)) continue; if (state.PatternStartTimestamp + this.MaxDuration > synctime) { #region eventListStateMap if (this.eventListStateMap != null) { var currentStateMap = this.eventListStateMap[state.state]; if (currentStateMap != null) { var m = currentStateMap.Length; for (int cnt = 0; cnt < m; cnt++) { var arcinfo = currentStateMap[cnt]; if (arcinfo.Fence(synctime, currentList.payloads, state.register)) { var newReg = arcinfo.Transfer == null ? state.register : arcinfo.Transfer(synctime, currentList.payloads, state.register); int ns = arcinfo.toState; while (true) { if (this.isFinal[ns]) { this.batch.vsync.col[this.iter] = synctime; this.batch.vother.col[this.iter] = Math.Min(state.PatternStartTimestamp + this.MaxDuration, StreamEvent.InfinitySyncTime); this.batch[this.iter] = newReg; this.batch.key.col[this.iter] = currentList.key; this.batch.hash.col[this.iter] = el_hash; this.iter++; if (this.iter == Config.DataBatchSize) FlushContents(); } if (this.hasOutgoingArcs[ns]) { // Since we will eventually remove this state/index from activeStates, attempt to reuse this index for the outgoing state instead of deleting/re-adding // If index is already -1, this means we've already reused the state and must allocate/insert a new index for the outgoing state. if (index != -1) { this.activeStates.Values[index].key = currentList.key; this.activeStates.Values[index].state = ns; this.activeStates.Values[index].register = newReg; this.activeStates.Values[index].PatternStartTimestamp = state.PatternStartTimestamp; index = -1; } else { // Do not attempt to insert directly into activeStates, as that could corrupt the traversal state. newActiveStates.Add(new GroupedActiveState<TKey, TRegister> { key = currentList.key, state = ns, register = newReg, PatternStartTimestamp = state.PatternStartTimestamp, }); } ended = false; // Add epsilon arc destinations to stack if (this.epsilonStateMap == null) break; if (this.epsilonStateMap[ns] != null) { for (int cnt2 = 0; cnt2 < this.epsilonStateMap[ns].Length; cnt2++) this.stack.Push(this.epsilonStateMap[ns][cnt2]); } } if (this.stack.Count == 0) break; ns = this.stack.Pop(); } if (this.IsDeterministic) break; // We are guaranteed to have only one successful transition } } } } #endregion #region singleEventStateMap if ((this.singleEventStateMap != null) && (currentList.payloads.Count == 1)) { var currentStateMap = this.singleEventStateMap[state.state]; if (currentStateMap != null) { var m = currentStateMap.Length; for (int cnt = 0; cnt < m; cnt++) { var arcinfo = currentStateMap[cnt]; if (arcinfo.Fence(synctime, currentList.payloads[0], state.register)) { var newReg = arcinfo.Transfer == null ? state.register : arcinfo.Transfer(synctime, currentList.payloads[0], state.register); int ns = arcinfo.toState; while (true) { if (this.isFinal[ns]) { this.batch.vsync.col[this.iter] = synctime; this.batch.vother.col[this.iter] = Math.Min(state.PatternStartTimestamp + this.MaxDuration, StreamEvent.InfinitySyncTime); this.batch[this.iter] = newReg; this.batch.key.col[this.iter] = currentList.key; this.batch.hash.col[this.iter] = el_hash; this.iter++; if (this.iter == Config.DataBatchSize) FlushContents(); } if (this.hasOutgoingArcs[ns]) { // Since we will eventually remove this state/index from activeStates, attempt to reuse this index for the outgoing state instead of deleting/re-adding // If index is already -1, this means we've already reused the state and must allocate/insert a new index for the outgoing state. if (index != -1) { this.activeStates.Values[index].key = currentList.key; this.activeStates.Values[index].state = ns; this.activeStates.Values[index].register = newReg; this.activeStates.Values[index].PatternStartTimestamp = state.PatternStartTimestamp; index = -1; } else { // Do not attempt to insert directly into activeStates, as that could corrupt the traversal state. newActiveStates.Add(new GroupedActiveState<TKey, TRegister> { key = currentList.key, state = ns, register = newReg, PatternStartTimestamp = state.PatternStartTimestamp, }); } ended = false; // Add epsilon arc destinations to stack if (this.epsilonStateMap == null) break; if (this.epsilonStateMap[ns] != null) { for (int cnt2 = 0; cnt2 < this.epsilonStateMap[ns].Length; cnt2++) this.stack.Push(this.epsilonStateMap[ns][cnt2]); } } if (this.stack.Count == 0) break; ns = this.stack.Pop(); } if (this.IsDeterministic) break; // We are guaranteed to have only one successful transition } } } } #endregion } if (index == orig_index) this.activeFindTraverser.Remove(); if (this.IsDeterministic) break; // We are guaranteed to have only one active state } // Now that we are done traversing the current active states, add any new ones. foreach (var newActiveState in newActiveStates) { this.activeStates.Insert(el_hash, newActiveState); } } /* (2) Start new activations from the start state(s) */ if (!this.AllowOverlappingInstances && !ended) continue; for (int counter = 0; counter < this.numStartStates; counter++) { int startState = this.startStates[counter]; #region eventListStateMap if (this.eventListStateMap != null) { var startStateMap = this.eventListStateMap[startState]; if (startStateMap != null) { var m = startStateMap.Length; for (int cnt = 0; cnt < m; cnt++) { var arcinfo = startStateMap[cnt]; if (arcinfo.Fence(synctime, currentList.payloads, this.defaultRegister)) { var newReg = arcinfo.Transfer == null ? this.defaultRegister : arcinfo.Transfer(synctime, currentList.payloads, this.defaultRegister); int ns = arcinfo.toState; while (true) { if (this.isFinal[ns]) { this.batch.vsync.col[this.iter] = synctime; this.batch.vother.col[this.iter] = Math.Min(synctime + this.MaxDuration, StreamEvent.InfinitySyncTime); this.batch[this.iter] = newReg; this.batch.key.col[this.iter] = currentList.key; this.batch.hash.col[this.iter] = el_hash; this.iter++; if (this.iter == Config.DataBatchSize) FlushContents(); } if (this.hasOutgoingArcs[ns]) { int index = this.activeStates.Insert(el_hash); this.activeStates.Values[index].key = currentList.key; this.activeStates.Values[index].state = ns; this.activeStates.Values[index].register = newReg; this.activeStates.Values[index].PatternStartTimestamp = synctime; // Add epsilon arc destinations to stack if (this.epsilonStateMap == null) break; if (this.epsilonStateMap[ns] != null) { for (int cnt2 = 0; cnt2 < this.epsilonStateMap[ns].Length; cnt2++) this.stack.Push(this.epsilonStateMap[ns][cnt2]); } } if (this.stack.Count == 0) break; ns = this.stack.Pop(); } if (this.IsDeterministic) break; // We are guaranteed to have only one successful transition } } } } #endregion #region singleEventStateMap if ((this.singleEventStateMap != null) && (currentList.payloads.Count == 1)) { var startStateMap = this.singleEventStateMap[startState]; if (startStateMap != null) { var m = startStateMap.Length; for (int cnt = 0; cnt < m; cnt++) { var arcinfo = startStateMap[cnt]; if (arcinfo.Fence(synctime, currentList.payloads[0], this.defaultRegister)) { var newReg = arcinfo.Transfer == null ? this.defaultRegister : arcinfo.Transfer(synctime, currentList.payloads[0], this.defaultRegister); int ns = arcinfo.toState; while (true) { if (this.isFinal[ns]) { this.batch.vsync.col[this.iter] = synctime; this.batch.vother.col[this.iter] = Math.Min(synctime + this.MaxDuration, StreamEvent.InfinitySyncTime); this.batch[this.iter] = newReg; this.batch.key.col[this.iter] = currentList.key; this.batch.hash.col[this.iter] = el_hash; this.iter++; if (this.iter == Config.DataBatchSize) FlushContents(); } if (this.hasOutgoingArcs[ns]) { int index = this.activeStates.Insert(el_hash); this.activeStates.Values[index].key = currentList.key; this.activeStates.Values[index].state = ns; this.activeStates.Values[index].register = newReg; this.activeStates.Values[index].PatternStartTimestamp = synctime; // Add epsilon arc destinations to stack if (this.epsilonStateMap == null) break; if (this.epsilonStateMap[ns] != null) { for (int cnt2 = 0; cnt2 < this.epsilonStateMap[ns].Length; cnt2++) this.stack.Push(this.epsilonStateMap[ns][cnt2]); } } if (this.stack.Count == 0) break; ns = this.stack.Pop(); } if (this.IsDeterministic) break; // We are guaranteed to have only one successful transition } } } } #endregion if (this.IsDeterministic) break; // We are guaranteed to have only one start state } } this.currentTimestampEventList.entries[partitionIndex].value.Clear(); } public override unsafe void OnNext(StreamMessage<TKey, TPayload> batch) { var count = batch.Count; var srckey = batch.key.col; fixed (long* src_bv = batch.bitvector.col, src_vsync = batch.vsync.col, src_vother = batch.vother.col) { fixed (int* src_hash = batch.hash.col) { for (int i = 0; i < count; i++) { if ((src_bv[i >> 6] & (1L << (i & 0x3f))) == 0) { var partitionKey = this.getPartitionKey(srckey[i]); int partitionIndex = EnsurePartition(partitionKey); long synctime = src_vsync[i]; int index; if (synctime > this.lastSyncTime.entries[partitionIndex].value) // move time forward { ProcessCurrentTimestamp(partitionIndex); this.lastSyncTime.entries[partitionIndex].value = synctime; } bool done = false; var eventListTraverser = new FastMap<SavedEventList<TKey, TPayload>>.FindTraverser(this.currentTimestampEventList.entries[partitionIndex].value); if (eventListTraverser.Find(src_hash[i])) { while (eventListTraverser.Next(out index)) { var state = this.currentTimestampEventList.entries[partitionIndex].value.Values[index]; if (this.keyEqualityComparer(state.key, srckey[i])) { state.payloads.Add(batch.payload.col[i]); done = true; break; } } } if (!done) { index = this.currentTimestampEventList.entries[partitionIndex].value.Insert(src_hash[i]); var list = new List<TPayload>(10) { batch[i] }; this.currentTimestampEventList.entries[partitionIndex].value.Values[index] = new SavedEventList<TKey, TPayload> { key = srckey[i], payloads = list }; } } else if (src_vother[i] == PartitionedStreamEvent.LowWatermarkOtherTime) { long synctime = src_vsync[i]; int partitionIndex = FastDictionary2<TPartitionKey, List<TKey>>.IteratorStart; while (this.lastSyncTime.Iterate(ref partitionIndex)) { if (synctime > this.lastSyncTime.entries[partitionIndex].value) // move time forward { ProcessCurrentTimestamp(partitionIndex); this.lastSyncTime.entries[partitionIndex].value = synctime; } } OnLowWatermark(synctime); } else if (src_vother[i] == PartitionedStreamEvent.PunctuationOtherTime) { var partitionKey = this.getPartitionKey(srckey[i]); int partitionIndex = EnsurePartition(partitionKey); long synctime = src_vsync[i]; if (synctime > this.lastSyncTime.entries[partitionIndex].value) // move time forward { ProcessCurrentTimestamp(partitionIndex); this.lastSyncTime.entries[partitionIndex].value = synctime; } } } } } batch.Free(); } private int EnsurePartition(TPartitionKey partitionKey) { if (!this.lastSyncTime.Lookup(partitionKey, out int index)) { this.lastSyncTime.Insert(partitionKey, long.MinValue); index = this.currentTimestampEventList.Insert(partitionKey, new FastMap<SavedEventList<TKey, TPayload>>()); } return index; } protected override void UpdatePointers() => this.activeFindTraverser = new FastMap<GroupedActiveState<TKey, TRegister>>.FindTraverser(this.activeStates); } }
59.380952
203
0.392469
[ "MIT" ]
Chaycej/Trill
Sources/Core/Microsoft.StreamProcessing/Operators/Afa/CompiledPartitionedAfaPipe_EventList.cs
27,436
C#
using System; using System.Net; namespace ExceptionMiddleware.Errors { public class NotFoundException : InvalidRestOperationException { #region Properties public override int ResponseCode => (int) HttpStatusCode.NotFound; #endregion #region Constructors public NotFoundException(int id, string typeName, string customError, string additionalMessage = "", Exception innerException = null) : this(id.ToString(), typeName, customError, additionalMessage, innerException) { } public NotFoundException(string id, string typeName, string customError, string additionalMessage = "", Exception innerException = null) : base($"No {typeName} with Id: {id} was found." + additionalMessage, customError, innerException) { } #endregion } }
29.4
111
0.656463
[ "MIT" ]
DesselBane/ExceptionMiddleware
Errors/NotFoundException.cs
884
C#
 #region License, Terms and Conditions // // IPaymentProfileAttributes.cs // // Authors: Kori Francis <twitter.com/djbyter>, David Ball // Copyright (C) 2010 Clinical Support Systems, Inc. All rights reserved. // // THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #endregion // ReSharper disable once CheckNamespace namespace ChargifyNET { #region Imports using System; using System.Xml.Serialization; #endregion /// <summary> /// The types of credit cards supported by Chargify internally /// </summary> public enum CardType { /// <summary> /// Visa /// </summary> [XmlEnum("visa")] Visa, /// <summary> /// Mastercard /// </summary> [XmlEnum("master")] Master, /// <summary> /// Discover /// </summary> [XmlEnum("discover")] Discover, /// <summary> /// American Express /// </summary> [XmlEnum("american_express")] American_Express, /// <summary> /// Diners Club /// </summary> [XmlEnum("diners_club")] Diners_Club, /// <summary> /// JCB /// </summary> [XmlEnum("jcb")] JCB, /// <summary> /// Switch /// </summary> [XmlEnum("switch")] Switch, /// <summary> /// Solo /// </summary> [XmlEnum("solo")] Solo, /// <summary> /// Dankort /// </summary> [XmlEnum("dankort")] Dankort, /// <summary> /// Maestro /// </summary> [XmlEnum("maestro")] Maestro, /// <summary> /// Forbrugsforeningen /// </summary> [XmlEnum("forbrugsforeningen")] Forbrugsforeningen, /// <summary> /// Laser /// </summary> [XmlEnum("laser")] Laser, /// <summary> /// Internal value used to determine if the field has been set. /// </summary> Unknown = -1 } /// <summary> /// The vaults supported by Chargify for importing /// </summary> public enum VaultType { /// <summary> /// Authorize.NET /// </summary> [XmlEnum("authorizenet")] AuthorizeNET, /// <summary> /// Trust Commerce /// </summary> [XmlEnum("trust_commerce")] Trust_Commerce, /// <summary> /// Payment Express /// </summary> [XmlEnum("payment_express")] Payment_Express, /// <summary> /// Beanstream /// </summary> [XmlEnum("beanstream")] Beanstream, /// <summary> /// Braintree Version 1 (Orange) /// </summary> [XmlEnum("braintree1")] Braintree1, /// <summary> /// Braintree Blue /// </summary> [XmlEnum("braintree_blue")] Braintree_Blue, /// <summary> /// PayPal /// </summary> [XmlEnum("paypal")] PayPal, /// <summary> /// QuickPay /// </summary> [XmlEnum("quickpay")] QuickPay, /// <summary> /// Eway /// </summary> [XmlEnum("eway")] Eway, /// <summary> /// Eway /// </summary> [XmlEnum("eway_rapid_std")] EwayRapidStd, /// <summary> /// Stripe /// </summary> [XmlEnum("stripe")] Stripe, /// <summary> /// Pin /// </summary> [XmlEnum("pin")] Pin, /// <summary> /// Wirecard /// </summary> [XmlEnum("wirecard")] Wirecard, /// <summary> /// Bpoint /// </summary> [XmlEnum("bpoint")] Bpoint, /// <summary> /// FirstData /// </summary> [XmlEnum("firstdata")] FirstData, /// <summary> /// Elavon Virtual Merchant Gateway /// </summary> [XmlEnum("elavon")] Elavon, /// <summary> /// CyberSource /// </summary> [XmlEnum("cybersource")] CyberSource, /// <summary> /// PayMill /// </summary> [XmlEnum("paymill")] PayMill, /// <summary> /// Litle /// </summary> [XmlEnum("litle")] Litle, /// <summary> /// Moneris /// </summary> [XmlEnum("moneris")] Moneris, /// <summary> /// Internal value used to determine if the field has been set. /// </summary> Unknown = -1 } /// <summary> /// The type of bank account /// </summary> public enum BankAccountType { /// <summary> /// Checking /// </summary> [XmlEnum("checking")] Checking, /// <summary> /// Savings /// </summary> [XmlEnum("savings")] Savings, /// <summary> /// Internal value used to determine if the field has been set. /// </summary> Unknown = -1 } /// <summary> /// The primary account purpose /// </summary> public enum BankAccountHolderType { /// <summary> /// Personal /// </summary> [XmlEnum("personal")] Personal, /// <summary> /// Buisiness /// </summary> [XmlEnum("business")] Business, /// <summary> /// Internal value used to determine if the field has been set. /// </summary> Unknown = -1 } /// <summary> /// Class which can be used to "import" subscriptions via the API into Chargify /// Info here: http://support.chargify.com/faqs/api/api-subscription-and-stored-card-token-imports /// </summary> public interface IPaymentProfileAttributes : IComparable<IPaymentProfileAttributes> { /// <summary> /// The "token" provided by your vault storage for an already stored payment profile /// </summary> string VaultToken { get; set; } /// <summary> /// (Only for Authorize.NET CIM storage) The "customerProfileId" for the owner of the /// "customerPaymentProfileId" provided as the VaultToken /// </summary> string CustomerVaultToken { get; set; } /// <summary> /// The vault that stores the payment profile with the provided VaultToken /// </summary> VaultType CurrentVault { get; set; } /// <summary> /// The year of expiration /// </summary> int ExpirationYear { get; set; } /// <summary> /// The month of expiration /// </summary> int ExpirationMonth { get; set; } /// <summary> /// (Optional) If you know the card type, you may supply it here so that we may display /// the card type in the UI. /// </summary> CardType CardType { get; set; } /// <summary> /// (Optional) If you have the last 4 digits of the credit card number, you may supply /// them here so we may create a masked card number for display in the UI /// </summary> string LastFour { get; set; } /// <summary> /// The name of the bank where the customer's account resides /// </summary> string BankName { get; set; } /// <summary> /// The routing number of the bank /// </summary> string BankRoutingNumber { get; set; } /// <summary> /// The customer's bank account number /// </summary> string BankAccountNumber { get; set; } /// <summary> /// Either checking or savings /// </summary> BankAccountType BankAccountType { get; set; } /// <summary> /// Either personal or business /// </summary> BankAccountHolderType BankAccountHolderType { get; set; } } }
28.468944
102
0.519908
[ "MIT" ]
EdLichtman/chargify-dot-net
Source/ChargifyDotNet/Interfaces/IPaymentProfileAttributes.cs
9,169
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticLoadBalancing.Model { /// <summary> /// Information about a load balancer. /// </summary> public partial class LoadBalancerDescription { private List<string> _availabilityZones = new List<string>(); private List<BackendServerDescription> _backendServerDescriptions = new List<BackendServerDescription>(); private string _canonicalHostedZoneName; private string _canonicalHostedZoneNameID; private DateTime? _createdTime; private string _dnsName; private HealthCheck _healthCheck; private List<Instance> _instances = new List<Instance>(); private List<ListenerDescription> _listenerDescriptions = new List<ListenerDescription>(); private string _loadBalancerName; private Policies _policies; private string _scheme; private List<string> _securityGroups = new List<string>(); private SourceSecurityGroup _sourceSecurityGroup; private List<string> _subnets = new List<string>(); private string _vpcId; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public LoadBalancerDescription() { } /// <summary> /// Gets and sets the property AvailabilityZones. /// <para> /// The Availability Zones for the load balancer. /// </para> /// </summary> public List<string> AvailabilityZones { get { return this._availabilityZones; } set { this._availabilityZones = value; } } // Check to see if AvailabilityZones property is set internal bool IsSetAvailabilityZones() { return this._availabilityZones != null && this._availabilityZones.Count > 0; } /// <summary> /// Gets and sets the property BackendServerDescriptions. /// <para> /// Information about your EC2 instances. /// </para> /// </summary> public List<BackendServerDescription> BackendServerDescriptions { get { return this._backendServerDescriptions; } set { this._backendServerDescriptions = value; } } // Check to see if BackendServerDescriptions property is set internal bool IsSetBackendServerDescriptions() { return this._backendServerDescriptions != null && this._backendServerDescriptions.Count > 0; } /// <summary> /// Gets and sets the property CanonicalHostedZoneName. /// <para> /// The DNS name of the load balancer. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/using-domain-names-with-elb.html">Configure /// a Custom Domain Name</a> in the <i>Classic Load Balancers Guide</i>. /// </para> /// </summary> public string CanonicalHostedZoneName { get { return this._canonicalHostedZoneName; } set { this._canonicalHostedZoneName = value; } } // Check to see if CanonicalHostedZoneName property is set internal bool IsSetCanonicalHostedZoneName() { return this._canonicalHostedZoneName != null; } /// <summary> /// Gets and sets the property CanonicalHostedZoneNameID. /// <para> /// The ID of the Amazon Route 53 hosted zone for the load balancer. /// </para> /// </summary> public string CanonicalHostedZoneNameID { get { return this._canonicalHostedZoneNameID; } set { this._canonicalHostedZoneNameID = value; } } // Check to see if CanonicalHostedZoneNameID property is set internal bool IsSetCanonicalHostedZoneNameID() { return this._canonicalHostedZoneNameID != null; } /// <summary> /// Gets and sets the property CreatedTime. /// <para> /// The date and time the load balancer was created. /// </para> /// </summary> public DateTime CreatedTime { get { return this._createdTime.GetValueOrDefault(); } set { this._createdTime = value; } } // Check to see if CreatedTime property is set internal bool IsSetCreatedTime() { return this._createdTime.HasValue; } /// <summary> /// Gets and sets the property DNSName. /// <para> /// The DNS name of the load balancer. /// </para> /// </summary> public string DNSName { get { return this._dnsName; } set { this._dnsName = value; } } // Check to see if DNSName property is set internal bool IsSetDNSName() { return this._dnsName != null; } /// <summary> /// Gets and sets the property HealthCheck. /// <para> /// Information about the health checks conducted on the load balancer. /// </para> /// </summary> public HealthCheck HealthCheck { get { return this._healthCheck; } set { this._healthCheck = value; } } // Check to see if HealthCheck property is set internal bool IsSetHealthCheck() { return this._healthCheck != null; } /// <summary> /// Gets and sets the property Instances. /// <para> /// The IDs of the instances for the load balancer. /// </para> /// </summary> public List<Instance> Instances { get { return this._instances; } set { this._instances = value; } } // Check to see if Instances property is set internal bool IsSetInstances() { return this._instances != null && this._instances.Count > 0; } /// <summary> /// Gets and sets the property ListenerDescriptions. /// <para> /// The listeners for the load balancer. /// </para> /// </summary> public List<ListenerDescription> ListenerDescriptions { get { return this._listenerDescriptions; } set { this._listenerDescriptions = value; } } // Check to see if ListenerDescriptions property is set internal bool IsSetListenerDescriptions() { return this._listenerDescriptions != null && this._listenerDescriptions.Count > 0; } /// <summary> /// Gets and sets the property LoadBalancerName. /// <para> /// The name of the load balancer. /// </para> /// </summary> public string LoadBalancerName { get { return this._loadBalancerName; } set { this._loadBalancerName = value; } } // Check to see if LoadBalancerName property is set internal bool IsSetLoadBalancerName() { return this._loadBalancerName != null; } /// <summary> /// Gets and sets the property Policies. /// <para> /// The policies defined for the load balancer. /// </para> /// </summary> public Policies Policies { get { return this._policies; } set { this._policies = value; } } // Check to see if Policies property is set internal bool IsSetPolicies() { return this._policies != null; } /// <summary> /// Gets and sets the property Scheme. /// <para> /// The type of load balancer. Valid only for load balancers in a VPC. /// </para> /// /// <para> /// If <code>Scheme</code> is <code>internet-facing</code>, the load balancer has a public /// DNS name that resolves to a public IP address. /// </para> /// /// <para> /// If <code>Scheme</code> is <code>internal</code>, the load balancer has a public DNS /// name that resolves to a private IP address. /// </para> /// </summary> public string Scheme { get { return this._scheme; } set { this._scheme = value; } } // Check to see if Scheme property is set internal bool IsSetScheme() { return this._scheme != null; } /// <summary> /// Gets and sets the property SecurityGroups. /// <para> /// The security groups for the load balancer. Valid only for load balancers in a VPC. /// </para> /// </summary> public List<string> SecurityGroups { get { return this._securityGroups; } set { this._securityGroups = value; } } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this._securityGroups != null && this._securityGroups.Count > 0; } /// <summary> /// Gets and sets the property SourceSecurityGroup. /// <para> /// The security group for the load balancer, which you can use as part of your inbound /// rules for your registered instances. To only allow traffic from load balancers, add /// a security group rule that specifies this source security group as the inbound source. /// </para> /// </summary> public SourceSecurityGroup SourceSecurityGroup { get { return this._sourceSecurityGroup; } set { this._sourceSecurityGroup = value; } } // Check to see if SourceSecurityGroup property is set internal bool IsSetSourceSecurityGroup() { return this._sourceSecurityGroup != null; } /// <summary> /// Gets and sets the property Subnets. /// <para> /// The IDs of the subnets for the load balancer. /// </para> /// </summary> public List<string> Subnets { get { return this._subnets; } set { this._subnets = value; } } // Check to see if Subnets property is set internal bool IsSetSubnets() { return this._subnets != null && this._subnets.Count > 0; } /// <summary> /// Gets and sets the property VPCId. /// <para> /// The ID of the VPC for the load balancer. /// </para> /// </summary> public string VPCId { get { return this._vpcId; } set { this._vpcId = value; } } // Check to see if VPCId property is set internal bool IsSetVPCId() { return this._vpcId != null; } } }
32.755495
154
0.570829
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/ElasticLoadBalancing/Generated/Model/LoadBalancerDescription.cs
11,923
C#
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; namespace BananaLoader.Tomlyn.Syntax { /// <summary> /// An inline table TOML syntax node. /// </summary> public sealed class InlineTableSyntax : ValueSyntax { private SyntaxToken _openBrace; private SyntaxToken _closeBrace; /// <summary> /// Creates a new instance of an <see cref="InlineTableSyntax"/> /// </summary> public InlineTableSyntax() : base(SyntaxKind.InlineTable) { Items = new SyntaxList<InlineTableItemSyntax>() { Parent = this }; } /// <summary> /// Creates a new instance of an <see cref="InlineTableSyntax"/> /// </summary> /// <param name="keyValues">The key values of this inline table</param> public InlineTableSyntax(params KeyValueSyntax[] keyValues) : this() { if (keyValues == null) throw new ArgumentNullException(nameof(keyValues)); OpenBrace = SyntaxFactory.Token(TokenKind.OpenBrace).AddTrailingWhitespace(); CloseBrace = SyntaxFactory.Token(TokenKind.CloseBrace).AddLeadingWhitespace(); for (var i = 0; i < keyValues.Length; i++) { var keyValue = keyValues[i]; Items.Add(new InlineTableItemSyntax(keyValue) { Comma = (i + 1 < keyValues.Length) ? SyntaxFactory.Token(TokenKind.Comma).AddTrailingWhitespace() : null }); } } /// <summary> /// The token open brace `{` /// </summary> public SyntaxToken OpenBrace { get => _openBrace; set => ParentToThis(ref _openBrace, value, TokenKind.OpenBrace); } /// <summary> /// The items of this table. /// </summary> public SyntaxList<InlineTableItemSyntax> Items { get; } /// <summary> /// The token close brace `}` /// </summary> public SyntaxToken CloseBrace { get => _closeBrace; set => ParentToThis(ref _closeBrace, value, TokenKind.CloseBrace); } public override void Accept(SyntaxVisitor visitor) { visitor.Visit(this); } public override int ChildrenCount => 3; protected override SyntaxNode GetChildrenImpl(int index) { switch (index) { case 0: return OpenBrace; case 1: return Items; default: return CloseBrace; } } } }
32.206897
124
0.549251
[ "Apache-2.0", "MIT" ]
NaNraptor/BananaLoader
BananaLoader.AssemblyGenerator/Tomlyn/Syntax/InlineTableSyntax.cs
2,802
C#
using Microsoft.Azure.Cosmos; using Microsoft.Azure.Cosmos.Fluent; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; namespace Community.Azure.Cosmos { public static class DependencyInjectionExtensions { private static readonly Dictionary<IServiceCollection, HashSet<string>> RegisteredClients = new(); /// <summary> /// Add <see cref="CosmosClient"/> with id and <see cref="CosmosClientFactory"/> to access client by it's id. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="builder">The cosmos client configuration.</param> /// <param name="clientId">The cosmos client id. Will be used to get client from factory. Should be unique.</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException">In case of cosmos client with given id already added.</exception> public static IServiceCollection AddCosmosClient(this IServiceCollection services, Func<IServiceProvider, CosmosClientBuilder> builder, string clientId = CosmosClientFactory.DefaultCosmosClientId) { if (services is null) { throw new ArgumentNullException(nameof(services)); } if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (!RegisteredClients.TryGetValue(services, out var clients)) { clients = new HashSet<string>(); RegisteredClients.Add(services, clients); } if (clients.Contains(clientId)) { throw new InvalidOperationException($"CosmosClient with id {clientId} already registered"); } clients.Add(clientId); services.TryAddSingleton(sp => new CosmosClientFactory(sp)); services.AddSingleton(sp => new CosmosClientWrapper(new Lazy<CosmosClient>(() => builder(sp).Build(), LazyThreadSafetyMode.ExecutionAndPublication), clientId)); return services; } /// <summary> /// Add <see cref="CosmosDatabase{TDatabase}"/> to service collection as a <see cref="ServiceLifetime.Singleton"/> if the service type hasn't already been registered. /// </summary> /// <typeparam name="TDatabase">Type to reference database</typeparam> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="createIfNotExists">Whether to create database if it not exists.</param> /// <param name="databaseId">The database id</param> /// <param name="throughput">Optional. The <see cref="ThroughputProperties"/> for the newly created database.</param> /// <param name="clientId">The cosmos client id to work with database. Should be registered in advance by executing <see cref="AddCosmosClient"/> method.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException">In case of cosmos client with given id not added in advance.</exception> public static IServiceCollection AddCosmosDatabase<TDatabase>( this IServiceCollection services, bool createIfNotExists, string databaseId, ThroughputProperties? throughput = null, string clientId = CosmosClientFactory.DefaultCosmosClientId) { return services.AddCosmosDatabase<TDatabase>(createIfNotExists, (sp) => databaseId, (sp) => throughput, clientId); } /// <summary> /// Add <see cref="CosmosDatabase{TDatabase}"/> to service collection as a <see cref="ServiceLifetime.Singleton"/> if the service type hasn't already been registered. /// </summary> /// <typeparam name="TDatabase">Type to reference database</typeparam> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="createIfNotExists">Whether to create database if it not exists.</param> /// <param name="databaseId">The database id</param> /// <param name="throughput">Optional. The <see cref="ThroughputProperties"/> for the newly created database.</param> /// <param name="clientId">The cosmos client id to work with database. Should be registered in advance by executing <see cref="AddCosmosClient"/> method.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidOperationException">In case of cosmos client with given id not added in advance.</exception> public static IServiceCollection AddCosmosDatabase<TDatabase>( this IServiceCollection services, bool createIfNotExists, Func<IServiceProvider, string> databaseId, Func<IServiceProvider, ThroughputProperties?>? throughputProperties = null, string clientId = CosmosClientFactory.DefaultCosmosClientId) { if (services is null) { throw new ArgumentNullException(nameof(services)); } if (databaseId is null) { throw new ArgumentNullException(nameof(databaseId)); } if (RegisteredClients.TryGetValue(services, out var clients) && clients.Contains(clientId)) { services.TryAddSingleton(sp => { Lazy<CosmosClient> client = sp.GetRequiredService<CosmosClientFactory>().GetCosmosClientLazy(clientId); return new CosmosDatabase<TDatabase>(client, databaseId(sp), throughputProperties?.Invoke(sp), createIfNotExists); }); } else { throw new InvalidOperationException($"CosmosClien with id {clientId} not registered. Call {nameof(AddCosmosClient)} method first"); }; return services; } /// <summary> /// Add <see cref="CosmosContainer{TContainer}"/> to service collection as a <see cref="ServiceLifetime.Singleton"/> if the service type hasn't already been registered. Container should be created in advance. /// </summary> /// <typeparam name="TDatabase">Type to reference database</typeparam> /// <typeparam name="TContainer">Type to reference container</typeparam> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="containerId">The container/collection id</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IServiceCollection AddCosmosContainer<TDatabase, TContainer>( this IServiceCollection services, string containerId) { return services.AddCosmosContainer<TDatabase, TContainer>(false, sp => new ContainerProperties(containerId, "/any")); } /// <summary> /// Add <see cref="CosmosContainer{TContainer}"/> to service collection as a <see cref="ServiceLifetime.Singleton"/> if the service type hasn't already been registered. /// </summary> /// <typeparam name="TDatabase">Type to reference database</typeparam> /// <typeparam name="TContainer">Type to reference container</typeparam> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="createIfNotExists">Whether to create container if it not exists.</param> /// <param name="containerProperties">The container properties.</param> /// <param name="throughputProperties">The <see cref="ThroughputProperties"/> for the newly created container.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IServiceCollection AddCosmosContainer<TDatabase, TContainer>( this IServiceCollection services, bool createIfNotExists, Func<IServiceProvider, ContainerProperties> containerProperties, Func<IServiceProvider, ThroughputProperties>? throughputProperties = null) { if (services is null) { throw new ArgumentNullException(nameof(services)); } if (!services.Any(d => d.ServiceType == typeof(CosmosDatabase<TDatabase>))) { throw new InvalidOperationException($"CosmosDatabase with type {typeof(CosmosDatabase<TDatabase>)} not added. Call {nameof(AddCosmosDatabase)} method first"); } services.TryAddSingleton(sp => { return new CosmosContainer<TContainer>(sp.GetRequiredService<CosmosDatabase<TDatabase>>(), createIfNotExists, containerProperties(sp), throughputProperties?.Invoke(sp)); }); return services; } } }
52.392045
216
0.642338
[ "MIT" ]
IharYakimush/Azure
Community.Azure.Cosmos/DependencyInjectionExtensions.cs
9,223
C#
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Irony.CompilerServices { public class TerminalLookupTable : Dictionary<char, TerminalList> { } // ScannerData is a container for all info needed by scanner to read input. // ScannerData is a field in LanguageData structure and is used by Scanner. public class ScannerData { public readonly GrammarData GrammarData; public readonly TerminalLookupTable TerminalsLookup = new TerminalLookupTable(); //hash table for fast terminal lookup by input char public readonly TerminalList FallbackTerminals = new TerminalList(); //terminals that have no explicit prefixes public string ScannerRecoverySymbols; public char[] LineTerminators; //used for line counting public readonly TerminalList MultilineTerminals = new TerminalList(); public readonly TokenFilterList TokenFilters = new TokenFilterList(); public ScannerData(GrammarData grammarData) { GrammarData = grammarData; } }//class // A struct used for packing/unpacking ScannerState int value; used for VS integration. [StructLayout(LayoutKind.Explicit)] public struct VsScannerStateMap { [FieldOffset(0)] public int Value; [FieldOffset(0)] public byte TerminalIndex; //1-based index of active multiline term in MultilineTerminals [FieldOffset(1)] public byte TokenSubType; //terminal subtype (used in StringLiteral to identify string kind) [FieldOffset(2)] public short TerminalFlags; //Terminal flags }//struct }//namespace
41.603774
136
0.695238
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/Misc/Reports/Irony/CompilerServices/Scanner/ScannerData.cs
2,207
C#
// <copyright file="RandomPolygonGenerator.cs" company="Eötvös Loránd University (ELTE)"> // Copyright 2016-2019 Roberto Giachetta. Licensed under the // Educational Community 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://opensource.org/licenses/ECL-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" // BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing // permissions and limitations under the License. // </copyright> namespace AEGIS.Algorithms { using System; using System.Collections.Generic; using AEGIS.Resources; /// <summary> /// Represents a type which performs creation of random polygons. /// </summary> /// <remarks> /// The implementation is based on Rod Stephens's polygon generator algorithm, <see cref="http://csharphelper.com/blog/2012/08/generate-random-polygons-in-c/" />. /// </remarks> public class RandomPolygonGenerator { /// <summary> /// The resulting polygon. /// </summary> private BasicProxyPolygon result; /// <summary> /// A value indicating whether the result has been computed. /// </summary> private Boolean hasResult; /// <summary> /// Initializes a new instance of the <see cref="RandomPolygonGenerator"/> class. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="envelopeMin">The lower bound of the generated polygon envelope.</param> /// <param name="envelopeMax">The upper bound of the generated polygon envelope.</param> /// <param name="convexityRatio">The convexity ratio.</param> /// <param name="precisionModel">The precision model.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// The number of coordinates is less than 3. /// or /// The envelope's minimum coordinate is greater than the maximum coordinate. /// or /// The convexity ratio is less than 0. /// or /// The convexity ratio is greater than 1. /// </exception> public RandomPolygonGenerator(Int32 coordinateCount, Coordinate envelopeMin, Coordinate envelopeMax, Double convexityRatio, PrecisionModel precisionModel) { if (coordinateCount < 3) throw new ArgumentOutOfRangeException(nameof(coordinateCount), CoreMessages.CoordinateCountLessThan3); if (envelopeMin.X > envelopeMax.X || envelopeMin.Y > envelopeMax.Y) throw new ArgumentOutOfRangeException(nameof(envelopeMax), CoreMessages.EnvelopeMinIsGreaterThanMax); if (convexityRatio < 0.0) throw new ArgumentOutOfRangeException(nameof(convexityRatio), CoreMessages.ConvexityRatioLessThan0); if (convexityRatio > 1.0) throw new ArgumentOutOfRangeException(nameof(convexityRatio), CoreMessages.ConvexityRatioGreaterThan1); this.PrecisionModel = precisionModel ?? PrecisionModel.Default; this.CoordinateCount = coordinateCount; this.EnvelopeMinimum = envelopeMin; this.EnvelopeMaximum = envelopeMax; this.ConvexityRatio = convexityRatio; this.result = null; this.hasResult = false; } /// <summary> /// Gets the precision model. /// </summary> /// <value>The precision model used for computing the result.</value> public PrecisionModel PrecisionModel { get; private set; } /// <summary> /// Gets the number of coordinates. /// </summary> /// <value>The number of coordinates.</value> public Int32 CoordinateCount { get; private set; } /// <summary> /// Gets the minimum coordinate of the envelope. /// </summary> /// <value>The minimum coordinate of the envelope.</value> public Coordinate EnvelopeMinimum { get; private set; } /// <summary> /// Gets the maximum coordinate of the envelope. /// </summary> /// <value>The maximum coordinate of the envelope.</value> public Coordinate EnvelopeMaximum { get; private set; } /// <summary> /// Gets the convexity ratio. /// </summary> /// <value>The convexity ratio.</value> public Double ConvexityRatio { get; private set; } /// <summary> /// Gets the result of the algorithm. /// </summary> /// <value>The generated random polygon.</value> public IBasicPolygon Result { get { if (!this.hasResult) this.Compute(); return this.result; } } /// <summary> /// Computes the result of the algorithm. /// </summary> public void Compute() { Coordinate[] shell = new Coordinate[this.CoordinateCount + 1]; Random rand = new Random(); // random points Double[] values = new Double[this.CoordinateCount]; Double minRadius = this.ConvexityRatio; Double maxRadius = 1.0; for (Int32 coordIndex = 0; coordIndex < this.CoordinateCount; coordIndex++) { values[coordIndex] = minRadius + rand.NextDouble() * (maxRadius - minRadius); } // random angle weights Double[] angleWeights = new Double[this.CoordinateCount]; Double totalWeight = 0; for (Int32 i = 0; i < this.CoordinateCount; i++) { angleWeights[i] = rand.NextDouble(); totalWeight += angleWeights[i]; } // convert weights into radians Double[] angles = new Double[this.CoordinateCount]; for (Int32 coordIndex = 0; coordIndex < this.CoordinateCount; coordIndex++) { angles[coordIndex] = angleWeights[coordIndex] * 2 * Math.PI / totalWeight; } // moving points according to angles Double halfWidth = (this.EnvelopeMaximum.X - this.EnvelopeMinimum.X) / 2; Double halfHeight = (this.EnvelopeMaximum.Y - this.EnvelopeMinimum.Y) / 2; Double midPointX = this.EnvelopeMinimum.X + halfWidth; Double midPointY = this.EnvelopeMinimum.Y + halfHeight; Double theta = 0; for (Int32 coordIndex = 0; coordIndex < this.CoordinateCount; coordIndex++) { shell[coordIndex] = this.PrecisionModel.MakePrecise(new Coordinate(midPointX + (halfWidth * values[coordIndex] * Math.Cos(theta)), midPointY + (halfHeight * values[coordIndex] * Math.Sin(theta)))); theta += angles[coordIndex]; } shell[this.CoordinateCount] = shell[0]; this.result = new BasicProxyPolygon(shell); this.hasResult = true; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException">The number of coordinates is less than 3.</exception> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount) { return new RandomPolygonGenerator(coordinateCount, new Coordinate(Double.MinValue, Double.MinValue), new Coordinate(Double.MaxValue, Double.MaxValue), 0.1, null).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="precisionModel">The precision model.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException">The number of coordinates is less than 3.</exception> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, PrecisionModel precisionModel) { return new RandomPolygonGenerator(coordinateCount, new Coordinate(Double.MinValue, Double.MinValue), new Coordinate(Double.MaxValue, Double.MaxValue), 0.1, precisionModel).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="envelope">The bounding envelope of the generated polygon.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException">The number of coordinates is less than 3.</exception> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Envelope envelope) { return new RandomPolygonGenerator(coordinateCount, envelope.Minimum, envelope.Maximum, 0.1, null).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="envelope">The bounding envelope of the generated polygon.</param> /// <param name="precisionModel">The precision model.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException">The number of coordinates is less than 3.</exception> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Envelope envelope, PrecisionModel precisionModel) { return new RandomPolygonGenerator(coordinateCount, envelope.Minimum, envelope.Maximum, 0.1, precisionModel).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="envelope">The bounding envelope of the generated polygon.</param> /// <param name="convexityRatio">The convexity ratio.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// The number of coordinates is less than 3. /// or /// The convexity ratio is less than 0. /// or /// The convexity ratio is greater than 1. /// </exception> /// <remarks> /// Statistics for <paramref name="convexityRatio" /> with respect to chance of convex polygon: 0.1 => 1%, 0.2 => 3%, 0.3 => 6%, 0.4 => 10%, 0.5 => 15%, 0.6 => 25%, 0.7 => 39%, 0.8 => 53%, 0.9 => 72%, 1.0 => 100%. /// </remarks> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Envelope envelope, Double convexityRatio) { return new RandomPolygonGenerator(coordinateCount, envelope.Minimum, envelope.Maximum, convexityRatio, null).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="envelope">The bounding envelope of the generated polygon.</param> /// <param name="convexityRatio">The convexity ratio.</param> /// <param name="precisionModel">The precision model.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// The number of coordinates is less than 3. /// or /// The convexity ratio is less than 0. /// or /// The convexity ratio is greater than 1. /// </exception> /// <remarks> /// Statistics for <paramref name="convexityRatio" /> with respect to chance of convex polygon: 0.1 => 1%, 0.2 => 3%, 0.3 => 6%, 0.4 => 10%, 0.5 => 15%, 0.6 => 25%, 0.7 => 39%, 0.8 => 53%, 0.9 => 72%, 1.0 => 100%. /// </remarks> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Envelope envelope, Double convexityRatio, PrecisionModel precisionModel) { return new RandomPolygonGenerator(coordinateCount, envelope.Minimum, envelope.Maximum, convexityRatio, precisionModel).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon vertexes.</param> /// <param name="envelopeMin">The lower bound of the generated polygon envelope.</param> /// <param name="envelopeMax">The upper bound of the generated polygon envelope.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// The number of coordinates is less than 3. /// or /// The envelope's minimum coordinate is greater than the maximum coordinate. /// </exception> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Coordinate envelopeMin, Coordinate envelopeMax) { return new RandomPolygonGenerator(coordinateCount, envelopeMin, envelopeMax, 0.1, null).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon vertexes.</param> /// <param name="envelopeMin">The lower bound of the generated polygon envelope.</param> /// <param name="envelopeMax">The upper bound of the generated polygon envelope.</param> /// <param name="precisionModel">The precision model.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// The number of coordinates is less than 3. /// or /// The envelope's minimum coordinate is greater than the maximum coordinate. /// </exception> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Coordinate envelopeMin, Coordinate envelopeMax, PrecisionModel precisionModel) { return new RandomPolygonGenerator(coordinateCount, envelopeMin, envelopeMax, 0.1, precisionModel).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="envelopeMin">The lower bound of the generated polygon envelope.</param> /// <param name="envelopeMax">The upper bound of the generated polygon envelope.</param> /// <param name="convexityRatio">The convexity ratio.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// The number of coordinates is less than 3. /// or /// The envelope's minimum coordinate is greater than the maximum coordinate. /// or /// The convexity ratio is less than 0. /// or /// The convexity ratio is greater than 1. /// </exception> /// <remarks> /// Statistics for <paramref name="convexityRatio" /> with respect to chance of convex polygon: 0.1 => 1%, 0.2 => 3%, 0.3 => 6%, 0.4 => 10%, 0.5 => 15%, 0.6 => 25%, 0.7 => 39%, 0.8 => 53%, 0.9 => 72%, 1.0 => 100%. /// </remarks> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Coordinate envelopeMin, Coordinate envelopeMax, Double convexityRatio) { return new RandomPolygonGenerator(coordinateCount, envelopeMin, envelopeMax, convexityRatio, null).Result; } /// <summary> /// Generates a random polygon. /// </summary> /// <param name="coordinateCount">The number of the polygon coordinates.</param> /// <param name="envelopeMin">The lower bound of the generated polygon envelope.</param> /// <param name="envelopeMax">The upper bound of the generated polygon envelope.</param> /// <param name="convexityRatio">The convexity ratio.</param> /// <param name="precisionModel">The precision model.</param> /// <returns>The generated polygon.</returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// The number of coordinates is less than 3. /// or /// The envelope's minimum coordinate is greater than the maximum coordinate. /// or /// The convexity ratio is less than 0. /// or /// The convexity ratio is greater than 1. /// </exception> /// <remarks> /// Statistics for <paramref name="convexityRatio" /> with respect to chance of convex polygon: 0.1 => 1%, 0.2 => 3%, 0.3 => 6%, 0.4 => 10%, 0.5 => 15%, 0.6 => 25%, 0.7 => 39%, 0.8 => 53%, 0.9 => 72%, 1.0 => 100%. /// </remarks> public static IBasicPolygon CreateRandomPolygon(Int32 coordinateCount, Coordinate envelopeMin, Coordinate envelopeMax, Double convexityRatio, PrecisionModel precisionModel) { return new RandomPolygonGenerator(coordinateCount, envelopeMin, envelopeMax, convexityRatio, null).Result; } } }
49.404494
221
0.623038
[ "ECL-2.0" ]
AegisSpatial/aegis
src/Core/Algorithms/RandomPolygonGenerator.cs
17,593
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using EventStore.Core.Bus; using EventStore.Core.Index; using EventStore.Core.Messages; using EventStore.Core.Services.Storage; using EventStore.Core.Services.Storage.ReaderIndex; using EventStore.Core.Tests.Services.Replication; using EventStore.Core.Tests.Services.Storage; using EventStore.Core.TransactionLog.Checkpoint; using EventStore.Core.TransactionLog.Chunks; using EventStore.Core.TransactionLog.LogRecords; using NUnit.Framework; namespace EventStore.Core.Tests.Services.IndexCommitter { public abstract class with_index_committer_service<TLogFormat, TStreamId> { protected int CommitCount = 2; protected ITableIndex TableIndex; protected ICheckpoint ReplicationCheckpoint; protected ICheckpoint WriterCheckpoint; protected InMemoryBus Publisher = new InMemoryBus("publisher"); protected ConcurrentQueue<StorageMessage.CommitIndexed> CommitReplicatedMgs = new ConcurrentQueue<StorageMessage.CommitIndexed>(); protected ConcurrentQueue<ReplicationTrackingMessage.IndexedTo> IndexWrittenMgs = new ConcurrentQueue<ReplicationTrackingMessage.IndexedTo>(); protected IndexCommitterService<TStreamId> Service; protected FakeIndexCommitter<TStreamId> IndexCommitter; protected ITFChunkScavengerLogManager TfChunkScavengerLogManager; [OneTimeSetUp] public virtual void TestFixtureSetUp() { IndexCommitter = new FakeIndexCommitter<TStreamId>(); ReplicationCheckpoint = new InMemoryCheckpoint(); WriterCheckpoint = new InMemoryCheckpoint(0); TableIndex = new FakeTableIndex<TStreamId>(); TfChunkScavengerLogManager = new FakeTfChunkLogManager(); Service = new IndexCommitterService<TStreamId>(IndexCommitter, Publisher, WriterCheckpoint, ReplicationCheckpoint, CommitCount, TableIndex, new QueueStatsManager()); Service.Init(0); Publisher.Subscribe(new AdHocHandler<StorageMessage.CommitIndexed>(m => CommitReplicatedMgs.Enqueue(m))); Publisher.Subscribe(new AdHocHandler<ReplicationTrackingMessage.IndexedTo>(m => IndexWrittenMgs.Enqueue(m))); Publisher.Subscribe<ReplicationTrackingMessage.ReplicatedTo>(Service); Given(); When(); } [OneTimeTearDown] public virtual void TestFixtureTearDown() { Service.Stop(); } public abstract void Given(); public abstract void When(); protected void AddPendingPrepare(long transactionPosition, long postPosition = -1) { postPosition = postPosition == -1 ? transactionPosition : postPosition; var prepare = CreatePrepare(transactionPosition, transactionPosition); Service.AddPendingPrepare(new[] { prepare }, postPosition); } protected void AddPendingPrepares(long transactionPosition, long[] logPositions) { var prepares = new List<IPrepareLogRecord<TStreamId>>(); foreach (var pos in logPositions) { prepares.Add(CreatePrepare(transactionPosition, pos)); } Service.AddPendingPrepare(prepares.ToArray(), logPositions[^1]); } private IPrepareLogRecord<TStreamId> CreatePrepare(long transactionPosition, long logPosition) { var recordFactory = LogFormatHelper<TLogFormat, TStreamId>.RecordFactory; var streamId = LogFormatHelper<TLogFormat, TStreamId>.StreamId; var eventTypeId = LogFormatHelper<TLogFormat, TStreamId>.EventTypeId; return LogRecord.Prepare(recordFactory, logPosition, Guid.NewGuid(), Guid.NewGuid(), transactionPosition, 0, streamId, -1, PrepareFlags.None, eventTypeId, new byte[10], new byte[0]); } protected void AddPendingCommit(long transactionPosition, long logPosition, long postPosition = -1) { postPosition = postPosition == -1 ? logPosition : postPosition; var commit = LogRecord.Commit(logPosition, Guid.NewGuid(), transactionPosition, 0); Service.AddPendingCommit(commit, postPosition); } } public class FakeIndexCommitter<TStreamId> : IIndexCommitter<TStreamId> { public ConcurrentQueue<IPrepareLogRecord<TStreamId>> CommittedPrepares = new ConcurrentQueue<IPrepareLogRecord<TStreamId>>(); public ConcurrentQueue<CommitLogRecord> CommittedCommits = new ConcurrentQueue<CommitLogRecord>(); public long LastIndexedPosition { get; set; } public void Init(long buildToPosition) { } public void Dispose() { } public long Commit(CommitLogRecord commit, bool isTfEof, bool cacheLastEventNumber) { CommittedCommits.Enqueue(commit); return 0; } public long Commit(IList<IPrepareLogRecord<TStreamId>> committedPrepares, bool isTfEof, bool cacheLastEventNumber) { foreach (var prepare in committedPrepares) { CommittedPrepares.Enqueue(prepare); } return 0; } public long GetCommitLastEventNumber(CommitLogRecord commit) { return 0; } } }
40.508621
168
0.78953
[ "Apache-2.0", "CC0-1.0" ]
BearerPipelineTest/EventStore
src/EventStore.Core.Tests/Services/IndexCommitter/with_index_committer_service.cs
4,699
C#
using System.Collections.Generic; using UnityEngine; namespace sc.terrain.vegetationspawner { public partial class VegetationSpawner { public void RefreshGrassPrototypes() { foreach (Terrain terrain in terrains) { List<DetailPrototype> grassPrototypeCollection = new List<DetailPrototype>(); int index = 0; foreach (GrassPrefab item in grassPrefabs) { item.index = index; DetailPrototype detailPrototype = new DetailPrototype(); UpdateGrassItem(item, detailPrototype); grassPrototypeCollection.Add(detailPrototype); index++; } if (grassPrototypeCollection.Count > 0) terrain.terrainData.detailPrototypes = grassPrototypeCollection.ToArray(); } } public void SpawnAllGrass(Terrain targetTerrain = null) { RefreshGrassPrototypes(); InitializeSeed(); foreach (GrassPrefab item in grassPrefabs) { SpawnGrass(item, targetTerrain); } } public void UpdateProperties(GrassPrefab item) { foreach (Terrain terrain in terrains) { //Note only works when creating these copies :/ DetailPrototype[] detailPrototypes = terrain.terrainData.detailPrototypes; DetailPrototype detailPrototype = GetGrassPrototype(item, terrain); //Could have been removed if(detailPrototype == null) continue; UpdateGrassItem(item, detailPrototype); detailPrototypes[item.index] = detailPrototype; terrain.terrainData.detailPrototypes = detailPrototypes; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(terrain); UnityEditor.EditorUtility.SetDirty(terrain.terrainData); #endif } } public void SetDetailResolution() { foreach (Terrain terrain in terrains) { terrain.terrainData.SetDetailResolution(detailResolution, grassPatchSize); #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(terrain.terrainData); #endif } } public void SpawnGrass(GrassPrefab item, Terrain targetTerrain = null) { if (item.collisionCheck) RebuildCollisionCacheIfNeeded(); item.instanceCount = 0; if (targetTerrain == null) { foreach (Terrain terrain in terrains) { SpawnGrassOnTerrain(terrain, item); } } else { SpawnGrassOnTerrain(targetTerrain, item); } onGrassRespawn?.Invoke(item); } private void SpawnGrassOnTerrain(Terrain terrain, GrassPrefab item) { //int[,] map = terrain.terrainData.GetDetailLayer(0, 0, terrain.terrainData.detailWidth, terrain.terrainData.detailHeight, item.index); int[,] map = new int[terrain.terrainData.detailWidth, terrain.terrainData.detailHeight]; int counter = 0; int cellCount = terrain.terrainData.detailWidth * terrain.terrainData.detailHeight; if (item.enabled) { for (int x = 0; x < terrain.terrainData.detailWidth; x++) { for (int y = 0; y < terrain.terrainData.detailHeight; y++) { counter++; #if UNITY_EDITOR //Show progress bar every 10% if (counter % (cellCount / 10) == 0) { UnityEditor.EditorUtility.DisplayProgressBar("Vegetation Spawner", "Spawning " + item.name + " on " + terrain.name, (float)counter/(float)cellCount); } #endif InitializeSeed(x * y + item.seed); //Default int instanceCount = 1; //XZ world position Vector3 wPos = terrain.DetailToWorld(y, x); Vector2 normalizedPos = terrain.GetNormalizedPosition(wPos); //Skip if failing probability check if (((Random.value * 100f) <= item.probability) == false) { instanceCount = 0; continue; } if (item.collisionCheck) { //Check for collision if (InsideOccupiedCell(terrain, wPos, normalizedPos)) { instanceCount = 0; continue; } } terrain.SampleHeight(normalizedPos, out _, out wPos.y, out _); if (item.rejectUnderwater && wPos.y < waterHeight) { instanceCount = 0; continue; } //Check height if (wPos.y < item.heightRange.x || wPos.y > item.heightRange.y) { instanceCount = 0; continue; } if (item.slopeRange.x > 0 || item.slopeRange.y < 90) { float slope = terrain.GetSlope(normalizedPos); //Reject if slope check fails if (slope < item.slopeRange.x || slope > item.slopeRange.y) { instanceCount = 0; continue; } } if (item.curvatureRange.x > 0 || item.curvatureRange.y < 1f) { float curvature = terrain.SampleConvexity(normalizedPos); //0=concave, 0.5=flat, 1=convex curvature = TerrainSampler.ConvexityToCurvature(curvature); if (curvature < item.curvatureRange.x || curvature > item.curvatureRange.y) { instanceCount = 0; continue; } } //Reject based on layer masks float spawnChance = 0f; if (item.layerMasks.Count == 0) { spawnChance = 100f; } else { splatmapTexelIndex = terrain.SplatmapTexelIndex(normalizedPos); } foreach (TerrainLayerMask layer in item.layerMasks) { Texture2D splat = terrain.terrainData.GetAlphamapTexture(GetSplatmapID(layer.layerID)); m_splatmapColor = splat.GetPixel(splatmapTexelIndex.x, splatmapTexelIndex.y); int channel = layer.layerID % 4; float value = SampleChannel(m_splatmapColor, channel); if (value > 0) { value = Mathf.Clamp01(value - layer.threshold); } value *= 100f; spawnChance += value; } InitializeSeed(x * y + item.seed); if ((Random.value <= spawnChance) == false) { instanceCount = 0; } //if (instanceCount == 1) DebugPoints.Instance.Add(wPos, true, 0f); item.instanceCount += instanceCount; //Passed all conditions, spawn one instance here map[x, y] = instanceCount; } } } terrain.terrainData.SetDetailLayer(0, 0, item.index, map); #if UNITY_EDITOR UnityEditor.EditorUtility.ClearProgressBar(); #endif } private DetailPrototype GetGrassPrototype(GrassPrefab item, Terrain terrain) { if (item.index >= terrain.terrainData.detailPrototypes.Length) return null; return terrain.terrainData.detailPrototypes[item.index]; } private void UpdateGrassItem(GrassPrefab item, DetailPrototype d) { d.healthyColor = item.mainColor; d.dryColor = item.linkColors ? item.mainColor : item.secondaryColor; d.minHeight = item.minMaxHeight.x; d.maxHeight = item.minMaxHeight.y; d.minWidth = item.minMaxWidth.x; d.maxWidth = item.minMaxWidth.y; d.noiseSpread = item.noiseSize; if (item.type == GrassType.Mesh) { d.renderMode = DetailRenderMode.Grass; //Actually a mesh d.usePrototypeMesh = true; d.prototype = item.prefab; d.prototypeTexture = null; } if (item.type == GrassType.Texture && item.billboard) { d.renderMode = item.renderAsBillboard ? DetailRenderMode.GrassBillboard : DetailRenderMode.Grass; d.usePrototypeMesh = false; d.prototypeTexture = item.billboard; d.prototype = null; } } } }
38.391144
178
0.45223
[ "Apache-2.0" ]
jrouillard/Arachnarok
Assets/VegetationSpawner/Runtime/VegetationSpawner.Grass.cs
10,406
C#
using System.Collections.Generic; using System.Linq; using System.Text; using Jotunn.Utils; using UnityEngine; namespace JotunnDoc.Docs { public class MaterialDoc : Doc { public MaterialDoc() : base("prefabs/material-list.md") { On.Player.OnSpawned += DocMaterials; } private void DocMaterials(On.Player.orig_OnSpawned orig, Player self) { orig(self); if (Generated) { return; } Jotunn.Logger.LogInfo("Documenting prefab materials"); AddHeader(1, "Prefab material list"); AddText("All materials, the prefabs they are used in and their respective shaders and keywords currently in the game (ZNetScene and ZoneManager)."); AddText("This file is automatically generated from Valheim using the JotunnDoc mod found on our GitHub."); AddTableHeader("Material", "Prefabs", "Shader", "Keywords"); List<GameObject> allPrefabs = new List<GameObject>(); allPrefabs.AddRange(ZNetScene.instance.m_nonNetViewPrefabs); allPrefabs.AddRange(ZNetScene.instance.m_prefabs); allPrefabs.AddRange(ZoneSystem.instance.m_locations.Where(x => x.m_prefab).Select(x => x.m_prefab)); Dictionary<string, Material> mats = new Dictionary<string, Material>(); Dictionary<string, List<string>> matPrefabs = new Dictionary<string, List<string>>(); foreach (GameObject prefab in allPrefabs.OrderBy(x => x.name)) { foreach (Material mat in ShaderHelper.GetAllRendererMaterials(prefab)) { const string instanceToken = " (Instance)"; string matName = mat.name; // Add distinct materials if (matName.EndsWith(instanceToken)) { matName = matName.Substring(0, matName.Length - instanceToken.Length); } if (!mats.ContainsKey(matName)) { mats.Add(matName, mat); } // Add prefab per material if (!matPrefabs.ContainsKey(matName)) { matPrefabs.Add(matName, new List<string>()); } matPrefabs[matName].Add(prefab.name); } } foreach (var entry in mats.OrderBy(x => x.Key)) { Material mat = entry.Value; StringBuilder prefabsb = new StringBuilder(); prefabsb.Append("<ul>"); foreach (string prefab in matPrefabs[entry.Key].Distinct().OrderBy(x => x)) { prefabsb.Append("<li>"); prefabsb.Append(prefab); prefabsb.Append("</li>"); } prefabsb.Append("</ul>"); StringBuilder keysb = new StringBuilder(); keysb.Append("<dl>"); if (mat.shaderKeywords.Length > 0) { foreach (string prop in mat.shaderKeywords) { keysb.Append("<dd>"); keysb.Append(prop); keysb.Append("</dd>"); } } keysb.Append("</dl>"); AddTableRow(entry.Key, prefabsb.ToString(), mat.shader.name, keysb.ToString()); } Save(); } } }
35.930693
160
0.504547
[ "MIT" ]
MSchmoecker/Jotunn
JotunnDoc/Docs/MaterialDoc.cs
3,631
C#
#nullable enable using System; using Leclair.Stardew.Common.Events; using StardewModdingAPI; namespace Leclair.Stardew.Almanac.Managers; public class BaseManager : EventSubscriber<ModEntry> { public readonly string Name; public BaseManager(ModEntry mod, string? name = null) : base(mod) { Name = name ?? GetType().Name; } protected void Log(string message, LogLevel level = LogLevel.Debug, Exception? ex = null, LogLevel? exLevel = null) { Mod.Monitor.Log($"[{Name}] {message}", level: level); if (ex != null) Mod.Monitor.Log($"[{Name}] Details:\n{ex}", level: exLevel ?? level); } }
23.346154
118
0.705107
[ "MIT" ]
KhloeLeclair/StardewMods
Almanac/Managers/BaseManager.cs
607
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReplacementShader : MonoBehaviour { public Shader ReplacementMaterial; void OnEnable() { if (ReplacementMaterial != null) GetComponent<Camera>().SetReplacementShader(ReplacementMaterial, "RenderType"); } void OnDisable() { GetComponent<Camera>().ResetReplacementShader(); } }
21.4
91
0.691589
[ "MIT" ]
TacPhoto/Learning
Unity/FirstSteps/ReplacementShader/ReplacementShader.cs
430
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the servicecatalog-appregistry-2020-06-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.AppRegistry.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AppRegistry.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ApplicationSummary Object /// </summary> public class ApplicationSummaryUnmarshaller : IUnmarshaller<ApplicationSummary, XmlUnmarshallerContext>, IUnmarshaller<ApplicationSummary, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ApplicationSummary IUnmarshaller<ApplicationSummary, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ApplicationSummary Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ApplicationSummary unmarshalledObject = new ApplicationSummary(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("arn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Arn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("creationTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreationTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("description", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Description = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("id", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Id = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("lastUpdateTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.LastUpdateTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ApplicationSummaryUnmarshaller _instance = new ApplicationSummaryUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ApplicationSummaryUnmarshaller Instance { get { return _instance; } } } }
37.532787
167
0.604062
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/AppRegistry/Generated/Model/Internal/MarshallTransformations/ApplicationSummaryUnmarshaller.cs
4,579
C#
using Acr.UserDialogs; using System.Threading.Tasks; namespace BethanysPieShopStockApp.Services { public class DialogService : IDialogService { public Task ShowDialog(string message, string title, string buttonLabel) { return UserDialogs.Instance.AlertAsync(message, title, buttonLabel); } } }
24.571429
80
0.700581
[ "MIT" ]
VeselinovStf/Data-in-Xamarin.Forms
Working-With-Remote-Data/src/Mobile/BethanysPieShopStockApp/Services/DialogService.cs
346
C#
// Decompiled with JetBrains decompiler // Type: Functal.FnFunction_Cast_ToInt32_FromInt16 // Assembly: Functal, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 47DC2DAE-D56F-4FC5-A0C3-CC69F2DF9A1F // Assembly location: \\WSE\Folder Redirection\JP\Downloads\Functal-1_0_0\Functal.dll namespace Functal { internal class FnFunction_Cast_ToInt32_FromInt16 : FnFunction<int> { [FnArg] protected FnObject<short> Value; public FnFunction_Cast_ToInt32_FromInt16() : base(new FnFunction<int>.CompileFlags[1] { FnFunction<int>.CompileFlags.IMPLICIT_CONVERSION }) { } public override int GetValue() { return (int) this.Value.GetValue(); } } }
25.785714
85
0.711911
[ "MIT" ]
jpdillingham/Functal
src/FnFunction_Cast_ToInt32_FromInt16.cs
724
C#
using Microsoft.Extensions.DependencyInjection; using StockTicker.Service; using System; using System.Collections.Generic; using System.Text; namespace ClientSideAuth.Extensions { public static class DependencyInjection { public static IServiceCollection AddRandomStockTicker(this IServiceCollection services) { services.AddSingleton<IStockTickerService, RandomStockTicker>(); return services; } } }
25.315789
96
0.706861
[ "Apache-2.0" ]
fluffy-bunny/asp.net-inmemory-identity-blazor
src/StockTicker.Service/Extensions/DependencyInjection.cs
483
C#
using System.IO; using CoreLibraries.IO; using VaultLib.Core; using VaultLib.Core.Data; using VaultLib.Core.Types; using VaultLib.Core.Types.Attrib; using VaultLib.Frameworks.Speed; namespace VaultLib.Support.ProStreet.VLT { [VLTTypeInfo(nameof(TireTimeEffectRecord))] public class TireTimeEffectRecord : VLTBaseType { public TireTimeEffectRecord(VltClass @class, VltClassField field, VltCollection collection = null) : base(@class, field, collection) { mEmitter = new RefSpec(Class, Field, Collection); mEmitterLowLod = new RefSpec(Class, Field, Collection); } public TireCondition mTireCondition { get; set; } public RefSpec mEmitter { get; set; } public RefSpec mEmitterLowLod { get; set; } public float mMinTime { get; set; } public float mMaxTime { get; set; } public override void Read(Vault vault, BinaryReader br) { mTireCondition = br.ReadEnum<TireCondition>(); mEmitter.Read(vault, br); mEmitterLowLod.Read(vault, br); mMinTime = br.ReadSingle(); mMaxTime = br.ReadSingle(); } public override void Write(Vault vault, BinaryWriter bw) { bw.WriteEnum(mTireCondition); mEmitter.Write(vault, bw); mEmitterLowLod.Write(vault, bw); bw.Write(mMinTime); bw.Write(mMaxTime); } } }
33.136364
140
0.62963
[ "MIT" ]
BreakinBenny/VaultLib
VaultLib.Support.ProStreet/VLT/TireTimeEffectRecord.cs
1,460
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoT.Model { /// <summary> /// The properties of the thing, including thing name, thing type name, and a list of /// thing attributes. /// </summary> public partial class ThingAttribute { private Dictionary<string, string> _attributes = new Dictionary<string, string>(); private string _thingArn; private string _thingName; private string _thingTypeName; private long? _version; /// <summary> /// Gets and sets the property Attributes. /// <para> /// A list of thing attributes which are name-value pairs. /// </para> /// </summary> public Dictionary<string, string> Attributes { get { return this._attributes; } set { this._attributes = value; } } // Check to see if Attributes property is set internal bool IsSetAttributes() { return this._attributes != null && this._attributes.Count > 0; } /// <summary> /// Gets and sets the property ThingArn. /// <para> /// The thing ARN. /// </para> /// </summary> public string ThingArn { get { return this._thingArn; } set { this._thingArn = value; } } // Check to see if ThingArn property is set internal bool IsSetThingArn() { return this._thingArn != null; } /// <summary> /// Gets and sets the property ThingName. /// <para> /// The name of the thing. /// </para> /// </summary> public string ThingName { get { return this._thingName; } set { this._thingName = value; } } // Check to see if ThingName property is set internal bool IsSetThingName() { return this._thingName != null; } /// <summary> /// Gets and sets the property ThingTypeName. /// <para> /// The name of the thing type, if the thing has been associated with a type. /// </para> /// </summary> public string ThingTypeName { get { return this._thingTypeName; } set { this._thingTypeName = value; } } // Check to see if ThingTypeName property is set internal bool IsSetThingTypeName() { return this._thingTypeName != null; } /// <summary> /// Gets and sets the property Version. /// <para> /// The version of the thing record in the registry. /// </para> /// </summary> public long Version { get { return this._version.GetValueOrDefault(); } set { this._version = value; } } // Check to see if Version property is set internal bool IsSetVersion() { return this._version.HasValue; } } }
29.075188
101
0.569692
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/ThingAttribute.cs
3,867
C#
#pragma checksum "..\..\MainWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "43459500A2029731FA3FEA093A5D22C55A3F4CC5" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Accord.MainApp; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Accord.MainApp { /// <summary> /// MainWindow /// </summary> public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Accord.MainApp;component/mainwindow.xaml", System.UriKind.Relative); #line 1 "..\..\MainWindow.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { this._contentLoaded = true; } } }
38.934211
141
0.668131
[ "MIT" ]
bhabesh7/bhabeshgitprojects
CSharpCompiler/Accord.MainApp/obj/Debug/MainWindow.g.i.cs
2,961
C#
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace ZendeskApi.Client.Models { [JsonObject("satisfaction_rating")] public class SatisfactionRating { [JsonProperty] public long? Id { get; set; } [JsonProperty("group_id")] public long GroupId { get; set; } [JsonProperty("assignee_id")] public long AssigneeId { get; set; } [JsonProperty("requester_id")] public long RequesterId { get; set; } [JsonProperty("ticket_id")] public long TicketId { get; set; } [JsonConverter(typeof(StringEnumConverter))] [JsonProperty("score")] public SatisfactionRatingScore Score { get; set; } [JsonProperty("created_at")] public DateTime? CreatedAt { get; set; } [JsonProperty("updated_at")] public DateTime? UpdatedAt { get; set; } [JsonProperty("comment")] public TicketComment Comment { get; set; } [JsonProperty("url")] public string Url { get; set; } } }
25.357143
58
0.610329
[ "Apache-2.0" ]
gareththackeray/ZendeskApiClient
src/ZendeskApi.Client/Models/SatisfactionRating.cs
1,067
C#
using qckdev.AspNetCore.Identity.Exceptions; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using System; using System.Threading.Tasks; namespace qckdev.AspNetCore.Identity.JwtBearer { sealed class JwtRefreshTokenProvider<TUser> : IUserTwoFactorTokenProvider<TUser> where TUser : class { const string PROVIDER = "jwt"; IAuthenticationService AuthenticationService { get; } public JwtRefreshTokenProvider(IAuthenticationService authenticationService) { this.AuthenticationService = authenticationService; } public Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user) { throw new NotImplementedException(); } public async Task<string> GenerateAsync(string purpose, UserManager<TUser> manager, TUser user) { var tokenValue = JwtGenerator.CreateGenericToken(); IdentityResult result; result = await manager.SetAuthenticationTokenAsync(user, PROVIDER, nameof(JwtRefreshTokenProvider<TUser>), tokenValue); if (result.Succeeded) { return tokenValue; } else { throw new IdentityException("Error creating refresh token.", result.Errors); } } public async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser> manager, TUser user) { string storedToken; storedToken = await manager.GetAuthenticationTokenAsync(user, PROVIDER, nameof(JwtRefreshTokenProvider<TUser>)); return (storedToken != null && storedToken == token); } } }
32.849057
131
0.658242
[ "MIT" ]
hfrances/qckdev.AspNetCore.Identity
qckdev.AspNetCore.Identity/JwtBearer/JwtRefreshTokenProvider.cs
1,743
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Threading; using MarcusW.VncClient.Protocol.Services; namespace MarcusW.VncClient.Protocol.Implementation.Services.Communication { /// <summary> /// A <see cref="IZLibInflater"/> implementation using the builtin System.IO.Compression implementation of zlib. /// Provides methods for inflating (decompressing) received data using per-connection zlib streams. /// </summary> public sealed class BuiltinZLibInflater : IZLibInflater { private readonly Dictionary<int, Inflater> _inflaters = new Dictionary<int, Inflater>(); private volatile bool _disposed; /// <inheritdoc /> public Stream ReadAndInflate(Stream source, int sourceLength, int zlibStreamId = -1, CancellationToken cancellationToken = default) { if (source == null) throw new ArgumentNullException(nameof(source)); if (_disposed) throw new ObjectDisposedException(nameof(BuiltinZLibInflater)); cancellationToken.ThrowIfCancellationRequested(); bool hasExisting = _inflaters.TryGetValue(zlibStreamId, out Inflater? inflater); if (hasExisting) { // Because we always read the exact size of bytes we need, it sometimes happens, that the inflate stream doesn't realize that all data has been read and therefore // reads garbage when the buffer has been refilled. This is fixed by attempting an additional read of 1 byte after all bytes have been read. // This read will not return any results, but it solves the problem. Believe me. :D // This is also useful to throw a nice exception if somebody fucked up and didn't read the full buffer. Span<byte> buf = stackalloc byte[1]; if (inflater!.DeflateStream.Read(buf) != 0) throw new RfbProtocolException( $"Attempted to refill the zlib inflate stream before all bytes have been read. There was at least one byte pending to read. Stream id: {zlibStreamId}"); } // The data must be read and buffered in a memory stream, before passing it to the inflate stream. // This seems to be necessary to limit the inflate stream in the amount of bytes it has access to, // so it doesn't read more bytes than wanted. // Inspiration taken from: https://github.com/quamotion/remoteviewing/blob/926d2baf8de446252fdc3a59054d0af51cdb065d/RemoteViewing/Vnc/VncClient.Framebuffer.cs#L208 // TODO: Can this limit somehow be implemented without having to copy all the data? Maybe a custom Stream implementation? // Create a new inflater, if necessary if (!hasExisting) { inflater = new Inflater(); _inflaters.Add(zlibStreamId, inflater); } // Write the source data to the memory stream to buffer it inflater!.MemoryStream.Position = 0; source.CopyAllTo(inflater.MemoryStream, sourceLength, cancellationToken); inflater.MemoryStream.SetLength(sourceLength); inflater.MemoryStream.Position = 0; // Skip the two bytes of the ZLib header (see RFC1950) when a new stream was created if (!hasExisting) { if (sourceLength < 2) throw new InvalidOperationException("Inflater cannot be initialized with less than two bytes."); inflater.MemoryStream.Position = 2; } return inflater.DeflateStream; } /// <inheritdoc /> public void ResetZlibStream(int id) { if (_disposed) throw new ObjectDisposedException(nameof(BuiltinZLibInflater)); if (_inflaters.TryGetValue(id, out Inflater? inflater)) inflater.Dispose(); _inflaters.Remove(id); } /// <inheritdoc /> public void Dispose() { if (_disposed) return; foreach (Inflater inflater in _inflaters.Values) inflater.Dispose(); _disposed = true; } private sealed class Inflater : IDisposable { public MemoryStream MemoryStream { get; set; } public DeflateStream DeflateStream { get; set; } public Inflater() { MemoryStream = new MemoryStream(); DeflateStream = new DeflateStream(MemoryStream, CompressionMode.Decompress, false); } public void Dispose() { MemoryStream.Dispose(); DeflateStream.Dispose(); } } } }
41.116667
178
0.619578
[ "MIT" ]
MarcusWichelmann/MarcusW.VncClient
src/MarcusW.VncClient/Protocol/Implementation/Services/Communication/BuiltinZLibInflater.cs
4,934
C#
using Microsoft.Identity.Web; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration) //Default - AzureAd .EnableTokenAcquisitionToCallDownstreamApi() .AddMicrosoftGraph(graphBaseUrl: "https://graph.microsoft.com/v1.0", defaultScopes: "user.read") .AddInMemoryTokenCaches(); builder.Services.AddAuthorization(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
25.25
100
0.776678
[ "MIT" ]
ceeidpnotes/ceeidpnotes
Demos-Src/CS/NOT_FINISHED/TKFY22-step5-mtapp-onbehalf/TKFY22-step5-Api01/Program.cs
909
C#
using E_ShopApp.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace E_ShopApp.Pages { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoginPage : ContentPage { public LoginPage() { InitializeComponent(); } private void TapBackArrow_Tapped(object sender, EventArgs e) { Navigation.PopModalAsync(); } private async void BtnLogin_Clicked(object sender, EventArgs e) { var response = await ApiService.Login(EntEmail.Text, EntPassword.Text); Preferences.Set("email", EntEmail.Text); Preferences.Set("password", EntPassword.Text); if (response) { Application.Current.MainPage = new NavigationPage(new HomePage()); } else { await DisplayAlert("Login failed", "Kindly check to confirm that the login details are correct", "Okay"); } } } }
27.714286
121
0.618557
[ "MIT" ]
JiboGithub/EShop_MobileAppXamarin
E_ShopApp/Pages/LoginPage.xaml.cs
1,166
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the auditmanager-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.AuditManager.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AuditManager.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListControlDomainInsights operation /// </summary> public class ListControlDomainInsightsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { ListControlDomainInsightsResponse response = new ListControlDomainInsightsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("controlDomainInsights", targetDepth)) { var unmarshaller = new ListUnmarshaller<ControlDomainInsights, ControlDomainInsightsUnmarshaller>(ControlDomainInsightsUnmarshaller.Instance); response.ControlDomainInsights = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("nextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonAuditManagerException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static ListControlDomainInsightsResponseUnmarshaller _instance = new ListControlDomainInsightsResponseUnmarshaller(); internal static ListControlDomainInsightsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListControlDomainInsightsResponseUnmarshaller Instance { get { return _instance; } } } }
41.117188
195
0.647729
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/AuditManager/Generated/Model/Internal/MarshallTransformations/ListControlDomainInsightsResponseUnmarshaller.cs
5,263
C#
using System; using System.Linq; using System.Collections.Generic; using System.Runtime.InteropServices; using Torque3D.Engine; using Torque3D.Util; namespace Torque3D { public unsafe class CollisionTrigger : GameBase { public CollisionTrigger(bool pRegister = false) : base(pRegister) { } public CollisionTrigger(string pName, bool pRegister = false) : this(false) { Name = pName; if (pRegister) registerObject(); } public CollisionTrigger(string pName, string pParent, bool pRegister = false) : this(pName, pRegister) { CopyFrom(Sim.FindObject<SimObject>(pParent)); } public CollisionTrigger(string pName, SimObject pParent, bool pRegister = false) : this(pName, pRegister) { CopyFrom(pParent); } public CollisionTrigger(SimObject pObj) : base(pObj) { } public CollisionTrigger(IntPtr pObjPtr) : base(pObjPtr) { } protected override void CreateSimObjectPtr() { ObjectPtr = InternalUnsafeMethods.CollisionTrigger_create(); } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _getNumObjects(IntPtr thisPtr); private static _getNumObjects _getNumObjectsFunc; internal static int getNumObjects(IntPtr thisPtr) { if (_getNumObjectsFunc == null) { _getNumObjectsFunc = (_getNumObjects)Marshal.GetDelegateForFunctionPointer(Torque3D.DllLoadUtils.GetProcAddress(Torque3D.Torque3DLibHandle, "fn_CollisionTrigger_getNumObjects"), typeof(_getNumObjects)); } return _getNumObjectsFunc(thisPtr); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _getObject(IntPtr thisPtr, int index); private static _getObject _getObjectFunc; internal static int getObject(IntPtr thisPtr, int index) { if (_getObjectFunc == null) { _getObjectFunc = (_getObject)Marshal.GetDelegateForFunctionPointer(Torque3D.DllLoadUtils.GetProcAddress(Torque3D.Torque3DLibHandle, "fn_CollisionTrigger_getObject"), typeof(_getObject)); } return _getObjectFunc(thisPtr, index); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _CollisionTrigger_create(); private static _CollisionTrigger_create _CollisionTrigger_createFunc; internal static IntPtr CollisionTrigger_create() { if (_CollisionTrigger_createFunc == null) { _CollisionTrigger_createFunc = (_CollisionTrigger_create)Marshal.GetDelegateForFunctionPointer(Torque3D.DllLoadUtils.GetProcAddress(Torque3D.Torque3DLibHandle, "fn_CollisionTrigger_create"), typeof(_CollisionTrigger_create)); } return _CollisionTrigger_createFunc(); } } #endregion #region Functions public virtual int getNumObjects() { return InternalUnsafeMethods.getNumObjects(ObjectPtr); } public virtual int getObject(int index) { return InternalUnsafeMethods.getObject(ObjectPtr, index); } #endregion #region Properties public string Polyhedron { get { return getFieldValue("Polyhedron"); } set { setFieldValue("Polyhedron", value); } } public string EnterCommand { get { return getFieldValue("EnterCommand"); } set { setFieldValue("EnterCommand", value); } } public string LeaveCommand { get { return getFieldValue("LeaveCommand"); } set { setFieldValue("LeaveCommand", value); } } public string TickCommand { get { return getFieldValue("TickCommand"); } set { setFieldValue("TickCommand", value); } } #endregion } }
27.717105
140
0.627819
[ "MIT" ]
lukaspj/T3D-CSharp-Tools
BaseLibrary/Torque3D/Engine/CollisionTrigger.cs
4,213
C#
namespace ePlatform.eBelge.Api.Models.Models.Enums { public enum EFaturaDataStatus { Waiting = 0, Running = 1, Completed = 2, Failed = 3 } }
18.4
50
0.565217
[ "MIT" ]
Quaqmre/eplatform-api-dotnet-client
src/ePlatform.eBelge.Api.Invoice/Models/Enums/EFaturaDataStatus.cs
184
C#
using Examine; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; namespace Umbraco.Cms.Infrastructure.Examine { public class UmbracoIndexConfig : IUmbracoIndexConfig { public UmbracoIndexConfig(IPublicAccessService publicAccessService, IScopeProvider scopeProvider) { ScopeProvider = scopeProvider; PublicAccessService = publicAccessService; } protected IPublicAccessService PublicAccessService { get; } protected IScopeProvider ScopeProvider { get; } public IContentValueSetValidator GetContentValueSetValidator() { return new ContentValueSetValidator(false, true, PublicAccessService, ScopeProvider); } public IContentValueSetValidator GetPublishedContentValueSetValidator() { return new ContentValueSetValidator(true, false, PublicAccessService, ScopeProvider); } /// <summary> /// Returns the <see cref="IValueSetValidator"/> for the member indexer /// </summary> /// <returns></returns> public IValueSetValidator GetMemberValueSetValidator() { return new MemberValueSetValidator(); } } }
32.342105
105
0.6786
[ "MIT" ]
Ambertvu/Umbraco-CMS
src/Umbraco.Infrastructure/Examine/UmbracoIndexConfig.cs
1,229
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using OrchardCore.Environment.Shell; namespace OrchardCore.Modules { /// <summary> /// This middleware replaces the default service provider by the one for the current tenant /// </summary> public class ModularTenantContainerMiddleware { private readonly RequestDelegate _next; private readonly IShellHost _orchardHost; private readonly IRunningShellTable _runningShellTable; public ModularTenantContainerMiddleware( RequestDelegate next, IShellHost orchardHost, IRunningShellTable runningShellTable) { _next = next; _orchardHost = orchardHost; _runningShellTable = runningShellTable; } public async Task Invoke(HttpContext httpContext) { // Ensure all ShellContext are loaded and available. _orchardHost.Initialize(); var shellSetting = _runningShellTable.Match(httpContext); // Register the shell settings as a custom feature. httpContext.Features.Set(shellSetting); // We only serve the next request if the tenant has been resolved. if (shellSetting != null) { var shellContext = _orchardHost.GetOrCreateShellContext(shellSetting); var existingRequestServices = httpContext.RequestServices; try { using (var scope = shellContext.EnterServiceScope()) { if (!shellContext.IsActivated) { lock (shellContext) { // The tenant gets activated here if (!shellContext.IsActivated) { var tenantEvents = scope.ServiceProvider.GetServices<IModularTenantEvents>(); foreach (var tenantEvent in tenantEvents) { tenantEvent.ActivatingAsync().Wait(); } httpContext.Items["BuildPipeline"] = true; shellContext.IsActivated = true; foreach (var tenantEvent in tenantEvents) { tenantEvent.ActivatedAsync().Wait(); } } } } shellContext.RequestStarted(); await _next.Invoke(httpContext); } } finally { shellContext.RequestEnded(); } } } } }
36.891566
113
0.482691
[ "BSD-3-Clause" ]
Yuexs/OrchardCore
src/OrchardCore/OrchardCore.Modules/ModularTenantContainerMiddleware.cs
3,062
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _05_Hands_of_Cards { class Program { static void Main(string[] args) { Dictionary<string, string> playersCards = new Dictionary<string, string>(); string input = Console.ReadLine(); while (input != "JOKER") { List<string> inputEll = input.Split(':').ToList(); if (playersCards.ContainsKey(inputEll[0])) { playersCards[inputEll[0]] += inputEll[1]; } else { playersCards[inputEll[0]] = inputEll[1]; } input = Console.ReadLine(); } foreach (var plaeyr in playersCards) { int points = CountPoints((plaeyr.Value)); Console.WriteLine($"{plaeyr.Key}: {points}"); } } private static int CountPoints(string playerValue) { List<string> cards = playerValue.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList(); int points = 0; for (int i = 0; i < cards.Count; i++) { points += CountCardPoints(cards[i]); } return points; } private static int CountCardPoints(string card) { int power = 0; for (int i = 2; i < 10; i++) { if ((int)(card[0] - '0') == i) { power = i; } } switch (card[0]) { case '1': power = 10; break; case 'J': power = 11; break; case 'Q': power = 12; break; case 'K': power = 13; break; case 'A': power = 14; break; } int type = 0; switch (card[card.Length - 1]) { case 'C': type = 1; break; case 'D': type = 2; break; case 'H': type = 3; break; case 'S': type = 4; break; } return (power * type); } } }
26.39604
135
0.368717
[ "MIT" ]
akkirilov/ProgrammingFundamentalsHomeworks
01_ProgrammingFundamentals/Homeworks/06_Dictionaries-Exercises/05_Hands of Cards/Program.cs
2,668
C#
namespace ResXManager.Infrastructure { public static class JsonConvert { public static string? SerializeObject(object value) { return Newtonsoft.Json.JsonConvert.SerializeObject(value); } public static T? DeserializeObject<T>(string value) where T : class { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value); } public static void PopulateObject(string value, object target) { Newtonsoft.Json.JsonConvert.PopulateObject(value, target); } } }
27.727273
76
0.601639
[ "MIT" ]
GeertvanHorrik/ResXResourceManager
src/ResXManager.Infrastructure/JsonConvert.cs
612
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using watchtower.Constants; using watchtower.Models; using watchtower.Models.Events; namespace watchtower.Code.Challenge { public class AssaultRifleChallenge : IRunChallenge { public int ID => 14; public string Name => "Salting"; public string Description => "Get kills with ARs"; public int Multiplier => 2; public int Duration => 120; public ChallengeDurationType DurationType => ChallengeDurationType.TIMED; public Task<bool> WasMet(KillEvent ev, PsItem? item) { return Task.FromResult(item != null && item.CategoryID == ItemCategory.AssaultRifle); } } }
24.193548
97
0.686667
[ "MIT" ]
ElReyZero/flash
Code/Challenge/AssaultRifleChallenge.cs
752
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace chkam05.VisualPlayer.Data.Lyrics.Events { public class LyricsItemUpdateEventArgs : EventArgs { // VARIABLES public string PropertyName { get; private set; } public object PropertyValue { get; private set; } public Type PropertyType { get; private set; } // METHODS #region CLASS METHODS // -------------------------------------------------------------------------------- /// <summary> LyricsItemUpdateEventArgs class constructor. </summary> /// <param name="name"> Lyrics changed property name. </param> /// <param name="value"> Lyrics changed value. </param> /// <param name="type"> Lyrics changed property type. </param> public LyricsItemUpdateEventArgs(string name, object value, Type type) { PropertyName = name; PropertyValue = value; PropertyType = type; } #endregion CLASS METHODS } }
28.179487
92
0.579618
[ "MIT" ]
chkam05/chkam05.VisualPlayer
chkam05.VisualPlayer/Data/Lyrics/Events/LyricsItemUpdateEventArgs.cs
1,101
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Query.Pipeline; using Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.SqlExpressions; namespace Microsoft.EntityFrameworkCore.Relational.Query.Pipeline { public class RelationalShapedQueryOptimizer : ShapedQueryOptimizer { private readonly QueryCompilationContext2 _queryCompilationContext; public RelationalShapedQueryOptimizer( QueryCompilationContext2 queryCompilationContext, ISqlExpressionFactory sqlExpressionFactory) { _queryCompilationContext = queryCompilationContext; SqlExpressionFactory = sqlExpressionFactory; } protected ISqlExpressionFactory SqlExpressionFactory { get; private set; } public override Expression Visit(Expression query) { query = base.Visit(query); query = new SelectExpressionProjectionApplyingExpressionVisitor().Visit(query); query = new SelectExpressionTableAliasUniquifyingExpressionVisitor().Visit(query); if (!RelationalOptionsExtension.Extract(_queryCompilationContext.ContextOptions).UseRelationalNulls) { query = new NullSemanticsRewritingVisitor(SqlExpressionFactory).Visit(query); } query = new SqlExpressionOptimizingVisitor(SqlExpressionFactory).Visit(query); query = new NullComparisonTransformingExpressionVisitor().Visit(query); if (query is ShapedQueryExpression shapedQueryExpression) { shapedQueryExpression.ShaperExpression = new ShaperExpressionProcessingExpressionVisitor((SelectExpression)shapedQueryExpression.QueryExpression) .Inject(shapedQueryExpression.ShaperExpression); } return query; } } }
42.04
126
0.716461
[ "Apache-2.0" ]
Wrank/EntityFrameworkCore
src/EFCore.Relational/Query/Pipeline/RelationalShapedQueryOptimizingExpressionVisitors.cs
2,104
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.Runtime.InteropServices; using System.Text; using Microsoft.Git.CredentialManager.Interop.Windows.Native; namespace Microsoft.Git.CredentialManager.Interop.Windows { public class WindowsSystemPrompts : ISystemPrompts { private IntPtr _parentHwd = IntPtr.Zero; public object ParentWindowId { get => _parentHwd.ToString(); set => _parentHwd = ConvertUtils.TryToInt32(value, out int ptr) ? new IntPtr(ptr) : IntPtr.Zero; } public bool ShowCredentialPrompt(string resource, string userName, out ICredential credential) { EnsureArgument.NotNullOrWhiteSpace(resource, nameof(resource)); string message = $"Enter credentials for '{resource}'"; var credUiInfo = new CredUi.CredentialUiInfo { BannerArt = IntPtr.Zero, CaptionText = "Git Credential Manager", // TODO: make this a parameter? Parent = _parentHwd, MessageText = message, Size = Marshal.SizeOf(typeof(CredUi.CredentialUiInfo)) }; var packFlags = CredUi.CredentialPackFlags.None; var uiFlags = CredUi.CredentialUiWindowsFlags.Generic; if (!string.IsNullOrEmpty(userName)) { // If we are given a username, pre-populate the dialog with the given value uiFlags |= CredUi.CredentialUiWindowsFlags.InCredOnly; } IntPtr inBufferPtr = IntPtr.Zero; uint inBufferSize; try { CreateCredentialInfoBuffer(userName, packFlags, out inBufferSize, out inBufferPtr); return DisplayCredentialPrompt(ref credUiInfo, ref packFlags, inBufferPtr, inBufferSize, false, uiFlags, out credential); } finally { if (inBufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(inBufferPtr); } } } private static void CreateCredentialInfoBuffer(string userName, CredUi.CredentialPackFlags flags, out uint inBufferSize, out IntPtr inBufferPtr) { // Windows Credential API calls require at least an empty string; not null userName = userName ?? string.Empty; int desiredBufSize = 0; // Execute with a null packed credentials pointer to determine the required buffer size. // This method always returns false when determining the buffer size so we only fail if the size is not strictly positive. CredUi.CredPackAuthenticationBuffer(flags, userName, string.Empty, IntPtr.Zero, ref desiredBufSize); Win32Error.ThrowIfError(desiredBufSize > 0, "Unable to determine credential buffer size."); // Create a buffer of the desired size and pass the pointer and size back to the caller inBufferSize = (uint) desiredBufSize; inBufferPtr = Marshal.AllocHGlobal(desiredBufSize); Win32Error.ThrowIfError( CredUi.CredPackAuthenticationBuffer(flags, userName, string.Empty, inBufferPtr, ref desiredBufSize), "Unable to write to credential buffer." ); } private static bool DisplayCredentialPrompt( ref CredUi.CredentialUiInfo credUiInfo, ref CredUi.CredentialPackFlags packFlags, IntPtr inBufferPtr, uint inBufferSize, bool saveCredentials, CredUi.CredentialUiWindowsFlags uiFlags, out ICredential credential) { uint authPackage = 0; IntPtr outBufferPtr = IntPtr.Zero; uint outBufferSize; try { // Open a standard Windows authentication dialog to acquire username and password credentials int error = CredUi.CredUIPromptForWindowsCredentials( ref credUiInfo, 0, ref authPackage, inBufferPtr, inBufferSize, out outBufferPtr, out outBufferSize, ref saveCredentials, uiFlags); switch (error) { case Win32Error.Cancelled: credential = null; return false; default: Win32Error.ThrowIfError(error, "Failed to show credential prompt."); break; } int maxUserLength = 512; int maxPassLength = 512; int maxDomainLength = 256; var usernameBuffer = new StringBuilder(maxUserLength); var domainBuffer = new StringBuilder(maxDomainLength); var passwordBuffer = new StringBuilder(maxPassLength); // Unpack the result Win32Error.ThrowIfError( CredUi.CredUnPackAuthenticationBuffer( packFlags, outBufferPtr, outBufferSize, usernameBuffer, ref maxUserLength, domainBuffer, ref maxDomainLength, passwordBuffer, ref maxPassLength), "Failed to unpack credential buffer." ); // Return the plaintext credential strings to the caller string userName = usernameBuffer.ToString(); string password = passwordBuffer.ToString(); credential = new GitCredential(userName, password); return true; } finally { if (outBufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(outBufferPtr); } } } } }
38.830189
152
0.557823
[ "MIT" ]
0823969789/Git-Credential-Manager-Core
src/shared/Microsoft.Git.CredentialManager/Interop/Windows/WindowsSystemPrompts.cs
6,174
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using PMDVoices2SQLite; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PMDVoices2SQLite.Tests { [TestClass()] public class PMDVoiceMethodTests { [TestMethod()] public void VoiceParserTest() { string? pmdVoiceText; pmdVoiceText = ";NM ALG FBL" + Environment.NewLine + "@000 002 007 = APiano" + Environment.NewLine + "; ar dr sr rr sl tl ks ml dt ams" + Environment.NewLine + " 031 005 000 006 001 037 000 001 007 000" + Environment.NewLine + " 031 005 003 006 001 047 002 012 000 000" + Environment.NewLine + " 031 005 000 006 001 035 000 003 003 000" + Environment.NewLine + " 015 004 000 007 015 000 003 001 000 000" + Environment.NewLine; PMDVoice voice = new(0, 2, 7, 31, 31, 31, 31, 5, 5, 5, 4, 0, 3, 0, 0, 6, 6, 6, 7, 1, 1, 1, 15, 37, 47, 35, 0, 0, 2, 0, 3, 1, 12, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "None", "= APiano"); PMDVoice[]? expected = new PMDVoice[] { voice }; List<PMDVoice>? actual = (List<PMDVoice>)PMDVoiceMethod.VoiceParser(pmdVoiceText); Assert.AreEqual(expected[0], actual[0]); } [TestMethod()] public void ToMMLTest() { string? pmdVoiceText; pmdVoiceText = "; NM ALG FBL" + Environment.NewLine + "@000 002 007 = APiano" + Environment.NewLine + "; AR DR SR RR SL TL KS ML DT AMS" + Environment.NewLine + " 031 005 000 006 001 037 000 001 007 000 " + Environment.NewLine + " 031 005 003 006 001 047 002 012 000 000 " + Environment.NewLine + " 031 005 000 006 001 035 000 003 003 000 " + Environment.NewLine + " 015 004 000 007 015 000 003 001 000 000 " + Environment.NewLine; PMDVoice voice = new(0, 2, 7, 31, 31, 31, 15, 5, 5, 5, 4, 0, 3, 0, 0, 6, 6, 6, 7, 1, 1, 1, 15, 37, 47, 35, 0, 0, 2, 0, 3, 1, 12, 3, 1, 7, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, "None", "= APiano"); string? expected = pmdVoiceText; string? actual = voice.ToMML(true, false); Assert.AreEqual(expected, actual); } } }
39.149254
94
0.500572
[ "CC0-1.0" ]
average34/PMDVoices2SQLite
PMDVoices2SQLiteTests/PMDVoiceMethodTests.cs
2,625
C#
using Codeplex.Data; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace HatoDSP { public class PatchReader { Dictionary<string, CellTree> cells = new Dictionary<string, CellTree>(); Dictionary<string, string[]> children = new Dictionary<string, string[]>(); Dictionary<string, double[]> ctrl = new Dictionary<string, double[]>(); // TODO: エクスプレッションの対応 string root = null; public CellTree Root { get { return cells[root]; } } public static string RemoveComments(string jsonWithComments) { // jsonではコメント使えないんですか!?!? //json = Regex.Replace(json, @"//.*$", "", RegexOptions.Multiline); //json = Regex.Replace(json, @"/\*.*\*/", ""); // これだと /* /* */ もアレしてしまう気がする //json = Regex.Replace(json, @"/\*.*?\*/", ""); // これだと /* // */ もアレしてしまう //return Regex.Replace(jsonWithComments, @"(/\*.*?\*/|//.*?$)", "", RegexOptions.Multiline | RegexOptions.Singleline); // FIXME: ↑これだと文字列定数中のコメントも削除されそう・・・ // ^((?:[^\"]*?\"(\\\"|[^\"\\])*?\")*?[^\"]*?)(/\*.*?\*/|//.*?\r\n) string pattern = @"^((?:[^\""]*?\""(?:\\\""|[^\""\\])*?\"")*?[^\""]*?)(/\*.*?\*/|//.*?(\r\n|\Z))"; // 改行文字は\r\n // これでどうでしょうか // 処理時間的な意味での改善の余地はあるかもしれない。 int recursionLimit = 1000; while (true) { string replaced = Regex.Replace(jsonWithComments, pattern, "$1\r\n", RegexOptions.Singleline | RegexOptions.Compiled); // 空白文字に置換してもよい // jsonは改行と空白を区別しない if (jsonWithComments == replaced) break; jsonWithComments = replaced; if (--recursionLimit <= 0) break; } Debug.Assert(recursionLimit > 0, "正規表現は難しいよねw"); return jsonWithComments; } public PatchReader(string json) { try { json = RemoveComments(json); dynamic dj = DynamicJson.Parse(json); if (!dj.IsArray) throw new PatchFormatException(); foreach (var x in (dynamic[])dj) { string name = x.name; if (name == "$synth") { dynamic[] cldrn = (dynamic[])x.children; if (cldrn.Length != 1) new NotImplementedException("あー"); string cld = (string)cldrn[0]; if (cld.LastIndexOf(":") < 0 || cld.Substring(cld.LastIndexOf(":") + 1) != "0") throw new Exception("あー"); root = cld.Substring(0, cld.LastIndexOf(":")); } else { cells[name] = new CellTree(x.name, x.module); // TODO: childrenのポート番号の指定 if (x.IsDefined("children")) { children[name] = (string[])x.children; } if (x.IsDefined("ctrl")) { ctrl[name] = (double[])x.ctrl; } } } foreach (var x in children) { cells[x.Key].AddChildren(x.Value.Select(y => { // "name:port" の形で指定する。portの省略は多分できない。 int idx = y.LastIndexOf(":"); if (idx == -1) throw new Exception("child は name:port の形で指定して下さい。portの省略はできません。"); string name = y.Substring(0, idx); int port = Int32.Parse(y.Substring(idx + 1)); return new CellWire(cells[name], port); }).ToArray()); } foreach (var x in ctrl) { cells[x.Key].AssignControllers(x.Value.Select(y => new CellParameterValue((float)y)).ToArray()); } if (root == null) throw new PatchFormatException(); } catch (System.Xml.XmlException ex) { throw new PatchFormatException(ex.ToString()); } } } }
36.153226
151
0.447245
[ "MIT" ]
yuinore/HeartBeat
HatoDSP/PatchReader.cs
4,911
C#
using System; using System.Windows.Forms; using AdminTools.Forms; namespace AdminTools { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } } }
20.764706
65
0.614731
[ "MIT" ]
Gartenschlaeger/AdminTools
AdminTools/Program.cs
355
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPoolingManager : MonoBehaviour { public static ObjectPoolingManager SharedInstance; [System.Serializable] public class ObjectPoolItem { public GameObject poolItem; public GameObject parentPooler; public int amount; public bool shouldExpand; public bool randomlyPositioned; public bool activeStarted; } [Header("Object Pooling")] [SerializeField] private Vector2 randomXAxis = new Vector2(10, 40); [SerializeField] private Vector2 randomZAxis = new Vector2(10, 40); [SerializeField] private Vector2 randomPosOffset; [SerializeField] private List<ObjectPoolItem> itemsToPool; [SerializeField] private List<GameObject> pooledObjects; private void Awake() { SharedInstance = this; randomXAxis.x -= randomPosOffset.x; randomXAxis.y -= randomPosOffset.x; randomZAxis.x -= randomPosOffset.y; randomZAxis.y -= randomPosOffset.y; pooledObjects = new List<GameObject>(); foreach (ObjectPoolItem item in itemsToPool) { for (int i = 0; i < item.amount; ++i) { GameObject obj = Instantiate(item.poolItem); obj.name = item.poolItem.name; obj.SetActive(item.activeStarted); obj.transform.SetParent(item.parentPooler.transform); if (item.randomlyPositioned) { obj.transform.Translate( new Vector3(Random.Range(randomXAxis.x, randomXAxis.y), 0, Random.Range(randomZAxis.x, randomZAxis.y))); } pooledObjects.Add(obj); } if (item.poolItem.name.Contains("BoxItem")) { StartCoroutine(nameof(SpawnBoxItem), item.poolItem.name); } } } IEnumerator SpawnBoxItem(string itemName) { if(PoolNamedObject(itemName, true)) { yield return new WaitForSeconds(5.0f); StartCoroutine(nameof(SpawnBoxItem), itemName); } else { yield return new WaitForSeconds(20.0f); StartCoroutine(nameof(SpawnBoxItem), itemName); } } public bool PoolNamedObject(string name) { int idx = 0; foreach (ObjectPoolItem item in itemsToPool) { if(item.poolItem.name.Equals(name)) { for(int i = idx; i < idx + item.amount; ++i) { if (!pooledObjects[i].activeSelf) { pooledObjects[i].SetActive(true); return true; } } } else { idx += item.amount; continue; } } return false; } public bool PoolNamedObject(string name, bool randomly) { int idx = 0; foreach (ObjectPoolItem item in itemsToPool) { if (item.poolItem.name.Equals(name)) { for (int i = idx; i < idx + item.amount; ++i) { if (!pooledObjects[i].activeSelf) { pooledObjects[i].SetActive(true); if (randomly) { pooledObjects[i].transform.Translate( new Vector3(Random.Range(randomXAxis.x, randomXAxis.y), 0, Random.Range(randomZAxis.x, randomZAxis.y))); } return true; } } } else { idx += item.amount; continue; } } return false; } public GameObject GetPooledObject(string tag) { for (int i = 0; i < pooledObjects.Count; ++i) { if (!pooledObjects[i].activeInHierarchy && pooledObjects[i].CompareTag(tag)) { return pooledObjects[i]; } } foreach (ObjectPoolItem item in itemsToPool) { if(item.poolItem.CompareTag(tag) && item.shouldExpand) { GameObject obj = Instantiate(item.poolItem); obj.SetActive(false); obj.transform.SetParent(item.parentPooler.transform); pooledObjects.Add(obj); return obj; } } return null; } #region Wave managing [System.Serializable] public struct Wave { public bool started; public GameObject enemyObject; public int amounts; public float createInterval; } [Header("Wave")] [SerializeField] private List<Wave> waves; [SerializeField] private float waveInterval; [Header("Wave")] private int currWaveIdx; void Start() { currWaveIdx = 0; StartCoroutine(nameof(GenerateEnemy), currWaveIdx); } IEnumerator GenerateEnemy(int idx) { for (int i = 0; i < waves[idx].amounts; ++i) { PoolNamedObject(waves[idx].enemyObject.name, true); yield return new WaitForSeconds(waves[idx].createInterval); } currWaveIdx++; if (currWaveIdx < waves.Count) { StartCoroutine(nameof(GenerateEnemy), currWaveIdx); } } #endregion }
20.652381
79
0.67489
[ "Apache-2.0" ]
PioneerRedwood/BrawlMasters
Assets/Scripts/Managers/ObjectPoolingManager.cs
4,337
C#
namespace MassTransit.ActiveMqTransport.Configuration { using System; using System.Collections.Generic; public class ActiveMqHostConfigurator : IActiveMqHostConfigurator { readonly ConfigurationHostSettings _settings; public ActiveMqHostConfigurator(Uri address) { _settings = new ConfigurationHostSettings(address); if (_settings.Port == 61617 || _settings.Host.EndsWith("amazonaws.com", StringComparison.OrdinalIgnoreCase)) UseSsl(); } public ActiveMqHostSettings Settings => _settings; public void Username(string username) { _settings.Username = username; } public void Password(string password) { _settings.Password = password; } public void UseSsl() { _settings.UseSsl = true; if (_settings.Port == 61616) _settings.Port = 61617; } public void FailoverHosts(string[] hosts) { _settings.FailoverHosts = hosts; } public void TransportOptions(IEnumerable<KeyValuePair<string, string>> options) { foreach (KeyValuePair<string, string> option in options) _settings.TransportOptions[option.Key] = option.Value; } public void EnableOptimizeAcknowledge() { _settings.TransportOptions["jms.optimizeAcknowledge"] = "true"; } public void SetPrefetchPolicy(int limit) { _settings.TransportOptions["jms.prefetchPolicy.all"] = limit.ToString(); } public void SetQueuePrefetchPolicy(int limit) { _settings.TransportOptions["jms.prefetchPolicy.queuePrefetch"] = limit.ToString(); } } }
27.712121
120
0.604155
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/Transports/MassTransit.ActiveMqTransport/ActiveMqTransport/Configuration/ActiveMqHostConfigurator.cs
1,829
C#
using System; using System.Threading; using Microsoft.Extensions.Logging; namespace k8s.Operators { /// <summary> /// Implements the watch callback method for a given <namespace, resource, label selector> /// </summary> public class EventWatcher { private readonly ILogger _logger; private readonly CancellationToken _cancellationToken; public Type ResourceType { get; private set; } public CustomResourceDefinitionAttribute CRD { get; private set; } public string Namespace { get; private set; } public string LabelSelector { get; private set; } public IController Controller { get; private set; } public EventWatcher(Type resourceType, string @namespace, string labelSelector, IController controller, ILogger logger, CancellationToken cancellationToken) { this.ResourceType = resourceType; this.Namespace = @namespace; this.LabelSelector = labelSelector; this.Controller = controller; this._logger = logger; this._cancellationToken = cancellationToken; // Retrieve the CRD associated to the CR var crd = (CustomResourceDefinitionAttribute)Attribute.GetCustomAttribute(resourceType, typeof(CustomResourceDefinitionAttribute)); this.CRD = crd; } /// <summary> /// Dispatches an incoming event to the controller /// </summary> public void OnIncomingEvent(WatchEventType eventType, CustomResource resource) { var resourceEvent = new CustomResourceEvent(eventType, resource); _logger.LogDebug($"Received event {resourceEvent}"); Controller.ProcessEventAsync(resourceEvent, _cancellationToken) .ContinueWith(t => { if (t.IsFaulted) { var exception = t.Exception.Flatten().InnerException; _logger.LogError(exception, $"Error processing {resourceEvent}"); } }); } } }
38.581818
164
0.62394
[ "Apache-2.0" ]
falox/csharp-operator-sdk
src/k8s.Operators/EventWatcher.cs
2,122
C#
using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using Seeker.Data.Models; namespace Seeker.Web.Areas.Identity.Pages.Account { [AllowAnonymous] public class ExternalLoginModel : PageModel { private readonly SignInManager<SeekerUser> _signInManager; private readonly UserManager<SeekerUser> _userManager; private readonly ILogger<ExternalLoginModel> _logger; public ExternalLoginModel( SignInManager<SeekerUser> signInManager, UserManager<SeekerUser> userManager, ILogger<ExternalLoginModel> logger) { _signInManager = signInManager; _userManager = userManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public string LoginProvider { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } } public IActionResult OnGetAsync() { return RedirectToPage("./Login"); } public IActionResult OnPost(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return RedirectToPage("./Login", new {ReturnUrl = returnUrl }); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information."; return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return LocalRedirect(returnUrl); } if (result.IsLockedOut) { return RedirectToPage("./Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ReturnUrl = returnUrl; LoginProvider = info.LoginProvider; if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { Input = new InputModel { Email = info.Principal.FindFirstValue(ClaimTypes.Email) }; } return Page(); } } public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } if (ModelState.IsValid) { var user = new SeekerUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return Page(); } } }
38.402878
154
0.572312
[ "MIT" ]
DamnStation/Seeker
src/Seeker/Web/Seeker.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs
5,340
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.ResourceManager; using Azure.ResourceManager.Sql; namespace Azure.ResourceManager.Sql.Models { /// <summary> Creates or updates a job step. This will implicitly create a new job version. </summary> public partial class ServerJobAgentJobStepCreateOrUpdateOperation : Operation<ServerJobAgentJobStep> { private readonly OperationOrResponseInternals<ServerJobAgentJobStep> _operation; /// <summary> Initializes a new instance of ServerJobAgentJobStepCreateOrUpdateOperation for mocking. </summary> protected ServerJobAgentJobStepCreateOrUpdateOperation() { } internal ServerJobAgentJobStepCreateOrUpdateOperation(ArmClient armClient, Response<JobStepData> response) { _operation = new OperationOrResponseInternals<ServerJobAgentJobStep>(Response.FromValue(new ServerJobAgentJobStep(armClient, response.Value), response.GetRawResponse())); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override ServerJobAgentJobStep Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<ServerJobAgentJobStep>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<ServerJobAgentJobStep>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); } }
41.131148
236
0.738143
[ "MIT" ]
danielortega-msft/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/LongRunningOperation/ServerJobAgentJobStepCreateOrUpdateOperation.cs
2,509
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. namespace Mosa.Compiler.Framework.IR { /// <summary> /// MulOverflowOut64 /// </summary> /// <seealso cref="Mosa.Compiler.Framework.IR.BaseIRInstruction" /> public sealed class MulOverflowOut64 : BaseIRInstruction { public MulOverflowOut64() : base(2, 2) { } public override bool IsCommutative { get { return true; } } } }
22.095238
68
0.702586
[ "BSD-3-Clause" ]
AnErrupTion/MOSA-Project
Source/Mosa.Compiler.Framework/IR/MulOverflowOut64.cs
464
C#
using DexTranslate.Abstractions.Service; using DexTranslate.Api.Controllers; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Moq; using System.IO; using System.Threading.Tasks; using Xunit; namespace DexTranslate.ApiFixtures { public class ImportControllerFixtures { [Fact] public async Task It_Can_Import_Csv_File() { // Arrange var service = new Mock<IImportService>(); var controller = SetUp(service); // Act var file = new Mock<IFormFile>(); var result = await controller.Post(file.Object, "nl-NL", true) as OkResult; // Assert Assert.NotNull(result); service.Verify(s => s.ImportTranslations(It.Is<string>(l => l == "nl-NL"), It.Is<bool>(m => m), It.IsAny<Stream>()), Times.Once); } private static ImportController SetUp( Mock<IImportService> service = null, Mock<ILogger<ImportController>> logger = null) { service = service ?? new Mock<IImportService>(); logger = logger ?? new Mock<ILogger<ImportController>>(); var controller = new ImportController(logger.Object, service.Object); return controller; } } }
31.595238
141
0.616428
[ "MIT" ]
dexgrid/dextranslate
tests/DexTranslate.ApiFixtures/ImportControllerFixtures.cs
1,329
C#
// <auto-generated /> namespace Microsoft.AspNetCore.Localization { using System.Globalization; using System.Reflection; using System.Resources; internal static class Resources { private static readonly ResourceManager _resourceManager = new ResourceManager("Microsoft.AspNetCore.Localization.Resources", typeof(Resources).GetTypeInfo().Assembly); /// <summary> /// Please provide at least one culture. /// </summary> internal static string Exception_CulturesShouldNotBeEmpty { get => GetString("Exception_CulturesShouldNotBeEmpty"); } /// <summary> /// Please provide at least one culture. /// </summary> internal static string FormatException_CulturesShouldNotBeEmpty() => GetString("Exception_CulturesShouldNotBeEmpty"); private static string GetString(string name, params string[] formatterNames) { var value = _resourceManager.GetString(name); System.Diagnostics.Debug.Assert(value != null); if (formatterNames != null) { for (var i = 0; i < formatterNames.Length; i++) { value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}"); } } return value; } } }
30.866667
123
0.585313
[ "Apache-2.0" ]
CBaud/AspNetCore
src/Middleware/Localization/src/Properties/Resources.Designer.cs
1,389
C#
using System; using System.Collections.Generic; #nullable disable namespace P1FinalDbContext { public partial class Customer { public Customer() { Orders = new HashSet<Order>(); } public int CustomerId { get; set; } public string Fname { get; set; } public string Lname { get; set; } public string Username { get; set; } public string Password { get; set; } public string Email { get; set; } public virtual ICollection<Order> Orders { get; set; } } }
22.4
62
0.585714
[ "MIT" ]
06012021-dotnet-uta/ChristianRomeroP1
P1FinalDbContext/Customer.cs
562
C#
using System; namespace Reference.Lib.DataStructures.Graphs { public interface IWeightedEdge<T, W> : IEdge<T> where T : IComparable<T> where W : IComparable<W> { W Weight { get; } } }
20
51
0.609091
[ "MIT" ]
lsadam0/Reference.Lib
src/Reference.Lib/DataStructures/Graphs/IWeightedEdge.cs
220
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace WinAppDriver.Extensions { public static class COMExceptionExtensions { public static bool IsTimeout(this COMException comEx) { // Operation timed out. (Exception from HRESULT: 0x80131505) return comEx.Message.StartsWith("Operation timed out") || comEx.Message.Contains("0x80131505"); } } }
27.157895
107
0.709302
[ "MIT" ]
ejhollas/WinAppDriver
WinAppDriver/Extensions/COMExceptionExtensions.cs
518
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR; public class PlayerMovementFPS : MonoBehaviour { [SerializeField] KeyCode jumpKey = KeyCode.Space; public CharacterController controller; public float speed = 12f; //Apparently mixing character controller and rigidbody is a bad idea, so instead to get //things like gravity we introduce the velocity vector which is updated. public float gravity = -9.81f; Vector3 velocity; public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; public float jumpHeight = 6f; public float groundDeathHeight = 30f; bool isGrounded; private PlayerHealth playerHealth; InputDevice device; // Start is called before the first frame update void Start() { var rightHandDevices = new List<InputDevice>(); InputDevices.GetDevicesAtXRNode(UnityEngine.XR.XRNode.RightHand, rightHandDevices); if(rightHandDevices.Count == 1) { device = rightHandDevices[0]; Debug.Log("Found left hand device"); } else { Debug.Log("No left hand devices!!"); } playerHealth = (PlayerHealth)FindObjectOfType(typeof(PlayerHealth)); } // Update is called once per frame void Update() { if (controller.transform.position.y < groundDeathHeight) { playerHealth.OnDamage(25); } //isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); isGrounded = controller.isGrounded; if (isGrounded && velocity.y < 0) { velocity.y = -2f; //"Set to zero" but actually force player to indeed hit the bottom } bool jumpValue; if ( isGrounded && ( Input.GetKeyDown(jumpKey) || (device.TryGetFeatureValue(UnityEngine.XR.CommonUsages.primaryButton, out jumpValue) && jumpValue) ) ){ velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity); } float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); //local coordinates based direction we want to move Vector3 move = transform.right * x + transform.forward * z; controller.Move(move * speed * Time.deltaTime); velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); } }
30.695122
114
0.634485
[ "MIT" ]
Ziggareto/ucl-vr-game-2021
Assets/Scripts/MovementLooking/PlayerMovementFPS.cs
2,519
C#
/* * Prime Developer Trial * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals.Client.OpenAPIDateConverter; namespace FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals.Model { /// <summary> /// Value range of the sideways yield relative to the ask price. /// </summary> [DataContract(Name = "_securitizedDerivative_notation_screener_valueRanges_get_data_keyFigures_sidewaysYield_relative")] public partial class SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative : IEquatable<SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative" /> class. /// </summary> /// <param name="minimum">minimum.</param> /// <param name="maximum">maximum.</param> public SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative(SecuritizedDerivativeNotationRankingIntradayListDataPerformanceRelativeMinimum minimum = default(SecuritizedDerivativeNotationRankingIntradayListDataPerformanceRelativeMinimum), SecuritizedDerivativeNotationRankingIntradayListDataPerformanceRelativeMaximum maximum = default(SecuritizedDerivativeNotationRankingIntradayListDataPerformanceRelativeMaximum)) { this.Minimum = minimum; this.Maximum = maximum; } /// <summary> /// Gets or Sets Minimum /// </summary> [DataMember(Name = "minimum", EmitDefaultValue = false)] public SecuritizedDerivativeNotationRankingIntradayListDataPerformanceRelativeMinimum Minimum { get; set; } /// <summary> /// Gets or Sets Maximum /// </summary> [DataMember(Name = "maximum", EmitDefaultValue = false)] public SecuritizedDerivativeNotationRankingIntradayListDataPerformanceRelativeMaximum Maximum { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative {\n"); sb.Append(" Minimum: ").Append(Minimum).Append("\n"); sb.Append(" Maximum: ").Append(Maximum).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative); } /// <summary> /// Returns true if SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative instances are equal /// </summary> /// <param name="input">Instance of SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative to be compared</param> /// <returns>Boolean</returns> public bool Equals(SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative input) { if (input == null) { return false; } return ( this.Minimum == input.Minimum || (this.Minimum != null && this.Minimum.Equals(input.Minimum)) ) && ( this.Maximum == input.Maximum || (this.Maximum != null && this.Maximum.Equals(input.Maximum)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Minimum != null) { hashCode = (hashCode * 59) + this.Minimum.GetHashCode(); } if (this.Maximum != null) { hashCode = (hashCode * 59) + this.Maximum.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
41.204082
457
0.648176
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/SecuritizedDerivativesAPIforDigitalPortals/v2/src/FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals/Model/SecuritizedDerivativeNotationScreenerValueRangesGetDataKeyFiguresSidewaysYieldRelative.cs
6,057
C#
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; namespace Mundipagg.Models.Request { [JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class UpdateSubscriptionBillingDateRequest { public DateTime NextBillingAt { get; set; } } }
25.166667
70
0.761589
[ "MIT" ]
AmandaMaiaPessanha/mundipagg-dotnet
Mundipagg/Models/Request/UpdateSubscriptionBillingDateRequest.cs
302
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using SeoSchema; using SeoSchema.Enumerations; using SuperStructs; namespace SeoSchema.Entities { /// <summary> /// The act of giving money to a seller in exchange for goods or services rendered. An agent buys an object, product, or service from a seller for a price. Reciprocal of SellAction. /// <see cref="https://schema.org/BuyAction"/> /// </summary> public class BuyAction : IEntity { /// An entity which offers (sells / leases / lends / loans) the services / goods. A seller may also be a provider. Supersedes merchant, vendor. public Or<Organization, Person>? Seller { get; set; } /// The offer price of a product, or of a price component when attached to PriceSpecification and its subtypes. /// /// Usage guidelines: /// /// /// Use the priceCurrency property (with standard formats: ISO 4217 currency format e.g. "USD"; Ticker symbol for cryptocurrencies e.g. "BTC"; well known names for Local Exchange Tradings Systems (LETS) and other currency types e.g. "Ithaca HOUR") instead of including ambiguous symbols such as '$' in the value. /// Use '.' (Unicode 'FULL STOP' (U+002E)) rather than ',' to indicate a decimal point. Avoid using these symbols as a readability separator. /// Note that both RDFa and Microdata syntax allow the use of a "content=" attribute for publishing simple machine-readable values alongside more human-friendly formatting. /// Use values from 0123456789 (Unicode 'DIGIT ZERO' (U+0030) to 'DIGIT NINE' (U+0039)) rather than superficially similiar Unicode symbols. public Or<double, string>? Price { get; set; } /// One or more detailed price specifications, indicating the unit price and delivery or payment charges. public Or<PriceSpecification>? PriceSpecification { get; set; } /// Indicates the current disposition of the Action. public Or<ActionStatusType>? ActionStatus { get; set; } /// The direct performer or driver of the action (animate or inanimate). e.g. John wrote a book. public Or<Organization, Person>? Agent { get; set; } /// The endTime of something. For a reserved event or service (e.g. FoodEstablishmentReservation), the time that it is expected to end. For actions that span a period of time, when the action was performed. e.g. John wrote a book from January to December. /// /// Note that Event uses startDate/endDate instead of startTime/endTime, even when describing dates with times. This situation may be clarified in future revisions. public Or<DateTime>? EndTime { get; set; } /// For failed actions, more information on the cause of the failure. public Or<Thing>? Error { get; set; } /// The object that helped the agent perform the action. e.g. John wrote a book with a pen. public Or<Thing>? Instrument { get; set; } /// The location of for example where the event is happening, an organization is located, or where an action takes place. public Or<Place, PostalAddress, string>? Location { get; set; } /// The object upon which the action is carried out, whose state is kept intact or changed. Also known as the semantic roles patient, affected or undergoer (which change their state) or theme (which doesn't). e.g. John read a book. public Or<Thing>? Object { get; set; } /// Other co-agents that participated in the action indirectly. e.g. John wrote a book with Steve. public Or<Organization, Person>? Participant { get; set; } /// The result produced in the action. e.g. John wrote a book. public Or<Thing>? Result { get; set; } /// The startTime of something. For a reserved event or service (e.g. FoodEstablishmentReservation), the time that it is expected to start. For actions that span a period of time, when the action was performed. e.g. John wrote a book from January to December. /// /// Note that Event uses startDate/endDate instead of startTime/endTime, even when describing dates with times. This situation may be clarified in future revisions. public Or<DateTime>? StartTime { get; set; } /// Indicates a target EntryPoint for an Action. public Or<EntryPoint>? Target { get; set; } /// An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally. public Or<Uri>? AdditionalType { get; set; } /// An alias for the item. public Or<string>? AlternateName { get; set; } /// A description of the item. public Or<string>? Description { get; set; } /// A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation. public Or<string>? DisambiguatingDescription { get; set; } /// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details. public Or<PropertyValue, string, Uri>? Identifier { get; set; } /// An image of the item. This can be a URL or a fully described ImageObject. public Or<ImageObject, Uri>? Image { get; set; } /// Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details. Inverse property: mainEntity. public Or<CreativeWork, Uri>? MainEntityOfPage { get; set; } /// The name of the item. public Or<string>? Name { get; set; } /// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role. public Or<Action>? PotentialAction { get; set; } /// URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website. public Or<Uri>? SameAs { get; set; } /// A CreativeWork or Event about this Thing.. Inverse property: about. public Or<CreativeWork, Event>? SubjectOf { get; set; } /// URL of the item. public Or<Uri>? Url { get; set; } } }
63.583333
427
0.690403
[ "MIT" ]
jefersonsv/SeoSchema
src/SeoSchema/Entities/BuyAction.cs
6,867
C#
using System; using System.Linq; class Euler1_3 { public static void Main() { var range = Enumerable.Range(1, 999); var result = (from n in range where n % 3 == 0 || n % 5 == 0 select n).Sum(); Console.WriteLine(result); } }
21.066667
52
0.474684
[ "MIT" ]
gdm9000/euler1
c#/euler1_3.cs
316
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; namespace FamousQuotes.App.Areas.Identity.Pages.Account.Manage { public static class ManageNavPages { public static string Index => "Index"; public static string Email => "Email"; public static string ChangePassword => "ChangePassword"; public static string DownloadPersonalData => "DownloadPersonalData"; public static string DeletePersonalData => "DeletePersonalData"; public static string ExternalLogins => "ExternalLogins"; public static string PersonalData => "PersonalData"; public static string TwoFactorAuthentication => "TwoFactorAuthentication"; public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index); public static string EmailNavClass(ViewContext viewContext) => PageNavClass(viewContext, Email); public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword); public static string DownloadPersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DownloadPersonalData); public static string DeletePersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, DeletePersonalData); public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins); public static string PersonalDataNavClass(ViewContext viewContext) => PageNavClass(viewContext, PersonalData); public static string TwoFactorAuthenticationNavClass(ViewContext viewContext) => PageNavClass(viewContext, TwoFactorAuthentication); private static string PageNavClass(ViewContext viewContext, string page) { var activePage = viewContext.ViewData["ActivePage"] as string ?? System.IO.Path.GetFileNameWithoutExtension(viewContext.ActionDescriptor.DisplayName); return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null; } } }
42.372549
140
0.751041
[ "MIT" ]
mayapeneva/FamousQuotes
FamousQuotes.App/Areas/Identity/Pages/Account/Manage/ManageNavPages.cs
2,163
C#
using System; using System.Collections.Generic; using UnityEngine; namespace Unity.VisualScripting { public sealed class DescriptorProvider : SingleDecoratorProvider<object, IDescriptor, DescriptorAttribute>, IDisposable { private readonly Dictionary<object, HashSet<Action>> listeners = new Dictionary<object, HashSet<Action>>(); protected override bool cache => true; private DescriptorProvider() { PluginContainer.delayCall += () => // The provider gets created at runtime on Start for the debug data { BoltCore.Configuration.namingSchemeChanged += DescribeAll; XmlDocumentation.loadComplete += DescribeAll; }; } public override bool IsValid(object described) { return !described.IsUnityNull(); } public void Dispose() { BoltCore.Configuration.namingSchemeChanged -= DescribeAll; XmlDocumentation.loadComplete -= DescribeAll; ClearListeners(); } public void AddListener(object describable, Action onDescriptionChange) { if (!listeners.ContainsKey(describable)) { listeners.Add(describable, new HashSet<Action>()); } listeners[describable].Add(onDescriptionChange); } public void RemoveListener(object describable, Action onDescriptionChange) { if (!listeners.ContainsKey(describable)) { Debug.LogWarning($"Trying to remove unknown description change listener for '{describable}'."); return; } listeners[describable].Remove(onDescriptionChange); if (listeners[describable].Count == 0) { listeners.Remove(describable); } } public void ClearListeners() { listeners.Clear(); } public void TriggerDescriptionChange(object describable) { if (!listeners.ContainsKey(describable)) { return; } foreach (var onDescriptionChange in listeners[describable]) { onDescriptionChange?.Invoke(); } } public void Describe(object describable) { GetDecorator(describable).isDirty = true; } public void DescribeAll() { foreach (var descriptor in decorators.Values) { descriptor.isDirty = true; } } public IDescriptor Descriptor(object target) { return GetDecorator(target); } public TDescriptor Descriptor<TDescriptor>(object target) where TDescriptor : IDescriptor { return GetDecorator<TDescriptor>(target); } public IDescription Description(object target) { var descriptor = Descriptor(target); descriptor.Validate(); return descriptor.description; } public TDescription Description<TDescription>(object target) where TDescription : IDescription { var description = Description(target); if (!(description is TDescription)) { throw new InvalidCastException($"Description type mismatch for '{target}': found {description.GetType()}, expected {typeof(TDescription)}."); } return (TDescription)description; } static DescriptorProvider() { instance = new DescriptorProvider(); } public static DescriptorProvider instance { get; } } public static class XDescriptorProvider { public static void Describe(this object target) { DescriptorProvider.instance.Describe(target); } public static bool HasDescriptor(this object target) { Ensure.That(nameof(target)).IsNotNull(target); return DescriptorProvider.instance.HasDecorator(target.GetType()); } public static IDescriptor Descriptor(this object target) { return DescriptorProvider.instance.Descriptor(target); } public static TDescriptor Descriptor<TDescriptor>(this object target) where TDescriptor : IDescriptor { return DescriptorProvider.instance.Descriptor<TDescriptor>(target); } public static IDescription Description(this object target) { return DescriptorProvider.instance.Description(target); } public static TDescription Description<TDescription>(this object target) where TDescription : IDescription { return DescriptorProvider.instance.Description<TDescription>(target); } } }
29.871951
157
0.593182
[ "MIT" ]
2PUEG-VRIK/UnityEscapeGame
2P-UnityEscapeGame/Library/PackageCache/com.unity.visualscripting@1.6.1/Editor/VisualScripting.Core/Descriptors/DescriptorProvider.cs
4,899
C#
using System; using Arcus.Messaging.Abstractions.ServiceBus.MessageHandling; using GuardNet; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { /// <summary> /// Extensions on the <see cref="IServiceCollection"/> to add an <see cref="IAzureServiceBusMessageHandler{TMessage}"/>'s implementations. /// </summary> // ReSharper disable once InconsistentNaming public static class IServiceCollectionExtensions { /// <summary> /// Adds an <see cref="IAzureServiceBusMessageRouter"/> implementation /// to route the incoming messages through registered <see cref="IAzureServiceBusMessageHandler{TMessage}"/> instances. /// </summary> /// <param name="services">The collection of services to add the router to.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="services"/> is <c>null</c>.</exception> public static ServiceBusMessageHandlerCollection AddServiceBusMessageRouting(this IServiceCollection services) { Guard.NotNull(services, nameof(services), "Requires a set of services to register the Azure Service Bus message routing"); return AddServiceBusMessageRouting(services, configureOptions: null); } /// <summary> /// Adds an <see cref="IAzureServiceBusMessageRouter"/> implementation /// to route the incoming messages through registered <see cref="IAzureServiceBusMessageHandler{TMessage}"/> instances. /// </summary> /// <param name="services">The collection of services to add the router to.</param> /// <param name="configureOptions">The function to configure the options that change the behavior of the router.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="services"/> is <c>null</c>.</exception> public static ServiceBusMessageHandlerCollection AddServiceBusMessageRouting( this IServiceCollection services, Action<AzureServiceBusMessageRouterOptions> configureOptions) { Guard.NotNull(services, nameof(services), "Requires a set of services to register the Azure Service Bus message routing"); return AddServiceBusMessageRouting(services, serviceProvider => { var options = new AzureServiceBusMessageRouterOptions(); configureOptions?.Invoke(options); var logger = serviceProvider.GetService<ILogger<AzureServiceBusMessageRouter>>(); return new AzureServiceBusMessageRouter(serviceProvider, options, logger); }); } /// <summary> /// Adds an <see cref="IAzureServiceBusMessageRouter"/> implementation /// to route the incoming messages through registered <see cref="IAzureServiceBusMessageHandler{TMessage}"/> instances. /// </summary> /// <param name="services">The collection of services to add the router to.</param> /// <param name="implementationFactory">The function to create the <typeparamref name="TMessageRouter"/> implementation.</param> /// <typeparam name="TMessageRouter">The type of the <see cref="IAzureServiceBusMessageRouter"/> implementation.</typeparam> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="services"/> or <paramref name="implementationFactory"/> is <c>null</c>.</exception> public static ServiceBusMessageHandlerCollection AddServiceBusMessageRouting<TMessageRouter>( this IServiceCollection services, Func<IServiceProvider, TMessageRouter> implementationFactory) where TMessageRouter : IAzureServiceBusMessageRouter { Guard.NotNull(services, nameof(services), "Requires a set of services to register the Azure Service Bus message routing"); Guard.NotNull(implementationFactory, nameof(implementationFactory), "Requires a function to create the Azure Service Bus message router"); return AddServiceBusMessageRouting(services, (provider, options) => implementationFactory(provider), configureOptions: null); } /// <summary> /// Adds an <see cref="IAzureServiceBusMessageRouter"/> implementation /// to route the incoming messages through registered <see cref="IAzureServiceBusMessageHandler{TMessage}"/> instances. /// </summary> /// <param name="services">The collection of services to add the router to.</param> /// <param name="implementationFactory">The function to create the <typeparamref name="TMessageRouter"/> implementation.</param> /// <param name="configureOptions">The function to configure the options that change the behavior of the router.</param> /// <typeparam name="TMessageRouter">The type of the <see cref="IAzureServiceBusMessageRouter"/> implementation.</typeparam> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="services"/> or <paramref name="implementationFactory"/> is <c>null</c>.</exception> public static ServiceBusMessageHandlerCollection AddServiceBusMessageRouting<TMessageRouter>( this IServiceCollection services, Func<IServiceProvider, AzureServiceBusMessageRouterOptions, TMessageRouter> implementationFactory, Action<AzureServiceBusMessageRouterOptions> configureOptions) where TMessageRouter : IAzureServiceBusMessageRouter { Guard.NotNull(services, nameof(services), "Requires a set of services to register the Azure Service Bus message routing"); Guard.NotNull(implementationFactory, nameof(implementationFactory), "Requires a function to create the Azure Service Bus message router"); services.TryAddSingleton<IAzureServiceBusMessageRouter>(serviceProvider => { var options = new AzureServiceBusMessageRouterOptions(); configureOptions?.Invoke(options); return implementationFactory(serviceProvider, options); }); services.AddMessageRouting(serviceProvider => serviceProvider.GetRequiredService<IAzureServiceBusMessageRouter>()); return new ServiceBusMessageHandlerCollection(services); } } }
63.45098
167
0.703337
[ "MIT" ]
arcus-azure/arcus.messaging-
src/Arcus.Messaging.Abstractions.ServiceBus/Extensions/IServiceCollectionExtensions.cs
6,474
C#
namespace CTOS { partial class add { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.addData = new System.Windows.Forms.Button(); this.cancelData = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.textBox5 = new System.Windows.Forms.TextBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.textBox7 = new System.Windows.Forms.TextBox(); this.name = new System.Windows.Forms.Label(); this.gender = new System.Windows.Forms.Label(); this.job = new System.Windows.Forms.Label(); this.phone = new System.Windows.Forms.Label(); this.address = new System.Windows.Forms.Label(); this.marriage = new System.Windows.Forms.Label(); this.salary = new System.Windows.Forms.Label(); this.age = new System.Windows.Forms.Label(); this.textBox8 = new System.Windows.Forms.TextBox(); this.id = new System.Windows.Forms.Label(); this.textBox9 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // addData // this.addData.Location = new System.Drawing.Point(14, 274); this.addData.Name = "addData"; this.addData.Size = new System.Drawing.Size(75, 23); this.addData.TabIndex = 0; this.addData.Text = "添加数据"; this.addData.UseVisualStyleBackColor = true; this.addData.Click += new System.EventHandler(this.addData_Click); // // cancelData // this.cancelData.Location = new System.Drawing.Point(115, 274); this.cancelData.Name = "cancelData"; this.cancelData.Size = new System.Drawing.Size(75, 23); this.cancelData.TabIndex = 1; this.cancelData.Text = "结束"; this.cancelData.UseVisualStyleBackColor = true; this.cancelData.Click += new System.EventHandler(this.cancelData_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(115, 13); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 21); this.textBox1.TabIndex = 2; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(115, 41); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(100, 21); this.textBox2.TabIndex = 3; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(115, 69); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(100, 21); this.textBox3.TabIndex = 4; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(115, 97); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(100, 21); this.textBox4.TabIndex = 5; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(115, 125); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(100, 21); this.textBox5.TabIndex = 6; // // textBox6 // this.textBox6.Location = new System.Drawing.Point(115, 153); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(100, 21); this.textBox6.TabIndex = 7; // // textBox7 // this.textBox7.Location = new System.Drawing.Point(115, 181); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(100, 21); this.textBox7.TabIndex = 8; // // name // this.name.AutoSize = true; this.name.Location = new System.Drawing.Point(12, 45); this.name.Name = "name"; this.name.Size = new System.Drawing.Size(29, 12); this.name.TabIndex = 9; this.name.Text = "姓名"; // // gender // this.gender.AutoSize = true; this.gender.Location = new System.Drawing.Point(12, 70); this.gender.Name = "gender"; this.gender.Size = new System.Drawing.Size(29, 12); this.gender.TabIndex = 10; this.gender.Text = "性别"; // // job // this.job.AutoSize = true; this.job.Location = new System.Drawing.Point(12, 98); this.job.Name = "job"; this.job.Size = new System.Drawing.Size(29, 12); this.job.TabIndex = 11; this.job.Text = "职业"; // // phone // this.phone.AutoSize = true; this.phone.Location = new System.Drawing.Point(12, 126); this.phone.Name = "phone"; this.phone.Size = new System.Drawing.Size(29, 12); this.phone.TabIndex = 12; this.phone.Text = "电话"; // // address // this.address.AutoSize = true; this.address.Location = new System.Drawing.Point(12, 157); this.address.Name = "address"; this.address.Size = new System.Drawing.Size(29, 12); this.address.TabIndex = 13; this.address.Text = "地址"; // // marriage // this.marriage.AutoSize = true; this.marriage.Location = new System.Drawing.Point(12, 182); this.marriage.Name = "marriage"; this.marriage.Size = new System.Drawing.Size(53, 12); this.marriage.TabIndex = 14; this.marriage.Text = "婚姻状况"; // // salary // this.salary.AutoSize = true; this.salary.Location = new System.Drawing.Point(12, 210); this.salary.Name = "salary"; this.salary.Size = new System.Drawing.Size(29, 12); this.salary.TabIndex = 15; this.salary.Text = "薪金"; // // age // this.age.AutoSize = true; this.age.Location = new System.Drawing.Point(12, 238); this.age.Name = "age"; this.age.Size = new System.Drawing.Size(29, 12); this.age.TabIndex = 16; this.age.Text = "年龄"; // // textBox8 // this.textBox8.Location = new System.Drawing.Point(115, 209); this.textBox8.Name = "textBox8"; this.textBox8.Size = new System.Drawing.Size(100, 21); this.textBox8.TabIndex = 17; // // id // this.id.AutoSize = true; this.id.Location = new System.Drawing.Point(12, 13); this.id.Name = "id"; this.id.Size = new System.Drawing.Size(17, 12); this.id.TabIndex = 18; this.id.Text = "id"; // // textBox9 // this.textBox9.Location = new System.Drawing.Point(115, 235); this.textBox9.Name = "textBox9"; this.textBox9.Size = new System.Drawing.Size(100, 21); this.textBox9.TabIndex = 19; // // add // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(245, 312); this.Controls.Add(this.textBox9); this.Controls.Add(this.id); this.Controls.Add(this.textBox8); this.Controls.Add(this.age); this.Controls.Add(this.salary); this.Controls.Add(this.marriage); this.Controls.Add(this.address); this.Controls.Add(this.phone); this.Controls.Add(this.job); this.Controls.Add(this.gender); this.Controls.Add(this.name); this.Controls.Add(this.textBox7); this.Controls.Add(this.textBox6); this.Controls.Add(this.textBox5); this.Controls.Add(this.textBox4); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.cancelData); this.Controls.Add(this.addData); this.Name = "add"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "CTOS Database"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button addData; private System.Windows.Forms.Button cancelData; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.Label name; private System.Windows.Forms.Label gender; private System.Windows.Forms.Label job; private System.Windows.Forms.Label phone; private System.Windows.Forms.Label address; private System.Windows.Forms.Label marriage; private System.Windows.Forms.Label salary; private System.Windows.Forms.Label age; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.Label id; private System.Windows.Forms.TextBox textBox9; } }
40.809524
107
0.540257
[ "Apache-2.0" ]
duxingzhe/Customized-System
CTOS/C#/CTOS/add.Designer.cs
11,191
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:2.4.0.0 // SpecFlow Generator Version:2.4.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace SFA.Tl.Matching.Automation.Tests.Project.Tests.Features { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "2.4.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("Select Providers page - Search results")] public partial class SelectProvidersPage_SearchResultsFeature { private TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "SelectProviders_SearchResults.feature" #line hidden [NUnit.Framework.OneTimeSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Select Providers page - Search results", "\tThis feature is used to confirm the search results on the Select providers page " + "are displayed with the correct information. ", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.OneTimeTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioInitialize(scenarioInfo); testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<NUnit.Framework.TestContext>(NUnit.Framework.TestContext.CurrentContext); } public virtual void ScenarioStart() { testRunner.OnScenarioStart(); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } public virtual void FeatureBackground() { #line 4 #line 5 testRunner.Given("I have navigated to the IDAMS login page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 6 testRunner.And("I have logged in as an \"Admin User\"", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 7 testRunner.And("I navigate to the Select Providers page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Select Providers - Details entered on the Find Provider page will be displayed in" + " the header on Select Providers page")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void SelectProviders_DetailsEnteredOnTheFindProviderPageWillBeDisplayedInTheHeaderOnSelectProvidersPage() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Select Providers - Details entered on the Find Provider page will be displayed in" + " the header on Select Providers page", null, new string[] { "regression"}); #line 10 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 11 testRunner.Then("the provider results returned will match the expected values", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 12 testRunner.And("the Select Providers page will display the count, skill area, postcode and radius" + " in the H2 heading", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Search on Select Providers page and return zero results in any skill area")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void SearchOnSelectProvidersPageAndReturnZeroResultsInAnySkillArea() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Search on Select Providers page and return zero results in any skill area", null, new string[] { "regression"}); #line 15 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 16 testRunner.When("I have filled in the search form on the Search Providers page with criteria which" + " returns no results", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 17 testRunner.Then("the Select Providers page will display a H2 heading for zero results", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Search on Select Providers page and return zero results in only selected skill ar" + "ea")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void SearchOnSelectProvidersPageAndReturnZeroResultsInOnlySelectedSkillArea() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Search on Select Providers page and return zero results in only selected skill ar" + "ea", null, new string[] { "regression"}); #line 20 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 21 testRunner.When("I have filled in the search form on the Search Providers page with criteria which" + " returns no results in only selected skill area", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 22 testRunner.Then("the Select Providers page will display a H2 heading for zero results for the sele" + "cted skill area", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Validate search results on Select a Provider page where results are returned 2")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void ValidateSearchResultsOnSelectAProviderPageWhereResultsAreReturned2() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Validate search results on Select a Provider page where results are returned 2", null, new string[] { "regression"}); #line 25 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 26 testRunner.When("I have filled in the search form on the Search Providers page with criteria which" + " returns some results", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 27 testRunner.Then("the provider results returned will match the expected values", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 28 testRunner.And("the Select Providers page will display the count, skill area, postcode and radius" + " in the H2 heading", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Validate search results on Select a Provider page where 1 result is returned")] [NUnit.Framework.CategoryAttribute("regression")] public virtual void ValidateSearchResultsOnSelectAProviderPageWhere1ResultIsReturned() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Validate search results on Select a Provider page where 1 result is returned", null, new string[] { "regression"}); #line 31 this.ScenarioInitialize(scenarioInfo); this.ScenarioStart(); #line 4 this.FeatureBackground(); #line 32 testRunner.When("I have filled in the search form on the Search Providers page with criteria which" + " returns one result", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 33 testRunner.Then("the Select Providers page will display the count, skill area, postcode, radius an" + "d text result in in the H2 heading", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
47.073892
265
0.65676
[ "MIT" ]
SkillsFundingAgency/das-tlevels-automation-suite
src/SFA.Tl.Matching.Automation.Tests/Project/Tests/Features/SelectProviders_SearchResults.feature.cs
9,558
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace BDSA2018.Lecture11.Entities { public class Episode { public int Id { get; set; } [Required] [StringLength(100)] public string Title { get; set; } public DateTime? FirstAired { get; set; } public ICollection<EpisodeCharacter> EpisodeCharacters { get; set; } public Episode() { EpisodeCharacters = new HashSet<EpisodeCharacter>(); } } }
21.56
76
0.625232
[ "MIT" ]
ondfisk/BDSA2018
BDSA2018.Lecture11.Entities/Episode.cs
539
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; namespace Microsoft.AspNetCore.Mvc.ModelBinding { /// <summary> /// A provider that can supply instances of <see cref="ModelMetadata"/>. /// </summary> /// <remarks> /// While not obsolete, implementing or using <see cref="ModelMetadataProvider" /> is preferred over <see cref="IModelMetadataProvider"/>. /// </remarks> public interface IModelMetadataProvider { /// <summary> /// Supplies metadata describing a <see cref="Type"/>. /// </summary> /// <param name="modelType">The <see cref="Type"/>.</param> /// <returns>A <see cref="ModelMetadata"/> instance describing the <see cref="Type"/>.</returns> ModelMetadata GetMetadataForType(Type modelType); /// <summary> /// Supplies metadata describing the properties of a <see cref="Type"/>. /// </summary> /// <param name="modelType">The <see cref="Type"/>.</param> /// <returns>A set of <see cref="ModelMetadata"/> instances describing properties of the <see cref="Type"/>.</returns> IEnumerable<ModelMetadata> GetMetadataForProperties(Type modelType); } }
42.40625
142
0.652911
[ "Apache-2.0" ]
belav/aspnetcore
src/Mvc/Mvc.Abstractions/src/ModelBinding/IModelMetadataProvider.cs
1,357
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DataFactory.Latest.Inputs { /// <summary> /// Delete activity. /// </summary> public sealed class DeleteActivityArgs : Pulumi.ResourceArgs { /// <summary> /// Delete activity dataset reference. /// </summary> [Input("dataset", required: true)] public Input<Inputs.DatasetReferenceArgs> Dataset { get; set; } = null!; [Input("dependsOn")] private InputList<Inputs.ActivityDependencyArgs>? _dependsOn; /// <summary> /// Activity depends on condition. /// </summary> public InputList<Inputs.ActivityDependencyArgs> DependsOn { get => _dependsOn ?? (_dependsOn = new InputList<Inputs.ActivityDependencyArgs>()); set => _dependsOn = value; } /// <summary> /// Activity description. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// Whether to record detailed logs of delete-activity execution. Default value is false. Type: boolean (or Expression with resultType boolean). /// </summary> [Input("enableLogging")] public Input<object>? EnableLogging { get; set; } /// <summary> /// Linked service reference. /// </summary> [Input("linkedServiceName")] public Input<Inputs.LinkedServiceReferenceArgs>? LinkedServiceName { get; set; } /// <summary> /// Log storage settings customer need to provide when enableLogging is true. /// </summary> [Input("logStorageSettings")] public Input<Inputs.LogStorageSettingsArgs>? LogStorageSettings { get; set; } /// <summary> /// The max concurrent connections to connect data source at the same time. /// </summary> [Input("maxConcurrentConnections")] public Input<int>? MaxConcurrentConnections { get; set; } /// <summary> /// Activity name. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// Activity policy. /// </summary> [Input("policy")] public Input<Inputs.ActivityPolicyArgs>? Policy { get; set; } /// <summary> /// If true, files or sub-folders under current folder path will be deleted recursively. Default is false. Type: boolean (or Expression with resultType boolean). /// </summary> [Input("recursive")] public Input<object>? Recursive { get; set; } /// <summary> /// Delete activity store settings. /// </summary> [Input("storeSettings")] public Input<object>? StoreSettings { get; set; } /// <summary> /// Type of activity. /// Expected value is 'Execution'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; [Input("userProperties")] private InputList<Inputs.UserPropertyArgs>? _userProperties; /// <summary> /// Activity user properties. /// </summary> public InputList<Inputs.UserPropertyArgs> UserProperties { get => _userProperties ?? (_userProperties = new InputList<Inputs.UserPropertyArgs>()); set => _userProperties = value; } public DeleteActivityArgs() { } } }
33.324561
169
0.589629
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DataFactory/Latest/Inputs/DeleteActivityArgs.cs
3,799
C#
using System; using System.Collections.Generic; using Sirenix.OdinInspector; using UnityEngine; namespace JReact.Selection { /// <summary> /// selects one item /// </summary> /// <typeparam name="T">type of the selectable item</typeparam> public abstract class J_Selector<T> : ScriptableObject, jObservableValue<T>, iResettable { // --------------- FIELDS AND PROPERTIES --------------- // private event Action<T> OnSelect; [FoldoutGroup("State", false, 5), ShowInInspector] private T _current; public T Current { get => _current; private set { //deselects if required if (_current != null) ActOnDeselection(_current); //set the value _current = value; if (_current != null) ActOnSelection(_current); //send event OnSelect?.Invoke(value); } } // --------------- COMMANDS --------------- // /// <summary> /// selects an item /// </summary> /// <param name="item">the item selected</param> public void Select(T item) { if (!CanSelect(item)) return; Current = item; } /// <summary> /// deselects the selected item /// </summary> public void Deselect() { if (!CanDeselect(Current)) return; Current = default; } // --------------- QUERIES --------------- // /// <summary> /// checks if the item is selected /// </summary> public bool IsSelected(T item) { if (EqualityComparer<T>.Default.Equals(Current, default(T))) return false; else return EqualityComparer<T>.Default.Equals(Current, item); } // --------------- VIRTUAL IMPLEMENTATION --------------- // //logic to stop the selection protected virtual bool CanSelect(T item) => true; /// any logic to be applied on the selected item protected virtual void ActOnSelection(T item) {} //logic to stop the deselection protected virtual bool CanDeselect(T selected) => true; //any logic to apply on the deselected item protected virtual void ActOnDeselection(T item) {} // --------------- DISABLE AND RESET --------------- // private void OnDisable() => ResetThis(); public virtual void ResetThis() => Deselect(); // --------------- SUBSCRIBERS --------------- // public void Subscribe(Action<T> actionToAdd) => OnSelect += actionToAdd; public void UnSubscribe(Action<T> actionToRemove) => OnSelect -= actionToRemove; #if UNITY_EDITOR [BoxGroup("Debug", true, true, 100), SerializeField] private T _selectTest; [BoxGroup("Debug", true, true, 100), Button("Select", ButtonSizes.Medium)] private void DebugSelect() => Current = _selectTest; [BoxGroup("Debug", true, true, 100), Button("DeSelect", ButtonSizes.Medium)] private void DebugDeSelect() => Current = default; #endif } }
33.505263
92
0.534716
[ "MIT" ]
GiacomoMariani/JReact_Headless
Selection/J_Selector.cs
3,185
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using BuildXL.Cache.ContentStore.FileSystem; using BuildXL.Cache.ContentStore.Service; using BuildXL.Cache.ContentStore.Stores; using BuildXL.Cache.ContentStore.Interfaces.FileSystem; using BuildXL.Cache.ContentStore.Interfaces.Stores; using BuildXL.Cache.Host.Configuration; using BuildXL.Cache.ContentStore.Interfaces.Logging; namespace BuildXL.Cache.Host.Service.Internal { /// <summary> /// Creates and configures LocalContentServer instances. /// </summary> public class ContentServerFactory { private readonly IAbsFileSystem _fileSystem; private readonly ILogger _logger; private readonly DistributedCacheServiceArguments _arguments; public ContentServerFactory(DistributedCacheServiceArguments arguments) { _arguments = arguments; _logger = arguments.Logger; _fileSystem = new PassThroughFileSystem(_logger); } public LocalContentServer Create() { var cacheConfig = _arguments.Configuration; var hostInfo = _arguments.HostInfo; var dataRootPath = new AbsolutePath(_arguments.DataRootPath); var distributedSettings = cacheConfig.DistributedContentSettings; cacheConfig.LocalCasSettings = cacheConfig.LocalCasSettings.FilterUnsupportedNamedCaches(hostInfo.Capabilities, _logger); ServiceConfiguration serviceConfiguration; if (distributedSettings == null || !distributedSettings.IsDistributedContentEnabled) { serviceConfiguration = CreateServiceConfiguration(_logger, _fileSystem, cacheConfig.LocalCasSettings, dataRootPath, isDistributed: false); var localContentServerConfiguration = CreateLocalContentServerConfiguration(cacheConfig.LocalCasSettings.ServiceSettings, serviceConfiguration); return new LocalContentServer( _fileSystem, _logger, cacheConfig.LocalCasSettings.ServiceSettings.ScenarioName, path => ContentStoreFactory.CreateContentStore(_fileSystem, path, evictionAnnouncer: null, distributedEvictionSettings: default, contentStoreSettings: default, trimBulkAsync: null), localContentServerConfiguration); } else { _logger.Debug($"Creating on stamp id {hostInfo.StampId} with scenario {cacheConfig.LocalCasSettings.ServiceSettings.ScenarioName ?? string.Empty}"); RedisContentSecretNames secretNames = distributedSettings.GetRedisConnectionSecretNames(hostInfo.StampId); var factory = new DistributedContentStoreFactory( _arguments, secretNames); serviceConfiguration = CreateServiceConfiguration(_logger, _fileSystem, cacheConfig.LocalCasSettings, dataRootPath, isDistributed: true); var localContentServerConfiguration = CreateLocalContentServerConfiguration(cacheConfig.LocalCasSettings.ServiceSettings, serviceConfiguration); return new LocalContentServer( _fileSystem, _logger, cacheConfig.LocalCasSettings.ServiceSettings.ScenarioName, path => { var cacheSettingsByCacheName = cacheConfig.LocalCasSettings.CacheSettingsByCacheName; var drivesWithContentStore = new Dictionary<string, IContentStore>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, NamedCacheSettings> settings in cacheSettingsByCacheName) { _logger.Debug($"Using [{settings.Key}]'s settings: {settings.Value}"); var rootPath = cacheConfig.LocalCasSettings.GetCacheRootPathWithScenario(settings.Key); drivesWithContentStore[GetRoot(rootPath)] = factory.CreateContentStore(rootPath, replicationSettings: null); } return new MultiplexedContentStore(drivesWithContentStore, cacheConfig.LocalCasSettings.PreferredCacheDrive); }, localContentServerConfiguration); } } private static LocalServerConfiguration CreateLocalContentServerConfiguration(LocalCasServiceSettings localCasServiceSettings, ServiceConfiguration serviceConfiguration) { serviceConfiguration.GrpcPort = localCasServiceSettings.GrpcPort; var localContentServerConfiguration = new LocalServerConfiguration(serviceConfiguration); if (localCasServiceSettings.UnusedSessionTimeoutMinutes.HasValue) { localContentServerConfiguration.UnusedSessionTimeout = TimeSpan.FromMinutes(localCasServiceSettings.UnusedSessionTimeoutMinutes.Value); } if (localCasServiceSettings.UnusedSessionHeartbeatTimeoutMinutes.HasValue) { localContentServerConfiguration.UnusedSessionHeartbeatTimeout = TimeSpan.FromMinutes(localCasServiceSettings.UnusedSessionHeartbeatTimeoutMinutes.Value); } return localContentServerConfiguration; } private static ServiceConfiguration CreateServiceConfiguration(ILogger logger, IAbsFileSystem fileSystem, LocalCasSettings localCasSettings, AbsolutePath dataRootPath, bool isDistributed) { var namedCacheRoots = new Dictionary<string, AbsolutePath>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, NamedCacheSettings> settings in localCasSettings.CacheSettingsByCacheName) { var rootPath = localCasSettings.GetCacheRootPathWithScenario(settings.Key); logger.Debug($"Writing content store config file at {rootPath}."); WriteContentStoreConfigFile(settings.Value.CacheSizeQuotaString, rootPath, fileSystem); if (!isDistributed) { namedCacheRoots[settings.Key] = rootPath; } else { // Arbitrary set to match ServiceConfiguration and LocalContentServer pattern namedCacheRoots[localCasSettings.CasClientSettings.DefaultCacheName] = rootPath; } } if (!namedCacheRoots.Keys.Any(name => localCasSettings.CasClientSettings.DefaultCacheName.Equals(name, StringComparison.OrdinalIgnoreCase))) { throw new ArgumentException( $"Must have the default cache name {localCasSettings.CasClientSettings.DefaultCacheName} as one of the named cache roots."); } return new ServiceConfiguration( namedCacheRoots, dataRootPath, localCasSettings.ServiceSettings.MaxPipeListeners, localCasSettings.ServiceSettings.GracefulShutdownSeconds, (int)localCasSettings.ServiceSettings.GrpcPort, grpcPortFileName: localCasSettings.ServiceSettings.GrpcPortFileName); } private static void WriteContentStoreConfigFile(string cacheSizeQuotaString, AbsolutePath rootPath, IAbsFileSystem fileSystem) { fileSystem.CreateDirectory(rootPath); var maxSizeQuota = new MaxSizeQuota(cacheSizeQuotaString); var casConfig = new ContentStoreConfiguration(maxSizeQuota); casConfig.Write(fileSystem, rootPath).GetAwaiter().GetResult(); } private static string GetRoot(AbsolutePath rootPath) { return Path.GetPathRoot(rootPath.Path); } } }
51.00625
202
0.665115
[ "MIT" ]
MatisseHack/BuildXL
Public/Src/Cache/DistributedCache.Host/Service/Internal/ContentServerFactory.cs
8,163
C#
using JSC_LMS.Application.Response; using MediatR; using System; using System.Collections.Generic; using System.Text; namespace JSC_LMS.Application.Features.Students.Queries.GetStudentByPagination { public class GetStudentByPaginationQuery : IRequest<Response<GetStudentListByPaginationResponse>> { public int page { get; set; } public int size { get; set; } } }
26.2
101
0.753181
[ "Apache-2.0" ]
ashishneosoftmail/JSC_LMS
src/Core/JSC_LMS.Application/Features/Students/Queries/GetStudentByPagination/GetStudentByPaginationQuery.cs
395
C#
using AutoFixture; using FluentAssertions; using TramsDataApi.ApplyToBecome; using Xunit; namespace TramsDataApi.Test.ApplyToBecome { public class SyncAcademyConversionProjectFactoryTests { private readonly Fixture _fixture; public SyncAcademyConversionProjectFactoryTests() { _fixture = new Fixture(); } [Fact] public void ReturnsSyncAcademyConversionProject_WhenGivenSyncIfdPipeline() { var ifdPipeline = _fixture.Build<SyncIfdPipeline>() .With(x => x.GeneralDetailsUrn, "123456") .With(x => x.ProjectTemplateInformationFyRevenueBalanceCarriedForward, _fixture.Create<decimal>().ToString) .With(x => x.ProjectTemplateInformationFy1RevenueBalanceCarriedForward, _fixture.Create<decimal>().ToString) .With(x => x.ProjectTemplateInformationAy1CapacityForecast, _fixture.Create<int>().ToString) .With(x => x.ProjectTemplateInformationAy1TotalPupilNumberForecast, _fixture.Create<int>().ToString) .With(x => x.ProjectTemplateInformationAy2CapacityForecast, _fixture.Create<int>().ToString) .With(x => x.ProjectTemplateInformationAy2TotalPupilNumberForecast, _fixture.Create<int>().ToString) .With(x => x.ProjectTemplateInformationAy3CapacityForecast, _fixture.Create<int>().ToString) .With(x => x.ProjectTemplateInformationAy3TotalPupilNumberForecast, _fixture.Create<int>().ToString) .Create(); var expectedAcademyConversionProject = new SyncAcademyConversionProject { IfdPipelineId = (int)ifdPipeline.Sk, Urn = int.Parse(ifdPipeline.GeneralDetailsUrn), SchoolName = ifdPipeline.GeneralDetailsProjectName, LocalAuthority = ifdPipeline.GeneralDetailsLocalAuthority, ProjectStatus = "Active", ApplicationReceivedDate = ifdPipeline.ApprovalProcessApplicationDate, AssignedDate = null, HeadTeacherBoardDate = ifdPipeline.DeliveryProcessDateForDiscussionByRscHtb, Author = ifdPipeline.GeneralDetailsProjectLead, ClearedBy = ifdPipeline.GeneralDetailsTeamLeader, TrustReferenceNumber = ifdPipeline.TrustSponsorManagementTrust, ProposedAcademyOpeningDate = ifdPipeline.GeneralDetailsExpectedOpeningDate, PublishedAdmissionNumber = ifdPipeline.DeliveryProcessPan, PartOfPfiScheme = ifdPipeline.DeliveryProcessPfi, ViabilityIssues = ifdPipeline.ProjectTemplateInformationViabilityIssue, FinancialDeficit = ifdPipeline.ProjectTemplateInformationDeficit, RationaleForProject = ifdPipeline.ProjectTemplateInformationRationaleForProject, RationaleForTrust = ifdPipeline.ProjectTemplateInformationRationaleForSponsor, RisksAndIssues = ifdPipeline.ProjectTemplateInformationRisksAndIssues, RevenueCarryForwardAtEndMarchCurrentYear = decimal.Parse(ifdPipeline.ProjectTemplateInformationFyRevenueBalanceCarriedForward), ProjectedRevenueBalanceAtEndMarchNextYear = decimal.Parse(ifdPipeline.ProjectTemplateInformationFy1RevenueBalanceCarriedForward), YearOneProjectedCapacity = int.Parse(ifdPipeline.ProjectTemplateInformationAy1CapacityForecast), YearOneProjectedPupilNumbers = int.Parse(ifdPipeline.ProjectTemplateInformationAy1TotalPupilNumberForecast), YearTwoProjectedCapacity = int.Parse(ifdPipeline.ProjectTemplateInformationAy2CapacityForecast), YearTwoProjectedPupilNumbers = int.Parse(ifdPipeline.ProjectTemplateInformationAy2TotalPupilNumberForecast), YearThreeProjectedCapacity = int.Parse(ifdPipeline.ProjectTemplateInformationAy3CapacityForecast), YearThreeProjectedPupilNumbers = int.Parse(ifdPipeline.ProjectTemplateInformationAy3TotalPupilNumberForecast), ConversionSupportGrantAmount = 25000, AcademyTypeAndRoute = "Converter" }; var academyConversionProject = SyncAcademyConversionProjectFactory.Create(ifdPipeline); academyConversionProject.Should().BeEquivalentTo(expectedAcademyConversionProject); } } }
60.767123
145
0.710325
[ "MIT" ]
DFE-Digital/trams-data-api
TramsDataApi.Test/ApplyToBecome/SyncAcademyConversionProjectFactoryTests.cs
4,436
C#
namespace AgileObjects.AgileMapper.Api.Configuration { /// <summary> /// Provides options for configuring a mapping based on the preceding condition. /// </summary> /// <typeparam name="TSource">The source type to which the configuration should apply.</typeparam> /// <typeparam name="TTarget">The target type to which the configuration should apply.</typeparam> public interface IConditionalRootMappingConfigurator<TSource, TTarget> : IRootMappingConfigurator<TSource, TTarget> { /// <summary> /// Map the source type being configured to the derived target type specified by /// <typeparamref name="TDerivedTarget"/> if the preceding condition evaluates to true. /// </summary> /// <typeparam name="TDerivedTarget">The derived target type to create.</typeparam> /// <returns> /// An IMappingConfigContinuation to enable further configuration of mappings from and to the source and /// target type being configured. /// </returns> IMappingConfigContinuation<TSource, TTarget> MapTo<TDerivedTarget>() where TDerivedTarget : TTarget; /// <summary> /// Map the target type being configured to null if the preceding condition evaluates to true. /// </summary> /// <returns> /// An IMappingConfigContinuation to enable further configuration of mappings from and to the source and /// target type being configured. /// </returns> IMappingConfigContinuation<TSource, TTarget> MapToNull(); } }
50.5
114
0.659653
[ "MIT" ]
WeiiWang/AgileMapper
AgileMapper/Api/Configuration/IConditionalRootMappingConfigurator.cs
1,616
C#
using System; using Newtonsoft.Json; using Siccity.GLTFUtility.Converters; using UnityEngine; namespace Siccity.GLTFUtility { // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessor /// <summary> Reads data from BufferViews </summary> public class GLTFAccessor { #region Serialized fields public int? bufferView; public int byteOffset = 0; [JsonProperty(Required = Required.Always), JsonConverter(typeof(EnumConverter))] public AccessorType type; [JsonProperty(Required = Required.Always)] public GLType componentType; [JsonProperty(Required = Required.Always)] public int count; public float[] min; public float[] max; public Sparse sparse; #endregion public class ImportResult { public byte[] bytes; public int count; public GLType componentType; public AccessorType type; public Matrix4x4[] ReadMatrix4x4() { if (!ValidateAccessorType(type, AccessorType.MAT4)) return new Matrix4x4[count]; Matrix4x4[] m = new Matrix4x4[count]; int componentSize = GetComponentSize(); int componentTypeSize = GetComponentTypeSize(); Func<byte[], int, float> converter = GetFloatConverter(); for (int i = 0; i < count; i++) { int startIndex = i * componentSize; m[i].m00 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m01 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m02 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m03 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m10 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m11 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m12 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m13 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m20 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m21 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m22 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m23 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m30 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m31 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m32 = converter(bytes, startIndex); startIndex += componentTypeSize; m[i].m33 = converter(bytes, startIndex); } return m; } public Vector4[] ReadVec4() { if (!ValidateAccessorType(type, AccessorType.VEC4)) return new Vector4[count]; Vector4[] verts = new Vector4[count]; int componentSize = GetComponentSize(); int componentTypeSize = GetComponentTypeSize(); Func<byte[], int, float> converter = GetFloatConverter(); for (int i = 0; i < count; i++) { int startIndex = i * componentSize; verts[i].x = converter(bytes, startIndex); startIndex += componentTypeSize; verts[i].y = converter(bytes, startIndex); startIndex += componentTypeSize; verts[i].z = converter(bytes, startIndex); startIndex += componentTypeSize; verts[i].w = converter(bytes, startIndex); } return verts; } public Color[] ReadColor() { if (!ValidateAccessorType(type, AccessorType.VEC4)) return new Color[count]; Color[] colors = new Color[count]; int componentSize = GetComponentSize(); int componentTypeSize = GetComponentTypeSize(); if (componentType == GLType.BYTE || componentType == GLType.UNSIGNED_BYTE) { Color32 color = Color.black; for (int i = 0; i < count; i++) { int startIndex = i * componentSize; color.r = bytes[startIndex]; startIndex += componentTypeSize; color.g = bytes[startIndex]; startIndex += componentTypeSize; color.b = bytes[startIndex]; if (type == AccessorType.VEC4) { startIndex += componentTypeSize; color.a = bytes[startIndex]; } else { color.a = (byte) 255; } colors[i] = color; } } else if (componentType == GLType.FLOAT) { Func<byte[], int, float> converter = GetFloatConverter(); for (int i = 0; i < count; i++) { int startIndex = i * componentSize; colors[i].r = converter(bytes, startIndex); startIndex += componentTypeSize; colors[i].g = converter(bytes, startIndex); startIndex += componentTypeSize; colors[i].b = converter(bytes, startIndex); if (type == AccessorType.VEC4) { startIndex += componentTypeSize; colors[i].a = converter(bytes, startIndex); } else { colors[i].a = 1; } } } else { Debug.LogWarning("Unexpected componentType! " + componentType); } return colors; } public Vector3[] ReadVec3() { if (!ValidateAccessorType(type, AccessorType.VEC3)) return new Vector3[count]; Vector3[] verts = new Vector3[count]; int componentSize = GetComponentSize(); int componentTypeSize = GetComponentTypeSize(); Func<byte[], int, float> converter = GetFloatConverter(); for (int i = 0; i < count; i++) { int startIndex = i * componentSize; verts[i].x = converter(bytes, startIndex); startIndex += componentTypeSize; verts[i].y = converter(bytes, startIndex); startIndex += componentTypeSize; verts[i].z = converter(bytes, startIndex); } return verts; } public Vector2[] ReadVec2() { if (!ValidateAccessorType(type, AccessorType.VEC2)) return new Vector2[count]; if (componentType != GLType.FLOAT) { Debug.LogError("Non-float componentType not supported. Got " + (int) componentType); return new Vector2[count]; } Vector2[] verts = new Vector2[count]; int componentSize = GetComponentSize(); int componentTypeSize = GetComponentTypeSize(); Func<byte[], int, float> converter = GetFloatConverter(); for (int i = 0; i < count; i++) { int startIndex = i * componentSize; verts[i].x = converter(bytes, startIndex); startIndex += componentTypeSize; verts[i].y = converter(bytes, startIndex); startIndex += componentTypeSize; } return verts; } public float[] ReadFloat() { if (!ValidateAccessorType(type, AccessorType.SCALAR)) return new float[count]; float[] floats = new float[count]; int componentSize = GetComponentSize(); Func<byte[], int, float> converter = GetFloatConverter(); for (int i = 0; i < count; i++) { int startIndex = i * componentSize; floats[i] = converter(bytes, startIndex); } return floats; } public int[] ReadInt() { if (!ValidateAccessorType(type, AccessorType.SCALAR)) return new int[count]; int[] ints = new int[count]; int componentSize = GetComponentSize(); Func<byte[], int, int> converter = GetIntConverter(); for (int i = 0; i < count; i++) { int startIndex = i * componentSize; ints[i] = converter(bytes, startIndex); } return ints; } public Func<byte[], int, float> GetFloatConverter() { switch (componentType) { case GLType.BYTE: return (x, y) => (float) (sbyte) x[y]; case GLType.UNSIGNED_BYTE: return (x, y) => (float) x[y]; case GLType.FLOAT: return System.BitConverter.ToSingle; case GLType.SHORT: return (x, y) => (float) System.BitConverter.ToInt16(x, y); case GLType.UNSIGNED_SHORT: return (x, y) => (float) System.BitConverter.ToUInt16(x, y); case GLType.UNSIGNED_INT: return (x, y) => (float) System.BitConverter.ToUInt16(x, y); default: Debug.LogWarning("No componentType defined"); return System.BitConverter.ToSingle; } } public Func<byte[], int, int> GetIntConverter() { switch (componentType) { case GLType.BYTE: return (x, y) => (int) (sbyte) x[y]; case GLType.UNSIGNED_BYTE: return (x, y) => (int) x[y]; case GLType.FLOAT: return (x, y) => (int) System.BitConverter.ToSingle(x, y); case GLType.SHORT: return (x, y) => (int) System.BitConverter.ToInt16(x, y); case GLType.UNSIGNED_SHORT: return (x, y) => (int) System.BitConverter.ToUInt16(x, y); case GLType.UNSIGNED_INT: return (x, y) => (int) System.BitConverter.ToUInt16(x, y); default: Debug.LogWarning("No componentType defined"); return (x, y) => (int) System.BitConverter.ToUInt16(x, y); } } /// <summary> Get the size of the attribute type, in bytes </summary> public int GetComponentSize() { return GetComponentNumber() * GetComponentTypeSize(); } public int GetComponentTypeSize() { switch (componentType) { case GLType.BYTE: return 1; case GLType.UNSIGNED_BYTE: return 1; case GLType.SHORT: return 2; case GLType.UNSIGNED_SHORT: return 2; case GLType.FLOAT: return 4; case GLType.UNSIGNED_INT: return 4; default: Debug.LogError("componentType " + (int) componentType + " not supported!"); return 0; } } public int GetComponentNumber() { switch (type) { case AccessorType.SCALAR: return 1; case AccessorType.VEC2: return 2; case AccessorType.VEC3: return 3; case AccessorType.VEC4: return 4; case AccessorType.MAT2: return 4; case AccessorType.MAT3: return 9; case AccessorType.MAT4: return 16; default: Debug.LogError("type " + type + " not supported!"); return 0; } } private static bool ValidateAccessorType(AccessorType type, AccessorType expected) { if (type != expected) { Debug.LogError("Type mismatch! Expected " + expected + " got " + type); return false; } return true; } } public ImportResult Import(GLTFBufferView.ImportResult[] bufferViews) { ImportResult result = new ImportResult(); GLTFBufferView.ImportResult bufferView = bufferViews[this.bufferView.Value]; result.bytes = bufferView.bytes.SubArray(byteOffset, bufferView.bytes.Length - byteOffset); result.componentType = componentType; result.type = type; result.count = count; return result; } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse public class Sparse { [JsonProperty(Required = Required.Always)] public int count; [JsonProperty(Required = Required.Always)] public Indices indices; [JsonProperty(Required = Required.Always)] public Values values; // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#values public class Values { [JsonProperty(Required = Required.Always)] public int bufferView; public int byteOffset = 0; } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#indices public class Indices { [JsonProperty(Required = Required.Always)] public int bufferView; [JsonProperty(Required = Required.Always)] public int componentType; public int byteOffset = 0; } } } }
33.577039
108
0.6553
[ "MIT" ]
takhlaq/GLTFUtility
Scripts/Spec/GLTFAccessor.cs
11,116
C#
using System; namespace MultiplyBigNumber { class Program { static void Main(string[] args) { decimal first = decimal.Parse(Console.ReadLine()); decimal second = decimal.Parse(Console.ReadLine()); Console.WriteLine(first * second); } } }
20.8
63
0.573718
[ "MIT" ]
kristiyanivanovx/SoftUni-Programming-Basics-March-2020
02 - CSharp-Fundamentals/08 - Text Processing - Exercise/MultiplyBigNumber/Program.cs
314
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace AutoBalance1Wpf { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : Application { } }
18.555556
43
0.667665
[ "MIT" ]
kcg-edu-future-lab/Algorithm-Motion
Lab/AlgorithmMotion201906/AutoBalance1Wpf/App.xaml.cs
354
C#
namespace GitHubAPI.IntegrationTests { using NUnit.Framework; using GitHubAPI.Models; using GitHubAPI.Api.Issues; using GitHubAPI.IntegrationTests.Ext; using FluentAssertions; using RestSharp; using System.Collections.Generic; public class IssueTests { public abstract class GetIssuesTestsBase : TestsSpecBase { protected GithubRestApiClient Github; protected string User; protected IRestResponse<List<Issue>> Response = null; public override void Context() { base.Context(); Github = new GithubRestApiClient(GitHubUrl); } } public class when_retrieving_issues_unauthenticated : GetIssuesTestsBase { public override void Because() { User = Username; Response = Github.GetIssues<List<Issue>>(); } [Fact] public void then_response_data_with_model_should_have_one() { //TODO: Check the headers for a Status = 404 not found - github returns this for resources which require authenticating Response.Data.Should().HaveCount(1); } [Fact] public void then_response_dynamic_should_have_message_not_found() { //TODO: why can't i do response.Dynamic().message? Assert.That(Response.Dynamic().message, Is.StringMatching("Not Found")); } [Fact] public void then_response_data_with_model_should_not_contain_data() { Response.Data[0].Number.Should().Be(0); } } public class when_retrieving_issues_authenticated : GetIssuesTestsBase { public override void Because() { User = Username; Github = Github.WithAuthentication(Authenticator()); Response = Github.GetIssues<List<Issue>>(); } [Fact] public void then_response_data_with_model_should_contain_some_issues() { Response.Data.Should().NotBeEmpty(); } } public abstract class CreateIssueTestsBase : GitHubAPI.IntegrationTests.Ext.TestsSpecBase { protected GithubRestApiClient Github; protected string User; protected string RepoOwnerName; protected string RepoName; protected string[] Labels; protected string Title; protected string Body; protected IRestResponse<Issue> Response; public override void Context() { base.Context(); Github = new GithubRestApiClient(GitHubUrl); } } public class when_creating_issues_unauthenticated : CreateIssueTestsBase { public override void Because() { User = Username; RepoName = "Whatever"; RepoOwnerName = "Whatever"; Response = Github.CreateIssue<Issue>(RepoOwnerName, RepoName, Title, Body, User, Labels); } [Fact] public void then_response_data_with_model_should_be_empty() { Response.Data.Assignee.Should().BeNull(); Response.Data.Number.Should().Be(0); Response.Data.Title.Should().BeNull(); Response.Data.User.Should().BeNull(); } [Fact] public void then_response_dynamic_should_have_message_not_found() { //Note this will fail unless the JsonObject in SimpleJson has define dynamic set NUnit.Framework.Assert.That(Response.Dynamic().message, NUnit.Framework.Is.StringMatching("Not Found")); } } public class when_creating_issues_authenticated_to_nonexistant_repo : CreateIssueTestsBase { public override void Because() { User = Username; RepoName = "Whatever"; RepoOwnerName = "Whatever"; Github = Github.WithAuthentication(Authenticator()); Response = Github.CreateIssue<Issue>(RepoOwnerName, RepoName, Title, Body, User, Labels); } [Fact] public void then_response_data_with_model_should_be_empty() { Response.Data.Assignee.Should().BeNull(); Response.Data.Number.Should().Be(0); Response.Data.Title.Should().BeNull(); Response.Data.User.Should().BeNull(); } [Fact] public void then_response_dynamic_should_have_message_not_found() { //TODO: why can't i do response.Dynamic().message? NUnit.Framework.Assert.That(Response.Dynamic()["message"], NUnit.Framework.Is.StringMatching("Not Found")); } } [TestFixture] public class when_creating_issues_authenticated_to_unauthorized_repo : CreateIssueTestsBase { public override void Because() { User = Username; RepoName = "NeedARepoYouCantCreateIssuesIn"; RepoOwnerName = "Whatever"; Github = Github.WithAuthentication(Authenticator()); Response = Github.CreateIssue<Issue>(RepoOwnerName, RepoName, Title, Body, User, Labels); } [Fact] [Ignore] //TODO: setup a repo that matches requirements public void then_response_data_with_model_should_be_empty() { Response.Data.Assignee.Should().BeNull(); Response.Data.Number.Should().Be(0); Response.Data.Title.Should().BeNull(); Response.Data.User.Should().BeNull(); } [Fact] [Ignore] //TODO: setup a repo that matches requirements public void then_response_dynamic_should_have_message_not_found() { //TODO: why can't i do response.Dynamic().message? NUnit.Framework.Assert.That(Response.Dynamic()["message"], NUnit.Framework.Is.StringMatching("Not Found")); } } [TestFixture] public class when_creating_issues_authenticated_to_authorized_repo : CreateIssueTestsBase { public override void Because() { User = Username; RepoName = "NeedARepoYouCanCreateIssuesIn"; RepoOwnerName = "Whatever"; Github = Github.WithAuthentication(Authenticator()); Response = Github.CreateIssue<Issue>(RepoOwnerName, RepoName, Title, Body, User, Labels); } [Fact] [Ignore] //TODO: setup a repo that matches requirements public void then_response_data_with_model_should_have_issue_data() { //TODO: what should we check for } } public abstract class EditIssueTestsBase : GitHubAPI.IntegrationTests.Ext.TestsSpecBase { protected GithubRestApiClient Github; protected string User; protected string RepoOwnerName; protected string RepoName; protected string[] Labels; protected string Title; protected string Body; protected IRestResponse<Issue> Response; protected Issue IssueToUpdate; public override void Context() { base.Context(); Github = new GithubRestApiClient(GitHubUrl); } } public class when_editing_issues_authenticated_to_existent_issue : EditIssueTestsBase { public override void Because() { User = Username; RepoName = "Whatever"; RepoOwnerName = "Whatever"; Github = Github.WithAuthentication(Authenticator()); IssueToUpdate = Github.CreateIssue<Issue>(RepoOwnerName, RepoName, "Isssue To Update", "Text to Update", User).Data; Response = Github.EditIssue<Issue>(RepoOwnerName, RepoName, IssueToUpdate.Number); } [Fact] [Ignore] //TODO: setup repo with right permissions public void then_response_data_with_model_should_have_updates() { //TODO: add changes to EditIssue call and then check here } } } }
34.654762
135
0.564525
[ "Apache-2.0" ]
HaKDMoDz/csharp-github-api
csharp-github-api.IntegrationTests/IssueTests.cs
8,735
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model. */ using Amazon.Runtime; namespace Amazon.IdentityManagement.Model { /// <summary> /// Paginator for the ListAccountAliases operation ///</summary> public interface IListAccountAliasesPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListAccountAliasesResponse> Responses { get; } /// <summary> /// Enumerable containing all of the AccountAliases /// </summary> IPaginatedEnumerable<string> AccountAliases { get; } } } #endif
33.325
102
0.672168
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IdentityManagement/Generated/Model/_bcl45+netstandard/IListAccountAliasesPaginator.cs
1,333
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [ExecuteInEditMode] public class DropdownTextAlignLeft : MonoBehaviour { #pragma warning disable 0649 //Serialized Fields [SerializeField] private Text textComponent; [SerializeField] private RectTransform rectTransform; [SerializeField] private bool onlyUpdateOnChangeText = true; [SerializeField] private float initialX, initialXSize; #pragma warning restore 0649 private string lastUpdatedText; void Start() { textComponent = GetComponent<Text>(); lastUpdatedText = textComponent.text; rectTransform = (RectTransform)transform; initialX = rectTransform.position.x; initialXSize = rectTransform.sizeDelta.x; } void Update() { if ((!onlyUpdateOnChangeText || lastUpdatedText != textComponent.text)) updateSize(); } void updateSize() { //Debug.Log((rectTransform.sizeDelta.x - initialXSize)); rectTransform.position = new Vector3(initialX + (rectTransform.sizeDelta.x - initialXSize), rectTransform.position.y, rectTransform.position.z); lastUpdatedText = textComponent.text; } }
27.177778
152
0.714636
[ "MIT" ]
Trif4/NitoriWare
Assets/Scripts/UI/DropdownTextAlignLeft.cs
1,225
C#
// <auto-generated /> using System; using IdentityServer4.EntityFramework.DbContexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace SqlServer.Migrations.ConfigurationDb { [DbContext(typeof(ConfigurationDbContext))] partial class ConfigurationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.11-servicing-32099") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("Created"); b.Property<string>("Description") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasMaxLength(200); b.Property<bool>("Enabled"); b.Property<DateTime?>("LastAccessed"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200); b.Property<bool>("NonEditable"); b.Property<DateTime?>("Updated"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("ApiResources"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ApiResourceId"); b.Property<string>("Type") .IsRequired() .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("ApiResourceId"); b.ToTable("ApiClaims"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ApiResourceId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("ApiResourceId"); b.ToTable("ApiProperties"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ApiResourceId"); b.Property<string>("Description") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasMaxLength(200); b.Property<bool>("Emphasize"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200); b.Property<bool>("Required"); b.Property<bool>("ShowInDiscoveryDocument"); b.HasKey("Id"); b.HasIndex("ApiResourceId"); b.HasIndex("Name") .IsUnique(); b.ToTable("ApiScopes"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ApiScopeId"); b.Property<string>("Type") .IsRequired() .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("ApiScopeId"); b.ToTable("ApiScopeClaims"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ApiResourceId"); b.Property<DateTime>("Created"); b.Property<string>("Description") .HasMaxLength(1000); b.Property<DateTime?>("Expiration"); b.Property<string>("Type") .IsRequired() .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasMaxLength(4000); b.HasKey("Id"); b.HasIndex("ApiResourceId"); b.ToTable("ApiSecrets"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.Client", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AbsoluteRefreshTokenLifetime"); b.Property<int>("AccessTokenLifetime"); b.Property<int>("AccessTokenType"); b.Property<bool>("AllowAccessTokensViaBrowser"); b.Property<bool>("AllowOfflineAccess"); b.Property<bool>("AllowPlainTextPkce"); b.Property<bool>("AllowRememberConsent"); b.Property<bool>("AlwaysIncludeUserClaimsInIdToken"); b.Property<bool>("AlwaysSendClientClaims"); b.Property<int>("AuthorizationCodeLifetime"); b.Property<bool>("BackChannelLogoutSessionRequired"); b.Property<string>("BackChannelLogoutUri") .HasMaxLength(2000); b.Property<string>("ClientClaimsPrefix") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200); b.Property<string>("ClientName") .HasMaxLength(200); b.Property<string>("ClientUri") .HasMaxLength(2000); b.Property<int?>("ConsentLifetime"); b.Property<DateTime>("Created"); b.Property<string>("Description") .HasMaxLength(1000); b.Property<int>("DeviceCodeLifetime"); b.Property<bool>("EnableLocalLogin"); b.Property<bool>("Enabled"); b.Property<bool>("FrontChannelLogoutSessionRequired"); b.Property<string>("FrontChannelLogoutUri") .HasMaxLength(2000); b.Property<int>("IdentityTokenLifetime"); b.Property<bool>("IncludeJwtId"); b.Property<DateTime?>("LastAccessed"); b.Property<string>("LogoUri") .HasMaxLength(2000); b.Property<bool>("NonEditable"); b.Property<string>("PairWiseSubjectSalt") .HasMaxLength(200); b.Property<string>("ProtocolType") .IsRequired() .HasMaxLength(200); b.Property<int>("RefreshTokenExpiration"); b.Property<int>("RefreshTokenUsage"); b.Property<bool>("RequireClientSecret"); b.Property<bool>("RequireConsent"); b.Property<bool>("RequirePkce"); b.Property<int>("SlidingRefreshTokenLifetime"); b.Property<bool>("UpdateAccessTokenClaimsOnRefresh"); b.Property<DateTime?>("Updated"); b.Property<string>("UserCodeType") .HasMaxLength(100); b.Property<int?>("UserSsoLifetime"); b.HasKey("Id"); b.HasIndex("ClientId") .IsUnique(); b.ToTable("Clients"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("Type") .IsRequired() .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasMaxLength(250); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientClaims"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("Origin") .IsRequired() .HasMaxLength(150); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientCorsOrigins"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("GrantType") .IsRequired() .HasMaxLength(250); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientGrantTypes"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("Provider") .IsRequired() .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientIdPRestrictions"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("PostLogoutRedirectUri") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientPostLogoutRedirectUris"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientProperties"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("RedirectUri") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientRedirectUris"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<string>("Scope") .IsRequired() .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientScopes"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<DateTime>("Created"); b.Property<string>("Description") .HasMaxLength(2000); b.Property<DateTime?>("Expiration"); b.Property<string>("Type") .IsRequired() .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasMaxLength(4000); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("ClientSecrets"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("IdentityResourceId"); b.Property<string>("Type") .IsRequired() .HasMaxLength(200); b.HasKey("Id"); b.HasIndex("IdentityResourceId"); b.ToTable("IdentityClaims"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("Created"); b.Property<string>("Description") .HasMaxLength(1000); b.Property<string>("DisplayName") .HasMaxLength(200); b.Property<bool>("Emphasize"); b.Property<bool>("Enabled"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200); b.Property<bool>("NonEditable"); b.Property<bool>("Required"); b.Property<bool>("ShowInDiscoveryDocument"); b.Property<DateTime?>("Updated"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("IdentityResources"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("IdentityResourceId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(250); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("IdentityResourceId"); b.ToTable("IdentityProperties"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceClaim", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") .WithMany("UserClaims") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiResourceProperty", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") .WithMany("Properties") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScope", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") .WithMany("Scopes") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiScopeClaim", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.ApiScope", "ApiScope") .WithMany("UserClaims") .HasForeignKey("ApiScopeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ApiSecret", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.ApiResource", "ApiResource") .WithMany("Secrets") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientClaim", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("Claims") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientCorsOrigin", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("AllowedCorsOrigins") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientGrantType", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("AllowedGrantTypes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientIdPRestriction", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("IdentityProviderRestrictions") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("PostLogoutRedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientProperty", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("Properties") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientRedirectUri", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("RedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientScope", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("AllowedScopes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.ClientSecret", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.Client", "Client") .WithMany("ClientSecrets") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityClaim", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") .WithMany("UserClaims") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.IdentityResourceProperty", b => { b.HasOne("IdentityServer4.EntityFramework.Entities.IdentityResource", "IdentityResource") .WithMany("Properties") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
36.962373
125
0.487961
[ "Apache-2.0" ]
284171004/IdentityServer4
src/EntityFramework.Storage/migrations/SqlServer/Migrations/ConfigurationDb/ConfigurationDbContextModelSnapshot.cs
25,543
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NBitcoin; using NBitcoin.DataEncoders; using Stratis.Bitcoin.Base; using Stratis.Bitcoin.Base.Deployments; using Stratis.Bitcoin.Base.Deployments.Models; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Controllers; using Stratis.Bitcoin.Controllers.Models; using Stratis.Bitcoin.Features.Consensus; using Stratis.Bitcoin.Features.RPC.Exceptions; using Stratis.Bitcoin.Features.RPC.ModelBinders; using Stratis.Bitcoin.Features.RPC.Models; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.Primitives; using Stratis.Bitcoin.Utilities; using Stratis.Bitcoin.Utilities.Extensions; namespace Stratis.Bitcoin.Features.RPC.Controllers { /// <summary> /// A <see cref="FeatureController"/> that implements several RPC methods for the full node. /// </summary> [ApiVersion("1")] public class FullNodeController : FeatureController { /// <summary>Instance logger.</summary> private readonly ILogger logger; /// <summary>An interface implementation used to retrieve a transaction.</summary> private readonly IPooledTransaction pooledTransaction; /// <summary>An interface implementation used to retrieve unspent transactions from a pooled source.</summary> private readonly IPooledGetUnspentTransaction pooledGetUnspentTransaction; /// <summary>An interface implementation used to retrieve unspent transactions.</summary> private readonly IGetUnspentTransaction getUnspentTransaction; /// <summary>An interface implementation used to retrieve the network difficulty target.</summary> private readonly INetworkDifficulty networkDifficulty; /// <summary>An interface implementation for the blockstore.</summary> private readonly IBlockStore blockStore; /// <summary>A interface implementation for the initial block download state.</summary> private readonly IInitialBlockDownloadState ibdState; private readonly IStakeChain stakeChain; public FullNodeController( ILoggerFactory loggerFactory, IPooledTransaction pooledTransaction = null, IPooledGetUnspentTransaction pooledGetUnspentTransaction = null, IGetUnspentTransaction getUnspentTransaction = null, INetworkDifficulty networkDifficulty = null, IFullNode fullNode = null, NodeSettings nodeSettings = null, Network network = null, ChainIndexer chainIndexer = null, IChainState chainState = null, Connection.IConnectionManager connectionManager = null, IConsensusManager consensusManager = null, IBlockStore blockStore = null, IInitialBlockDownloadState ibdState = null, IStakeChain stakeChain = null) : base( fullNode: fullNode, network: network, nodeSettings: nodeSettings, chainIndexer: chainIndexer, chainState: chainState, connectionManager: connectionManager, consensusManager: consensusManager) { this.logger = loggerFactory.CreateLogger(this.GetType().FullName); this.pooledTransaction = pooledTransaction; this.pooledGetUnspentTransaction = pooledGetUnspentTransaction; this.getUnspentTransaction = getUnspentTransaction; this.networkDifficulty = networkDifficulty; this.blockStore = blockStore; this.ibdState = ibdState; this.stakeChain = stakeChain; } /// <summary> /// Stops the full node. /// </summary> [ActionName("stop")] [ActionDescription("Stops the full node.")] public Task Stop() { if (this.FullNode != null) { this.FullNode.NodeLifetime.StopApplication(); this.FullNode = null; } return Task.CompletedTask; } /// <summary> /// Retrieves a transaction given a transaction hash in either simple or verbose form. /// </summary> /// <param name="txid">The transaction hash.</param> /// <param name="verbose">True if verbose model wanted.</param> /// <param name="blockHash">The hash of the block in which to look for the transaction.</param> /// <returns>A <see cref="TransactionBriefModel"/> or <see cref="TransactionVerboseModel"/> as specified by verbose. <c>null</c> if no transaction matching the hash.</returns> /// <exception cref="ArgumentException">Thrown if txid is invalid uint256.</exception>" /// <remarks>When called with a blockhash argument, getrawtransaction will return the transaction if the specified block is available and the transaction is found in that block. /// When called without a blockhash argument, getrawtransaction will return the transaction if it is in the mempool, or if -txindex is enabled and the transaction is in a block in the blockchain.</remarks> [ActionName("getrawtransaction")] [ActionDescription("Gets a raw, possibly pooled, transaction from the full node.")] public async Task<TransactionModel> GetRawTransactionAsync(string txid, [IntToBool]bool verbose = false, string blockHash = null) { Guard.NotEmpty(txid, nameof(txid)); if (!uint256.TryParse(txid, out uint256 trxid)) { throw new ArgumentException(nameof(trxid)); } uint256 hash = null; if (!string.IsNullOrEmpty(blockHash) && !uint256.TryParse(blockHash, out hash)) { throw new ArgumentException(nameof(blockHash)); } // Special exception for the genesis block coinbase transaction. if (trxid == this.Network.GetGenesis().GetMerkleRoot().Hash) { throw new RPCServerException(RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved."); } Transaction trx = null; ChainedHeaderBlock chainedHeaderBlock = null; if (hash == null) { // Look for the transaction in the mempool, and if not found, look in the indexed transactions. trx = (this.pooledTransaction == null ? null : await this.pooledTransaction.GetTransaction(trxid).ConfigureAwait(false)) ?? this.blockStore.GetTransactionById(trxid); if (trx == null) { throw new RPCServerException(RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY, "No such mempool transaction. Use -txindex to enable blockchain transaction queries."); } } else { // Retrieve the block specified by the block hash. chainedHeaderBlock = this.ConsensusManager.GetBlockData(hash); if (chainedHeaderBlock == null) { throw new RPCServerException(RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found."); } trx = chainedHeaderBlock.Block.Transactions.SingleOrDefault(t => t.GetHash() == trxid); if (trx == null) { throw new RPCServerException(RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY, "No such transaction found in the provided block."); } } if (verbose) { ChainedHeader block = chainedHeaderBlock != null ? chainedHeaderBlock.ChainedHeader : this.GetTransactionBlock(trxid); return new TransactionVerboseModel(trx, this.Network, block, this.ChainState?.ConsensusTip); } else return new TransactionBriefModel(trx); } /// <summary> /// Decodes a transaction from its raw hexadecimal format. /// </summary> /// <param name="hex">The raw transaction hex.</param> /// <returns>A <see cref="TransactionVerboseModel"/> or <c>null</c> if the transaction could not be decoded.</returns> [ActionName("decoderawtransaction")] [ActionDescription("Decodes a serialized transaction hex string into a JSON object describing the transaction.")] public TransactionModel DecodeRawTransaction(string hex) { try { return new TransactionVerboseModel(this.FullNode.Network.CreateTransaction(hex), this.Network); } catch (FormatException ex) { throw new ArgumentException(nameof(hex), ex.Message); } catch (Exception) { return null; } } /// <summary> /// Implements gettextout RPC call. /// </summary> /// <param name="txid">The transaction id.</param> /// <param name="vout">The vout number.</param> /// <param name="includeMemPool">Whether to include the mempool.</param> /// <returns>A <see cref="GetTxOutModel"/> containing the unspent outputs of the transaction id and vout. <c>null</c> if unspent outputs not found.</returns> /// <exception cref="ArgumentException">Thrown if txid is invalid.</exception>" [ActionName("gettxout")] [ActionDescription("Gets the unspent outputs of a transaction id and vout number.")] public async Task<GetTxOutModel> GetTxOutAsync(string txid, uint vout, bool includeMemPool = true) { uint256 trxid; if (!uint256.TryParse(txid, out trxid)) throw new ArgumentException(nameof(txid)); UnspentOutputs unspentOutputs = null; if (includeMemPool && this.pooledGetUnspentTransaction != null) unspentOutputs = await this.pooledGetUnspentTransaction.GetUnspentTransactionAsync(trxid).ConfigureAwait(false); if (!includeMemPool && this.getUnspentTransaction != null) unspentOutputs = await this.getUnspentTransaction.GetUnspentTransactionAsync(trxid).ConfigureAwait(false); if (unspentOutputs != null) return new GetTxOutModel(unspentOutputs, vout, this.Network, this.ChainIndexer.Tip); return null; } /// <summary> /// Implements the getblockcount RPC call. /// </summary> /// <returns>The current consensus tip height.</returns> [ActionName("getblockcount")] [ActionDescription("Gets the current consensus tip height.")] public int GetBlockCount() { return this.ConsensusManager?.Tip.Height ?? -1; } /// <summary> /// Implements the getinfo RPC call. /// </summary> /// <returns>A <see cref="GetInfoModel"/> with information about the full node.</returns> [ActionName("getinfo")] [ActionDescription("Gets general information about the full node.")] public GetInfoModel GetInfo() { var model = new GetInfoModel { Version = this.FullNode?.Version?.ToUint() ?? 0, ProtocolVersion = (uint)(this.Settings?.ProtocolVersion ?? NodeSettings.SupportedProtocolVersion), Blocks = this.ChainState?.ConsensusTip?.Height ?? 0, TimeOffset = this.ConnectionManager?.ConnectedPeers?.GetMedianTimeOffset() ?? 0, Connections = this.ConnectionManager?.ConnectedPeers?.Count(), Proxy = string.Empty, Difficulty = this.GetNetworkDifficulty()?.Difficulty ?? 0, Testnet = this.Network.IsTest(), RelayFee = this.Settings?.MinRelayTxFeeRate?.FeePerK?.ToUnit(MoneyUnit.BTC) ?? 0, Errors = string.Empty, //TODO: Wallet related infos: walletversion, balance, keypNetwoololdest, keypoolsize, unlocked_until, paytxfee WalletVersion = null, Balance = null, KeypoolOldest = null, KeypoolSize = null, UnlockedUntil = null, PayTxFee = null }; return model; } /// <summary> /// Implements getblockheader RPC call. /// </summary> /// <param name="hash">Hash of the block.</param> /// <param name="isJsonFormat">Indicates whether to provide data in Json or binary format.</param> /// <returns>The block header rpc format.</returns> /// <remarks>The binary format is not supported with RPC.</remarks> [ActionName("getblockheader")] [ActionDescription("Gets the block header of the block identified by the hash.")] public object GetBlockHeader(string hash, bool isJsonFormat = true) { Guard.NotNull(hash, nameof(hash)); this.logger.LogDebug("RPC GetBlockHeader {0}", hash); if (this.ChainIndexer == null) return null; BlockHeader blockHeader = this.ChainIndexer.GetHeader(uint256.Parse(hash))?.Header; if (blockHeader == null) return null; if (isJsonFormat) return new BlockHeaderModel(blockHeader); return new HexModel(blockHeader.ToHex(this.Network)); } /// <summary> /// Returns information about a bitcoin address and it's validity. /// </summary> /// <param name="address">The bech32 or base58 <see cref="BitcoinAddress"/> to validate.</param> /// <returns><see cref="ValidatedAddress"/> instance containing information about the bitcoin address and it's validity.</returns> /// <exception cref="ArgumentNullException">Thrown if address provided is null or empty.</exception> [ActionName("validateaddress")] [ActionDescription("Returns information about a bech32 or base58 bitcoin address")] public ValidatedAddress ValidateAddress(string address) { Guard.NotEmpty(address, nameof(address)); var result = new ValidatedAddress { IsValid = false, Address = address, }; try { // P2WPKH if (BitcoinWitPubKeyAddress.IsValid(address, this.Network, out Exception _)) { result.IsValid = true; } // P2WSH else if (BitcoinWitScriptAddress.IsValid(address, this.Network, out Exception _)) { result.IsValid = true; } // P2PKH else if (BitcoinPubKeyAddress.IsValid(address, this.Network)) { result.IsValid = true; } // P2SH else if (BitcoinScriptAddress.IsValid(address, this.Network)) { result.IsValid = true; result.IsScript = true; } } catch (NotImplementedException) { result.IsValid = false; } if (result.IsValid) { var scriptPubKey = BitcoinAddress.Create(address, this.Network).ScriptPubKey; result.ScriptPubKey = scriptPubKey.ToHex(); result.IsWitness = scriptPubKey.IsWitness(this.Network); } return result; } /// <summary> /// RPC method for returning a block. /// <para> /// Supports Json format by default, and optionally raw (hex) format by supplying <c>0</c> to <see cref="verbosity"/>. /// </para> /// </summary> /// <param name="blockHash">Hash of block to find.</param> /// <param name="verbosity">Defaults to 1. 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data.</param> /// <returns>The block according to format specified in <see cref="verbosity"/></returns> [ActionName("getblock")] [ActionDescription("Returns the block in hex, given a block hash.")] public object GetBlock(string blockHash, int verbosity = 1) { uint256 blockId = uint256.Parse(blockHash); // Does the block exist. ChainedHeader chainedHeader = this.ChainIndexer.GetHeader(blockId); if (chainedHeader == null) return null; Block block = chainedHeader.Block ?? this.blockStore?.GetBlock(blockId); // In rare occasions a block that is found in the // indexer may not have been pushed to the store yet. if (block == null) return null; if (verbosity == 0) return new HexModel(block.ToHex(this.Network)); var blockModel = new BlockModel(block, chainedHeader, this.ChainIndexer.Tip, this.Network, verbosity); if (this.Network.Consensus.IsProofOfStake) { var posBlock = block as PosBlock; blockModel.PosBlockSignature = posBlock.BlockSignature.ToHex(this.Network); blockModel.PosBlockTrust = new Target(chainedHeader.GetBlockProof()).ToUInt256().ToString(); blockModel.PosChainTrust = chainedHeader.ChainWork.ToString(); // this should be similar to ChainWork if (this.stakeChain != null) { BlockStake blockStake = this.stakeChain.Get(blockId); blockModel.PosModifierv2 = blockStake?.StakeModifierV2.ToString(); blockModel.PosFlags = blockStake?.Flags == BlockFlag.BLOCK_PROOF_OF_STAKE ? "proof-of-stake" : "proof-of-work"; blockModel.PosHashProof = blockStake?.HashProof.ToString(); } } return blockModel; } [ActionName("getnetworkinfo")] [ActionDescription("Returns an object containing various state info regarding P2P networking.")] public NetworkInfoModel GetNetworkInfo() { var networkInfoModel = new NetworkInfoModel { Version = this.FullNode?.Version?.ToUint() ?? 0, SubVersion = this.Settings?.Agent, ProtocolVersion = (uint)(this.Settings?.ProtocolVersion ?? NodeSettings.SupportedProtocolVersion), IsLocalRelay = this.ConnectionManager?.Parameters?.IsRelay ?? false, TimeOffset = this.ConnectionManager?.ConnectedPeers?.GetMedianTimeOffset() ?? 0, Connections = this.ConnectionManager?.ConnectedPeers?.Count(), IsNetworkActive = true, RelayFee = this.Settings?.MinRelayTxFeeRate?.FeePerK?.ToUnit(MoneyUnit.BTC) ?? 0, IncrementalFee = this.Settings?.MinRelayTxFeeRate?.FeePerK?.ToUnit(MoneyUnit.BTC) ?? 0 // set to same as min relay fee }; var services = this.ConnectionManager?.Parameters?.Services; if (services != null) { networkInfoModel.LocalServices = Encoders.Hex.EncodeData(BitConverter.GetBytes((ulong)services)); } return networkInfoModel; } [ActionName("getblockchaininfo")] [ActionDescription("Returns an object containing various state info regarding blockchain processing.")] public BlockchainInfoModel GetBlockchainInfo() { var blockchainInfo = new BlockchainInfoModel { Chain = this.Network?.Name, Blocks = (uint)(this.ChainState?.ConsensusTip?.Height ?? 0), Headers = (uint)(this.ChainIndexer?.Height ?? 0), BestBlockHash = this.ChainState?.ConsensusTip?.HashBlock, Difficulty = this.GetNetworkDifficulty()?.Difficulty ?? 0.0, MedianTime = this.ChainState?.ConsensusTip?.GetMedianTimePast().ToUnixTimeSeconds() ?? 0, VerificationProgress = 0.0, IsInitialBlockDownload = this.ibdState?.IsInitialBlockDownload() ?? true, Chainwork = this.ChainState?.ConsensusTip?.ChainWork, IsPruned = false }; if (blockchainInfo.Headers > 0) { blockchainInfo.VerificationProgress = (double)blockchainInfo.Blocks / blockchainInfo.Headers; } // softfork deployments blockchainInfo.SoftForks = new List<SoftForks>(); foreach (var consensusBuriedDeployment in Enum.GetValues(typeof(BuriedDeployments))) { bool active = this.ChainIndexer.Height >= this.Network.Consensus.BuriedDeployments[(BuriedDeployments) consensusBuriedDeployment]; blockchainInfo.SoftForks.Add(new SoftForks { Id = consensusBuriedDeployment.ToString().ToLower(), Version = (int)consensusBuriedDeployment + 2, // hack to get the deployment number similar to bitcoin core without changing the enums Status = new SoftForksStatus {Status = active} }); } // softforkbip9 deployments blockchainInfo.SoftForksBip9 = new Dictionary<string, SoftForksBip9>(); ConsensusRuleEngine ruleEngine = (ConsensusRuleEngine)this.ConsensusManager.ConsensusRules; ThresholdState[] thresholdStates = ruleEngine.NodeDeployments.BIP9.GetStates(this.ChainIndexer.Tip.Previous); List<ThresholdStateModel> metrics = ruleEngine.NodeDeployments.BIP9.GetThresholdStateMetrics(this.ChainIndexer.Tip.Previous, thresholdStates); foreach (ThresholdStateModel metric in metrics.Where(m => !m.DeploymentName.ToLower().Contains("test"))) // to remove the test dummy { // TODO: Deployment timeout may not be implemented yet // Deployments with timeout value of 0 are hidden. // A timeout value of 0 guarantees a softfork will never be activated. // This is used when softfork codes are merged without specifying the deployment schedule. if (metric.TimeTimeOut?.Ticks > 0) blockchainInfo.SoftForksBip9.Add(metric.DeploymentName, this.CreateSoftForksBip9(metric, thresholdStates[metric.DeploymentIndex])); } // TODO: Implement blockchainInfo.warnings return blockchainInfo; } private SoftForksBip9 CreateSoftForksBip9(ThresholdStateModel metric, ThresholdState state) { var softForksBip9 = new SoftForksBip9() { Status = metric.ThresholdState.ToLower(), Bit = this.Network.Consensus.BIP9Deployments[metric.DeploymentIndex].Bit, StartTime = metric.TimeStart?.ToUnixTimestamp() ?? 0, Timeout = metric.TimeTimeOut?.ToUnixTimestamp() ?? 0, Since = metric.SinceHeight }; if (state == ThresholdState.Started) { softForksBip9.Statistics = new SoftForksBip9Statistics(); softForksBip9.Statistics.Period = metric.ConfirmationPeriod; softForksBip9.Statistics.Threshold = metric.Threshold; softForksBip9.Statistics.Count = metric.Blocks; softForksBip9.Statistics.Elapsed = metric.Height - metric.PeriodStartHeight; softForksBip9.Statistics.Possible = (softForksBip9.Statistics.Period - softForksBip9.Statistics.Threshold) >= (softForksBip9.Statistics.Elapsed - softForksBip9.Statistics.Count); } return softForksBip9; } private ChainedHeader GetTransactionBlock(uint256 trxid) { ChainedHeader block = null; uint256 blockid = this.blockStore?.GetBlockIdByTransactionId(trxid); if (blockid != null) block = this.ChainIndexer?.GetHeader(blockid); return block; } private Target GetNetworkDifficulty() { return this.networkDifficulty?.GetNetworkDifficulty(); } } }
45.13211
213
0.611863
[ "MIT" ]
Auxon/StratisBitcoinFullNode
src/Stratis.Bitcoin.Features.RPC/Controllers/FullNodeController.cs
24,599
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT { /// <summary> /// <see cref="Windows.UI.Xaml.Controls.ClickMode"/> /// </summary> public enum ClickMode { Release = 0, Press = 1, Hover = 2, } }
28.875
72
0.645022
[ "MIT" ]
devsko/Microsoft.Toolkit.Win32
Microsoft.Toolkit.Win32.UI.Controls/Interop/WinRT/ClickMode.cs
462
C#
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Mechsoft.GeneralUtilities; using Mechsoft.FleetDeal; using log4net; public partial class User_Controls_UCSeries : System.Web.UI.UserControl { #region Variable declaration Cls_SeriesMaster objSeries = null; ILog logger = LogManager.GetLogger(typeof(User_Controls_UCSeries)); #endregion #region Bind models public void BindModelDropDrown(DropDownList ddlToBind, string ValueToSelect, int MakeID) { try { ddlToBind.Items.Clear(); Cls_ModelHelper objModel = new Cls_ModelHelper(); objModel.MakeID = MakeID; DataTable dtModels = objModel.GetModelsOfMake(); ddlToBind.DataSource = dtModels; ddlToBind.DataBind(); if (ddlToBind.Items.Count == 0) { ddlToBind.Items.Insert(0, new ListItem("-No Models Found-", "0")); } else { ddlToBind.Items.Insert(0, new ListItem("-Select Model-", "0")); } if (ValueToSelect != "0") ddlToBind.SelectedIndex = ddlToBind.Items.IndexOf(ddlToBind.Items.FindByValue(ValueToSelect.ToString())); } catch (Exception ex) { logger.Error("BindDropDrown Function :" + ex.Message); } } #endregion #region BindData private void BindData() { try { objSeries = new Cls_SeriesMaster(); DataTable dtSeries = null; dtSeries = objSeries.GetAllSeries(); DataView dv = dtSeries.DefaultView; dv.Sort = string.Format("{0} {1}", ViewState[Cls_Constants.VIEWSTATE_SORTEXPRESSION].ToString(), ViewState[Cls_Constants.VIEWSTATE_SORTDIRECTION].ToString()); dtSeries = dv.ToTable(); BindGridView(dtSeries); BindMakeDropDown(((DropDownList)gvSeriesDetails.FooterRow.FindControl("ddlMakes")),null, "0",""); BindMakeDropDown(ddlSearchMakes,null, "0", ""); ddlSearchModel.Items.Insert(0, new ListItem("-Select Make-", "0")); } catch (Exception ex) { logger.Error("BindData Function :" + ex.Message); } } #endregion #region Bind grid view private void BindGridView(DataTable dtSeries) { try { if (dtSeries != null) { if (dtSeries.Rows.Count == 0) { RemoveConstraints(dtSeries); dtSeries.Rows.Add(dtSeries.NewRow()); gvSeriesDetails.DataSource = dtSeries; gvSeriesDetails.DataBind(); gvSeriesDetails.Rows[0].Visible = false; } else { gvSeriesDetails.DataSource = dtSeries; gvSeriesDetails.DataBind(); } } else { } } catch (Exception ex) { } } #endregion #region Bind makes private void BindMakeDropDown(DropDownList dropDownList, DropDownList ddlModelsToBind, string ValueToSelect, string ModelValueToSelect) { try { Cls_MakeHelper objMake = new Cls_MakeHelper(); DataTable dtMakes = objMake.GetActiveMakes(); dropDownList.DataSource = dtMakes; dropDownList.DataBind(); dropDownList.Items.Insert(0, new ListItem("-Select Make-", "0")); if (ValueToSelect != "0") { dropDownList.SelectedIndex = dropDownList.Items.IndexOf(dropDownList.Items.FindByValue(ValueToSelect.ToString())); BindModelDropDrown(ddlModelsToBind, ModelValueToSelect, Convert.ToInt16(ValueToSelect)); } } catch (Exception ex) { logger.Error("BindMakeDropDown Function :" + ex.Message); } } #endregion #region Remove constraints private void RemoveConstraints(DataTable dt) { try { foreach (DataColumn Dc in dt.Columns) { Dc.ReadOnly = false; Dc.AllowDBNull = true; } } catch (Exception ex) { logger.Error("RemoveConstraints Function :" + ex.Message); } } #endregion #region Page load protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { ViewState[Cls_Constants.VIEWSTATE_SORTEXPRESSION] = "Make"; ViewState[Cls_Constants.VIEWSTATE_SORTDIRECTION] = Cls_Constants.VIEWSTATE_ASC; BindData(); } } catch (Exception ex) { logger.Error("Page_Load Event :" + ex.Message); } } #endregion #region Add button click protected void imgbtnAdd_Click(object sender, ImageClickEventArgs e) { try { objSeries = new Cls_SeriesMaster(); objSeries.ModelID = Convert.ToInt16(((DropDownList)gvSeriesDetails.FooterRow.FindControl("ddlModels")).SelectedValue.ToString()); objSeries.Series = ((TextBox)gvSeriesDetails.FooterRow.FindControl("txtSeries")).Text.ToString(); if (objSeries.CheckIfSeriesExists().Rows.Count == 0) { objSeries.DBOperation = DbOperations.INSERT; int result = objSeries.AddSeries(); if (result == 1) lblResult.Text = "Make Added Successfully"; else lblResult.Text = " Make Addition Failed"; BindData(); } else { lblResult.Text = "Series " + objSeries.Series + " already exists."; } } catch (Exception ex) { logger.Error("imgbtnAdd_Click Event :" + ex.Message); } } #endregion #region Grid row updating protected void gvSeriesDetails_RowUpdating(object sender, GridViewUpdateEventArgs e) { try { int ID = Convert.ToInt16(gvSeriesDetails.DataKeys[e.RowIndex][0].ToString()); int ModelID = Convert.ToInt16(((DropDownList)gvSeriesDetails.Rows[e.RowIndex].FindControl("ddlEditModels")).SelectedValue.ToString()); String Series = ((TextBox)gvSeriesDetails.Rows[e.RowIndex].FindControl("txtEditSeries")).Text.ToString(); objSeries = new Cls_SeriesMaster(); objSeries.ID = ID; objSeries.ModelID = ModelID; objSeries.Series = Series; if (objSeries.CheckIfSeriesExists().Rows.Count == 0) { objSeries.DBOperation = DbOperations.UPDATE; int result = objSeries.UpdateSeries(); gvSeriesDetails.EditIndex = -1; BindData(); if (result == 1) lblResult.Text = "Series Updated Successfully"; else lblResult.Text = " Series Updation Failed"; } else { lblResult.Text = "Series " + Series + " already exists."; } } catch (Exception ex) { logger.Error("gvSeriesDetails_RowUpdating Event :" + ex.Message); } } #endregion #region Grid row command protected void gvSeriesDetails_RowCommand(object sender, GridViewCommandEventArgs e) { try { objSeries = new Cls_SeriesMaster(); int Result = 0; if (e.CommandName == "Activeness") { int RowIndex = Convert.ToInt16(e.CommandArgument.ToString()); RowIndex = RowIndex - (gvSeriesDetails.PageIndex * gvSeriesDetails.PageSize); int ID = Convert.ToInt16(gvSeriesDetails.DataKeys[RowIndex][0].ToString()); Boolean IsActive = Convert.ToBoolean(((HiddenField)gvSeriesDetails.Rows[RowIndex].FindControl("hdfIsActive")).Value.ToString()); objSeries.ID = ID; objSeries.DBOperation = DbOperations.CHANGE_ACTIVENESS; objSeries.IsActive = (!IsActive); Result = objSeries.SetActivenessOfSeries(); if (Result == 1) { if (!IsActive) lblResult.Text = "Series Activated Successfully"; else lblResult.Text = "Series Deactivated Successfully"; } else { if (!IsActive) lblResult.Text = "Failed to Activate the Make"; else lblResult.Text = "Failed to Deactivate the Make"; } BindData(); } if (e.CommandName.Equals("GetModelsofMake")) { } } catch (Exception ex) { logger.Error("gvSeriesDetails_RowCommand Event :" + ex.Message); } } #endregion #region Cancel button click protected void imgbtnCancel_Click(object sender, ImageClickEventArgs e) { try { gvSeriesDetails.EditIndex = -1; BindData(); } catch (Exception ex) { logger.Error("imgbtnCancel_Click Event :" + ex.Message); } } #endregion #region Gris row data bound protected void gvSeriesDetails_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { try { Image imgBtnActive = ((Image)e.Row.FindControl("imgbtnActivate")); Image imgActive = ((Image)e.Row.FindControl("imgActive")); LinkButton lnkbtnActivate = ((LinkButton)e.Row.FindControl("lnkbtnActiveness")); if (imgBtnActive != null) { if (Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "IsActive"))) { imgBtnActive.ImageUrl = "~/Images/Active.png"; imgActive.ImageUrl = "~/Images/active_bullate.jpg"; imgActive.ToolTip = "Deactivate This Record"; e.Row.CssClass = "gridactiverow"; } else { imgBtnActive.ImageUrl = "~/Images/Inactive.ico"; imgActive.ImageUrl = "~/Images/deactive_bullate.jpg"; e.Row.CssClass = "griddeactiverow"; imgActive.ToolTip = "Activate This Record"; } } if (lnkbtnActivate != null) { if (Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "IsActive"))) { lnkbtnActivate.Text = "Deactivate"; } else { lnkbtnActivate.Text = "Activate"; } } } catch (Exception ex) { logger.Error("gvSeriesDetails_RowDataBound Event :" + ex.Message); } } } #endregion #region Grid row editing protected void gvSeriesDetails_RowEditing(object sender, GridViewEditEventArgs e) { lblResult.Text = ""; Boolean IsActive = Convert.ToBoolean(((HiddenField)gvSeriesDetails.Rows[e.NewEditIndex].FindControl("hdfIsActive")).Value.ToString()); if (IsActive) { gvSeriesDetails.EditIndex = e.NewEditIndex; BindData(); try { DropDownList ddlModelsToBind = ((DropDownList)gvSeriesDetails.Rows[e.NewEditIndex].FindControl("ddlEditModels")); DropDownList dropDownList = ((DropDownList)gvSeriesDetails.Rows[e.NewEditIndex].FindControl("ddlEditMakes")); HiddenField MakeID = ((HiddenField)gvSeriesDetails.Rows[e.NewEditIndex].FindControl("hdfMakeID")); HiddenField ModelID = ((HiddenField)gvSeriesDetails.Rows[e.NewEditIndex].FindControl("hdfModelID")); BindMakeDropDown(dropDownList, ddlModelsToBind, MakeID.Value.ToString(), ModelID.Value.ToString()); } catch (Exception ex) { logger.Error("gvSeriesDetails_RowEditing Event :" + ex.Message); } } else { lblResult.Text = "Deactivated series cna not be updated"; } } #endregion #region Grid page index changing protected void gvSeriesDetails_PageIndexChanging(object sender, GridViewPageEventArgs e) { try { gvSeriesDetails.PageIndex = e.NewPageIndex; BindData(); } catch (Exception ex) { logger.Error("gvSeriesDetails_PageIndexChanging Event :" + ex.Message); } } #endregion #region Grid sorting protected void gv_Sorting(object sender, GridViewSortEventArgs e) { ViewState[Cls_Constants.VIEWSTATE_SORTEXPRESSION] = e.SortExpression; //Swap sort direction this.DefineSortDirection(); // BindData(objCourseMaster); this.BindData(); } #endregion #region Define sort direction /// <summary> /// Define sort direction for grid. /// </summary> /// <param name="objAlias"></param> private void DefineSortDirection() { if (ViewState[Cls_Constants.VIEWSTATE_SORTEXPRESSION] != null) { if (ViewState[Cls_Constants.VIEWSTATE_SORTDIRECTION].ToString() == Cls_Constants.VIEWSTATE_ASC) { ViewState[Cls_Constants.VIEWSTATE_SORTDIRECTION] = Cls_Constants.VIEWSTATE_DESC; } else { ViewState[Cls_Constants.VIEWSTATE_SORTDIRECTION] = Cls_Constants.VIEWSTATE_ASC; } } } #endregion #region ddlmake selected index protected void ddlMakes_SelectedIndexChanged(object sender, EventArgs e) { ddlSearchModel.Items.Clear(); int MakeID = Convert.ToInt16(((DropDownList)sender).SelectedValue.ToString()); BindModelDropDrown(ddlSearchModel, "0", MakeID); } #endregion #region ddl Search make selected index protected void ddlSearchMakes_SelectedIndexChanged(object sender, EventArgs e) { int MakeID = Convert.ToInt16(((DropDownList)sender).SelectedValue.ToString()); BindModelDropDrown(ddlSearchModel, "0", MakeID); } #endregion #region ddl Edit makes selected index changed protected void ddlEditMakes_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow gvRow = (GridViewRow)((DropDownList)(sender)).Parent.Parent; HiddenField hdfkMakeID = (HiddenField)gvRow.FindControl("hdfMakeID"); DropDownList ddtToBind = ((DropDownList)gvRow.FindControl("ddlEditModels")); HiddenField ModelID = ((HiddenField)gvRow.FindControl("hdfModelID")); if (!(sender as DropDownList).SelectedValue.Equals("-Select-")) { int i = gvSeriesDetails.EditIndex; int MakeID = Convert.ToInt16((sender as DropDownList).SelectedValue.ToString()); BindModelDropDrown(ddtToBind, ModelID.Value.ToString(), MakeID); } else { ddtToBind.Items.Clear(); ddtToBind.Items.Insert(0, new ListItem("-Select Make First-", "-Select-")); } } #endregion #region Search cancel button protected void imgbtnSearchCancel_Click(object sender, ImageClickEventArgs e) { ddlSearchModel.Items.Clear(); ddlSearchMakes.SelectedIndex = 0; ddlSearchModel.Items.Insert(0, new ListItem("-Select Make-", "0")); txtSearchSeries.Text = ""; BindData(); } #endregion #region Search button click protected void imgbtnSearch_Click(object sender, ImageClickEventArgs e) { objSeries = new Cls_SeriesMaster(); DataTable dtSeries = null; try { objSeries.MakeID = Convert.ToInt32(ddlSearchMakes.SelectedValue.ToString()); objSeries.ModelID = Convert.ToInt32(ddlSearchModel.SelectedValue.ToString()); objSeries.Series = txtSearchSeries.Text; dtSeries=objSeries.GetSeriesByMakeAndModel(); BindGridView(dtSeries); } catch (Exception ex) { } } #endregion }
33.551102
170
0.570183
[ "MIT" ]
mileslee1987/PrivateFleet
PrivateFleet.New/User Controls/UCSeries.ascx.cs
16,742
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IDeviceAndAppManagementRoleAssignmentRequest. /// </summary> public partial interface IDeviceAndAppManagementRoleAssignmentRequest : IBaseRequest { /// <summary> /// Creates the specified DeviceAndAppManagementRoleAssignment using PUT. /// </summary> /// <param name="deviceAndAppManagementRoleAssignmentToCreate">The DeviceAndAppManagementRoleAssignment to create.</param> /// <returns>The created DeviceAndAppManagementRoleAssignment.</returns> System.Threading.Tasks.Task<DeviceAndAppManagementRoleAssignment> CreateAsync(DeviceAndAppManagementRoleAssignment deviceAndAppManagementRoleAssignmentToCreate); /// <summary> /// Creates the specified DeviceAndAppManagementRoleAssignment using PUT. /// </summary> /// <param name="deviceAndAppManagementRoleAssignmentToCreate">The DeviceAndAppManagementRoleAssignment to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DeviceAndAppManagementRoleAssignment.</returns> System.Threading.Tasks.Task<DeviceAndAppManagementRoleAssignment> CreateAsync(DeviceAndAppManagementRoleAssignment deviceAndAppManagementRoleAssignmentToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified DeviceAndAppManagementRoleAssignment. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified DeviceAndAppManagementRoleAssignment. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified DeviceAndAppManagementRoleAssignment. /// </summary> /// <returns>The DeviceAndAppManagementRoleAssignment.</returns> System.Threading.Tasks.Task<DeviceAndAppManagementRoleAssignment> GetAsync(); /// <summary> /// Gets the specified DeviceAndAppManagementRoleAssignment. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DeviceAndAppManagementRoleAssignment.</returns> System.Threading.Tasks.Task<DeviceAndAppManagementRoleAssignment> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified DeviceAndAppManagementRoleAssignment using PATCH. /// </summary> /// <param name="deviceAndAppManagementRoleAssignmentToUpdate">The DeviceAndAppManagementRoleAssignment to update.</param> /// <returns>The updated DeviceAndAppManagementRoleAssignment.</returns> System.Threading.Tasks.Task<DeviceAndAppManagementRoleAssignment> UpdateAsync(DeviceAndAppManagementRoleAssignment deviceAndAppManagementRoleAssignmentToUpdate); /// <summary> /// Updates the specified DeviceAndAppManagementRoleAssignment using PATCH. /// </summary> /// <param name="deviceAndAppManagementRoleAssignmentToUpdate">The DeviceAndAppManagementRoleAssignment to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated DeviceAndAppManagementRoleAssignment.</returns> System.Threading.Tasks.Task<DeviceAndAppManagementRoleAssignment> UpdateAsync(DeviceAndAppManagementRoleAssignment deviceAndAppManagementRoleAssignmentToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IDeviceAndAppManagementRoleAssignmentRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IDeviceAndAppManagementRoleAssignmentRequest Expand(Expression<Func<DeviceAndAppManagementRoleAssignment, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IDeviceAndAppManagementRoleAssignmentRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IDeviceAndAppManagementRoleAssignmentRequest Select(Expression<Func<DeviceAndAppManagementRoleAssignment, object>> selectExpression); } }
55.235849
206
0.695303
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IDeviceAndAppManagementRoleAssignmentRequest.cs
5,855
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Cdn.Models { public partial class HttpErrorRange : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(Begin)) { writer.WritePropertyName("begin"); writer.WriteNumberValue(Begin.Value); } if (Optional.IsDefined(End)) { writer.WritePropertyName("end"); writer.WriteNumberValue(End.Value); } writer.WriteEndObject(); } internal static HttpErrorRange DeserializeHttpErrorRange(JsonElement element) { Optional<int> begin = default; Optional<int> end = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("begin")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } begin = property.Value.GetInt32(); continue; } if (property.NameEquals("end")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } end = property.Value.GetInt32(); continue; } } return new HttpErrorRange(Optional.ToNullable(begin), Optional.ToNullable(end)); } } }
31.580645
92
0.506129
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/cdn/Azure.ResourceManager.Cdn/src/Generated/Models/HttpErrorRange.Serialization.cs
1,958
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraBehaviour : MonoBehaviour { public Transform target; public float resizeSpeed = 3f; public bool gameOver; float previousZ; // Update is called once per frame void LateUpdate () { if(target.position.z > transform.position.z - 3f && !gameOver){ transform.position = new Vector3(transform.position.x,transform.position.y,target.position.z + 3f); } } void FixedUpdate(){ //setCameraSize(); } void setCameraSize(){ float desiredSize = findSize(); GetComponent<Camera>().orthographicSize = Mathf.SmoothDamp(Camera.main.orthographicSize, desiredSize, ref resizeSpeed, Time.fixedDeltaTime); } float findSize(){ Vector3 camPosition = transform.InverseTransformPoint(transform.position); Vector3 targetPosition = transform.InverseTransformPoint(target.position); return targetPosition.y - camPosition.y; } }
28.114286
104
0.722561
[ "MIT" ]
JetLightStudio/ValleyOfCubes_Unity3D
Assets/Scripts/CameraBehaviour.cs
986
C#
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Testing; using NUnit.Framework; namespace Grpc.IntegrationTesting { /// <summary> /// Runs interop tests in-process. /// </summary> public class InteropClientServerTest { const string Host = "localhost"; Server server; Channel channel; TestService.TestServiceClient client; [TestFixtureSetUp] public void Init() { server = new Server { Services = { TestService.BindService(new TestServiceImpl()) }, Ports = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } } }; server.Start(); var options = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride) }; int port = server.Ports.Single().BoundPort; channel = new Channel(Host, port, TestCredentials.CreateSslCredentials(), options); client = new TestService.TestServiceClient(channel); } [TestFixtureTearDown] public void Cleanup() { channel.ShutdownAsync().Wait(); server.ShutdownAsync().Wait(); } [Test] public void EmptyUnary() { InteropClient.RunEmptyUnary(client); } [Test] public void LargeUnary() { InteropClient.RunLargeUnary(client); } [Test] public async Task ClientStreaming() { await InteropClient.RunClientStreamingAsync(client); } [Test] public async Task ServerStreaming() { await InteropClient.RunServerStreamingAsync(client); } [Test] public async Task PingPong() { await InteropClient.RunPingPongAsync(client); } [Test] public async Task EmptyStream() { await InteropClient.RunEmptyStreamAsync(client); } [Test] public async Task CancelAfterBegin() { await InteropClient.RunCancelAfterBeginAsync(client); } [Test] public async Task CancelAfterFirstResponse() { await InteropClient.RunCancelAfterFirstResponseAsync(client); } [Test] public async Task TimeoutOnSleepingServer() { await InteropClient.RunTimeoutOnSleepingServerAsync(client); } [Test] public async Task CustomMetadata() { await InteropClient.RunCustomMetadataAsync(client); } [Test] public async Task StatusCodeAndMessage() { await InteropClient.RunStatusCodeAndMessageAsync(client); } [Test] public void UnimplementedService() { InteropClient.RunUnimplementedService(new UnimplementedService.UnimplementedServiceClient(channel)); } [Test] public void UnimplementedMethod() { InteropClient.RunUnimplementedMethod(client); } } }
30.608696
112
0.64306
[ "BSD-3-Clause" ]
JiangxinNet/grpc
src/csharp/Grpc.IntegrationTesting/InteropClientServerTest.cs
4,928
C#
using Files.Repository; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.StaticFiles; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Threax.AspNetCore.Halcyon.Ext; namespace Files.Controllers { [Route("[controller]")] [ResponseCache(NoStore = true)] [Authorize(AuthenticationSchemes = AuthCoreSchemes.Cookies + "," + AuthCoreSchemes.Bearer)] public class DownloadController : Controller { private IPathInfoRepository repo; public DownloadController(IPathInfoRepository repo) { this.repo = repo; } /// <summary> /// Get a single value. /// </summary> /// <param name="path">The file to download.</param> /// <param name="contentTypeProvider">The content type provider from services.</param> /// <returns></returns> [HttpGet("{*Path}")] [HalRel("Download")] public async Task<FileStreamResult> Download(String path, [FromServices] IContentTypeProvider contentTypeProvider) { String contentType; if (!contentTypeProvider.TryGetContentType(path, out contentType)) { contentType = "application/octet-stream"; Response.Headers["Content-Disposition"] = "attachment"; } if (contentType?.Equals("text/html", StringComparison.InvariantCultureIgnoreCase) == true) { contentType = "application/octet-stream"; Response.Headers["Content-Disposition"] = "attachment"; } return new FileStreamResult(await repo.OpenRead(path), contentType) { EnableRangeProcessing = true }; } } }
33.618182
122
0.626284
[ "MIT" ]
threax/Threax.Files
Files/Controllers/DownloadController.cs
1,851
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Examples.Demos.EyeTracking.Logging { [AddComponentMenu("Scripts/MRTK/Examples/LogStructureEyeGaze")] public class LogStructureEyeGaze : LogStructure { private IMixedRealityEyeGazeProvider EyeTrackingProvider => eyeTrackingProvider ?? (eyeTrackingProvider = CoreServices.InputSystem?.EyeGazeProvider); private IMixedRealityEyeGazeProvider eyeTrackingProvider = null; public override string[] GetHeaderColumns() { return new string[] { // UserId "UserId", // SessionType "SessionType", // Timestamp "dt in ms", // Cam / Head tracking "HeadOrigin.x", "HeadOrigin.y", "HeadOrigin.z", "HeadDir.x", "HeadDir.y", "HeadDir.z", // Smoothed eye gaze tracking "EyeOrigin.x", "EyeOrigin.y", "EyeOrigin.z", "EyeDir.x", "EyeDir.y", "EyeDir.z", "EyeHitPos.x", "EyeHitPos.y", "EyeHitPos.z", }; } public override object[] GetData(string inputType, string inputStatus, EyeTrackingTarget intTarget) { // Let's prepare all the data we wanna log // Eye gaze hit position Vector3? eyeHitPos = null; if (EyeTrackingProvider?.GazeTarget != null && EyeTrackingProvider.IsEyeTrackingEnabledAndValid) eyeHitPos = EyeTrackingProvider.HitPosition; object[] data = new object[] { // Cam / Head tracking CameraCache.Main.transform.position.x, CameraCache.Main.transform.position.y, CameraCache.Main.transform.position.z, 0, 0, 0, // Smoothed eye gaze signal EyeTrackingProvider.IsEyeTrackingEnabledAndValid ? EyeTrackingProvider.GazeOrigin.x : 0, EyeTrackingProvider.IsEyeTrackingEnabledAndValid ? EyeTrackingProvider.GazeOrigin.y : 0, EyeTrackingProvider.IsEyeTrackingEnabledAndValid ? EyeTrackingProvider.GazeOrigin.z : 0, EyeTrackingProvider.IsEyeTrackingEnabledAndValid ? EyeTrackingProvider.GazeDirection.x : 0, EyeTrackingProvider.IsEyeTrackingEnabledAndValid ? EyeTrackingProvider.GazeDirection.y : 0, EyeTrackingProvider.IsEyeTrackingEnabledAndValid ? EyeTrackingProvider.GazeDirection.z : 0, (eyeHitPos != null) ? eyeHitPos.Value.x : float.NaN, (eyeHitPos != null) ? eyeHitPos.Value.y : float.NaN, (eyeHitPos != null) ? eyeHitPos.Value.z : float.NaN, }; return data; } } }
39.926829
157
0.571472
[ "MIT" ]
ERNICommunity/ERNI.SmartHomeAR
Assets/MRTK/Examples/Demos/EyeTracking/DemoVisualizer/Scripts/LogStructureEyeGaze.cs
3,276
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class TagHelpersTest : IClassFixture<MvcTestFixture<TagHelpersWebSite.Startup>>, IClassFixture<MvcEncodedTestFixture<TagHelpersWebSite.Startup>> { // Some tests require comparing the actual response body against an expected response baseline // so they require a reference to the assembly on which the resources are located, in order to // make the tests less verbose, we get a reference to the assembly with the resources and we // use it on all the rest of the tests. private static readonly Assembly _resourcesAssembly = typeof(TagHelpersTest).GetTypeInfo().Assembly; public TagHelpersTest( MvcTestFixture<TagHelpersWebSite.Startup> fixture, MvcEncodedTestFixture<TagHelpersWebSite.Startup> encodedFixture) { Client = fixture.Client; EncodedClient = encodedFixture.Client; } public HttpClient Client { get; } public HttpClient EncodedClient { get; } [Theory] [InlineData("Index")] [InlineData("About")] [InlineData("Help")] [InlineData("UnboundDynamicAttributes")] public async Task CanRenderViewsWithTagHelpers(string action) { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Home." + action + ".html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act // The host is not important as everything runs in memory and tests are isolated from each other. var response = await Client.GetAsync("http://localhost/Home/" + action); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); var responseContent = await response.Content.ReadAsStringAsync(); #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true); #endif } [Fact] public async Task CanRenderViewsWithTagHelpersAndUnboundDynamicAttributes_Encoded() { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Home.UnboundDynamicAttributes.Encoded.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act // The host is not important as everything runs in memory and tests are isolated from each other. var response = await EncodedClient.GetAsync("http://localhost/Home/UnboundDynamicAttributes"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); var responseContent = await response.Content.ReadAsStringAsync(); #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true); #endif } [Fact] public async Task ReregisteringAntiforgeryTokenInsideFormTagHelper_DoesNotAddDuplicateAntiforgeryTokenFields() { // Arrange var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8"); var outputFile = "compiler/resources/TagHelpersWebSite.Employee.DuplicateAntiforgeryTokenRegistration.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync("http://localhost/Employee/DuplicateAntiforgeryTokenRegistration"); var responseContent = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); responseContent = responseContent.Trim(); var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken( responseContent, "/Employee/DuplicateAntiforgeryTokenRegistration"); #if GENERATE_BASELINES // Reverse usual substitution and insert a format item into the new file content. responseContent = responseContent.Replace(forgeryToken, "{0}"); ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else expectedContent = string.Format(expectedContent, forgeryToken); // Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal( PlatformNormalizer.NormalizeContent(expectedContent.Trim()), responseContent, ignoreLineEndingDifferences: true); #endif } public static TheoryData TagHelpersAreInheritedFromViewImportsPagesData { get { // action, expected return new TheoryData<string, string> { { "NestedViewImportsTagHelper", @"<root>root-content</root> <nested>nested-content</nested>" }, { "ViewWithLayoutAndNestedTagHelper", @"layout:<root>root-content</root> <nested>nested-content</nested>" }, { "ViewWithInheritedRemoveTagHelper", @"layout:<root>root-content</root> page:<root/> <nested>nested-content</nested>" }, { "ViewWithInheritedTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, { "ViewWithOverriddenTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, { "ViewWithNestedInheritedTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, { "ViewWithNestedOverriddenTagHelperPrefix", @"layout:<root>root-content</root> page:<root>root-content</root>" }, }; } } [Theory] [MemberData(nameof(TagHelpersAreInheritedFromViewImportsPagesData))] public async Task TagHelpersAreInheritedFromViewImportsPages(string action, string expected) { // Arrange & Act var result = await Client.GetStringAsync("http://localhost/Home/" + action); // Assert Assert.Equal(expected, result.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task DefaultInheritedTagsCanBeRemoved() { // Arrange var expected = @"<a href=""~/VirtualPath"">Virtual path</a>"; var result = await Client.GetStringAsync("RemoveDefaultInheritedTagHelpers"); // Assert Assert.Equal(expected, result.Trim(), ignoreLineEndingDifferences: true); } [Fact] public async Task ViewsWithModelMetadataAttributes_CanRenderForm() { // Arrange var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync("http://localhost/Employee/Create"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else // Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal( PlatformNormalizer.NormalizeContent(expectedContent), responseContent, ignoreLineEndingDifferences: true); #endif } [Fact] public async Task ViewsWithModelMetadataAttributes_CanRenderPostedValue() { // Arrange var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Details.AfterCreate.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); var validPostValues = new Dictionary<string, string> { { "FullName", "Boo" }, { "Gender", "M" }, { "Age", "22" }, { "EmployeeId", "0" }, { "JoinDate", "2014-12-01" }, { "Email", "a@b.com" }, }; var postContent = new FormUrlEncodedContent(validPostValues); // Act var response = await Client.PostAsync("http://localhost/Employee/Create", postContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true); #endif } [Fact] public async Task ViewsWithModelMetadataAttributes_CanHandleInvalidData() { // Arrange var outputFile = "compiler/resources/TagHelpersWebSite.Employee.Create.Invalid.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); var validPostValues = new Dictionary<string, string> { { "FullName", "Boo" }, { "Gender", "M" }, { "Age", "1000" }, { "EmployeeId", "0" }, { "Email", "a@b.com" }, { "Salary", "z" }, }; var postContent = new FormUrlEncodedContent(validPostValues); // Act var response = await Client.PostAsync("http://localhost/Employee/Create", postContent); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else // Mono issue - https://github.com/aspnet/External/issues/19 Assert.Equal( PlatformNormalizer.NormalizeContent(expectedContent), responseContent, ignoreLineEndingDifferences: true); #endif } [Theory] [InlineData("Index")] [InlineData("CustomEncoder")] [InlineData("NullEncoder")] [InlineData("TwoEncoders")] [InlineData("ThreeEncoders")] public async Task EncodersPages_ReturnExpectedContent(string actionName) { // Arrange var outputFile = $"compiler/resources/TagHelpersWebSite.Encoders.{ actionName }.html"; var expectedContent = await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile: false); // Act var response = await Client.GetAsync($"/Encoders/{ actionName }"); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var responseContent = await response.Content.ReadAsStringAsync(); #if GENERATE_BASELINES ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent); #else Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true); #endif } } }
40.552795
120
0.618012
[ "Apache-2.0" ]
Karthik270290/Projects
test/Microsoft.AspNetCore.Mvc.FunctionalTests/TagHelpersTest.cs
13,058
C#
using System; using System.Collections; using System.Drawing; using System.Windows.Forms; namespace PocketPCControls { /// <summary> /// A control for viewing image thumbnails. /// </summary> public class ThumbnailViewer : Control { /* * Constants */ public const int THUMBNAIL_WIDTH = 64; public const int THUMBNAIL_HEIGHT = 64; public const int SPACER = 8; public const int SCROLLBAR_WIDTH = 20; #if POCKETPC protected const string PREFIX = "PUC.PocketPCControls."; #endif #if DESKTOP protected const string PREFIX = "DesktopPUC.PocketPCControls."; #endif protected const String NO_IMAGE_NAME = "noimage.bmp"; /* * Static Members & Constructor */ public readonly static Image NO_IMAGE; protected readonly static Pen LIGHTGREY_PEN = new Pen( Color.LightGray ); protected readonly static Pen BLACK_PEN = new Pen( Color.Black ); protected readonly static Pen SELECTED_PEN = new Pen( Color.DarkBlue ); protected readonly static SolidBrush WHITE_BRUSH = new SolidBrush( Color.White ); protected readonly static Rectangle SRCRECT = new Rectangle( 0, 0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT ); protected static System.Drawing.Image getImageFromResource( string imgName ) { string imageName = PREFIX + imgName; System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Stream file = thisExe.GetManifestResourceStream( imageName ); return new Bitmap( file ); } static ThumbnailViewer() { NO_IMAGE = getImageFromResource( NO_IMAGE_NAME ); } /* * Events */ public event EventHandler SelectedIndexChanged; /* * Member Variables */ protected ArrayList _thumbnails; protected int _selectedIndex; protected ScrollbarOrientation _scrollbarLoc; protected int _firstViewable; protected int _rows; protected int _cols; protected ScrollBar _scrollbar; protected Image _imageBuffer; /* * Constructor */ public ThumbnailViewer() { _thumbnails = new ArrayList(); _selectedIndex = -1; _scrollbarLoc = ScrollbarOrientation.Horizontal; _firstViewable = 0; _rows = _cols = 1; if ( _scrollbarLoc == ScrollbarOrientation.Horizontal ) { _scrollbar = new HScrollBar(); _scrollbar.Size = new Size( this.Width, SCROLLBAR_WIDTH ); _scrollbar.Location = new Point( 0, this.Height - SCROLLBAR_WIDTH ); } else { _scrollbar = new VScrollBar(); _scrollbar.Size = new Size( SCROLLBAR_WIDTH, this.Height ); _scrollbar.Location = new Point( this.Width - SCROLLBAR_WIDTH, 0 ); } this.Controls.Add( _scrollbar ); _scrollbar.ValueChanged += new EventHandler(ScrollBar_ValueChanged); } /* * Indexor */ public Image this[ int idx ] { get { if ( idx >= _thumbnails.Count || _thumbnails[ idx ] == null ) return null; return ((Thumbnail)_thumbnails[ idx ]).Image; } set { if ( idx >= _thumbnails.Count ) { _thumbnails.Capacity = idx+1; for( int i = _thumbnails.Count; i <= idx; i++ ) _thumbnails.Add( new Thumbnail( NO_IMAGE ) ); setupScrollbars(); } if ( value == null ) value = NO_IMAGE; if ( ((Thumbnail)_thumbnails[ idx ]).Image == NO_IMAGE ) { _thumbnails[ idx ] = new Thumbnail( value ); if ( ( idx >= _firstViewable ) && ( idx < ( _firstViewable + ViewableCount ) ) ) this.Invalidate(); } else { ((Thumbnail)_thumbnails[ idx ]).Image = value; if ( ( idx >= _firstViewable ) && ( idx < ( _firstViewable + ViewableCount ) ) ) this.Invalidate( ((Thumbnail)_thumbnails[ idx ]).VisibleRect ); } } } /* * Properties */ public int Count { get { return _thumbnails.Count; } } public int SelectedIndex { get { return _selectedIndex; } set { if ( _selectedIndex != value ) { _selectedIndex = value; this.Invalidate(); DisplayItem( _selectedIndex ); if ( SelectedIndexChanged != null ) SelectedIndexChanged( this, new EventArgs() ); } } } public int TopIndex { get { return _firstViewable; } set { _firstViewable = value; } } public int ViewableCount { get { return _rows * _cols; } } public ScrollbarOrientation ScrollbarOrientation { get { return _scrollbarLoc; } set { if ( value != _scrollbarLoc ) { _scrollbarLoc = value; this.Controls.Remove( _scrollbar ); _scrollbar.ValueChanged -= new EventHandler(ScrollBar_ValueChanged); if ( _scrollbarLoc == ScrollbarOrientation.Horizontal ) { _scrollbar = new HScrollBar(); _scrollbar.Size = new Size( this.Width, SCROLLBAR_WIDTH ); _scrollbar.Location = new Point( 0, this.Height - SCROLLBAR_WIDTH ); } else { _scrollbar = new VScrollBar(); _scrollbar.Size = new Size( SCROLLBAR_WIDTH, this.Height ); _scrollbar.Location = new Point( this.Width - SCROLLBAR_WIDTH, 0 ); } this.Controls.Add( _scrollbar ); _scrollbar.ValueChanged += new EventHandler(ScrollBar_ValueChanged); determineArrangement(); this.Invalidate(); } } } /* * Member Methods */ public void DisplayItem( int idx ) { // if the index is already in view, do nothing if ( idx >= _firstViewable && idx < _firstViewable + ViewableCount ) return; if ( _scrollbarLoc == ScrollbarOrientation.Horizontal ) { int col = idx / _rows; _firstViewable = col * _rows; this.Invalidate(); } else { int row = idx / _cols; _firstViewable = row * _cols; this.Invalidate(); } } /// <summary> /// Determine the number of rows and columns that this /// controls will use to show thumbnails. /// </summary> protected void determineArrangement() { int h = this.Height; int w = this.Width; if ( _scrollbarLoc == ScrollbarOrientation.Horizontal ) h -= SCROLLBAR_WIDTH; else w -= SCROLLBAR_WIDTH; _rows = Math.Max( 1, h / ( THUMBNAIL_HEIGHT + SPACER ) ); _cols = Math.Max( 1, w / ( THUMBNAIL_WIDTH + SPACER ) ); setupScrollbars(); } protected void setupScrollbars() { if ( _scrollbarLoc == ScrollbarOrientation.Horizontal ) { int maxcols = (int)Math.Ceiling( (double)Count / (double)_rows ); _scrollbar.Minimum = 0; _scrollbar.SmallChange = 1; _scrollbar.LargeChange = _cols; _scrollbar.Maximum = Math.Max( maxcols - 1, 0 ); _scrollbar.Value = _firstViewable / _rows; if ( maxcols <= _cols ) _scrollbar.Enabled = false; else _scrollbar.Enabled = true; } else { int maxrows = (int)Math.Ceiling( (double)Count / (double)_cols ); _scrollbar.Minimum = 0; _scrollbar.SmallChange = 1; _scrollbar.LargeChange = _rows; _scrollbar.Maximum = maxrows - 1; _scrollbar.Value = _firstViewable / _cols; if ( maxrows <= _rows ) _scrollbar.Enabled = false; else _scrollbar.Enabled = true; } } /* * Control Methods */ protected override void OnResize(EventArgs e) { if ( _imageBuffer != null ) _imageBuffer.Dispose(); _imageBuffer = new Bitmap( this.Width, this.Height ); if ( _scrollbarLoc == ScrollbarOrientation.Horizontal ) { _scrollbar.Size = new Size( this.Width, SCROLLBAR_WIDTH ); _scrollbar.Location = new Point( 0, this.Height - SCROLLBAR_WIDTH ); } else { _scrollbar.Size = new Size( SCROLLBAR_WIDTH, this.Height ); _scrollbar.Location = new Point( this.Width - SCROLLBAR_WIDTH, 0 ); } determineArrangement(); this.Invalidate(); } protected override void OnMouseDown(MouseEventArgs e) { int start = _firstViewable; for( int i = 0; ( i < ViewableCount ) && ( (start + i) < Count ) ; i++ ) { if ( _thumbnails[ start + i ] != null && ((Thumbnail)_thumbnails[ start + i ]).VisibleRect.Contains( e.X, e.Y ) ) { _selectedIndex = start + i; if ( SelectedIndexChanged != null ) SelectedIndexChanged( this, new EventArgs() ); this.Invalidate(); break; } } } protected override void OnPaintBackground(PaintEventArgs e) { // for double-buffering } protected override void OnPaint(PaintEventArgs e) { if ( _imageBuffer == null ) OnResize( e ); // get graphics object from buffer Graphics buf = Graphics.FromImage( _imageBuffer ); // fill background buf.FillRectangle( WHITE_BRUSH, 0, 0, this.Width, this.Height ); // draw thumbnails int idx = _firstViewable; if ( _scrollbarLoc == ScrollbarOrientation.Vertical ) { for( int row = 0; row < _rows && idx < Count; row++ ) for( int col = 0; col < _cols && idx < Count; col++, idx++ ) drawThumbnail( buf, (Thumbnail)_thumbnails[ idx ], row, col, idx == _selectedIndex ); } else { for( int col = 0; col < _cols && idx < Count; col++ ) for( int row = 0; row < _rows && idx < Count; row++, idx++ ) drawThumbnail( buf, (Thumbnail)_thumbnails[ idx ], row, col, idx == _selectedIndex ); } // draw buffer to the screen e.Graphics.DrawImage( _imageBuffer, 0, 0 ); } protected void drawThumbnail( Graphics g, Thumbnail tmbnail, int row, int col, bool selected ) { int x = SPACER + col * ( THUMBNAIL_WIDTH + SPACER ); int y = SPACER + row * ( THUMBNAIL_HEIGHT + SPACER ); g.DrawRectangle( LIGHTGREY_PEN, x-1, y-1, THUMBNAIL_WIDTH+1, THUMBNAIL_HEIGHT+1 ); if ( selected ) { g.DrawRectangle( SELECTED_PEN, x-2, y-2, THUMBNAIL_WIDTH+3, THUMBNAIL_HEIGHT+3 ); g.DrawRectangle( SELECTED_PEN, x-3, y-3, THUMBNAIL_WIDTH+5, THUMBNAIL_HEIGHT+5 ); } tmbnail.VisibleRect = new Rectangle( x, y, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT ); if ( tmbnail.Image.Width > THUMBNAIL_WIDTH || tmbnail.Image.Height > THUMBNAIL_HEIGHT ) { // if the image is larger than a thumbnail size, scale it down to fit Rectangle scaledRect = new Rectangle( x, y, 0, 0 ); if ( tmbnail.Image.Width > tmbnail.Image.Height ) { scaledRect.Width = THUMBNAIL_WIDTH; scaledRect.Height = (int)Math.Ceiling( (double)THUMBNAIL_WIDTH * ( (double)tmbnail.Image.Height / (double)tmbnail.Image.Width ) ); scaledRect.Y = y + ( THUMBNAIL_HEIGHT - scaledRect.Height ) / 2; } else { scaledRect.Height = THUMBNAIL_HEIGHT; scaledRect.Width = (int)Math.Ceiling( (double)THUMBNAIL_HEIGHT * ( (double)tmbnail.Image.Width / (double)tmbnail.Image.Height ) ); scaledRect.X = x + ( THUMBNAIL_WIDTH - scaledRect.Width ) / 2; } #if DESKTOP g.DrawImage( tmbnail.Image, scaledRect ); #endif #if POCKETPC g.DrawImage( tmbnail.Image, scaledRect, new Rectangle( 0, 0, tmbnail.Image.Width, tmbnail.Image.Height ), GraphicsUnit.Pixel ); #endif } else { int nX = 0, nY = 0; if ( tmbnail.Image.Width < THUMBNAIL_WIDTH ) nX = ( THUMBNAIL_WIDTH - tmbnail.Image.Width ) / 2; if ( tmbnail.Image.Height < THUMBNAIL_HEIGHT ) nY = ( THUMBNAIL_HEIGHT - tmbnail.Image.Height ) / 2; Rectangle srcRect = SRCRECT; if ( tmbnail.Image.Width > THUMBNAIL_WIDTH ) srcRect.X = ( tmbnail.Image.Width - THUMBNAIL_WIDTH ) / 2; if ( tmbnail.Image.Height > THUMBNAIL_HEIGHT ) srcRect.Y = ( tmbnail.Image.Height - THUMBNAIL_HEIGHT ) / 2; Rectangle destRect = new Rectangle( x + nX, y + nY, THUMBNAIL_WIDTH - nX, THUMBNAIL_HEIGHT - nY ); g.DrawImage( tmbnail.Image, destRect, srcRect, GraphicsUnit.Pixel ); } } protected override void OnKeyDown(KeyEventArgs e) { switch( e.KeyCode ) { case Keys.Up: if ( _selectedIndex != 0 ) { _selectedIndex--; this.Invalidate(); } break; case Keys.Down: if ( _selectedIndex != ( Count - 1 ) ) { _selectedIndex++; this.Invalidate(); } break; } } /* * Event Handlers */ private void ScrollBar_ValueChanged(object sender, EventArgs e) { if ( _scrollbar.Value < 0 ) return; if ( _scrollbarLoc == ScrollbarOrientation.Horizontal ) _firstViewable = _scrollbar.Value * _rows; else _firstViewable = _scrollbar.Value * _cols; this.Invalidate(); } /* * Inner Class */ public class Thumbnail { /* * Member Variables */ public Image Image; public Rectangle VisibleRect; /* * Constructor */ public Thumbnail( Image image ) { Image = image; } } } /// <summary> /// /// </summary> public enum ScrollbarOrientation { Horizontal, Vertical } }
23.938294
132
0.61069
[ "MIT" ]
jwnichls/puc
csharp/PocketPCControls/ThumbnailViewer.cs
13,190
C#
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Xunit; public class ClassWithNoNamespace { } namespace System.Drawing.Tests { public class bitmap_173x183_indexed_8bit { } public class ToolboxBitmapAttributeTests : RemoteExecutorTestBase { private static Size DefaultSize = new Size(16, 16); private void AssertDefaultSize(Image image) { try { Assert.Equal(DefaultSize, image.Size); } catch (Exception ex) { // On .NET Framework sometimes the size might be default or it might // be disposed in which case Size property throws an ArgumentException // so allow both cases see https://github.com/dotnet/corefx/issues/27361. if (PlatformDetection.IsFullFramework && ex is ArgumentException) { return; } throw; } } public static IEnumerable<object[]> Ctor_FileName_TestData() { yield return new object[] { null, new Size(0, 0) }; yield return new object[] { Helpers.GetTestBitmapPath("bitmap_173x183_indexed_8bit.bmp"), new Size(173, 183) }; yield return new object[] { Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico"), new Size(16, 16) }; yield return new object[] { Helpers.GetTestBitmapPath("invalid.ico"), new Size(0, 0) }; } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.GdiplusIsAvailable)] [MemberData(nameof(Ctor_FileName_TestData))] public void Ctor_FileName(string fileName, Size size) { var attribute = new ToolboxBitmapAttribute(fileName); using (Image image = attribute.GetImage(null)) { if (size == Size.Empty) { AssertDefaultSize(image); } else { Assert.Equal(size, image.Size); } } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.GdiplusIsAvailable)] [InlineData(null, -1, -1)] [InlineData(typeof(ClassWithNoNamespace), -1, -1)] [InlineData(typeof(bitmap_173x183_indexed_8bit), 173, 183)] [InlineData(typeof(ToolboxBitmapAttributeTests), -1, -1)] public void Ctor_Type(Type type, int width, int height) { var attribute = new ToolboxBitmapAttribute(type); using (Image image = attribute.GetImage(type)) { if (width == -1 && height == -1) { AssertDefaultSize(image); } else { Assert.Equal(new Size(width, height), image.Size); } } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.GdiplusIsAvailable)] [InlineData(null, null, -1, -1)] [InlineData(null, "invalid.ico", -1, -1)] [InlineData(typeof(ClassWithNoNamespace), null, -1, -1)] [InlineData(typeof(ToolboxBitmapAttributeTests), "", -1, -1)] [InlineData(typeof(ToolboxBitmapAttributeTests), null, -1, -1)] [InlineData(typeof(ToolboxBitmapAttributeTests), "invalid.ico", -1, -1)] [InlineData(typeof(ToolboxBitmapAttributeTests), "48x48_multiple_entries_4bit", 16, 16)] [InlineData(typeof(ToolboxBitmapAttributeTests), "48x48_multiple_entries_4bit.ico", 16, 16)] [InlineData(typeof(ToolboxBitmapAttributeTests), "empty.file", -1, -1)] [InlineData(typeof(ToolboxBitmapAttributeTests), "bitmap_173x183_indexed_8bit", 173, 183)] [InlineData(typeof(ToolboxBitmapAttributeTests), "bitmap_173x183_indexed_8bit.bmp", 173, 183)] public void Ctor_Type_String(Type type, string fileName, int width, int height) { var attribute = new ToolboxBitmapAttribute(type, fileName); using (Image image = attribute.GetImage(type, fileName, false)) { if (width == -1 && height == -1) { AssertDefaultSize(image); } else { Assert.Equal(new Size(width, height), image.Size); } } } [ConditionalTheory(Helpers.GdiplusIsAvailable)] [InlineData("bitmap_173x183_indexed_8bit.bmp", 173, 183)] [InlineData("48x48_multiple_entries_4bit.ico", 16, 16)] public void GetImage_TypeFileNameBool_ReturnsExpected(string fileName, int width, int height) { var attribute = new ToolboxBitmapAttribute((string)null); using (Image image = attribute.GetImage(typeof(ToolboxBitmapAttributeTests), fileName, large: true)) { Assert.Equal(new Size(32, 32), image.Size); } using (Image image = attribute.GetImage(typeof(ToolboxBitmapAttributeTests), fileName, large: false)) { Assert.Equal(new Size(width, height), image.Size); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void GetImage_NullComponent_ReturnsNull() { var attribute = new ToolboxBitmapAttribute((string)null); Assert.Null(attribute.GetImage((object)null)); Assert.Null(attribute.GetImage((object)null, true)); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void GetImage_Component_ReturnsExpected() { ToolboxBitmapAttribute attribute = new ToolboxBitmapAttribute((string)null); using (Image smallImage = attribute.GetImage(new bitmap_173x183_indexed_8bit(), large: false)) { Assert.Equal(new Size(173, 183), smallImage.Size); using (Image largeImage = attribute.GetImage(new bitmap_173x183_indexed_8bit(), large: true)) { Assert.Equal(new Size(32, 32), largeImage.Size); } } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.GdiplusIsAvailable)] public void GetImage_Default_ReturnsExpected() { ToolboxBitmapAttribute attribute = ToolboxBitmapAttribute.Default; using (Image image = attribute.GetImage(typeof(ToolboxBitmapAttributeTests), "bitmap_173x183_indexed_8bit", large: true)) { Assert.Equal(new Size(32, 32), image.Size); } using (Image image = attribute.GetImage(typeof(ToolboxBitmapAttributeTests), "bitmap_173x183_indexed_8bit", large: false)) { Assert.Equal(new Size(173, 183), image.Size); } } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { ToolboxBitmapAttribute.Default, ToolboxBitmapAttribute.Default, true }; yield return new object[] { ToolboxBitmapAttribute.Default, new ToolboxBitmapAttribute(typeof(ToolboxBitmapAttribute), "bitmap_173x183_indexed_8bit"), true }; yield return new object[] { ToolboxBitmapAttribute.Default, new object(), false }; yield return new object[] { ToolboxBitmapAttribute.Default, null, false }; } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.GdiplusIsAvailable)] [MemberData(nameof(Equals_TestData))] public void Equals_Other_ReturnsExpected(ToolboxBitmapAttribute attribute, object other, bool expected) { Assert.Equal(expected, attribute.Equals(other)); Assert.Equal(attribute.GetHashCode(), attribute.GetHashCode()); } } }
41.742268
170
0.602618
[ "MIT" ]
Adam25T/corefx
src/System.Drawing.Common/tests/ToolboxBitmapAttributeTests.cs
8,100
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; // Except public class Obst_Clear : MonoBehaviour { private GameObject drone; public GameObject _building; /// <summary> /// 今回の Update で検出された遮蔽物の Renderer コンポーネント。 /// </summary> private List<Renderer> rendererHitsList_ = new List<Renderer>(); /// <summary> /// 前回の Update で検出された遮蔽物の Renderer コンポーネント。 /// 今回の Update で該当しない場合は、遮蔽物ではなくなったので Renderer コンポーネントを有効にする。 /// </summary> /// <summary> /// 遮蔽物とするレイヤーマスク。 /// </summary> private int layerMask_; /// <summary> /// マテリアル比較用 /// </summary> private bool Compare_Material; /// <summary> /// 半透明マテリアル /// </summary> private Material mat; /// <summary> /// Except /// </summary> private Renderer[] rendererHitsPrevs_; /// <summary> /// Sphereを出すかの判定 /// </summary> private bool obst = false; /// <summary> /// 建物のMeshRenderer /// </summary> Renderer _mesh; void Start() { drone = GameObject.Find("droneModel"); mat = Resources.Load<Material>("Temparent_obj") as Material; if(drone == null){ Debug.Log("null"); } layerMask_ = 1; } void Update() { // カメラと被写体を結ぶ ray を作成 Vector3 _difference = (drone.transform.position - this.transform.position); Vector3 _direction = _difference.normalized; Ray _ray = new Ray(this.transform.position, _direction); Quaternion angle = new Quaternion(0f,0f,0f,0f); // 前回の結果を退避してから、Raycast して今回の遮蔽物のリストを取得する // RaycastHit[] _hits = Physics.RaycastAll(_ray, _difference.magnitude, layerMask_); // RaycastHit[] _hits = Physics.SphereCastAll(this.transform.position, 0.03f ,_direction, _difference.magnitude, layerMask_); RaycastHit[] _hits = Physics.BoxCastAll(this.transform.position, Vector3.one * 0.2f, _direction, angle, _difference.magnitude, layerMask_); //MaskObjectのRendererコンポーネント rendererHitsPrevs_ = rendererHitsList_.ToArray(); rendererHitsList_.Clear(); // 遮蔽物は一時的にすべて描画機能を無効にする。 foreach (RaycastHit _hit in _hits) { if(_hit.collider.gameObject.tag == "Building"){ Debug.Log("1"); // 遮蔽物の Renderer コンポーネントを無効にする Renderer _renderer = _hit.collider.gameObject.GetComponent<Renderer>(); Material mat = Resources.Load<Material>("Temparent_obj"); if (_renderer != null) { // _renderer.enabled = false; _renderer.material = mat; // _renderer.GetComponent<change>().enabled = false; Debug.Log(_renderer.tag); rendererHitsList_.Add(_renderer); obst = true; } } } // 前回まで対象で、今回対象でなくなったものは、表示を元に戻す。 foreach (Renderer _renderer in rendererHitsPrevs_.Except<Renderer>(rendererHitsList_)) { // Debug.Log("return" + _renderer.material.name); // _renderer.enabled = true; Compare_Material = (_renderer.material.name).SequenceEqual(mat.name + " (Instance"); _renderer.GetComponent<change>().enabled = true; Material mat_default = Resources.Load<Material>("default") as Material; _renderer.material = mat_default; obst = false; } } }
32.605505
148
0.590884
[ "MIT" ]
Howellm/AR_HoloLens2_Stereo
Assets/Obstract_Check/Obst_Clear.cs
4,038
C#
using System; public class Program { public static void Main() { double width = double.Parse(Console.ReadLine()); double height = double.Parse(Console.ReadLine()); Console.WriteLine(GetTriangleArea(width, height)); } static double GetTriangleArea(double width, double height) { return width * height / 2; } }
18.7
62
0.625668
[ "MIT" ]
IvayloKovachev09/SoftUni
Programming Fundamentals/method and debuging lab1/05. Calculate Triangle Area/05. Calculate Triangle Area.cs
376
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Mat3x5 { [TestFixture] public class BoolMat3x5Test { } }
18.652174
39
0.794872
[ "MIT" ]
akriegman/GlmSharpN
GlmSharp/GlmSharpTest5/Generated/Mat3x5/bmat3x5.Test.cs
429
C#
using System; using System.Linq; using System.Threading; using Inscribe.Storage; using Livet; namespace Inscribe.Core { /// <summary> /// Statistics Service /// </summary> public static class Statistics { private static readonly DateTime wakeupTimeStamp = DateTime.Now; static Timer tweetSpeedUpdate; static Timer wakeUpTimeUpdate; /// <summary> /// 初期化時アクセス用 /// </summary> public static void Initialize() { } static Statistics() { tweetSpeedUpdate = new Timer(TweetSpeedUpdateSink, null, 0, 1000 * 20); wakeUpTimeUpdate = new Timer(WakeupTimeUpdateSink, null, 0, 1000); } private static void TweetSpeedUpdateSink(object o) { // 鳥人 var morigin = (DateTime.Now - new TimeSpan(0, 1, 0)); TweetSpeedPerMin = TweetStorage.GetAll((t) => t.CreatedAt > morigin).Count(); var horigin = (DateTime.Now - new TimeSpan(1, 0, 0)); TweetSpeedPerHour = TweetStorage.GetAll((t) => t.CreatedAt > horigin).Count(); //System.Diagnostics.Debug.WriteLine(morigin.ToString() + " / " + horigin.ToString()); OnTweetSpeedUpdated(EventArgs.Empty); } private static void WakeupTimeUpdateSink(object o) { OnWakeupTimeUpdated(EventArgs.Empty); } #region TweetSpeedUpdatedイベント public static event EventHandler<EventArgs> TweetSpeedUpdated; private static Notificator<EventArgs> _TweetSpeedUpdatedEvent; public static Notificator<EventArgs> TweetSpeedUpdatedEvent { get { if (_TweetSpeedUpdatedEvent == null) _TweetSpeedUpdatedEvent = new Notificator<EventArgs>(); return _TweetSpeedUpdatedEvent; } set { _TweetSpeedUpdatedEvent = value; } } private static void OnTweetSpeedUpdated(EventArgs e) { var threadSafeHandler = Interlocked.CompareExchange(ref TweetSpeedUpdated, null, null); if (threadSafeHandler != null) threadSafeHandler(null, e); TweetSpeedUpdatedEvent.Raise(e); } #endregion #region WakeupTimeUpdatedイベント public static event EventHandler<EventArgs> WakeupTimeUpdated; private static Notificator<EventArgs> _WakeupTimeUpdatedEvent; public static Notificator<EventArgs> WakeupTimeUpdatedEvent { get { if (_WakeupTimeUpdatedEvent == null) _WakeupTimeUpdatedEvent = new Notificator<EventArgs>(); return _WakeupTimeUpdatedEvent; } set { _WakeupTimeUpdatedEvent = value; } } private static void OnWakeupTimeUpdated(EventArgs e) { var threadSafeHandler = Interlocked.CompareExchange(ref WakeupTimeUpdated, null, null); if (threadSafeHandler != null) threadSafeHandler(null, e); WakeupTimeUpdatedEvent.Raise(e); } #endregion public static int TweetSpeedPerMin { get; private set; } public static int TweetSpeedPerHour { get; private set; } public static string WakeupTime { get { var wakeup = DateTime.Now.Subtract(wakeupTimeStamp); return Math.Floor(wakeup.TotalHours).ToString() + ":" + wakeup.Minutes.ToString("00") + ":" + wakeup.Seconds.ToString("00"); } } } }
32.481818
108
0.602015
[ "MIT" ]
fin-alice/Mystique
Inscribe/Core/Statistics.cs
3,613
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using Excel = Microsoft.Office.Interop.Excel; namespace School_Software { public partial class frmBookIssueListStudent : Form { SqlDataReader rdr = null; DataTable dtable = new DataTable(); SqlConnection con = null; SqlCommand cmd = null; DataTable dt = new DataTable(); Connectionstring cs = new Connectionstring(); public frmBookIssueListStudent() { InitializeComponent(); } public void Auto() { try { con = new SqlConnection(cs.DBcon); con.Open(); cmd = new SqlCommand("SELECT Rtrim(BookIssue_Student.ID),BookIssue_Student.IssueDate,BookIssue_Student.DueDate,Rtrim(BookIssue_Student.AccessionNo),Rtrim(Book.BookTitle),Rtrim(Book.Author),Rtrim(Book.JointAuthors),Rtrim(BookIssue_Student.AdmissionNo),Rtrim(Student.StudentName),Rtrim(School.SchoolName),Rtrim(Class.ClassName),Rtrim(Section.SectionName),Rtrim(BookIssue_Student.Status),Rtrim(BookIssue_Student.Remarks) FROM BookIssue_Student INNER JOIN Book ON BookIssue_Student.AccessionNo = Book.AccessionNo INNER JOIN Student ON BookIssue_Student.AdmissionNo = Student.AdmissionNo INNER JOIN ClassSection ON Student.ClassSection_ID = ClassSection.ClassSectionID INNER JOIN Class ON ClassSection.Class_ID = Class.ClassID INNER JOIN Section ON ClassSection.Section_ID = Section.SectionID INNER JOIN School ON Student.School_ID = School.SchoolID", con); rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataGridView1.Rows.Clear(); while (rdr.Read() == true) { DataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7], rdr[8], rdr[9], rdr[10], rdr[11], rdr[12], rdr[13]); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void frmBookIssueListStudent_Load(object sender, EventArgs e) { Auto(); } public void Reset() { txtAccessionNo.Text = ""; txtBookTitle.Text = ""; txtAddmissionNo.Text = ""; txtStudentName.Text = ""; txtBookTitle.Text = ""; dtpDateFrom.Text = System.DateTime.Now.ToString(); dtpDateTo.Text = System.DateTime.Now.ToString(); txtFrom.Text = System.DateTime.Now.ToString(); txtTo.Text = System.DateTime.Now.ToString(); Auto(); } private void txtAccessionNo_TextChanged(object sender, EventArgs e) { try { con = new SqlConnection(cs.DBcon); con.Open(); cmd = new SqlCommand("SELECT Rtrim(BookIssue_Student.ID),BookIssue_Student.IssueDate,BookIssue_Student.DueDate,Rtrim(BookIssue_Student.AccessionNo),Rtrim(Book.BookTitle),Rtrim(Book.Author),Rtrim(Book.JointAuthors),Rtrim(BookIssue_Student.AdmissionNo),Rtrim(Student.StudentName),Rtrim(School.SchoolName),Rtrim(Class.ClassName),Rtrim(Section.SectionName),Rtrim(BookIssue_Student.Status),Rtrim(BookIssue_Student.Remarks) FROM BookIssue_Student INNER JOIN Book ON BookIssue_Student.AccessionNo = Book.AccessionNo INNER JOIN Student ON BookIssue_Student.AdmissionNo = Student.AdmissionNo INNER JOIN ClassSection ON Student.ClassSection_ID = ClassSection.ClassSectionID INNER JOIN Class ON ClassSection.Class_ID = Class.ClassID INNER JOIN Section ON ClassSection.Section_ID = Section.SectionID INNER JOIN School ON Student.School_ID = School.SchoolID Where BookIssue_Student.AccessionNo like '%" + txtAccessionNo.Text + "%' Order by DueDate", con); rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataGridView1.Rows.Clear(); while (rdr.Read() == true) { DataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7], rdr[8], rdr[9], rdr[10], rdr[11], rdr[12], rdr[13]); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void txtBookTitle_TextChanged(object sender, EventArgs e) { try { con = new SqlConnection(cs.DBcon); con.Open(); cmd = new SqlCommand("SELECT Rtrim(BookIssue_Student.ID),BookIssue_Student.IssueDate,BookIssue_Student.DueDate,Rtrim(BookIssue_Student.AccessionNo),Rtrim(Book.BookTitle),Rtrim(Book.Author),Rtrim(Book.JointAuthors),Rtrim(BookIssue_Student.AdmissionNo),Rtrim(Student.StudentName),Rtrim(School.SchoolName),Rtrim(Class.ClassName),Rtrim(Section.SectionName),Rtrim(BookIssue_Student.Status),Rtrim(BookIssue_Student.Remarks) FROM BookIssue_Student INNER JOIN Book ON BookIssue_Student.AccessionNo = Book.AccessionNo INNER JOIN Student ON BookIssue_Student.AdmissionNo = Student.AdmissionNo INNER JOIN ClassSection ON Student.ClassSection_ID = ClassSection.ClassSectionID INNER JOIN Class ON ClassSection.Class_ID = Class.ClassID INNER JOIN Section ON ClassSection.Section_ID = Section.SectionID INNER JOIN School ON Student.School_ID = School.SchoolID Where Book.BookTitle like '%" + txtBookTitle.Text + "%' Order by DueDate", con); rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataGridView1.Rows.Clear(); while (rdr.Read() == true) { DataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7], rdr[8], rdr[9], rdr[10], rdr[11], rdr[12], rdr[13]); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void txtAddmissionNo_TextChanged(object sender, EventArgs e) { try { con = new SqlConnection(cs.DBcon); con.Open(); cmd = new SqlCommand("SELECT Rtrim(BookIssue_Student.ID),BookIssue_Student.IssueDate,BookIssue_Student.DueDate,Rtrim(BookIssue_Student.AccessionNo),Rtrim(Book.BookTitle),Rtrim(Book.Author),Rtrim(Book.JointAuthors),Rtrim(BookIssue_Student.AdmissionNo),Rtrim(Student.StudentName),Rtrim(School.SchoolName),Rtrim(Class.ClassName),Rtrim(Section.SectionName),Rtrim(BookIssue_Student.Status),Rtrim(BookIssue_Student.Remarks) FROM BookIssue_Student INNER JOIN Book ON BookIssue_Student.AccessionNo = Book.AccessionNo INNER JOIN Student ON BookIssue_Student.AdmissionNo = Student.AdmissionNo INNER JOIN ClassSection ON Student.ClassSection_ID = ClassSection.ClassSectionID INNER JOIN Class ON ClassSection.Class_ID = Class.ClassID INNER JOIN Section ON ClassSection.Section_ID = Section.SectionID INNER JOIN School ON Student.School_ID = School.SchoolID Where BookIssue_Student.AdmissionNo like '%" + txtAddmissionNo.Text + "%' Order by DueDate", con); rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataGridView1.Rows.Clear(); while (rdr.Read() == true) { DataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7], rdr[8], rdr[9], rdr[10], rdr[11], rdr[12], rdr[13]); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void txtStudentName_TextChanged(object sender, EventArgs e) { try { con = new SqlConnection(cs.DBcon); con.Open(); cmd = new SqlCommand("SELECT Rtrim(BookIssue_Student.ID),BookIssue_Student.IssueDate,BookIssue_Student.DueDate,Rtrim(BookIssue_Student.AccessionNo),Rtrim(Book.BookTitle),Rtrim(Book.Author),Rtrim(Book.JointAuthors),Rtrim(BookIssue_Student.AdmissionNo),Rtrim(Student.StudentName),Rtrim(School.SchoolName),Rtrim(Class.ClassName),Rtrim(Section.SectionName),Rtrim(BookIssue_Student.Status),Rtrim(BookIssue_Student.Remarks) FROM BookIssue_Student INNER JOIN Book ON BookIssue_Student.AccessionNo = Book.AccessionNo INNER JOIN Student ON BookIssue_Student.AdmissionNo = Student.AdmissionNo INNER JOIN ClassSection ON Student.ClassSection_ID = ClassSection.ClassSectionID INNER JOIN Class ON ClassSection.Class_ID = Class.ClassID INNER JOIN Section ON ClassSection.Section_ID = Section.SectionID INNER JOIN School ON Student.School_ID = School.SchoolID Where Student.StudentName like '%" + txtStudentName.Text + "%' Order by DueDate", con); rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataGridView1.Rows.Clear(); while (rdr.Read() == true) { DataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7], rdr[8], rdr[9], rdr[10], rdr[11], rdr[12], rdr[13]); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Button2_Click(object sender, EventArgs e) { try { con = new SqlConnection(cs.DBcon); con.Open(); cmd = new SqlCommand("SELECT Rtrim(BookIssue_Student.ID),BookIssue_Student.IssueDate,BookIssue_Student.DueDate,Rtrim(BookIssue_Student.AccessionNo),Rtrim(Book.BookTitle),Rtrim(Book.Author),Rtrim(Book.JointAuthors),Rtrim(BookIssue_Student.AdmissionNo),Rtrim(Student.StudentName),Rtrim(School.SchoolName),Rtrim(Class.ClassName),Rtrim(Section.SectionName),Rtrim(BookIssue_Student.Status),Rtrim(BookIssue_Student.Remarks) FROM BookIssue_Student INNER JOIN Book ON BookIssue_Student.AccessionNo = Book.AccessionNo INNER JOIN Student ON BookIssue_Student.AdmissionNo = Student.AdmissionNo INNER JOIN ClassSection ON Student.ClassSection_ID = ClassSection.ClassSectionID INNER JOIN Class ON ClassSection.Class_ID = Class.ClassID INNER JOIN Section ON ClassSection.Section_ID = Section.SectionID INNER JOIN School ON Student.School_ID = School.SchoolID Where IssueDate Between @date1 and @Date2 Order by DueDate", con); cmd.Parameters.Add("@date1", SqlDbType.DateTime, 30, "IssueDate").Value = dtpDateFrom.Value.Date; cmd.Parameters.Add("@date2", SqlDbType.DateTime, 30, "IssueDate").Value = dtpDateTo.Value.Date; rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataGridView1.Rows.Clear(); while (rdr.Read() == true) { DataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7], rdr[8], rdr[9], rdr[10], rdr[11], rdr[12], rdr[13]); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnduedate_Click(object sender, EventArgs e) { try { con = new SqlConnection(cs.DBcon); con.Open(); cmd = new SqlCommand("SELECT Rtrim(BookIssue_Student.ID),BookIssue_Student.IssueDate,BookIssue_Student.DueDate,Rtrim(BookIssue_Student.AccessionNo),Rtrim(Book.BookTitle),Rtrim(Book.Author),Rtrim(Book.JointAuthors),Rtrim(BookIssue_Student.AdmissionNo),Rtrim(Student.StudentName),Rtrim(School.SchoolName),Rtrim(Class.ClassName),Rtrim(Section.SectionName),Rtrim(BookIssue_Student.Status),Rtrim(BookIssue_Student.Remarks) FROM BookIssue_Student INNER JOIN Book ON BookIssue_Student.AccessionNo = Book.AccessionNo INNER JOIN Student ON BookIssue_Student.AdmissionNo = Student.AdmissionNo INNER JOIN ClassSection ON Student.ClassSection_ID = ClassSection.ClassSectionID INNER JOIN Class ON ClassSection.Class_ID = Class.ClassID INNER JOIN Section ON ClassSection.Section_ID = Section.SectionID INNER JOIN School ON Student.School_ID = School.SchoolID Where DueDate Between @date1 and @Date2 Order by DueDate", con); cmd.Parameters.Add("@date1", SqlDbType.DateTime, 30, "DueDate").Value = txtFrom.Value.Date; cmd.Parameters.Add("@date2", SqlDbType.DateTime, 30, "DueDate").Value = txtTo.Value.Date; rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); DataGridView1.Rows.Clear(); while (rdr.Read() == true) { DataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5], rdr[6], rdr[7], rdr[8], rdr[9], rdr[10], rdr[11], rdr[12], rdr[13]); } con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void DataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (lblSET.Text == "R1") { } } private void DataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { string strRowNumber = (e.RowIndex + 1).ToString(); SizeF size = e.Graphics.MeasureString(strRowNumber, this.Font); if (DataGridView1.RowHeadersWidth < Convert.ToInt32((size.Width + 20))) { DataGridView1.RowHeadersWidth = Convert.ToInt32((size.Width + 20)); } Brush b = SystemBrushes.ButtonHighlight; e.Graphics.DrawString(strRowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2)); } private void dtpDateTo_Validating(object sender, CancelEventArgs e) { if ((dtpDateFrom.Value.Date) > (dtpDateTo.Value.Date)) { MessageBox.Show("Invalid Selection", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); dtpDateTo.Focus(); } } private void txtTo_Validating(object sender, CancelEventArgs e) { if ((txtFrom.Value.Date) > (txtTo.Value.Date)) { MessageBox.Show("Invalid Selection", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error); txtTo.Focus(); } } private void button4_Click(object sender, EventArgs e) { Reset(); } private void button10_Click(object sender, EventArgs e) { if (DataGridView1.Rows.Count == 0) { MessageBox.Show("Please add data in datagrid", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } int rowsTotal = 0; int colsTotal = 0; int I = 0; int j = 0; int iC = 0; System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; Excel.Application xlApp = new Excel.Application(); try { Excel.Workbook excelBook = xlApp.Workbooks.Add(); Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelBook.Worksheets[1]; xlApp.Visible = true; rowsTotal = DataGridView1.RowCount; colsTotal = DataGridView1.Columns.Count - 1; var _with1 = excelWorksheet; _with1.Cells.Select(); _with1.Cells.Delete(); for (iC = 0; iC <= colsTotal; iC++) { _with1.Cells[1, iC + 1].Value = DataGridView1.Columns[iC].HeaderText; } for (I = 0; I <= rowsTotal - 1; I++) { for (j = 0; j <= colsTotal; j++) { _with1.Cells[I + 2, j + 1].value = DataGridView1.Rows[I].Cells[j].Value; } } _with1.Rows["1:1"].Font.FontStyle = "Bold"; _with1.Rows["1:1"].Font.Size = 12; _with1.Cells.Columns.AutoFit(); _with1.Cells.Select(); _with1.Cells.EntireColumn.AutoFit(); _with1.Cells[1, 1].Select(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; xlApp = null; } } } }
59.286689
959
0.623913
[ "MIT" ]
maziesmith/Library-Management-System-c-
Library PRO Software/frmBookIssueListStudent.cs
17,373
C#
namespace Assets.Script { public class RightScreenTrigger : ScreenTrigger, IBulletRecycle { } }
16.714286
67
0.65812
[ "MIT" ]
tboogh/T-Type
Assets/Script/RightScreenTrigger.cs
119
C#