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 |
|---|---|---|---|---|---|---|---|---|
// ***********************************************************************
// Assembly : FenrirFS
// Component : FSFileSystemEntry.cs
// Author : vonderborch
// Created : 07-13-2016
//
// Version : 2.0.0
// Last Modified By : vonderborch
// Last Modified On : 09-24-2016
// ***********************************************************************
// <copyright file="FSFileSystemEntry.cs">
// Copyright © 2016
// </copyright>
// <summary>
// Defines the abstract FSFileSystemEntry class.
// </summary>
//
// Changelog:
// - 2.0.0 (09-24-2016) - Beta version.
// ***********************************************************************
using FenrirFS.Helpers;
using System;
using System.Threading;
using System.Threading.Tasks;
using IO = System.IO;
namespace FenrirFS
{
/// <summary>
/// An abstract representation of a File System Entry.
/// </summary>
public abstract class FSFileSystemEntry
{
#region Public Properties
/// <summary>
/// Gets the creation time.
/// </summary>
/// <value>The creation time.</value>
public DateTime CreationTime
{
get { return GetCreationTime(false); }
}
/// <summary>
/// Gets the UTC creation time.
/// </summary>
/// <value>The UTC creation time.</value>
public DateTime CreationTimeUtc
{
get { return GetCreationTime(true); }
}
/// <summary>
/// Gets a value indicating whether the entry exists or not.
/// </summary>
/// <value><c>true</c> if [entry exists]; otherwise, <c>false</c>.</value>
public abstract bool Exists { get; }
/// <summary>
/// Gets the type of the file system entry.
/// </summary>
/// <value>The type of the file system entry.</value>
public FileSystemEntryType FileSystemEntryType { get; protected set; }
/// <summary>
/// Gets the full path of the entry.
/// </summary>
/// <value>The full path.</value>
public abstract string FullPath { get; protected set; }
/// <summary>
/// Gets the last accessed time.
/// </summary>
/// <value>The last accessed time.</value>
public DateTime LastAccessedTime
{
get { return GetLastAccessedTime(false); }
}
/// <summary>
/// Gets the UTC last accessed time.
/// </summary>
/// <value>The UTC last accessed time.</value>
public DateTime LastAccessedTimeUtc
{
get { return GetLastAccessedTime(true); }
}
/// <summary>
/// Gets the last modified time.
/// </summary>
/// <value>The last modified time.</value>
public DateTime LastModifiedTime
{
get { return GetLastModifiedTime(false); }
}
/// <summary>
/// Gets the UTC last modified time.
/// </summary>
/// <value>The UTC last modified time.</value>
public DateTime LastModifiedTimeUtc
{
get { return GetLastModifiedTime(true); }
}
/// <summary>
/// Gets the name of the entry.
/// </summary>
/// <value>The name.</value>
public string Name { get; protected set; }
/// <summary>
/// Gets the parent folder of the entry.
/// </summary>
/// <value>The parent folder.</value>
public FSDirectory ParentFolder
{
get { return FS.GetDirectory(IO.Path.GetDirectoryName(Path)); }
}
/// <summary>
/// Gets the parent folder path of the entry.
/// </summary>
/// <value>The parent folder path.</value>
public string ParentFolderPath
{
get { return IO.Path.GetDirectoryName(Path); }
}
/// <summary>
/// Gets the path of the entry.
/// </summary>
/// <value>The path.</value>
public string Path { get; protected set; }
/// <summary>
/// Gets the root folder of the entry.
/// </summary>
/// <value>The root folder.</value>
public FSDirectory RootFolder
{
get { return FS.GetDirectory(IO.Path.GetPathRoot(Path)); }
}
/// <summary>
/// Gets the root folder path of the entry.
/// </summary>
/// <value>The root folder path.</value>
public string RootFolderPath
{
get { return IO.Path.GetPathRoot(Path); }
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Performs an implicit conversion from <see cref="FSFile"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="file">The item.</param>
/// <returns>The result of the conversion.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public static implicit operator string(FSFileSystemEntry item)
{
return item.FullPath;
}
/// <summary>
/// Asynchronously gets the creation time.
/// </summary>
/// <param name="useUtc">if set to <c>true</c> [use UTC].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The creation time.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public async Task<DateTime> AsyncGetCreationTime(bool useUtc = false, CancellationToken? cancellationToken = null)
{
await Tasks.ScheduleTask(cancellationToken);
return GetCreationTime(useUtc);
}
/// <summary>
/// Asynchronously gets the last accessed time.
/// </summary>
/// <param name="useUtc">if set to <c>true</c> [use UTC].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The last accessed time.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public async Task<DateTime> AsyncGetLastAccessedTime(bool useUtc = false, CancellationToken? cancellationToken = null)
{
await Tasks.ScheduleTask(cancellationToken);
return GetLastAccessedTime(useUtc);
}
/// <summary>
/// Asynchronously gets the last modified time.
/// </summary>
/// <param name="useUtc">if set to <c>true</c> [use UTC].</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The last modified time.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public async Task<DateTime> AsyncGetLastModifiedTime(bool useUtc = false, CancellationToken? cancellationToken = null)
{
await Tasks.ScheduleTask(cancellationToken);
return GetLastModifiedTime(useUtc);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public override bool Equals(object obj)
{
return obj != null
? FullPath == obj.ToString()
: false;
}
/// <summary>
/// Gets the creation time.
/// </summary>
/// <param name="useUtc">if set to <c>true</c> [use UTC].</param>
/// <returns>The creation time.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public abstract DateTime GetCreationTime(bool useUtc = false);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public override int GetHashCode()
{
return FullPath.GetHashCode();
}
/// <summary>
/// Gets the last accessed time.
/// </summary>
/// <param name="useUtc">if set to <c>true</c> [use UTC].</param>
/// <returns>The last accessed time.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public abstract DateTime GetLastAccessedTime(bool useUtc = false);
/// <summary>
/// Gets the last modified time.
/// </summary>
/// <param name="useUtc">if set to <c>true</c> [use UTC].</param>
/// <returns>The last modified time.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public abstract DateTime GetLastModifiedTime(bool useUtc = false);
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
/// Changelog:
/// - 2.0.0 (09-24-2016) - Beta Version.
public override string ToString()
{
return FullPath;
}
#endregion Public Methods
}
} | 34.713262 | 140 | 0.527414 | [
"MIT"
] | vonderborch/FenrirFS | Core/FileSystem/FSFileSystemEntry.cs | 9,688 | C# |
using UnityEngine;
using Verse;
namespace ZenGarden;
[StaticConstructorOnStartup]
public static class Static
{
public static Texture2D texHarvestSecondary =
ContentFinder<Texture2D>.Get("Cupro/UI/Designations/HarvestSecondary");
public static DesignationDef DesignationHarvestSecondary =
DefDatabase<DesignationDef>.GetNamed("ZEN_Designator_PlantsHarvestSecondary");
public static string LabelOrchardZone = "ZEN_OrchardZone".Translate();
public static string LabelHarvestSecondary = "ZEN_DesignatorHarvestSecondary".Translate();
public static string DescriptionHarvestSecondary = "ZEN_DesignatorHarvestSecondaryDesc".Translate();
public static string ReportDesignatePlantsWithSecondary = "ZEN_MustDesignatePlantsWithSecondary".Translate();
public static string ReportDesignateHarvestableSecondary = "ZEN_MustDesignateHarvestableSecondary".Translate();
public static string ReportBadSeason = "ZEN_CannotGrowBadSeason".Translate();
public static string DisplayStat_LimitedGrowSeasons = "ZEN_DisplayStat_LimitedGrowSeasons".Translate();
public static string DisplayStat_GrowsInAllSeasons = "ZEN_DisplayStat_GrowsInAllSeasons".Translate();
public static string DisplayStat_MinPlantGrowth = "ZEN_DisplayStat_MinPlantGrowth".Translate();
public static string DisplayStat_MinGrowthReport = "ZEN_DisplayStat_MinGrowthReport".Translate();
} | 56 | 115 | 0.820714 | [
"CC0-1.0"
] | emipa606/ZenGarden | Source/ZenGarden/Static/Static.cs | 1,402 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Argo
{
public class MonitorService : BackgroundService
{
private ILogger<MonitorService> _logger;
private ServerOptions _options;
private IServerMonitor _serverMonitor;
protected IServiceProvider ServiceProvider { get; }
public MonitorService(IServiceProvider serviceProvider,
IOptions<ServerOptions> options,
IServerMonitor serverMonitor,
ILogger<MonitorService> logger)
{
ServiceProvider = serviceProvider;
_logger = logger;
_options = options.Value;
_serverMonitor = serverMonitor;
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
await base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested
&& _options.InvalidSessionRelease
&& _serverMonitor != null)
{
await _serverMonitor.Execute().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(_options.MonitorInterval), stoppingToken);
}
}
}
}
| 31.462963 | 96 | 0.664509 | [
"MIT"
] | delaco/Argo | src/Argo/MonitorService.cs | 1,701 | C# |
using System;
using System.IO;
using System.Text;
using DeconTools.Backend.Core;
using DeconTools.Backend.FileIO;
using DeconTools.Backend.Runs;
using DeconTools.Workflows.Backend.Core;
using DeconTools.Workflows.Backend.FileIO;
using DeconTools.Workflows.Backend.Results;
using NUnit.Framework;
namespace DeconTools.Workflows.UnitTesting
{
[TestFixture]
public class AlignmentResults_Tests
{
private Run run;
private NETAndMassAligner aligner;
[OneTimeSetUp]
public void setupTests()
{
var rf = new RunFactory();
run = rf.CreateRun(DeconTools.UnitTesting2.FileRefs.RawDataMSFiles.OrbitrapStdFile1);
var deconToolsResultFile = Path.Combine(FileRefs.ImportedData, "QC_Shew_08_04-pt5-2_11Jan09_Sphinx_08-11-18_targetedFeatures.txt");
var importer = new UnlabeledTargetedResultFromTextImporter(deconToolsResultFile);
var repo = importer.Import();
var massTagFile = @"\\protoapps\UserData\Slysz\Data\MassTags\qcshew_standard_file_allMassTags.txt";
var mtc = new TargetCollection();
var mtimporter = new MassTagFromTextFileImporter(massTagFile);
mtc = mtimporter.Import();
aligner = new NETAndMassAligner();
aligner.SetFeaturesToBeAligned(repo.Results);
aligner.SetReferenceMassTags(mtc.TargetList);
aligner.Execute(run);
}
[Test]
public void outputAlignmentHeatmapData_Test1()
{
var sb=new StringBuilder();
foreach (var scan in aligner.Result.ScanLCValues)
{
sb.Append(scan);
sb.Append("\t");
}
sb.Append(Environment.NewLine);
foreach (var netval in aligner.Result.NETValues)
{
sb.Append(netval);
sb.Append(Environment.NewLine);
}
sb.Append(Environment.NewLine);
Console.WriteLine(sb.ToString());
Console.WriteLine(displayHeatMapData(aligner.Result));
}
[Test]
public void outputMassErrorData()
{
var sb = new StringBuilder();
sb.Append("scan\tbefore\tafter");
for (var i = 0; i < aligner.Result.Mass_vs_scan_ResidualsBeforeAlignment.Length; i++)
{
sb.Append(aligner.Result.Mass_vs_scan_ResidualsScanValues[i]);
sb.Append("\t");
sb.Append(aligner.Result.Mass_vs_scan_ResidualsBeforeAlignment[i]);
sb.Append("\t");
sb.Append(aligner.Result.Mass_vs_scan_ResidualsAfterAlignment[i]);
sb.Append(Environment.NewLine);
}
Console.WriteLine(sb.ToString());
}
[Test]
public void outputMass_vs_MZResidualsData()
{
var sb = new StringBuilder();
sb.Append("scan\tbefore\tafter");
sb.Append(Environment.NewLine);
for (var i = 0; i < aligner.Result.Mass_vs_mz_ResidualsMZValues.Length; i++)
{
sb.Append(aligner.Result.Mass_vs_mz_ResidualsMZValues[i]);
sb.Append("\t");
sb.Append(aligner.Result.Mass_vs_mz_ResidualsBeforeAlignment[i]);
sb.Append("\t");
sb.Append(aligner.Result.Mass_vs_mz_ResidualsAfterAlignment[i]);
sb.Append(Environment.NewLine);
}
Console.WriteLine(sb.ToString());
}
[Test]
public void getStatsOnVariablity()
{
Console.WriteLine("MassMean = " + aligner.Result.MassAverage + " +/- " + aligner.Result.MassStDev);
Console.WriteLine("NETMean = " + aligner.Result.NETAverage + " +/- " + aligner.Result.NETStDev);
}
[Test]
public void getMassErrorHistogramTest1()
{
var sb = new StringBuilder();
for (var i = 0; i < aligner.Result.massHistogramData.GetLength(0); i++)
{
for (var k = 0; k < aligner.Result.massHistogramData.GetLength(1); k++)
{
sb.Append(aligner.Result.massHistogramData[i,k]);
sb.Append("\t");
}
sb.Append(Environment.NewLine);
}
Console.WriteLine("MassErrorHistogramData:");
Console.WriteLine(sb.ToString());
}
[Test]
public void getNETErrorHistogramTest1()
{
var sb = new StringBuilder();
for (var i = 0; i < aligner.Result.NETHistogramData.GetLength(0); i++)
{
for (var k = 0; k < aligner.Result.NETHistogramData.GetLength(1); k++)
{
sb.Append(aligner.Result.NETHistogramData[i, k]);
sb.Append("\t");
}
sb.Append(Environment.NewLine);
}
Console.WriteLine("NET_ErrorHistogramData:");
Console.WriteLine(sb.ToString());
}
private string displayHeatMapData(AlignmentResult alignmentResult)
{
var sb = new StringBuilder();
for (var i = alignmentResult.AlignmentHeatmapScores.GetLength(1)-1; i >=0 ; i--)
{
for (var k = 0; k < alignmentResult.AlignmentHeatmapScores.GetLength(0); k++)
{
sb.Append(alignmentResult.AlignmentHeatmapScores[k, i]);
sb.Append("\t");
}
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
}
}
| 30.789744 | 144 | 0.532645 | [
"Apache-2.0"
] | PNNL-Comp-Mass-Spec/DeconTools | DeconTools.Workflows/DeconTools.Workflows.UnitTesting/AlignmentTests/AlignmentResults_Tests.cs | 6,006 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.ComponentModel.Design;
using System.Windows.Forms;
using Be.Windows.Forms;
namespace ShandalarImageToolbox
{
public partial class HexEditor : UserControl
{
FindOptions _findOptions = new FindOptions();
ByteViewer ByteViewer;
public HexEditor()
{
InitializeComponent();
ByteViewer = new ByteViewer();
ByteViewer.Dock = DockStyle.Fill;
stPanel1.Controls.Add(ByteViewer);
}
public void OnControlClosing()
{
Cleanup();
ByteViewer.Dispose();
}
private void Cleanup()
{
}
public void LoadData(byte[] data)
{
Cleanup();
ByteViewer.SetBytes(data);
}
private void findToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
}
| 19.666667 | 76 | 0.585687 | [
"MIT"
] | CelestialAmber/MtgShandalarImageDecoder | ShandalarImageToolbox/Custom Forms/HexEditor/HexEditorNew.cs | 1,064 | C# |
using System;
using TreeGecko.Library.Common.Attributes;
using TreeGecko.Library.Common.Helpers;
using TreeGecko.Library.Common.Interfaces;
namespace TreeGecko.Library.Common.Objects
{
public abstract class AbstractTGObject : ITGSerializable, IActive
{
protected AbstractTGObject()
{
Guid = Guid.NewGuid();
Active = true;
LastModifiedDateTime = DateTime.UtcNow;
}
/// <summary>
///
/// </summary>
[InternalTGObjectGuid]
public Guid Guid { get; set; }
/// <summary>
///
/// </summary>
public Guid VersionGuid { get; set; }
/// <summary>
///
/// </summary>
public string VersionTimeStamp { get; set; }
/// <summary>
///
/// </summary>
public bool Active { get; set; }
/// <summary>
/// Gets or sets the last modified date time.
/// </summary>
/// <value>
/// The last modified date time.
/// </value>
public DateTime LastModifiedDateTime { get; set; }
/// <summary>
///
/// </summary>
public Guid? LastModifiedBy { get; set; }
/// <summary>
/// Gets or sets the parent GUID.
/// </summary>
/// <value>
/// The parent GUID.
/// </value>
public Guid? ParentGuid { get; set; }
/// <summary>
///
/// </summary>
public DateTime PersistedDateTime { get; set; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual TGSerializedObject GetTGSerializedObject()
{
TGSerializedObject obj = new TGSerializedObject
{
TGObjectType = TGObjectType
};
obj.Add("Guid", Guid);
obj.Add("Active", Active);
obj.Add("LastModifiedBy", LastModifiedBy);
obj.Add("LastModifiedDateTime", LastModifiedDateTime);
obj.Add("VersionTimeStamp", VersionTimeStamp);
obj.Add("ParentGuid", ParentGuid);
obj.Add("VersionGuid", VersionGuid);
obj.Add("PersistedDateTime", PersistedDateTime);
return obj;
}
/// <summary>
///
/// </summary>
/// <param name="_tg"></param>
public virtual void LoadFromTGSerializedObject(TGSerializedObject _tg)
{
Guid = _tg.GetGuid("Guid");
if (Guid == Guid.Empty)
{
Guid = Guid.NewGuid();
}
Active = _tg.GetBoolean("Active");
LastModifiedDateTime = _tg.GetDateTime("LastModifiedDateTime");
LastModifiedBy = _tg.GetNullableGuid("LastModifiedBy");
string versionTimeStamp = _tg.GetString("VersionTimeStamp");
if (VersionTimeStamp == null)
{
VersionTimeStamp = DateHelper.GetCurrentTimeStamp();
}
else
{
VersionTimeStamp = versionTimeStamp;
}
ParentGuid = _tg.GetNullableGuid("ParentGuid");
VersionGuid = _tg.GetGuid("VersionGuid");
PersistedDateTime = _tg.GetDateTime("PersistedDateTime");
}
/// <summary>
///
/// </summary>
/// <param name="_bcnSerializedString"></param>
public void LoadFromTGSerializedString(string _bcnSerializedString)
{
TGSerializedObject tgSerializedObject = new TGSerializedObject(_bcnSerializedString);
LoadFromTGSerializedObject(tgSerializedObject);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
TGSerializedObject obj = GetTGSerializedObject();
return obj.ToString();
}
public virtual string TGObjectType
{
get { return ReflectionHelper.GetTypeName(GetType()); }
}
}
} | 28.172414 | 97 | 0.522889 | [
"MIT"
] | TreeGecko/Libraries | src/tgCommonLibrary/Objects/AbstractTGObject.cs | 4,087 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FuckQustodio
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 23.173913 | 66 | 0.587242 | [
"MIT"
] | jack-debug/FuckQustodio | Program.cs | 535 | C# |
using System.Collections.Generic;
using Eto.Forms;
namespace ArbitesEto2
{
public partial class FmMacroEdit
{
public List<UCMacroButton> Buttons { get; set; }
public MacroData Data { get; set; }
public bool SaveOutput { get; set; }
public FmMacroEdit()
{
InitializeComponent();
this.Icon = MdSessionData.WindowIcon;
this.Buttons = new List<UCMacroButton>();
this.Data = new MacroData();
this.SaveOutput = false;
for (var i = 0; i < 8; i++)
{
var btn = new UCMacroButton();
btn.KeyIndex = i;
this.Buttons.Add(btn);
var tc = new TableCell();
tc.Control = btn;
btn.Visible = false;
this.TRStack.Cells.Add(tc);
btn.LeftClick += (sender, e) => KeyLeft(sender);
btn.RightClick += (sender, e) => KeyRight(sender);
btn.DeleteClick += (sender, e) => KeyDelete(sender);
btn.ValueChanged += (sender, e) => KeyUpdate(sender);
btn.IsDownChanged += (sender, e) => KeyIsDownChanged(sender);
}
this.TRStack.Cells.Add(null);
EventHook();
RefreshStack();
}
public FmMacroEdit(MacroData data) : this()
{
this.Data = new MacroData(data);
RefreshStack();
}
private void EventHook()
{
this.BtnAddKey.Click += (sender, e) => AddKey();
this.BtnOK.Click += (sender, e) => Save();
this.BtnCancel.Click += (sender, e) => Cancel();
Closing += (sender, e) => IsClosing();
}
private void IsClosing()
{
MdSessionData.OpenedMacroEdit = false;
}
private void Save()
{
this.SaveOutput = true;
var lay = MdSessionData.CurrentLayout;
var dataCont = new MacroDataContainer();
var hasData = false;
foreach (var ele in lay.AddonDatas)
{
if (ele.GetType() == MacroDataContainer.DATA_TYPE)
{
hasData = true;
dataCont = ele as MacroDataContainer;
}
}
if (!hasData)
{
lay.AddonDatas.Add(dataCont);
}
var data = this.Data;
hasData = false;
var oldDataIndex = 0;
if (dataCont != null)
{
foreach (var ele in dataCont.MacroKeys)
{
if (ele.Index == this.Data.Index)
{
hasData = true;
break;
}
oldDataIndex++;
}
if (hasData)
{
dataCont.MacroKeys[oldDataIndex] = data;
}
else
{
dataCont.MacroKeys.Add(data);
}
}
MdSessionData.CurrentKeyboardUI.DisplayUnsavedChangeSignal();
Close();
}
private void Cancel()
{
Close();
}
private void KeyLeft(object sender)
{
var btn = sender as UCMacroButton;
if (btn != null)
{
var index = btn.KeyIndex;
if (index > 0)
{
var ele = this.Data.Keys[index];
var bele = this.Data.IsKeyDown[index];
this.Data.Keys.RemoveAt(index);
this.Data.IsKeyDown.RemoveAt(index);
this.Data.Keys.Insert(index - 1, ele);
this.Data.IsKeyDown.Insert(index - 1, bele);
RefreshStack();
}
else
{
MessageBox.Show("Error: Already leftmost key.");
}
}
}
private void KeyRight(object sender)
{
var btn = sender as UCMacroButton;
if (btn != null)
{
var index = btn.KeyIndex;
if (index < this.Data.Keys.Count - 1)
{
var ele = this.Data.Keys[index];
var bele = this.Data.IsKeyDown[index];
this.Data.Keys.RemoveAt(index);
this.Data.IsKeyDown.RemoveAt(index);
this.Data.Keys.Insert(index + 1, ele);
this.Data.IsKeyDown.Insert(index + 1, bele);
RefreshStack();
}
else
{
MessageBox.Show("Error: Already rightmost key.");
}
}
}
private void KeyDelete(object sender)
{
var btn = sender as UCMacroButton;
if (btn != null)
{
var index = btn.KeyIndex;
this.Data.Keys.RemoveAt(index);
this.Data.IsKeyDown.RemoveAt(index);
}
RefreshStack();
}
private void KeyUpdate(object sender)
{
var btn = sender as UCMacroButton;
if (btn != null)
{
var index = btn.KeyIndex;
this.Data.Keys[index] = new Key(btn.Key);
}
}
private void KeyIsDownChanged(object sender)
{
var btn = sender as UCMacroButton;
if (btn != null)
{
var index = btn.KeyIndex;
this.Data.IsKeyDown[index] = btn.IsDown;
}
}
private void AddKey()
{
if (this.Data.Keys.Count < 8)
{
this.Data.Keys.Add(new Key());
this.Data.IsKeyDown.Add(true);
RefreshStack();
}
else
{
MessageBox.Show("Error: Maximum number of keys reached");
}
}
private void RefreshStack()
{
for (var i = 0; i < 8; i++)
{
if (i < this.Data.Keys.Count)
{
this.Buttons[i].Key = new Key(this.Data.Keys[i]);
this.Buttons[i].IsDown = this.Data.IsKeyDown[i];
this.Buttons[i].ReloadUI();
this.Buttons[i].Visible = true;
}
else
{
this.Buttons[i].Visible = false;
}
}
this.LTip.Text = "Currently editing macro key \"macro" + this.Data.Index + "\"";
this.LKeyAmount.Text = "Capacity: " + this.Data.Keys.Count + " out of 8 keys.";
}
}
}
| 28.510288 | 92 | 0.42653 | [
"BSD-3-Clause"
] | blahlicus/arbites-family | ArbitesEto2/ArbitesEto2/Forms/FmMacroEdit.cs | 6,930 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics.ContractsLight;
using System.Linq;
using BuildXL.Cache.ContentStore.Interfaces.Results;
using Microsoft.Azure.Management.Redis.Fluent;
namespace BuildXL.Cache.Monitor.App.Rules.Autoscaling
{
public class RedisClusterSize : IEquatable<RedisClusterSize>
{
public static IReadOnlyList<RedisClusterSize> Instances =
RedisTier.Instances.SelectMany(tier => Enumerable
.Range(1, 10)
.Select(shards => new RedisClusterSize(tier, shards))).ToList();
public RedisTier Tier { get; }
/// <summary>
/// From 1 through 10
/// </summary>
public int Shards { get; }
public int ClusterMemorySizeMb => Tier.Properties.MemorySizeMb * Shards;
public double MonthlyCostUsd => Tier.Properties.MonthlyCostPerShardUsd * Shards;
public int? AvailableBandwidthMb => Tier.Properties.AvailableBandwidthMb * Shards;
public int? EstimatedRequestsPerSecond => Tier.Properties.EstimatedRequestsPerSecond * Shards;
private readonly Lazy<IReadOnlyList<RedisClusterSize>> _scaleEligibleSizes;
public IReadOnlyList<RedisClusterSize> ScaleEligibleSizes => _scaleEligibleSizes.Value;
public RedisClusterSize(RedisTier tier, int shards)
{
Contract.Requires(1 <= shards && shards <= 10, "Number of shards out of bounds, must be between 1 and 10");
Tier = tier;
Shards = shards;
_scaleEligibleSizes = new Lazy<IReadOnlyList<RedisClusterSize>>(() => Instances.Where(to => RedisScalingUtilities.CanScale(this, to)).ToList(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
}
public static RedisClusterSize Parse(string clusterSize)
{
return RedisClusterSize.TryParse(clusterSize).ThrowIfFailure();
}
public static Result<RedisClusterSize> TryParse(string clusterSize)
{
if (string.IsNullOrEmpty(clusterSize))
{
return new Result<RedisClusterSize>(errorMessage: $"Empty string can't be parsed into {nameof(RedisClusterSize)}");
}
var parts = clusterSize.Split(new string[] { "/" }, StringSplitOptions.None);
if (parts.Length != 2)
{
return new Result<RedisClusterSize>(errorMessage: $"Failed to split {nameof(RedisClusterSize)} from `{clusterSize}`: {string.Join(", ", parts)}");
}
var redisTierResult = RedisTier.TryParse(parts[0]);
if (!redisTierResult.Succeeded)
{
return new Result<RedisClusterSize>(redisTierResult);
}
var redisTier = redisTierResult.Value;
Contract.AssertNotNull(redisTier);
if (!int.TryParse(parts[1], out var shards)) {
return new Result<RedisClusterSize>(errorMessage: $"Failed to obtain number of shards from `{parts[1]}`");
}
return new RedisClusterSize(redisTier, shards);
}
public static Result<RedisClusterSize> FromAzureCache(IRedisCache redisCache)
{
var sku = redisCache.Sku;
if (!Enum.TryParse<RedisPlan>(sku.Name, out var plan))
{
return new Result<RedisClusterSize>(errorMessage: $"Failed to parse `{nameof(RedisPlan)}` from value `{sku.Name}`");
}
try
{
return new RedisClusterSize(new RedisTier(plan, sku.Capacity), redisCache.ShardCount);
}
catch (Exception exception)
{
return new Result<RedisClusterSize>(exception);
}
}
public override string ToString() => $"{Tier}/{Shards}";
public override bool Equals(object? obj)
{
return obj is RedisClusterSize item && Equals(item);
}
public bool Equals(RedisClusterSize? redisClusterSize)
{
return redisClusterSize != null && Tier.Equals(redisClusterSize.Tier) && Shards == redisClusterSize.Shards;
}
public override int GetHashCode() => (Tier.GetHashCode(), Shards).GetHashCode();
}
}
| 38.626087 | 212 | 0.612337 | [
"MIT"
] | RobJellinghaus/BuildXL | Public/Src/Cache/Monitor/Library/Rules/Autoscaling/RedisClusterSize.cs | 4,444 | C# |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Security.AccessControl;
using System.Security.Principal;
namespace Alphaleonis.Win32.Filesystem
{
partial class Directory
{
/// <summary>[AlphaFS] Check if the directory has permission inheritance enabled.</summary>
/// <returns><see langword="true"/> if permission inheritance is enabled, <see langword="false"/> if permission inheritance is disabled.</returns>
/// <param name="path">The full path to the directory to check.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
public static bool HasInheritedPermissions(string path, PathFormat pathFormat)
{
if (Utils.IsNullOrWhiteSpace(path))
throw new ArgumentNullException("path");
var acl = File.GetAccessControlCore<DirectorySecurity>(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat);
return acl.GetAccessRules(false, true, typeof(SecurityIdentifier)).Count > 0;
}
/// <summary>[AlphaFS] Check if the directory has permission inheritance enabled.</summary>
/// <param name="path">The full path to the directory to check.</param>
/// <returns><see langword="true"/> if permission inheritance is enabled, <see langword="false"/> if permission inheritance is disabled.</returns>
public static bool HasInheritedPermissions(string path)
{
if (Utils.IsNullOrWhiteSpace(path))
throw new ArgumentNullException("path");
var acl = File.GetAccessControlCore<DirectorySecurity>(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, PathFormat.RelativePath);
return acl.GetAccessRules(false, true, typeof(SecurityIdentifier)).Count > 0;
}
}
}
| 51.389831 | 191 | 0.726583 | [
"MIT"
] | OpenDataSpace/AlphaFS | AlphaFS/Filesystem/Directory Class/Directory.HasInheritedPermissions.cs | 3,032 | C# |
#pragma checksum "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\Shared\MainLayout.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "da2568bd6639c8d310c2f50cdaa3fbbd27a99a9b"
// <auto-generated/>
#pragma warning disable 1591
namespace Jello.Shared
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Jello;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Jello.Shared;
#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\_Imports.razor"
using Jello.Data;
#line default
#line hidden
#nullable disable
public partial class MainLayout : LayoutComponentBase
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__builder.OpenElement(0, "div");
__builder.AddAttribute(1, "class", "sidebar");
__builder.OpenComponent<Jello.Shared.NavMenu>(2);
__builder.CloseComponent();
__builder.CloseElement();
__builder.AddMarkupContent(3, "\r\n\r\n");
__builder.OpenElement(4, "div");
__builder.AddAttribute(5, "class", "main");
__builder.OpenElement(6, "div");
__builder.AddAttribute(7, "class", "top-row px-4 auth");
__builder.OpenComponent<Jello.Shared.LoginDisplay>(8);
__builder.CloseComponent();
__builder.AddMarkupContent(9, "\r\n ");
__builder.AddMarkupContent(10, "<a href=\"https://docs.microsoft.com/aspnet/\" target=\"_blank\">About</a>");
__builder.CloseElement();
__builder.AddMarkupContent(11, "\r\n\r\n ");
__builder.OpenElement(12, "div");
__builder.AddAttribute(13, "class", "content px-4");
__builder.AddContent(14,
#nullable restore
#line 14 "C:\Users\Admin\Desktop\IIT\L6\EAD\CW2\Jello\Jello\Jello\Shared\MainLayout.razor"
Body
#line default
#line hidden
#nullable disable
);
__builder.CloseElement();
__builder.CloseElement();
}
#pragma warning restore 1998
}
}
#pragma warning restore 1591
| 31.702479 | 182 | 0.712722 | [
"MIT"
] | AyoobAboosalih/Jello | Jello/Jello/obj/Debug/net5.0/Razor/Shared/MainLayout.razor.g.cs | 3,836 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CoreWCF.Channels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace CoreWCF.Configuration
{
internal class ServiceBuilder : CommunicationObject, IServiceBuilder
{
private readonly IDictionary<Type, IServiceConfiguration> _services = new Dictionary<Type, IServiceConfiguration>();
private readonly TaskCompletionSource<object> _openingCompletedTcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
public ServiceBuilder(IServiceProvider serviceProvider, IApplicationLifetime appLifetime)
{
ServiceProvider = serviceProvider;
appLifetime.ApplicationStarted.Register(() =>
{
if (State == CommunicationState.Created)
{
// Using discard as any exceptions are swallowed from the ApplicationStarted
// callback and no place to await the OpenAsync call. Should only hit this code
// when hosting in IIS.
_ = OpenAsync();
}
});
}
public ICollection<IServiceConfiguration> ServiceConfigurations => _services.Values;
public ICollection<Uri> BaseAddresses { get; } = new List<Uri>();
ICollection<Type> IServiceBuilder.Services => _services.Keys;
public IServiceProvider ServiceProvider { get; }
protected override TimeSpan DefaultCloseTimeout => TimeSpan.FromMinutes(1);
protected override TimeSpan DefaultOpenTimeout => TimeSpan.FromMinutes(1);
public IServiceBuilder AddService<TService>() where TService : class
{
return AddService(typeof(TService));
}
public IServiceBuilder AddService(Type service)
{
if (service is null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(service)));
}
var serviceConfig = (IServiceConfiguration)ServiceProvider.GetRequiredService(
typeof(IServiceConfiguration<>).MakeGenericType(service));
_services[serviceConfig.ServiceType] = serviceConfig;
return this;
}
public IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, string address)
{
return AddServiceEndpoint<TService>(typeof(TContract), binding, address);
}
public IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, Uri address)
{
return AddServiceEndpoint<TService>(typeof(TContract), binding, address);
}
public IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, string address, Uri listenUri)
{
return AddServiceEndpoint<TService>(typeof(TContract), binding, address, listenUri);
}
public IServiceBuilder AddServiceEndpoint<TService, TContract>(Binding binding, Uri address, Uri listenUri)
{
return AddServiceEndpoint<TService>(typeof(TContract), binding, address, listenUri);
}
public IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, string address)
{
return AddServiceEndpoint<TService>(implementedContract, binding, address, (Uri)null);
}
public IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, Uri address)
{
return AddServiceEndpoint<TService>(implementedContract, binding, address, (Uri)null);
}
public IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, string address, Uri listenUri)
{
if (address is null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(address)));
}
return AddServiceEndpoint<TService>(implementedContract, binding, new Uri(address, UriKind.RelativeOrAbsolute), listenUri);
}
public IServiceBuilder AddServiceEndpoint<TService>(Type implementedContract, Binding binding, Uri address, Uri listenUri)
{
return AddServiceEndpoint(typeof(TService), implementedContract, binding, address, listenUri);
}
public IServiceBuilder AddServiceEndpoint(Type service, Type implementedContract, Binding binding, Uri address, Uri listenUri)
{
if (service is null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(service)));
}
if (implementedContract is null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(implementedContract)));
}
if (binding is null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(binding)));
}
if (_services.TryGetValue(service, out IServiceConfiguration serviceConfig))
{
serviceConfig.Endpoints.Add(new ServiceEndpointConfiguration()
{
Address = address,
Binding = binding,
Contract = implementedContract,
ListenUri = listenUri
});
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError((new ArgumentException(SR.Format(SR.UnknownServiceConfiguration), nameof(service))));
}
return this;
}
protected override void OnAbort()
{
}
protected override Task OnCloseAsync(CancellationToken token)
{
return Task.CompletedTask;
}
protected override Task OnOpenAsync(CancellationToken token)
{
_openingCompletedTcs.TrySetResult(null);
return Task.CompletedTask;
}
protected override void OnFaulted()
{
base.OnFaulted();
_openingCompletedTcs.TrySetResult(null);
}
// This is to allow the ServiceHostObjectModel to wait until all the Opening event handlers have ran
// to do some configuration such as adding base addresses before the actual service dispatcher is created.
internal Task WaitForOpening()
{
return _openingCompletedTcs.Task;
}
}
}
| 39.651163 | 162 | 0.652786 | [
"MIT"
] | ScriptBox99/CoreWCF | src/CoreWCF.Primitives/src/CoreWCF/Configuration/ServiceBuilder.cs | 6,820 | 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 cloudcontrol-2021-09-30.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.CloudControlApi.Model
{
/// <summary>
/// The resource handler has returned that the request couldn't be completed due to networking
/// issues, such as a failure to receive a response from the server.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class NetworkFailureException : AmazonCloudControlApiException
{
/// <summary>
/// Constructs a new NetworkFailureException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public NetworkFailureException(string message)
: base(message) {}
/// <summary>
/// Construct instance of NetworkFailureException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public NetworkFailureException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of NetworkFailureException
/// </summary>
/// <param name="innerException"></param>
public NetworkFailureException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of NetworkFailureException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NetworkFailureException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of NetworkFailureException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public NetworkFailureException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the NetworkFailureException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected NetworkFailureException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.56 | 178 | 0.681413 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/CloudControlApi/Generated/Model/NetworkFailureException.cs | 5,945 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("HotChocolate.AspNetCore.Tests")]
| 26 | 63 | 0.836538 | [
"MIT"
] | Ciantic/hotchocolate | src/HotChocolate/AspNetCore/src/AspNetCore/Properties/InternalsVisibleTo.cs | 104 | C# |
using System;
using System.Collections.Specialized;
using System.Net.Http;
using System.Net.WebSockets;
using System.Threading.Tasks;
using GraphQL.Client.Http;
using Speckle.Core.Api.GraphQL.Serializer;
using Speckle.Core.Credentials;
using Speckle.Core.Logging;
using Speckle.Newtonsoft.Json;
namespace Speckle.Core.Api
{
public partial class Client : IDisposable
{
public string ServerUrl { get => Account.serverInfo.url; }
public string ApiToken { get => Account.token; }
[JsonIgnore]
public Account Account { get; set; }
HttpClient HttpClient { get; set; }
public GraphQLHttpClient GQLClient { get; set; }
public object UploadValues(string v1, string v2, NameValueCollection user_1)
{
throw new NotImplementedException();
}
public Client() { }
public Client(Account account)
{
if (account == null)
throw new SpeckleException($"Provided account is null.");
Account = account;
HttpClient = new HttpClient();
if (account.token.ToLowerInvariant().Contains("bearer"))
{
HttpClient.DefaultRequestHeaders.Add("Authorization", account.token);
}
else
{
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {account.token}");
}
GQLClient = new GraphQLHttpClient(
new GraphQLHttpClientOptions
{
EndPoint = new Uri(new Uri(account.serverInfo.url), "/graphql"),
UseWebSocketForQueriesAndMutations = false,
ConfigureWebSocketConnectionInitPayload = (opts) => { return new { Authorization = $"Bearer {account.token}" }; },
OnWebsocketConnected = OnWebSocketConnect,
},
new NewtonsoftJsonSerializer(),
HttpClient);
GQLClient.WebSocketReceiveErrors.Subscribe(e =>
{
if (e is WebSocketException we)
Console.WriteLine($"WebSocketException: {we.Message} (WebSocketError {we.WebSocketErrorCode}, ErrorCode {we.ErrorCode}, NativeErrorCode {we.NativeErrorCode}");
else
Console.WriteLine($"Exception in websocket receive stream: {e.ToString()}");
});
}
public Task OnWebSocketConnect(GraphQLHttpClient client)
{
Console.WriteLine("Websocket is open");
return Task.CompletedTask;
}
public void Dispose()
{
UserStreamAddedSubscription?.Dispose();
UserStreamRemovedSubscription?.Dispose();
StreamUpdatedSubscription?.Dispose();
BranchCreatedSubscription?.Dispose();
BranchUpdatedSubscription?.Dispose();
BranchDeletedSubscription?.Dispose();
CommitCreatedSubscription?.Dispose();
CommitUpdatedSubscription?.Dispose();
CommitDeletedSubscription?.Dispose();
GQLClient?.Dispose();
}
}
}
| 29.43617 | 169 | 0.676545 | [
"Apache-2.0"
] | ENAC-CNPA/speckle-sharp | Core/Core/Api/GraphQL/Client.cs | 2,769 | C# |
using System;
using System.ComponentModel.Composition;
using Formatter;
namespace Logger
{
[Export]
public class ConsoleLogger
{
private FormatterBase formatter;
[ImportingConstructor]
public ConsoleLogger([Import(typeof(FormatterBase))]FormatterBase formatter)
{
this.formatter = formatter;
}
public void Log(string message)
{
string formattedString = this.formatter.Format(message);
Console.WriteLine(formattedString);
}
}
}
| 21.88 | 84 | 0.634369 | [
"BSD-2-Clause"
] | StefanHenneken/Blog-2011-10-MEFPart06-Sample01 | ConsoleLogger/ConsoleLogger.cs | 549 | C# |
using System;
using System.Collections.Generic;
using Telerik.JustDecompiler.Ast;
using Telerik.JustDecompiler.Ast.Expressions;
using Telerik.JustDecompiler.Ast.Statements;
using Telerik.JustDecompiler.Decompiler;
namespace Telerik.JustDecompiler.Steps
{
/// <remarks>
/// Depends on the following previous steps:
/// * ResolveDynamicVariablesStep
/// * VariableInliningPattern
/// * Steps that use Negator (e.g. CreateIfElseIfStatementsStep)
/// </remarks>
class ParenthesizeExpressionsStep : BaseCodeVisitor, IDecompilationStep
{
public BlockStatement Process(DecompilationContext context, BlockStatement body)
{
BlockStatement result = (BlockStatement)new Parenthesizer().Visit(body);
return result;
}
private class Parenthesizer : BaseCodeTransformer
{
public override ICodeNode VisitBinaryExpression(BinaryExpression node)
{
bool shouldAddLeftParentheses = false;
if (node.Left.CodeNodeType == CodeNodeType.BinaryExpression)
{
BinaryExpression leftAsBinary = node.Left as BinaryExpression;
int compared = leftAsBinary.CompareOperators(node);
// (a + b) * c
if (compared > 0)
{
shouldAddLeftParentheses = true;
}
else if (leftAsBinary.IsOverridenOperation)
{
shouldAddLeftParentheses = true;
}
}
if (shouldAddLeftParentheses)
{
node.Left = new ParenthesesExpression(node.Left);
}
bool shouldAddRightParentheses = false;
if (node.Right.CodeNodeType == CodeNodeType.BinaryExpression)
{
BinaryExpression rightAsBinary = node.Right as BinaryExpression;
int compared = rightAsBinary.CompareOperators(node);
// a * (b + c)
if (compared > 0)
{
shouldAddRightParentheses = true;
}
else if (compared == 0)
{
// a * (b / c)
if (node.Operator != rightAsBinary.Operator)
{
shouldAddRightParentheses = true;
}
// a - (b - c)
else if (!IsCommutative(node.Operator))
{
shouldAddRightParentheses = true;
}
// a + (b + c)
else if (rightAsBinary.ExpressionType == rightAsBinary.ExpressionType.Module.TypeSystem.Single ||
rightAsBinary.ExpressionType == rightAsBinary.ExpressionType.Module.TypeSystem.Double)
{
shouldAddRightParentheses = true;
}
}
else if (!node.IsAssignmentExpression && rightAsBinary.IsOverridenOperation)
{
shouldAddRightParentheses = true;
}
}
if (shouldAddRightParentheses)
{
node.Right = new ParenthesesExpression(node.Right);
}
return base.VisitBinaryExpression(node);
}
public override ICodeNode VisitUnaryExpression(UnaryExpression node)
{
if (node.Operator == UnaryOperator.AddressDereference)
{
if (!(node.Operand.CodeNodeType == CodeNodeType.VariableReferenceExpression ||
node.Operand.CodeNodeType == CodeNodeType.ArgumentReferenceExpression ||
node.Operand.CodeNodeType == CodeNodeType.ExplicitCastExpression))
{
node.Operand = new ParenthesesExpression(node.Operand);
}
}
else if (node.Operator != UnaryOperator.None)
{
if (node.Operand.CodeNodeType == CodeNodeType.BinaryExpression)
{
node.Operand = new ParenthesesExpression(node.Operand);
}
}
return base.VisitUnaryExpression(node);
}
private bool IsCommutative(BinaryOperator @operator)
{
return @operator == BinaryOperator.Add ||
@operator == BinaryOperator.BitwiseAnd ||
@operator == BinaryOperator.BitwiseOr ||
@operator == BinaryOperator.BitwiseXor ||
@operator == BinaryOperator.LogicalAnd ||
@operator == BinaryOperator.LogicalOr ||
@operator == BinaryOperator.Multiply ||
@operator == BinaryOperator.ValueEquality ||
@operator == BinaryOperator.ValueInequality ||
@operator == BinaryOperator.Assign;
}
}
}
}
| 31.1 | 104 | 0.659411 | [
"ECL-2.0",
"Apache-2.0"
] | Bebere/JustDecompileEngine | Cecil.Decompiler/Steps/ParenthesizeExpressionsStep.cs | 4,045 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace TodoApi.Identity;
public interface IRoleManagerWrapper
{
/// <summary>
/// Create the target role.
/// </summary>
/// <param name="role">The target role.</param>
/// <returns>IdentityResult.</returns>
Task<IdentityResult> CreateAsync(string role);
/// <summary>
/// Check if the role exists already.
/// </summary>
/// <param name="role">The target role.</param>
/// <returns>True if it exists.</returns>
Task<bool> RoleExistsAsync(string role);
} | 27.380952 | 51 | 0.65913 | [
"MIT"
] | charlehsin/net6-webapi-tutorial | TodoApi/Identity/IRoleManagerWrapper.cs | 575 | 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.
// <auto-generated/>
// Template Source: ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type EdgeSearchEngineBase.
/// </summary>
[JsonConverter(typeof(DerivedTypeConverter<EdgeSearchEngineBase>))]
public partial class EdgeSearchEngineBase
{
///<summary>
/// The internal EdgeSearchEngineBase constructor
///</summary>
protected internal EdgeSearchEngineBase()
{
// Don't allow initialization of abstract complex types
}
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>
/// Gets or sets @odata.type.
/// </summary>
[JsonPropertyName("@odata.type")]
public string ODataType { get; set; }
}
}
| 30.956522 | 153 | 0.558989 | [
"MIT"
] | ehtick/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/model/EdgeSearchEngineBase.cs | 1,424 | C# |
namespace xLayout.Animations
{
public class InverseCondition : UICondition
{
public UICondition[] originals;
public override bool IsMet()
{
return !originals[0].IsMet();
}
}
} | 20 | 47 | 0.558333 | [
"MIT"
] | BAndysc/xLayout | Assets/Plugins/xLayout/Animations/Condition/InverseCondition.cs | 240 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class WeaponAction : MonoBehaviour
{
[SerializeField]
protected int code;
protected void Start()
{
gameObject.GetComponent<Weapon>().AddAction(code, this);
}
public abstract void Process();
public void RemoveSelf()
{
Destroy(this);
}
}
| 17.590909 | 64 | 0.671835 | [
"MIT"
] | lannguyen0910/rpg-hero-adventure | src/Assets/scripts/object/weapon/logic/WeaponAction.cs | 387 | C# |
// Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace Hazelcast.Core
{
internal static partial class BytesExtensions // Protocol
{
// use little endian where it makes sense
// for some types (byte, bool...) it just does not make sense
// for some types (guid...) endianness is just not an option
public static void WriteLongL(this byte[] bytes, int position, long value)
=> bytes.WriteLong(position, value, Endianness.LittleEndian);
public static void WriteIntL(this byte[] bytes, int position, int value)
=> bytes.WriteInt(position, value, Endianness.LittleEndian);
public static void WriteIntL(this byte[] bytes, int position, Enum value)
=> bytes.WriteInt(position, (int) (object) value, Endianness.LittleEndian);
public static void WriteBoolL(this byte[] bytes, int position, bool value)
=> bytes.WriteBool(position, value);
public static void WriteGuidL(this byte[] bytes, int position, Guid value)
=> bytes.WriteGuid(position, value);
public static void WriteByteL(this byte[] bytes, int position, byte value)
=> bytes.WriteByte(position, value);
public static long ReadLongL(this byte[] bytes, int position)
=> bytes.ReadLong(position, Endianness.LittleEndian);
public static int ReadIntL(this byte[] bytes, int position)
=> bytes.ReadInt(position, Endianness.LittleEndian);
public static bool ReadBoolL(this byte[] bytes, int position)
=> bytes.ReadBool(position);
public static Guid ReadGuidL(this byte[] bytes, int position)
=> bytes.ReadGuid(position);
public static byte ReadByteL(this byte[] bytes, int position)
=> bytes.ReadByte(position);
private static Guid ReadGuid(this byte[] bytes, int position)
{
// read the 'empty' bool
if (bytes.ReadBool(position)) return Guid.Empty;
// not 'empty', must be able to read a full guid
if (bytes.Length < position + SizeOfGuid)
throw new ArgumentOutOfRangeException(nameof(position));
position += SizeOfByte;
// ReSharper disable once UseObjectOrCollectionInitializer
#pragma warning disable IDE0017 // Simplify object initialization
var v = new JavaUuidOrder();
#pragma warning restore IDE0017 // Simplify object initialization
v.X0 = bytes[position]; position += SizeOfByte;
v.X1 = bytes[position]; position += SizeOfByte;
v.X2 = bytes[position]; position += SizeOfByte;
v.X3 = bytes[position]; position += SizeOfByte;
v.X4 = bytes[position]; position += SizeOfByte;
v.X5 = bytes[position]; position += SizeOfByte;
v.X6 = bytes[position]; position += SizeOfByte;
v.X7 = bytes[position]; position += SizeOfByte;
v.X8 = bytes[position]; position += SizeOfByte;
v.X9 = bytes[position]; position += SizeOfByte;
v.XA = bytes[position]; position += SizeOfByte;
v.XB = bytes[position]; position += SizeOfByte;
v.XC = bytes[position]; position += SizeOfByte;
v.XD = bytes[position]; position += SizeOfByte;
v.XE = bytes[position]; position += SizeOfByte;
v.XF = bytes[position];
return v.Value;
}
private static void WriteGuid(this byte[] bytes, int position, Guid value)
{
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
// must at least be able to write a bool
if (position < 0 || bytes.Length < position + SizeOfBool)
throw new ArgumentOutOfRangeException(nameof(position));
// write the 'empty' bool
bytes.WriteBool(position, value == Guid.Empty);
if (value == Guid.Empty) return;
// if not empty, must be able to write the full guid
if (bytes.Length < position + SizeOfGuid)
throw new ArgumentOutOfRangeException(nameof(position));
position += SizeOfByte;
var v = new JavaUuidOrder {Value = value};
bytes[position] = v.X0;
position += SizeOfByte;
bytes[position] = v.X1;
position += SizeOfByte;
bytes[position] = v.X2;
position += SizeOfByte;
bytes[position] = v.X3;
position += SizeOfByte;
bytes[position] = v.X4;
position += SizeOfByte;
bytes[position] = v.X5;
position += SizeOfByte;
bytes[position] = v.X6;
position += SizeOfByte;
bytes[position] = v.X7;
position += SizeOfByte;
bytes[position] = v.X8;
position += SizeOfByte;
bytes[position] = v.X9;
position += SizeOfByte;
bytes[position] = v.XA;
position += SizeOfByte;
bytes[position] = v.XB;
position += SizeOfByte;
bytes[position] = v.XC;
position += SizeOfByte;
bytes[position] = v.XD;
position += SizeOfByte;
bytes[position] = v.XE;
position += SizeOfByte;
bytes[position] = v.XF;
}
}
}
| 38.811688 | 87 | 0.600301 | [
"Apache-2.0"
] | alexb5dh/hazelcast-csharp-client | src/Hazelcast.Net/Core/BytesExtensions.Protocol.cs | 5,979 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
namespace Microsoft.Bot.Builder.Integration.AspNet.Core
{
/// <summary>
/// Extension class for bot integration with ASP.NET Core 2.0 projects.
/// </summary>
/// <seealso cref="ApplicationBuilderExtensions"/>
/// <seealso cref="BotAdapter"/>
public static class ServiceCollectionExtensions
{
private static readonly JsonSerializer ActivitySerializer = JsonSerializer.Create();
/// <summary>
/// Adds a bot service to the ASP.NET container.
/// </summary>
/// <typeparam name="TBot">The type of the bot to add.</typeparam>
/// <param name="services">The services collection for the ASP.NET application.</param>
/// <param name="setupAction">The delegate to run after an instance of the bot is added to the collection.</param>
/// <returns>The updated services collection.</returns>
/// <remarks>This method adds a default instance of <typeparamref name="TBot"/> as a transient service.</remarks>
public static IServiceCollection AddBot<TBot>(this IServiceCollection services, Action<BotFrameworkOptions> setupAction = null) where TBot : class, IBot
{
services.AddTransient<IBot, TBot>();
services.Configure(setupAction);
return services;
}
}
}
| 40.405405 | 160 | 0.677592 | [
"MIT"
] | joescars/botbuilder-dotnet | libraries/integration/Microsoft.Bot.Builder.Integration.AspNet.Core/ServiceCollectionExtensions.cs | 1,497 | C# |
using System;
using System.Windows.Forms;
namespace GSA.ToolKits.FormUtility
{
/// <summary>
/// 加载提示窗口
/// </summary>
public partial class WaitDialogForm : Form
{
/// <summary>
/// 构造函数
/// </summary>
public WaitDialogForm()
{
InitializeComponent();
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="tipsInfo">提示信息</param>
public WaitDialogForm(string tipsInfo)
{
InitializeComponent();
this.lblTipsInfo.Text = tipsInfo;
}
}
}
| 20.724138 | 47 | 0.502496 | [
"MIT"
] | cockroach888/GSA.MOLLE.ToolKits | src/ToolKits.FormUtility/src/WaitDialogForm.cs | 639 | C# |
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Support.V4.Widget;
using Android.Support.V7.Graphics.Drawable;
using Android.Support.V7.Widget;
using Android.Views;
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Threading.Tasks;
using ActionBarDrawerToggle = Android.Support.V7.App.ActionBarDrawerToggle;
using AView = Android.Views.View;
using LP = Android.Views.ViewGroup.LayoutParams;
using R = Android.Resource;
using Toolbar = Android.Support.V7.Widget.Toolbar;
namespace Xamarin.Forms.Platform.Android
{
public class ShellToolbarTracker : Java.Lang.Object, AView.IOnClickListener, IShellToolbarTracker, IFlyoutBehaviorObserver
{
#region IFlyoutBehaviorObserver
void IFlyoutBehaviorObserver.OnFlyoutBehaviorChanged(FlyoutBehavior behavior)
{
if (_flyoutBehavior == behavior)
return;
_flyoutBehavior = behavior;
if (Page != null)
UpdateLeftBarButtonItem();
}
#endregion IFlyoutBehaviorObserver
bool _canNavigateBack;
bool _disposed;
DrawerLayout _drawerLayout;
ActionBarDrawerToggle _drawerToggle;
FlyoutBehavior _flyoutBehavior = FlyoutBehavior.Flyout;
Page _page;
SearchHandler _searchHandler;
IShellSearchView _searchView;
ContainerView _titleViewContainer;
IShellContext _shellContext;
//assume the default
Color _tintColor = Color.Default;
Toolbar _toolbar;
string _defaultNavigationContentDescription;
public ShellToolbarTracker(IShellContext shellContext, Toolbar toolbar, DrawerLayout drawerLayout)
{
_shellContext = shellContext ?? throw new ArgumentNullException(nameof(shellContext));
_toolbar = toolbar ?? throw new ArgumentNullException(nameof(toolbar));
_drawerLayout = drawerLayout ?? throw new ArgumentNullException(nameof(drawerLayout));
((IShellController)_shellContext.Shell).AddFlyoutBehaviorObserver(this);
}
public bool CanNavigateBack
{
get { return _canNavigateBack; }
set
{
if (_canNavigateBack == value)
return;
_canNavigateBack = value;
UpdateLeftBarButtonItem();
}
}
public Page Page
{
get { return _page; }
set
{
if (_page == value)
return;
var oldPage = _page;
_page = value;
OnPageChanged(oldPage, _page);
}
}
public Color TintColor
{
get { return _tintColor; }
set
{
_tintColor = value;
if (Page != null)
{
UpdateToolbarItems();
UpdateLeftBarButtonItem();
}
}
}
protected SearchHandler SearchHandler
{
get => _searchHandler;
set
{
if (value == _searchHandler)
return;
var oldValue = _searchHandler;
_searchHandler = value;
OnSearchHandlerChanged(oldValue, _searchHandler);
}
}
void AView.IOnClickListener.OnClick(AView v)
{
var backButtonHandler = Shell.GetBackButtonBehavior(Page);
if (backButtonHandler?.Command != null)
backButtonHandler.Command.Execute(backButtonHandler.CommandParameter);
else if (CanNavigateBack)
OnNavigateBack();
else
_shellContext.Shell.FlyoutIsPresented = !_shellContext.Shell.FlyoutIsPresented;
v.Dispose();
}
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
UpdateTitleView(_shellContext.AndroidContext, _toolbar, null);
_drawerToggle?.Dispose();
if (_searchView != null)
{
_searchView.View.RemoveFromParent();
_searchView.View.ViewAttachedToWindow -= OnSearchViewAttachedToWindow;
_searchView.SearchConfirmed -= OnSearchConfirmed;
_searchView.Dispose();
}
((IShellController)_shellContext.Shell).RemoveFlyoutBehaviorObserver(this);
}
SearchHandler = null;
_shellContext = null;
_drawerToggle = null;
_searchView = null;
Page = null;
_toolbar = null;
_drawerLayout = null;
_disposed = true;
}
}
protected virtual IShellSearchView GetSearchView(Context context)
{
return new ShellSearchView(context, _shellContext);
}
protected virtual void OnNavigateBack()
{
Page.Navigation.PopAsync();
}
protected virtual void OnPageChanged(Page oldPage, Page newPage)
{
if (oldPage != null)
{
oldPage.PropertyChanged -= OnPagePropertyChanged;
((INotifyCollectionChanged)oldPage.ToolbarItems).CollectionChanged -= OnPageToolbarItemsChanged;
}
if (newPage != null)
{
newPage.PropertyChanged += OnPagePropertyChanged;
((INotifyCollectionChanged)newPage.ToolbarItems).CollectionChanged += OnPageToolbarItemsChanged;
UpdatePageTitle(_toolbar, newPage);
UpdateLeftBarButtonItem();
UpdateToolbarItems();
UpdateNavBarVisible(_toolbar, newPage);
UpdateTitleView();
}
}
protected virtual void OnPagePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == Page.TitleProperty.PropertyName)
UpdatePageTitle(_toolbar, Page);
else if (e.PropertyName == Shell.SearchHandlerProperty.PropertyName)
UpdateToolbarItems();
else if (e.PropertyName == Shell.NavBarIsVisibleProperty.PropertyName)
UpdateNavBarVisible(_toolbar, Page);
else if (e.PropertyName == Shell.BackButtonBehaviorProperty.PropertyName)
UpdateLeftBarButtonItem();
else if (e.PropertyName == Shell.TitleViewProperty.PropertyName)
UpdateTitleView();
}
protected virtual void OnPageToolbarItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateToolbarItems();
}
protected virtual void OnSearchConfirmed(object sender, EventArgs e)
{
_toolbar.CollapseActionView();
}
protected virtual void OnSearchHandlerChanged(SearchHandler oldValue, SearchHandler newValue)
{
if (oldValue != null)
{
oldValue.PropertyChanged -= OnSearchHandlerPropertyChanged;
}
if (newValue != null)
{
newValue.PropertyChanged += OnSearchHandlerPropertyChanged;
}
}
protected virtual void OnSearchHandlerPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == SearchHandler.SearchBoxVisibilityProperty.PropertyName ||
e.PropertyName == SearchHandler.IsSearchEnabledProperty.PropertyName)
{
UpdateToolbarItems();
}
}
protected virtual async void UpdateLeftBarButtonItem(Context context, Toolbar toolbar, DrawerLayout drawerLayout, Page page)
{
var backButtonHandler = Shell.GetBackButtonBehavior(page);
toolbar.SetNavigationOnClickListener(this);
if (backButtonHandler != null)
{
await UpdateDrawerArrowFromBackButtonBehavior(context, toolbar, drawerLayout, backButtonHandler);
}
else
{
await UpdateDrawerArrow(context, toolbar, drawerLayout);
}
}
protected virtual async Task UpdateDrawerArrow(Context context, Toolbar toolbar, DrawerLayout drawerLayout)
{
if (_drawerToggle == null && !context.IsDesignerContext())
{
_drawerToggle = new ActionBarDrawerToggle(context.GetActivity(), drawerLayout, toolbar, R.String.Ok, R.String.Ok)
{
ToolbarNavigationClickListener = this,
};
await UpdateDrawerArrowFromFlyoutIcon(context, _drawerToggle);
_drawerToggle.DrawerSlideAnimationEnabled = false;
drawerLayout.AddDrawerListener(_drawerToggle);
}
if (CanNavigateBack)
{
_drawerToggle.DrawerIndicatorEnabled = false;
using (var icon = new DrawerArrowDrawable(context.GetThemedContext()))
{
icon.SetColorFilter(TintColor.ToAndroid(Color.White), PorterDuff.Mode.SrcAtop);
icon.Progress = 1;
toolbar.NavigationIcon = icon;
}
}
else if (_flyoutBehavior == FlyoutBehavior.Flyout)
{
toolbar.NavigationIcon = null;
var drawable = _drawerToggle.DrawerArrowDrawable;
drawable.SetColorFilter(TintColor.ToAndroid(Color.White), PorterDuff.Mode.SrcAtop);
_drawerToggle.DrawerIndicatorEnabled = true;
}
else
{
_drawerToggle.DrawerIndicatorEnabled = false;
}
_drawerToggle.SyncState();
//this needs to be set after SyncState
UpdateToolbarIconAccessibilityText(toolbar, _shellContext.Shell);
}
protected virtual void UpdateToolbarIconAccessibilityText(Toolbar toolbar, Shell shell)
{
//if AutomationId was specified the user wants to use UITests and interact with FlyoutIcon
if (!string.IsNullOrEmpty(shell.FlyoutIcon?.AutomationId))
{
if (_defaultNavigationContentDescription == null)
_defaultNavigationContentDescription = toolbar.NavigationContentDescription;
toolbar.NavigationContentDescription = shell.FlyoutIcon.AutomationId;
}
else
{
toolbar.SetNavigationContentDescription(_shellContext.Shell.FlyoutIcon, _defaultNavigationContentDescription);
}
}
protected virtual async Task UpdateDrawerArrowFromBackButtonBehavior(Context context, Toolbar toolbar, DrawerLayout drawerLayout, BackButtonBehavior backButtonHandler)
{
var behavior = backButtonHandler;
var command = behavior.Command;
var commandParameter = behavior.CommandParameter;
var image = behavior.IconOverride;
var text = behavior.TextOverride;
var enabled = behavior.IsEnabled;
Drawable icon = null;
if (image != null)
icon = await context.GetFormsDrawableAsync(image);
if (text != null)
icon = new FlyoutIconDrawerDrawable(context, TintColor, icon, text);
if (CanNavigateBack && icon == null)
{
icon = new DrawerArrowDrawable(context.GetThemedContext());
(icon as DrawerArrowDrawable).Progress = 1;
}
var iconState = icon.GetConstantState();
if (iconState != null)
{
using (var mutatedIcon = iconState.NewDrawable().Mutate())
{
mutatedIcon.SetColorFilter(TintColor.ToAndroid(Color.White), PorterDuff.Mode.SrcAtop);
toolbar.NavigationIcon = mutatedIcon;
}
}
else
{
toolbar.NavigationIcon = icon;
}
}
protected virtual async Task UpdateDrawerArrowFromFlyoutIcon(Context context, ActionBarDrawerToggle actionBarDrawerToggle)
{
Element item = Page;
ImageSource icon = null;
while (!Application.IsApplicationOrNull(item))
{
if (item is IShellController shell)
{
icon = shell.FlyoutIcon;
if (icon != null)
{
var drawable = await context.GetFormsDrawableAsync(icon);
actionBarDrawerToggle.DrawerArrowDrawable = new FlyoutIconDrawerDrawable(context, TintColor, drawable, null);
}
return;
}
item = item?.Parent;
}
}
protected virtual void UpdateMenuItemIcon(Context context, IMenuItem menuItem, ToolbarItem toolBarItem)
{
_shellContext.ApplyDrawableAsync(toolBarItem, ToolbarItem.IconImageSourceProperty, baseDrawable =>
{
if (baseDrawable != null)
{
using (var constant = baseDrawable.GetConstantState())
using (var newDrawable = constant.NewDrawable())
using (var iconDrawable = newDrawable.Mutate())
{
iconDrawable.SetColorFilter(TintColor.ToAndroid(Color.White), PorterDuff.Mode.SrcAtop);
menuItem.SetIcon(iconDrawable);
}
}
});
}
protected virtual void UpdateNavBarVisible(Toolbar toolbar, Page page)
{
var navBarVisible = Shell.GetNavBarIsVisible(page);
toolbar.Visibility = navBarVisible ? ViewStates.Visible : ViewStates.Gone;
}
protected virtual void UpdatePageTitle(Toolbar toolbar, Page page)
{
_toolbar.Title = page.Title;
}
protected virtual void UpdateTitleView(Context context, Toolbar toolbar, View titleView)
{
if (titleView == null)
{
if (_titleViewContainer != null)
{
_titleViewContainer.RemoveFromParent();
_titleViewContainer.Dispose();
_titleViewContainer = null;
}
}
else
{
_titleViewContainer = new ContainerView(context, titleView);
_titleViewContainer.MatchHeight = _titleViewContainer.MatchWidth = true;
_titleViewContainer.LayoutParameters = new Toolbar.LayoutParams(LP.MatchParent, LP.MatchParent)
{
LeftMargin = (int)context.ToPixels(titleView.Margin.Left),
TopMargin = (int)context.ToPixels(titleView.Margin.Top),
RightMargin = (int)context.ToPixels(titleView.Margin.Right),
BottomMargin = (int)context.ToPixels(titleView.Margin.Bottom)
};
_toolbar.AddView(_titleViewContainer);
}
}
protected virtual void UpdateToolbarItems(Toolbar toolbar, Page page)
{
var menu = toolbar.Menu;
menu.Clear();
foreach (var item in page.ToolbarItems)
{
using (var title = new Java.Lang.String(item.Text))
{
var menuitem = menu.Add(title);
UpdateMenuItemIcon(_shellContext.AndroidContext, menuitem, item);
menuitem.SetTitleOrContentDescription(item);
menuitem.SetEnabled(item.IsEnabled);
menuitem.SetShowAsAction(ShowAsAction.Always);
menuitem.SetOnMenuItemClickListener(new GenericMenuClickListener(((IMenuItemController)item).Activate));
menuitem.Dispose();
}
}
SearchHandler = Shell.GetSearchHandler(page);
if (SearchHandler != null && SearchHandler.SearchBoxVisibility != SearchBoxVisibility.Hidden)
{
var context = _shellContext.AndroidContext;
if (_searchView == null)
{
_searchView = GetSearchView(context);
_searchView.SearchHandler = SearchHandler;
_searchView.LoadView();
_searchView.View.ViewAttachedToWindow += OnSearchViewAttachedToWindow;
var lp = new LP(LP.MatchParent, LP.MatchParent);
_searchView.View.LayoutParameters = lp;
lp.Dispose();
_searchView.SearchConfirmed += OnSearchConfirmed;
}
if (SearchHandler.SearchBoxVisibility == SearchBoxVisibility.Collapsible)
{
var placeholder = new Java.Lang.String(SearchHandler.Placeholder);
var item = menu.Add(placeholder);
placeholder.Dispose();
item.SetEnabled(SearchHandler.IsSearchEnabled);
item.SetIcon(Resource.Drawable.abc_ic_search_api_material);
using (var icon = item.Icon)
icon.SetColorFilter(TintColor.ToAndroid(Color.White), PorterDuff.Mode.SrcAtop);
item.SetShowAsAction(ShowAsAction.IfRoom | ShowAsAction.CollapseActionView);
if (_searchView.View.Parent != null)
_searchView.View.RemoveFromParent();
_searchView.ShowKeyboardOnAttached = true;
item.SetActionView(_searchView.View);
item.Dispose();
}
else if (SearchHandler.SearchBoxVisibility == SearchBoxVisibility.Expanded)
{
_searchView.ShowKeyboardOnAttached = false;
if (_searchView.View.Parent != _toolbar)
_toolbar.AddView(_searchView.View);
}
}
else
{
if (_searchView != null)
{
_searchView.View.RemoveFromParent();
_searchView.View.ViewAttachedToWindow -= OnSearchViewAttachedToWindow;
_searchView.SearchConfirmed -= OnSearchConfirmed;
_searchView.Dispose();
_searchView = null;
}
}
menu.Dispose();
}
void OnSearchViewAttachedToWindow(object sender, AView.ViewAttachedToWindowEventArgs e)
{
// We only need to do this tint hack when using collapsed search handlers
if (SearchHandler.SearchBoxVisibility != SearchBoxVisibility.Collapsible)
return;
for (int i = 0; i < _toolbar.ChildCount; i++)
{
var child = _toolbar.GetChildAt(i);
if (child is AppCompatImageButton button)
{
// we want the newly added button which will need layout
if (child.IsLayoutRequested)
{
button.SetColorFilter(TintColor.ToAndroid(Color.White), PorterDuff.Mode.SrcAtop);
}
button.Dispose();
}
}
}
void UpdateLeftBarButtonItem()
{
UpdateLeftBarButtonItem(_shellContext.AndroidContext, _toolbar, _drawerLayout, Page);
}
void UpdateTitleView()
{
UpdateTitleView(_shellContext.AndroidContext, _toolbar, Shell.GetTitleView(Page));
}
void UpdateToolbarItems()
{
UpdateToolbarItems(_toolbar, Page);
}
class FlyoutIconDrawerDrawable : DrawerArrowDrawable
{
Drawable _iconBitmap;
string _text;
Color _defaultColor;
float _defaultSize;
Color _pressedBackgroundColor => _defaultColor.AddLuminosity(-.12);//<item name="highlight_alpha_material_light" format="float" type="dimen">0.12</item>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && _iconBitmap != null)
{
_iconBitmap.Dispose();
}
}
public FlyoutIconDrawerDrawable(Context context, Color defaultColor, Drawable icon, string text) : base(context)
{
_defaultColor = defaultColor;
_defaultSize = Forms.GetFontSizeNormal(context);
_iconBitmap = icon;
_text = text;
}
public override void Draw(Canvas canvas)
{
bool pressed = false;
if (_iconBitmap != null)
{
_iconBitmap.SetBounds(Bounds.Left, Bounds.Top, Bounds.Right, Bounds.Bottom);
_iconBitmap.Draw(canvas);
}
else if (!string.IsNullOrEmpty(_text))
{
var paint = new Paint { AntiAlias = true };
paint.TextSize = _defaultSize;
paint.Color = pressed ? _pressedBackgroundColor.ToAndroid() : _defaultColor.ToAndroid();
paint.SetStyle(Paint.Style.Fill);
var y = (Bounds.Height() + paint.TextSize) / 2;
canvas.DrawText(_text, 0, y, paint);
}
}
}
}
}
| 29.13036 | 169 | 0.725549 | [
"MIT"
] | Arobono/Xamarin.Forms | Xamarin.Forms.Platform.Android/Renderers/ShellToolbarTracker.cs | 16,985 | C# |
using System;
namespace Unity.VisualScripting.Community.Libraries.Humility
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]
public sealed class DisplayNameAttribute : Attribute
{
public string label;
public DisplayNameAttribute(string label)
{
this.label = label;
}
}
}
| 27.9375 | 164 | 0.700224 | [
"MIT"
] | Fitz-YM/Bolt.Addons.Community | Runtime/Libraries/Humility/Attributes/DisplayNameAttribute.cs | 449 | C# |
using System.Collections.Generic;
using Alipay.AopSdk.Core.Response;
namespace Alipay.AopSdk.Core.Request
{
/// <summary>
/// AOP API: koubei.marketing.campaign.recruit.shop.query
/// </summary>
public class
KoubeiMarketingCampaignRecruitShopQueryRequest : IAopRequest<KoubeiMarketingCampaignRecruitShopQueryResponse>
{
/// <summary>
/// 招商门店分页查询接口
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "koubei.marketing.campaign.recruit.shop.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AopDictionary();
parameters.Add("biz_content", BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
} | 18 | 111 | 0.706284 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk.Core/Request/KoubeiMarketingCampaignRecruitShopQueryRequest.cs | 2,216 | 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 glacier-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Glacier.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Glacier.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListProvisionedCapacity Request Marshaller
/// </summary>
public class ListProvisionedCapacityRequestMarshaller : IMarshaller<IRequest, ListProvisionedCapacityRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListProvisionedCapacityRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListProvisionedCapacityRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Glacier");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-06-01";
request.HttpMethod = "GET";
request.AddPathResource("{accountId}", publicRequest.IsSetAccountId() ? StringUtils.FromString(publicRequest.AccountId) : string.Empty);
request.ResourcePath = "/{accountId}/provisioned-capacity";
return request;
}
private static ListProvisionedCapacityRequestMarshaller _instance = new ListProvisionedCapacityRequestMarshaller();
internal static ListProvisionedCapacityRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListProvisionedCapacityRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 34.882353 | 161 | 0.670152 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/Glacier/Generated/Model/Internal/MarshallTransformations/ListProvisionedCapacityRequestMarshaller.cs | 2,965 | C# |
using Microsoft.EntityFrameworkCore;
using Stations.Data.EntityConfig;
using Stations.Models;
namespace Stations.Data
{
public class StationsDbContext : DbContext
{
public StationsDbContext()
{
}
public StationsDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Station> Stations { get; set; }
public DbSet<Train> Trains { get; set; }
public DbSet<CustomerCard> Cards { get; set; }
public DbSet<SeatingClass> SeatingClasses { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<TrainSeat> TrainSeats { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Configuration.ConnectionString);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new StationConfig());
modelBuilder.ApplyConfiguration(new TrainConfig());
modelBuilder.ApplyConfiguration(new TrainSeatConfig());
modelBuilder.ApplyConfiguration(new SeatingClassConfig());
modelBuilder.ApplyConfiguration(new TicketConfig());
modelBuilder.ApplyConfiguration(new TripCongif());
modelBuilder.ApplyConfiguration(new CustomerConfig());
}
}
} | 31.622222 | 85 | 0.692902 | [
"MIT"
] | ewgeni-dinew/04.Databases_Advanced-Entity_Framework | 14.Exam Preparation II/13. DB-Advanced-EF-Core-Exam-Preparation-2-Stations-Skeleton/Stations.Data/StationsDbContext.cs | 1,425 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace HandshakeVR.Demo
{
public class Alert : MonoBehaviour
{
public UnityEvent OnAlert;
[SerializeField]
float viewAngle = 25;
[SerializeField]
float viewDuration = 1f;
float viewTime = 0;
bool hasAlerted = false;
Transform viewCamera;
Animator animator;
int alertHash;
// Use this for initialization
void Start()
{
viewCamera = Camera.main.transform;
animator = GetComponent<Animator>();
alertHash = Animator.StringToHash("Alert");
}
// Update is called once per frame
void Update()
{
animator.SetBool(alertHash, !hasAlerted);
if(!hasAlerted)
{
Vector3 directionToSelf = (transform.position - viewCamera.position).normalized;
if (Vector3.Angle(directionToSelf, viewCamera.forward) <= viewAngle)
{
viewTime += Time.deltaTime;
if (viewTime >= viewDuration)
{
OnAlert.Invoke();
hasAlerted = true;
return;
}
}
else viewTime = 0;
}
}
}
} | 25 | 97 | 0.483333 | [
"MIT"
] | jcorvinus/HandshakeVR | Assets/HandshakeVR/Scripts/Demo/Alert.cs | 1,502 | C# |
using TcfBackup.Filesystem;
namespace TcfBackup.Source;
public class FilesListSource : ISource, IDisposable
{
private readonly IEnumerable<IFile> _files;
public FilesListSource(IEnumerable<IFile> files) => _files = files;
public static FilesListSource CreateMutable(IFilesystem fs, IEnumerable<string> files) => new(files.Select(f => (IFile)new MutableFile(fs, f)));
public static FilesListSource CreateImmutable(IFilesystem fs, IEnumerable<string> files) => new(files.Select(f => (IFile)new ImmutableFile(fs, f)));
public IEnumerable<IFile> GetFiles() => _files;
public void Prepare()
{
}
public void Cleanup()
{
foreach (var file in _files)
{
try
{
file.Delete();
}
catch (Exception)
{
// NOP
}
}
}
public void Dispose() => Cleanup();
} | 25.611111 | 152 | 0.603037 | [
"MIT"
] | TheCheshireFox/tcf-backup | TcfBackup.Source/FilesListSource.cs | 922 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Store.DTO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Store.DTO")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e2d06df8-dde2-4414-a5a8-800399559d35")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.459459 | 84 | 0.74531 | [
"MIT"
] | zeinabkamel/AdvancedWF | AdvancedWf.DTO/Properties/AssemblyInfo.cs | 1,389 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Numerics
{
/// <summary>Defines a mechanism for decrementing a given value.</summary>
/// <typeparam name="TSelf">The type that implements this interface.</typeparam>
public interface IDecrementOperators<TSelf>
where TSelf : IDecrementOperators<TSelf>
{
/// <summary>Decrements a value.</summary>
/// <param name="value">The value to decrement.</param>
/// <returns>The result of decrementing <paramref name="value" />.</returns>
static abstract TSelf operator --(TSelf value);
/// <summary>Decrements a value.</summary>
/// <param name="value">The value to decrement.</param>
/// <returns>The result of decrementing <paramref name="value" />.</returns>
/// <exception cref="OverflowException">The result of decrementing <paramref name="value" /> is not representable by <typeparamref name="TSelf" />.</exception>
static abstract TSelf operator checked --(TSelf value);
}
}
| 49.130435 | 167 | 0.676106 | [
"MIT"
] | AlexanderSemenyak/runtime | src/libraries/System.Private.CoreLib/src/System/Numerics/IDecrementOperators.cs | 1,130 | C# |
using System.ComponentModel.DataAnnotations;
using Abp.MultiTenancy;
namespace EduVault.Authorization.Accounts.Dto
{
public class IsTenantAvailableInput
{
[Required]
[StringLength(AbpTenantBase.MaxTenancyNameLength)]
public string TenancyName { get; set; }
}
}
| 23 | 58 | 0.722408 | [
"MIT"
] | nataizya-s/gitlab | aspnet-core/src/EduVault.Application/Authorization/Accounts/Dto/IsTenantAvailableInput.cs | 301 | C# |
using EA.TMS.Common.Core;
using EA.TMS.DataAccess.Core;
using System.Collections.Generic;
namespace EA.TMS.Business.Core
{
public interface IActionManager
{
void Create(BaseEntity entity);
void Update(BaseEntity entity);
void Delete(BaseEntity entity);
IEnumerable<BaseEntity> GetAll();
IUnitOfWork UnitOfWork { get; }
void SaveChanges();
}
} | 19.47619 | 41 | 0.665037 | [
"MIT"
] | cristofima/TenantManagementSystem | EA.TMS.Business/Core/IActionManager.cs | 411 | C# |
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace FastSLQL.Format
{
internal static class DBFileSystem
{
public static void Serialize(string fileName, string[] data)
{
BinaryFormatter bf = new BinaryFormatter();
using (Stream writer = new FileStream(fileName, FileMode.OpenOrCreate))
{
bf.Serialize(writer, data);
}
}
public static string[] DeSerialize(string fileName)
{
BinaryFormatter bf = new BinaryFormatter();
using (Stream reader = new FileStream(fileName, FileMode.Open))
{
if (reader.Length <= 0)
return new string[] { "", "", "" };
return (string[])bf.Deserialize(reader);
}
}
}
}
| 30.733333 | 87 | 0.505423 | [
"MIT"
] | ZikkeyLS/FastSLQL | Format/DBFileSystem.cs | 924 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using TerrariaApi.Server;
using TShockAPI;
using Terraria.Localization;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
namespace Starvers
{
using Vector = TOFOUT.Terraria.Server.Vector2;
/// <summary>
/// 事先将弹幕和速度存入,稍后发射
/// </summary>
public class ProjQueue :Queue<ProjPair>, IProjSet
{
#region Fields
private int Size;
#endregion
#region Ctor
public ProjQueue(int size = 30) : base(size)
{
Size = size;
//ProjIndex = (int*)Marshal.AllocHGlobal(sizeof(int) * Size);
//Velocity = (Vector*)Marshal.AllocHGlobal(sizeof(Vector) * Size);
}
#endregion
#region Push
public bool Push(int idx, Vector velocity)
{
Enqueue((idx, velocity));
return Count < Size;
}
public bool Push(IEnumerable<int> idxes, Vector vel)
{
foreach(var idx in idxes)
{
if (!Push(idx, vel))
{
return false;
}
}
return Count < Size;
}
public unsafe bool Push(int* ptr, int count, Vector vel)
{
int* end = ptr + count;
while (ptr != end)
{
if (!Push(*ptr++, vel))
{
return false;
}
}
return Count < Size;
}
#endregion
#region Launch
public void Launch()
{
while(Count > 0)
{
Dequeue().Launch();
}
}
public void Launch(Vector Velocity)
{
while (Count > 0)
{
Dequeue().Launch(Velocity);
}
}
public bool Launch(int HowMany, Vector Vel)
{
while(HowMany-- > 0 && Count > 0)
{
Launch(Vel);
}
return Count > 0;
}
public bool Launch(int HowMany)
{
while (HowMany-- > 0 && Count > 0)
{
Launch();
}
return Count > 0;
}
public bool LaunchTo(int HowMany, Vector Pos, float vel)
{
while (HowMany-- > 0 && Count > 0)
{
Dequeue().Launch(Pos, vel);
}
return Count > 0;
}
public void LaunchTo(Vector Pos, float vel)
{
LaunchTo(Count, Pos, vel);
}
#endregion
#region Reset
public void Reset()
{
Clear();
}
#endregion
}
}
| 18.694915 | 69 | 0.631006 | [
"MIT"
] | DreamPrism/Starver | ProjContainers/ProjQueue.cs | 2,236 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Alquran.model
{
class DataQuran
{
[JsonProperty(PropertyName = "nomor")]
public string Nomor { get; set; }
[JsonProperty(PropertyName = "nama")]
public string Nama { get; set; }
[JsonProperty(PropertyName = "nama_latin")]
public string Latin { get; set; }
[JsonProperty(PropertyName = "jumlah_ayat")]
public string Jumlah { get; set; }
[JsonProperty(PropertyName = "tempat_turun")]
public string Tempat { get; set; }
[JsonProperty(PropertyName = "arti")]
public string Arti { get; set; }
[JsonProperty(PropertyName = "deskripsi")]
public string Deskripsi { get; set; }
[JsonProperty(PropertyName = "audio")]
public string Audio { get; set; }
}
}
| 24.868421 | 53 | 0.62328 | [
"MIT"
] | suryamsj/Aplikasi-E-Quran | Alquran/model/DataQuran.cs | 947 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SkyrimTwitchBotLib.Models {
public class SkyrimStreamRedemption {
public string Username { get; set; }
public string RedemptionName { get; set; }
public DateTime RedemptionTime { get; set; }
public string RedemptionCommand { get; set; }
public int RedemptionSeptims { get; set; }
}
}
| 28.75 | 53 | 0.695652 | [
"MIT"
] | mrowrpurr/SkyrimTwitchBot | SkyrimTwitchBotLib/Models/SkyrimStreamRedemption.cs | 462 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Concept.Linq.Lesson1 {
class Human {
public string Name { get; }
public int Age { get; }
public Human(string name, int age) => (Name, Age) = (name, age);
}
class Main {
public void Run() {
List<Human> humans = CreateHumans();
Show(Query(humans));
}
private List<Human> CreateHumans() {
return new List<Human> {
new Human("A1", 0), new Human("B1", 1),
new Human("A2", 2), new Human("B2", 3),
new Human("A3", 4), new Human("B3", 5),
};
}
private IEnumerable<IGrouping<char,Human>> Query(in List<Human> humans) {
return from h in humans
group h by h.Name[0];
}
private void Show(in IEnumerable<IGrouping<char,Human>> groups) {
foreach (var g in groups) {
Console.WriteLine($"Key={g.Key}");
foreach (var v in g) {
Console.WriteLine($" Value=Name:{v.Name}, Age:{v.Age}");
}
}
}
}
}
| 31.052632 | 81 | 0.490678 | [
"CC0-1.0"
] | ytyaru/CSharp.Concept.Linq.Group.20191201085538 | src/lesson1/Main.cs | 1,180 | C# |
namespace ESIConnectionLibrary.PublicModels
{
public enum V1ContractsPublicType
{
Unknown,
ItemExchange,
Auction,
Courier,
Loan
}
} | 16.727273 | 44 | 0.592391 | [
"MIT"
] | Dusty-Meg/ESIConnectionLibrary | ESIConnectionLibrary/ESIConnectionLibrary/PublicModels/V1ContractsPublicType.cs | 186 | C# |
// ArrayListTest.cs - NUnit Test Cases for the System.Collections.ArrayList class
//
// David Brandt (bucky@keystreams.com)
//
// (C) Ximian, Inc. http://www.ximian.com
// Copyright (C) 2005 Novell (http://www.novell.com)
//
using System;
using System.Collections;
using NUnit.Framework;
namespace MonoTests.System.Collections
{
[TestFixture]
public class ArrayListTest
{
[Test]
public void TestCtor ()
{
{
ArrayList al1 = new ArrayList ();
Assert.IsNotNull (al1, "no basic ArrayList");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (null);
} catch (ArgumentNullException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "null icollection error not thrown");
}
{
// what can I say? I like chars. [--DB]
char [] coll = { 'a', 'b', 'c', 'd' };
ArrayList al1 = new ArrayList (coll);
Assert.IsNotNull (al1, "no icollection ArrayList");
for (int i = 0; i < coll.Length; i++) {
Assert.AreEqual (coll [i], al1 [i], i + " not ctor'ed properly.");
}
}
{
try {
Char [,] c1 = new Char [2, 2];
ArrayList al1 = new ArrayList (c1);
Assert.Fail ("Should fail with multi-dimensional array in constructor.");
} catch (RankException) {
}
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (-1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative capacity error not thrown");
}
}
[Test]
public void TestCapacity ()
{
#if NET_2_0
int default_capacity = 4;
int unspecified_capacity = 0;
#else
int default_capacity = 16;
int unspecified_capacity = 16;
#endif
for (int i = 1; i < 100; i++) {
ArrayList al1 = new ArrayList (i);
Assert.AreEqual (i, al1.Capacity, "Bad capacity of " + i);
}
{
ArrayList al1 = new ArrayList (0);
// LAMESPEC:
// Assert.AreEqual (// 16, al1.Capacity, "Bad capacity when set to 0");
al1.Add ("?");
Assert.AreEqual (default_capacity, al1.Capacity, "Bad capacity when set to 0");
}
{
ArrayList al1 = new ArrayList ();
Assert.AreEqual (unspecified_capacity, al1.Capacity, "Bad default capacity");
}
}
[Test]
public void TestCount ()
{
{
ArrayList al1 = new ArrayList ();
Assert.AreEqual (0, al1.Count, "Bad initial count");
for (int i = 1; i <= 100; i++) {
al1.Add (i);
Assert.AreEqual (i, al1.Count, "Bad count " + i);
}
}
for (int i = 0; i < 100; i++) {
char [] coll = new Char [i];
ArrayList al1 = new ArrayList (coll);
Assert.AreEqual (i, al1.Count, "Bad count for " + i);
}
}
[Test]
public void TestIsFixed ()
{
ArrayList al1 = new ArrayList ();
Assert.IsTrue (!al1.IsFixedSize, "should not be fixed by default");
ArrayList al2 = ArrayList.FixedSize (al1);
Assert.IsTrue (al2.IsFixedSize, "fixed-size wrapper not working");
}
[Test]
public void TestIsReadOnly ()
{
ArrayList al1 = new ArrayList ();
Assert.IsTrue (!al1.IsReadOnly, "should not be ReadOnly by default");
ArrayList al2 = ArrayList.ReadOnly (al1);
Assert.IsTrue (al2.IsReadOnly, "read-only wrapper not working");
}
[Test]
public void TestIsSynchronized ()
{
ArrayList al1 = new ArrayList ();
Assert.IsTrue (!al1.IsSynchronized, "should not be synchronized by default");
ArrayList al2 = ArrayList.Synchronized (al1);
Assert.IsTrue (al2.IsSynchronized, "synchronized wrapper not working");
}
[Test]
public void TestItem ()
{
ArrayList al1 = new ArrayList ();
{
bool errorThrown = false;
try {
object o = al1 [-1];
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative item error not thrown");
}
{
bool errorThrown = false;
try {
object o = al1 [1];
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "past-end item error not thrown");
}
for (int i = 0; i <= 100; i++) {
al1.Add (i);
}
for (int i = 0; i <= 100; i++) {
Assert.AreEqual (i, al1 [i], "item not fetched for " + i);
}
}
[Test]
public void TestAdapter ()
{
{
bool errorThrown = false;
try {
ArrayList al1 = ArrayList.Adapter (null);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "null adapter error not thrown");
}
{
char [] list = { 'a', 'b', 'c', 'd' };
ArrayList al1 = ArrayList.Adapter (list);
Assert.IsNotNull (al1, "Couldn't get an adapter");
for (int i = 0; i < list.Length; i++) {
Assert.AreEqual (list [i], al1 [i], "adapter not adapting");
}
list [0] = 'z';
for (int i = 0; i < list.Length; i++) {
Assert.AreEqual (list [i], al1 [i], "adapter not adapting");
}
}
// Test Binary Search
{
bool errorThrown = false;
try {
String [] s1 = { "This", "is", "a", "test" };
ArrayList al1 = ArrayList.Adapter (s1);
al1.BinarySearch (42);
} catch (InvalidOperationException) {
// this is what .NET throws
errorThrown = true;
} catch (ArgumentException) {
// this is what the docs say it should throw
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "search-for-wrong-type error not thrown");
}
{
char [] arr = { 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'd' };
ArrayList al1 = ArrayList.Adapter (arr);
Assert.IsTrue (al1.BinarySearch ('c') >= 3, "couldn't find elem #1");
Assert.IsTrue (al1.BinarySearch ('c') < 6, "couldn't find elem #2");
}
{
char [] arr = { 'a', 'b', 'b', 'd', 'd', 'd', 'e', 'e' };
ArrayList al1 = ArrayList.Adapter (arr);
Assert.AreEqual (-4, al1.BinarySearch ('c'), "couldn't find next-higher elem");
}
{
char [] arr = { 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'd' };
ArrayList al1 = ArrayList.Adapter (arr);
Assert.AreEqual (-9, al1.BinarySearch ('e'), "couldn't find end");
}
// Sort
{
char [] starter = { 'd', 'b', 'f', 'e', 'a', 'c' };
ArrayList al1 = ArrayList.Adapter (starter);
al1.Sort ();
Assert.AreEqual ('a', al1 [0], "Should be sorted");
Assert.AreEqual ('b', al1 [1], "Should be sorted");
Assert.AreEqual ('c', al1 [2], "Should be sorted");
Assert.AreEqual ('d', al1 [3], "Should be sorted");
Assert.AreEqual ('e', al1 [4], "Should be sorted");
Assert.AreEqual ('f', al1 [5], "Should be sorted");
}
// TODO - test other adapter types?
}
[Test]
public void TestAdd ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList ());
al1.Add ("Hi!");
} catch (NotSupportedException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "add to fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList ());
al1.Add ("Hi!");
} catch (NotSupportedException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 2: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "add to read only error not thrown");
}
{
ArrayList al1 = new ArrayList ();
for (int i = 1; i <= 100; i++) {
al1.Add (i);
Assert.AreEqual (i, al1.Count, "add failed " + i);
Assert.AreEqual (i, al1 [i - 1], "add failed " + i);
}
}
{
string [] strArray = new string [] { };
ArrayList al1 = new ArrayList (strArray);
al1.Add ("Hi!");
al1.Add ("Hi!");
Assert.AreEqual (2, al1.Count, "add failed");
}
}
[Test]
public void TestAddRange ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList ());
String [] s1 = { "Hi!" };
al1.AddRange (s1);
} catch (NotSupportedException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "add to fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList ());
String [] s1 = { "Hi!" };
al1.AddRange (s1);
} catch (NotSupportedException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 2: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "add to read only error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList ();
al1.AddRange (null);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 3: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "add to read only error not thrown");
}
{
ArrayList a1 = new ArrayList ();
Assert.AreEqual (0, a1.Count, "ArrayList should start empty");
char [] coll = { 'a', 'b', 'c' };
a1.AddRange (coll);
Assert.AreEqual (3, a1.Count, "ArrayList has wrong elements");
a1.AddRange (coll);
Assert.AreEqual (6, a1.Count, "ArrayList has wrong elements");
}
{
ArrayList list = new ArrayList ();
for (int i = 0; i < 100; i++) {
list.Add (1);
}
Assert.AreEqual (49, list.BinarySearch (1), "BinarySearch off-by-one bug");
}
}
[Test]
public void TestBinarySearch ()
{
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList ();
String [] s1 = { "This", "is", "a", "test" };
al1.AddRange (s1);
al1.BinarySearch (42);
} catch (InvalidOperationException) {
// this is what .NET throws
errorThrown = true;
} catch (ArgumentException) {
// this is what the docs say it should throw
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "search-for-wrong-type error not thrown");
}
{
char [] arr = { 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'd' };
ArrayList al1 = new ArrayList (arr);
Assert.IsTrue (al1.BinarySearch ('c') >= 3, "couldn't find elem #1");
Assert.IsTrue (al1.BinarySearch ('c') < 6, "couldn't find elem #2");
}
{
char [] arr = { 'a', 'b', 'b', 'd', 'd', 'd', 'e', 'e' };
ArrayList al1 = new ArrayList (arr);
Assert.AreEqual (-4, al1.BinarySearch ('c'), "couldn't find next-higher elem");
}
{
char [] arr = { 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'd' };
ArrayList al1 = new ArrayList (arr);
Assert.AreEqual (-9, al1.BinarySearch ('e'), "couldn't find end");
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void BinarySearch_IndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.BinarySearch (Int32.MaxValue, 1, this, null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void BinarySearch_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.BinarySearch (1, Int32.MaxValue, this, null);
}
[Test]
public void BinarySearch_Null ()
{
ArrayList al = new ArrayList ();
al.Add (this);
Assert.AreEqual (-1, al.BinarySearch (null), "null");
}
// TODO - BinarySearch with IComparer
[Test]
public void TestClear ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList ());
al1.Clear ();
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "add to fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList ());
al1.Clear ();
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "add to read only error not thrown");
}
{
ArrayList al1 = new ArrayList ();
al1.Add ('c');
Assert.AreEqual (1, al1.Count, "should have one element");
al1.Clear ();
Assert.AreEqual (0, al1.Count, "should be empty");
}
{
int [] i1 = { 1, 2, 3, 4 };
ArrayList al1 = new ArrayList (i1);
Assert.AreEqual (i1.Length, al1.Count, "should have elements");
int capacity = al1.Capacity;
al1.Clear ();
Assert.AreEqual (0, al1.Count, "should be empty again");
Assert.AreEqual (capacity, al1.Capacity, "capacity shouldn't have changed");
}
}
[Test]
public void TestClone ()
{
{
char [] c1 = { 'a', 'b', 'c' };
ArrayList al1 = new ArrayList (c1);
ArrayList al2 = (ArrayList) al1.Clone ();
Assert.AreEqual (al1 [0], al2 [0], "ArrayList match");
Assert.AreEqual (al1 [1], al2 [1], "ArrayList match");
Assert.AreEqual (al1 [2], al2 [2], "ArrayList match");
}
{
char [] d10 = { 'a', 'b' };
char [] d11 = { 'a', 'c' };
char [] d12 = { 'b', 'c' };
char [] [] d1 = { d10, d11, d12 };
ArrayList al1 = new ArrayList (d1);
ArrayList al2 = (ArrayList) al1.Clone ();
Assert.AreEqual (al1 [0], al2 [0], "Array match");
Assert.AreEqual (al1 [1], al2 [1], "Array match");
Assert.AreEqual (al1 [2], al2 [2], "Array match");
((char []) al1 [0]) [0] = 'z';
Assert.AreEqual (al1 [0], al2 [0], "shallow copy");
}
}
[Test]
public void TestContains ()
{
char [] c1 = { 'a', 'b', 'c' };
ArrayList al1 = new ArrayList (c1);
Assert.IsTrue (!al1.Contains (null), "never find a null");
Assert.IsTrue (al1.Contains ('b'), "can't find value");
Assert.IsTrue (!al1.Contains ('?'), "shouldn't find value");
}
[Test]
public void TestCopyTo ()
{
{
bool errorThrown = false;
try {
Char [] c1 = new Char [2];
ArrayList al1 = new ArrayList (c1);
al1.CopyTo (null, 2);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "error not thrown 1");
}
{
bool errorThrown = false;
try {
Char [] c1 = new Char [2];
ArrayList al1 = new ArrayList (c1);
Char [,] c2 = new Char [2, 2];
al1.CopyTo (c2, 2);
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 2: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "error not thrown 2");
}
{
bool errorThrown = false;
try {
// This appears to be a bug in the ArrayList Constructor.
// It throws a RankException if a multidimensional Array
// is passed. The docs imply that an IEnumerator is used
// to retrieve the items from the collection, so this should
// work. In anycase this test is for CopyTo, so use what
// works on both platforms.
//Char[,] c1 = new Char[2,2];
Char [] c1 = new Char [2];
ArrayList al1 = new ArrayList (c1);
Char [] c2 = new Char [2];
al1.CopyTo (c2, 2);
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 3: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "error not thrown 3");
}
{
bool errorThrown = false;
try {
Char [] c1 = new Char [2];
ArrayList al1 = new ArrayList (c1);
Char [] c2 = new Char [2];
al1.CopyTo (c2, -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 4: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "error not thrown 4");
}
{
bool errorThrown = false;
try {
Char [] c1 = new Char [2];
ArrayList al1 = new ArrayList (c1);
Char [] c2 = new Char [2];
al1.CopyTo (c2, 3);
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 5: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "error not thrown 5");
}
{
bool errorThrown = false;
try {
Char [] c1 = new Char [2];
ArrayList al1 = new ArrayList (c1);
Char [] c2 = new Char [2];
al1.CopyTo (c2, 1);
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 6: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "error not thrown 6");
}
{
bool errorThrown = false;
try {
String [] c1 = { "String", "array" };
ArrayList al1 = new ArrayList (c1);
Char [] c2 = new Char [2];
al1.CopyTo (c2, 0);
} catch (InvalidCastException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 7: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "error not thrown 7");
}
Char [] orig = { 'a', 'b', 'c', 'd' };
ArrayList al = new ArrayList (orig);
Char [] copy = new Char [10];
Array.Clear (copy, 0, copy.Length);
al.CopyTo (copy, 3);
Assert.AreEqual ((char) 0, copy [0], "Wrong CopyTo 0");
Assert.AreEqual ((char) 0, copy [1], "Wrong CopyTo 1");
Assert.AreEqual ((char) 0, copy [2], "Wrong CopyTo 2");
Assert.AreEqual (orig [0], copy [3], "Wrong CopyTo 3");
Assert.AreEqual (orig [1], copy [4], "Wrong CopyTo 4");
Assert.AreEqual (orig [2], copy [5], "Wrong CopyTo 5");
Assert.AreEqual (orig [3], copy [6], "Wrong CopyTo 6");
Assert.AreEqual ((char) 0, copy [7], "Wrong CopyTo 7");
Assert.AreEqual ((char) 0, copy [8], "Wrong CopyTo 8");
Assert.AreEqual ((char) 0, copy [9], "Wrong CopyTo 9");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CopyTo_IndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.CopyTo (Int32.MaxValue, new byte [2], 0, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CopyTo_ArrayIndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.CopyTo (0, new byte [2], Int32.MaxValue, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CopyTo_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.CopyTo (0, new byte [2], 0, Int32.MaxValue);
}
[Test]
public void TestFixedSize ()
{
{
bool errorThrown = false;
try {
ArrayList al1 = ArrayList.FixedSize (null);
} catch (ArgumentNullException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "null arg error not thrown");
}
{
ArrayList al1 = new ArrayList ();
Assert.AreEqual (false, al1.IsFixedSize, "arrays start un-fixed.");
ArrayList al2 = ArrayList.FixedSize (al1);
Assert.AreEqual (true, al2.IsFixedSize, "should be fixed.");
}
}
[Test]
public void TestEnumerator ()
{
String [] s1 = { "this", "is", "a", "test" };
ArrayList al1 = new ArrayList (s1);
IEnumerator en = al1.GetEnumerator ();
en.MoveNext ();
al1.Add ("something");
try {
en.MoveNext ();
Assert.Fail ("Add() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.AddRange (al1);
try {
en.MoveNext ();
Assert.Fail ("AddRange() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.Clear ();
try {
en.MoveNext ();
Assert.Fail ("Clear() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
al1 = new ArrayList (s1);
en = al1.GetEnumerator ();
en.MoveNext ();
al1.Insert (0, "new first");
try {
en.MoveNext ();
Assert.Fail ("Insert() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.InsertRange (0, al1);
try {
en.MoveNext ();
Assert.Fail ("InsertRange() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.Remove ("this");
try {
en.MoveNext ();
Assert.Fail ("Remove() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.RemoveAt (2);
try {
en.MoveNext ();
Assert.Fail ("RemoveAt() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.RemoveRange (1, 1);
try {
en.MoveNext ();
Assert.Fail ("RemoveRange() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.Reverse ();
try {
en.MoveNext ();
Assert.Fail ("Reverse() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
en = al1.GetEnumerator ();
en.MoveNext ();
al1.Sort ();
try {
en.MoveNext ();
Assert.Fail ("Sort() didn't invalidate the enumerator");
} catch (InvalidOperationException) {
// do nothing...this is what we expect
}
}
[Test]
public void TestGetEnumerator ()
{
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList ();
IEnumerator en = a.GetEnumerator (-1, 1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative index error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList ();
IEnumerator en = a.GetEnumerator (1, -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative index error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList ();
IEnumerator en = a.GetEnumerator (1, 1);
} catch (ArgumentException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "out-of-range index error not thrown");
}
{
String [] s1 = { "this", "is", "a", "test" };
ArrayList al1 = new ArrayList (s1);
IEnumerator en = al1.GetEnumerator ();
Assert.IsNotNull (en, "No enumerator");
for (int i = 0; i < s1.Length; i++) {
en.MoveNext ();
Assert.AreEqual (al1 [i], en.Current, "Not enumerating");
}
}
{
String [] s1 = { "this", "is", "a", "test" };
ArrayList al1 = new ArrayList (s1);
IEnumerator en = al1.GetEnumerator (1, 2);
Assert.IsNotNull (en, "No enumerator");
for (int i = 0; i < 2; i++) {
en.MoveNext ();
Assert.AreEqual (al1 [i + 1], en.Current, "Not enumerating");
}
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetEnumerator_IndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.GetEnumerator (Int32.MaxValue, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetEnumerator_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.GetEnumerator (0, Int32.MaxValue);
}
[Test]
public void TestGetRange ()
{
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList ();
ArrayList b = a.GetRange (-1, 1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative index error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList ();
ArrayList b = a.GetRange (1, -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative index error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList ();
ArrayList b = a.GetRange (1, 1);
} catch (ArgumentException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "out-of-range index error not thrown");
}
{
char [] chars = { 'a', 'b', 'c', 'd', 'e', 'f' };
ArrayList a = new ArrayList (chars);
ArrayList b = a.GetRange (1, 3);
Assert.AreEqual (3, b.Count, "GetRange returned wrong size ArrayList");
for (int i = 0; i < b.Count; i++) {
Assert.AreEqual (chars [i + 1], b [i], "range didn't work");
}
a [2] = '?'; // should screw up ArrayList b.
bool errorThrown = false;
try {
int i = b.Count;
} catch (InvalidOperationException) {
errorThrown = true;
}
Assert.AreEqual (true, errorThrown, "Munging 'a' should mess up 'b'");
}
{
char [] chars = { 'a', 'b', 'c', 'd', 'e', 'f' };
ArrayList a = new ArrayList (chars);
ArrayList b = a.GetRange (3, 3);
object [] obj_chars = b.ToArray ();
for (int i = 0; i < 3; i++) {
char c = (char) obj_chars [i];
Assert.AreEqual (chars [i + 3], c, "range.ToArray didn't work");
}
char [] new_chars = (char []) b.ToArray (typeof (char));
for (int i = 0; i < 3; i++) {
Assert.AreEqual (chars [i + 3], new_chars [i], "range.ToArray with type didn't work");
}
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetRange_IndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.GetRange (Int32.MaxValue, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void GetRange_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.GetRange (0, Int32.MaxValue);
}
[Test]
public void TestIndexOf ()
{
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (1);
int i = a.IndexOf ('a', -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative indexof error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (1);
int i = a.IndexOf ('a', 2);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "past-end indexof error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (1);
int i = a.IndexOf ('a', 0, -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative indexof error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (1);
int i = a.IndexOf ('a', 0, 2);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "past-end indexof error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (2);
int i = a.IndexOf ('a', 1, 2);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "past-end indexof error not thrown");
}
{
char [] c = { 'a', 'b', 'c', 'd', 'e' };
ArrayList a = new ArrayList (c);
Assert.AreEqual (-1, a.IndexOf (null), "never find null");
Assert.AreEqual (-1, a.IndexOf (null, 0), "never find null");
Assert.AreEqual (-1, a.IndexOf (null, 0, 5), "never find null");
Assert.AreEqual (2, a.IndexOf ('c'), "can't find elem");
Assert.AreEqual (2, a.IndexOf ('c', 2), "can't find elem");
Assert.AreEqual (2, a.IndexOf ('c', 2, 2), "can't find elem");
Assert.AreEqual (-1, a.IndexOf ('c', 3, 2), "shouldn't find elem");
Assert.AreEqual (-1, a.IndexOf ('?'), "shouldn't find");
Assert.AreEqual (-1, a.IndexOf (3), "shouldn't find");
}
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void IndexOf_StartIndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.IndexOf ('a', Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void IndexOf_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.IndexOf ('a', 1, Int32.MaxValue);
}
[Test]
public void TestInsert ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList ());
al1.Insert (0, "Hi!");
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "insert to fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList ());
al1.Insert (0, "Hi!");
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "insert to read only error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.Insert (-1, "Hi!");
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "insert to read only error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.Insert (4, "Hi!");
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "insert to read only error not thrown");
}
{
ArrayList al1 = new ArrayList ();
Assert.AreEqual (0, al1.Count, "arraylist starts empty");
al1.Insert (0, 'a');
al1.Insert (1, 'b');
al1.Insert (0, 'c');
Assert.AreEqual (3, al1.Count, "arraylist needs stuff");
Assert.AreEqual ('c', al1 [0], "arraylist got stuff");
Assert.AreEqual ('a', al1 [1], "arraylist got stuff");
Assert.AreEqual ('b', al1 [2], "arraylist got stuff");
}
}
[Test]
public void TestInsertRange ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList ());
string [] s = { "Hi!" };
al1.InsertRange (0, s);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "insert to fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList ());
string [] s = { "Hi!" };
al1.InsertRange (0, s);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "insert to read only error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
string [] s = { "Hi!" };
al1.InsertRange (-1, s);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "negative index insert error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
string [] s = { "Hi!" };
al1.InsertRange (4, s);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "out-of-range insert error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.InsertRange (0, null);
} catch (ArgumentNullException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "null insert error not thrown");
}
{
char [] c = { 'a', 'b', 'c' };
ArrayList a = new ArrayList (c);
a.InsertRange (1, c);
Assert.AreEqual ('a', a [0], "bad insert 1");
Assert.AreEqual ('a', a [1], "bad insert 2");
Assert.AreEqual ('b', a [2], "bad insert 3");
Assert.AreEqual ('c', a [3], "bad insert 4");
Assert.AreEqual ('b', a [4], "bad insert 5");
Assert.AreEqual ('c', a [5], "bad insert 6");
}
}
[Test]
public void TestLastIndexOf ()
{
//{
//bool errorThrown = false;
//try {
//ArrayList a = new ArrayList(1);
//int i = a.LastIndexOf('a', -1);
//} catch (ArgumentOutOfRangeException) {
//errorThrown = true;
//}
//Assert.IsTrue (//errorThrown, "first negative lastindexof error not thrown");
//}
{
bool errorThrown = false;
try {
ArrayList a = new ArrayList (1);
int i = a.LastIndexOf ('a', 2);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "past-end lastindexof error not thrown");
}
//{
//bool errorThrown = false;
//try {
//ArrayList a = new ArrayList(1);
//int i = a.LastIndexOf('a', 0, -1);
//} catch (ArgumentOutOfRangeException) {
//errorThrown = true;
//}
//Assert.IsTrue (//errorThrown, "second negative lastindexof error not thrown");
//}
//{
//bool errorThrown = false;
//try {
//ArrayList a = new ArrayList(1);
//int i = a.LastIndexOf('a', 0, 2);
//} catch (ArgumentOutOfRangeException) {
//errorThrown = true;
//}
//Assert.IsTrue (//errorThrown, "past-end lastindexof error not thrown");
//}
//{
//bool errorThrown = false;
//try {
//ArrayList a = new ArrayList(2);
//int i = a.LastIndexOf('a', 0, 2);
//} catch (ArgumentOutOfRangeException) {
//errorThrown = true;
//}
//Assert.IsTrue (//errorThrown, "past-end lastindexof error not thrown");
//}
int iTest = 0;
try {
char [] c = { 'a', 'b', 'c', 'd', 'e' };
ArrayList a = new ArrayList (c);
Assert.AreEqual (-1, a.LastIndexOf (null), "never find null");
iTest++;
Assert.AreEqual (-1, a.LastIndexOf (null, 4), "never find null");
iTest++;
Assert.AreEqual (-1, a.LastIndexOf (null, 4, 5), "never find null");
iTest++;
Assert.AreEqual (2, a.LastIndexOf ('c'), "can't find elem");
iTest++;
Assert.AreEqual (2, a.LastIndexOf ('c', 4), "can't find elem");
iTest++;
Assert.AreEqual (2, a.LastIndexOf ('c', 3, 2), "can't find elem");
iTest++;
Assert.AreEqual (-1, a.LastIndexOf ('c', 4, 2), "shouldn't find elem");
iTest++;
Assert.AreEqual (-1, a.LastIndexOf ('?'), "shouldn't find");
iTest++;
Assert.AreEqual (-1, a.LastIndexOf (1), "shouldn't find");
} catch (Exception e) {
Assert.Fail ("Unexpected exception caught when iTest=" + iTest + ". e=" + e);
}
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void LastIndexOf_StartIndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.LastIndexOf ('a', Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void LastIndexOf_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.LastIndexOf ('a', 1, Int32.MaxValue);
}
[Test]
public void TestReadOnly ()
{
{
bool errorThrown = false;
try {
ArrayList al1 = ArrayList.ReadOnly (null);
} catch (ArgumentNullException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "null arg error not thrown");
}
{
ArrayList al1 = new ArrayList ();
Assert.AreEqual (false, al1.IsReadOnly, "arrays start writeable.");
ArrayList al2 = ArrayList.ReadOnly (al1);
Assert.AreEqual (true, al2.IsReadOnly, "should be readonly.");
}
}
[Test]
public void TestRemove ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList (3));
al1.Remove (1);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "remove fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList (3));
al1.Remove (1);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "remove read only error not thrown");
}
{
char [] c = { 'a', 'b', 'c' };
ArrayList a = new ArrayList (c);
a.Remove (1);
a.Remove ('?');
Assert.AreEqual (c.Length, a.Count, "should be unchanged");
a.Remove ('a');
Assert.AreEqual (2, a.Count, "should be changed");
Assert.AreEqual ('b', a [0], "should have shifted");
Assert.AreEqual ('c', a [1], "should have shifted");
}
}
[Test]
public void TestRemoveAt ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList (3));
al1.RemoveAt (1);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "remove from fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList (3));
al1.RemoveAt (1);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "remove from read only error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.RemoveAt (-1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "remove at negative index error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.RemoveAt (4);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "remove at out-of-range index error not thrown");
}
{
char [] c = { 'a', 'b', 'c' };
ArrayList a = new ArrayList (c);
a.RemoveAt (0);
Assert.AreEqual (2, a.Count, "should be changed");
Assert.AreEqual ('b', a [0], "should have shifted");
Assert.AreEqual ('c', a [1], "should have shifted");
}
}
[Test]
public void TestRemoveRange ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.FixedSize (new ArrayList (3));
al1.RemoveRange (0, 1);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "removerange from fixed size error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList (3));
al1.RemoveRange (0, 1);
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "removerange from read only error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.RemoveRange (-1, 1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "removerange at negative index error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.RemoveRange (0, -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "removerange at negative index error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.RemoveRange (2, 3);
} catch (ArgumentException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "removerange at bad range error not thrown");
}
{
char [] c = { 'a', 'b', 'c' };
ArrayList a = new ArrayList (c);
a.RemoveRange (1, 2);
Assert.AreEqual (1, a.Count, "should be changed");
Assert.AreEqual ('a', a [0], "should have shifted");
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void RemoveRange_IndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.RemoveRange (Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void RemoveRange_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.RemoveRange (1, Int32.MaxValue);
}
[Test]
public void TestRepeat ()
{
{
bool errorThrown = false;
try {
ArrayList al1 = ArrayList.Repeat ('c', -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "repeat negative copies error not thrown");
}
{
ArrayList al1 = ArrayList.Repeat ("huh?", 0);
Assert.AreEqual (0, al1.Count, "should be nothing in array");
}
{
ArrayList al1 = ArrayList.Repeat ("huh?", 3);
Assert.AreEqual (3, al1.Count, "should be something in array");
Assert.AreEqual ("huh?", al1 [0], "array elem doesn't check");
Assert.AreEqual ("huh?", al1 [1], "array elem doesn't check");
Assert.AreEqual ("huh?", al1 [2], "array elem doesn't check");
}
}
[Test]
public void TestReverse ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList ());
al1.Reverse ();
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "reverse on read only error not thrown");
}
{
bool errorThrown = false;
try {
char [] c = new Char [2];
ArrayList al1 = new ArrayList (c);
al1.Reverse (0, 3);
} catch (ArgumentException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "error not thrown");
}
{
bool errorThrown = false;
try {
char [] c = new Char [2];
ArrayList al1 = new ArrayList (c);
al1.Reverse (3, 0);
} catch (ArgumentException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "error not thrown");
}
{
char [] c = { 'a', 'b', 'c', 'd', 'e' };
ArrayList al1 = new ArrayList (c);
al1.Reverse (2, 1);
for (int i = 0; i < al1.Count; i++) {
Assert.AreEqual (c [i], al1 [i], "Should be no change yet");
}
al1.Reverse ();
for (int i = 0; i < al1.Count; i++) {
Assert.AreEqual (c [i], al1 [4 - i], "Should be reversed");
}
al1.Reverse ();
for (int i = 0; i < al1.Count; i++) {
Assert.AreEqual (c [i], al1 [i], "Should be back to normal");
}
al1.Reverse (1, 3);
Assert.AreEqual (c [0], al1 [0], "Should be back to normal");
Assert.AreEqual (c [3], al1 [1], "Should be back to normal");
Assert.AreEqual (c [2], al1 [2], "Should be back to normal");
Assert.AreEqual (c [1], al1 [3], "Should be back to normal");
Assert.AreEqual (c [4], al1 [4], "Should be back to normal");
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Reverse_IndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.Reverse (Int32.MaxValue, 1);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Reverse_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.Reverse (1, Int32.MaxValue);
}
[Test]
public void TestSetRange ()
{
{
bool errorThrown = false;
try {
char [] c = { 'a', 'b', 'c' };
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList (3));
al1.SetRange (0, c);
} catch (NotSupportedException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 1: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "setrange on read only error not thrown");
}
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.SetRange (0, null);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 2: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "setrange with null error not thrown");
}
{
bool errorThrown = false;
try {
char [] c = { 'a', 'b', 'c' };
ArrayList al1 = new ArrayList (3);
al1.SetRange (-1, c);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 3: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "setrange with negative index error not thrown");
}
{
bool errorThrown = false;
try {
char [] c = { 'a', 'b', 'c' };
ArrayList al1 = new ArrayList (3);
al1.SetRange (2, c);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
} catch (Exception e) {
Assert.Fail ("Incorrect exception thrown at 4: " + e.ToString ());
}
Assert.IsTrue (errorThrown, "setrange with too much error not thrown");
}
{
char [] c = { 'a', 'b', 'c' };
ArrayList al1 = ArrayList.Repeat ('?', 3);
Assert.IsTrue (c [0] != (char) al1 [0], "no match yet");
Assert.IsTrue (c [1] != (char) al1 [1], "no match yet");
Assert.IsTrue (c [2] != (char) al1 [2], "no match yet");
al1.SetRange (0, c);
Assert.AreEqual (c [0], al1 [0], "should match");
Assert.AreEqual (c [1], al1 [1], "should match");
Assert.AreEqual (c [2], al1 [2], "should match");
}
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void SetRange_Overflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.SetRange (Int32.MaxValue, new ArrayList ());
}
[Test]
public void TestInsertRange_this ()
{
String [] s1 = { "this", "is", "a", "test" };
ArrayList al = new ArrayList (s1);
al.InsertRange (2, al);
String [] s2 = { "this", "is", "this", "is", "a", "test", "a", "test" };
for (int i = 0; i < al.Count; i++) {
Assert.AreEqual (s2 [i], al [i], "at i=" + i);
}
}
[Test]
public void TestSort ()
{
{
bool errorThrown = false;
try {
ArrayList al1 =
ArrayList.ReadOnly (new ArrayList ());
al1.Sort ();
} catch (NotSupportedException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "sort on read only error not thrown");
}
{
char [] starter = { 'd', 'b', 'f', 'e', 'a', 'c' };
ArrayList al1 = new ArrayList (starter);
al1.Sort ();
Assert.AreEqual ('a', al1 [0], "Should be sorted");
Assert.AreEqual ('b', al1 [1], "Should be sorted");
Assert.AreEqual ('c', al1 [2], "Should be sorted");
Assert.AreEqual ('d', al1 [3], "Should be sorted");
Assert.AreEqual ('e', al1 [4], "Should be sorted");
Assert.AreEqual ('f', al1 [5], "Should be sorted");
}
{
ArrayList al1 = new ArrayList ();
al1.Add (null);
al1.Add (null);
al1.Add (32);
al1.Add (33);
al1.Add (null);
al1.Add (null);
al1.Sort ();
Assert.AreEqual (null, al1 [0], "Should be null (0)");
Assert.AreEqual (null, al1 [1], "Should be null (1)");
Assert.AreEqual (null, al1 [2], "Should be null (2)");
Assert.AreEqual (null, al1 [3], "Should be null (3)");
Assert.AreEqual (32, al1 [4], "Should be 32");
Assert.AreEqual (33, al1 [5], "Should be 33");
}
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Sort_IndexOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.Sort (Int32.MaxValue, 1, null);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Sort_CountOverflow ()
{
ArrayList al = new ArrayList ();
al.Add (this);
al.Sort (1, Int32.MaxValue, null);
}
// TODO - Sort with IComparers
// TODO - Synchronize
[Test]
public void TestToArray ()
{
{
bool errorThrown = false;
try {
ArrayList al1 = new ArrayList (3);
al1.ToArray (null);
} catch (ArgumentNullException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "toarray with null error not thrown");
}
{
bool errorThrown = false;
try {
char [] c = { 'a', 'b', 'c' };
string s = "huh?";
ArrayList al1 = new ArrayList (c);
al1.ToArray (s.GetType ());
} catch (InvalidCastException) {
errorThrown = true;
}
Assert.IsTrue (errorThrown, "toarray with bad type error not thrown");
}
{
char [] c1 = { 'a', 'b', 'c', 'd', 'e' };
ArrayList al1 = new ArrayList (c1);
object [] o2 = al1.ToArray ();
for (int i = 0; i < c1.Length; i++) {
Assert.AreEqual (c1 [i], o2 [i], "should be copy");
}
Array c2 = al1.ToArray (c1 [0].GetType ());
for (int i = 0; i < c1.Length; i++) {
Assert.AreEqual (c1 [i], c2.GetValue (i), "should be copy");
}
}
}
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void TrimToSize_ReadOnly ()
{
ArrayList al1 = ArrayList.ReadOnly (new ArrayList ());
al1.TrimToSize ();
}
[Test]
public void TrimToSize ()
{
ArrayList al1 = new ArrayList ();
#if NET_2_0
// Capacity is 0 under 2.0
int capacity = 4;
#else
int capacity = al1.Capacity;
#endif
int size = capacity / 2;
for (int i = 1; i <= size; i++) {
al1.Add ('?');
}
al1.RemoveAt (0);
al1.TrimToSize ();
Assert.AreEqual (size - 1, al1.Capacity, "no capacity match");
al1.Clear ();
al1.TrimToSize ();
Assert.AreEqual (capacity, al1.Capacity, "no default capacity");
}
class Comparer : IComparer
{
private bool called = false;
public bool Called
{
get
{
bool result = called;
called = false;
return called;
}
}
public int Compare (object x, object y)
{
called = true;
return 0;
}
}
[Test]
public void BinarySearch1_EmptyList ()
{
ArrayList list = new ArrayList ();
Assert.AreEqual (-1, list.BinarySearch (0), "BinarySearch");
}
[Test]
public void BinarySearch2_EmptyList ()
{
Comparer comparer = new Comparer ();
ArrayList list = new ArrayList ();
Assert.AreEqual (-1, list.BinarySearch (0, comparer), "BinarySearch");
// bug 77030 - the comparer isn't called for an empty array/list
Assert.IsTrue (!comparer.Called, "Called");
}
[Test]
public void BinarySearch3_EmptyList ()
{
Comparer comparer = new Comparer ();
ArrayList list = new ArrayList ();
Assert.AreEqual (-1, list.BinarySearch (0, 0, 0, comparer), "BinarySearch");
// bug 77030 - the comparer isn't called for an empty array/list
Assert.IsTrue (!comparer.Called, "Called");
}
[Test]
#if ONLY_1_1
[Category ("NotDotNet")] // MS bug
#endif
public void AddRange_GetRange ()
{
ArrayList source = ArrayList.Adapter (new object [] { "1", "2" });
Assert.AreEqual (2, source.Count, "#1");
Assert.AreEqual ("1", source [0], "#2");
Assert.AreEqual ("2", source [1], "#3");
ArrayList range = source.GetRange (1, 1);
Assert.AreEqual (1, range.Count, "#4");
Assert.AreEqual ("2", range [0], "#5");
ArrayList target = new ArrayList ();
target.AddRange (range);
Assert.AreEqual (1, target.Count, "#6");
Assert.AreEqual ("2", target [0], "#7");
}
[Test]
#if ONLY_1_1
[Category ("NotDotNet")] // MS bug
#endif
public void IterateSelf ()
{
ArrayList list = new ArrayList ();
list.Add (list);
IEnumerator enumerator = list.GetEnumerator ();
Assert.IsTrue (enumerator.MoveNext (), "#1");
Assert.IsTrue (object.ReferenceEquals (list, enumerator.Current), "#2");
Assert.IsTrue (!enumerator.MoveNext (), "#3");
}
}
}
| 27.400857 | 91 | 0.589008 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/corlib/Test/System.Collections/ArrayListTest.cs | 51,130 | C# |
// <copyright file="GameContext.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.GameLogic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
using MUnique.OpenMU.GameLogic.MiniGames;
using MUnique.OpenMU.GameLogic.PlugIns;
using MUnique.OpenMU.GameLogic.Views;
using MUnique.OpenMU.Interfaces;
using MUnique.OpenMU.Persistence;
using MUnique.OpenMU.PlugIns;
/// <summary>
/// The game context which holds all data of the game together.
/// </summary>
public class GameContext : Disposable, IGameContext
{
private readonly Dictionary<ushort, GameMap> _mapList = new ();
private readonly Dictionary<MiniGameMapKey, MiniGameContext> _miniGames = new ();
private readonly Timer _recoverTimer;
private readonly IMapInitializer _mapInitializer;
private readonly Timer _tasksTimer;
private readonly SemaphoreSlim _playerListLock = new (1);
/// <summary>
/// Keeps the list of all players.
/// </summary>
private readonly List<Player> _playerList = new ();
/// <summary>
/// Initializes a new instance of the <see cref="GameContext" /> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <param name="persistenceContextProvider">The persistence context provider.</param>
/// <param name="mapInitializer">The map initializer.</param>
/// <param name="loggerFactory">The logger factory.</param>
/// <param name="plugInManager">The plug in manager.</param>
/// <param name="dropGenerator">The drop generator.</param>
public GameContext(GameConfiguration configuration, IPersistenceContextProvider persistenceContextProvider, IMapInitializer mapInitializer, ILoggerFactory loggerFactory, PlugInManager plugInManager, IDropGenerator dropGenerator)
{
try
{
this.Configuration = configuration;
this.PersistenceContextProvider = persistenceContextProvider;
this.PlugInManager = plugInManager;
this._mapInitializer = mapInitializer;
this.LoggerFactory = loggerFactory;
this.DropGenerator = dropGenerator;
this.ItemPowerUpFactory = new ItemPowerUpFactory(loggerFactory.CreateLogger<ItemPowerUpFactory>());
this._recoverTimer = new Timer(this.RecoverTimerElapsed, null, this.Configuration.RecoveryInterval, this.Configuration.RecoveryInterval);
this._tasksTimer = new Timer(this.ExecutePeriodicTasks, null, 1000, 1000);
this.FeaturePlugIns = new FeaturePlugInContainer(this.PlugInManager);
}
catch (Exception ex)
{
loggerFactory.CreateLogger<GameContext>().LogError(ex, "Unexpected error in constructor of GameContext.");
throw;
}
}
/// <summary>
/// Occurs when a game map got created.
/// </summary>
public event EventHandler<GameMap>? GameMapCreated;
/// <summary>
/// Occurs when a game map got removed.
/// </summary>
/// <remarks>
/// Currently, maps are never removed.
/// It may make sense to remove unused maps after a certain period.
/// </remarks>
public event EventHandler<GameMap>? GameMapRemoved;
/// <inheritdoc />
public virtual float ExperienceRate => this.Configuration.ExperienceRate;
/// <summary>
/// Gets the initialized maps which are hosted on this context.
/// </summary>
public IEnumerable<GameMap> Maps => this._mapList.Values;
/// <inheritdoc/>
public GameConfiguration Configuration { get; }
/// <inheritdoc/>
public PlugInManager PlugInManager { get; }
/// <inheritdoc/>
public IDropGenerator DropGenerator { get; }
/// <inheritdoc />
public FeaturePlugInContainer FeaturePlugIns { get; }
/// <inheritdoc/>
public IItemPowerUpFactory ItemPowerUpFactory { get; }
/// <inheritdoc/>
public IPersistenceContextProvider PersistenceContextProvider { get; }
/// <summary>
/// Gets the players by character name dictionary.
/// </summary>
public IDictionary<string, Player> PlayersByCharacterName { get; } = new ConcurrentDictionary<string, Player>();
/// <inheritdoc />
public ILoggerFactory LoggerFactory { get; }
/// <inheritdoc />
public int PlayerCount => this._playerList.Count;
/// <inheritdoc/>
public GameMap? GetMap(ushort mapId, bool createIfNotExists = true)
{
if (this._mapList.TryGetValue(mapId, out var map))
{
return map;
}
if (!createIfNotExists)
{
return null;
}
GameMap? createdMap;
lock (this._mapInitializer)
{
if (this._mapList.TryGetValue(mapId, out map))
{
return map;
}
createdMap = this._mapInitializer.CreateGameMap(mapId);
if (createdMap is null)
{
return null;
}
this._mapList.Add(mapId, createdMap);
createdMap.ObjectAdded += (sender, args) => this.PlugInManager.GetPlugInPoint<IObjectAddedToMapPlugIn>()?.ObjectAddedToMap(args.Map, args.Object);
createdMap.ObjectRemoved += (sender, args) => this.PlugInManager.GetPlugInPoint<IObjectRemovedFromMapPlugIn>()?.ObjectRemovedFromMap(args.Map, args.Object);
}
// ReSharper disable once InconsistentlySynchronizedField it's desired behavior to initialize the map outside the lock to keep locked timespan short.
this._mapInitializer.InitializeState(createdMap);
this.GameMapCreated?.Invoke(this, createdMap);
return createdMap;
}
/// <summary>
/// Gets the mini game map which is meant to be hosted by the game.
/// </summary>
/// <param name="miniGameDefinition">The mini game definition.</param>
/// <param name="requester">The requesting player.</param>
/// <returns>The hosted mini game instance.</returns>
public MiniGameContext GetMiniGame(MiniGameDefinition miniGameDefinition, Player requester)
{
var miniGameKey = MiniGameMapKey.Create(miniGameDefinition, requester);
if (this._miniGames.TryGetValue(miniGameKey, out var miniGameContext))
{
return miniGameContext;
}
lock (this._mapInitializer)
{
if (this._miniGames.TryGetValue(miniGameKey, out miniGameContext))
{
return miniGameContext;
}
switch (miniGameDefinition.Type)
{
case MiniGameType.DevilSquare:
miniGameContext = new DevilSquareContext(miniGameKey, miniGameDefinition, this, this._mapInitializer);
break;
default:
miniGameContext = new MiniGameContext(miniGameKey, miniGameDefinition, this, this._mapInitializer);
break;
}
this._miniGames.Add(miniGameKey, miniGameContext);
}
var createdMap = miniGameContext.Map;
// ReSharper disable once InconsistentlySynchronizedField it's desired behavior to initialize the map outside the lock to keep locked timespan short.
this._mapInitializer.InitializeState(createdMap);
this.GameMapCreated?.Invoke(this, createdMap);
return miniGameContext;
}
/// <inheritdoc />
public void RemoveMiniGame(MiniGameContext miniGameContext)
{
miniGameContext.Dispose();
this._miniGames.Remove(miniGameContext.Key);
}
/// <summary>
/// Adds the player to the game.
/// </summary>
/// <param name="player">The player.</param>
public virtual void AddPlayer(Player player)
{
player.PlayerLeftWorld += this.PlayerLeftWorld;
player.PlayerEnteredWorld += this.PlayerEnteredWorld;
player.PlayerDisconnected += this.PlayerDisconnected;
this._playerListLock.Wait();
try
{
this._playerList.Add(player);
}
finally
{
this._playerListLock.Release();
}
}
/// <summary>
/// Removes the player from the game.
/// </summary>
/// <param name="player">The player.</param>
public virtual void RemovePlayer(Player player)
{
if (player.SelectedCharacter != null)
{
this.PlayersByCharacterName.Remove(player.SelectedCharacter.Name);
}
player.CurrentMap?.Remove(player);
this._playerListLock.Wait();
try
{
this._playerList.Remove(player);
}
finally
{
this._playerListLock.Release();
}
player.PlayerDisconnected -= this.PlayerDisconnected;
player.PlayerEnteredWorld -= this.PlayerEnteredWorld;
player.PlayerLeftWorld -= this.PlayerLeftWorld;
}
/// <summary>
/// Gets the player by the character name.
/// </summary>
/// <param name="name">The character name.</param>
/// <returns>The player by character name.</returns>
public Player? GetPlayerByCharacterName(string name)
{
this.PlayersByCharacterName.TryGetValue(name, out var player);
return player;
}
/// <inheritdoc />
public void ForEachPlayer(Action<Player> action)
{
if (this._playerList.Count == 0)
{
return;
}
this._playerListLock.Wait();
try
{
for (int i = this._playerList.Count - 1; i >= 0; --i)
{
var player = this._playerList[i];
action(player);
}
}
finally
{
this._playerListLock.Release();
}
}
/// <inheritdoc/>
public void SendGlobalMessage(string message, MessageType messageType)
{
this.ForEachPlayer(player => player.ViewPlugIns.GetPlugIn<IShowMessagePlugIn>()?.ShowMessage(message, messageType));
}
/// <inheritdoc/>
public void SendGlobalNotification(string message)
{
var regex = new Regex(Regex.Escape("!"));
var sendingMessage = regex.Replace(message, string.Empty, 1);
this.SendGlobalMessage(sendingMessage, MessageType.GoldenCenter);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this._recoverTimer.Dispose();
this._tasksTimer.Dispose();
}
private void ExecutePeriodicTasks(object? state)
{
try
{
this.PlugInManager.GetPlugInPoint<IPeriodicTaskPlugIn>()?.ExecuteTask(this);
}
catch (Exception ex)
{
Debug.Fail(ex.Message, ex.StackTrace);
}
}
private void RecoverTimerElapsed(object? state)
{
this.ForEachPlayer(player =>
{
if (player.SelectedCharacter != null && player.PlayerState.CurrentState == PlayerState.EnteredWorld)
{
player.Regenerate();
}
});
}
private void PlayerDisconnected(object? sender, EventArgs e)
{
if (sender is not Player player)
{
return;
}
this.RemovePlayer(player);
}
private void PlayerEnteredWorld(object? sender, EventArgs e)
{
if (sender is not Player player)
{
return;
}
this.PlayersByCharacterName.Add(player.SelectedCharacter!.Name, player);
}
private void PlayerLeftWorld(object? sender, EventArgs e)
{
if (sender is not Player player)
{
return;
}
this.PlayersByCharacterName.Remove(player.SelectedCharacter!.Name);
}
} | 32.127717 | 232 | 0.633257 | [
"MIT"
] | ADMTec/OpenMU | src/GameLogic/GameContext.cs | 11,825 | C# |
using System;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
using HtmlAgilityPack;
public static class DoubanSpider
{
public static BookRecord[] Request(string isbn)
{
var url = "https://www.douban.com/search?q=" + isbn;
BookRecord[] ret;
var web = new HtmlWeb();
// 从搜索页面获取书目页面的url
var doc = web.Load(url);
HtmlNodeCollection detailNodes = doc.DocumentNode.SelectNodes("//div[@class='result']");
if(detailNodes == null) return new BookRecord[0];
ret = new BookRecord[detailNodes.Count];
var index = 0;
foreach(HtmlNode node in detailNodes){
BookRecord bookDetail = new BookRecord();
bookDetail.name = node.SelectSingleNode("//div[@class='title']//a").InnerText;
bookDetail.imageUrl = node.SelectSingleNode("//div[@class='pic']//img").Attributes["src"].Value;
bookDetail.detailUrl = node.SelectSingleNode("//a[@class='nbg']").Attributes["href"].Value;
bookDetail.isbn = isbn;
var author_publisher = node.SelectSingleNode("//span[@class='subject-cast']").InnerText.Split('/');
bookDetail.author = author_publisher[0].Trim();
bookDetail.publisher = author_publisher.Length > 1 ? author_publisher[1].Trim():"";
ret[index] = bookDetail;
index++;
}
return ret;
}
// 从书目页面获取信息
// public static void RequestDetail(string detailUrl)
// {
// // 从搜索页面获取书目页面的url
// var web = new HtmlWeb();
// var doc = web.Load(detailUrl);
// var author = doc.DocumentNode.SelectSingleNode("//meta[@property='book:author']").Attributes["content"].Value;
// var author = doc.DocumentNode.SelectSingleNode("//span[@class='pl']").Attributes["content"].Value;
// }
} | 36.846154 | 122 | 0.596555 | [
"MIT"
] | flyingSnow-hu/personal-library | Assets/Scripts/DoubanSpider.cs | 1,982 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nimbus.StressTests.ThroughputTests.MessageContracts;
using NUnit.Framework;
namespace Nimbus.StressTests.ThroughputTests
{
[TestFixture]
public class WhenSendingManyLargeCommandsOfTheSameType : ThroughputSpecificationForBus
{
protected override int NumMessagesToSend
{
get { return 1000; }
}
protected override int ExpectedMessagesPerSecond
{
get { return 50; }
}
public override IEnumerable<Task> SendMessages(IBus bus)
{
for (var i = 0; i < NumMessagesToSend; i++)
{
var command = new FooCommand
{
SomeMessage = new string(Enumerable.Range(0, 32*1024).Select(j => '.').ToArray()),
};
yield return bus.Send(command);
Console.Write(".");
}
Console.WriteLine();
}
}
} | 29.054054 | 116 | 0.556279 | [
"MIT"
] | sbalkum/Nimbus | src/Tests/Nimbus.StressTests/ThroughputTests/WhenSendingManyLargeCommandsOfTheSameType.cs | 1,077 | C# |
/*
* Copyright 2018 Andrey Lemin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using UnityEngine;
namespace Assets.PseudoCardboard.Scripts
{
/// Для VR-представления применяется вершинные шейдеры с заданными процедурными мешами.
/// Меши представляют собой равномерные полигональные сетки и располагаются на сцене, частично перекрывая друг друга.
/// Изображения с камер сохраняются в текстуры, которых натягиваются на меши.
/// Если пользователь без линз посмотрит левым глазом на левый меш, а правым на правый, то получится в точности та картинка, которую пользователь должен увидеть в шлеме с линзами (после всех коррекций)
/// Меш обрабатывается вершинным шейдером, который производит коррекцию дисторсии, меняя координату z у вершин мешей, меш становится объёмным
/// На обработанные меши "смотрит" другая пара камер, поле зрения которых соответсвует параметрам глаз пользоватля в HMD
/// Метод использует пять камеры и две поверхности, но даёт максимально наглядную иллюстрацию работающего принципа
[ExecuteInEditMode]
public class VrCameraBiMesh : MonoBehaviour
{
public Material EyeMaterialLeft;
public Material EyeMaterialRight;
[SerializeField]
private Camera _camWorldLeft;
private FovScaler _camWorldLeftScaler;
[SerializeField]
private Camera _camWorldRight;
private FovScaler _camWorldRightScaler;
[SerializeField]
private Camera _camEyeLeft;
[SerializeField]
private Camera _camEyeRight;
private bool _hmdParamsDirty = true;
private DisplayParameters _display;
void OnEnable()
{
_display = null;
_camWorldLeft.transform.localRotation = Quaternion.identity;
_camWorldRight.transform.localRotation = Quaternion.identity;
_camWorldLeftScaler = _camWorldLeft.GetComponentInChildren<FovScaler>();
_camWorldRightScaler = _camWorldRight.GetComponentInChildren<FovScaler>();
_camEyeLeft.transform.localRotation = Quaternion.identity;
_camEyeRight.transform.localRotation = Quaternion.identity;
OnHmdParamsChanged(HmdParameters.Instance);
HmdParameters.Instance.ParamsChanged.AddListener(OnHmdParamsChanged);
}
void OnDisable()
{
HmdParameters.Instance.ParamsChanged.RemoveListener(OnHmdParamsChanged);
}
void OnHmdParamsChanged(HmdParameters hmd)
{
_hmdParamsDirty = true;
}
void Update()
{
DisplayParameters newDisplay = DisplayParameters.Collect();
if (_hmdParamsDirty || !newDisplay.Equals(_display))
{
UpdateViewAndMaterialParameters(HmdParameters.Instance, newDisplay);
_hmdParamsDirty = false;
_display = newDisplay;
}
}
void UpdateViewAndMaterialParameters(HmdParameters hmd, DisplayParameters display)
{
Distortion distortion = new Distortion(hmd.DistortionK1, hmd.DistortionK2);
distortion.DistortionK1 = hmd.DistortionK1;
distortion.DistortionK2 = hmd.DistortionK2;
float zNear = _camWorldLeft.nearClipPlane;
float zFar = _camWorldLeft.farClipPlane;
Fov displayDistancesLeft = Calculator.GetFovDistancesLeft(display, hmd);
// То, как должен видеть левый глаз свой кусок экрана. Без линзы. C учётом только размеров дисплея
Fov fovDisplayTanAngles = displayDistancesLeft / hmd.ScreenToLensDist;
// FoV шлема
Fov hmdMaxFovTanAngles = Fov.AnglesToTanAngles(hmd.MaxFovAngles);
// То, как должен видеть левый глаз свой кусок экрана. Без линзы. C учётом размеров дисплея и FoV шлема
Fov fovEyeTanAglesLeft = Fov.Min(fovDisplayTanAngles, hmdMaxFovTanAngles);
// То, как должен видеть левый глаз. Мнимое изображение (после увеличения идеальной линзой без искажений). С широким углом. Именно так надо снять сцену
Fov fovWorldTanAnglesLeft = Calculator.DistortTanAngles(fovEyeTanAglesLeft, distortion);
Matrix4x4 projWorldLeft;
Matrix4x4 projWorldRight;
Calculator.ComposeProjectionMatricesFromFovTanAngles(fovWorldTanAnglesLeft, zNear, zFar, out projWorldLeft, out projWorldRight);
Matrix4x4 projEyeLeft;
Matrix4x4 projEyeRight;
Calculator.ComposeProjectionMatricesFromFovTanAngles(fovDisplayTanAngles, zNear, zFar, out projEyeLeft, out projEyeRight);
_camWorldLeft.transform.localPosition = 0.5f * Vector3.left * hmd.InterlensDistance;
_camWorldRight.transform.localPosition = 0.5f * Vector3.right * hmd.InterlensDistance;
_camEyeLeft.transform.localPosition = 0.5f * Vector3.left * hmd.InterlensDistance;
_camEyeRight.transform.localPosition = 0.5f * Vector3.right * hmd.InterlensDistance;
_camWorldLeft.projectionMatrix = projWorldLeft;
_camWorldRight.projectionMatrix = projWorldRight;
_camWorldLeftScaler.SetFov(fovWorldTanAnglesLeft);
_camWorldRightScaler.SetFov(fovWorldTanAnglesLeft.GetFlippedHorizontally());
_camEyeLeft.projectionMatrix = projEyeLeft;
_camEyeRight.projectionMatrix = projEyeRight;
EyeMaterialLeft.SetFloat("_DistortionK1", hmd.DistortionK1);
EyeMaterialRight.SetFloat("_DistortionK1", hmd.DistortionK1);
EyeMaterialLeft.SetFloat("_DistortionK2", hmd.DistortionK2);
EyeMaterialRight.SetFloat("_DistortionK2", hmd.DistortionK2);
}
}
}
| 41.616438 | 206 | 0.7184 | [
"Apache-2.0"
] | Elevator89/PseudoCardboard | Assets/PseudoCardboard/Scripts/VrCameraBiMesh.cs | 6,912 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FirstREST.Lib_Primavera.Model
{
public class LinhaDocVenda
{
public string CodArtigo
{
get;
set;
}
public string DescArtigo
{
get;
set;
}
public string IdCabecDoc
{
get;
set;
}
public double Quantidade
{
get;
set;
}
public string Unidade
{
get;
set;
}
public double Desconto
{
get;
set;
}
public double PrecoUnitario
{
get;
set;
}
public double TotalILiquido
{
get;
set;
}
public double TotalLiquido
{
get;
set;
}
}
} | 15.057143 | 40 | 0.363378 | [
"MIT"
] | rodavoce/SINF-WebStore | musicstore/Lib_Primavera/Model/LinhaDocVenda.cs | 1,056 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime: 4.0.30319.42000
//
// Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si
// el código se vuelve a generar.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Examen.Properties
{
/// <summary>
/// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc.
/// </summary>
// StronglyTypedResourceBuilder generó automáticamente esta clase
// a través de una herramienta como ResGen o Visual Studio.
// Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen
// con la opción /str o recompile su proyecto de VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Examen.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Invalida la propiedad CurrentUICulture del subproceso actual para todas las
/// búsquedas de recursos usando esta clase de recursos fuertemente tipados.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 40.25 | 172 | 0.615252 | [
"MIT"
] | Edgar1975/Edgar.Saavedra | Examen/Examen/Properties/Resources.Designer.cs | 2,911 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// This code was generated by an automated template.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.x86.Instructions
{
/// <summary>
/// MovzxLoad16
/// </summary>
/// <seealso cref="Mosa.Platform.x86.X86Instruction" />
public sealed class MovzxLoad16 : X86Instruction
{
public override int ID { get { return 270; } }
internal MovzxLoad16()
: base(1, 2)
{
}
public override bool IsMemoryRead { get { return true; } }
public override void Emit(InstructionNode node, BaseCodeEmitter emitter)
{
System.Diagnostics.Debug.Assert(node.ResultCount == 1);
System.Diagnostics.Debug.Assert(node.OperandCount == 2);
if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 5) && node.Operand2.IsConstantZero)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b01);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b101);
emitter.OpcodeEncoder.Append8Bits(0x00);
return;
}
if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 5) && node.Operand2.IsCPURegister)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b01);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(node.Operand2.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b101);
emitter.OpcodeEncoder.Append8Bits(0x00);
return;
}
if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 4) && node.Operand2.IsConstantZero)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append3Bits(0b100);
return;
}
if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 4) && (node.Operand2.IsConstant && node.Operand2.ConstantSignedInteger >= -128 && node.Operand2.ConstantSignedInteger <= 127))
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b01);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append8BitImmediate(node.Operand2);
return;
}
if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 4) && node.Operand2.IsConstant)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b10);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append8BitImmediate(node.Operand2);
return;
}
if (node.Operand1.IsCPURegister && node.Operand2.IsCPURegister)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b100);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(node.Operand2.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode);
return;
}
if (node.Operand1.IsCPURegister && node.Operand2.IsConstantZero)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode);
return;
}
if (node.Operand1.IsCPURegister && (node.Operand2.IsConstant && node.Operand2.ConstantSignedInteger >= -128 && node.Operand2.ConstantSignedInteger <= 127))
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b01);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode);
emitter.OpcodeEncoder.Append8BitImmediate(node.Operand2);
return;
}
if (node.Operand1.IsCPURegister && node.Operand2.IsConstant)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b10);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode);
emitter.OpcodeEncoder.Append32BitImmediate(node.Operand2);
return;
}
if (node.Operand1.IsConstant && node.Operand2.IsConstantZero)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b101);
emitter.OpcodeEncoder.Append32BitImmediate(node.Operand1);
return;
}
if (node.Operand1.IsConstant && node.Operand2.IsConstant)
{
emitter.OpcodeEncoder.Append8Bits(0x0F);
emitter.OpcodeEncoder.Append8Bits(0xB7);
emitter.OpcodeEncoder.Append2Bits(0b00);
emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode);
emitter.OpcodeEncoder.Append3Bits(0b101);
emitter.OpcodeEncoder.Append32BitImmediateWithOffset(node.Operand1, node.Operand2);
return;
}
throw new Compiler.Common.Exceptions.CompilerException("Invalid Opcode");
}
}
}
| 38.147239 | 204 | 0.758443 | [
"BSD-3-Clause"
] | marcelocaetano/MOSA-Project | Source/Mosa.Platform.x86/Instructions/MovzxLoad16.cs | 6,218 | C# |
namespace SixLabors.ImageSharp.Benchmarks.General.Vectorization
{
using System.Numerics;
using BenchmarkDotNet.Attributes;
public class DivUInt32
{
private uint[] input;
private uint[] result;
[Params(32)]
public int InputSize { get; set; }
private uint testValue;
[GlobalSetup]
public void Setup()
{
this.input = new uint[this.InputSize];
this.result = new uint[this.InputSize];
this.testValue = 42;
for (int i = 0; i < this.InputSize; i++)
{
this.input[i] = (uint)i;
}
}
[Benchmark(Baseline = true)]
public void Standard()
{
uint v = this.testValue;
for (int i = 0; i < this.input.Length; i++)
{
this.result[i] = this.input[i] / v;
}
}
[Benchmark]
public void Simd()
{
Vector<uint> v = new Vector<uint>(this.testValue);
for (int i = 0; i < this.input.Length; i += Vector<uint>.Count)
{
Vector<uint> a = new Vector<uint>(this.input, i);
a = a / v;
a.CopyTo(this.result, i);
}
}
}
} | 24 | 75 | 0.469907 | [
"Apache-2.0"
] | 4thOffice/ImageSharp | tests/ImageSharp.Benchmarks/General/Vectorization/DivUInt32.cs | 1,296 | C# |
using BusinessLayer;
using BusinessLayer.Storage;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace Battleships.Commands
{
public class ActionCommand : ICommand
{
private readonly Action _action;
private readonly Func<bool> _canExecuteAction;
public ActionCommand(Action action) : this(action, () => true)
{
}
public ActionCommand(Action action, Func<bool> canExecute)
{
_action = action;
_canExecuteAction = canExecute;
}
public Guid Guid { get; set; }
public Field Field { get; set; }
public void Execute(object obj)
{
_action();
}
public bool CanExecute(object obj)
{
return _canExecuteAction();
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
}
remove
{
CommandManager.RequerySuggested -= value;
}
}
}
}
| 22.431373 | 70 | 0.549825 | [
"MIT"
] | Gerfatz/M326 | src/Battleships/Commands/ActionCommand.cs | 1,146 | 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.MachineLearningServices.Models
{
public partial class AuthKeys : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(PrimaryKey))
{
writer.WritePropertyName("primaryKey");
writer.WriteStringValue(PrimaryKey);
}
if (Optional.IsDefined(SecondaryKey))
{
writer.WritePropertyName("secondaryKey");
writer.WriteStringValue(SecondaryKey);
}
writer.WriteEndObject();
}
}
}
| 26.6875 | 63 | 0.614754 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/machinelearningservices/Azure.ResourceManager.MachineLearningServices/src/Generated/Models/AuthKeys.Serialization.cs | 854 | C# |
//
// Mono.Xml.XmlNodeWriter
//
// Author:
// Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
//
// (C)2003 Atsushi Enomoto
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Xml;
namespace System.Xml
{
internal class XmlNodeWriter : XmlWriter
{
public XmlNodeWriter () : this (true)
{
}
// It should be public after some tests are done :-)
public XmlNodeWriter (bool isDocumentEntity)
{
doc = new XmlDocument ();
state = XmlNodeType.None;
this.isDocumentEntity = isDocumentEntity;
if (!isDocumentEntity)
current = fragment = doc.CreateDocumentFragment ();
}
XmlDocument doc;
bool isClosed;
// If it is not null, then we are now inside the element.
XmlNode current;
// If it is not null, then we are now inside the attribute.
XmlAttribute attribute;
// If it is false, then allow to contain multiple document elements.
bool isDocumentEntity;
XmlDocumentFragment fragment;
// None: started or closed.
// XmlDeclaration: after xmldecl. Never allow xmldecl.
// DocumentType: after doctype. Never allow xmldecl and doctype.
// Element: inside document element.
//
XmlNodeType state;
// Properties
public XmlNode Document {
get { return isDocumentEntity ? (XmlNode)doc : (XmlNode)fragment; }
}
public override WriteState WriteState {
get {
if (isClosed)
return WriteState.Closed;
if (attribute != null)
return WriteState.Attribute;
switch (state) {
case XmlNodeType.None:
return WriteState.Start;
case XmlNodeType.XmlDeclaration:
return WriteState.Prolog;
case XmlNodeType.DocumentType:
return WriteState.Element;
default:
return WriteState.Content;
}
}
}
public override string XmlLang {
get {
for (XmlElement n = current as XmlElement; n != null; n = n.ParentNode as XmlElement)
if (n.HasAttribute ("xml:lang"))
return n.GetAttribute ("xml:lang");
return String.Empty;
}
}
public override XmlSpace XmlSpace {
get {
for (XmlElement n = current as XmlElement; n != null; n = n.ParentNode as XmlElement) {
string xs = n.GetAttribute ("xml:space");
switch (xs) {
case "preserve":
return XmlSpace.Preserve;
case "default":
return XmlSpace.Default;
case "":
continue;
default:
throw new InvalidOperationException (String.Format ("Invalid xml:space {0}.", xs));
}
}
return XmlSpace.None;
}
}
// Private Methods
private void CheckState ()
{
if (isClosed)
throw new InvalidOperationException ();
}
private void WritePossiblyTopLevelNode (XmlNode n, bool possiblyAttribute)
{
CheckState ();
if (!possiblyAttribute && attribute != null)
throw new InvalidOperationException (String.Format ("Current state is not acceptable for {0}.", n.NodeType));
if (state != XmlNodeType.Element)
Document.AppendChild (n);
else if (attribute != null)
attribute.AppendChild (n);
else
current.AppendChild (n);
if (state == XmlNodeType.None)
state = XmlNodeType.XmlDeclaration;
}
// Public Methods
public override void Close ()
{
CheckState ();
isClosed = true;
}
public override void Flush ()
{
}
public override string LookupPrefix (string ns)
{
CheckState ();
if (current == null)
throw new InvalidOperationException ();
return current.GetPrefixOfNamespace (ns);
}
// StartDocument
public override void WriteStartDocument ()
{
WriteStartDocument (null);
}
public override void WriteStartDocument (bool standalone)
{
WriteStartDocument (standalone ? "yes" : "no");
}
private void WriteStartDocument (string sddecl)
{
CheckState ();
if (state != XmlNodeType.None)
throw new InvalidOperationException ("Current state is not acceptable for xmldecl.");
doc.AppendChild (doc.CreateXmlDeclaration ("1.0", null, sddecl));
state = XmlNodeType.XmlDeclaration;
}
// EndDocument
public override void WriteEndDocument ()
{
CheckState ();
isClosed = true;
}
// DocumentType
public override void WriteDocType (string name, string publicId, string systemId, string internalSubset)
{
CheckState ();
switch (state) {
case XmlNodeType.None:
case XmlNodeType.XmlDeclaration:
doc.AppendChild (doc.CreateDocumentType (name, publicId, systemId, internalSubset));
state = XmlNodeType.DocumentType;
break;
default:
throw new InvalidOperationException ("Current state is not acceptable for doctype.");
}
}
// StartElement
public override void WriteStartElement (string prefix, string name, string ns)
{
CheckState ();
if (isDocumentEntity && state == XmlNodeType.EndElement && doc.DocumentElement != null)
throw new InvalidOperationException ("Current state is not acceptable for startElement.");
XmlElement el = doc.CreateElement (prefix, name, ns);
if (current == null) {
Document.AppendChild (el);
state = XmlNodeType.Element;
} else {
current.AppendChild (el);
state = XmlNodeType.Element;
}
current = el;
}
// EndElement
public override void WriteEndElement ()
{
WriteEndElementInternal (false);
}
public override void WriteFullEndElement ()
{
WriteEndElementInternal (true);
}
private void WriteEndElementInternal (bool forceFull)
{
CheckState ();
if (current == null)
throw new InvalidOperationException ("Current state is not acceptable for endElement.");
if (!forceFull && current.FirstChild == null)
((XmlElement) current).IsEmpty = true;
if (isDocumentEntity && current.ParentNode == doc)
state = XmlNodeType.EndElement;
else
current = current.ParentNode;
}
// StartAttribute
public override void WriteStartAttribute (string prefix, string name, string ns)
{
CheckState ();
if (attribute != null)
throw new InvalidOperationException ("There is an open attribute.");
if (!(current is XmlElement))
throw new InvalidOperationException ("Current state is not acceptable for startAttribute.");
attribute = doc.CreateAttribute (prefix, name, ns);
((XmlElement)current).SetAttributeNode (attribute);
}
public override void WriteEndAttribute ()
{
CheckState ();
if (attribute == null)
throw new InvalidOperationException ("Current state is not acceptable for startAttribute.");
attribute = null;
}
public override void WriteCData (string data)
{
CheckState ();
if (current == null)
throw new InvalidOperationException ("Current state is not acceptable for CDATAsection.");
current.AppendChild (doc.CreateCDataSection (data));
}
public override void WriteComment (string comment)
{
WritePossiblyTopLevelNode (doc.CreateComment (comment), false);
}
public override void WriteProcessingInstruction (string name, string value)
{
WritePossiblyTopLevelNode (
doc.CreateProcessingInstruction (name, value), false);
}
public override void WriteEntityRef (string name)
{
WritePossiblyTopLevelNode (doc.CreateEntityReference (name), true);
}
public override void WriteCharEntity (char c)
{
WritePossiblyTopLevelNode (doc.CreateTextNode (new string (new char [] {c}, 0, 1)), true);
}
public override void WriteWhitespace (string ws)
{
WritePossiblyTopLevelNode (doc.CreateWhitespace (ws), true);
}
public override void WriteString (string data)
{
CheckState ();
if (current == null)
throw new InvalidOperationException ("Current state is not acceptable for Text.");
if (attribute != null)
attribute.AppendChild (doc.CreateTextNode (data));
else {
XmlText last = current.LastChild as XmlText;
if (last == null)
current.AppendChild(doc.CreateTextNode(data));
else
last.AppendData(data);
}
}
public override void WriteName (string name)
{
WriteString (name);
}
public override void WriteNmToken (string nmtoken)
{
WriteString (nmtoken);
}
public override void WriteQualifiedName (string name, string ns)
{
string prefix = LookupPrefix (ns);
if (prefix == null)
throw new ArgumentException (String.Format ("Invalid namespace {0}", ns));
if (prefix != String.Empty)
WriteString (name);
else
WriteString (prefix + ":" + name);
}
public override void WriteChars (char [] chars, int start, int len)
{
WriteString (new string (chars, start, len));
}
public override void WriteRaw (string data)
{
// It never supports raw string.
WriteString (data);
}
public override void WriteRaw (char [] chars, int start, int len)
{
// It never supports raw string.
WriteChars (chars, start, len);
}
public override void WriteBase64 (byte [] data, int start, int len)
{
// It never supports raw string.
WriteString (Convert.ToBase64String (data, start, len));
}
public override void WriteBinHex (byte [] data, int start, int len)
{
throw new NotImplementedException ();
}
public override void WriteSurrogateCharEntity (char c1, char c2)
{
throw new NotImplementedException ();
}
}
}
| 26.11054 | 113 | 0.692626 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.XML/Mono.Xml/XmlNodeWriter.cs | 10,157 | C# |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using NUnit.Engine.Extensibility;
namespace NUnit.Engine.Services
{
public class XmlTransformResultWriter : IResultWriter
{
private string _xsltFile;
private readonly XslCompiledTransform _transform = new XslCompiledTransform();
public XmlTransformResultWriter(object[] args)
{
Guard.ArgumentNotNull(args, "args");
_xsltFile = args[0] as string;
Guard.ArgumentValid(
!string.IsNullOrEmpty(_xsltFile),
"Argument to XmlTransformWriter must be a non-empty string",
"args");
try
{
_transform.Load(_xsltFile);
}
catch (Exception ex)
{
throw new ArgumentException("Unable to load transform " + _xsltFile, ex.InnerException);
}
}
/// <summary>
/// Checks if the output is writable. If the output is not
/// writable, this method should throw an exception.
/// </summary>
/// <param name="outputPath"></param>
public void CheckWritability(string outputPath)
{
using ( new StreamWriter( outputPath, false ) )
{
// We don't need to check if the XSLT file exists,
// that would have thrown in the constructor
}
}
public void WriteResultFile(XmlNode result, TextWriter writer)
{
using (var xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
_transform.Transform(result, xmlWriter);
}
}
public void WriteResultFile(XmlNode result, string outputPath)
{
using (var xmlWriter = new XmlTextWriter(outputPath, Encoding.Default))
{
xmlWriter.Formatting = Formatting.Indented;
_transform.Transform(result, xmlWriter);
}
}
}
}
| 36.945055 | 104 | 0.605294 | [
"MIT"
] | JetBrains/nunit | src/NUnitEngine/nunit.engine/Services/ResultWriters/XmlTransformResultWriter.cs | 3,364 | C# |
#nullable enable
using System;
using System.Threading;
using System.Threading.Tasks;
using Android.Graphics.Drawables;
using Android.Widget;
namespace Microsoft.Maui
{
public static class ImageViewExtensions
{
public static void Clear(this ImageView imageView)
{
// stop the animation
if (imageView.Drawable is IAnimatable animatable)
animatable.Stop();
// clear the view and release any bitmaps
imageView.SetImageResource(global::Android.Resource.Color.Transparent);
}
public static void UpdateAspect(this ImageView imageView, IImage image)
{
imageView.SetScaleType(image.Aspect.ToScaleType());
}
public static void UpdateIsAnimationPlaying(this ImageView imageView, IImageSourcePart image)
{
if (imageView.Drawable is IAnimatable animatable)
{
if (image.IsAnimationPlaying)
{
if (!animatable.IsRunning)
animatable.Start();
}
else
{
if (animatable.IsRunning)
animatable.Stop();
}
}
}
public static async Task<IImageSourceServiceResult<Drawable>?> UpdateSourceAsync(this ImageView imageView, IImageSourcePart image, IImageSourceServiceProvider services, CancellationToken cancellationToken = default)
{
imageView.Clear();
image.UpdateIsLoading(false);
var context = imageView.Context;
if (context == null)
return null;
var imageSource = image.Source;
if (imageSource == null)
return null;
var events = image as IImageSourcePartEvents;
events?.LoadingStarted();
image.UpdateIsLoading(true);
try
{
var service = services.GetRequiredImageSourceService(imageSource);
var result = await service.GetDrawableAsync(imageSource, context, cancellationToken);
var drawable = result?.Value;
var applied = !cancellationToken.IsCancellationRequested && imageView.IsAlive() && imageSource == image.Source;
// only set the image if we are still on the same one
if (applied)
{
imageView.SetImageDrawable(drawable);
imageView.UpdateIsAnimationPlaying(image);
}
events?.LoadingCompleted(applied);
return result;
}
catch (OperationCanceledException)
{
// no-op
events?.LoadingCompleted(false);
}
catch (Exception ex)
{
events?.LoadingFailed(ex);
}
finally
{
// only mark as finished if we are still working on the same image
if (imageSource == image.Source)
{
image.UpdateIsLoading(false);
}
}
return null;
}
}
} | 23.514286 | 217 | 0.706359 | [
"MIT"
] | 3DSX/maui | src/Core/src/Platform/Android/ImageViewExtensions.cs | 2,471 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Microsoft.CodeAnalysis.Diagnostics;
namespace LocalisationAnalyser.Tools
{
public class OsuAnalyzerConfigOptions : AnalyzerConfigOptions
{
public override bool TryGetValue(string key, out string value)
{
// License header is hard-coded for now as the tool is meant for internal osu! usage only.
if (key == $"dotnet_diagnostic.{DiagnosticRules.STRING_CAN_BE_LOCALISED.Id}.license_header")
{
value = "// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.\n// See the LICENCE file in the repository root for full licence text.";
return true;
}
value = string.Empty;
return false;
}
}
}
| 37.75 | 176 | 0.65011 | [
"MIT"
] | ppy/osu-localisation-analyser | LocalisationAnalyser.Tools/OsuAnalyzerConfigOptions.cs | 906 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using QuantConnect.Data.Market;
namespace QuantConnect.Indicators.CandlestickPatterns
{
/// <summary>
/// Takuri (Dragonfly Doji with very long lower shadow) candlestick pattern indicator
/// </summary>
/// <remarks>
/// Must have:
/// - doji body
/// - open and close at the high of the day = no or very short upper shadow
/// - very long lower shadow
/// The meaning of "doji", "very short" and "very long" is specified with SetCandleSettings
/// The returned value is always positive(+1) but this does not mean it is bullish: takuri must be considered
/// relatively to the trend
/// </remarks>
public class Takuri : CandlestickPattern
{
private readonly int _bodyDojiAveragePeriod;
private readonly int _shadowVeryShortAveragePeriod;
private readonly int _shadowVeryLongAveragePeriod;
private decimal _bodyDojiPeriodTotal;
private decimal _shadowVeryShortPeriodTotal;
private decimal _shadowVeryLongPeriodTotal;
/// <summary>
/// Initializes a new instance of the <see cref="Takuri"/> class using the specified name.
/// </summary>
/// <param name="name">The name of this indicator</param>
public Takuri(string name)
: base(name, Math.Max(Math.Max(CandleSettings.Get(CandleSettingType.BodyDoji).AveragePeriod, CandleSettings.Get(CandleSettingType.ShadowVeryShort).AveragePeriod),
CandleSettings.Get(CandleSettingType.ShadowVeryLong).AveragePeriod) + 1)
{
_bodyDojiAveragePeriod = CandleSettings.Get(CandleSettingType.BodyDoji).AveragePeriod;
_shadowVeryShortAveragePeriod = CandleSettings.Get(CandleSettingType.ShadowVeryShort).AveragePeriod;
_shadowVeryLongAveragePeriod = CandleSettings.Get(CandleSettingType.ShadowVeryLong).AveragePeriod;
}
/// <summary>
/// Initializes a new instance of the <see cref="Takuri"/> class.
/// </summary>
public Takuri()
: this("TAKURI")
{
}
/// <summary>
/// Gets a flag indicating when this indicator is ready and fully initialized
/// </summary>
public override bool IsReady
{
get { return Samples >= Period; }
}
/// <summary>
/// Computes the next value of this indicator from the given state
/// </summary>
/// <param name="window">The window of data held in this indicator</param>
/// <param name="input">The input given to the indicator</param>
/// <returns>A new value for this indicator</returns>
protected override decimal ComputeNextValue(IReadOnlyWindow<IBaseDataBar> window, IBaseDataBar input)
{
if (!IsReady)
{
if (Samples >= Period - _bodyDojiAveragePeriod)
{
_bodyDojiPeriodTotal += GetCandleRange(CandleSettingType.BodyDoji, input);
}
if (Samples >= Period - _shadowVeryShortAveragePeriod)
{
_shadowVeryShortPeriodTotal += GetCandleRange(CandleSettingType.ShadowVeryShort, input);
}
if (Samples >= Period - _shadowVeryLongAveragePeriod)
{
_shadowVeryLongPeriodTotal += GetCandleRange(CandleSettingType.ShadowVeryLong, input);
}
return 0m;
}
decimal value;
if (GetRealBody(input) <= GetCandleAverage(CandleSettingType.BodyDoji, _bodyDojiPeriodTotal, input) &&
GetUpperShadow(input) < GetCandleAverage(CandleSettingType.ShadowVeryShort, _shadowVeryShortPeriodTotal, input) &&
GetLowerShadow(input) > GetCandleAverage(CandleSettingType.ShadowVeryLong, _shadowVeryLongPeriodTotal, input)
)
value = 1m;
else
value = 0m;
// add the current range and subtract the first range: this is done after the pattern recognition
// when avgPeriod is not 0, that means "compare with the previous candles" (it excludes the current candle)
_bodyDojiPeriodTotal += GetCandleRange(CandleSettingType.BodyDoji, input) -
GetCandleRange(CandleSettingType.BodyDoji, window[_bodyDojiAveragePeriod]);
_shadowVeryShortPeriodTotal += GetCandleRange(CandleSettingType.ShadowVeryShort, input) -
GetCandleRange(CandleSettingType.ShadowVeryShort, window[_shadowVeryShortAveragePeriod]);
_shadowVeryLongPeriodTotal += GetCandleRange(CandleSettingType.ShadowVeryLong, input) -
GetCandleRange(CandleSettingType.ShadowVeryLong, window[_shadowVeryLongAveragePeriod]);
return value;
}
/// <summary>
/// Resets this indicator to its initial state
/// </summary>
public override void Reset()
{
_bodyDojiPeriodTotal = 0m;
_shadowVeryShortPeriodTotal = 0m;
_shadowVeryLongPeriodTotal = 0m;
base.Reset();
}
}
}
| 43.698529 | 174 | 0.641932 | [
"Apache-2.0"
] | 3ai-co/Lean | Indicators/CandlestickPatterns/Takuri.cs | 5,945 | C# |
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Boots.Core;
using Polly.Timeout;
using Xunit;
namespace Boots.Tests
{
public class HttpClientWithPolicyTests
{
[Fact]
public void InvalidTimeout ()
{
var boots = new Bootstrapper {
Timeout = TimeSpan.FromSeconds (-1),
};
Assert.Throws<ArgumentOutOfRangeException> (() => new HttpClientWithPolicy (boots));
}
[Fact]
public void DefaultTimeout ()
{
// Mainly validates the 100-second default:
// https://docs.microsoft.com/dotnet/api/system.net.http.httpclient.timeout#remarks
var boots = new Bootstrapper ();
using var client = new HttpClientWithPolicy (boots);
Assert.Equal (TimeSpan.FromSeconds (100), client.Timeout);
}
[Fact]
public async Task Cancelled ()
{
var boots = new Bootstrapper ();
boots.UpdateActivePolicy ();
using var client = new AlwaysTimeoutClient (boots);
var token = new CancellationToken (canceled: true);
await Assert.ThrowsAsync<OperationCanceledException> (() =>
client.DownloadAsync (new Uri ("http://google.com"), "", token));
Assert.Equal (0, client.TimesCalled);
}
[Theory]
[InlineData (typeof (AlwaysTimeoutClient), typeof (TimeoutRejectedException))]
[InlineData (typeof (AlwaysThrowsClient), typeof (HttpRequestException))]
[InlineData (typeof (AlwaysThrowsClient), typeof (IOException))]
[InlineData (typeof (AlwaysThrowsClient), typeof (NotImplementedException), 0)]
[InlineData (typeof (AlwaysThrowsClient), typeof (NullReferenceException), 0)]
public async Task TimeoutPolicy (Type clientType, Type exceptionType, int expectedRetries = 5)
{
var writer = new StringWriter ();
var boots = new Bootstrapper {
NetworkRetries = 5,
ReadWriteTimeout = TimeSpan.FromMilliseconds (1),
Logger = writer,
};
boots.UpdateActivePolicy ();
using var client = (TestClient) Activator.CreateInstance (clientType, new object [] { boots });
client.ExceptionType = exceptionType;
await Assert.ThrowsAsync (exceptionType, () =>
client.DownloadAsync (new Uri ("http://google.com"), "", CancellationToken.None));
Assert.Equal (expectedRetries + 1, client.TimesCalled);
for (int i = 1; i <= expectedRetries; i++) {
Assert.Contains ($"Retry attempt {i}: {exceptionType.FullName}", writer.ToString ());
}
}
class TestClient : HttpClientWithPolicy
{
public TestClient (Bootstrapper boots) : base (boots) { }
public int TimesCalled { get; set; }
public Type ExceptionType { get; set; }
}
class AlwaysTimeoutClient : TestClient
{
public AlwaysTimeoutClient (Bootstrapper boots) : base (boots) { }
async Task<T> Forever<T> (CancellationToken token)
{
TimesCalled++;
await Task.Delay (System.Threading.Timeout.Infinite, token);
return default;
}
protected override Task DoDownloadAsync (Uri uri, string tempFile, CancellationToken token) => Forever<object> (token);
protected override Task<T> DoGetJsonAsync<T> (Uri uri, CancellationToken token) => Forever<T> (token);
protected override Task<XmlDocument> DoGetXmlDocumentAsync (Uri uri, CancellationToken token) => Forever<XmlDocument> (token);
}
class AlwaysThrowsClient : TestClient
{
public AlwaysThrowsClient (Bootstrapper boots) : base (boots) { }
Task<T> Throw<T> ()
{
TimesCalled++;
throw (Exception) Activator.CreateInstance (ExceptionType);
}
protected override Task DoDownloadAsync (Uri uri, string tempFile, CancellationToken token) => Throw<object> ();
protected override Task<T> DoGetJsonAsync<T> (Uri uri, CancellationToken token) => Throw<T> ();
protected override Task<XmlDocument> DoGetXmlDocumentAsync (Uri uri, CancellationToken token) => Throw<XmlDocument> ();
}
}
}
| 32.466102 | 129 | 0.712608 | [
"MIT"
] | jonathanpeppers/boots | Boots.Tests/HttpClientWithPolicyTests.cs | 3,831 | C# |
namespace Service.BackofficeCreds.Domain.Models
{
public class Role
{
public string Name { get; set; }
public bool IsSupervisor { get; set; }
}
} | 21.625 | 47 | 0.624277 | [
"MIT"
] | MyJetWallet/Service.BackofficeCreds | src/Service.BackofficeCreds.Domain.Models/Role.cs | 173 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record.PivotTable
{
using System;
using System.Text;
using NPOI.HSSF.Record;
using NPOI.Util;
using NPOI.Util.IO;
/**
* SXVDEX - Extended PivotTable View Fields (0x0100)<br/>
*
* @author Patrick Cheng
*/
public class ExtendedPivotTableViewFieldsRecord : StandardRecord
{
public const short sid = 0x0100;
/** the value of the <tt>cchSubName</tt> field when the subName is not present */
private const int STRING_NOT_PRESENT_LEN = 0xFFFF;
private int grbit1;
private int grbit2;
private int citmShow;
private int isxdiSort;
private int isxdiShow;
private int reserved1;
private int reserved2;
private String subName;
public ExtendedPivotTableViewFieldsRecord(RecordInputStream in1)
{
grbit1 = in1.ReadInt();
grbit2 = in1.ReadUByte();
citmShow = in1.ReadUByte();
isxdiSort = in1.ReadUShort();
isxdiShow = in1.ReadUShort();
// This record seems to have different valid encodings
switch (in1.Remaining) {
case 0:
// as per "Microsoft Excel Developer's Kit" book
// older version of SXVDEX - doesn't seem to have a sub-total name
reserved1 = 0;
reserved2 = 0;
subName = null;
return;
case 10:
// as per "MICROSOFT OFFICE EXCEL 97-2007 BINARY FILE FORMAT SPECIFICATION" pdf
break;
default:
throw new RecordFormatException("Unexpected remaining size (" + in1.Remaining + ")");
}
int cchSubName = in1.ReadUShort();
reserved1 = in1.ReadInt();
reserved2 = in1.ReadInt();
if (cchSubName != STRING_NOT_PRESENT_LEN)
{
subName = in1.ReadUnicodeLEString(cchSubName);
}
}
public override void Serialize(LittleEndianOutput out1)
{
out1.WriteInt(grbit1);
out1.WriteByte(grbit2);
out1.WriteByte(citmShow);
out1.WriteShort(isxdiSort);
out1.WriteShort(isxdiShow);
if (subName == null)
{
out1.WriteShort(STRING_NOT_PRESENT_LEN);
}
else
{
out1.WriteShort(subName.Length);
}
out1.WriteInt(reserved1);
out1.WriteInt(reserved2);
if (subName != null)
{
StringUtil.PutUnicodeLE(subName, out1);
}
}
protected override int DataSize
{
get
{
return 4 + 1 + 1 + 2 + 2 + 2 + 4 + 4 +
(subName == null ? 0 : (2 * subName.Length)); // in unicode
}
}
public override short Sid
{
get
{
return sid;
}
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[SXVDEX]\n");
buffer.Append(" .grbit1 =").Append(HexDump.IntToHex(grbit1)).Append("\n");
buffer.Append(" .grbit2 =").Append(HexDump.ByteToHex(grbit2)).Append("\n");
buffer.Append(" .citmShow =").Append(HexDump.ByteToHex(citmShow)).Append("\n");
buffer.Append(" .isxdiSort =").Append(HexDump.ShortToHex(isxdiSort)).Append("\n");
buffer.Append(" .isxdiShow =").Append(HexDump.ShortToHex(isxdiShow)).Append("\n");
buffer.Append(" .subName =").Append(subName).Append("\n");
buffer.Append("[/SXVDEX]\n");
return buffer.ToString();
}
}
} | 32.888112 | 97 | 0.554965 | [
"MIT"
] | cschen1205/myob-accounting-plugin | NPOI/main/HSSF/Record/PivotTable/ExtendedPivotTableViewFieldsRecord.cs | 4,703 | C# |
namespace CriptoHub
{
partial class Home
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Home));
this.panelMenu = new System.Windows.Forms.Panel();
this.btSair = new System.Windows.Forms.Button();
this.btSuporte = new System.Windows.Forms.Button();
this.btFeedback = new System.Windows.Forms.Button();
this.btImoveis = new System.Windows.Forms.Button();
this.btLocatarios = new System.Windows.Forms.Button();
this.btClientes = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.btContratos = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.lbNome = new System.Windows.Forms.Label();
this.panelLogo = new System.Windows.Forms.Panel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.BarraSuperior = new System.Windows.Forms.Panel();
this.panelDesktop = new System.Windows.Forms.Panel();
this.lbData = new System.Windows.Forms.Label();
this.lbHora = new System.Windows.Forms.Label();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.HoraData = new System.Windows.Forms.Timer(this.components);
this.panelMenu.SuspendLayout();
this.panelLogo.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.panelDesktop.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.SuspendLayout();
//
// panelMenu
//
this.panelMenu.AllowDrop = true;
this.panelMenu.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(15)))), ((int)(((byte)(0)))), ((int)(((byte)(45)))));
this.panelMenu.Controls.Add(this.btSair);
this.panelMenu.Controls.Add(this.btSuporte);
this.panelMenu.Controls.Add(this.btFeedback);
this.panelMenu.Controls.Add(this.btImoveis);
this.panelMenu.Controls.Add(this.btLocatarios);
this.panelMenu.Controls.Add(this.btClientes);
this.panelMenu.Controls.Add(this.label2);
this.panelMenu.Controls.Add(this.panel1);
this.panelMenu.Controls.Add(this.panel3);
this.panelMenu.Controls.Add(this.btContratos);
this.panelMenu.Controls.Add(this.label1);
this.panelMenu.Controls.Add(this.lbNome);
this.panelMenu.Controls.Add(this.panelLogo);
this.panelMenu.Dock = System.Windows.Forms.DockStyle.Left;
this.panelMenu.Location = new System.Drawing.Point(0, 0);
this.panelMenu.Name = "panelMenu";
this.panelMenu.Size = new System.Drawing.Size(220, 566);
this.panelMenu.TabIndex = 0;
//
// btSair
//
this.btSair.Cursor = System.Windows.Forms.Cursors.Hand;
this.btSair.FlatAppearance.BorderSize = 0;
this.btSair.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btSair.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btSair.ForeColor = System.Drawing.SystemColors.Control;
this.btSair.Location = new System.Drawing.Point(25, 476);
this.btSair.Name = "btSair";
this.btSair.Size = new System.Drawing.Size(177, 27);
this.btSair.TabIndex = 13;
this.btSair.Text = "Sair";
this.btSair.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btSair.UseVisualStyleBackColor = true;
this.btSair.Click += new System.EventHandler(this.btSair_Click);
//
// btSuporte
//
this.btSuporte.Cursor = System.Windows.Forms.Cursors.Hand;
this.btSuporte.FlatAppearance.BorderSize = 0;
this.btSuporte.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btSuporte.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btSuporte.ForeColor = System.Drawing.SystemColors.Control;
this.btSuporte.Location = new System.Drawing.Point(25, 434);
this.btSuporte.Name = "btSuporte";
this.btSuporte.Size = new System.Drawing.Size(177, 27);
this.btSuporte.TabIndex = 12;
this.btSuporte.Text = "Suporte";
this.btSuporte.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btSuporte.UseVisualStyleBackColor = true;
this.btSuporte.Click += new System.EventHandler(this.btSuporte_Click);
//
// btFeedback
//
this.btFeedback.Cursor = System.Windows.Forms.Cursors.Hand;
this.btFeedback.FlatAppearance.BorderSize = 0;
this.btFeedback.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btFeedback.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btFeedback.ForeColor = System.Drawing.SystemColors.Control;
this.btFeedback.Location = new System.Drawing.Point(25, 401);
this.btFeedback.Name = "btFeedback";
this.btFeedback.Size = new System.Drawing.Size(177, 27);
this.btFeedback.TabIndex = 11;
this.btFeedback.Text = "Fornecer FeedBack";
this.btFeedback.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btFeedback.UseVisualStyleBackColor = true;
this.btFeedback.Click += new System.EventHandler(this.btFeedback_Click);
//
// btImoveis
//
this.btImoveis.Cursor = System.Windows.Forms.Cursors.Hand;
this.btImoveis.FlatAppearance.BorderSize = 0;
this.btImoveis.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btImoveis.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btImoveis.ForeColor = System.Drawing.SystemColors.Control;
this.btImoveis.Location = new System.Drawing.Point(25, 327);
this.btImoveis.Name = "btImoveis";
this.btImoveis.Size = new System.Drawing.Size(177, 27);
this.btImoveis.TabIndex = 10;
this.btImoveis.Text = "Imóveis";
this.btImoveis.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btImoveis.UseVisualStyleBackColor = true;
this.btImoveis.Click += new System.EventHandler(this.btImoveis_Click);
//
// btLocatarios
//
this.btLocatarios.Cursor = System.Windows.Forms.Cursors.Hand;
this.btLocatarios.FlatAppearance.BorderSize = 0;
this.btLocatarios.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btLocatarios.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btLocatarios.ForeColor = System.Drawing.SystemColors.Control;
this.btLocatarios.Location = new System.Drawing.Point(25, 294);
this.btLocatarios.Name = "btLocatarios";
this.btLocatarios.Size = new System.Drawing.Size(177, 27);
this.btLocatarios.TabIndex = 9;
this.btLocatarios.Text = "Locatários";
this.btLocatarios.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btLocatarios.UseVisualStyleBackColor = true;
this.btLocatarios.Click += new System.EventHandler(this.btLocatarios_Click);
//
// btClientes
//
this.btClientes.Cursor = System.Windows.Forms.Cursors.Hand;
this.btClientes.FlatAppearance.BorderSize = 0;
this.btClientes.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btClientes.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btClientes.ForeColor = System.Drawing.SystemColors.Control;
this.btClientes.Location = new System.Drawing.Point(25, 263);
this.btClientes.Name = "btClientes";
this.btClientes.Size = new System.Drawing.Size(177, 27);
this.btClientes.TabIndex = 8;
this.btClientes.Text = "Clientes";
this.btClientes.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btClientes.UseVisualStyleBackColor = true;
this.btClientes.Click += new System.EventHandler(this.btClientes_Click);
//
// label2
//
this.label2.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.SystemColors.Control;
this.label2.Location = new System.Drawing.Point(27, 234);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(131, 19);
this.label2.TabIndex = 7;
this.label2.Text = "GERENCIAMENTO";
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.DeepSkyBlue;
this.panel1.Location = new System.Drawing.Point(12, 379);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(190, 1);
this.panel1.TabIndex = 6;
//
// panel3
//
this.panel3.BackColor = System.Drawing.Color.DeepSkyBlue;
this.panel3.Location = new System.Drawing.Point(12, 216);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(190, 1);
this.panel3.TabIndex = 5;
//
// btContratos
//
this.btContratos.Cursor = System.Windows.Forms.Cursors.Hand;
this.btContratos.FlatAppearance.BorderSize = 0;
this.btContratos.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btContratos.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btContratos.ForeColor = System.Drawing.SystemColors.Control;
this.btContratos.Location = new System.Drawing.Point(25, 176);
this.btContratos.Name = "btContratos";
this.btContratos.Size = new System.Drawing.Size(177, 27);
this.btContratos.TabIndex = 4;
this.btContratos.Text = "Contratos";
this.btContratos.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btContratos.UseVisualStyleBackColor = true;
this.btContratos.Click += new System.EventHandler(this.btContratos_Click);
//
// label1
//
this.label1.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.Control;
this.label1.Location = new System.Drawing.Point(27, 147);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(131, 19);
this.label1.TabIndex = 3;
this.label1.Text = "ATIVIDADES";
//
// lbNome
//
this.lbNome.Dock = System.Windows.Forms.DockStyle.Top;
this.lbNome.Font = new System.Drawing.Font("Calibri", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbNome.ForeColor = System.Drawing.SystemColors.Control;
this.lbNome.Location = new System.Drawing.Point(0, 87);
this.lbNome.Name = "lbNome";
this.lbNome.Size = new System.Drawing.Size(220, 49);
this.lbNome.TabIndex = 2;
this.lbNome.Text = "Nome Funcionario";
this.lbNome.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// panelLogo
//
this.panelLogo.Controls.Add(this.pictureBox1);
this.panelLogo.Dock = System.Windows.Forms.DockStyle.Top;
this.panelLogo.Location = new System.Drawing.Point(0, 0);
this.panelLogo.Name = "panelLogo";
this.panelLogo.Size = new System.Drawing.Size(220, 87);
this.panelLogo.TabIndex = 0;
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(12, 19);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(197, 63);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// BarraSuperior
//
this.BarraSuperior.BackColor = System.Drawing.SystemColors.Control;
this.BarraSuperior.Location = new System.Drawing.Point(220, 0);
this.BarraSuperior.Name = "BarraSuperior";
this.BarraSuperior.Size = new System.Drawing.Size(789, 20);
this.BarraSuperior.TabIndex = 1;
this.BarraSuperior.MouseDown += new System.Windows.Forms.MouseEventHandler(this.BarraSuperior_MouseDown);
//
// panelDesktop
//
this.panelDesktop.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(15)))), ((int)(((byte)(0)))), ((int)(((byte)(45)))));
this.panelDesktop.Controls.Add(this.lbData);
this.panelDesktop.Controls.Add(this.lbHora);
this.panelDesktop.Controls.Add(this.pictureBox2);
this.panelDesktop.Location = new System.Drawing.Point(220, 20);
this.panelDesktop.Name = "panelDesktop";
this.panelDesktop.Size = new System.Drawing.Size(789, 546);
this.panelDesktop.TabIndex = 2;
//
// lbData
//
this.lbData.Font = new System.Drawing.Font("Calibri", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbData.ForeColor = System.Drawing.Color.Aqua;
this.lbData.Location = new System.Drawing.Point(222, 359);
this.lbData.Name = "lbData";
this.lbData.Size = new System.Drawing.Size(373, 46);
this.lbData.TabIndex = 3;
this.lbData.Text = "Data";
this.lbData.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// lbHora
//
this.lbHora.Font = new System.Drawing.Font("Calibri", 48F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbHora.ForeColor = System.Drawing.SystemColors.Control;
this.lbHora.Location = new System.Drawing.Point(279, 284);
this.lbHora.Name = "lbHora";
this.lbHora.Size = new System.Drawing.Size(260, 78);
this.lbHora.TabIndex = 2;
this.lbHora.Text = "Hora";
this.lbHora.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// pictureBox2
//
this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
this.pictureBox2.Location = new System.Drawing.Point(322, 156);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(152, 125);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox2.TabIndex = 1;
this.pictureBox2.TabStop = false;
//
// HoraData
//
this.HoraData.Enabled = true;
this.HoraData.Tick += new System.EventHandler(this.HoraData_Tick);
//
// Home
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(1009, 566);
this.ControlBox = false;
this.Controls.Add(this.panelDesktop);
this.Controls.Add(this.BarraSuperior);
this.Controls.Add(this.panelMenu);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "Home";
this.Text = "Home";
this.panelMenu.ResumeLayout(false);
this.panelLogo.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.panelDesktop.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panelMenu;
private System.Windows.Forms.Button btContratos;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lbNome;
private System.Windows.Forms.Panel panelLogo;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Button btSair;
private System.Windows.Forms.Button btSuporte;
private System.Windows.Forms.Button btFeedback;
private System.Windows.Forms.Button btImoveis;
private System.Windows.Forms.Button btLocatarios;
private System.Windows.Forms.Button btClientes;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel BarraSuperior;
private System.Windows.Forms.Panel panelDesktop;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Label lbData;
private System.Windows.Forms.Label lbHora;
private System.Windows.Forms.Timer HoraData;
}
} | 54.081967 | 159 | 0.616854 | [
"MIT"
] | MarcosBrandao21/PIM-III-Cripto-Hub | CriptoHub/Home.Designer.cs | 19,798 | C# |
/*
* WebAPI
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: data
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter;
namespace IO.Swagger.Model
{
/// <summary>
/// IxFe Send response
/// </summary>
[DataContract]
public partial class IxFeSendResponseDTO : IEquatable<IxFeSendResponseDTO>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="IxFeSendResponseDTO" /> class.
/// </summary>
/// <param name="signCert">Signature Certificate.</param>
/// <param name="sendRequestId">Identifier of asynchronous activity (QueueId).</param>
public IxFeSendResponseDTO(SignCertDTO signCert = default(SignCertDTO), string sendRequestId = default(string))
{
this.SignCert = signCert;
this.SendRequestId = sendRequestId;
}
/// <summary>
/// Signature Certificate
/// </summary>
/// <value>Signature Certificate</value>
[DataMember(Name="signCert", EmitDefaultValue=false)]
public SignCertDTO SignCert { get; set; }
/// <summary>
/// Identifier of asynchronous activity (QueueId)
/// </summary>
/// <value>Identifier of asynchronous activity (QueueId)</value>
[DataMember(Name="sendRequestId", EmitDefaultValue=false)]
public string SendRequestId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class IxFeSendResponseDTO {\n");
sb.Append(" SignCert: ").Append(SignCert).Append("\n");
sb.Append(" SendRequestId: ").Append(SendRequestId).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 JsonConvert.SerializeObject(this, 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 IxFeSendResponseDTO);
}
/// <summary>
/// Returns true if IxFeSendResponseDTO instances are equal
/// </summary>
/// <param name="input">Instance of IxFeSendResponseDTO to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(IxFeSendResponseDTO input)
{
if (input == null)
return false;
return
(
this.SignCert == input.SignCert ||
(this.SignCert != null &&
this.SignCert.Equals(input.SignCert))
) &&
(
this.SendRequestId == input.SendRequestId ||
(this.SendRequestId != null &&
this.SendRequestId.Equals(input.SendRequestId))
);
}
/// <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.SignCert != null)
hashCode = hashCode * 59 + this.SignCert.GetHashCode();
if (this.SendRequestId != null)
hashCode = hashCode * 59 + this.SendRequestId.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 34.377622 | 140 | 0.581774 | [
"Apache-2.0"
] | zanardini/ARXivarNext-StressTest | ARXivarNext-StressTest/IO.Swagger/Model/IxFeSendResponseDTO.cs | 4,916 | C# |
using AnimalCentre.Models.Contracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace AnimalCentre.Models.Procedures
{
public abstract class Procedure : IProcedure
{
protected ICollection<IAnimal> procedureHistory;
protected Procedure()
{
this.procedureHistory = new List<IAnimal>();
}
public string History()
{
var sb = new StringBuilder();
sb.AppendLine($"{this.GetType().Name}");
foreach (var animal in this.procedureHistory)
{
sb.AppendLine(animal.ToString());
}
string result = sb.ToString().TrimEnd();
return result;
}
public virtual void DoService(IAnimal animal, int procedureTime)
{
if (procedureTime > animal.ProcedureTime)
{
throw new ArgumentException("Animal doesn't have enough procedure time");
}
animal.ProcedureTime -= procedureTime;
procedureHistory.Add(animal);
}
}
}
| 24.555556 | 89 | 0.574661 | [
"MIT"
] | bodyquest/SoftwareUniversity-Bulgaria | C# OOP 2019/EXAM_PREP/ExamPrep - Apr 2019 (AnimalCentre, BankAccount)/AnimalCenter_Business_Logic/Models/Procedures/Procedure.cs | 1,107 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("12.EqualPairs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("12.EqualPairs")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cc244415-0e2a-43e8-bc9b-21f9850f0e3e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.744103 | [
"MIT"
] | yangra/SoftUni | ProgrammingBasics/05.Loops/12.EqualPairs/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoItX3Lib;
namespace addressbook_tests_autoit
{
public class ApplicationManager
{
public static string WINTITLE = "Free Address Book";
private AutoItX3 aux;
private GroupHelper groupHelper;
public ApplicationManager()
{
aux = new AutoItX3();
aux.Run(@"C:\Tools\AppsForTesting\AddressbookNative4\AddressBook.exe", "", aux.SW_SHOW);
aux.WinWait(WINTITLE);
aux.WinActivate(WINTITLE);
aux.WinWaitActive(WINTITLE);
groupHelper = new GroupHelper(this);
}
public void Stop()
{
aux.ControlClick(WINTITLE, "", "WindowsForms10.BUTTON.app.0.3dd72c210");
}
public AutoItX3 Aux
{
get
{
return aux;
}
}
public GroupHelper Groups
{
get
{
return groupHelper;
}
}
}
}
| 22.489796 | 100 | 0.546279 | [
"Apache-2.0"
] | azagorodskih/csharp_training | addressbook_tests_autoit/addressbook_tests_autoit/appmanager/ApplicationManager.cs | 1,104 | C# |
using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public partial class hkbRocketboxCharacterControllerInternalState : hkReferencedObject
{
public override uint Signature { get => 1772527852; }
public bool m_rapidTurnRequest;
public int m_currPose;
public int m_prevPose;
public float m_noVelocityTimer;
public float m_linearSpeedModifier;
public float m_characterAngle;
public int m_plantedFootIdx;
public float m_timeStep;
public override void Read(PackFileDeserializer des, BinaryReaderEx br)
{
base.Read(des, br);
m_rapidTurnRequest = br.ReadBoolean();
br.ReadUInt16();
br.ReadByte();
m_currPose = br.ReadInt32();
m_prevPose = br.ReadInt32();
m_noVelocityTimer = br.ReadSingle();
m_linearSpeedModifier = br.ReadSingle();
m_characterAngle = br.ReadSingle();
m_plantedFootIdx = br.ReadInt32();
m_timeStep = br.ReadSingle();
}
public override void Write(PackFileSerializer s, BinaryWriterEx bw)
{
base.Write(s, bw);
bw.WriteBoolean(m_rapidTurnRequest);
bw.WriteUInt16(0);
bw.WriteByte(0);
bw.WriteInt32(m_currPose);
bw.WriteInt32(m_prevPose);
bw.WriteSingle(m_noVelocityTimer);
bw.WriteSingle(m_linearSpeedModifier);
bw.WriteSingle(m_characterAngle);
bw.WriteInt32(m_plantedFootIdx);
bw.WriteSingle(m_timeStep);
}
}
}
| 33.058824 | 90 | 0.605575 | [
"MIT"
] | SyllabusGames/DSMapStudio | HKX2/Autogen/hkbRocketboxCharacterControllerInternalState.cs | 1,686 | C# |
using System;
using System.IO;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class LinuxPreferenceProvider : BasePreferenceProvider
{
static string s_EditorPrefsPath;
static string EditorPrefsPath
{
get
{
if (string.IsNullOrEmpty (s_EditorPrefsPath))
{
string prefix = Environment.GetEnvironmentVariable ("XDG_DATA_HOME");
if (string.IsNullOrEmpty (prefix))
prefix = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".local/share");
s_EditorPrefsPath = Path.Combine (prefix, "unity3d/prefs");
}
return s_EditorPrefsPath;
}
}
#region " BasePreferenceProvider "
public override void SetKeyValue(string valueName, object newValue)
{
if (valueName == null)
throw new ArgumentNullException("valueName");
if (newValue == null)
throw new ArgumentNullException("newValue");
XmlDocument prefs = LoadPrefsFile ();
XmlElement oldElement = (XmlElement)prefs.SelectSingleNode (string.Format ("/unity_prefs/pref[@name='{0}']", valueName));
if (oldElement == null)
{
// Ugh, create new element
oldElement = prefs.CreateElement ("pref");
XmlAttribute name = prefs.CreateAttribute ("name");
name.Value = valueName;
XmlAttribute type = prefs.CreateAttribute ("type");
type.Value = FormatType (newValue.GetType ());
oldElement.Attributes.Append (name);
oldElement.Attributes.Append (type);
prefs.DocumentElement.AppendChild (oldElement);
}
oldElement.InnerText = FormatValue (newValue);
try
{
prefs.Save (EditorPrefsPath);
}
catch (Exception e)
{
Debug.LogErrorFormat ("Error saving editor prefs to '{0}'", EditorPrefsPath);
Debug.LogException (e);
}
}
public override void FetchKeyValues(IDictionary<string, object> prefsLookup)
{
XmlDocument prefs = LoadPrefsFile ();
foreach (XmlElement pref in prefs.SelectNodes ("/unity_prefs/pref").OfType<XmlElement> ())
{
try
{
prefsLookup[pref.Attributes["name"].Value] = ParseValue (pref.Attributes["type"].Value, pref.InnerText);
}
catch (Exception e)
{
// Bogus pref, don't care
Debug.LogErrorFormat ("Error parsing pref '{0}'", pref.OuterXml);
Debug.LogException (e);
}
}
}
#endregion
static XmlDocument LoadPrefsFile ()
{
var prefs = new XmlDocument ();
try
{
prefs.Load (EditorPrefsPath);
}
catch (Exception e)
{
Debug.LogError ("Error fetching prefs");
Debug.LogException (e);
}
return prefs;
}
static object ParseValue (string prefType, string value)
{
switch (prefType)
{
case "string":
// strings are base64-encoded
return Convert.FromBase64String (value);
case "int":
{
int parsed;
if (!int.TryParse (value, NumberStyles.Any, CultureInfo.InvariantCulture, out parsed))
Debug.LogErrorFormat ("Error parsing int pref '{0}'", value);
return parsed;
}
case "float":
{
float parsed;
if (!float.TryParse (value, NumberStyles.Any, CultureInfo.InvariantCulture, out parsed))
Debug.LogErrorFormat ("Error parsing float pref '{0}'", value);
return parsed;
}
default:
Debug.LogErrorFormat ("Unknown pref type '{0}'", prefType);
return null;
}
}
static string FormatValue (object value)
{
// TODO: ugh
if (value is byte[])
return Convert.ToBase64String ((byte[])value);
else if (value is int)
return ((int)value).ToString (CultureInfo.InvariantCulture);
else if (value is float)
return ((float)value).ToString (CultureInfo.InvariantCulture);
Debug.LogErrorFormat ("Don't know how to format type '{0}'", value.GetType ().FullName);
return string.Empty;
}
static string FormatType (Type type)
{
if (type == typeof (byte[]))
return "string";
if (type == typeof (int))
return "int";
if (type == typeof (float))
return "float";
Debug.LogErrorFormat ("Don't know how to format type '{0}'", type.FullName);
return string.Empty;
}
} | 26.431373 | 123 | 0.692878 | [
"MIT"
] | CapnRat/Unity-Utilities | Assets/Editor/LinuxPreferenceProvider.cs | 4,046 | C# |
using Game.Managers;
using Game.Tasks;
using Mirror;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(InteractionListener))]
public class InteractiveTask : NetworkBehaviour {
[SyncVar]
public string TaskName;
[SyncVar]
public Task Task;
public InteractionListener InteractionListener { get; private set; }
public void SetTask(Task task)
{
Task = task;
}
private void Start() {
InteractionListener = gameObject.GetComponent<InteractionListener>();
InteractionListener.OnInteraction.AddListener(Trigger);
if (!string.IsNullOrEmpty(TaskName))
Task = TaskManager.Task(TaskName);
}
private void OnDestroy() {
InteractionListener.OnInteraction.RemoveListener(Trigger);
}
public void Trigger() {
TaskManager.TriggeredTask(Task);
}
}
| 22.642857 | 77 | 0.701367 | [
"MIT"
] | benedekdaniel/Gravitational-Waves | Assets/Scripts/Interaction/InteractiveTask.cs | 951 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client
{
static class MessageSystemPropertyNames
{
public const string MessageId = "message-id";
public const string LockToken = "iothub-messagelocktoken";
public const string SequenceNumber = "sequence-number";
public const string To = "to";
public const string EnqueuedTime = "iothub-enqueuedtime";
public const string ExpiryTimeUtc = "absolute-expiry-time";
public const string CorrelationId = "correlation-id";
public const string DeliveryCount = "iothub-deliverycount";
public const string UserId = "user-id";
public const string Operation = "iothub-operation";
public const string Ack = "iothub-ack";
public const string OutputName = "iothub-outputname";
public const string InputName = "iothub-inputname";
public const string MessageSchema = "iothub-message-schema";
public const string CreationTimeUtc = "iothub-creation-time-utc";
public const string ContentEncoding = "iothub-content-encoding";
public const string ContentType = "iothub-content-type";
public const string ConnectionDeviceId = "iothub-connection-device-id";
public const string ConnectionModuleId = "iothub-connection-module-id";
public const string DiagId = "iothub-diag-id";
public const string DiagCorrelationContext = "diag-correlation-context";
public const string InterfaceId = "iothub-interface-id";
}
} | 32.346154 | 101 | 0.694411 | [
"MIT"
] | Oaz/azure-iot-sdk-csharp | iothub/device/src/MessageSystemPropertyNames.cs | 1,684 | C# |
using System;
using System.Reflection;
namespace IOT.Areas.HelpPage.ModelDescriptions
{
public interface IModelDocumentationProvider
{
string GetDocumentation(MemberInfo member);
string GetDocumentation(Type type);
}
} | 20.666667 | 51 | 0.741935 | [
"MIT"
] | MShahzadMirza/IOTESAS | IOT/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs | 248 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.Search;
namespace Azure.Search.Models
{
internal partial class SearchDocumentsResult
{
internal static SearchDocumentsResult DeserializeSearchDocumentsResult(JsonElement element)
{
SearchDocumentsResult result = new SearchDocumentsResult();
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("@odata.count"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
result.Count = property.Value.GetInt64();
continue;
}
if (property.NameEquals("@search.coverage"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
result.Coverage = property.Value.GetDouble();
continue;
}
if (property.NameEquals("@search.facets"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
result.Facets = new Dictionary<string, IList<FacetResult>>();
foreach (var property0 in property.Value.EnumerateObject())
{
IList<FacetResult> value = new List<FacetResult>();
foreach (var item in property0.Value.EnumerateArray())
{
value.Add(FacetResult.DeserializeFacetResult(item));
}
result.Facets.Add(property0.Name, value);
}
continue;
}
if (property.NameEquals("@search.nextPageParameters"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
result.NextPageParameters = SearchOptions.DeserializeSearchOptions(property.Value);
continue;
}
if (property.NameEquals("value"))
{
foreach (var item in property.Value.EnumerateArray())
{
result.Results.Add(SearchResult.DeserializeSearchResult(item));
}
continue;
}
if (property.NameEquals("@odata.nextLink"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
result.NextLink = property.Value.GetString();
continue;
}
}
return result;
}
}
}
| 36.05618 | 103 | 0.45497 | [
"MIT"
] | Kishp01/azure-sdk-for-net | sdk/search/Azure.Search/src/Generated/Models/SearchDocumentsResult.Serialization.cs | 3,209 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using Uno.EventsComponents;
using Uno.Players;
using System.Linq;
namespace Uno
{
[Serializable]
class UnoTournament
{
private List<Player> mPlayers;
private int mWinThreshold = 500;
public UnoTournament()
{
mPlayers = new List<Player>();
SubscribeEvents();
}
public List<Player> UnoGames
{
get { return mPlayers; }
}
/// <summary>
/// used as an method so subscribers can be initialised after loading from file.
/// </summary>
public void SubscribeEvents()
{
EventPublisher.RaiseAddToTournament += AddGameToTournament;
EventPublisher.RaiseUnsubscribeTournamentEvents += UnoTournament_UnsubscribeTournamentEvents;
}
/// <summary>
/// Used to ensure no duplicate events are triggered before garbage collection after loading or creating new instances
/// </summary>
/// <param name="sender">always null</param>
/// <param name="eventArgs">always null</param>
private void UnoTournament_UnsubscribeTournamentEvents(object sender, EventArgs eventArgs)
{
EventPublisher.RaiseAddToTournament -= AddGameToTournament;
EventPublisher.RaiseUnsubscribeTournamentEvents -= UnoTournament_UnsubscribeTournamentEvents;
}
/// <summary>
/// Checks for matching player entries, if found adds the new score to the last
/// If not found adds a new player to the contestents.
/// Reports score or winner
/// </summary>
/// <param name="pPlayer">player object containing all player details</param>
public void AddGameToTournament(object sender, EventArgsAddToTournament eventArgsAddTo)
{
if (mPlayers.Count == 0)
{
mPlayers.Add(eventArgsAddTo.WinningPlayer);
CheckForWinner(eventArgsAddTo.WinningPlayer);
}
else
{
bool playerFound = false;
foreach (Player player in mPlayers)
{
if (player.Name == eventArgsAddTo.WinningPlayer.Name)
{
player.FinalScore += eventArgsAddTo.WinningPlayer.FinalScore;
playerFound = true;
CheckForWinner(player);
break;
}
}
if (!playerFound)
{
mPlayers.Add(eventArgsAddTo.WinningPlayer);
CheckForWinner(eventArgsAddTo.WinningPlayer);
}
}
}
/// <summary>
/// checks to see if the new score takes the player over the winning threshold,
/// if it does anounces it, else tells the user the points were added.
/// </summary>
/// <param name="pPlayer">player object with all details about the player.</param>
private void CheckForWinner(Player pPlayer)
{
if (pPlayer.FinalScore >= 500)
{
MessageBox.Show(pPlayer.Name + " has won the tournament", "tournament won");
}
else
{
MessageBox.Show(pPlayer.Name + "'s points have been added to the tournament", "points added");
}
EventPublisher.GameOver();
EventPublisher.MainMenu();
}
}
}
| 34.207547 | 126 | 0.559294 | [
"Unlicense"
] | sarapayne/UnoWpfDotNetCore3.1 | Uno/Uno/UnoTournament.cs | 3,628 | C# |
using RMUD;
using static RMUD.Core;
public class disambig_red_door : MudObject
{
public override void Initialize()
{
AddNoun("DOOR");
// Doors can be referred to as 'the open door' or 'the closed door' as appropriate.
AddNoun("CLOSED").When(actor => !GetProperty<bool>("open?"));
AddNoun("OPEN").When(actor => GetProperty<bool>("open?"));
SetProperty("open?", false);
SetProperty("openable?", true);
SetProperty("lockable?", true);
AddNoun("RED");
this.CheckIsMatchingKey().Do((door, key) =>
{
if (object.ReferenceEquals(key, Core.GetObject("palantine\\disambig_key")))
return CheckResult.Allow;
return CheckResult.Disallow;
});
Short = "red door";
}
}
| 26.096774 | 91 | 0.5822 | [
"MIT"
] | Blecki/RMUDReboot | DelmudDB/database/static/palantine/disambig_red_door.cs | 811 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CustomCharEdit.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CustomCharEdit.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 33.847222 | 165 | 0.690193 | [
"MIT"
] | Celarix/Misc | LCDBoardController/CustomCharEdit/Properties/Resources.Designer.cs | 2,439 | C# |
/*
Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com)
This file is part of Highlander Project https://github.com/alexanderwatt/Highlander.Net
Highlander is free software: you can redistribute it and/or modify it
under the terms of the Highlander license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/alexanderwatt/Highlander.Net/blob/develop/LICENSE>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
namespace Orion.Analytics.Options
{
/// <summary>
/// Class that encapsulates a Black vanilla European swaption.
/// The principal method offered to clients of the class is the
/// functionality to price European payer and receiver swaptions.
/// No data validation of inputs is performed by the class.
/// </summary>
public class BlackVanillaSwaption
{
#region Public Enum for Valid Swaption Types
/// <summary>
/// Enumerated type for the category of valid Black vanilla swaptions.
/// </summary>
public enum SwaptionType
{
/// <summary>
/// Payer swaption.
/// </summary>
Payer,
/// <summary>
/// Receiver swaption
/// </summary>
Receiver
}
#endregion Public Enum for Valid Swaption Types
#region Constructor
/// <summary>
/// Constructor for the class <see cref="BlackVanillaSwaption"/>.
/// </summary>
/// <param name="swaptionType">Identifier for the swaption type.</param>
/// <param name="strike">Swaption strike expressed as a decimal.
/// Example: 0.09 for a strike of 9%.</param>
/// <param name="optionExpiry">Option expiry expressed in years.
/// Example: 0.5 for a 6 month option expiry.</param>
public BlackVanillaSwaption(SwaptionType swaptionType, double strike, double optionExpiry)
{
// Initialise all private fields.
_swaptionType = swaptionType;
_strike = strike;
_optionExpiry = optionExpiry;
}
#endregion Constructor
#region Public Business Logic Methods
/// <summary>
/// Functionality to price a Black vanilla swaption.
/// </summary>
/// <param name="swapRate">Swap rate expressed as a decimal.
/// Example: 0.07 for a swap rate of 7%.</param>
/// <param name="annuityFactor">Annuity factor, for the swap
/// associated with the swaption.</param>
/// <param name="sigma">Black yield volatility expressed as a decimal.
/// Example: 0.1191 for a volatility of 11.91%.</param>
/// <returns>Price of a Black vanilla swaption.</returns>
public double PriceBlackVanillaSwaption(double swapRate, double annuityFactor, double sigma)
{
var price = _swaptionType == SwaptionType.Payer
? PriceBlackVanillaPayerSwaption(swapRate, annuityFactor, sigma)
: PriceBlackVanillaReceiverSwaption(swapRate, annuityFactor, sigma);
return price;
}
#endregion Public Business Logic Methods
#region Private Helper Business Logic Methods
/// <summary>
/// Functionality to price a Black vanilla payer swaption.
/// </summary>
/// <param name="swapRate">Swap rate expressed as a decimal.
/// Example: 0.07 for a swap rate of 7%.</param>
/// <param name="annuityFactor">Annuity factor, for the swap
/// associated with the swaption.</param>
/// <param name="sigma">Black yield volatility expressed as a decimal.
/// Example: 0.1191 for a volatility of 11.91%.</param>
/// <returns>Price of a Black vanilla payer swaption.</returns>
private double PriceBlackVanillaPayerSwaption(double swapRate, double annuityFactor, double sigma)
{
var model = new BlackScholesMertonModel(true, swapRate, _strike, sigma, _optionExpiry);
// Compute and return the price of a Black vanilla payer swaption.
var price = annuityFactor * model.Value;
return price;
}
/// <summary>
/// Functionality to price a Black vanilla receiver swaption.
/// </summary>
/// <param name="swapRate">Swap rate expressed as a decimal.
/// Example: 0.07 for a swap rate of 7%.</param>
/// <param name="annuityFactor">Annuity factor, for the swap
/// associated with the swaption.</param>
/// <param name="sigma">Black yield volatility expressed as a decimal.
/// Example: 0.1191 for a volatility of 11.91%.</param>
/// <returns>Price of a Black vanilla receiver swaption.</returns>
private double PriceBlackVanillaReceiverSwaption(double swapRate, double annuityFactor, double sigma)
{
var model = new BlackScholesMertonModel(false, swapRate, _strike, sigma, _optionExpiry);
// Compute and return the price of a Black vanilla payer swaption.
var price = annuityFactor * model.Value;
return price;
}
#endregion Private Helper Business Logic Methods
#region Private Fields
/// <summary>
/// Option expiry expressed in years.
/// Example: 0.5 for a 6 month option expiry.
/// </summary>
private readonly double _optionExpiry;
/// <summary>
/// Swaption strike expressed as a decimal.
/// Example: 0.09 for a strike of 9%.
/// </summary>
private readonly double _strike;
/// <summary>
/// Identifier for the swaption type.
/// </summary>
private readonly SwaptionType _swaptionType;
#endregion Private Fields
}
} | 40.831081 | 109 | 0.625352 | [
"BSD-3-Clause"
] | mmrath/Highlander.Net | Metadata/FpML.V5r3/FpML.V5r3.Reporting.Analytics/Options/BlackVanillaSwaption.cs | 6,043 | C# |
/// Created by Ferdowsur Asif @ Tiny Giant Studios
using UnityEditor;
using UnityEngine;
namespace MText
{
[CustomEditor(typeof(MText_LoopAnimation))]
public class MText_LoopAnimationEditor : Editor
{
MText_LoopAnimation myTarget;
SerializedObject soTarget;
void OnEnable()
{
myTarget = (MText_LoopAnimation)target;
soTarget = new SerializedObject(target);
}
public override void OnInspectorGUI()
{
soTarget.Update();
EditorGUI.BeginChangeCheck();
DrawDefaultInspector();
WarningCheck();
if (EditorGUI.EndChangeCheck())
{
soTarget.ApplyModifiedProperties();
}
}
private void WarningCheck()
{
EditorGUI.indentLevel = 0;
if (!myTarget.GetComponent<Modular3DText>()) { EditorGUILayout.HelpBox("Modular 3D Text is needed for this to work", MessageType.Error); }
else
{
if (myTarget.GetComponent<Modular3DText>().combineMeshInEditor || myTarget.GetComponent<Modular3DText>().combineMeshDuringRuntime)
{
EditorGUILayout.HelpBox("Turn off single for animation to work. The option is found in Modular 3D Text, Advanced Settings", MessageType.Warning);
}
}
GUILayout.Space(5);
}
}
} | 30.808511 | 165 | 0.587017 | [
"MIT"
] | Aupuma/Immersal-Fork | Assets/Tiny Giant Studio/Modular 3D Text/Scripts/Editor/MText_LoopAnimationEditor.cs | 1,450 | C# |
using System;
using System.Linq;
using System.Reflection;
using Contentful.Core.Models.Management;
using Forte.ContentfulSchema.ContentTypes;
using Forte.ContentfulSchema.Conventions;
using Forte.ContentfulSchema.Discovery;
using Moq;
using Xunit;
namespace Forte.ContentfulSchema.Tests.Conventions
{
public class DefaultFieldControlConventionTests
{
private readonly IFieldControlConvention _defaultConvention = DefaultFieldControlConvention.Default;
[Fact]
public void ShouldReturnSlugEditorWidgetIdForSlugNamedProperty()
{
var propInfo = GetPropertyInfoOfFirstProperty<ClassWithSlugProperty>();
var widgetId = _defaultConvention.GetWidgetId(propInfo);
Assert.Equal(SystemWidgetIds.SlugEditor,widgetId);
}
[Fact]
public void ShouldReturnMultipleLineEditorWidgetIdForPropOfILongStringType()
{
var propInfo = GetPropertyInfoOfFirstProperty<ClassWithILongProperty>();
var widgetId = _defaultConvention.GetWidgetId(propInfo);
Assert.Equal(SystemWidgetIds.MultipleLine,widgetId);
}
[Fact]
public void ShouldReturnMarkdownWidgetIdForPropOfIMarkdownStringType()
{
var propInfo = GetPropertyInfoOfFirstProperty<ClassWithIMarkdownString>();
var widgetId = _defaultConvention.GetWidgetId(propInfo);
Assert.Equal(SystemWidgetIds.Markdown,widgetId);
}
[Fact]
public void ShouldUseCustomizedDefaultConventions()
{
var conventions = new (Func<PropertyInfo, bool> Predicate, string Widget)[]
{
(p => p.Name.Equals("CustomProp"), SystemWidgetIds.Checkbox)
};
var convention = new DefaultFieldControlConvention(conventions);
var propInfo = GetPropertyInfoOfFirstProperty<ClassForCustomConvention>();
var widgetId = convention.GetWidgetId(propInfo);
Assert.Equal(SystemWidgetIds.Checkbox, widgetId);
}
private static PropertyInfo GetPropertyInfoOfFirstProperty<T>()
{
return typeof(T).GetProperties().First();
}
private class ClassWithSlugProperty
{
public string Slug { get; set; }
}
private class ClassWithILongProperty
{
public ILongString LongText { get; set; }
}
private class ClassWithIMarkdownString
{
public IMarkdownString MarkDownString{ get; set; }
}
private class ClassForCustomConvention
{
public string CustomProp { get; set; }
}
}
} | 32.301205 | 108 | 0.661693 | [
"MIT"
] | fortedigital/Contentful.Schema | Forte.ContentfulSchema.Tests/Conventions/DefaultFieldControlConventionTests.cs | 2,681 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static void Main(string[] args)
{
try
{
List<Private> privates = new List<Private>();
string command = string.Empty;
while ((command = Console.ReadLine()) != "End")
{
string[] commandARgs = command.Split(" ", StringSplitOptions.RemoveEmptyEntries);
string soldierType = commandARgs[0];
ParseCommands(privates, commandARgs, soldierType);
}
}
catch (ArgumentException ex)
{
}
}
private static void ParseCommands(List<Private> privates, string[] commandARgs, string soldierType)
{
switch (soldierType)
{
case "Private":
Soldier privateSoldier = new Private(int.Parse(commandARgs[1]),
commandARgs[2], commandARgs[3], decimal.Parse(commandARgs[4]));
privates.Add((Private)privateSoldier);
Console.WriteLine(privateSoldier);
break;
case "Spy":
Spy spy = new Spy(int.Parse(commandARgs[1]), commandARgs[2], (commandARgs[3]), int.Parse(commandARgs[4]));
Console.WriteLine(spy);
break;
case "LeutenantGeneral":
Soldier leutenantGeneral = new LeutenantGeneral(int.Parse(commandARgs[1]), commandARgs[2], commandARgs[3], decimal.Parse(commandARgs[4]));
Console.WriteLine(leutenantGeneral);
for (int i = privates.Count - 1; i >= 0; i--)
{
Console.WriteLine($" {privates[i]}");
}
break;
case "Commando":
if (commandARgs.Length == 6)
{
Soldier commando = new Commando(int.Parse(commandARgs[1]), commandARgs[2], commandARgs[3], decimal.Parse(commandARgs[4]), commandARgs[5]);
Console.WriteLine(commando);
}
else
{
Soldier commando = new Commando(int.Parse(commandARgs[1]), commandARgs[2], commandARgs[3], decimal.Parse(commandARgs[4]), commandARgs[5], commandARgs[commandARgs.Length - 2], commandARgs[commandARgs.Length - 1]);
Console.WriteLine(commando);
}
break;
case "Engineer":
int id = int.Parse(commandARgs[1]);
var firstName = commandARgs[2];
var lastName = commandARgs[3];
decimal salary = decimal.Parse(commandARgs[4]);
string corps = commandARgs[5];
if (commandARgs.Length == 6)
{
Engineer engineer = new Engineer(firstName, lastName, id, salary, corps);
Console.WriteLine(engineer);
}
else
{
List<Engineer> engineers = new List<Engineer>();
for (int i = 6; i < commandARgs.Length; i += 2)
{
string partName = commandARgs[i];
int hourseWorked = int.Parse(commandARgs[i + 1]);
Engineer engineer = new Engineer(firstName, lastName, id, salary, corps, partName, hourseWorked);
engineers.Add(engineer);
engineer.AddToDict(partName, hourseWorked);
}
Console.WriteLine(engineers.First());
foreach (var item in engineers)
{
Console.WriteLine($" Part Name: {item.PartName} Hours Worked: {item.HouresWorked}");
}
}
break;
}
}
}
| 38.74 | 232 | 0.500516 | [
"MIT"
] | giggals/Software-University | Exercises-Interfaces/8.MilitaryElite/Program.cs | 3,876 | C# |
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using NAudio.Utils;
namespace NAudio.Wave
{
/// <summary>
/// Represents a Wave file format
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=2)]
public class WaveFormat
{
/// <summary>format type</summary>
protected WaveFormatEncoding waveFormatTag;
/// <summary>number of channels</summary>
protected short channels;
/// <summary>sample rate</summary>
protected int sampleRate;
/// <summary>for buffer estimation</summary>
protected int averageBytesPerSecond;
/// <summary>block size of data</summary>
protected short blockAlign;
/// <summary>number of bits per sample of mono data</summary>
protected short bitsPerSample;
/// <summary>number of following bytes</summary>
protected short extraSize;
/// <summary>
/// Creates a new PCM 44.1Khz stereo 16 bit format
/// </summary>
public WaveFormat() : this(44100,16,2)
{
}
/// <summary>
/// Creates a new 16 bit wave format with the specified sample
/// rate and channel count
/// </summary>
/// <param name="sampleRate">Sample Rate</param>
/// <param name="channels">Number of channels</param>
public WaveFormat(int sampleRate, int channels)
: this(sampleRate, 16, channels)
{
}
/// <summary>
/// Gets the size of a wave buffer equivalent to the latency in milliseconds.
/// </summary>
/// <param name="milliseconds">The milliseconds.</param>
/// <returns></returns>
public int ConvertLatencyToByteSize(int milliseconds)
{
int bytes = (int) ((AverageBytesPerSecond/1000.0)*milliseconds);
if ((bytes%BlockAlign) != 0)
{
// Return the upper BlockAligned
bytes = bytes + BlockAlign - (bytes % BlockAlign);
}
return bytes;
}
/// <summary>
/// Creates a WaveFormat with custom members
/// </summary>
/// <param name="tag">The encoding</param>
/// <param name="sampleRate">Sample Rate</param>
/// <param name="channels">Number of channels</param>
/// <param name="averageBytesPerSecond">Average Bytes Per Second</param>
/// <param name="blockAlign">Block Align</param>
/// <param name="bitsPerSample">Bits Per Sample</param>
/// <returns></returns>
public static WaveFormat CreateCustomFormat(WaveFormatEncoding tag, int sampleRate, int channels, int averageBytesPerSecond, int blockAlign, int bitsPerSample)
{
WaveFormat waveFormat = new WaveFormat();
waveFormat.waveFormatTag = tag;
waveFormat.channels = (short)channels;
waveFormat.sampleRate = sampleRate;
waveFormat.averageBytesPerSecond = averageBytesPerSecond;
waveFormat.blockAlign = (short)blockAlign;
waveFormat.bitsPerSample = (short)bitsPerSample;
waveFormat.extraSize = 0;
return waveFormat;
}
/// <summary>
/// Creates an A-law wave format
/// </summary>
/// <param name="sampleRate">Sample Rate</param>
/// <param name="channels">Number of Channels</param>
/// <returns>Wave Format</returns>
public static WaveFormat CreateALawFormat(int sampleRate, int channels)
{
return CreateCustomFormat(WaveFormatEncoding.ALaw, sampleRate, channels, sampleRate * channels, channels, 8);
}
/// <summary>
/// Creates a Mu-law wave format
/// </summary>
/// <param name="sampleRate">Sample Rate</param>
/// <param name="channels">Number of Channels</param>
/// <returns>Wave Format</returns>
public static WaveFormat CreateMuLawFormat(int sampleRate, int channels)
{
return CreateCustomFormat(WaveFormatEncoding.MuLaw, sampleRate, channels, sampleRate * channels, channels, 8);
}
/// <summary>
/// Creates a new PCM format with the specified sample rate, bit depth and channels
/// </summary>
public WaveFormat(int rate, int bits, int channels)
{
if (channels < 1)
{
throw new ArgumentOutOfRangeException(nameof(channels), "Channels must be 1 or greater");
}
// minimum 16 bytes, sometimes 18 for PCM
waveFormatTag = WaveFormatEncoding.Pcm;
this.channels = (short)channels;
sampleRate = rate;
bitsPerSample = (short)bits;
extraSize = 0;
blockAlign = (short)(channels * (bits / 8));
averageBytesPerSecond = this.sampleRate * this.blockAlign;
}
/// <summary>
/// Creates a new 32 bit IEEE floating point wave format
/// </summary>
/// <param name="sampleRate">sample rate</param>
/// <param name="channels">number of channels</param>
public static WaveFormat CreateIeeeFloatWaveFormat(int sampleRate, int channels)
{
var wf = new WaveFormat();
wf.waveFormatTag = WaveFormatEncoding.IeeeFloat;
wf.channels = (short)channels;
wf.bitsPerSample = 32;
wf.sampleRate = sampleRate;
wf.blockAlign = (short) (4*channels);
wf.averageBytesPerSecond = sampleRate * wf.blockAlign;
wf.extraSize = 0;
return wf;
}
/// <summary>
/// Helper function to retrieve a WaveFormat structure from a pointer
/// </summary>
/// <param name="pointer">WaveFormat structure</param>
/// <returns></returns>
public static WaveFormat MarshalFromPtr(IntPtr pointer)
{
var waveFormat = Marshal.PtrToStructure<WaveFormat>(pointer);
switch (waveFormat.Encoding)
{
case WaveFormatEncoding.Pcm:
// can't rely on extra size even being there for PCM so blank it to avoid reading
// corrupt data
waveFormat.extraSize = 0;
break;
case WaveFormatEncoding.Extensible:
waveFormat = Marshal.PtrToStructure<WaveFormatExtensible>(pointer);
break;
case WaveFormatEncoding.Adpcm:
waveFormat = Marshal.PtrToStructure<AdpcmWaveFormat>(pointer);
break;
case WaveFormatEncoding.Gsm610:
waveFormat = Marshal.PtrToStructure<Gsm610WaveFormat>(pointer);
break;
default:
if (waveFormat.ExtraSize > 0)
{
waveFormat = Marshal.PtrToStructure<WaveFormatExtraData>(pointer);
}
break;
}
return waveFormat;
}
/// <summary>
/// Helper function to marshal WaveFormat to an IntPtr
/// </summary>
/// <param name="format">WaveFormat</param>
/// <returns>IntPtr to WaveFormat structure (needs to be freed by callee)</returns>
public static IntPtr MarshalToPtr(WaveFormat format)
{
int formatSize = Marshal.SizeOf(format);
IntPtr formatPointer = Marshal.AllocHGlobal(formatSize);
Marshal.StructureToPtr(format, formatPointer, false);
return formatPointer;
}
/// <summary>
/// Reads in a WaveFormat (with extra data) from a fmt chunk (chunk identifier and
/// length should already have been read)
/// </summary>
/// <param name="br">Binary reader</param>
/// <param name="formatChunkLength">Format chunk length</param>
/// <returns>A WaveFormatExtraData</returns>
public static WaveFormat FromFormatChunk(BinaryReader br, int formatChunkLength)
{
var waveFormat = new WaveFormatExtraData();
waveFormat.ReadWaveFormat(br, formatChunkLength);
waveFormat.ReadExtraData(br);
return waveFormat;
}
private void ReadWaveFormat(BinaryReader br, int formatChunkLength)
{
if (formatChunkLength < 16)
throw new InvalidDataException("Invalid WaveFormat Structure");
waveFormatTag = (WaveFormatEncoding)br.ReadUInt16();
channels = br.ReadInt16();
sampleRate = br.ReadInt32();
averageBytesPerSecond = br.ReadInt32();
blockAlign = br.ReadInt16();
bitsPerSample = br.ReadInt16();
if (formatChunkLength > 16)
{
extraSize = br.ReadInt16();
if (extraSize != formatChunkLength - 18)
{
Debug.WriteLine("Format chunk mismatch");
extraSize = (short)(formatChunkLength - 18);
}
}
}
/// <summary>
/// Reads a new WaveFormat object from a stream
/// </summary>
/// <param name="br">A binary reader that wraps the stream</param>
public WaveFormat(BinaryReader br)
{
int formatChunkLength = br.ReadInt32();
ReadWaveFormat(br, formatChunkLength);
}
/// <summary>
/// Reports this WaveFormat as a string
/// </summary>
/// <returns>String describing the wave format</returns>
public override string ToString()
{
switch (waveFormatTag)
{
case WaveFormatEncoding.Pcm:
case WaveFormatEncoding.Extensible:
// extensible just has some extra bits after the PCM header
return $"{bitsPerSample} bit PCM: {sampleRate/1000}kHz {channels} channels";
default:
return waveFormatTag.ToString();
}
}
/// <summary>
/// Compares with another WaveFormat object
/// </summary>
/// <param name="obj">Object to compare to</param>
/// <returns>True if the objects are the same</returns>
public override bool Equals(object obj)
{
var other = obj as WaveFormat;
if(other != null)
{
return waveFormatTag == other.waveFormatTag &&
channels == other.channels &&
sampleRate == other.sampleRate &&
averageBytesPerSecond == other.averageBytesPerSecond &&
blockAlign == other.blockAlign &&
bitsPerSample == other.bitsPerSample;
}
return false;
}
/// <summary>
/// Provides a Hashcode for this WaveFormat
/// </summary>
/// <returns>A hashcode</returns>
public override int GetHashCode()
{
return (int) waveFormatTag ^
(int) channels ^
sampleRate ^
averageBytesPerSecond ^
(int) blockAlign ^
(int) bitsPerSample;
}
/// <summary>
/// Returns the encoding type used
/// </summary>
public WaveFormatEncoding Encoding => waveFormatTag;
/// <summary>
/// Writes this WaveFormat object to a stream
/// </summary>
/// <param name="writer">the output stream</param>
public virtual void Serialize(BinaryWriter writer)
{
writer.Write((int)(18 + extraSize)); // wave format length
writer.Write((short)Encoding);
writer.Write((short)Channels);
writer.Write((int)SampleRate);
writer.Write((int)AverageBytesPerSecond);
writer.Write((short)BlockAlign);
writer.Write((short)BitsPerSample);
writer.Write((short)extraSize);
}
/// <summary>
/// Returns the number of channels (1=mono,2=stereo etc)
/// </summary>
public int Channels => channels;
/// <summary>
/// Returns the sample rate (samples per second)
/// </summary>
public int SampleRate => sampleRate;
/// <summary>
/// Returns the average number of bytes used per second
/// </summary>
public int AverageBytesPerSecond => averageBytesPerSecond;
/// <summary>
/// Returns the block alignment
/// </summary>
public virtual int BlockAlign => blockAlign;
/// <summary>
/// Returns the number of bits per sample (usually 16 or 32, sometimes 24 or 8)
/// Can be 0 for some codecs
/// </summary>
public int BitsPerSample => bitsPerSample;
/// <summary>
/// Returns the number of extra bytes used by this waveformat. Often 0,
/// except for compressed formats which store extra data after the WAVEFORMATEX header
/// </summary>
public int ExtraSize => extraSize;
}
}
| 38.361272 | 167 | 0.562721 | [
"MIT"
] | ArisAgnew/NAudio | NAudio.Core/Wave/WaveFormats/WaveFormat.cs | 13,273 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.aliyuncvc.Model.V20191030
{
public class GetUserResponse : AcsResponse
{
private int? errorCode;
private string message;
private bool? success;
private string requestId;
private GetUser_UserInfo userInfo;
public int? ErrorCode
{
get
{
return errorCode;
}
set
{
errorCode = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public GetUser_UserInfo UserInfo
{
get
{
return userInfo;
}
set
{
userInfo = value;
}
}
public class GetUser_UserInfo
{
private string userName;
private long? createTime;
private string groupId;
private string groupName;
private string userId;
private string userTel;
private string userEmail;
private string userMobile;
private string userAvatarUrl;
private string departId;
private string departName;
public string UserName
{
get
{
return userName;
}
set
{
userName = value;
}
}
public long? CreateTime
{
get
{
return createTime;
}
set
{
createTime = value;
}
}
public string GroupId
{
get
{
return groupId;
}
set
{
groupId = value;
}
}
public string GroupName
{
get
{
return groupName;
}
set
{
groupName = value;
}
}
public string UserId
{
get
{
return userId;
}
set
{
userId = value;
}
}
public string UserTel
{
get
{
return userTel;
}
set
{
userTel = value;
}
}
public string UserEmail
{
get
{
return userEmail;
}
set
{
userEmail = value;
}
}
public string UserMobile
{
get
{
return userMobile;
}
set
{
userMobile = value;
}
}
public string UserAvatarUrl
{
get
{
return userAvatarUrl;
}
set
{
userAvatarUrl = value;
}
}
public string DepartId
{
get
{
return departId;
}
set
{
departId = value;
}
}
public string DepartName
{
get
{
return departName;
}
set
{
departName = value;
}
}
}
}
}
| 14.245136 | 63 | 0.542202 | [
"Apache-2.0"
] | hl8080/aliyun-openapi-net-sdk | aliyun-net-sdk-aliyuncvc/Aliyuncvc/Model/V20191030/GetUserResponse.cs | 3,661 | C# |
using Microsoft.Identity.Client;
using Xamarin.Forms;
namespace UserDetailsClient
{
public class App : Application
{
public static IPublicClientApplication PCA = null;
/// <summary>
/// The ClientID is the Application ID found in the portal (https://go.microsoft.com/fwlink/?linkid=2083908).
/// You can use the below id however if you create an app of your own you should replace the value here.
/// </summary>
public static string ClientID = "4a1aa1d5-c567-49d0-ad0b-cd957a47f842";
public const string BrokerRedirectUriOnIos = "msauth.com.yourcompany.UserDetailsClient://auth";
public static string[] Scopes = { "User.Read" };
public static string Username = string.Empty;
public static object ParentWindow { get; set; }
public App()
{
PCA = PublicClientApplicationBuilder.Create(ClientID)
.WithRedirectUri($"msal{ClientID}://auth")
.Build();
MainPage = new NavigationPage(new UserDetailsClient.MainPage());
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| 30.12766 | 118 | 0.605932 | [
"MIT"
] | Sidharthan1988/active-directory-xamarin-native-v2 | 2-With-broker/UserDetailsClient/UserDetailsClient/App.cs | 1,418 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using VMS.TPS.Common.Model.API;
using VMS.TPS.Common.Model.Types;
namespace PlanCheck.Calculators
{
class PQMMinMaxMean
{
public static string GetMinMaxMean(StructureSet structureSet, PlanningItemViewModel planningItem, StructureViewModel evalStructure, MatchCollection testMatch, Group evalunit, Group type)
{
try
{
var structure = structureSet.Structures.FirstOrDefault(x => x.Id == evalStructure.StructureName);
if (type.Value.CompareTo("Volume") == 0)
{
return string.Format("{0:0.00} {1}", evalStructure.VolumeValue, evalunit.Value);
}
else
{
double planSumRxDose = 0;
DVHData dvh;
DoseValuePresentation dvp = (evalunit.Value.CompareTo("%") == 0) ? DoseValuePresentation.Relative : DoseValuePresentation.Absolute;
if (dvp == DoseValuePresentation.Relative && planningItem.PlanningItemObject is PlanSum)
{
PlanSum planSum = (PlanSum)planningItem.PlanningItemObject;
foreach (PlanSetup planSetup in planSum.PlanSetups)
{
double planSetupRxDose = planSetup.TotalDose.Dose;
planSumRxDose += planSetupRxDose;
}
dvh = planningItem.PlanningItemObject.GetDVHCumulativeData(structure, DoseValuePresentation.Absolute, VolumePresentation.Relative, 0.1);
}
else
dvh = planningItem.PlanningItemObject.GetDVHCumulativeData(structure, dvp, VolumePresentation.Relative, 0.1);
if (type.Value.CompareTo("Max") == 0)
{
//checking dose output unit and adapting to template
//Gy to cGy
if ((evalunit.Value.CompareTo("Gy") == 0) && (dvh.MaxDose.Unit.CompareTo(DoseValue.DoseUnit.cGy) == 0))
{
return new DoseValue(dvh.MaxDose.Dose / 100, DoseValue.DoseUnit.Gy).ToString();
}
//Gy to Gy or % to %
else
{
if (dvp == DoseValuePresentation.Relative && planningItem.PlanningItemObject is PlanSum)
{
double maxDoseDouble = double.Parse(dvh.MaxDose.ValueAsString);
//double
return (maxDoseDouble / planSumRxDose * 100).ToString("0.0") + " " + evalunit.Value;
}
else
return dvh.MaxDose.ToString();
}
}
else if (type.Value.CompareTo("Min") == 0)
{
//checking dose output unit and adapting to template
//Gy to cGy
if ((evalunit.Value.CompareTo("Gy") == 0) && (dvh.MinDose.Unit.CompareTo(DoseValue.DoseUnit.cGy) == 0))
{
return new DoseValue(dvh.MinDose.Dose / 100, DoseValue.DoseUnit.Gy).ToString();
}
//Gy to Gy or % to %
else
{
return dvh.MinDose.ToString();
}
}
else
{
//checking dose output unit and adapting to template
//Gy to cGy
if ((evalunit.Value.CompareTo("Gy") == 0) && (dvh.MeanDose.Unit.CompareTo(DoseValue.DoseUnit.cGy) == 0))
{
return new DoseValue(dvh.MeanDose.Dose / 100, DoseValue.DoseUnit.Gy).ToString();
}
//Gy to Gy or % to %
else
{
return dvh.MeanDose.ToString();
}
}
}
}
catch (NullReferenceException)
{
return "Unable to calculate - DVH is not valid";
}
}
}
}
| 47.122449 | 194 | 0.461888 | [
"MIT"
] | LDClark/PlanCheck | PlanCheck.Script/Calculators/PQMMinMaxMean.cs | 4,618 | C# |
//-----------------------------------------------------------------------
// <copyright file="GravityActor.cs" company="brpeanut">
// Copyright (c), brpeanut. All rights reserved.
// </copyright>
// <summary> Base class for the gravity physics for Actors. </summary>
// <author> brpeanut/OpenMario - https://github.com/brpeanut/OpenMario </author>
//-----------------------------------------------------------------------
namespace OpenMario.Core.Actors
{
using System.Collections.Generic;
using System.Drawing;
/// <summary>
/// Base class for gravity in regards to the actors.
/// </summary>
public abstract class GravityActor : MovementActor
{
/// <summary>
/// Override of the of <see cref="BaseActor" /> Load method.
/// </summary>
/// <param name="env">
/// The <see cref="Environment" /> for the <see cref="GravityActor"/>
/// </param>
public abstract override void Load(Environment.Environment env);
/// <summary>
/// Override of the <see cref="BaseActor" /> Draw method.
/// </summary>
/// <param name="g">
/// The <see cref="Graphics"/> for <see cref="GravityActor"/> to draw.
/// </param>
public abstract override void Draw(Graphics g);
/// <summary>
/// Override of the <see cref="BaseActor" /> Move method.
/// Method is manipulated by controlling the gravity on the Actor's Y plane.
/// </summary>
public override void Move()
{
if (Velocity.Y < Physics.Physics.MaxGravity.Y)
{
this.Velocity -= Physics.Physics.Gravity;
}
else if (Velocity.Y > Physics.Physics.MaxGravity.Y)
{
this.Velocity += Physics.Physics.Gravity;
}
this.Position -= this.Velocity;
if (this.Position.X < 0)
this.Position = new VectorClass.Vector2D_Dbl(0, this.Position.Y);
if (this.Position.X >= Environment.Width - this.Width - 5)
this.Position = new VectorClass.Vector2D_Dbl(Environment.Width - this.Width - 5, this.Position.Y);
}
/// <summary>
/// Override of the <see cref="BaseActor" /> Update method
/// </summary>
/// <param name="loadedactors">
/// List of <c>BaseActor</c>
/// </param>
public override void Update(List<BaseActor> loadedactors)
{
this.Move();
}
}
} | 37.101449 | 114 | 0.522266 | [
"MIT"
] | lyshuga/OpenMario | OpenMario.Core/Actors/GravityActor.cs | 2,562 | 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.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AuditManager.Model
{
/// <summary>
/// Container for the parameters to the BatchImportEvidenceToAssessmentControl operation.
/// Uploads one or more pieces of evidence to the specified control in the assessment
/// in AWS Audit Manager.
/// </summary>
public partial class BatchImportEvidenceToAssessmentControlRequest : AmazonAuditManagerRequest
{
private string _assessmentId;
private string _controlId;
private string _controlSetId;
private List<ManualEvidence> _manualEvidence = new List<ManualEvidence>();
/// <summary>
/// Gets and sets the property AssessmentId.
/// <para>
/// The identifier for the specified assessment.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=36, Max=36)]
public string AssessmentId
{
get { return this._assessmentId; }
set { this._assessmentId = value; }
}
// Check to see if AssessmentId property is set
internal bool IsSetAssessmentId()
{
return this._assessmentId != null;
}
/// <summary>
/// Gets and sets the property ControlId.
/// <para>
/// The identifier for the specified control.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=36, Max=36)]
public string ControlId
{
get { return this._controlId; }
set { this._controlId = value; }
}
// Check to see if ControlId property is set
internal bool IsSetControlId()
{
return this._controlId != null;
}
/// <summary>
/// Gets and sets the property ControlSetId.
/// <para>
/// The identifier for the specified control set.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=300)]
public string ControlSetId
{
get { return this._controlSetId; }
set { this._controlSetId = value; }
}
// Check to see if ControlSetId property is set
internal bool IsSetControlSetId()
{
return this._controlSetId != null;
}
/// <summary>
/// Gets and sets the property ManualEvidence.
/// <para>
/// The list of manual evidence objects.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=50)]
public List<ManualEvidence> ManualEvidence
{
get { return this._manualEvidence; }
set { this._manualEvidence = value; }
}
// Check to see if ManualEvidence property is set
internal bool IsSetManualEvidence()
{
return this._manualEvidence != null && this._manualEvidence.Count > 0;
}
}
} | 32.5 | 111 | 0.587436 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/AuditManager/Generated/Model/BatchImportEvidenceToAssessmentControlRequest.cs | 3,900 | C# |
using System;
using System.Collections;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Math.EC.Endo;
using Org.BouncyCastle.Math.EC.Multiplier;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.Sec
{
public sealed class SecNamedCurves
{
private SecNamedCurves()
{
}
private static X9ECPoint ConfigureBasepoint(ECCurve curve, string encoding)
{
X9ECPoint G = new X9ECPoint(curve, Hex.DecodeStrict(encoding));
WNafUtilities.ConfigureBasepoint(G.Point);
return G;
}
private static ECCurve ConfigureCurve(ECCurve curve)
{
return curve;
}
private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p)
{
return c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create();
}
private static BigInteger FromHex(string hex)
{
return new BigInteger(1, Hex.DecodeStrict(hex));
}
/*
* secp112r1
*/
internal class Secp112r1Holder
: X9ECParametersHolder
{
private Secp112r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("DB7C2ABF62E35E668076BEAD2088");
BigInteger b = FromHex("659EF8BA043916EEDE8911702B22");
byte[] S = Hex.DecodeStrict("00F50B028E4D696E676875615175290472783FB1");
BigInteger n = FromHex("DB7C2ABF62E35E7628DFAC6561C5");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"0409487239995A5EE76B55F9C2F098A89CE5AF8724C0A23E0E0FF77500");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp112r2
*/
internal class Secp112r2Holder
: X9ECParametersHolder
{
private Secp112r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("6127C24C05F38A0AAAF65C0EF02C");
BigInteger b = FromHex("51DEF1815DB5ED74FCC34C85D709");
byte[] S = Hex.DecodeStrict("002757A1114D696E6768756151755316C05E0BD4");
BigInteger n = FromHex("36DF0AAFD8B8D7597CA10520D04B");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"044BA30AB5E892B4E1649DD0928643ADCD46F5882E3747DEF36E956E97");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r1
*/
internal class Secp128r1Holder
: X9ECParametersHolder
{
private Secp128r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("E87579C11079F43DD824993C2CEE5ED3");
byte[] S = Hex.DecodeStrict("000E0D4D696E6768756151750CC03A4473D03679");
BigInteger n = FromHex("FFFFFFFE0000000075A30D1B9038A115");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"04161FF7528B899B2D0C28607CA52C5B86CF5AC8395BAFEB13C02DA292DDED7A83");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r2
*/
internal class Secp128r2Holder
: X9ECParametersHolder
{
private Secp128r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("D6031998D1B3BBFEBF59CC9BBFF9AEE1");
BigInteger b = FromHex("5EEEFCA380D02919DC2C6558BB6D8A5D");
byte[] S = Hex.DecodeStrict("004D696E67687561517512D8F03431FCE63B88F4");
BigInteger n = FromHex("3FFFFFFF7FFFFFFFBE0024720613B5A3");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"047B6AA5D85E572983E6FB32A7CDEBC14027B6916A894D3AEE7106FE805FC34B44");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160k1
*/
internal class Secp160k1Holder
: X9ECParametersHolder
{
private Secp160k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("9ba48cba5ebcb9b6bd33b92830b2a2e0e192f10a", 16),
new BigInteger("c39c6c3b3a36d7701b9c71a1f5804ae5d0003f4", 16),
new ScalarSplitParameters(
new BigInteger[]{
new BigInteger("9162fbe73984472a0a9e", 16),
new BigInteger("-96341f1138933bc2f505", 16) },
new BigInteger[]{
new BigInteger("127971af8721782ecffa3", 16),
new BigInteger("9162fbe73984472a0a9e", 16) },
new BigInteger("9162fbe73984472a0a9d0590", 16),
new BigInteger("96341f1138933bc2f503fd44", 16),
176));
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
X9ECPoint G = ConfigureBasepoint(curve,
"043B4C382CE37AA192A4019E763036F4F5DD4D7EBB938CF935318FDCED6BC28286531733C3F03C4FEE");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r1
*/
internal class Secp160r1Holder
: X9ECParametersHolder
{
private Secp160r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^31 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
BigInteger b = FromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
byte[] S = Hex.DecodeStrict("1053CDE42C14D696E67687561517533BF3F83345");
BigInteger n = FromHex("0100000000000000000001F4C8F927AED3CA752257");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"044A96B5688EF573284664698968C38BB913CBFC8223A628553168947D59DCC912042351377AC5FB32");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r2
*/
internal class Secp160r2Holder
: X9ECParametersHolder
{
private Secp160r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70");
BigInteger b = FromHex("B4E134D3FB59EB8BAB57274904664D5AF50388BA");
byte[] S = Hex.DecodeStrict("B99B99B099B323E02709A4D696E6768756151751");
BigInteger n = FromHex("0100000000000000000000351EE786A818F3A1A16B");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"0452DCB034293A117E1F4FF11B30F7199D3144CE6DFEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192k1
*/
internal class Secp192k1Holder
: X9ECParametersHolder
{
private Secp192k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(3);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("bb85691939b869c1d087f601554b96b80cb4f55b35f433c2", 16),
new BigInteger("3d84f26c12238d7b4f3d516613c1759033b1a5800175d0b1", 16),
new ScalarSplitParameters(
new BigInteger[]{
new BigInteger("71169be7330b3038edb025f1", 16),
new BigInteger("-b3fb3400dec5c4adceb8655c", 16) },
new BigInteger[]{
new BigInteger("12511cfe811d0f4e6bc688b4d", 16),
new BigInteger("71169be7330b3038edb025f1", 16) },
new BigInteger("71169be7330b3038edb025f1d0f9", 16),
new BigInteger("b3fb3400dec5c4adceb8655d4c94", 16),
208));
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
X9ECPoint G = ConfigureBasepoint(curve,
"04DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192r1
*/
internal class Secp192r1Holder
: X9ECParametersHolder
{
private Secp192r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^64 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
byte[] S = Hex.DecodeStrict("3045AE6FC8422F64ED579528D38120EAE12196D5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"04188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224k1
*/
internal class Secp224k1Holder
: X9ECParametersHolder
{
private Secp224k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(5);
byte[] S = null;
BigInteger n = FromHex("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("fe0e87005b4e83761908c5131d552a850b3f58b749c37cf5b84d6768", 16),
new BigInteger("60dcd2104c4cbc0be6eeefc2bdd610739ec34e317f9b33046c9e4788", 16),
new ScalarSplitParameters(
new BigInteger[]{
new BigInteger("6b8cf07d4ca75c88957d9d670591", 16),
new BigInteger("-b8adf1378a6eb73409fa6c9c637d", 16) },
new BigInteger[]{
new BigInteger("1243ae1b4d71613bc9f780a03690e", 16),
new BigInteger("6b8cf07d4ca75c88957d9d670591", 16) },
new BigInteger("6b8cf07d4ca75c88957d9d67059037a4", 16),
new BigInteger("b8adf1378a6eb73409fa6c9c637ba7f5", 16),
240));
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
X9ECPoint G = ConfigureBasepoint(curve,
"04A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224r1
*/
internal class Secp224r1Holder
: X9ECParametersHolder
{
private Secp224r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^96 + 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
BigInteger b = FromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
byte[] S = Hex.DecodeStrict("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"04B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256k1
*/
internal class Secp256k1Holder
: X9ECParametersHolder
{
private Secp256k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", 16),
new BigInteger("5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", 16),
new ScalarSplitParameters(
new BigInteger[]{
new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16),
new BigInteger("-e4437ed6010e88286f547fa90abfe4c3", 16) },
new BigInteger[]{
new BigInteger("114ca50f7a8e2f3f657c1108d9d44cfd8", 16),
new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16) },
new BigInteger("3086d221a7d46bcde86c90e49284eb153dab", 16),
new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16),
272));
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
X9ECPoint G = ConfigureBasepoint(curve,
"0479BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256r1
*/
internal class Secp256r1Holder
: X9ECParametersHolder
{
private Secp256r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
BigInteger p = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
byte[] S = Hex.DecodeStrict("C49D360886E704936A6678E1139D26B7819F7E90");
BigInteger n = FromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve,
"046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp384r1
*/
internal class Secp384r1Holder
: X9ECParametersHolder
{
private Secp384r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp384r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^384 - 2^128 - 2^96 + 2^32 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC");
BigInteger b = FromHex("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF");
byte[] S = Hex.DecodeStrict("A335926AA319A27A1D00896A6773A4827ACDAC73");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"
+ "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp521r1
*/
internal class Secp521r1Holder
: X9ECParametersHolder
{
private Secp521r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp521r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^521 - 1
BigInteger p = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00");
byte[] S = Hex.DecodeStrict("D09E8800291CB85396CC6717393284AAA0DA64BA");
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"
+ "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r1
*/
internal class Sect113r1Holder
: X9ECParametersHolder
{
private Sect113r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r1Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("003088250CA6E7C7FE649CE85820F7");
BigInteger b = FromHex("00E8BEE4D3E2260744188BE0E9C723");
byte[] S = Hex.DecodeStrict("10E723AB14D696E6768756151756FEBF8FCB49A9");
BigInteger n = FromHex("0100000000000000D9CCEC8A39E56F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"04009D73616F35F4AB1407D73562C10F00A52830277958EE84D1315ED31886");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r2
*/
internal class Sect113r2Holder
: X9ECParametersHolder
{
private Sect113r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r2Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("00689918DBEC7E5A0DD6DFC0AA55C7");
BigInteger b = FromHex("0095E9A9EC9B297BD4BF36E059184F");
byte[] S = Hex.DecodeStrict("10C0FB15760860DEF1EEF4D696E676875615175D");
BigInteger n = FromHex("010000000000000108789B2496AF93");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"0401A57A6A7B26CA5EF52FCDB816479700B3ADC94ED1FE674C06E695BABA1D");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r1
*/
internal class Sect131r1Holder
: X9ECParametersHolder
{
private Sect131r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r1Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07A11B09A76B562144418FF3FF8C2570B8");
BigInteger b = FromHex("0217C05610884B63B9C6C7291678F9D341");
byte[] S = Hex.DecodeStrict("4D696E676875615175985BD3ADBADA21B43A97E2");
BigInteger n = FromHex("0400000000000000023123953A9464B54D");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"040081BAF91FDF9833C40F9C181343638399078C6E7EA38C001F73C8134B1B4EF9E150");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r2
*/
internal class Sect131r2Holder
: X9ECParametersHolder
{
private Sect131r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r2Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("03E5A88919D7CAFCBF415F07C2176573B2");
BigInteger b = FromHex("04B8266A46C55657AC734CE38F018F2192");
byte[] S = Hex.DecodeStrict("985BD3ADBAD4D696E676875615175A21B43A97E3");
BigInteger n = FromHex("0400000000000000016954A233049BA98F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"040356DCD8F2F95031AD652D23951BB366A80648F06D867940A5366D9E265DE9EB240F");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163k1
*/
internal class Sect163k1Holder
: X9ECParametersHolder
{
private Sect163k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163k1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("04000000000000000000020108A2E0CC0D99F8A5EF");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"0402FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE80289070FB05D38FF58321F2E800536D538CCDAA3D9");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r1
*/
internal class Sect163r1Holder
: X9ECParametersHolder
{
private Sect163r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07B6882CAAEFA84F9554FF8428BD88E246D2782AE2");
BigInteger b = FromHex("0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9");
byte[] S = Hex.DecodeStrict("24B7B137C8A14D696E6768756151756FD0DA2E5C");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"040369979697AB43897789566789567F787A7876A65400435EDB42EFAFB2989D51FEFCE3C80988F41FF883");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r2
*/
internal class Sect163r2Holder
: X9ECParametersHolder
{
private Sect163r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r2Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("020A601907B8C953CA1481EB10512F78744A3205FD");
byte[] S = Hex.DecodeStrict("85E25BFE5C86226CDB12016F7553F9D0E693A268");
BigInteger n = FromHex("040000000000000000000292FE77E70C12A4234C33");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"0403F0EBA16286A2D57EA0991168D4994637E8343E3600D51FBC6C71A0094FA2CDD545B11C5C0C797324F1");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r1
*/
internal class Sect193r1Holder
: X9ECParametersHolder
{
private Sect193r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r1Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01");
BigInteger b = FromHex("00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814");
byte[] S = Hex.DecodeStrict("103FAEC74D696E676875615175777FC5B191EF30");
BigInteger n = FromHex("01000000000000000000000000C7F34A778F443ACC920EBA49");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"0401F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E10025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r2
*/
internal class Sect193r2Holder
: X9ECParametersHolder
{
private Sect193r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r2Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B");
BigInteger b = FromHex("00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE");
byte[] S = Hex.DecodeStrict("10B7B4D696E676875615175137C8A16FD0DA2211");
BigInteger n = FromHex("010000000000000000000000015AAB561B005413CCD4EE99D5");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"0400D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233k1
*/
internal class Sect233k1Holder
: X9ECParametersHolder
{
private Sect233k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233k1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"04017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD612601DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233r1
*/
internal class Sect233r1Holder
: X9ECParametersHolder
{
private Sect233r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233r1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD");
byte[] S = Hex.DecodeStrict("74D59FF07F6B413D0EA14B344B20A2DB049B50C3");
BigInteger n = FromHex("01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"0400FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect239k1
*/
internal class Sect239k1Holder
: X9ECParametersHolder
{
private Sect239k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect239k1Holder();
private const int m = 239;
private const int k = 158;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve,
"0429A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283k1
*/
internal class Sect283k1Holder
: X9ECParametersHolder
{
private Sect283k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283k1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"
+ "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283r1
*/
internal class Sect283r1Holder
: X9ECParametersHolder
{
private Sect283r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283r1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5");
byte[] S = Hex.DecodeStrict("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"
+ "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409k1
*/
internal class Sect409k1Holder
: X9ECParametersHolder
{
private Sect409k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409k1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"
+ "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409r1
*/
internal class Sect409r1Holder
: X9ECParametersHolder
{
private Sect409r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409r1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F");
byte[] S = Hex.DecodeStrict("4099B5A457F9D69F79213D094C4BCD4D4262210B");
BigInteger n = FromHex("010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"
+ "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571k1
*/
internal class Sect571k1Holder
: X9ECParametersHolder
{
private Sect571k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571k1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"
+ "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3");
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571r1
*/
internal class Sect571r1Holder
: X9ECParametersHolder
{
private Sect571r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571r1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A");
byte[] S = Hex.DecodeStrict("2AA058F73A0E33AB486B0F610410C53A7F132310");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
X9ECPoint G = ConfigureBasepoint(curve, "04"
+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"
+ "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B");
return new X9ECParameters(curve, G, n, h, S);
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(Platform.ToUpperInvariant(name), oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static SecNamedCurves()
{
DefineCurve("secp112r1", SecObjectIdentifiers.SecP112r1, Secp112r1Holder.Instance);
DefineCurve("secp112r2", SecObjectIdentifiers.SecP112r2, Secp112r2Holder.Instance);
DefineCurve("secp128r1", SecObjectIdentifiers.SecP128r1, Secp128r1Holder.Instance);
DefineCurve("secp128r2", SecObjectIdentifiers.SecP128r2, Secp128r2Holder.Instance);
DefineCurve("secp160k1", SecObjectIdentifiers.SecP160k1, Secp160k1Holder.Instance);
DefineCurve("secp160r1", SecObjectIdentifiers.SecP160r1, Secp160r1Holder.Instance);
DefineCurve("secp160r2", SecObjectIdentifiers.SecP160r2, Secp160r2Holder.Instance);
DefineCurve("secp192k1", SecObjectIdentifiers.SecP192k1, Secp192k1Holder.Instance);
DefineCurve("secp192r1", SecObjectIdentifiers.SecP192r1, Secp192r1Holder.Instance);
DefineCurve("secp224k1", SecObjectIdentifiers.SecP224k1, Secp224k1Holder.Instance);
DefineCurve("secp224r1", SecObjectIdentifiers.SecP224r1, Secp224r1Holder.Instance);
DefineCurve("secp256k1", SecObjectIdentifiers.SecP256k1, Secp256k1Holder.Instance);
DefineCurve("secp256r1", SecObjectIdentifiers.SecP256r1, Secp256r1Holder.Instance);
DefineCurve("secp384r1", SecObjectIdentifiers.SecP384r1, Secp384r1Holder.Instance);
DefineCurve("secp521r1", SecObjectIdentifiers.SecP521r1, Secp521r1Holder.Instance);
DefineCurve("sect113r1", SecObjectIdentifiers.SecT113r1, Sect113r1Holder.Instance);
DefineCurve("sect113r2", SecObjectIdentifiers.SecT113r2, Sect113r2Holder.Instance);
DefineCurve("sect131r1", SecObjectIdentifiers.SecT131r1, Sect131r1Holder.Instance);
DefineCurve("sect131r2", SecObjectIdentifiers.SecT131r2, Sect131r2Holder.Instance);
DefineCurve("sect163k1", SecObjectIdentifiers.SecT163k1, Sect163k1Holder.Instance);
DefineCurve("sect163r1", SecObjectIdentifiers.SecT163r1, Sect163r1Holder.Instance);
DefineCurve("sect163r2", SecObjectIdentifiers.SecT163r2, Sect163r2Holder.Instance);
DefineCurve("sect193r1", SecObjectIdentifiers.SecT193r1, Sect193r1Holder.Instance);
DefineCurve("sect193r2", SecObjectIdentifiers.SecT193r2, Sect193r2Holder.Instance);
DefineCurve("sect233k1", SecObjectIdentifiers.SecT233k1, Sect233k1Holder.Instance);
DefineCurve("sect233r1", SecObjectIdentifiers.SecT233r1, Sect233r1Holder.Instance);
DefineCurve("sect239k1", SecObjectIdentifiers.SecT239k1, Sect239k1Holder.Instance);
DefineCurve("sect283k1", SecObjectIdentifiers.SecT283k1, Sect283k1Holder.Instance);
DefineCurve("sect283r1", SecObjectIdentifiers.SecT283r1, Sect283r1Holder.Instance);
DefineCurve("sect409k1", SecObjectIdentifiers.SecT409k1, Sect409k1Holder.Instance);
DefineCurve("sect409r1", SecObjectIdentifiers.SecT409r1, Sect409r1Holder.Instance);
DefineCurve("sect571k1", SecObjectIdentifiers.SecT571k1, Sect571k1Holder.Instance);
DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, Sect571r1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
DerObjectIdentifier oid = GetOid(name);
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier)objIds[Platform.ToUpperInvariant(name)];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string)names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(names.Values); }
}
}
}
| 43.194191 | 188 | 0.594555 | [
"MIT"
] | straight-coding/EmbedTools | crypto/src/asn1/sec/SECNamedCurves.cs | 52,049 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace KB
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 29.145455 | 106 | 0.612601 | [
"MIT"
] | Bjornej/KB | KB/src/KB/Startup.cs | 1,605 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Yukar.Common.GameData
{
public class Party : IGameDataItem
{
public const int MAX_PARTY = 4;
public const int MAX_ITEM = 99;
public const int MAX_MONEY = 9999999;
// パーティメンバー
public List<Hero> members = new List<Hero>();
// 控えメンバー(一度でもパーティに所属したことのあるメンバーはステータスや装備などを記憶する)
public List<Hero> others = new List<Hero>();
// アイテム袋
public class ItemStack
{
public Common.Rom.Item item;
public int num;
}
public List<ItemStack> items = new List<ItemStack>();
// 変更済みグラフィック
public class ChangedGraphic
{
public Guid face;
public Guid model;
}
public Dictionary<Guid, ChangedGraphic> changedHeroGraphic = new Dictionary<Guid, ChangedGraphic>();
// 変更済みの名前
private Dictionary<Guid, string> changedHeroName = new Dictionary<Guid, string>();
public string getHeroName(Guid guid)
{
if (changedHeroName.ContainsKey(guid))
return changedHeroName[guid];
var rom = catalog.getItemFromGuid(guid);
if (rom == null)
return "";
return rom.name;
}
public void setHeroName(Guid guid, string newName)
{
changedHeroName[guid] = newName;
}
// 所持金
private int money;
private Catalog catalog;
// 経験値テーブル
public static int[,] expTable = new int[5, Common.GameData.Hero.MAX_LEVEL];
// 既に手に入れたアイテム図鑑
public Dictionary<Guid, int> itemDict = new Dictionary<Guid, int>();
// インベントリ最大数
private int inventoryMax = -1;
public Party(Catalog catalog){
this.catalog = catalog;
createExpTable();
inventoryMax = catalog.getGameSettings().inventoryMax;
}
public static void createExpTable()
{
int old = 0;
for (int i = 1; i <= Common.GameData.Hero.MAX_LEVEL; i++)
{
expTable[0, i - 1] = (int)((old + Math.Min((int)(Math.Pow(i, 3)) + i * 25, 120000)) * 1.02);
expTable[1, i - 1] = (int)((old + Math.Min((int)(Math.Pow(i, 3)) + i * 25, 120000)) * 1.01);
expTable[2, i - 1] = old + Math.Min((int)(Math.Pow(i, 3)) + i * 25, 120000);
expTable[3, i - 1] = (int)((old + Math.Min((int)(Math.Pow(i, 3)) + i * 25, 120000)) * 0.99);
expTable[4, i - 1] = (int)((old + Math.Min((int)(Math.Pow(i, 3)) + i * 25, 120000)) * 0.98);
old = expTable[2, i - 1];
}
}
public Common.GameData.Hero AddMember(Common.Rom.Hero rom)
{
if (rom == null)
return null;
// 控えから見つかったら控え→パーティに加える
foreach (var hero in others)
{
if (hero.rom == rom)
{
others.Remove(hero);
members.Add(hero);
return null;
}
}
// 見つからなかったら、ROMから新しくGameDataを生成する
var data = createHeroFromRom(catalog, rom);
members.Add(data);
return data;
}
// マップキャラのステータスで使用されているキャラの取得用
public Common.GameData.Hero GetHero(Guid inId)
{
var hero = GetMember(inId, true);
if (hero != null)
{
return hero;
}
// 見つからなかったら、ROMから新しくGameDataを生成する
var rom = catalog.getItemFromGuid(inId) as Common.Rom.Hero;
if (rom == null)
{
return null;
}
var data = createHeroFromRom(catalog, rom);
others.Add(data);
return data;
}
// ROMから新しくGameDataを生成する
public static Common.GameData.Hero createHeroFromRom(Catalog catalog, Rom.Hero rom)
{
var data = new Common.GameData.Hero();
data.rom = rom;
data.level = rom.level;
if (rom.level > 1)
data.exp = expTable[rom.levelGrowthRate, rom.level - 2];
data.maxHitpoint = data.calcMaxHitPoint(rom);
data.maxMagicpoint = data.calcMaxMagicPoint(rom);
data.power = data.calcStatus(rom.power, rom.powerGrowth, rom.powerGrowthRate);
data.vitality = data.calcStatus(rom.vitality, rom.vitalityGrowth, rom.vitalityGrowthRate);
data.magic = data.calcStatus(rom.magic, rom.magicGrowth, rom.magicGrowthRate);
data.speed = data.calcStatus(rom.speed, rom.speedGrowth, rom.speedGrowthRate);
// スキルを反映
data.skills.AddRange(rom.skillLearnLevelsList.Where(skill => skill.level <= data.level).Select(skill => catalog.getItemFromGuid(skill.skill) as Common.Rom.Skill));
data.skills.RemoveAll(x => x == null);
// 装備を反映
if (rom.equipments.weapon != Guid.Empty)
data.equipments[0] = catalog.getItemFromGuid(rom.equipments.weapon) as Common.Rom.Item;
if (rom.equipments.shield != Guid.Empty)
data.equipments[1] = catalog.getItemFromGuid(rom.equipments.shield) as Common.Rom.Item;
if (rom.equipments.head != Guid.Empty)
data.equipments[2] = catalog.getItemFromGuid(rom.equipments.head) as Common.Rom.Item;
if (rom.equipments.body != Guid.Empty)
data.equipments[3] = catalog.getItemFromGuid(rom.equipments.body) as Common.Rom.Item;
if (rom.equipments.accessory[0] != Guid.Empty)
data.equipments[4] = catalog.getItemFromGuid(rom.equipments.accessory[0]) as Common.Rom.Item;
if (rom.equipments.accessory[1] != Guid.Empty)
data.equipments[5] = catalog.getItemFromGuid(rom.equipments.accessory[1]) as Common.Rom.Item;
data.refreshEquipmentEffect();
// HP・MPは装備で上がっている可能性があるので、最後に反映する
data.hitpoint = data.maxHitpoint;
data.magicpoint = data.maxMagicpoint;
data.consistency();
return data;
}
public void RemoveMember(Guid guid)
{
// パーティから見つかったら控えに移す
foreach (var hero in members)
{
if (hero.rom.guId == guid)
{
members.Remove(hero);
others.Add(hero);
return;
}
}
}
public int GetMoney()
{
return money;
}
public void SetMoney(int value)
{
if (value < 0)
value = 0;
else if (value > MAX_MONEY)
value = MAX_MONEY;
money = value;
}
public void AddMoney(int value)
{
SetMoney(money + value);
}
public int GetItemNum(Guid guid, bool includeEquipped = false)
{
int result = 0;
foreach (var item in items)
{
if (item.item.guId == guid)
result = item.num;
}
if (includeEquipped)
{
foreach (var member in members)
{
foreach (var eq in member.equipments)
{
if (eq != null && eq.guId == guid)
result++;
}
}
}
return result;
}
public void SetItemNum(Guid guid, int num)
{
var item = catalog.getItemFromGuid(guid) as Common.Rom.Item;
if (item == null)
return;
if (num > item.maxNum)
num = item.maxNum;
// 持ってる場合はここで数値がセットされる
foreach (var stack in items)
{
if (stack.item.guId == guid)
{
if (num <= 0)
items.Remove(stack);
else
{
// 個数が増える場合は総取得数を更新する
if (stack.num < num)
AddItemToDict(guid, num - stack.num);
stack.num = num;
}
return;
}
}
// 持ってない場合は AddItem する
AddItem(guid, num);
}
public bool ExistMember(Guid guid)
{
foreach (var member in members)
{
if(member.rom.guId == guid)
return true;
}
return false;
}
public Hero GetMember(Guid guid, bool includeOthers = false)
{
foreach (var member in members)
{
if (member.rom.guId == guid)
return member;
}
if (includeOthers)
{
foreach (var member in others)
{
if (member.rom.guId == guid)
return member;
}
}
return null;
}
public void AddItem(Guid guid, int num)
{
var item = catalog.getItemFromGuid(guid) as Common.Rom.Item;
if (item == null)
return;
if (num > item.maxNum)
num = item.maxNum;
foreach (var stack in items)
{
if (stack.item.guId == guid)
{
if (stack.num + num > item.maxNum)
num = item.maxNum - stack.num;
stack.num += num;
if (num > 0)
{
AddItemToDict(guid, num);
itemDict[guid] += num;
}
if (stack.num <= 0)
items.Remove(stack);
return;
}
}
if (num < 0)
return;
var newstack = new ItemStack();
newstack.item = item;
newstack.num = num;
items.Add(newstack);
AddItemToDict(guid, num);
}
private void AddItemToDict(Guid guid, int num)
{
if (!itemDict.ContainsKey(guid))
itemDict.Add(guid, num);
else
itemDict[guid] += num;
}
void IGameDataItem.save(System.IO.BinaryWriter writer)
{
// パーティメンバーを保存
writer.Write(members.Count);
foreach (var hero in members)
{
GameDataManager.saveChunk(hero, writer);
}
// 控えメンバーを保存
writer.Write(others.Count);
foreach (var hero in others)
{
GameDataManager.saveChunk(hero, writer);
}
// アイテム袋を保存
writer.Write(items.Count);
foreach (var stack in items)
{
writer.Write(stack.item.guId.ToByteArray());
writer.Write(stack.num);
}
// 所持金を保存
writer.Write(money);
// 手に入れたアイテム図鑑を保存
writer.Write(itemDict.Count);
foreach (var item in itemDict)
{
writer.Write(item.Key.ToByteArray());
writer.Write(item.Value);
}
// 変更したグラフィックを保存
writer.Write(changedHeroGraphic.Count);
foreach (var entry in changedHeroGraphic)
{
writer.Write(entry.Key.ToByteArray());
writer.Write(entry.Value.face.ToByteArray());
writer.Write(entry.Value.model.ToByteArray());
}
// 変更した名前を保存
writer.Write(changedHeroName.Count);
foreach (var entry in changedHeroName)
{
writer.Write(entry.Key.ToByteArray());
writer.Write(entry.Value);
}
// アイテム袋の最大値を保存
writer.Write(inventoryMax);
}
void IGameDataItem.load(Catalog catalog, System.IO.BinaryReader reader)
{
// パーティメンバーを復帰
members.Clear();
int count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
var hero = new Hero();
GameDataManager.readChunk(catalog, hero, reader);
if(hero.rom != null)
members.Add(hero);
}
// 控えメンバーを復帰
others.Clear();
count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
var hero = new Hero();
GameDataManager.readChunk(catalog, hero, reader);
if (hero.rom != null)
others.Add(hero);
}
// アイテム袋を復帰
items.Clear();
itemDict.Clear();
count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
var stack = new ItemStack();
stack.item = catalog.getItemFromGuid(Util.readGuid(reader)) as Common.Rom.Item;
stack.num = reader.ReadInt32();
if (stack.item != null)
{
items.Add(stack);
}
}
// 所持金を復帰
money = reader.ReadInt32();
// 今まで手に入れたアイテムを復元
count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
var guid = Util.readGuid(reader);
var num = reader.ReadInt32();
itemDict.Add(guid, num);
}
// 変更したグラフィックを反映
changedHeroGraphic.Clear();
count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
var heroGuid = Util.readGuid(reader);
var faceGuid = Util.readGuid(reader);
var modelGuid = Util.readGuid(reader);
var hero = catalog.getItemFromGuid(heroGuid) as Common.Rom.Hero;
if (hero != null)
{
AddChangedGraphic(hero.guId, faceGuid, modelGuid);
}
}
// 変更した名前を反映
changedHeroName.Clear();
count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
var heroGuid = Util.readGuid(reader);
var name = reader.ReadString();
setHeroName(heroGuid, name);
}
// アイテム袋の最大値を読み込み
inventoryMax = reader.ReadInt32();
}
public bool isGameOver()
{
// 全員のHPが0か調べる
foreach (var member in members)
{
if (member.hitpoint > 0)
return false;
}
return true;
}
public void AddChangedGraphic(Guid hero, Guid faceGuid, Guid modelGuid)
{
var entry = new ChangedGraphic();
entry.face = faceGuid;
entry.model = modelGuid;
if (changedHeroGraphic.ContainsKey(hero))
{
changedHeroGraphic[hero] = entry;
}
else
{
changedHeroGraphic.Add(hero, entry);
}
}
public Guid getMemberFace(int index)
{
var result = members[index].rom.face;
if (changedHeroGraphic.ContainsKey(members[index].rom.guId))
result = changedHeroGraphic[members[index].rom.guId].face;
return result;
}
public Guid getMemberGraphic(int index)
{
var result = members[index].rom.graphic;
if (changedHeroGraphic.ContainsKey(members[index].rom.guId))
result = changedHeroGraphic[members[index].rom.guId].model;
return result;
}
public Guid getMemberFace(Rom.Hero rom)
{
var result = rom.face;
if (changedHeroGraphic.ContainsKey(rom.guId))
result = changedHeroGraphic[rom.guId].face;
return result;
}
public Guid getMemberGraphic(Rom.Hero rom)
{
var result = rom.graphic;
if (changedHeroGraphic.ContainsKey(rom.guId))
result = changedHeroGraphic[rom.guId].model;
return result;
}
public int checkInventoryEmptyNum()
{
var max = inventoryMax;
if (max < 0)
max = catalog.getGameSettings().inventoryMax;
return max - items.Count;
}
public bool isOKToConsumptionItem(Guid guid, int amount)
{
var item = catalog.getItemFromGuid(guid) as Common.Rom.Item;
if (item == null)
return true;
return GetItemNum(guid) >= amount;
}
}
}
| 30.976534 | 175 | 0.475205 | [
"MIT"
] | Iseeicy/Icy | Assets/src/common/GameData/Party.cs | 18,125 | C# |
/*
* Copyright 2019 Douglas Kaip
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using com.CIMthetics.CSharpSECSTools.SECSCommUtils;
namespace SECSCommUtils
{
public class HSMSWriter
{
private NetworkStream iOStream;
private Queue<SECSConnection.TransientMessage> messagesToSend;
private EventWaitHandle messageToSendWaitHandle;
public HSMSWriter()
{
}
public HSMSWriter(NetworkStream iOStream, Queue<SECSConnection.TransientMessage> messagesToSend, EventWaitHandle messageToSendWaitHandle)
{
this.iOStream = iOStream;
this.messagesToSend = messagesToSend;
this.messageToSendWaitHandle = messageToSendWaitHandle;
}
internal static void Start()
{
throw new NotImplementedException();
}
}
}
| 31.106383 | 145 | 0.707934 | [
"Apache-2.0"
] | dkaip/CSharpSECSTools | SECSCommUtils/HSMS/HSMSWriter.cs | 1,464 | C# |
using BootStore.EntityFrameworkCore;
using Volo.Abp.Modularity;
namespace BootStore
{
[DependsOn(
typeof(BootStoreEntityFrameworkCoreTestModule)
)]
public class BootStoreDomainTestModule : AbpModule
{
}
} | 18.384615 | 54 | 0.715481 | [
"MIT"
] | 13640535881/LogDashboard | samples/abpvnext/test/BootStore.Domain.Tests/BootStoreDomainTestModule.cs | 241 | C# |
#region License
/*
* ServerSslConfiguration.cs
*
* The MIT License
*
* Copyright (c) 2014 liryna
* Copyright (c) 2014 sta.blockhead
*
* 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
#region Authors
/*
* Authors:
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace WebSocketSharp.Net
{
/// <summary>
/// Stores the parameters used to configure a <see cref="SslStream"/> instance as a server.
/// </summary>
public class ServerSslConfiguration : SslConfiguration
{
#region Private Fields
private X509Certificate2 _cert;
private bool _clientCertRequired;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ServerSslConfiguration"/> class with
/// the specified <paramref name="serverCertificate"/>.
/// </summary>
/// <param name="serverCertificate">
/// A <see cref="X509Certificate2"/> that represents the certificate used to authenticate
/// the server.
/// </param>
public ServerSslConfiguration (X509Certificate2 serverCertificate)
: this (serverCertificate, false, SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ServerSslConfiguration"/> class with
/// the specified <paramref name="serverCertificate"/>,
/// <paramref name="clientCertificateRequired"/>, <paramref name="enabledSslProtocols"/>,
/// and <paramref name="checkCertificateRevocation"/>.
/// </summary>
/// <param name="serverCertificate">
/// A <see cref="X509Certificate2"/> that represents the certificate used to authenticate
/// the server.
/// </param>
/// <param name="clientCertificateRequired">
/// <c>true</c> if the client must supply a certificate for authentication;
/// otherwise, <c>false</c>.
/// </param>
/// <param name="enabledSslProtocols">
/// The <see cref="SslProtocols"/> enum value that represents the protocols used for
/// authentication.
/// </param>
/// <param name="checkCertificateRevocation">
/// <c>true</c> if the certificate revocation list is checked during authentication;
/// otherwise, <c>false</c>.
/// </param>
public ServerSslConfiguration (
X509Certificate2 serverCertificate,
bool clientCertificateRequired,
SslProtocols enabledSslProtocols,
bool checkCertificateRevocation)
: base (enabledSslProtocols, checkCertificateRevocation)
{
_cert = serverCertificate;
_clientCertRequired = clientCertificateRequired;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets a value indicating whether the client must supply a certificate for
/// authentication.
/// </summary>
/// <value>
/// <c>true</c> if the client must supply a certificate; otherwise, <c>false</c>.
/// </value>
public bool ClientCertificateRequired {
get {
return _clientCertRequired;
}
set {
_clientCertRequired = value;
}
}
/// <summary>
/// Gets or sets the callback used to validate the certificate supplied by the client.
/// </summary>
/// <remarks>
/// If this callback returns <c>true</c>, the client certificate will be valid.
/// </remarks>
/// <value>
/// A <see cref="RemoteCertificateValidationCallback"/> delegate that references the method
/// used to validate the client certificate. The default value is a function that only returns
/// <c>true</c>.
/// </value>
public RemoteCertificateValidationCallback ClientCertificateValidationCallback {
get {
return CertificateValidationCallback;
}
set {
CertificateValidationCallback = value;
}
}
/// <summary>
/// Gets or sets the certificate used to authenticate the server for secure connection.
/// </summary>
/// <value>
/// A <see cref="X509Certificate2"/> that represents the certificate used to authenticate
/// the server.
/// </value>
public X509Certificate2 ServerCertificate {
get {
return _cert;
}
set {
_cert = value;
}
}
#endregion
}
}
| 32.854545 | 106 | 0.677735 | [
"MIT"
] | AelithBlanchett/websocket-sharp-core | websocket-sharp-core/Net/ServerSslConfiguration.cs | 5,423 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MeowDSIO.DataTypes.MSB.EVENT_PARAM_ST
{
public class MsbEventWindSFX : MsbEventBase
{
internal override void DebugPushUnknownFieldReport_Subtype(out string subtypeName, Dictionary<string, object> dict)
{
subtypeName = "WindSFX";
dict.Add(nameof(SubUnk1), SubUnk1);
dict.Add(nameof(SubUnk2), SubUnk2);
dict.Add(nameof(SubUnk3), SubUnk3);
dict.Add(nameof(SubUnk4), SubUnk4);
dict.Add(nameof(SubUnk5), SubUnk5);
dict.Add(nameof(SubUnk6), SubUnk6);
dict.Add(nameof(SubUnk7), SubUnk7);
dict.Add(nameof(SubUnk8), SubUnk8);
dict.Add(nameof(SubUnk9), SubUnk9);
dict.Add(nameof(SubUnk10), SubUnk10);
dict.Add(nameof(SubUnk11), SubUnk11);
dict.Add(nameof(SubUnk12), SubUnk12);
dict.Add(nameof(SubUnk13), SubUnk13);
dict.Add(nameof(SubUnk14), SubUnk14);
dict.Add(nameof(SubUnk15), SubUnk15);
dict.Add(nameof(SubUnk16), SubUnk16);
}
public float SubUnk1 { get; set; } = 0;
public float SubUnk2 { get; set; } = 0;
public float SubUnk3 { get; set; } = 0;
public float SubUnk4 { get; set; } = 0;
public float SubUnk5 { get; set; } = 0;
public float SubUnk6 { get; set; } = 0;
public float SubUnk7 { get; set; } = 0;
public float SubUnk8 { get; set; } = 0;
public float SubUnk9 { get; set; } = 0;
public float SubUnk10 { get; set; } = 0;
public float SubUnk11 { get; set; } = 0;
public float SubUnk12 { get; set; } = 0;
public float SubUnk13 { get; set; } = 0;
public float SubUnk14 { get; set; } = 0;
public float SubUnk15 { get; set; } = 0;
public float SubUnk16 { get; set; } = 0;
protected override EventParamSubtype GetSubtypeValue()
{
return EventParamSubtype.WindSFX;
}
protected override void SubtypeRead(DSBinaryReader bin)
{
SubUnk1 = bin.ReadSingle();
SubUnk2 = bin.ReadSingle();
SubUnk3 = bin.ReadSingle();
SubUnk4 = bin.ReadSingle();
SubUnk5 = bin.ReadSingle();
SubUnk6 = bin.ReadSingle();
SubUnk7 = bin.ReadSingle();
SubUnk8 = bin.ReadSingle();
SubUnk9 = bin.ReadSingle();
SubUnk10 = bin.ReadSingle();
SubUnk11 = bin.ReadSingle();
SubUnk12 = bin.ReadSingle();
SubUnk13 = bin.ReadSingle();
SubUnk14 = bin.ReadSingle();
SubUnk15 = bin.ReadSingle();
SubUnk16 = bin.ReadSingle();
}
protected override void SubtypeWrite(DSBinaryWriter bin)
{
bin.Write(SubUnk1);
bin.Write(SubUnk2);
bin.Write(SubUnk3);
bin.Write(SubUnk4);
bin.Write(SubUnk5);
bin.Write(SubUnk6);
bin.Write(SubUnk7);
bin.Write(SubUnk8);
bin.Write(SubUnk9);
bin.Write(SubUnk10);
bin.Write(SubUnk11);
bin.Write(SubUnk12);
bin.Write(SubUnk13);
bin.Write(SubUnk14);
bin.Write(SubUnk15);
bin.Write(SubUnk16);
}
}
}
| 35.802083 | 123 | 0.552808 | [
"MIT"
] | AinTunez/MeowDSIO | MeowDSIO/DataTypes/MSB/EVENT_PARAM_ST/MsbEventWindSFX.cs | 3,439 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Xml;
using System.Xml.Serialization;
using ACT.SpecialSpellTimer.Config.Models;
using ACT.SpecialSpellTimer.Config.Views;
using ACT.SpecialSpellTimer.Views;
using FFXIV.Framework.Bridge;
using FFXIV.Framework.Common;
using FFXIV.Framework.Extensions;
using FFXIV.Framework.Globalization;
using FFXIV.Framework.WPF.Views;
using FFXIV.Framework.XIVHelper;
using Prism.Mvvm;
namespace ACT.SpecialSpellTimer.Config
{
[Serializable]
public class Settings :
BindableBase
{
#region Singleton
private static Settings instance;
private static object singletonLocker = new object();
public static Settings Default
{
get
{
#if DEBUG
if (WPFHelper.IsDesignMode)
{
return new Settings();
}
#endif
lock (singletonLocker)
{
if (instance == null)
{
instance = new Settings();
}
}
return instance;
}
}
#endregion Singleton
public Settings()
{
this.Reset();
}
public readonly string FileName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
@"anoyetta\ACT\ACT.SpecialSpellTimer.config");
public void DeInit()
{
this.polonTimer.Stop();
this.polonTimer.Dispose();
this.polonTimer = null;
}
#region Constants
[XmlIgnore]
public const double UpdateCheckInterval = 12;
#endregion Constants
#region Data
[XmlIgnore]
public Locales UILocale => FFXIV.Framework.Config.Instance.UILocale;
public Locales FFXIVLocale => FFXIV.Framework.Config.Instance.XIVLocale;
private bool overlayVisible;
public bool OverlayVisible
{
get => this.overlayVisible;
set
{
if (this.SetProperty(ref this.overlayVisible, value))
{
var button = PluginCore.Instance.SwitchVisibleButton;
if (button != null)
{
if (this.overlayVisible)
{
button.BackColor = Color.SandyBrown;
button.ForeColor = Color.WhiteSmoke;
}
else
{
button.BackColor = SystemColors.Control;
button.ForeColor = Color.Black;
}
}
}
}
}
private static DesignGridView[] gridViews;
private bool visibleDesignGrid;
[XmlIgnore]
public bool VisibleDesignGrid
{
get => this.visibleDesignGrid;
set
{
if (this.SetProperty(ref this.visibleDesignGrid, value))
{
if (this.visibleDesignGrid)
{
lock (this)
{
if (gridViews == null)
{
var views = new List<DesignGridView>();
foreach (var screen in System.Windows.Forms.Screen.AllScreens)
{
var view = new DesignGridView()
{
WindowStartupLocation = System.Windows.WindowStartupLocation.Manual,
Left = screen.Bounds.X,
Top = screen.Bounds.Y,
Width = screen.Bounds.Width,
Height = screen.Bounds.Height,
Topmost = true,
};
view.ToTransparent();
views.Add(view);
}
gridViews = views.ToArray();
}
}
foreach (var view in gridViews)
{
view.Show();
view.ShowOverlay();
}
}
else
{
if (gridViews != null)
{
foreach (var view in gridViews)
{
view?.HideOverlay();
view?.Hide();
}
}
}
}
}
}
private bool clickThroughEnabled;
public bool ClickThroughEnabled
{
get => this.clickThroughEnabled;
set => this.SetProperty(ref this.clickThroughEnabled, value);
}
private int opacity;
/// <summary>
/// !注意! OpacityToView を使用すること!
/// </summary>
public int Opacity
{
get => this.opacity;
set
{
if (this.SetProperty(ref this.opacity, value))
{
this.RaisePropertyChanged(nameof(this.OpacityToView));
if (LPSView.Instance != null &&
LPSView.Instance.OverlayVisible)
{
LPSView.Instance.Opacity = this.OpacityToView;
}
if (POSView.Instance != null &&
POSView.Instance.OverlayVisible)
{
POSView.Instance.Opacity = this.OpacityToView;
}
}
}
}
[XmlIgnore]
public double OpacityToView => (100d - this.Opacity) / 100d;
public bool HideWhenNotActive { get; set; }
/// <summary>
/// FFXIVのプロセスが存在しなくてもオーバーレイを表示する
/// </summary>
public bool VisibleOverlayWithoutFFXIV { get; set; } = false;
public long LogPollSleepInterval { get; set; }
public long RefreshInterval { get; set; }
public int MaxFPS { get; set; }
public bool RenderCPUOnly { get; set; } = false;
private NameStyles pcNameInitialOnDisplayStyle = NameStyles.FullName;
public NameStyles PCNameInitialOnDisplayStyle
{
get => this.pcNameInitialOnDisplayStyle;
set
{
if (this.SetProperty(ref pcNameInitialOnDisplayStyle, value))
{
ConfigBridge.Instance.PCNameStyle = value;
}
}
}
public double TextBlurRate
{
get => FontInfo.BlurRadiusRate;
set => FontInfo.BlurRadiusRate = value;
}
public double TextOutlineThicknessRate
{
get => FontInfo.OutlineThicknessRate;
set => FontInfo.OutlineThicknessRate = value;
}
public int ReduceIconBrightness { get; set; }
public string ReadyText { get; set; }
public string OverText { get; set; }
#region Data - ProgressBar Background
[XmlIgnore] private readonly System.Windows.Media.Color DefaultBackgroundColor = System.Windows.Media.Colors.Black;
[XmlIgnore] private bool barBackgroundFixed;
[XmlIgnore] private double barBackgroundBrightness;
[XmlIgnore] private System.Windows.Media.Color barDefaultBackgroundColor;
/// <summary>
/// プログレスバーの背景が固定色か?
/// </summary>
public bool BarBackgroundFixed
{
get => this.barBackgroundFixed;
set => this.SetProperty(ref this.barBackgroundFixed, value);
}
/// <summary>
/// プログレスバーの背景の輝度
/// </summary>
public double BarBackgroundBrightness
{
get => this.barBackgroundBrightness;
set => this.barBackgroundBrightness = value;
}
/// <summary>
/// プログレスバーの標準の背景色
/// </summary>
[XmlIgnore]
public System.Windows.Media.Color BarDefaultBackgroundColor
{
get => this.barDefaultBackgroundColor;
set => this.barDefaultBackgroundColor = value;
}
/// <summary>
/// プログレスバーの標準の背景色
/// </summary>
[XmlElement(ElementName = "BarDefaultBackgroundColor")]
public string BarDefaultBackgroundColorText
{
get => this.BarDefaultBackgroundColor.ToString();
set => this.BarDefaultBackgroundColor = this.DefaultBackgroundColor.FromString(value);
}
#endregion Data - ProgressBar Background
public double TimeOfHideSpell { get; set; }
public bool EnabledPartyMemberPlaceholder { get; set; }
public bool EnabledSpellTimerNoDecimal { get; set; }
public bool EnabledNotifyNormalSpellTimer { get; set; }
public string NotifyNormalSpellTimerPrefix { get; set; }
public bool SimpleRegex { get; set; }
public bool RemoveTooltipSymbols { get; set; }
private bool ignoreDetailLogs = false;
public bool IgnoreDetailLogs
{
get => this.ignoreDetailLogs;
set => this.SetProperty(ref this.ignoreDetailLogs, value);
}
private bool ignoreDamageLogs = true;
public bool IgnoreDamageLogs
{
get => this.ignoreDamageLogs;
set => this.SetProperty(ref this.ignoreDamageLogs, value);
}
private bool isAutoIgnoreLogs = false;
public bool IsAutoIgnoreLogs
{
get => this.isAutoIgnoreLogs;
set => this.SetProperty(ref this.isAutoIgnoreLogs, value);
}
private bool removeWorldName = true;
public bool RemoveWorldName
{
get => this.removeWorldName;
set => this.SetProperty(ref this.removeWorldName, value);
}
public bool DetectPacketDump { get; set; }
private bool resetOnWipeOut;
public bool ResetOnWipeOut
{
get => this.resetOnWipeOut;
set => this.SetProperty(ref this.resetOnWipeOut, value);
}
public bool WipeoutNotifyToACT { get; set; }
private double waitingTimeToSyncTTS = 100;
public double WaitingTimeToSyncTTS
{
get => this.waitingTimeToSyncTTS;
set => this.SetProperty(ref this.waitingTimeToSyncTTS, value);
}
#region LPS View
private bool lpsViewVisible = false;
private double lpsViewX;
private double lpsViewY;
private double lpsViewScale = 1.0;
public bool LPSViewVisible
{
get => this.lpsViewVisible;
set
{
if (this.SetProperty(ref this.lpsViewVisible, value))
{
if (LPSView.Instance != null)
{
LPSView.Instance.OverlayVisible = value;
}
}
}
}
public double LPSViewX
{
get => this.lpsViewX;
set => this.SetProperty(ref this.lpsViewX, Math.Floor(value));
}
public double LPSViewY
{
get => this.lpsViewY;
set => this.SetProperty(ref this.lpsViewY, Math.Floor(value));
}
public double LPSViewScale
{
get => this.lpsViewScale;
set => this.SetProperty(ref this.lpsViewScale, value);
}
#endregion LPS View
#region POS View
private bool posViewVisible = false;
private double posViewX;
private double posViewY;
private double posViewScale = 1.0;
private bool posViewVisibleDebugInfo = WPFHelper.IsDesignMode ? true : false;
public bool POSViewVisible
{
get => this.posViewVisible;
set
{
if (this.SetProperty(ref this.posViewVisible, value))
{
if (POSView.Instance != null)
{
POSView.Instance.OverlayVisible = value;
}
}
}
}
public double POSViewX
{
get => this.posViewX;
set => this.SetProperty(ref this.posViewX, Math.Floor(value));
}
public double POSViewY
{
get => this.posViewY;
set => this.SetProperty(ref this.posViewY, Math.Floor(value));
}
public double POSViewScale
{
get => this.posViewScale;
set => this.SetProperty(ref this.posViewScale, value);
}
public bool POSViewVisibleDebugInfo
{
get => this.posViewVisibleDebugInfo;
set => this.SetProperty(ref this.posViewVisibleDebugInfo, value);
}
#endregion POS View
private bool saveLogEnabled;
private string saveLogDirectory;
public bool SaveLogEnabled
{
get => this.saveLogEnabled;
set
{
if (this.SetProperty(ref this.saveLogEnabled, value))
{
if (!this.saveLogEnabled)
{
ChatLogWorker.Instance.Write(true);
ChatLogWorker.Instance.Close();
}
}
}
}
public string SaveLogDirectory
{
get => this.saveLogDirectory;
set => this.SetProperty(ref this.saveLogDirectory, value);
}
private string timelineDirectory = string.Empty;
public string TimelineDirectory
{
get => this.timelineDirectory;
set => this.SetProperty(ref this.timelineDirectory, value);
}
private bool isMinimizeOnStart = false;
public bool IsMinimizeOnStart
{
get => this.isMinimizeOnStart;
set => this.SetProperty(ref this.isMinimizeOnStart, value);
}
#region Polon
private System.Timers.Timer polonTimer = new System.Timers.Timer();
private bool isEnabledPolon = false;
public bool IsEnabledPolon
{
get => this.isEnabledPolon;
set
{
if (this.SetProperty(ref this.isEnabledPolon, value))
{
lock (this.polonTimer)
{
if (!this.isEnabledPolon)
{
this.polonTimer.Stop();
}
else
{
this.polonCounter = 0;
this.polonTimer.Elapsed -= this.PolonTimer_Elapsed;
this.polonTimer.Elapsed += this.PolonTimer_Elapsed;
this.polonTimer.Interval = 15 * 1000;
this.polonTimer.AutoReset = true;
this.polonTimer.Start();
}
}
}
}
}
private void PolonTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lock (this.polonTimer)
{
if (this.isEnabledPolon)
{
if (this.polonCounter < NomarlPolonCount)
{
CommonSounds.Instance.PlayAsterisk();
}
else
{
var index = this.polonCounter - NomarlPolonCount;
if (index >= this.PolonMessages.Length)
{
CommonSounds.Instance.PlayAsterisk();
}
else
{
if (!PlayBridge.Instance.IsAvailable)
{
CommonSounds.Instance.PlayAsterisk();
}
else
{
var tts = this.PolonMessages[index];
PlayBridge.Instance.Play(tts, false, 1.0f);
}
}
}
this.polonCounter++;
}
}
}
private int polonCounter = 0;
private const int NomarlPolonCount = 3;
private readonly string[] PolonMessages = new[]
{
"ぽろん",
"ぽろろーん",
"ぴろーん?",
"ぽぽろん!",
"ポリネシア!",
"ポンキッキ!",
"びろーん",
"ぽぽぽぽーん!",
"えーしー",
"ねぇ、いっしょにポロンしよ?",
"せーのっ!",
"さっきのはフェイント",
"つぎはほんとうにいっしょに!",
"ぽろん!",
"あしたもいっしょにポロンしてね。",
};
#endregion Polon
#region Data - Timeline
private bool timelineTotalSecoundsFormat = false;
public bool TimelineTotalSecoundsFormat
{
get => this.timelineTotalSecoundsFormat;
set => this.SetProperty(ref this.timelineTotalSecoundsFormat, value);
}
private bool autoCombatLogAnalyze;
public bool AutoCombatLogAnalyze
{
get => this.autoCombatLogAnalyze;
set => this.SetProperty(ref this.autoCombatLogAnalyze, value);
}
private bool autoCombatLogSave;
public bool AutoCombatLogSave
{
get => this.autoCombatLogSave;
set => this.SetProperty(ref this.autoCombatLogSave, value);
}
private string combatLogSaveDirectory = string.Empty;
public string CombatLogSaveDirectory
{
get => this.combatLogSaveDirectory;
set => this.SetProperty(ref this.combatLogSaveDirectory, value);
}
#endregion Data - Timeline
#endregion Data
#region Data - Hidden
public bool AutoSortEnabled { get; set; }
public bool AutoSortReverse { get; set; }
public bool SingleTaskLogMatching { get; set; }
public bool DisableStartCondition { get; set; }
public bool EnableMultiLineMaching { get; set; }
/// <summary>点滅の輝度倍率 暗</summary>
public double BlinkBrightnessDark { get; set; }
/// <summary>点滅の輝度倍率 明</summary>
public double BlinkBrightnessLight { get; set; }
/// <summary>点滅のピッチ(秒)</summary>
public double BlinkPitch { get; set; }
/// <summary>点滅のピーク状態でのホールド時間(秒)</summary>
public double BlinkPeekHold { get; set; }
public List<ExpandedContainer> ExpandedList
{
get;
set;
} = new List<ExpandedContainer>();
private DateTime lastUpdateDateTime;
[XmlIgnore]
public DateTime LastUpdateDateTime
{
get => this.lastUpdateDateTime;
set => this.lastUpdateDateTime = value;
}
[XmlElement(ElementName = "LastUpdateDateTime")]
public string LastUpdateDateTimeCrypted
{
get => Crypter.EncryptString(this.lastUpdateDateTime.ToString("o"));
set
{
DateTime d;
if (DateTime.TryParse(value, out d))
{
if (d > DateTime.Now)
{
d = DateTime.Now;
}
this.lastUpdateDateTime = d;
return;
}
try
{
var decrypt = Crypter.DecryptString(value);
if (DateTime.TryParse(decrypt, out d))
{
if (d > DateTime.Now)
{
d = DateTime.Now;
}
this.lastUpdateDateTime = d;
return;
}
}
catch (Exception)
{
}
this.lastUpdateDateTime = DateTime.MinValue;
}
}
#endregion Data - Hidden
#region Load & Save
private readonly object locker = new object();
private bool isLoaded = false;
public void Load()
{
lock (this.locker)
{
this.Reset();
if (!File.Exists(this.FileName))
{
this.isLoaded = true;
this.Save();
return;
}
var fi = new FileInfo(this.FileName);
if (fi.Length <= 0)
{
this.isLoaded = true;
this.Save();
return;
}
using (var sr = new StreamReader(this.FileName, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(this.GetType());
var data = xs.Deserialize(sr) as Settings;
if (data != null)
{
instance = data;
instance.isLoaded = true;
}
}
}
}
}
private static readonly Encoding DefaultEncoding = new UTF8Encoding(false);
public void Save()
{
lock (this.locker)
{
if (!this.isLoaded)
{
return;
}
var directoryName = Path.GetDirectoryName(this.FileName);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
var buffer = new StringBuilder();
using (var sw = new StringWriter(buffer))
{
var xs = new XmlSerializer(this.GetType());
xs.Serialize(sw, this, ns);
}
buffer.Replace("utf-16", "utf-8");
File.WriteAllText(
this.FileName,
buffer.ToString() + Environment.NewLine,
DefaultEncoding);
}
}
private DateTime lastAutoSaveTimestamp = DateTime.MinValue;
public void StartAutoSave()
{
this.PropertyChanged += async (_, __) =>
{
var now = DateTime.Now;
if ((now - this.lastAutoSaveTimestamp).TotalSeconds > 20)
{
this.lastAutoSaveTimestamp = now;
await Task.Run(() => this.Save());
}
};
}
/// <summary>
/// レンダリングモードを適用する
/// </summary>
public void ApplyRenderMode()
{
var renderMode =
this.RenderCPUOnly ? RenderMode.SoftwareOnly : RenderMode.Default;
if (System.Windows.Media.RenderOptions.ProcessRenderMode != renderMode)
{
System.Windows.Media.RenderOptions.ProcessRenderMode = renderMode;
}
}
#endregion Load & Save
#region Default Values & Reset
public static readonly Dictionary<string, object> DefaultValues = new Dictionary<string, object>()
{
{ nameof(Settings.NotifyNormalSpellTimerPrefix), "spespe_" },
{ nameof(Settings.ReadyText), "Ready" },
{ nameof(Settings.OverText), "Over" },
{ nameof(Settings.TimeOfHideSpell), 1.0d },
{ nameof(Settings.LogPollSleepInterval), 30 },
{ nameof(Settings.RefreshInterval), 60 },
{ nameof(Settings.ReduceIconBrightness), 55 },
{ nameof(Settings.Opacity), 10 },
{ nameof(Settings.OverlayVisible), true },
{ nameof(Settings.AutoSortEnabled), true },
{ nameof(Settings.ClickThroughEnabled), false },
{ nameof(Settings.AutoSortReverse), false },
{ nameof(Settings.EnabledPartyMemberPlaceholder), true },
{ nameof(Settings.IsAutoIgnoreLogs), false },
{ nameof(Settings.AutoCombatLogAnalyze), false },
{ nameof(Settings.EnabledSpellTimerNoDecimal), true },
{ nameof(Settings.EnabledNotifyNormalSpellTimer), false },
{ nameof(Settings.SaveLogEnabled), false },
{ nameof(Settings.SaveLogDirectory), string.Empty },
{ nameof(Settings.HideWhenNotActive), false },
{ nameof(Settings.ResetOnWipeOut), true },
{ nameof(Settings.WipeoutNotifyToACT), true },
{ nameof(Settings.RemoveTooltipSymbols), true },
{ nameof(Settings.RemoveWorldName), true },
{ nameof(Settings.SimpleRegex), true },
{ nameof(Settings.DetectPacketDump), false },
{ nameof(Settings.TextBlurRate), 1.2d },
{ nameof(Settings.TextOutlineThicknessRate), 1.0d },
{ nameof(Settings.PCNameInitialOnDisplayStyle), NameStyles.FullName },
{ nameof(Settings.RenderCPUOnly), true },
{ nameof(Settings.SingleTaskLogMatching), false },
{ nameof(Settings.DisableStartCondition), false },
{ nameof(Settings.EnableMultiLineMaching), false },
{ nameof(Settings.MaxFPS), 30 },
{ nameof(Settings.IsEnabledPolon), false },
{ nameof(Settings.LPSViewVisible), false },
{ nameof(Settings.LPSViewX), 0 },
{ nameof(Settings.LPSViewY), 0 },
{ nameof(Settings.LPSViewScale), 1.0 },
{ nameof(Settings.BarBackgroundFixed), false },
{ nameof(Settings.BarBackgroundBrightness), 0.3 },
{ nameof(Settings.BarDefaultBackgroundColor), System.Windows.Media.Color.FromArgb(240, 0, 0, 0) },
// 設定画面のない設定項目
{ nameof(Settings.LastUpdateDateTime), DateTime.Parse("2000-1-1") },
{ nameof(Settings.BlinkBrightnessDark), 0.3d },
{ nameof(Settings.BlinkBrightnessLight), 2.5d },
{ nameof(Settings.BlinkPitch), 0.5d },
{ nameof(Settings.BlinkPeekHold), 0.08d },
};
/// <summary>
/// Clone
/// </summary>
/// <returns>
/// このオブジェクトのクローン</returns>
public Settings Clone() => (Settings)this.MemberwiseClone();
public void Reset()
{
lock (this.locker)
{
var pis = this.GetType().GetProperties();
foreach (var pi in pis)
{
try
{
var defaultValue =
DefaultValues.ContainsKey(pi.Name) ?
DefaultValues[pi.Name] :
null;
if (defaultValue != null)
{
pi.SetValue(this, defaultValue);
}
}
catch
{
Debug.WriteLine($"Settings Reset Error: {pi.Name}");
}
}
}
}
#endregion Default Values & Reset
}
}
| 30.749729 | 123 | 0.48108 | [
"BSD-3-Clause"
] | sheeva-r/ACT.Hojoring | source/ACT.SpecialSpellTimer/ACT.SpecialSpellTimer.Core/Config/Settings.cs | 28,936 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Configuration;
using System.Xml;
namespace Lucene.Net.Distributed.Configuration
{
/// <summary>
/// Implementation of custom configuration handler for the definition of search indexes
/// made accessible by the LuceneServer windows service. This configuration resides in
/// the configuration file of an application consuming the search indexes made accessible
/// by the LuceneServer windows service.
/// </summary>
public class DistributedSearcherConfigurationHandler : IConfigurationSectionHandler
{
/// <summary>
/// Empty public constructor for the configuration handler.
/// </summary>
public DistributedSearcherConfigurationHandler()
{
}
#region IConfigurationSectionHandler Members
/// <summary>
/// Required implementation of IConfigurationSectionHandler.
/// </summary>
/// <param name="parent">Required object for IConfigurationSectionHandler</param>
/// <param name="configContext">Configuration context object</param>
/// <param name="section">Xml configuration in the application configuration file</param>
/// <returns></returns>
public object Create(object parent, object configContext, XmlNode section)
{
DistributedSearchers wsConfig = new DistributedSearchers(section);
return wsConfig;
}
#endregion
}
}
| 38.368421 | 97 | 0.731139 | [
"Apache-2.0"
] | Distrotech/mono | external/Lucene.Net/src/contrib/DistributedSearch/Distributed/Configuration/DistributedSearcherConfigurationHandler.cs | 2,187 | C# |
// Copyright (c) Piotr Stenke. All rights reserved.
// Licensed under the MIT license.
using System;
using System.IO;
using System.Text;
using Durian.Configuration;
namespace Durian.Samples.DefaultParam
{
[DefaultParamConfiguration(TypeConvention = DPTypeConvention.Copy)]
public class Logger<[DefaultParam(typeof(string))]T> : ILogger<T> where T : IEquatable<string>
{
private readonly StringBuilder _builder;
public Logger()
{
_builder = new(1024);
}
public Logger(StringBuilder builder)
{
_builder = builder;
}
public void Clear()
{
_builder.Clear();
}
public void Error(T message)
{
_builder.Append("Error: ").AppendLine(message.ToString());
}
public void Info(T message)
{
_builder.Append("Info: ").AppendLine(message.ToString());
}
public void Save(string path)
{
File.WriteAllText(path, _builder.ToString());
}
public override string ToString()
{
return _builder.ToString();
}
public void Warning(T message)
{
_builder.Append("Warning: ").AppendLine(message.ToString());
}
}
}
| 18.824561 | 95 | 0.692451 | [
"MIT"
] | piotrstenke/Durian | samples/Durian.Samples.DefaultParam/Logger.cs | 1,075 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.IO;
namespace Microsoft.Xna.Framework.Audio
{
class VolumeEvent : ClipEvent
{
private readonly float _volume;
public VolumeEvent(XactClip clip, float timeStamp, float randomOffset, float volume)
: base(clip, timeStamp, randomOffset)
{
_volume = volume;
}
public override void Play()
{
_clip.SetVolume(_volume);
}
public override void Stop()
{
}
public override void Pause()
{
}
public override void Resume()
{
}
public override void SetTrackVolume(float volume)
{
}
public override void SetTrackPan(float pan)
{
}
public override void SetState(float volume, float pitch, float reverbMix, float? filterFrequency, float? filterQFactor)
{
}
public override bool Update(float dt)
{
return false;
}
public override void SetFade(float fadeInDuration, float fadeOutDuration)
{
}
}
}
| 19.770492 | 124 | 0.62272 | [
"MIT"
] | 06needhamt/MonoGame | MonoGame.Framework/Audio/Xact/VolumeEvent.cs | 1,206 | C# |
using System;
namespace Vip.DFe.SAT.Events
{
public sealed class SatMensagemEventArgs : EventArgs
{
#region Constructor
public SatMensagemEventArgs(int codigo, string mensagem)
{
Codigo = codigo;
Mensagem = mensagem;
}
#endregion Constructor
#region Properties
public int Codigo { get; private set; }
public string Mensagem { get; private set; }
#endregion Properties
}
} | 19.44 | 64 | 0.598765 | [
"MIT"
] | leandrovip/Vip.DFe | src/Vip.DFe/1-Services/SAT/Events/SatMensagemEventArgs.cs | 486 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RemoteEffectRole.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}
}
| 17.578947 | 44 | 0.628743 | [
"MIT"
] | infinitespace-studios/InfinitespaceStudios.Pipeline | InfinitespaceStudios.PipelineService/PipelineRole/Controllers/HomeController.cs | 336 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.
// File System.ServiceModel.Security.X509CertificateRecipientClientCredential.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.ServiceModel.Security
{
sealed public partial class X509CertificateRecipientClientCredential
{
#region Methods and constructors
public void SetDefaultCertificate(string subjectName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.StoreName storeName)
{
}
public void SetDefaultCertificate(System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.X509FindType findType, Object findValue)
{
}
public void SetScopedCertificate(System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.StoreName storeName, System.Security.Cryptography.X509Certificates.X509FindType findType, Object findValue, Uri targetService)
{
}
public void SetScopedCertificate(string subjectName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, System.Security.Cryptography.X509Certificates.StoreName storeName, Uri targetService)
{
}
internal X509CertificateRecipientClientCredential()
{
}
#endregion
#region Properties and indexers
public X509ServiceCertificateAuthentication Authentication
{
get
{
return default(X509ServiceCertificateAuthentication);
}
}
public System.Security.Cryptography.X509Certificates.X509Certificate2 DefaultCertificate
{
get
{
return default(System.Security.Cryptography.X509Certificates.X509Certificate2);
}
set
{
}
}
public Dictionary<Uri, System.Security.Cryptography.X509Certificates.X509Certificate2> ScopedCertificates
{
get
{
return default(Dictionary<Uri, System.Security.Cryptography.X509Certificates.X509Certificate2>);
}
}
#endregion
}
}
| 42.063158 | 463 | 0.776777 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/System.ServiceModel/Sources/System.ServiceModel.Security.X509CertificateRecipientClientCredential.cs | 3,996 | C# |
namespace CareerManagement.Entities
{
/// <summary>
/// 교육 링크
/// </summary>
public class EducationLink:LinkBase
{
/// <summary>
/// 교육 식별자
/// </summary>
public string EducationId { get; set; }
public virtual Education Education { get; set; }
}
}
| 20.125 | 56 | 0.521739 | [
"MIT"
] | bbonkr/career-management-backend | CareerManagement.Entities/EducationLink.cs | 342 | 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 lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Lightsail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lightsail.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetInstanceSnapshot Request Marshaller
/// </summary>
public class GetInstanceSnapshotRequestMarshaller : IMarshaller<IRequest, GetInstanceSnapshotRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetInstanceSnapshotRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(GetInstanceSnapshotRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Lightsail");
string target = "Lightsail_20161128.GetInstanceSnapshot";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetInstanceSnapshotName())
{
context.Writer.WritePropertyName("instanceSnapshotName");
context.Writer.Write(publicRequest.InstanceSnapshotName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static GetInstanceSnapshotRequestMarshaller _instance = new GetInstanceSnapshotRequestMarshaller();
internal static GetInstanceSnapshotRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetInstanceSnapshotRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.809524 | 154 | 0.619922 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/GetInstanceSnapshotRequestMarshaller.cs | 3,865 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.