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 |
|---|---|---|---|---|---|---|---|---|
#region
using Kudos.Exceptions;
using Newtonsoft.Json;
using System.Collections.Immutable;
using System.ComponentModel;
#endregion
namespace Kudos.Models.bases {
public abstract class SettingBase : INotifyPropertyChanged {
public abstract string HelpText { get; }
public abstract string HtmlHelpText { get; }
public abstract string StringValue { get; }
[JsonIgnore]
public string Description { get; }
[JsonIgnore]
public SettingNames Name { get; }
public abstract bool IsSet { get; protected set; }
public abstract object ObjectValue { get; set; }
protected SettingBase(SettingNames name, string description) {
Name = name;
Description = description;
}
public abstract bool AddValueWithString(string value, Settings settings, int valueParameterIndex = 1, string key = null, int? keyParameterIndex = null);
public abstract SettingBase Merge(SettingBase guildSetting);
public abstract bool SetValueWithString(string value, Settings settings, int parameterIndex = 1);
public bool AddOrSetValue(string value, Settings settings, int valueParameterIndex = 1, string key = null, int? keyParameterIndex = null) =>
this is IDictionarySetting
? AddValueWithString(value, settings, valueParameterIndex, key, keyParameterIndex)
: SetValueWithString(value, settings, valueParameterIndex);
public static Setting<T> Create<T>(SettingNames name, T defaultValue, string description) => new(name, defaultValue, description);
public static ListSetting<T> Create<T>(SettingNames name, ImmutableHashSet<T> defaultValue, string description) => new(name, defaultValue, description);
public static DictionarySetting<T1, T2> Create<T1, T2>(SettingNames name, ImmutableDictionary<T1, T2> defaultValue, string description) =>
new(name, defaultValue, description);
protected void SameTypeCheck(SettingBase setting) {
if (setting.GetType() == GetType()) {
return;
}
throw new KudosInternalException("setting must be of the same type");
}
public void Value<T>(out T value) {
value = this is Setting<T> setting ? setting.Value : default;
}
public abstract event PropertyChangedEventHandler PropertyChanged;
}
} | 38.650794 | 160 | 0.679261 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | TheBlue-1/kudos | Kudos/Models/bases/SettingBase.cs | 2,437 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Serilog;
using SysExtensions.Collections;
using SysExtensions.Serialization;
using SysExtensions.Text;
using SysExtensions.Threading;
namespace Mutuo.Etl.Blob {
public interface IJsonlStore {
public static readonly JsonSerializerSettings JCfg = new() {
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Include,
Formatting = Formatting.None,
Converters = {
new StringEnumConverter()
}
};
SPath Path { get; }
ISimpleFileStore Store { get; }
/// <summary>returns the latest file (either in landing or staging) within the given partition</summary>
/// <param name="partition"></param>
/// <returns></returns>
Task<StoreFileMd> LatestFile(SPath path = null);
IAsyncEnumerable<IReadOnlyCollection<StoreFileMd>> Files(SPath path, bool allDirectories = false);
}
/// <summary>Read/write to storage for an append-only immutable collection of items sored as jsonl</summary>
public class JsonlStore<T> : IJsonlStore {
readonly Func<T, string> GetPartition;
readonly Func<T, string> GetTs;
readonly ILogger Log;
readonly int Parallel;
readonly string Version;
/// <summary></summary>
/// <param name="getTs">A function to get a timestamp for this file. This must always be greater for new records using an
/// invariant string comparer</param>
public JsonlStore(ISimpleFileStore store, SPath path, Func<T, string> getTs,
ILogger log, string version = "", Func<T, string> getPartition = null, int parallel = 8) {
Store = store;
Path = path;
GetTs = getTs;
Log = log;
GetPartition = getPartition;
Parallel = parallel;
Version = version;
}
public ISimpleFileStore Store { get; }
public SPath Path { get; }
/// <summary>Returns the most recent file within this path (any child directories)</summary>
public async Task<StoreFileMd> LatestFile(SPath path = null) {
var files = await Files(path, allDirectories: true).SelectManyList();
var latest = files.OrderByDescending(f => StoreFileMd.GetTs(f.Path)).FirstOrDefault();
return latest;
}
public IAsyncEnumerable<IReadOnlyCollection<StoreFileMd>> Files(SPath path, bool allDirectories = false) =>
Store.Files(FilePath(path), allDirectories);
string Partition(T item) => GetPartition?.Invoke(item);
/// <summary>The land path for a given partition is where files are first put before being optimised. Default -
/// [Path]/[Partition], LandAndStage - [Path]/land/[partition]</summary>
SPath FilePath(string partition = null) => partition.NullOrEmpty() ? Path : Path.Add(partition);
public Task Append(T item, ILogger log = null) => Append(item.InArray(), log);
public async Task Append(IReadOnlyCollection<T> items, ILogger log = null) {
log ??= Log;
if (items.None()) return;
await items.GroupBy(Partition).BlockDo(async g => {
var ts = g.Max(GetTs);
var path = JsonlStoreExtensions.FilePath(FilePath(g.Key), ts, Version);
using var memStream = await g.ToJsonlGzStream(IJsonlStore.JCfg);
await Store.Save(path, memStream, log).WithDuration();
}, Parallel);
}
public async IAsyncEnumerable<IReadOnlyCollection<T>> Items(string partition = null) {
await foreach (var dir in Files(partition, allDirectories: true))
await foreach (var item in dir.BlockMap(f => LoadJsonl(f.Path), Parallel, capacity: 10))
yield return item;
}
async Task<IReadOnlyCollection<T>> LoadJsonl(SPath path) {
await using var stream = await Store.Load(path);
return stream.LoadJsonlGz<T>(IJsonlStore.JCfg);
}
}
public record StoreFileMd {
public StoreFileMd() { }
public StoreFileMd(SPath path, string ts, DateTime modified, long? bytes, string version = null) {
Path = path;
Ts = ts;
Modified = modified;
Bytes = bytes;
Version = version;
}
public SPath Path { get; set; }
public string Ts { get; set; }
public DateTime Modified { get; set; }
public string Version { get; set; }
public long? Bytes { get; set; }
public static StoreFileMd FromFileItem(FileListItem file) {
var tokens = file.Path.Name.Split(".");
var ts = tokens.FirstOrDefault();
var version = tokens.Length >= 4 ? tokens[1] : null;
return new(file.Path, ts, file.Modified?.UtcDateTime ?? DateTime.MinValue, file.Bytes, version);
}
public static string GetTs(SPath path) => path.Name.Split(".").FirstOrDefault();
}
} | 37.546875 | 125 | 0.674782 | [
"MIT"
] | markledwich2/Recfluence | App/Mutuo.Etl/Blob/JsonlStore.cs | 4,806 | C# |
// Copyright (C) 2017 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Alexey Kulakov
// Created: 2017.07.12
using NUnit.Framework;
using Xtensive.Orm.Configuration;
using Xtensive.Orm.Model;
using Xtensive.Orm.Providers;
using Xtensive.Orm.Upgrade;
using Xtensive.Orm.Tests.Upgrade.DynamicFulltextCatalogTestModel;
using Xtensive.Orm.Upgrade.Model;
using Database1 = Xtensive.Orm.Tests.Upgrade.DynamicFulltextCatalogTestModel.Database1;
using Database2 = Xtensive.Orm.Tests.Upgrade.DynamicFulltextCatalogTestModel.Database2;
namespace Xtensive.Orm.Tests.Upgrade.DynamicFulltextCatalogTestModel
{
namespace Database1
{
namespace Default
{
[HierarchyRoot]
public class TestEntity1 : Entity
{
[Field, Key]
public int Id { get; set; }
[Field]
[FullText("English")]
public string Text { get; set; }
}
}
namespace Model1
{
[HierarchyRoot]
public class TestEntity2 : Entity
{
[Field, Key]
public int Id { get; set; }
[Field]
[FullText("English")]
public string Text { get; set; }
}
}
namespace Model2
{
[HierarchyRoot]
public class TestEntity3 : Entity
{
[Field, Key]
public int Id { get; set; }
[Field]
[FullText("English")]
public string Text { get; set; }
}
}
}
namespace Database2
{
namespace Default
{
[HierarchyRoot]
public class TestEntity4 : Entity
{
[Field, Key]
public int Id { get; set; }
[Field]
[FullText("English")]
public string Text { get; set; }
}
}
namespace Model1
{
[HierarchyRoot]
public class TestEntity5 : Entity
{
[Field, Key]
public int Id { get; set; }
[Field]
[FullText("English")]
public string Text { get; set; }
}
}
namespace Model2
{
[HierarchyRoot]
public class TestEntity6 : Entity
{
[Field, Key]
public int Id { get; set; }
[Field]
[FullText("English")]
public string Text { get; set; }
}
}
}
[HierarchyRoot]
public class TestEntity : Entity
{
[Field, Key]
public int Id { get; set; }
[Field]
[FullText("English")]
public string Text { get; set; }
}
public class CustomFullTextCatalogNameBuilder : FullTextCatalogNameBuilder
{
private const string CatalogNameTemplate = "{catalog}_{schema}";
public override bool IsEnabled
{
get { return true; }
}
protected override string Build(TypeInfo typeInfo, string databaseName, string schemaName, string tableName)
{
return CatalogNameTemplate.Replace("{catalog}", databaseName).Replace("{schema}", schemaName);
}
}
public class CustomUpgradeHandler : UpgradeHandler
{
public override bool CanUpgradeFrom(string oldVersion)
{
return true;
}
public override void OnComplete(Domain domain)
{
domain.Extensions.Set(UpgradeContext.TargetStorageModel);
}
}
}
namespace Xtensive.Orm.Tests.Upgrade
{
[TestFixture]
public class DynamicFullTextCatalogTest
{
[OneTimeSetUp]
public void TestFixtureSetUp()
{
Require.AllFeaturesSupported(ProviderFeatures.FullText);
}
[Test]
public void NoResolverTest()
{
var configuration = DomainConfigurationFactory.Create();
configuration.Types.Register(typeof (TestEntity));
configuration.Types.Register(typeof (CustomUpgradeHandler));
configuration.UpgradeMode = DomainUpgradeMode.Recreate;
using (var domain = Domain.Build(configuration)) {
var targetStorageModel = domain.Extensions.Get<StorageModel>();
var table = targetStorageModel.Tables["TestEntity"];
var ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Null);
}
}
[Test]
public void SingleSchemaTest()
{
var configuration = DomainConfigurationFactory.Create();
configuration.Types.Register(typeof (TestEntity));
configuration.Types.Register(typeof (CustomUpgradeHandler));
configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder));
configuration.UpgradeMode = DomainUpgradeMode.Recreate;
using (var domain = Domain.Build(configuration)) {
var targetStorageModel = domain.Extensions.Get<StorageModel>();
var table = targetStorageModel.Tables["TestEntity"];
var ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
var database = domain.StorageProviderInfo.DefaultDatabase;
var schema = domain.StorageProviderInfo.DefaultSchema;
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_{1}", database, schema)));
}
}
[Test]
public void SingleSchemaWithDatabaseSwitchTest()
{
Require.ProviderIs(StorageProvider.SqlServer);
var configuration = DomainConfigurationFactory.Create();
configuration.Types.Register(typeof (TestEntity));
configuration.Types.Register(typeof (CustomUpgradeHandler));
configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder));
configuration.ConnectionInitializationSql = "USE [DO-Tests-1]";
configuration.UpgradeMode = DomainUpgradeMode.Recreate;
using (var domain = Domain.Build(configuration)) {
var targetStorageModel = domain.Extensions.Get<StorageModel>();
var table = targetStorageModel.Tables["TestEntity"];
var ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_dbo"));
}
}
[Test]
public void MultischemaTest()
{
Require.AllFeaturesSupported(ProviderFeatures.Multischema);
var defaultSchemaType = typeof (Database1.Default.TestEntity1);
var model1Type = typeof (Database1.Model1.TestEntity2);
var model2Type = typeof (Database1.Model2.TestEntity3);
var configuration = DomainConfigurationFactory.Create();
configuration.Types.Register(defaultSchemaType);
configuration.Types.Register(model1Type);
configuration.Types.Register(model2Type);
configuration.Types.Register(typeof (CustomUpgradeHandler));
configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder));
configuration.DefaultSchema = "dbo";
configuration.MappingRules.Map(defaultSchemaType.Assembly, defaultSchemaType.Namespace).ToSchema("dbo");
configuration.MappingRules.Map(model1Type.Assembly, model1Type.Namespace).ToSchema("Model1");
configuration.MappingRules.Map(model2Type.Assembly, model2Type.Namespace).ToSchema("Model2");
configuration.UpgradeMode = DomainUpgradeMode.Recreate;
using (var domain = Domain.Build(configuration)) {
var database = domain.StorageProviderInfo.DefaultDatabase;
var targetModel = domain.Extensions.Get<StorageModel>();
var defaultSchemaTable = targetModel.Tables["dbo:TestEntity1"];
var ftIndex = defaultSchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_dbo", database)));
var model1SchemaTable = targetModel.Tables["Model1:TestEntity2"];
ftIndex = model1SchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_Model1", database)));
var model2SchemaTable = targetModel.Tables["Model2:TestEntity3"];
ftIndex = model2SchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo(string.Format("{0}_Model2", database)));
}
}
[Test]
public void MultidatabaseTest()
{
Require.AllFeaturesSupported(ProviderFeatures.Multidatabase);
var db1DefaultSchemaType = typeof (Database1.Default.TestEntity1);
var db1Model1SchemaType = typeof (Database1.Model1.TestEntity2);
var db1Model2SchemaType = typeof (Database1.Model2.TestEntity3);
var db2DefaultSchemaType = typeof (Database2.Default.TestEntity4);
var db2Model1SchemaType = typeof (Database2.Model1.TestEntity5);
var db2Model2SchemaType = typeof (Database2.Model2.TestEntity6);
var configuragtion = DomainConfigurationFactory.Create();
configuragtion.Types.Register(db1DefaultSchemaType);
configuragtion.Types.Register(db1Model1SchemaType);
configuragtion.Types.Register(db1Model2SchemaType);
configuragtion.Types.Register(db2DefaultSchemaType);
configuragtion.Types.Register(db2Model1SchemaType);
configuragtion.Types.Register(db2Model2SchemaType);
configuragtion.Types.Register(typeof (CustomUpgradeHandler));
configuragtion.Types.Register(typeof (CustomFullTextCatalogNameBuilder));
configuragtion.DefaultDatabase = "DO-Tests";
configuragtion.DefaultSchema = "dbo";
configuragtion.MappingRules.Map(db1DefaultSchemaType.Assembly, db1DefaultSchemaType.Namespace).To("DO-Tests", "dbo");
configuragtion.MappingRules.Map(db1Model1SchemaType.Assembly, db1Model1SchemaType.Namespace).To("DO-Tests", "Model1");
configuragtion.MappingRules.Map(db1Model2SchemaType.Assembly, db1Model2SchemaType.Namespace).To("DO-Tests", "Model2");
configuragtion.MappingRules.Map(db2DefaultSchemaType.Assembly, db2DefaultSchemaType.Namespace).To("DO-Tests-1", "dbo");
configuragtion.MappingRules.Map(db2Model1SchemaType.Assembly, db2Model1SchemaType.Namespace).To("DO-Tests-1", "Model1");
configuragtion.MappingRules.Map(db2Model2SchemaType.Assembly, db2Model2SchemaType.Namespace).To("DO-Tests-1", "Model2");
configuragtion.UpgradeMode = DomainUpgradeMode.Recreate;
using (var domain = Domain.Build(configuragtion)) {
var targetStorageModel = domain.Extensions.Get<StorageModel>();
var db1DefaultSchemaTable = targetStorageModel.Tables["DO-Tests:dbo:TestEntity1"];
Assert.That(db1DefaultSchemaTable, Is.Not.Null);
var ftIndex = db1DefaultSchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo"));
var db1Model1SchemaTable = targetStorageModel.Tables["DO-Tests:Model1:TestEntity2"];
ftIndex = db1Model1SchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model1"));
var db1Model2SchemaTable = targetStorageModel.Tables["DO-Tests:Model2:TestEntity3"];
ftIndex = db1Model2SchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model2"));
var db2DefaultSchemaTable = targetStorageModel.Tables["DO-Tests-1:dbo:TestEntity4"];
ftIndex = db2DefaultSchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_dbo"));
var db2Model1SchemaTable = targetStorageModel.Tables["DO-Tests-1:Model1:TestEntity5"];
ftIndex = db2Model1SchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model1"));
var db2Model2SchemaTable = targetStorageModel.Tables["DO-Tests-1:Model2:TestEntity6"];
ftIndex = db2Model2SchemaTable.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model2"));
}
}
[Test]
public void MultinodeTest1()
{
Require.ProviderIs(StorageProvider.SqlServer);
var configuration = DomainConfigurationFactory.Create();
configuration.UpgradeMode = DomainUpgradeMode.Recreate;
configuration.Types.Register(typeof (TestEntity));
configuration.Types.Register(typeof (CustomUpgradeHandler));
configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder));
configuration.DefaultSchema = "dbo";
var nodeConfiguration1 = new NodeConfiguration("AdditionalNode1");
nodeConfiguration1.UpgradeMode = DomainUpgradeMode.Recreate;
nodeConfiguration1.SchemaMapping.Add("dbo", "Model1");
var nodeConfiguration2 = new NodeConfiguration("AdditionalNode2");
nodeConfiguration2.UpgradeMode = DomainUpgradeMode.Recreate;
nodeConfiguration2.SchemaMapping.Add("dbo", "Model2");
using (var domain = Domain.Build(configuration)) {
var domainStorageModel = domain.Extensions.Get<StorageModel>();
var table = domainStorageModel.Tables["dbo:TestEntity"];
Assert.That(table, Is.Not.Null);
var ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo"));
domain.Extensions.Clear();
domain.StorageNodeManager.AddNode(nodeConfiguration1);
var node1StorageModel = domain.Extensions.Get<StorageModel>();
table = node1StorageModel.Tables["Model1:TestEntity"];
Assert.That(table, Is.Not.Null);
ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model1"));
domain.Extensions.Clear();
domain.StorageNodeManager.AddNode(nodeConfiguration2);
var node2StorageModel = domain.Extensions.Get<StorageModel>();
table = node2StorageModel.Tables["Model2:TestEntity"];
Assert.That(table, Is.Not.Null);
ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_Model2"));
}
}
[Test]
public void MultinodeTest2()
{
Require.ProviderIs(StorageProvider.SqlServer);
var configuration = DomainConfigurationFactory.Create();
configuration.UpgradeMode = DomainUpgradeMode.Recreate;
configuration.Types.Register(typeof (TestEntity));
configuration.Types.Register(typeof (CustomUpgradeHandler));
configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder));
configuration.DefaultSchema = "dbo";
configuration.DefaultDatabase = "DO-Tests";
var nodeConfiguration1 = new NodeConfiguration("AdditionalNode1");
nodeConfiguration1.UpgradeMode = DomainUpgradeMode.Recreate;
nodeConfiguration1.SchemaMapping.Add("dbo", "Model1");
nodeConfiguration1.DatabaseMapping.Add("DO-Tests", "DO-Tests-1");
var nodeConfiguration2 = new NodeConfiguration("AdditionalNode2");
nodeConfiguration2.UpgradeMode = DomainUpgradeMode.Recreate;
nodeConfiguration2.SchemaMapping.Add("dbo", "Model2");
nodeConfiguration2.DatabaseMapping.Add("DO-Tests", "DO-Tests-2");
using (var domain = Domain.Build(configuration)) {
var domainStorageModel = domain.Extensions.Get<StorageModel>();
var table = domainStorageModel.Tables["DO-Tests:dbo:TestEntity"];
Assert.That(table, Is.Not.Null);
var ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo"));
domain.Extensions.Clear();
domain.StorageNodeManager.AddNode(nodeConfiguration1);
var node1StorageModel = domain.Extensions.Get<StorageModel>();
table = node1StorageModel.Tables["DO-Tests-1:Model1:TestEntity"];
Assert.That(table, Is.Not.Null);
ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model1"));
domain.Extensions.Clear();
domain.StorageNodeManager.AddNode(nodeConfiguration2);
var node2StorageModel = domain.Extensions.Get<StorageModel>();
table = node2StorageModel.Tables["DO-Tests-2:Model2:TestEntity"];
Assert.That(table, Is.Not.Null);
ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-2_Model2"));
}
}
[Test]
public void MultinodeTest3()
{
Require.ProviderIs(StorageProvider.SqlServer);
var configuration = DomainConfigurationFactory.Create();
configuration.UpgradeMode = DomainUpgradeMode.Recreate;
configuration.Types.Register(typeof (TestEntity));
configuration.Types.Register(typeof (CustomUpgradeHandler));
configuration.Types.Register(typeof (CustomFullTextCatalogNameBuilder));
configuration.DefaultSchema = "dbo";
var nodeConfiguration1 = new NodeConfiguration("AdditionalNode1");
nodeConfiguration1.ConnectionInitializationSql = "USE [DO-Tests-1]";
nodeConfiguration1.UpgradeMode = DomainUpgradeMode.Recreate;
nodeConfiguration1.SchemaMapping.Add("dbo", "Model1");
var nodeConfiguration2 = new NodeConfiguration("AdditionalNode2");
nodeConfiguration2.ConnectionInitializationSql = "USE [DO-Tests-2]";
nodeConfiguration2.UpgradeMode = DomainUpgradeMode.Recreate;
nodeConfiguration2.SchemaMapping.Add("dbo", "Model2");
using (var domain = Domain.Build(configuration)) {
var domainStorageModel = domain.Extensions.Get<StorageModel>();
var table = domainStorageModel.Tables["dbo:TestEntity"];
Assert.That(table, Is.Not.Null);
var ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests_dbo"));
domain.Extensions.Clear();
domain.StorageNodeManager.AddNode(nodeConfiguration1);
var node1StorageModel = domain.Extensions.Get<StorageModel>();
table = node1StorageModel.Tables["Model1:TestEntity"];
Assert.That(table, Is.Not.Null);
ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-1_Model1"));
domain.Extensions.Clear();
domain.StorageNodeManager.AddNode(nodeConfiguration2);
var node2StorageModel = domain.Extensions.Get<StorageModel>();
table = node2StorageModel.Tables["Model2:TestEntity"];
Assert.That(table, Is.Not.Null);
ftIndex = table.FullTextIndexes[0];
Assert.That(ftIndex, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.Not.Null);
Assert.That(ftIndex.FullTextCatalog, Is.EqualTo("DO-Tests-2_Model2"));
}
}
}
}
| 40.127451 | 127 | 0.679697 | [
"MIT"
] | SergeiPavlov/dataobjects-net | Orm/Xtensive.Orm.Tests/Upgrade/FullText/DynamicFullTextCatalogTest.cs | 20,467 | C# |
using System;
namespace Lithnet.Miiserver.Client
{
/// <summary>
/// An exception that is throw when more than the expected number of results are returned from a query
/// </summary>
[Serializable]
public class TooManyResultsException : Exception
{
/// <summary>
/// Initializes a new instance of the TooManyResultsException
/// </summary>
public TooManyResultsException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the TooManyResultsException
/// </summary>
/// <param name="message">A message describing the condition</param>
public TooManyResultsException(string message)
:base(message)
{
}
}
}
| 27 | 106 | 0.586207 | [
"MIT"
] | lithnet/miis-client | src/Lithnet.Miiserver.Client/Exceptions/TooManyResultsException.cs | 785 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trap : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
FindObjectOfType<LevelManager>().GameOver();
}
}
}
| 19.625 | 56 | 0.659236 | [
"MIT"
] | frolushka/d01 | Assets/Scripts/Trap.cs | 316 | C# |
using System; using ComponentBind;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Lemma.Components;
using System.IO;
using Lemma.Util;
namespace Lemma.Factories
{
public class DialogueFileFactory : Factory<Main>
{
public DialogueFileFactory()
{
this.Color = new Vector3(0.4f, 0.4f, 0.4f);
this.AvailableInRelease = false;
}
public override Entity Create(Main main)
{
Entity entity = new Entity(main, "DialogueFile");
entity.Add("Transform", new Transform());
return entity;
}
public override void Bind(Entity entity, Main main, bool creating = false)
{
this.SetMain(entity, main);
entity.CannotSuspend = true;
DialogueFile file = entity.GetOrCreate<DialogueFile>("DialogueFile");
file.EditorProperties();
}
}
}
| 21.230769 | 76 | 0.722222 | [
"Unlicense",
"MIT"
] | MSylvia/Lemma | Lemma/Factories/DialogueFileFactory.cs | 830 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MailSender
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} | 25.086957 | 99 | 0.587522 | [
"MIT"
] | EmilMitev/Telerik-Academy | Web Services and Cloud/Slides and demos/Archive/PaaS-Cloud-Hosting-for-.NET-and-Cloud-Databases/Demo/MailSender/MailSender/App_Start/RouteConfig.cs | 579 | C# |
// <auto-generated />
using System;
using MSN.BlazorServer.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace MySoloNetwork.Migrations.MSNBlazorServer
{
[DbContext(typeof(MSNBlazorServerContext))]
partial class MSNBlazorServerContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "5.0.7");
modelBuilder.Entity("MSN.BlazorServer.Data.SecurityStatement", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<Guid>("AspNetUsersID")
.HasColumnType("TEXT");
b.Property<string>("Statement")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("SecurityStatements");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessFailedCount")
.HasColumnType("INTEGER");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER");
b.Property<bool>("LockoutEnabled")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("TEXT");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("PhoneNumber")
.HasColumnType("TEXT");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("SecurityStamp")
.HasColumnType("TEXT");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("ProviderKey")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("ProviderDisplayName")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.HasColumnType("TEXT");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("LoginProvider")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 35.412587 | 95 | 0.446781 | [
"MIT"
] | JeffStewartDev/MySoloNetwork | ModelContext/MSNBlazorServerContextModelSnapshot.cs | 10,128 | C# |
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Firebase.Auth;
using Firebase.Database;
using System;
using System.Collections.Generic;
namespace Friends_Chat
{
[Activity(Label = "CreateChatActivity")]
public class CreateChatActivity : Activity, IChildEventListener
{
protected TextView titleUserSelection, titleChatName;
protected Spinner chatType, userToSelect;
protected ArrayAdapter adapterChatType, adapterUserList;
protected EditText chatName;
protected Button confirm;
private List<string> userList = new List<string>();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.CreateChat);
InitializeUserList();
InitializeTextViews();
InitializeSpinner();
InitializeEditText();
InitializeButton();
UpdateUI();
}
/// <summary>
/// Méthode d'initialisation de la liste des utilisateurs de l'application
/// </summary>
private void InitializeUserList()
{
FirebaseDatabase.Instance.Reference.Child("users").AddChildEventListener(this);
}
/// <summary>
/// Méthode d'initialisation des TextViews
/// </summary>
private void InitializeTextViews()
{
titleChatName = FindViewById<TextView>(Resource.Id.titleChatName);
titleUserSelection = FindViewById<TextView>(Resource.Id.titleUserSelection);
}
/// <summary>
/// Méthode d'initialisation des Spinner
/// </summary>
private void InitializeSpinner()
{
// Etape 1 : On récupère les références
chatType = FindViewById<Spinner>(Resource.Id.chatType);
userToSelect = FindViewById<Spinner>(Resource.Id.chatUser);
// Etape 2 : On crée les adaptateurs adéquats pour les spinners
adapterChatType = ArrayAdapter.CreateFromResource(this, Resource.Array.group_type_array, Android.Resource.Layout.SimpleSpinnerItem);
adapterChatType.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
chatType.Adapter = adapterChatType;
adapterUserList = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, userList);
userToSelect.Adapter = adapterUserList;
// Etape 3 : on crée les listeners
chatType.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => {
UpdateUI();
};
}
/// <summary>
/// Méthode d'initialisation du champ d'édition
/// </summary>
private void InitializeEditText()
{
chatName = FindViewById<EditText>(Resource.Id.chatRoomName);
}
private void InitializeButton()
{
confirm = FindViewById<Button>(Resource.Id.button_ok);
confirm.Click += delegate
{
switch (chatType.SelectedItemPosition)
{
case 0:
Log.Debug("Chat", "Chat de groupe sélectionné");
FirebaseDatabase.Instance.Reference.Child("groupChat").Child(chatName.Text.ToString()).Child("createAt").SetValueAsync(DateTimeOffset.Now.ToUnixTimeSeconds());
StartActivity(typeof(MainActivity));
break;
case 1:
Log.Debug("Chat", "Chat One to One sélectionné");
FirebaseDatabase.Instance.Reference.Child("oneToOneChat").Child(FirebaseAuth.Instance.CurrentUser.DisplayName + "~" + userList[userToSelect.SelectedItemPosition]).Child("createAt").SetValueAsync(DateTimeOffset.Now.ToUnixTimeSeconds());
StartActivity(typeof(MainActivity));
break;
default:
break;
}
};
}
/// <summary>
/// Méthode permettant de mettre à jour l'interface graphique de l'activité :
/// -> Le champ d'édition du nom de tchat collectif disparait si Tchat pour deux est sélectionné;
/// -> Le spinner de sélection d'un utilisateur disparait si Tchat de groupe est sélectionné;
/// -> Par défaut, tous les composants sont invisibles.
/// </summary>
private void UpdateUI()
{
switch (chatType.SelectedItemPosition)
{
case 0:
titleChatName.Visibility = ViewStates.Visible;
chatName.Visibility = ViewStates.Visible;
titleUserSelection.Visibility = ViewStates.Gone;
userToSelect.Visibility = ViewStates.Gone;
break;
case 1:
titleChatName.Visibility = ViewStates.Gone;
chatName.Visibility = ViewStates.Gone;
titleUserSelection.Visibility = ViewStates.Visible;
userToSelect.Visibility = ViewStates.Visible;
break;
default:
titleChatName.Visibility = ViewStates.Gone;
chatName.Visibility = ViewStates.Gone;
titleUserSelection.Visibility = ViewStates.Gone;
userToSelect.Visibility = ViewStates.Gone;
break;
}
}
public void OnCancelled(DatabaseError error) { }
public void OnChildAdded(DataSnapshot snapshot, string previousChildName)
{
if (!snapshot.Key.Equals(FirebaseAuth.Instance.CurrentUser.DisplayName))
{
userList.Add(snapshot.Key);
adapterUserList.NotifyDataSetChanged();
}
}
public void OnChildChanged(DataSnapshot snapshot, string previousChildName) { }
public void OnChildMoved(DataSnapshot snapshot, string previousChildName) { }
public void OnChildRemoved(DataSnapshot snapshot) { }
}
} | 38.564417 | 259 | 0.592428 | [
"MIT"
] | Macjiji/Friends-Chat-Csharp | app/CreateChatActivity.cs | 6,314 | C# |
using System.IO.Abstractions;
using System.Text.RegularExpressions;
using UnityEngine;
using System.IO;
using Unity.MLAgents.Policies;
using UnityEngine.Serialization;
namespace Unity.MLAgents.Demonstrations
{
/// <summary>
/// The Demonstration Recorder component facilitates the recording of demonstrations
/// used for imitation learning.
/// </summary>
/// <remarks>Add this component to the [GameObject] containing an <see cref="Agent"/>
/// to enable recording the agent for imitation learning. You must implement the
/// <see cref="Agent.Heuristic"/> function of the agent to provide manual control
/// in order to record demonstrations.
///
/// See [Imitation Learning - Recording Demonstrations] for more information.
///
/// [GameObject]: https://docs.unity3d.com/Manual/GameObjects.html
/// [Imitation Learning - Recording Demonstrations]: https://github.com/Unity-Technologies/ml-agents/blob/release_2_verified_docs/docs//Learning-Environment-Design-Agents.md#recording-demonstrations
/// </remarks>
[RequireComponent(typeof(Agent))]
[AddComponentMenu("ML Agents/Demonstration Recorder", (int)MenuGroup.Default)]
public class DemonstrationRecorder : MonoBehaviour
{
/// <summary>
/// Whether or not to record demonstrations.
/// </summary>
[FormerlySerializedAs("record")]
[Tooltip("Whether or not to record demonstrations.")]
public bool Record;
/// <summary>
/// Base demonstration file name. If multiple files are saved, the additional filenames
/// will have a sequence of unique numbers appended.
/// </summary>
[FormerlySerializedAs("demonstrationName")]
[Tooltip("Base demonstration file name. If multiple files are saved, the additional " +
"filenames will have a unique number appended.")]
public string DemonstrationName;
/// <summary>
/// Directory to save the demo files. Will default to a "Demonstrations/" folder in the
/// Application data path if not specified.
/// </summary>
[FormerlySerializedAs("demonstrationDirectory")]
[Tooltip("Directory to save the demo files. Will default to " +
"{Application.dataPath}/Demonstrations if not specified.")]
public string DemonstrationDirectory;
DemonstrationWriter m_DemoWriter;
internal const int MaxNameLength = 16;
const string k_ExtensionType = ".demo";
const string k_DefaultDirectoryName = "Demonstrations";
IFileSystem m_FileSystem;
Agent m_Agent;
void OnEnable()
{
m_Agent = GetComponent<Agent>();
}
void Update()
{
if (Record)
{
LazyInitialize();
}
}
/// <summary>
/// Creates demonstration store for use in recording.
/// Has no effect if the demonstration store was already created.
/// </summary>
internal DemonstrationWriter LazyInitialize(IFileSystem fileSystem = null)
{
if (m_DemoWriter != null)
{
return m_DemoWriter;
}
if (m_Agent == null)
{
m_Agent = GetComponent<Agent>();
}
m_FileSystem = fileSystem ?? new FileSystem();
var behaviorParams = GetComponent<BehaviorParameters>();
if (string.IsNullOrEmpty(DemonstrationName))
{
DemonstrationName = behaviorParams.BehaviorName;
}
if (string.IsNullOrEmpty(DemonstrationDirectory))
{
DemonstrationDirectory = Path.Combine(Application.dataPath, k_DefaultDirectoryName);
}
DemonstrationName = SanitizeName(DemonstrationName, MaxNameLength);
var filePath = MakeDemonstrationFilePath(m_FileSystem, DemonstrationDirectory, DemonstrationName);
var stream = m_FileSystem.File.Create(filePath);
m_DemoWriter = new DemonstrationWriter(stream);
AddDemonstrationWriterToAgent(m_DemoWriter);
return m_DemoWriter;
}
/// <summary>
/// Removes all characters except alphanumerics from demonstration name.
/// Shorten name if it is longer than the maxNameLength.
/// </summary>
internal static string SanitizeName(string demoName, int maxNameLength)
{
var rgx = new Regex("[^a-zA-Z0-9 -]");
demoName = rgx.Replace(demoName, "");
// If the string is too long, it will overflow the metadata.
if (demoName.Length > maxNameLength)
{
demoName = demoName.Substring(0, maxNameLength);
}
return demoName;
}
/// <summary>
/// Gets a unique path for the DemonstrationName in the DemonstrationDirectory.
/// </summary>
/// <param name="fileSystem"></param>
/// <param name="demonstrationDirectory"></param>
/// <param name="demonstrationName"></param>
/// <returns></returns>
internal static string MakeDemonstrationFilePath(
IFileSystem fileSystem, string demonstrationDirectory, string demonstrationName
)
{
// Create the directory if it doesn't already exist
if (!fileSystem.Directory.Exists(demonstrationDirectory))
{
fileSystem.Directory.CreateDirectory(demonstrationDirectory);
}
var literalName = demonstrationName;
var filePath = Path.Combine(demonstrationDirectory, literalName + k_ExtensionType);
var uniqueNameCounter = 0;
while (fileSystem.File.Exists(filePath))
{
// TODO should we use a timestamp instead of a counter here? This loops an increasing number of times
// as the number of demos increases.
literalName = demonstrationName + "_" + uniqueNameCounter;
filePath = Path.Combine(demonstrationDirectory, literalName + k_ExtensionType);
uniqueNameCounter++;
}
return filePath;
}
/// <summary>
/// Close the DemonstrationWriter and remove it from the Agent.
/// Has no effect if the DemonstrationWriter is already closed (or wasn't opened)
/// </summary>
public void Close()
{
if (m_DemoWriter != null)
{
RemoveDemonstrationWriterFromAgent(m_DemoWriter);
m_DemoWriter.Close();
m_DemoWriter = null;
}
}
/// <summary>
/// Clean up the DemonstrationWriter when shutting down or destroying the Agent.
/// </summary>
void OnDestroy()
{
Close();
}
/// <summary>
/// Add additional DemonstrationWriter to the Agent. It is still up to the user to Close this
/// DemonstrationWriters when recording is done.
/// </summary>
/// <param name="demoWriter"></param>
public void AddDemonstrationWriterToAgent(DemonstrationWriter demoWriter)
{
var behaviorParams = GetComponent<BehaviorParameters>();
demoWriter.Initialize(
DemonstrationName,
behaviorParams.BrainParameters,
behaviorParams.FullyQualifiedBehaviorName
);
m_Agent.DemonstrationWriters.Add(demoWriter);
}
/// <summary>
/// Remove additional DemonstrationWriter to the Agent. It is still up to the user to Close this
/// DemonstrationWriters when recording is done.
/// </summary>
/// <param name="demoWriter"></param>
public void RemoveDemonstrationWriterFromAgent(DemonstrationWriter demoWriter)
{
m_Agent.DemonstrationWriters.Remove(demoWriter);
}
}
}
| 38.380952 | 202 | 0.608685 | [
"MIT"
] | AlbertCayuela/NeuralNetwork | CardsOfTheWilds/Library/PackageCache/com.unity.ml-agents@1.0.6/Runtime/Demonstrations/DemonstrationRecorder.cs | 8,060 | C# |
using System.Collections.Generic;
namespace Conjure.Security
{
public interface IAppSecurity
{
AppUser GetUser();
AppRole GetRole();
IEnumerable<AppPermission> GetPermissions();
}
}
| 15.857143 | 52 | 0.657658 | [
"MIT"
] | ebekker/conjure-mvp | src/Conjure.Security/IAppSecurity.cs | 224 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Validation;
namespace BTCPayServer.Models.StoreViewModels
{
public class StoreViewModel
{
public class DerivationScheme
{
public string Crypto { get; set; }
public string Value { get; set; }
public WalletId WalletId { get; set; }
public bool WalletSupported { get; set; }
public bool Enabled { get; set; }
public bool Collapsed { get; set; }
}
public class AdditionalPaymentMethod
{
public string Provider { get; set; }
public bool Enabled { get; set; }
public string Action { get; set; }
}
public StoreViewModel()
{
}
public bool CanDelete { get; set; }
public string Id { get; set; }
[Display(Name = "Store Name")]
[Required]
[MaxLength(50)]
[MinLength(1)]
public string StoreName
{
get; set;
}
[Uri]
[Display(Name = "Store Website")]
[MaxLength(500)]
public string StoreWebsite
{
get;
set;
}
[Display(Name = "Allow anyone to create invoice")]
public bool AnyoneCanCreateInvoice { get; set; }
public List<StoreViewModel.DerivationScheme> DerivationSchemes { get; set; } = new List<StoreViewModel.DerivationScheme>();
public List<AdditionalPaymentMethod> ThirdPartyPaymentMethods { get; set; } =
new List<AdditionalPaymentMethod>();
[Display(Name = "Invoice expires if the full amount has not been paid after ... minutes")]
[Range(1, 60 * 24 * 24)]
public int InvoiceExpiration
{
get;
set;
}
[Display(Name = "Payment invalid if transactions fails to confirm ... minutes after invoice expiration")]
[Range(10, 60 * 24 * 24)]
public int MonitoringExpiration
{
get;
set;
}
[Display(Name = "Consider the invoice confirmed when the payment transaction...")]
public SpeedPolicy SpeedPolicy
{
get; set;
}
[Display(Name = "Add additional fee (network fee) to invoice...")]
public NetworkFeeMode NetworkFeeMode
{
get; set;
}
[Display(Name = "Description template of the lightning invoice")]
public string LightningDescriptionTemplate { get; set; }
[Display(Name = "Enable Payjoin/P2EP")]
public bool PayJoinEnabled { get; set; }
public class LightningNode
{
public string CryptoCode { get; set; }
public string Address { get; set; }
public bool Enabled { get; set; }
}
public List<LightningNode> LightningNodes
{
get; set;
} = new List<LightningNode>();
[Display(Name = "Consider the invoice paid even if the paid amount is ... % less than expected")]
[Range(0, 100)]
public double PaymentTolerance
{
get;
set;
}
}
}
| 28.798246 | 131 | 0.558026 | [
"MIT"
] | dergigi/btcpayserver | BTCPayServer/Models/StoreViewModels/StoreViewModel.cs | 3,285 | C# |
using Bonsai.Editor.Themes;
using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
namespace Bonsai.Editor
{
sealed class EditorSettings
{
const int MaxRecentFiles = 25;
const string RecentlyUsedFilesElement = "RecentlyUsedFiles";
const string DesktopBoundsElement = "DesktopBounds";
const string WindowStateElement = "WindowState";
const string RecentlyUsedFileElement = "RecentlyUsedFile";
const string FileTimestampElement = "Timestamp";
const string FileNameElement = "Name";
const string RectangleXElement = "X";
const string RectangleYElement = "Y";
const string RectangleWidthElement = "Width";
const string RectangleHeightElement = "Height";
const string EditorThemeElement = "EditorTheme";
const string SettingsFileName = "Bonsai.exe.settings";
static readonly string SettingsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), SettingsFileName);
static readonly Lazy<EditorSettings> instance = new Lazy<EditorSettings>(Load);
readonly RecentlyUsedFileCollection recentlyUsedFiles = new RecentlyUsedFileCollection(MaxRecentFiles);
internal EditorSettings()
{
}
public static EditorSettings Instance
{
get { return instance.Value; }
}
public Rectangle DesktopBounds { get; set; }
public FormWindowState WindowState { get; set; }
public ColorTheme EditorTheme { get; set; }
public RecentlyUsedFileCollection RecentlyUsedFiles
{
get { return recentlyUsedFiles; }
}
static EditorSettings Load()
{
var settings = new EditorSettings();
if (File.Exists(SettingsPath))
{
try
{
using (var reader = XmlReader.Create(SettingsPath))
{
reader.MoveToContent();
while (reader.Read())
{
if (reader.NodeType != XmlNodeType.Element) continue;
if (reader.Name == WindowStateElement)
{
FormWindowState windowState;
Enum.TryParse<FormWindowState>(reader.ReadElementContentAsString(), out windowState);
settings.WindowState = windowState;
}
else if (reader.Name == EditorThemeElement)
{
ColorTheme editorTheme;
Enum.TryParse<ColorTheme>(reader.ReadElementContentAsString(), out editorTheme);
settings.EditorTheme = editorTheme;
}
else if (reader.Name == DesktopBoundsElement)
{
int x, y, width, height;
reader.ReadToFollowing(RectangleXElement);
int.TryParse(reader.ReadElementContentAsString(), out x);
reader.ReadToFollowing(RectangleYElement);
int.TryParse(reader.ReadElementContentAsString(), out y);
reader.ReadToFollowing(RectangleWidthElement);
int.TryParse(reader.ReadElementContentAsString(), out width);
reader.ReadToFollowing(RectangleHeightElement);
int.TryParse(reader.ReadElementContentAsString(), out height);
settings.DesktopBounds = new Rectangle(x, y, width, height);
}
else if (reader.Name == RecentlyUsedFilesElement)
{
var fileReader = reader.ReadSubtree();
while (fileReader.ReadToFollowing(RecentlyUsedFileElement))
{
if (fileReader.Name == RecentlyUsedFileElement)
{
string fileName;
DateTimeOffset timestamp;
fileReader.ReadToFollowing(FileTimestampElement);
DateTimeOffset.TryParse(fileReader.ReadElementContentAsString(), out timestamp);
fileReader.ReadToFollowing(FileNameElement);
fileName = fileReader.ReadElementContentAsString();
settings.recentlyUsedFiles.Add(timestamp, fileName);
}
}
}
}
}
}
catch (XmlException) { }
}
return settings;
}
public void Save()
{
using (var writer = XmlWriter.Create(SettingsPath, new XmlWriterSettings { Indent = true }))
{
writer.WriteStartElement(typeof(EditorSettings).Name);
writer.WriteElementString(WindowStateElement, WindowState.ToString());
writer.WriteElementString(EditorThemeElement, EditorTheme.ToString());
writer.WriteStartElement(DesktopBoundsElement);
writer.WriteElementString(RectangleXElement, DesktopBounds.X.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString(RectangleYElement, DesktopBounds.Y.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString(RectangleWidthElement, DesktopBounds.Width.ToString(CultureInfo.InvariantCulture));
writer.WriteElementString(RectangleHeightElement, DesktopBounds.Height.ToString(CultureInfo.InvariantCulture));
writer.WriteEndElement();
if (recentlyUsedFiles.Count > 0)
{
writer.WriteStartElement(RecentlyUsedFilesElement);
foreach (var file in recentlyUsedFiles)
{
writer.WriteStartElement(RecentlyUsedFileElement);
writer.WriteElementString(FileTimestampElement, file.Timestamp.ToString("o"));
writer.WriteElementString(FileNameElement, file.FileName);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
}
}
| 47.891892 | 139 | 0.519752 | [
"MIT"
] | richbryant/bonsai | Bonsai.Editor/EditorSettings.cs | 7,090 | C# |
namespace JokesFunApp.Services.Models.Jokes
{
using JokesFunApp.Data.Models;
using JokesFunApp.Services.Mapping;
public class JokeDetailsViewModel : IMapFrom<Joke>
{
public string Content { get; set; }
public string HtmlContent => this.Content.Replace("\n", "<br />\n");
public string CategoryName { get; set; }
}
}
| 24.266667 | 76 | 0.656593 | [
"MIT"
] | Aleksandrov91/JokesFunApp | src/Services/JokesFunApp.Services.Models/Jokes/JokeDetailsViewModel.cs | 366 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Storage.Shared;
using Moq;
using NUnit.Framework;
namespace Azure.Storage.Tests
{
public class StorageWriteStreamTests
{
private static readonly string s_append = "Append";
private static readonly string s_flush = "Flush";
/// <summary>
/// This test uses a 1 KB buffer, and calls WriteAsync() 9 times.
/// We expect 2 Append calls, 1 Flush call, and 9 writes to the buffer.
/// In the current implementation, there will also be 2 writes to the buffer with count = 0.
/// </summary>
[Test]
public async Task BasicTest()
{
// Arrange
int bufferSize = Constants.KB;
int writeSize = 256;
int writeCount = 9;
Mock<PooledMemoryStream> mockBuffer = new Mock<PooledMemoryStream>(MockBehavior.Strict);
StorageWriteStreamImplementation stream = new StorageWriteStreamImplementation(
position: 0,
bufferSize: bufferSize,
progressHandler: null,
buffer: mockBuffer.Object);
mockBuffer.SetupSequence(r => r.WriteAsync(
It.IsAny<byte[]>(),
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask);
mockBuffer.SetupSequence(r => r.Position)
.Returns(0)
.Returns(256)
.Returns(512)
.Returns(768)
.Returns(1024)
.Returns(1024)
.Returns(0)
.Returns(256)
.Returns(512)
.Returns(1024)
.Returns(1024);
List<byte[]> data = new List<byte[]>();
for (int i = 0; i < writeCount; i++)
{
data.Add(GetRandomBuffer(writeSize));
}
// Act
for (int i = 0; i < writeCount; i++)
{
await stream.WriteAsync(data[i], 0, writeSize);
}
await stream.FlushAsync();
// Assert
Assert.AreEqual(3, stream.ApiCalls.Count);
Assert.AreEqual(s_append, stream.ApiCalls[0]);
Assert.AreEqual(s_append, stream.ApiCalls[1]);
Assert.AreEqual(s_flush, stream.ApiCalls[2]);
mockBuffer.Verify(r => r.Position, Times.Exactly(11));
for (int i = 0; i < writeCount; i++)
{
mockBuffer.Verify(r => r.WriteAsync(
data[i],
0,
writeSize,
default));
}
}
/// <summary>
/// In this test, we are using a 1 KB buffer, and doing 5 writes of 500 bytes each.
/// We expect 2 Append calls, 1 Flush call, and 7 writes to the buffer.
/// </summary>
/// <returns></returns>
[Test]
public async Task NonAlignedWrites()
{
// Arrange
int bufferSize = Constants.KB;
int writeSize = 500;
int writeCount = 5;
Mock<PooledMemoryStream> mockBuffer = new Mock<PooledMemoryStream>(MockBehavior.Strict);
StorageWriteStreamImplementation stream = new StorageWriteStreamImplementation(
position: 0,
bufferSize: bufferSize,
progressHandler: null,
buffer: mockBuffer.Object);
mockBuffer.SetupSequence(r => r.WriteAsync(
It.IsAny<byte[]>(),
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask);
mockBuffer.SetupSequence(r => r.Position)
.Returns(0)
.Returns(500)
.Returns(1000)
.Returns(1000)
.Returns(476)
.Returns(976)
.Returns(976);
List<byte[]> data = new List<byte[]>();
for (int i = 0; i < writeCount; i++)
{
data.Add(GetRandomBuffer(writeSize));
}
// Act
for (int i = 0; i < writeCount; i++)
{
await stream.WriteAsync(data[i], 0, writeSize);
}
await stream.FlushAsync();
// Assert
Assert.AreEqual(3, stream.ApiCalls.Count);
Assert.AreEqual(s_append, stream.ApiCalls[0]);
Assert.AreEqual(s_append, stream.ApiCalls[1]);
Assert.AreEqual(s_flush, stream.ApiCalls[2]);
mockBuffer.Verify(r => r.Position, Times.Exactly(7));
mockBuffer.Verify(r => r.WriteAsync(data[0], 0, writeSize, default));
mockBuffer.Verify(r => r.WriteAsync(data[1], 0, writeSize, default));
mockBuffer.Verify(r => r.WriteAsync(data[2], 0, 24, default));
mockBuffer.Verify(r => r.WriteAsync(data[2], 24, 476, default));
mockBuffer.Verify(r => r.WriteAsync(data[3], 0, writeSize, default));
mockBuffer.Verify(r => r.WriteAsync(data[4], 0, 48, default));
mockBuffer.Verify(r => r.WriteAsync(data[4], 48, 452, default));
}
/// <summary>
/// In this test, we have a 1 KB buffer, and are making 2 writes of 2000 bytes.
/// We expect 3 Append calls, 1 flush call, and 5 calls to buffer.Write.
/// </summary>
[Test]
public async Task WritesLargerThanBufferNonAligned()
{
// Arrange
int bufferSize = Constants.KB;
int writeSize = 2000;
int writeCount = 2;
Mock<PooledMemoryStream> mockBuffer = new Mock<PooledMemoryStream>(MockBehavior.Strict);
StorageWriteStreamImplementation stream = new StorageWriteStreamImplementation(
position: 0,
bufferSize: bufferSize,
progressHandler: null,
buffer: mockBuffer.Object);
mockBuffer.SetupSequence(r => r.WriteAsync(
It.IsAny<byte[]>(),
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask)
.Returns(Task.CompletedTask);
mockBuffer.SetupSequence(r => r.Position)
.Returns(0)
.Returns(0)
.Returns(976)
.Returns(976);
List<byte[]> data = new List<byte[]>();
for (int i = 0; i < writeCount; i++)
{
data.Add(GetRandomBuffer(writeSize));
}
// Act
for (int i = 0; i < writeCount; i++)
{
await stream.WriteAsync(data[i], 0, writeSize);
}
await stream.FlushAsync();
// Assert
Assert.AreEqual(4, stream.ApiCalls.Count);
Assert.AreEqual(s_append, stream.ApiCalls[0]);
Assert.AreEqual(s_append, stream.ApiCalls[1]);
Assert.AreEqual(s_append, stream.ApiCalls[2]);
Assert.AreEqual(s_flush, stream.ApiCalls[3]);
mockBuffer.Verify(r => r.Position, Times.Exactly(4));
mockBuffer.Verify(r => r.WriteAsync(data[0], 0, bufferSize, default));
mockBuffer.Verify(r => r.WriteAsync(data[0], bufferSize, 976, default));
mockBuffer.Verify(r => r.WriteAsync(data[1], 0, 48, default));
mockBuffer.Verify(r => r.WriteAsync(data[1], 48, 1024, default));
mockBuffer.Verify(r => r.WriteAsync(data[1], 1072, 928, default));
}
internal class StorageWriteStreamImplementation : StorageWriteStream
{
public List<string> ApiCalls;
public PooledMemoryStream Buffer { get; private set; }
public StorageWriteStreamImplementation(
long position,
long bufferSize,
IProgress<long> progressHandler,
PooledMemoryStream buffer)
: base(
position,
bufferSize,
progressHandler,
hashingOptions: default,
buffer)
{
ApiCalls = new List<string>();
}
protected override Task AppendInternal(bool async, CancellationToken cancellationToken)
{
ApiCalls.Add(s_append);
return Task.CompletedTask;
}
protected override Task FlushInternal(bool async, CancellationToken cancellationToken)
{
ApiCalls.Add(s_flush);
return Task.CompletedTask;
}
protected override void ValidateBufferSize(long bufferSize)
{
}
}
private static byte[] GetRandomBuffer(long size)
{
Random random = new Random(Environment.TickCount);
var buffer = new byte[size];
random.NextBytes(buffer);
return buffer;
}
}
}
| 36.445614 | 100 | 0.517859 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/storage/Azure.Storage.Common/tests/StorageWriteStreamTests.cs | 10,389 | C# |
//
// THIS FILE IS AUTOGENERATED - DO NOT EDIT
// In order to make changes make sure to edit the t4 template file (*.tt)
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqStatistics.NaN
{
public static partial class EnumerableStats
{
/// <summary>
/// Computes the Range of a sequence of nullable float values.
/// </summary>
/// <param name="source">The sequence of elements.</param>
/// <returns>The Range.</returns>
public static float? RangeNaN(this IEnumerable<float?> source)
{
var values = source.AllValues();
if (values.Any())
return values.RangeNaN();
return null;
}
/// <summary>
/// Computes the Range of a sequence of float values.
/// </summary>
/// <param name="source">The sequence of elements.</param>
/// <returns>The Range.</returns>
public static float RangeNaN(this IEnumerable<float> source)
{
var range = source.MinMaxNaN();
return range.Max - range.Min;
}
/// <summary>
/// Computes the Range of a sequence of nullable float values that are obtained
/// by invoking a transform function on each element of the input sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">The sequence of elements.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The Range.</returns>
public static float? RangeNaN<TSource>(this IEnumerable<TSource> source, Func<TSource, float?> selector)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
return source.Select(selector).RangeNaN();
}
/// <summary>
/// Computes the Range of a sequence of float values that are obtained
/// by invoking a transform function on each element of the input sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">The sequence of elements.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The Range.</returns>
public static float RangeNaN<TSource>(this IEnumerable<TSource> source, Func<TSource, float> selector)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
return source.Select(selector).RangeNaN();
}
/// <summary>
/// Computes the Range of a sequence of nullable double values.
/// </summary>
/// <param name="source">The sequence of elements.</param>
/// <returns>The Range.</returns>
public static double? RangeNaN(this IEnumerable<double?> source)
{
var values = source.AllValues();
if (values.Any())
return values.RangeNaN();
return null;
}
/// <summary>
/// Computes the Range of a sequence of double values.
/// </summary>
/// <param name="source">The sequence of elements.</param>
/// <returns>The Range.</returns>
public static double RangeNaN(this IEnumerable<double> source)
{
var range = source.MinMaxNaN();
return range.Max - range.Min;
}
/// <summary>
/// Computes the Range of a sequence of nullable double values that are obtained
/// by invoking a transform function on each element of the input sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">The sequence of elements.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The Range.</returns>
public static double? RangeNaN<TSource>(this IEnumerable<TSource> source, Func<TSource, double?> selector)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
return source.Select(selector).RangeNaN();
}
/// <summary>
/// Computes the Range of a sequence of double values that are obtained
/// by invoking a transform function on each element of the input sequence.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">The sequence of elements.</param>
/// <param name="selector">A transform function to apply to each element.</param>
/// <returns>The Range.</returns>
public static double RangeNaN<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (selector == null)
throw new ArgumentNullException(nameof(selector));
return source.Select(selector).RangeNaN();
}
}
} | 39.546099 | 114 | 0.589132 | [
"Apache-2.0"
] | dkackman/LinqStatistics | src/LinqStatistics/NaN/EnumerableStatsRange.cs | 5,578 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Defines a page in Azure responses.
/// </summary>
/// <typeparam name="T">Type of the page content items</typeparam>
[JsonObject]
public class Page<T> : IPage<T>
{
/// <summary>
/// Gets the link to the next page.
/// </summary>
[JsonProperty("")]
public string NextPageLink { get; private set; }
[JsonProperty("value")]
private IList<T> Items{ get; set; }
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A an enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<T> GetEnumerator()
{
return Items == null ? System.Linq.Enumerable.Empty<T>().GetEnumerator() : Items.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A an enumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| 33.4 | 111 | 0.627109 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/Monitor/Management.Monitor/Generated/Monitor/Models/Page.cs | 1,837 | C# |
namespace stNet.CurlSharp
{
/// <summary>
/// Contains values used to specify the time condition when using
/// the <see cref="CurlOption.TimeCondition" /> option in a call
/// to <see cref="CurlEasy.SetOpt" />
/// </summary>
public enum CurlTimeCond
{
/// <summary>
/// Use no time condition.
/// </summary>
None = 0,
/// <summary>
/// The time condition is true if the resource has been modified
/// since the date/time passed in
/// <see cref="CurlOption.TimeValue" />.
/// </summary>
IfModSince = 1,
/// <summary>
/// True if the resource has not been modified since the date/time
/// passed in <see cref="CurlOption.TimeValue" />.
/// </summary>
IfUnmodSince = 2,
/// <summary>
/// True if the resource's last modification date/time equals that
/// passed in <see cref="CurlOption.TimeValue" />.
/// </summary>
LastMod = 3,
/// <summary>
/// Last entry in enumeration; do not use in application code.
/// </summary>
Last = 4
};
} | 31.025641 | 78 | 0.519008 | [
"MIT"
] | PetersSharp/stCoCServer | stCoCServer/stExtLib/stNet-dll/CurlSharp/Enums/CurlTimeCond.cs | 1,210 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace BezierSolution
{
[ExecuteInEditMode]
public class BezierSpline : MonoBehaviour
{
private static Material gizmoMaterial;
private Color gizmoColor = Color.white;
private float gizmoStep = 0.05f;
private List<BezierPoint> endPoints = new List<BezierPoint>();
public bool loop = false;
public bool drawGizmos = false;
public int Count { get { return endPoints.Count; } }
public float Length { get { return GetLengthApproximately( 0f, 1f ); } }
public BezierPoint this[int index]
{
get
{
if( index < Count )
return endPoints[index];
Debug.LogError( "Bezier index " + index + " is out of range: " + Count );
return null;
}
}
private void Awake()
{
Refresh();
}
#if UNITY_EDITOR
private void OnTransformChildrenChanged()
{
Refresh();
}
#endif
public void Initialize( int endPointsCount )
{
if( endPointsCount < 2 )
{
Debug.LogError( "Can't initialize spline with " + endPointsCount + " point(s). At least 2 points are needed" );
return;
}
Refresh();
for( int i = 0; i < endPoints.Count; i++ )
DestroyImmediate( endPoints[i].gameObject );
endPoints.Clear();
for( int i = 0; i < endPointsCount; i++ )
InsertNewPointAt( i );
Refresh();
}
public void Refresh()
{
endPoints.Clear();
GetComponentsInChildren( endPoints );
}
public BezierPoint InsertNewPointAt( int index )
{
if( index < 0 || index > endPoints.Count )
{
Debug.LogError( "Index " + index + " is out of range: [0," + endPoints.Count + "]" );
return null;
}
int prevCount = endPoints.Count;
BezierPoint point = new GameObject( "Point" ).AddComponent<BezierPoint>();
point.transform.SetParent( endPoints.Count == 0 ? transform : ( index == 0 ? endPoints[0].transform.parent : endPoints[index - 1].transform.parent ), false );
point.transform.SetSiblingIndex( index == 0 ? 0 : endPoints[index - 1].transform.GetSiblingIndex() + 1 );
if( endPoints.Count == prevCount ) // If spline is not automatically Refresh()'ed
endPoints.Insert( index, point );
return point;
}
public BezierPoint DuplicatePointAt( int index )
{
if( index < 0 || index >= endPoints.Count )
{
Debug.LogError( "Index " + index + " is out of range: [0," + ( endPoints.Count - 1 ) + "]" );
return null;
}
BezierPoint newPoint = InsertNewPointAt( index + 1 );
endPoints[index].CopyTo( newPoint );
return newPoint;
}
public void RemovePointAt( int index )
{
if( endPoints.Count <= 2 )
{
Debug.LogError( "Can't remove point: spline must consist of at least two points!" );
return;
}
if( index < 0 || index >= endPoints.Count )
{
Debug.LogError( "Index " + index + " is out of range: [0," + endPoints.Count + ")" );
return;
}
BezierPoint point = endPoints[index];
endPoints.RemoveAt( index );
DestroyImmediate( point.gameObject );
}
public void SwapPointsAt( int index1, int index2 )
{
if( index1 == index2 )
{
Debug.LogError( "Indices can't be equal to each other" );
return;
}
if( index1 < 0 || index1 >= endPoints.Count || index2 < 0 || index2 >= endPoints.Count )
{
Debug.LogError( "Indices must be in range [0," + ( endPoints.Count - 1 ) + "]" );
return;
}
BezierPoint point1 = endPoints[index1];
int point1SiblingIndex = point1.transform.GetSiblingIndex();
endPoints[index1] = endPoints[index2];
endPoints[index2] = point1;
point1.transform.SetSiblingIndex( endPoints[index1].transform.GetSiblingIndex() );
endPoints[index1].transform.SetSiblingIndex( point1SiblingIndex );
}
public int IndexOf( BezierPoint point )
{
return endPoints.IndexOf( point );
}
public void DrawGizmos( Color color, int smoothness = 4 )
{
drawGizmos = true;
gizmoColor = color;
gizmoStep = 1f / ( endPoints.Count * Mathf.Clamp( smoothness, 1, 30 ) );
}
public void HideGizmos()
{
drawGizmos = false;
}
public Vector3 GetPoint( float normalizedT )
{
if( normalizedT <= 0f )
return endPoints[0].position;
else if( normalizedT >= 1f )
{
if( loop )
return endPoints[0].position;
return endPoints[endPoints.Count - 1].position;
}
float t = normalizedT * ( loop ? endPoints.Count : ( endPoints.Count - 1 ) );
BezierPoint startPoint, endPoint;
int startIndex = (int) t;
int endIndex = startIndex + 1;
if( endIndex == endPoints.Count )
endIndex = 0;
startPoint = endPoints[startIndex];
endPoint = endPoints[endIndex];
float localT = t - startIndex;
float oneMinusLocalT = 1f - localT;
return oneMinusLocalT * oneMinusLocalT * oneMinusLocalT * startPoint.position +
3f * oneMinusLocalT * oneMinusLocalT * localT * startPoint.followingControlPointPosition +
3f * oneMinusLocalT * localT * localT * endPoint.precedingControlPointPosition +
localT * localT * localT * endPoint.position;
}
public Vector3 GetTangent( float normalizedT )
{
if( normalizedT <= 0f )
return 3f * ( endPoints[0].followingControlPointPosition - endPoints[0].position );
else if( normalizedT >= 1f )
{
if( loop )
return 3f * ( endPoints[0].position - endPoints[0].precedingControlPointPosition );
else
{
int index = endPoints.Count - 1;
return 3f * ( endPoints[index].position - endPoints[index].precedingControlPointPosition );
}
}
float t = normalizedT * ( loop ? endPoints.Count : ( endPoints.Count - 1 ) );
BezierPoint startPoint, endPoint;
int startIndex = (int) t;
int endIndex = startIndex + 1;
if( endIndex == endPoints.Count )
endIndex = 0;
startPoint = endPoints[startIndex];
endPoint = endPoints[endIndex];
float localT = t - startIndex;
float oneMinusLocalT = 1f - localT;
return 3f * oneMinusLocalT * oneMinusLocalT * ( startPoint.followingControlPointPosition - startPoint.position ) +
6f * oneMinusLocalT * localT * ( endPoint.precedingControlPointPosition - startPoint.followingControlPointPosition ) +
3f * localT * localT * ( endPoint.position - endPoint.precedingControlPointPosition );
}
public float GetLengthApproximately( float startNormalizedT, float endNormalizedT, float accuracy = 50f )
{
if( endNormalizedT < startNormalizedT )
{
float temp = startNormalizedT;
startNormalizedT = endNormalizedT;
endNormalizedT = temp;
}
if( startNormalizedT < 0f )
startNormalizedT = 0f;
if( endNormalizedT > 1f )
endNormalizedT = 1f;
float step = AccuracyToStepSize( accuracy ) * ( endNormalizedT - startNormalizedT );
float length = 0f;
Vector3 lastPoint = GetPoint( startNormalizedT );
for( float i = startNormalizedT + step; i < endNormalizedT; i += step )
{
Vector3 thisPoint = GetPoint( i );
length += Vector3.Distance( thisPoint, lastPoint );
lastPoint = thisPoint;
}
length += Vector3.Distance( lastPoint, GetPoint( endNormalizedT ) );
return length;
}
public Vector3 FindNearestPointTo( Vector3 worldPos, float accuracy = 100f )
{
float normalizedT;
return FindNearestPointTo( worldPos, out normalizedT, accuracy );
}
public Vector3 FindNearestPointTo( Vector3 worldPos, out float normalizedT, float accuracy = 100f )
{
Vector3 result = Vector3.zero;
normalizedT = -1f;
float step = AccuracyToStepSize( accuracy );
float minDistance = Mathf.Infinity;
for( float i = 0f; i < 1f; i += step )
{
Vector3 thisPoint = GetPoint( i );
float thisDistance = ( worldPos - thisPoint ).sqrMagnitude;
if( thisDistance < minDistance )
{
minDistance = thisDistance;
result = thisPoint;
normalizedT = i;
}
}
return result;
}
// Obsolete method, changed with a faster and more accurate variant
//public Vector3 MoveAlongSpline( ref float normalizedT, float deltaMovement,
// bool increasedAccuracy = false, int maximumNumberOfChecks = 20, float maximumError = 0.001f )
//{
// // Maybe that one is a better approach? https://www.geometrictools.com/Documentation/MovingAlongCurveSpecifiedSpeed.pdf
// if( Mathf.Approximately( deltaMovement, 0f ) )
// return GetPoint( normalizedT );
// if( maximumNumberOfChecks < 3 )
// maximumNumberOfChecks = 3;
// normalizedT = Mathf.Clamp01( normalizedT );
// Vector3 point = GetPoint( normalizedT );
// float deltaMovementSqr = deltaMovement * deltaMovement;
// bool isForwardDir = deltaMovement > 0;
// float bestNormalizedT;
// float maxNormalizedT, minNormalizedT;
// float error;
// Vector3 result;
// if( isForwardDir )
// {
// bestNormalizedT = ( 1f + normalizedT ) * 0.5f;
// maxNormalizedT = 1f;
// minNormalizedT = normalizedT;
// }
// else
// {
// bestNormalizedT = normalizedT * 0.5f;
// maxNormalizedT = normalizedT;
// minNormalizedT = 0f;
// }
// result = GetPoint( bestNormalizedT );
// if( !increasedAccuracy )
// {
// error = ( result - point ).sqrMagnitude - deltaMovementSqr;
// }
// else
// {
// float distance = GetLengthApproximately( normalizedT, bestNormalizedT, 10f );
// error = distance * distance - deltaMovementSqr;
// }
// if( !isForwardDir )
// error = -error;
// if( Mathf.Abs( error ) > maximumError )
// {
// for( int i = 0; i < maximumNumberOfChecks; i++ )
// {
// if( error > 0 )
// {
// maxNormalizedT = bestNormalizedT;
// bestNormalizedT = ( bestNormalizedT + minNormalizedT ) * 0.5f;
// }
// else
// {
// minNormalizedT = bestNormalizedT;
// bestNormalizedT = ( bestNormalizedT + maxNormalizedT ) * 0.5f;
// }
// result = GetPoint( bestNormalizedT );
// if( !increasedAccuracy )
// {
// error = ( result - point ).sqrMagnitude - deltaMovementSqr;
// }
// else
// {
// float distance = GetLengthApproximately( normalizedT, bestNormalizedT, 10f );
// error = distance * distance - deltaMovementSqr;
// }
// if( !isForwardDir )
// error = -error;
// if( Mathf.Abs( error ) <= maximumError )
// {
// break;
// }
// }
// }
// normalizedT = bestNormalizedT;
// return result;
//}
public Vector3 MoveAlongSpline( ref float normalizedT, float deltaMovement, int accuracy = 3 )
{
// Credit: https://gamedev.stackexchange.com/a/27138
float _1OverCount = 1f / endPoints.Count;
for( int i = 0; i < accuracy; i++ )
normalizedT += deltaMovement * _1OverCount / ( accuracy * GetTangent( normalizedT ).magnitude );
return GetPoint( normalizedT );
}
public void ConstructLinearPath()
{
for( int i = 0; i < endPoints.Count; i++ )
{
endPoints[i].handleMode = BezierPoint.HandleMode.Free;
if( i < endPoints.Count - 1 )
{
Vector3 midPoint = ( endPoints[i].position + endPoints[i + 1].position ) * 0.5f;
endPoints[i].followingControlPointPosition = midPoint;
endPoints[i + 1].precedingControlPointPosition = midPoint;
}
else
{
Vector3 midPoint = ( endPoints[i].position + endPoints[0].position ) * 0.5f;
endPoints[i].followingControlPointPosition = midPoint;
endPoints[0].precedingControlPointPosition = midPoint;
}
}
}
public void AutoConstructSpline()
{
// Credit: http://www.codeproject.com/Articles/31859/Draw-a-Smooth-Curve-through-a-Set-of-2D-Points-wit
for( int i = 0; i < endPoints.Count; i++ )
endPoints[i].handleMode = BezierPoint.HandleMode.Mirrored;
int n = endPoints.Count - 1;
if( n == 1 )
{
endPoints[0].followingControlPointPosition = ( 2 * endPoints[0].position + endPoints[1].position ) / 3f;
endPoints[1].precedingControlPointPosition = 2 * endPoints[0].followingControlPointPosition - endPoints[0].position;
return;
}
Vector3[] rhs;
if( loop )
rhs = new Vector3[n + 1];
else
rhs = new Vector3[n];
for( int i = 1; i < n - 1; i++ )
{
rhs[i] = 4 * endPoints[i].position + 2 * endPoints[i + 1].position;
}
rhs[0] = endPoints[0].position + 2 * endPoints[1].position;
if( !loop )
rhs[n - 1] = ( 8 * endPoints[n - 1].position + endPoints[n].position ) * 0.5f;
else
{
rhs[n - 1] = 4 * endPoints[n - 1].position + 2 * endPoints[n].position;
rhs[n] = ( 8 * endPoints[n].position + endPoints[0].position ) * 0.5f;
}
// Get first control points
Vector3[] controlPoints = GetFirstControlPoints( rhs );
for( int i = 0; i < n; i++ )
{
// First control point
endPoints[i].followingControlPointPosition = controlPoints[i];
if( loop )
{
endPoints[i + 1].precedingControlPointPosition = 2 * endPoints[i + 1].position - controlPoints[i + 1];
}
else
{
// Second control point
if( i < n - 1 )
endPoints[i + 1].precedingControlPointPosition = 2 * endPoints[i + 1].position - controlPoints[i + 1];
else
endPoints[i + 1].precedingControlPointPosition = ( endPoints[n].position + controlPoints[n - 1] ) * 0.5f;
}
}
if( loop )
{
float controlPointDistance = Vector3.Distance( endPoints[0].followingControlPointPosition, endPoints[0].position );
Vector3 direction = Vector3.Normalize( endPoints[n].position - endPoints[1].position );
endPoints[0].precedingControlPointPosition = endPoints[0].position + direction * controlPointDistance * 0.5f;
endPoints[0].followingControlPointLocalPosition = -endPoints[0].precedingControlPointLocalPosition;
}
}
private static Vector3[] GetFirstControlPoints( Vector3[] rhs )
{
// Credit: http://www.codeproject.com/Articles/31859/Draw-a-Smooth-Curve-through-a-Set-of-2D-Points-wit
int n = rhs.Length;
Vector3[] x = new Vector3[n]; // Solution vector.
float[] tmp = new float[n]; // Temp workspace.
float b = 2f;
x[0] = rhs[0] / b;
for( int i = 1; i < n; i++ ) // Decomposition and forward substitution.
{
float val = 1f / b;
tmp[i] = val;
b = ( i < n - 1 ? 4f : 3.5f ) - val;
x[i] = ( rhs[i] - x[i - 1] ) / b;
}
for( int i = 1; i < n; i++ )
{
x[n - i - 1] -= tmp[n - i] * x[n - i]; // Backsubstitution.
}
return x;
}
public void AutoConstructSpline2()
{
// Credit: http://stackoverflow.com/questions/3526940/how-to-create-a-cubic-bezier-curve-when-given-n-points-in-3d
for( int i = 0; i < endPoints.Count; i++ )
{
Vector3 pMinus1, p1, p2;
if( i == 0 )
{
if( loop )
pMinus1 = endPoints[endPoints.Count - 1].position;
else
pMinus1 = endPoints[0].position;
}
else
{
pMinus1 = endPoints[i - 1].position;
}
if( loop )
{
p1 = endPoints[( i + 1 ) % endPoints.Count].position;
p2 = endPoints[( i + 2 ) % endPoints.Count].position;
}
else
{
if( i < endPoints.Count - 2 )
{
p1 = endPoints[i + 1].position;
p2 = endPoints[i + 2].position;
}
else if( i == endPoints.Count - 2 )
{
p1 = endPoints[i + 1].position;
p2 = endPoints[i + 1].position;
}
else
{
p1 = endPoints[i].position;
p2 = endPoints[i].position;
}
}
endPoints[i].followingControlPointPosition = endPoints[i].position + ( p1 - pMinus1 ) / 6f;
endPoints[i].handleMode = BezierPoint.HandleMode.Mirrored;
if( i < endPoints.Count - 1 )
endPoints[i + 1].precedingControlPointPosition = p1 - ( p2 - endPoints[i].position ) / 6f;
else if( loop )
endPoints[0].precedingControlPointPosition = p1 - ( p2 - endPoints[i].position ) / 6f;
}
}
/*public void AutoConstructSpline3()
{
// Todo? http://www.math.ucla.edu/~baker/149.1.02w/handouts/dd_splines.pdf
}*/
private float AccuracyToStepSize( float accuracy )
{
if( accuracy <= 0f )
return 0.2f;
return Mathf.Clamp( 1f / accuracy, 0.001f, 0.2f );
}
// Renders the spline gizmo during gameplay
// Credit: https://docs.unity3d.com/ScriptReference/GL.html
private void OnRenderObject()
{
if( !drawGizmos || endPoints.Count < 2 )
return;
if( !gizmoMaterial )
{
Shader shader = Shader.Find( "Hidden/Internal-Colored" );
gizmoMaterial = new Material( shader ) { hideFlags = HideFlags.HideAndDontSave };
gizmoMaterial.SetInt( "_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha );
gizmoMaterial.SetInt( "_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha );
gizmoMaterial.SetInt( "_Cull", (int) UnityEngine.Rendering.CullMode.Off );
gizmoMaterial.SetInt( "_ZWrite", 0 );
}
gizmoMaterial.SetPass( 0 );
GL.Begin( GL.LINES );
GL.Color( gizmoColor );
Vector3 lastPos = endPoints[0].position;
for( float i = gizmoStep; i < 1f; i += gizmoStep )
{
GL.Vertex3( lastPos.x, lastPos.y, lastPos.z );
lastPos = GetPoint( i );
GL.Vertex3( lastPos.x, lastPos.y, lastPos.z );
}
GL.Vertex3( lastPos.x, lastPos.y, lastPos.z );
lastPos = GetPoint( 1f );
GL.Vertex3( lastPos.x, lastPos.y, lastPos.z );
GL.End();
}
#if UNITY_EDITOR
public void Reset()
{
for( int i = endPoints.Count - 1; i >= 0; i-- )
UnityEditor.Undo.DestroyObjectImmediate( endPoints[i].gameObject );
Initialize( 2 );
endPoints[0].localPosition = Vector3.back;
endPoints[1].localPosition = Vector3.forward;
UnityEditor.Undo.RegisterCreatedObjectUndo( endPoints[0].gameObject, "Initialize Spline" );
UnityEditor.Undo.RegisterCreatedObjectUndo( endPoints[1].gameObject, "Initialize Spline" );
UnityEditor.Selection.activeTransform = endPoints[0].transform;
}
#endif
}
} | 27.459502 | 161 | 0.640535 | [
"MIT"
] | BenPhilippe/SpaceX | Assets/Plugins/BezierSolution/BezierSpline.cs | 17,631 | C# |
using System;
using System.IO;
using System.Net;
namespace DotnetSpider.DataFlow.Parser.Formatters
{
/// <summary>
/// 下载内容
/// </summary>
public class Download : Formatter
{
private readonly WebClient _client = new WebClient();
/// <summary>
/// 执行下载操作
/// </summary>
/// <param name="value">下载的链接</param>
/// <returns>下载完成后的文件名</returns>
protected override string Handle(string value)
{
var filePath = value;
var name = Path.GetFileName(filePath);
var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", name);
_client.DownloadFile(file, filePath);
return file;
}
/// <summary>
/// 校验参数是否设置正确
/// </summary>
protected override void CheckArguments()
{
}
}
}
| 20.857143 | 82 | 0.668493 | [
"MIT"
] | RocChing/DotnetSpider | src/DotnetSpider/DataFlow/Parser/Formatters/Download.cs | 800 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LoginradiusCoreSdk.Models.Comment
{
/// <summary>
/// TODO: Update summary.
/// </summary>
public class LoginRadiusComment
{
public string CommentId
{
get;
set;
}
public string Published
{
get;
set;
}
public string Updated
{
get;
set;
}
public string Name
{
get;
set;
}
public string ProfileUrl
{
get;
set;
}
public string ImageUrl
{
get;
set;
}
public string UserId
{
get;
set;
}
public string Type
{
get;
set;
}
public string Comment
{
get;
set;
}
public List<ReplyList> ReplyList { get; set; }
}
public class ReplyList
{
public string ReplyId
{
get;
set;
}
public string ReplyUrl
{
get;
set;
}
}
}
| 15.731707 | 54 | 0.396124 | [
"MIT"
] | LoginRadius/dot-net-core-sdk | LoginradiusCoreSdk/src/src/LoginradiusCoreSdk/Models/Comment/LoginRadiusComment.cs | 1,292 | C# |
/*
* Copyright(c) 2022 nifanfa, This code is part of the Moos licensed under the MIT licence.
*/
using Kernel.Misc;
namespace Kernel.Driver
{
public static unsafe partial class LocalAPIC
{
private static int LAPIC_ID = 0x0020;
private static int LAPIC_VER = 0x0030;
private static int LAPIC_TPR = 0x0080;
private static int LAPIC_APR = 0x0090;
private static int LAPIC_PPR = 0x00a0;
private static int LAPIC_EOI = 0x00b0;
private static int LAPIC_RRD = 0x00c0;
private static int LAPIC_LDR = 0x00d0;
private static int LAPIC_DFR = 0x00e0;
private static int LAPIC_SVR = 0x00f0;
private static int LAPIC_ISR = 0x0100;
private static int LAPIC_TMR = 0x0180;
private static int LAPIC_IRR = 0x0200;
private static int LAPIC_ESR = 0x0280;
private static int LAPIC_ICRLO = 0x0300;
private static int LAPIC_ICRHI = 0x0310;
private static int LAPIC_TIMER = 0x0320;
private static int LAPIC_THERMAL = 0x0330;
private static int LAPIC_PERF = 0x0340;
private static int LAPIC_LINT0 = 0x0350;
private static int LAPIC_LINT1 = 0x0360;
private static int LAPIC_ERROR = 0x0370;
private static int LAPIC_TICR = 0x0380;
private static int LAPIC_TCCR = 0x0390;
private static int LAPIC_TDCR = 0x03e0;
private static int ICR_FIXED = 0x00000000;
private static int ICR_LOWEST = 0x00000100;
private static int ICR_SMI = 0x00000200;
private static int ICR_NMI = 0x00000400;
private static int ICR_INIT = 0x00000500;
private static int ICR_STARTUP = 0x00000600;
private static int ICR_PHYSICAL = 0x00000000;
private static int ICR_LOGICAL = 0x00000800;
private static int ICR_IDLE = 0x00000000;
private static int ICR_SEND_PENDING = 0x00001000;
private static int ICR_DEASSERT = 0x00000000;
private static int ICR_ASSERT = 0x00004000;
private static int ICR_EDGE = 0x00000000;
private static int ICR_LEVEL = 0x00008000;
private static int ICR_NO_SHORTHAND = 0x00000000;
private static int ICR_SELF = 0x00040000;
private static int ICR_ALL_INCLUDING_SELF = 0x00080000;
private static int ICR_ALL_EXCLUDING_SELF = 0x000c0000;
private static int ICR_DESTINATION_SHIFT = 24;
static uint In(uint reg)
{
return MMIO.In32((uint*)(ACPI.MADT->LocalAPICAddress + reg));
}
static void Out(uint reg, uint data)
{
MMIO.Out32((uint*)(ACPI.MADT->LocalAPICAddress + reg), data);
}
public static void EndOfInterrupt()
{
Out((uint)LAPIC_EOI, 0);
}
public static void Initialize()
{
PIC.Disable();
//Enable All Interrupts
Out((uint)LAPIC_TPR, 0);
// Logical Destination Mode
Out((uint)LAPIC_DFR, 0xffffffff); // Flat mode
Out((uint)LAPIC_LDR, 0 << 24); // All cpus use logical id 0
// Configure Spurious Interrupt Vector Register
Out((uint)LAPIC_SVR, 0x100 | 0xff);
Console.WriteLine("[Local APIC] Local APIC initialized");
}
public static uint GetId()
{
return In((uint)LAPIC_ID) >> 24;
}
public static void SendInit(uint apic_id)
{
Out((uint)LAPIC_ICRHI, apic_id << ICR_DESTINATION_SHIFT);
Out((uint)LAPIC_ICRLO, (uint)(ICR_INIT | ICR_PHYSICAL
| ICR_ASSERT | ICR_EDGE | ICR_NO_SHORTHAND));
while ((In((uint)LAPIC_ICRLO) & ICR_SEND_PENDING) != 0) ;
}
public static void SendStartup(uint apic_id, uint vector)
{
Out((uint)LAPIC_ICRHI, apic_id << ICR_DESTINATION_SHIFT);
Out((uint)LAPIC_ICRLO, vector | (uint)ICR_STARTUP
| (uint)ICR_PHYSICAL | (uint)ICR_ASSERT | (uint)ICR_EDGE | (uint)ICR_NO_SHORTHAND);
while ((In((uint)LAPIC_ICRLO) & ICR_SEND_PENDING) != 0) ;
}
}
} | 35.418803 | 99 | 0.623793 | [
"MIT"
] | nifanfa/OS-Sharp | Kernel/Driver/LocalAPIC.cs | 4,144 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace mattatz.ProceduralFlower {
[System.Serializable]
public enum PFPartType {
None,
Petal,
Stover
};
public class PFPart : MonoBehaviour {
const string PROPERTY_COLOR = "_Color2";
const string PROPERTY_BEND = "_Bend";
const string PROPERTY_T = "_T";
public PFPartType Type {
get {
return type;
}
}
MeshRenderer rnd {
get {
if(_renderer == null) {
_renderer = GetComponent<MeshRenderer>();
}
return _renderer;
}
}
MaterialPropertyBlock block {
get {
if(_block == null) {
_block = new MaterialPropertyBlock();
rnd.GetPropertyBlock(_block);
}
return _block;
}
}
MaterialPropertyBlock _block;
MeshRenderer _renderer;
public List<PFSegment> children = new List<PFSegment>();
public readonly float EPSILON = 0.1f;
[SerializeField] PFPartType type = PFPartType.None;
float multiplySpeed = 1f;
float speed = 1f;
bool animating = false;
float ticker = 0f;
void Update () {
if(animating) {
ticker += Time.deltaTime * multiplySpeed * speed;
Fade(ticker);
children.ForEach(anim => anim.Animate(speed, ticker));
if(ticker > 1f + EPSILON) {
animating = false;
}
}
}
public void SetType (PFPartType tp) {
type = tp;
}
public void Colorize (Color color) {
if(type != PFPartType.None) {
block.SetColor(PROPERTY_COLOR, color);
rnd.SetPropertyBlock(block);
}
}
public void Bend (float bend) {
if(type != PFPartType.None) {
block.SetFloat(PROPERTY_BEND, bend);
rnd.SetPropertyBlock(block);
}
}
public void Fade (float t) {
if(type != PFPartType.None) {
block.SetFloat(PROPERTY_T, t);
rnd.SetPropertyBlock(block);
}
}
public void SetSpeed (float m) {
multiplySpeed = m;
}
public void Add (PFPart part, float ratio) {
children.Add(new PFSegment(part, ratio));
}
public void Animate (float s = 1f) {
speed = s;
animating = true;
ticker = 0f;
}
[System.Serializable]
public class PFSegment {
public readonly PFPart part;
public readonly float ratio;
bool animating = false;
public PFSegment (PFPart p, float r) {
part = p;
ratio = r;
}
public void Animate (float speed, float r) {
if(!animating && r <= ratio) {
part.Animate(speed);
}
}
}
}
}
| 19.21374 | 59 | 0.612237 | [
"MIT"
] | U3DC/unity-procedural-flower | Assets/Packages/ProceduralFlower/Scripts/PFPart.cs | 2,519 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using com.ebay.developer;
//using Service1;
using eBay.Service.Call;
using eBay.Service.Core.Sdk;
using eBay.Service.Core.Soap;
using System.Configuration;
/// <summary>
/// Summary description for apic
/// </summary>
public class apic
{
public apic()
{
}
static ApiContext apiContext = null;
public ApiContext GetApiContext()
{
//ApiContext is a singleton,
if (apiContext != null)
{
return apiContext;
}
else
{
apiContext = new ApiContext();
//supply Api Server Url
apiContext.SoapApiServerUrl = ConfigurationManager.AppSettings["Environment.ApiServerUrl"];
//Supply user token
ApiCredential apiCredential = new ApiCredential();
apiCredential.eBayToken = ConfigurationManager.AppSettings["UserAccount.ApiToken"];
apiContext.ApiCredential = apiCredential;
//Specify site: here we use US site
apiContext.Site = eBay.Service.Core.Soap.SiteCodeType.US;
return apiContext;
} // else
} //GetApiContext
}
| 20.262295 | 103 | 0.631877 | [
"MIT"
] | aliostad/deep-learning-lang-detection | data/test/csharp/491c2a26e6c18a1bc778a04bb74293925dd0e039apic.cs | 1,238 | 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("03.Ferrari")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03.Ferrari")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6058e373-82d3-4a87-8673-2d8c8b6d7514")]
// 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.513514 | 84 | 0.745677 | [
"MIT"
] | AleksandarKostadinov/C-Sharp-OOP-Advanced | 01.InterfacesAndAbstraction-Exercise/03.Ferrari/Properties/AssemblyInfo.cs | 1,391 | 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 sagemaker-2017-07-24.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.SageMaker.Model
{
/// <summary>
/// Paginator for the ListModelBiasJobDefinitions operation
///</summary>
public interface IListModelBiasJobDefinitionsPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListModelBiasJobDefinitionsResponse> Responses { get; }
/// <summary>
/// Enumerable containing all of the JobDefinitionSummaries
/// </summary>
IPaginatedEnumerable<MonitoringJobDefinitionSummary> JobDefinitionSummaries { get; }
}
} | 35.052632 | 107 | 0.705706 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/_bcl45+netstandard/IListModelBiasJobDefinitionsPaginator.cs | 1,332 | C# |
using System.Threading.Tasks;
namespace OneInch.Api
{
public interface IApproveClient
{
Task<ApproveCallDataResponseDto> GetTransactionApproval(ApproveTransactionRequest request);
Task<ApproveSpenderResponseDto> GetApprovedSpender();
Task<TokenAllowance> GetAllowance(AllowanceRequest request);
}
} | 30.454545 | 99 | 0.767164 | [
"MIT"
] | 0xDelco/1inch-api-v4 | src/OneInch.Api/Client/Abstractions/IApproveClient.cs | 335 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancingv2-2015-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticLoadBalancingV2.Model
{
/// <summary>
/// Information about a path pattern condition.
/// </summary>
public partial class PathPatternConditionConfig
{
private List<string> _values = new List<string>();
/// <summary>
/// Gets and sets the property Values.
/// <para>
/// One or more path patterns to compare against the request URL. The maximum size of
/// each string is 128 characters. The comparison is case sensitive. The following wildcard
/// characters are supported: * (matches 0 or more characters) and ? (matches exactly
/// 1 character).
/// </para>
///
/// <para>
/// If you specify multiple strings, the condition is satisfied if one of them matches
/// the request URL. The path pattern is compared only to the path of the URL, not to
/// its query string. To compare against the query string, use <a>QueryStringConditionConfig</a>.
/// </para>
/// </summary>
public List<string> Values
{
get { return this._values; }
set { this._values = value; }
}
// Check to see if Values property is set
internal bool IsSetValues()
{
return this._values != null && this._values.Count > 0;
}
}
} | 34.484848 | 120 | 0.651142 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/ElasticLoadBalancingV2/Generated/Model/PathPatternConditionConfig.cs | 2,276 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Trinity;
using Trinity.Storage;
using Trinity.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace EchoOnConsole
{
public class EchoOnConsole
{
[DllImport("Kernel32.dll", SetLastError = true) ]
private static extern IntPtr GetStdHandle(int device);
[DllImport("Kernel32.dll", SetLastError = true) ]
private static extern bool SetStdHandle(int device, IntPtr handle);
private const int STD_INPUT_HANDLE = -10;
private const int STD_OUTPUT_HANDLE = -11;
private const int STD_ERROR_HANDLE = -12;
[Fact]
public void T1()
{
var stdout = GetStdHandle(STD_OUTPUT_HANDLE);
try
{
var filestream = new FileStream("tmp.txt", FileMode.OpenOrCreate);
SetStdHandle(STD_OUTPUT_HANDLE, filestream.Handle);
TrinityConfig.LogEchoOnConsole = true;
Global.Initialize();
filestream.Close();
Assert.NotEqual(0, File.ReadAllText("tmp.txt").Length);
}
finally
{
SetStdHandle(STD_OUTPUT_HANDLE, stdout);
}
}
}
}
| 30.543478 | 82 | 0.602847 | [
"MIT"
] | Bhaskers-Blu-Org2/GraphEngine | src/Trinity.Core.UnitTest/config/EchoOnConsole2/EchoOnConsole.cs | 1,405 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using AbilityUser;
using Verse.AI;
using Verse;
using UnityEngine;
namespace TorannMagic
{
public class Verb_SummonTotemHealing : Verb_UseAbility
{
bool validTarg;
//Used for non-unique abilities that can be used with shieldbelt
public override bool CanHitTargetFrom(IntVec3 root, LocalTargetInfo targ)
{
if (targ.Thing != null && targ.Thing == this.caster)
{
return this.verbProps.targetParams.canTargetSelf;
}
if (targ.IsValid && targ.CenterVector3.InBounds(base.CasterPawn.Map) && !targ.Cell.Fogged(base.CasterPawn.Map) && targ.Cell.Walkable(base.CasterPawn.Map))
{
if ((root - targ.Cell).LengthHorizontal < this.verbProps.range)
{
ShootLine shootLine;
validTarg = this.TryFindShootLineFromTo(root, targ, out shootLine);
}
else
{
validTarg = false;
}
}
else
{
validTarg = false;
}
return validTarg;
}
int pwrVal = 0;
int verVal = 0;
int effVal = 0;
Thing totem = null;
protected override bool TryCastShot()
{
Pawn caster = base.CasterPawn;
Map map = caster.Map;
IntVec3 cell = currentTarget.Cell;
CompAbilityUserMagic comp = caster.TryGetComp<CompAbilityUserMagic>();
pwrVal = TM_Calc.GetSkillPowerLevel(caster, TorannMagicDefOf.TM_Totems);
verVal = TM_Calc.GetSkillVersatilityLevel(caster, TorannMagicDefOf.TM_Totems);
effVal = TM_Calc.GetSkillEfficiencyLevel(caster, TorannMagicDefOf.TM_Totems);
IntVec3 shiftPos = TM_Calc.GetEmptyCellForNewBuilding(cell, map, 2f, true, 0, true);
if (shiftPos != null && (shiftPos.IsValid && shiftPos.Standable(map)))
{
AbilityUser.SpawnThings tempPod = new SpawnThings();
tempPod.def = TorannMagicDefOf.TM_HealingTotem;
tempPod.spawnCount = 1;
try
{
this.totem = TM_Action.SingleSpawnLoop(caster, tempPod, shiftPos, map, 2500 + (125 * verVal), true, false, caster.Faction, false, ThingDefOf.WoodLog);
this.totem.SetFaction(caster.Faction);
Building_TMTotem_Healing totemBuilding = this.totem as Building_TMTotem_Healing;
if (totemBuilding != null)
{
totemBuilding.pwrVal = pwrVal;
totemBuilding.verVal = verVal;
totemBuilding.arcanePwr = comp.arcaneDmg;
}
for (int i = 0; i < 3; i++)
{
Vector3 rndPos = this.totem.DrawPos;
rndPos.x += Rand.Range(-.5f, .5f);
rndPos.z += Rand.Range(-.5f, .5f);
TM_MoteMaker.ThrowGenericFleck(FleckDefOf.DustPuffThick, rndPos, map, Rand.Range(.6f, 1f), .1f, .05f, .05f, 0, 0, 0, Rand.Range(0, 360));
FleckMaker.ThrowSmoke(rndPos, map, Rand.Range(.8f, 1.2f));
}
}
catch
{
comp.Mana.CurLevel += comp.ActualManaCost(TorannMagicDefOf.TM_SummonTotemHealing);
Log.Message("TM_Exception".Translate(
caster.LabelShort,
"Earth Totem"
));
}
}
else
{
if (caster.IsColonist)
{
Messages.Message("InvalidSummon".Translate(), MessageTypeDefOf.RejectInput);
comp.Mana.GainNeed(comp.ActualManaCost(TorannMagicDefOf.TM_SummonTotemHealing));
}
}
return false;
}
}
}
| 39.682692 | 170 | 0.521686 | [
"BSD-3-Clause"
] | Sn1p3rr3c0n/RWoM | RimWorldOfMagic/RimWorldOfMagic/Verb_SummonTotemHealing.cs | 4,129 | C# |
using Should;
using Xunit;
namespace Cassette
{
public class NullPlaceholderTracker_Tests
{
[Fact]
public void InsertPlaceholderCallsFuncAndReturnsTheResult()
{
var tracker = new NullPlaceholderTracker();
var result = tracker.InsertPlaceholder(() => ("<p></p>"));
result.ShouldEqual("<p></p>");
}
[Fact]
public void ReplacePlaceholdersReturnsTheHtmlPassedToIt()
{
var tracker = new NullPlaceholderTracker();
var result = tracker.ReplacePlaceholders("<p></p>");
result.ShouldEqual("<p></p>");
}
}
}
| 25.96 | 70 | 0.57473 | [
"MIT"
] | WS-QA/cassette | src/Cassette.UnitTests/NullPlaceholderTracker.cs | 651 | C# |
#region Copyright � 2001-2003 Jean-Claude Manoli [jc@manoli.net]
/*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the author(s) be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#endregion
namespace Manoli.Utils.CSharpFormat
{
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
/// <summary>
/// Generates color-coded HTML 4.01 from C# source code.
/// </summary>
public class CSharpFormat : CLikeFormat
{
/// <summary>
/// The list of C# keywords.
/// </summary>
protected override string Keywords
{
get
{
return "abstract as base bool break byte case catch char "
+ "checked class const continue decimal default delegate do double else "
+ "enum event explicit extern false finally fixed float for foreach goto "
+ "if implicit in int interface internal is lock long namespace new null "
+ "object operator out override partial params private protected public readonly "
+ "ref return sbyte sealed short sizeof stackalloc static string struct "
+ "switch this throw true try typeof uint ulong unchecked unsafe ushort "
+ "using value virtual void volatile where while yield";
}
}
/// <summary>
/// The list of C# preprocessors.
/// </summary>
protected override string Preprocessors
{
get
{
return "#if #else #elif #endif #define #undef #warning "
+ "#error #line #region #endregion #pragma";
}
}
}
}
| 33.727273 | 86 | 0.703504 | [
"MIT"
] | ds112/hbase-on-windowns | Samples/CSharp/C# Analytics Samples/Web/SourceCodeTab/Formatter/CSharpFormat.cs | 2,228 | 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using Thrift.Protocol;
using Thrift.Transport;
using System.IO;
namespace Thrift.Server
{
internal abstract class TServer
{
//Attributes
protected TProcessorFactory processorFactory;
protected TServerTransport serverTransport;
protected TTransportFactory inputTransportFactory;
protected TTransportFactory outputTransportFactory;
protected TProtocolFactory inputProtocolFactory;
protected TProtocolFactory outputProtocolFactory;
protected TServerEventHandler serverEventHandler = null;
//Methods
public void setEventHandler(TServerEventHandler seh)
{
serverEventHandler = seh;
}
public TServerEventHandler getEventHandler()
{
return serverEventHandler;
}
//Log delegation
public delegate void LogDelegate(string str);
private LogDelegate _logDelegate;
protected LogDelegate logDelegate
{
get { return _logDelegate; }
set { _logDelegate = (value != null) ? value : DefaultLogDelegate; }
}
protected static void DefaultLogDelegate(string s)
{
Console.Error.WriteLine(s);
}
//Construction
public TServer(TProcessor processor,
TServerTransport serverTransport)
: this(processor, serverTransport,
new TTransportFactory(),
new TTransportFactory(),
new TBinaryProtocol.Factory(),
new TBinaryProtocol.Factory(),
DefaultLogDelegate)
{
}
public TServer(TProcessor processor,
TServerTransport serverTransport,
LogDelegate logDelegate)
: this(processor,
serverTransport,
new TTransportFactory(),
new TTransportFactory(),
new TBinaryProtocol.Factory(),
new TBinaryProtocol.Factory(),
logDelegate)
{
}
public TServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory)
: this(processor,
serverTransport,
transportFactory,
transportFactory,
new TBinaryProtocol.Factory(),
new TBinaryProtocol.Factory(),
DefaultLogDelegate)
{
}
public TServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(processor,
serverTransport,
transportFactory,
transportFactory,
protocolFactory,
protocolFactory,
DefaultLogDelegate)
{
}
public TServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
LogDelegate logDelegate)
{
this.processorFactory = new TSingletonProcessorFactory(processor);
this.serverTransport = serverTransport;
this.inputTransportFactory = inputTransportFactory;
this.outputTransportFactory = outputTransportFactory;
this.inputProtocolFactory = inputProtocolFactory;
this.outputProtocolFactory = outputProtocolFactory;
this.logDelegate = (logDelegate != null) ? logDelegate : DefaultLogDelegate;
}
public TServer(TProcessorFactory processorFactory,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
LogDelegate logDelegate)
{
this.processorFactory = processorFactory;
this.serverTransport = serverTransport;
this.inputTransportFactory = inputTransportFactory;
this.outputTransportFactory = outputTransportFactory;
this.inputProtocolFactory = inputProtocolFactory;
this.outputProtocolFactory = outputProtocolFactory;
this.logDelegate = (logDelegate != null) ? logDelegate : DefaultLogDelegate;
}
//Abstract Interface
public abstract void Serve();
public abstract void Stop();
}
}
| 36.25 | 88 | 0.641556 | [
"MIT"
] | oldmine/cassandra-thrift-client | Cassandra.ThriftClient/Internal/Thrift/Server/TServer.cs | 5,655 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraMovement : MonoBehaviour
{
private Vector3 origin;
private Vector3 difference;
private Vector3 resetCamera;
private bool drag = false;
private void Start()
{
resetCamera = Camera.main.transform.position;
}
private void LateUpdate()
{
if (Input.GetMouseButton(0))
{
difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition)) - Camera.main.transform.position;
if (drag == false)
{
drag = true;
origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else
{
drag = false;
}
if (drag)
{
Camera.main.transform.position = origin - difference;
}
if (Input.GetMouseButton(1))
{
Camera.main.transform.position = resetCamera;
}
}
}
| 22.311111 | 112 | 0.564741 | [
"Apache-2.0"
] | Hungerarray/1000-Steps-Simulator | Assets/cameraMovement.cs | 1,004 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace LightningBug.Polly.SimpleWebAppExample
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 25.36 | 76 | 0.70347 | [
"Apache-2.0"
] | jasondentler/lightning-bug | src/examples/polly/LightningBug.Polly.SimpleWebAppExample/Program.cs | 636 | C# |
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace src.Models
{
public class CreateModel
{
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
public class RoleEditModel
{
public IdentityRole Role { get; set; }
public IEnumerable<ApplicationUser> Members { get; set; }
public IEnumerable<ApplicationUser> NonMembers { get; set; }
}
public class RoleModificationModel
{
[Required]
public string RoleName { get; set; }
public string RoleId { get; set; }
public string[] IdsToAdd { get; set; }
public string[] IdsToDelete { get; set; }
}
}
| 20.611111 | 62 | 0.708895 | [
"MIT"
] | alexcosta97/web-apps-project | src/Models/UserViewModels.cs | 742 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.TestClient.PublishTestResults;
using Microsoft.TeamFoundation.TestManagement.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.TeamFoundation.Core.WebApi;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.Agent.Worker.TestResults.Utils;
namespace Microsoft.VisualStudio.Services.Agent.Worker.TestResults
{
[ServiceLocator(Default = typeof(TestDataPublisher))]
public interface ITestDataPublisher : IAgentService
{
void InitializePublisher(IExecutionContext executionContext, string projectName, VssConnection connection, string testRunner);
Task<bool> PublishAsync(TestRunContext runContext, List<string> testResultFiles, PublishOptions publishOptions, CancellationToken cancellationToken = default(CancellationToken));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "CommandTraceListener")]
public class TestDataPublisher : AgentService, ITestDataPublisher
{
private IExecutionContext _executionContext;
private string _projectName;
private ITestRunPublisher _testRunPublisher;
private ITestLogStore _testLogStore;
private IParser _parser;
private VssConnection _connection;
private IFeatureFlagService _featureFlagService;
private string _testRunner;
private bool _calculateTestRunSummary;
public void InitializePublisher(IExecutionContext context, string projectName, VssConnection connection, string testRunner)
{
Trace.Entering();
_executionContext = context;
_projectName = projectName;
_connection = connection;
_testRunner = testRunner;
_testRunPublisher = new TestRunPublisher(connection, new CommandTraceListener(context));
_testLogStore = new TestLogStore(connection, new CommandTraceListener(context));
var extensionManager = HostContext.GetService<IExtensionManager>();
_featureFlagService = HostContext.GetService<IFeatureFlagService>();
_parser = (extensionManager.GetExtensions<IParser>()).FirstOrDefault(x => _testRunner.Equals(x.Name, StringComparison.OrdinalIgnoreCase));
Trace.Leaving();
}
public async Task<bool> PublishAsync(TestRunContext runContext, List<string> testResultFiles, PublishOptions publishOptions, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
TestDataProvider testDataProvider = ParseTestResultsFile(runContext, testResultFiles);
var publishTasks = new List<Task>();
if (testDataProvider != null){
var testRunData = testDataProvider.GetTestRunData();
//publishing run level attachment
publishTasks.Add(Task.Run(() => _testRunPublisher.PublishTestRunDataAsync(runContext, _projectName, testRunData, publishOptions, cancellationToken)));
//publishing build level attachment
publishTasks.Add(Task.Run(() => UploadBuildDataAttachment(runContext, testDataProvider.GetBuildData(), cancellationToken)));
await Task.WhenAll(publishTasks);
_calculateTestRunSummary = _featureFlagService.GetFeatureFlagState(TestResultsConstants.CalculateTestRunSummaryFeatureFlag, TestResultsConstants.TFSServiceInstanceGuid);
var runOutcome = GetTestRunOutcome(_executionContext, testRunData, out TestRunSummary testRunSummary);
// Storing testrun summary in environment variable, which will be read by PublishPipelineMetadataTask and publish to evidence store.
if(_calculateTestRunSummary)
{
TestResultUtils.StoreTestRunSummaryInEnvVar(_executionContext, testRunSummary, _testRunner, "PublishTestResults");
}
return runOutcome;
}
return false;
}
catch (Exception ex)
{
_executionContext.Warning("Failed to publish test run data: "+ ex.ToString());
}
return false;
}
private TestDataProvider ParseTestResultsFile(TestRunContext runContext, List<string> testResultFiles)
{
if (_parser == null)
{
throw new ArgumentException("Unknown test runner");
}
return _parser.ParseTestResultFiles(_executionContext, runContext, testResultFiles);
}
private bool GetTestRunOutcome(IExecutionContext executionContext, IList<TestRunData> testRunDataList, out TestRunSummary testRunSummary)
{
bool anyFailedTests = false;
testRunSummary = new TestRunSummary();
foreach (var testRunData in testRunDataList)
{
foreach (var testCaseResult in testRunData.TestResults)
{
testRunSummary.Total += 1;
Enum.TryParse(testCaseResult.Outcome, out TestOutcome outcome);
switch(outcome)
{
case TestOutcome.Failed:
case TestOutcome.Aborted:
testRunSummary.Failed += 1;
anyFailedTests = true;
break;
case TestOutcome.Passed:
testRunSummary.Passed += 1;
break;
case TestOutcome.Inconclusive:
testRunSummary.Skipped += 1;
break;
default: break;
}
if(!_calculateTestRunSummary && anyFailedTests)
{
return anyFailedTests;
}
}
}
return anyFailedTests;
}
private async Task UploadRunDataAttachment(TestRunContext runContext, List<TestRunData> testRunData, PublishOptions publishOptions, CancellationToken cancellationToken = default(CancellationToken))
{
await _testRunPublisher.PublishTestRunDataAsync(runContext, _projectName, testRunData, publishOptions, cancellationToken);
}
private async Task UploadBuildDataAttachment(TestRunContext runContext, List<BuildData> buildDataList, CancellationToken cancellationToken = default(CancellationToken))
{
_executionContext.Debug("Uploading build level attachements individually");
Guid projectId = await GetProjectId(_projectName);
var attachFilesTasks = new List<Task>();
HashSet<BuildAttachment> attachments = new HashSet<BuildAttachment>(new BuildAttachmentComparer());
foreach (var buildData in buildDataList)
{
attachFilesTasks.AddRange(buildData.BuildAttachments
.Select(
async attachment =>
{
if (attachments.Contains(attachment))
{
_executionContext.Debug($"Skipping upload of {attachment.Filename} as it was already uploaded.");
await Task.Yield();
}
else
{
attachments.Add(attachment);
await UploadTestBuildLog(projectId, attachment, runContext, cancellationToken);
}
})
);
}
_executionContext.Debug($"Total build level attachments: {attachFilesTasks.Count}.");
await Task.WhenAll(attachFilesTasks);
}
private async Task UploadTestBuildLog(Guid projectId, BuildAttachment buildAttachment, TestRunContext runContext, CancellationToken cancellationToken)
{
await _testLogStore.UploadTestBuildLogAsync(projectId, runContext.BuildId, buildAttachment.TestLogType, buildAttachment.Filename, buildAttachment.Metadata, null, buildAttachment.AllowDuplicateUploads, buildAttachment.TestLogCompressionType, cancellationToken);
}
private async Task<Guid> GetProjectId(string projectName)
{
var _projectClient = _connection.GetClient<ProjectHttpClient>();
TeamProject proj = null;
try
{
proj = await _projectClient.GetProject(projectName);
}
catch (Exception ex)
{
_executionContext.Warning("Get project failed" + projectName + " , exception: " + ex);
}
return proj.Id;
}
}
}
| 45.545 | 272 | 0.626853 | [
"MIT"
] | lukeenterprise/azure-pipelines-agent | src/Agent.Worker/TestResults/TestDataPublisher.cs | 9,109 | C# |
/*
* Copyright(c) 2017 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace Tizen.NUI
{
internal class SWIGTYPE_p_Dali__RenderSurface
{
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
internal SWIGTYPE_p_Dali__RenderSurface(global::System.IntPtr cPtr)
{
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
protected SWIGTYPE_p_Dali__RenderSurface()
{
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_Dali__RenderSurface obj)
{
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
}
}
| 36.435897 | 137 | 0.707248 | [
"Apache-2.0",
"MIT"
] | AchoWang/TizenFX | src/Tizen.NUI/src/internal/NativeBinding/SWIGTYPE_p_Dali__RenderSurface.cs | 1,421 | C# |
// <auto-generated />
namespace Iauq.Data.Migrations
{
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
public sealed partial class PollBodyRenamedToDescription : IMigrationMetadata
{
string IMigrationMetadata.Id
{
get { return "201206200459059_PollBodyRenamedToDescription"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return "H4sIAAAAAAAEAO0dy3LcRu6+VfsPU3Pa3apoZHnL5aSkpBQp3lUltlWWkquKmmmNWOGQE5JjS9+2h/2k/YVls/noB9AvvmYcXWQPm0QD3QAajUYD//vPf09/eNpEs88kzcIkPpu/Ojqez0i8TFZhvD6b7/KHb97Of/j+r385/Wm1eZr9Vr93Qt8rvoyzs/ljnm+/Wyyy5SPZBNnRJlymSZY85EfLZLMIVsni5Pj47eLV8YIUIOYFrNns9NMuzsMNKX8UPy+SeEm2+S6I3icrEmXV86LlpoQ6+xBsSLYNluRsfhXs/ji6DPJgPjuPwqBA4IZED47YHH9LsZk3/ZQ4bLYRebp93pKyOwo3eU/yYEX74t4s3r1Oky1J8+f2xdswj8h8Rr8ufudpMXzz2bvwiax+IfE6fzybPwRRVrzxPniqn7w+Lgbx1zgsRrv4KE93RfOHXRQF91Hze2Hq+Cbarafo92fy/CVJV5lj3yd99H1JsmUabvOCFR27f+PY/emCYwv++U8F/+bPHLNcBDlZJ+mzxCnFMAkPOHo+kYfq26uVQvRC/lAeBvoNI/0qzl+f8GRUZG/ffHeTJyn5F4lJWmC3ug7ynKQx/ZaU6FdC8932jZ3cfLs4PqFyswjiOMkDNv762boMs20UPH9MVyTlEH71BkBYD8lHwvTcZtXtL0G83gVrYh5vPZzrIC0GXQMF5P0PwedwXQ40gtZ89olE5QvZY7hluvCo5sW79q13abL5lEQcozaNdzfJLl3SoU2wN26DdE1ye+wKfZ4X1GYwdqzxrpEYHjmprem5wU1+oUbeFjU2D/phq98BBo014UNWtTsP2GMYrZDhssdKGSwEa1usKBQYKdoCTqDQoCAktkLonC5azarVtw1rv+hbHk36d3wleZUlF8XXrh07d4vLD+OpEGFXR4WIypGiMntRiA3U9q0WO6VR0T3qG5D2sRasCsqLXEkcfr27j8LskTT4/pgUwx/EzsJy85h8+UCygpB2vrtBvMr+neRdgdCvr+K8m5HWn7lXDXex0SO34fL3jIP25p/O0D4VYGoIl0kB2l3HXRci9ltIvmTd7MCJzNjz+yxPg2Xu2POr4877tR+T1bNjr8V/u9J7G6xdt6b6Xm1IbbwFdcdUu/NeBFcq6oVnms2HzEK7/DFJnVExrdnP3TcJijWO7SL62CRUsAFrXGhBkfLcIbDRB1H6NSMpaDsIDYpVI7Y6WzSaHYvtEGGbO8/tykWy2Zh3nc1LAENVbThD1S90srDowL+YVwKadEg8ti6v3bcQiqRnGfVjuq6Lb7p2fBNErotx9wXqp00QRq6knrztb5+GexRKbVQ1SxqsfKrIJNfUq3vKUpuC6Gh3YN6qqwKt6i2hAcNIo7G0602cfSEpjBBru2P/UEO/RUlqUlS83N7JB0RBvijSPfD/eNupfsahpfdRFgjYN2mLERUnT9UFWl6iVvN01ZTC/SICkjfkfLtNk8/dPTXV+Pbkg7hOsjAPPxPqi+joRPgQFPzUDygff8Sr7hrDwytwovdFjLcRrtjCYy8sAfr4pRCT/nSmdtdaogxuyfgWYOcjNHvaNfqNq8mwQTauktlji1I56N23iOjBpC9e2g215eypSIGT67XYMJPtZa2RglEisiz6vsrJpqs2qG3ijtrpanu+WqUkG8H9ifIyPywwRz8m4ZLQ5rtmo8FxtdKqcrb6iqvAtduXblscWWViWyA/E6+h80Xyelg7ZeOHPLk6YXx2Sz5rUTnvd3TiAdFgzxGhqBr9xAFZgFzFVTEjcInuIBYvIjGASExzPukf0tndK3qVvd9FecgWLQ4B622jh3xfJ1F0x7hYkCX+uSLfQqOrfFeqxFfXwBItKSIvWaZUvUiy7MJY0v1951CTPEhzBuo23BicGFYHCPGqT3B/BmWj2fBV0u+rHmSRBHWH3/IapMkuIy9i+ZUFs/szfg+BQL+E8e+/pq7HjwavH3RlA2by8yxLlmE5z+Ix4B1ydaPQdTNTwEkb5lOHTc5KW2IbhcsCh7P5P5RR0YBt1nsObHPKIcJ9pcAtJJBQL08YRAVgGu0VxrkqrmG8DLdBZEBB+s5S0OngNz3ILZdkS2Iqq4ZBtemaP29SUWh6krSQaYROFxyP2LFO5ZEzzbDsXO2FbWSfnxHo8dFRz2wjojAi04gDatNx6/mfhGHEI0tsapHzy3ZmyxNvB15BrmOMpl/A/kfgE3AgD0KzcIfJ2KRCQTHtjJbRZQ4sAp1TOzGcK3FNbI0WIzXQRk+iyrAYQHuFqQ6blxCA9IwgBCDZNv22kb4TLa7CcRe+DsInl/y0svgIp8UVPlAzAu1zcYVQGGVxhQb0ABZX8RzZoAXkaLnOakU+EPbgvy5qRaRnPLUikm21tvJxE5MwiuBWwaYV9rG0s1r6KxU2kcn5GF+SiORkdl76lKllkS2DlbpLLrarKytUIAZjxyDD8Bc0DiOwF0SzTbfN6cc0axbvQ0cXF9ChbprOgXgLPkmUkWEn+IPwFzQaY6xyAN2Hwl/CCax+YuHjWJvpHZTf4KCOFq0qymhIjoNGZjS+g+i36VwONJqECeWgGGyq0QgZ93nGgQLMAxlw/dnlCAIjsA4ynlZbOS6obFJPqdE8xy/hGffpOiMdD9wcy07HCBvRXepjrU+73qk5MbAJ1iTIaGe4zfthoR10sL2dRy4io2QrQZkbz+VkdvFq3SB4ThTzoPblB8FwGENwsIG16ZtPGTaNzpVSRhlnWeNC68I8GicaArZHLxqMxJi8s+d+NHZMTrVX8QVJa+KD3R+X96VOe1I5h35xQ3KRz8qsS+2huzLFCqOIUGpxgYC0KsYApL2wqyJS62cDiOqCn/I9syoNH1fX/5SP2fmJEfn6wgmAfGWaGEA0YbkKhNrSNuHQbE9ANLjdohUgHIgRAHUAQZ8zv5up9ypyCebIKqpJBsIJiMJR3D1T7jUsS4kstRYxJA0FPBMr4m8RNcID4gRT3qKLxDoMRH37CB8GaLkBcZfWG98hkNYXCzAe5EuXjVXqNUf7Atbw4T6HdKVDNITDx/lDTTx/r1klGzuoFhAGjqo5bCuNqyEYOJw2DZgvoS3LILTCOxEVXWUf4k6xst0YhrXle4WQZONHsZJIgoexAt71IqeVbPD41QKM/7TX8NBphxwX0JxJfgufaZd8FMPQLQYXq2Tjp2QCyuA5GYdxtY5riAaPt3iaaxy7c7pwxQHgc/T4xnyAY0bYfO6iwKgw7Ylw8eYWRj5+umB7vmBHhu2xAAetwb3zgCgXO9XR0Lq5rRzdZsytXNsmDdLBmNOpPb3L1s5p623VjqMCgZS76jgYfJCWXkiOAG6nqxkK3Ok4kBWgJkcGeELvk7T0SlpZqpaOSJtx7TIaGqNI516zcrB1GAeNZeRj+9e3JRo3UNN2umC1V6oHtBIGWKTl9H2w3YbxmivaUj2Z3bCKLRff3LiXZ9kwGIulIHWy06rpKU/SggGkViomK/IuTDOawye4D+jdkovVRnnNyulV96X4vtRZqx0P9Sf0/617raxec4TtGNvxe1eQRBVeSR1RZxr4dEYr5gRRkAIXrC6SaLeJcRcn/rV474mHI7bYQ6zuP/Ggqkf2MHg3Ow9I537HobWuVx4W7pClEiHNk+KyVRhBkkqZtawYr1V2fnyHKXALvsM/HYbv6F/xe/bEHkJTmEBAon64N3OqMTCsVAmUst9qRtEvh5lQIYu+OCVcgz08KJU+DxZqd8G2TKsv4lk+clB0dVZ9QdXVD6dUwWqCfUHxKa32kFmyfR4ae+KijJtc+6I2bh6Pu9S02fN5MO1Te0gs7x0PhT1xoKfMbC+QUz4BIVTVy7R56mVtgpa90+PVFsHjcash3bXNEKIaoKzAHQaTtTqCbGvXYWDbNxxBCzesMejCS+C8LaSJs+YO/v4a373uXhsOzd0oQiWouVIkSBB60WiypZg5WvzWYTWxe/mxaRGGPxtmBW4TrfMw2qcuvFFnThd5o37qsIqXqdCFdbt8Yg+hymvOg6ge7Q1fYSdlNnxVBhG48xX82b6a6n6aazKDHXWN2hnsQOJmqzlFvxzKYG9zKYt2cPvcYYqVfMrCRCutDspIzK0saCSxyYWlhSTLIm8LTeMao91NyP6WdeFKHzCZ2OKOwWuCjnlYaCTyZOKPH5LZSD+USbf83CT82IfDyL585URYoA3XUXCo/IUEwRTUXFTQUNgmuxUIbR/vDc/wB6KeqwaSC9aKd3QfD8M/rrKM6swySaugMssnezaz3WbVe0YPbjZ7WAHRTbZ5Y41YOXICUNHWkVv3hvNYiI0f36lpN8uPTVwHfzaY9VmlwZRsz+qpw1oGJsIUVjTwDYctKJAZU9iPAu2HITVTadUmktv3fBXKYVkCMJ+vYp/+mc5X+9ayTf5H4bC2fjg+34kxEaoXsA59xjx9dTvkzoNcLzSaA/DGieHR6ihY8RsFBF8b4jp1wge9L2WFD4Xhho8co+I8ZUBIl+74m3vN8lAUGC806stz2Bp4PcwlGkbmiZszSkW/q7C8lXiV0YStTXZXS4rNHKEEL8mvNCqketL8boKXqsAhIaKpHBEan1SORFYFMcmRROyV+awg/3O4olFEN89Zsb2qDtH+iC6isAwgq194H8ThA8ny2+R3EpeJbd/OZ+dRGGQsrswpRqrJXpxlK2GdgpI5g1knR0jmHFLyjWmbeygxn22CKCp765KHOf4cpMvHIFWzLjtC5SOQuJHoWKtMgmGf+VjhCORe+aFyBDtp6HkOmyAhHVwDVIdCjsCKc7DzIQTzsH7uQ3f+h4J3/KFVkTv+AJqgnY4qp1f9pYbp1ASufcCxOB0G4iFKAh+l1YTo+Gu+YbRyG66jAczy3LsltudrWdZA/7YJnv7uTngZyWOAZIMSEHajIfq1O81qDM5w8NtgHHuOcO0DqIwAdvPGvRu1OPIo1gAgAE20jT8agr3et12iBsIc7BrYRtTo5MK9PFcbX6NTYu4FSVjETQ+ap4q70WF38rYvu0l1sxwswwxixPqonv2vPj6Q0SpXDfcxErGK4Z72GFgy3AcQWDB8GNPslQefQhYUUAVo/CUTKPXtM2pSZcYehXCqqsyDyCBcTdlnwNVayh6Tr1RSdlgYD6LA7yCT6MzrgJLhyvJ6roV7X0l2b8d+kL23ZnvlZWViJVvNa/aelyUdyrYRyol6eeM0pURV66ZbLVE/ePvIuQdQcfPPekhj6/Hx8QhKpS6tTNqOfhPfrTAaOaC+Ch/qm3mt7sJ/Uap77mo+d8m13GZHYVg4pkBWU3l45tn1yoarufRvo09mPvlvv85cyf5pjFVY7NR/PC5wmpmeuKCk0aa/iWuI2RcDdmEEi8oEIxYiHHX+0ZwUaleTF910K+frXWtXgaQqgGHn32FO+pn+Q5F++8KknSoGji/yyJX0ScV94vKi7qVF+iglMv7Uj2rzOUy/Ich1b4px97bQsxoAHBCLosqHsMQjaQn2cn13qSjsXe5XgQSs78NWmsLSCgwg8C2Bh7O+W1QI7ri+WzPQwa3v9qw1fZ1f16Jz3YvMjT3vo5ry9lN/gEVSp62KWlfn4XAYqQTqeIUrv74Cp1YLhcFEGHvmx1opHOZ8+uKk9lW7py7U7aCqelUV45ZGPoBFBq+OIlU2EWaLPRiRXyz4tSc+QRJJDMQlB8Ahhlvd7huOQdikOTSW+x/QOzHWGoRdwQf7wu/Oj8sr0PVsVy/SV8Qr1vM3Jq/geQ1GKs+qFrSQ56xKYyC53rQFWtlV9rP56j4pZphFVWiqich9tB5xpY+2CeoDr9uikFHvyVUq6haQCKxKjgyf6V0FOHsMQYbrMclgmXgoYNljCCxc0VAdjcq1AIxG1QKPBlI/SYZf70MU8HUDBB0r0aUgz9mtKv5cI0iCpjga3JGmDi3egRk4s+cU0OwxBBishoeWr9VWr4XFtal7a8HqCF+2TSjL3yYwi45TWUrWNGJVElUrQ4c53Jdoieo9KRtlhSz4JTt4GIjUngsj+xMrLgpC7p7+yOyv7LENotB36mT2RmSvlW+VgoUTzt5gBf48VM+ghIpn2R3KU/vLIb+atInn+5DAvssTQ+UkDXPHneOav526CLGrBFoPyt5UGvXQoYMSOWR5XaSerpZc0XTns4Z3J7bX0rnu7Dokab3WhwbmTc+irjM+bc1vpci3BXEWQ+KrOwVHK6Y/dTk2OzGlvJsSM4D2SmJd8lVLIpzj0XWxHoREh1KzalbG08WnXfH1hl3nOb0kWbhuQdBckzG7CdoCrd+5ih+S2pMnYVS/giQGOk/z8CFY5kVzIRZZGK/ns9+CaEdompN7srqKP+7y7S4vSCab+0iwkqhHUNd/WU9XxPn0Y3kbLeuDhALNsCCBfIx/3IXRqsH7HXBZCgFBXY3VlUA6lzm9Grh+biB9SGJLQNXwNR7SW7LZRjQRxcf4JqC3UjHczGMojtjpZRis02DDjyB7UgcZBLSqWttF0QH/Rdtf8bNg19Xm6fv/A4s5rfgk3wAA"; }
}
}
}
| 283.88 | 6,538 | 0.934057 | [
"MIT"
] | m-sadegh-sh/Iauq | src/Iauq.Data/Migrations/201206200459059_PollBodyRenamedToDescription.Designer.cs | 7,097 | C# |
using DwLang.Language.Lexer;
namespace DwLang.Language.Parser
{
public class DwLangParserException : DwLangException
{
public DwLangParserException(Token token, string message) : base(message)
{
Token = token;
}
public Token Token { get; }
}
}
| 20.2 | 81 | 0.627063 | [
"MIT"
] | miroiu/dw-lang | DwLang.Language/Parser/DwLangParserException.cs | 305 | C# |
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
using Microsoft.AspNetCore.Components;
namespace BootstrapBlazor.Components;
/// <summary>
///
/// </summary>
public partial class IconDialog : IAsyncDisposable
{
[Inject]
[NotNull]
private ClipboardService? ClipboardService { get; set; }
/// <summary>
///
/// </summary>
[Parameter]
public string? IconName { get; set; }
[NotNull]
private Button? ButtonIcon { get; set; }
[NotNull]
private Button? ButtonFullIcon { get; set; }
private string IconFullName => $"<i class=\"{IconName}\" aria-hidden=\"true\"></i>";
private CancellationTokenSource CopyIconTokenSource { get; } = new();
private CancellationTokenSource CopyFullIconTokenSource { get; } = new();
private Task OnClickCopyIcon() => ClipboardService.Copy(IconName, async () =>
{
await ButtonIcon.ShowTooltip("拷贝成功");
try
{
await Task.Delay(1000, CopyIconTokenSource.Token);
await ButtonIcon.RemoveTooltip();
}
catch (TaskCanceledException)
{
}
});
private Task OnClickCopyFullIcon() => ClipboardService.Copy(IconFullName, async () =>
{
await ButtonFullIcon.ShowTooltip("拷贝成功");
try
{
await Task.Delay(1000, CopyFullIconTokenSource.Token);
await ButtonFullIcon.RemoveTooltip();
}
catch (TaskCanceledException)
{
}
});
private async Task OnClickClose()
{
if (OnClose != null)
{
await OnClose();
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public async ValueTask DisposeAsync()
{
if (CopyIconTokenSource.IsCancellationRequested)
{
await ButtonIcon.RemoveTooltip();
}
CopyIconTokenSource.Dispose();
if (CopyFullIconTokenSource.IsCancellationRequested)
{
await ButtonFullIcon.RemoveTooltip();
}
CopyFullIconTokenSource.Dispose();
GC.SuppressFinalize(this);
}
}
| 24.870968 | 111 | 0.604842 | [
"Apache-2.0"
] | ScriptBox99/BootstrapBlazor | src/BootstrapBlazor/Components/FAIcons/IconDialog.razor.cs | 2,331 | C# |
using Attest.Testing.Core;
using Solid.Bootstrapping;
using Solid.Core;
using Solid.Practices.IoC;
using TechTalk.SpecFlow;
using ScenarioContext = TechTalk.SpecFlow.ScenarioContext;
namespace Attest.Testing.SpecFlow
{
/// <summary>
/// Base class for all integration-tests fixtures that involve ioc container adapter and test bootstrapper
/// and use SpecFlow as test framework provider.
/// </summary>
/// <typeparam name="TRootObject">The type of root object, from which the test's flow starts.</typeparam>
/// <typeparam name="TBootstrapper">The type of bootstrapper.</typeparam>
public abstract class IntegrationTestsBase<TRootObject, TBootstrapper> :
IntegrationTestsBase<TRootObject>,
IRootObjectFactory
where TRootObject : class
where TBootstrapper : IInitializable, IHaveRegistrator, IHaveResolver, new()
{
private readonly IInitializationParametersManager<IocContainerProxy> _initializationParametersManager;
private readonly ScenarioHelper _scenarioHelper;
/// <summary>
/// Initializes a new instance of the <see cref="IntegrationTestsBase{TRootObject,TBootstrapper}"/> class.
/// </summary>
/// <param name="scenarioContext">The scenario context.</param>
/// <param name="resolutionStyle">The resolution style.</param>
protected IntegrationTestsBase(
ScenarioContext scenarioContext,
InitializationParametersResolutionStyle resolutionStyle = InitializationParametersResolutionStyle.PerRequest)
{
_initializationParametersManager =
ContainerAdapterInitializationParametersManagerStore<TBootstrapper>.GetInitializationParametersManager(
resolutionStyle);
Core.ScenarioContext.Current = new ScenarioContextWrapper(scenarioContext);
_scenarioHelper = new ScenarioHelper(scenarioContext);
}
/// <summary>
/// Override this method to implement custom test setup logic.
/// </summary>
[BeforeScenario]
protected override void Setup()
{
SetupCore();
SetupOverride();
}
/// <summary>
/// Override this method to implement custom test teardown logic.
/// </summary>
[AfterScenario]
protected override void TearDown()
{
OnBeforeTeardown();
TearDownCore();
OnAfterTeardown();
}
private void SetupCore()
{
var initializationParameters = _initializationParametersManager.GetInitializationParameters();
Registrator = initializationParameters.IocContainer;
Resolver = initializationParameters.IocContainer;
_scenarioHelper.Initialize(initializationParameters.IocContainer, this);
}
/// <summary>
/// Provides additional opportunity to modify the test setup logic.
/// </summary>
protected virtual void SetupOverride()
{
}
private void TearDownCore()
{
_scenarioHelper.Clear();
}
/// <summary>
/// Override to inject custom logic before the teardown starts.
/// </summary>
protected virtual void OnBeforeTeardown()
{
}
/// <summary>
/// Override to inject custom logic after the teardown finishes.
/// </summary>
protected virtual void OnAfterTeardown()
{
}
private TRootObject CreateRootObjectTyped()
{
return CreateRootObject();
}
object IRootObjectFactory.CreateRootObject()
{
return CreateRootObjectTyped();
}
/// <summary>
/// Represents integration tests base with explicit root object creation (usually after [Arrange] step)
/// </summary>
public class WithExplicitRootObjectCreation : IntegrationTestsBase<TRootObject, TBootstrapper>
{
/// <summary>
/// Initializes a new instance of the <see cref="IntegrationTestsBase{TRootObject,TBootstrapper}.WithExplicitRootObjectCreation"/> class.
/// </summary>
/// <param name="scenarioContext"></param>
public WithExplicitRootObjectCreation(ScenarioContext scenarioContext)
:base(scenarioContext)
{
}
/// <inheritdoc />
[BeforeScenario]
protected override void Setup()
{
SetupOverride();
}
/// <summary>
/// Initializes Root object and IoC-related objects.
/// </summary>
public void InitializeRootObject()
{
SetupCore();
}
}
}
/// <summary>
/// Base class for all integration-tests fixtures that involve ioc container, its adapter, and test bootstrapper
/// and use SpecFlow as test framework provider.
/// </summary>
/// <typeparam name="TContainer">The type of ioc container.</typeparam>
/// <typeparam name="TContainerAdapter">The type of ioc container adapter.</typeparam>
/// <typeparam name="TRootObject">The type of root object, from which the test's flow starts.</typeparam>
/// <typeparam name="TBootstrapper">The type of bootstrapper.</typeparam>
public abstract class IntegrationTestsBase<TContainer, TContainerAdapter, TRootObject, TBootstrapper> :
IntegrationTestsBase<TRootObject>,
IRootObjectFactory
where TContainerAdapter : class, IIocContainer, IIocContainerAdapter<TContainer>
where TRootObject : class
where TBootstrapper : IInitializable, IHaveContainer<TContainer>, new()
{
private readonly IInitializationParametersManager<TContainer> _initializationParametersManager;
private readonly ScenarioHelper _scenarioHelper;
/// <summary>
/// Initializes a new instance of the <see cref="IntegrationTestsBase{TRootObject,TBootstrapper}"/> class.
/// </summary>
/// <param name="scenarioContext">The scenario context.</param>
/// <param name="resolutionStyle">The resolution style.</param>
protected IntegrationTestsBase(
ScenarioContext scenarioContext,
InitializationParametersResolutionStyle resolutionStyle = InitializationParametersResolutionStyle.PerRequest)
{
_initializationParametersManager =
ContainerInitializationParametersManagerStore<TBootstrapper, TContainer>.GetInitializationParametersManager(
resolutionStyle);
Core.ScenarioContext.Current = new ScenarioContextWrapper(scenarioContext);
_scenarioHelper = new ScenarioHelper(scenarioContext);
}
/// <summary>
/// Override this method to implement custom test setup logic.
/// </summary>
[BeforeScenario]
protected override void Setup()
{
SetupCore();
SetupOverride();
}
/// <summary>
/// Override this method to implement custom test teardown logic.
/// </summary>
[AfterScenario]
protected override void TearDown()
{
OnBeforeTeardown();
TearDownCore();
OnAfterTeardown();
}
private void SetupCore()
{
var initializationParameters = _initializationParametersManager.GetInitializationParameters();
var containerAdapter = CreateAdapter(initializationParameters.IocContainer);
Registrator = containerAdapter;
Resolver = containerAdapter;
_scenarioHelper.Initialize(containerAdapter, this);
}
/// <summary>
/// Provides additional opportunity to modify the test setup logic.
/// </summary>
protected virtual void SetupOverride()
{
}
/// <summary>
/// Override to provide ioc container adapter creation logic.
/// </summary>
/// <param name="container">The ioc container.</param>
/// <returns></returns>
protected abstract TContainerAdapter CreateAdapter(TContainer container);
private void TearDownCore()
{
_scenarioHelper.Clear();
}
/// <summary>
/// Override to inject custom logic before the teardown starts.
/// </summary>
protected virtual void OnBeforeTeardown()
{
}
/// <summary>
/// Override to inject custom logic after the teardown finishes.
/// </summary>
protected virtual void OnAfterTeardown()
{
}
private TRootObject CreateRootObjectTyped()
{
return CreateRootObject();
}
object IRootObjectFactory.CreateRootObject()
{
return CreateRootObjectTyped();
}
}
}
| 37.34127 | 150 | 0.598512 | [
"MIT"
] | JTOne123/Attest | Attest.Testing.SpecFlow/IntegrationTestsBase.cs | 9,412 | C# |
using System;
namespace Commuter.Services
{
public struct Location
{
public Location(double latitude, double longitude, double? altitude = null)
{
Latitude = latitude;
Longitude = longitude;
Altitude = altitude;
}
public double Latitude { get; }
public double Longitude { get; }
public double? Altitude { get; }
}
}
| 23 | 83 | 0.572464 | [
"Apache-2.0"
] | robertsundstrom/commuter | Commuter.Core/Services/Location.cs | 416 | C# |
#region BSD License
/* Copyright (c) 2013-2018, Doxense SAS
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Doxense nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
namespace FoundationDB.Layers.Directories
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Doxense.Collections.Tuples;
using Doxense.Diagnostics.Contracts;
using JetBrains.Annotations;
/// <summary>Represents a path in a Directory Layer</summary>
[DebuggerDisplay("{ToString(),nq}")]
public readonly struct FdbDirectoryPath : IReadOnlyList<string>, IEquatable<FdbDirectoryPath>
{
public static readonly FdbDirectoryPath Empty = new FdbDirectoryPath(Array.Empty<string>());
internal readonly string[] Segments;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FdbDirectoryPath(string[] segments)
{
this.Segments = segments;
}
public bool IsEmpty
{
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this.Segments == null || this.Segments.Length == 0;
}
public int Count => GetSegments().Length;
public string this[int index] => GetSegments()[index];
public string Name
{
[Pure, NotNull]
get
{
var segments = GetSegments();
return segments.Length != 0 ? segments[segments.Length - 1] : string.Empty;
}
}
[Pure]
public FdbDirectoryPath Concat(FdbDirectoryPath path)
{
if (path.IsEmpty) return this;
if (this.IsEmpty) return path;
var segments = this.Segments;
int n = segments.Length;
Array.Resize(ref segments, checked(n + path.Segments.Length));
path.Segments.CopyTo(segments, n);
return new FdbDirectoryPath(segments);
}
[Pure]
public FdbDirectoryPath Concat([NotNull] string segment)
{
if (this.IsEmpty) return Create(segment);
var segments = this.Segments;
int n = segments.Length;
Array.Resize(ref segments, checked(n + 1));
segments[n] = segment;
return new FdbDirectoryPath(segments);
}
#if NETCOREAPP || NETSTANDARD2_1
[Pure]
public FdbDirectoryPath Concat(ReadOnlySpan<char> segment)
{
return Concat(segment.ToString());
}
#endif
[Pure]
public FdbDirectoryPath Concat([NotNull, ItemNotNull] params string[] path)
{
if (this.IsEmpty) return Create(path);
var segments = this.Segments;
int n = segments.Length;
Array.Resize(ref segments, checked(n + path.Length));
path.CopyTo(segments, n);
return new FdbDirectoryPath(segments);
}
[Pure]
public FdbDirectoryPath Concat([NotNull, ItemNotNull] IEnumerable<string> segments)
{
Contract.NotNull(segments, nameof(segments));
if (this.IsEmpty) return Create(segments);
var after = new List<string>();
after.AddRange(this.Segments);
after.AddRange(segments);
return new FdbDirectoryPath(after.ToArray());
}
[Pure]
public FdbDirectoryPath Concat([NotNull] IVarTuple segments)
{
Contract.NotNull(segments, nameof(segments));
if (this.IsEmpty) return Create(segments);
var after = new List<string>();
after.AddRange(this.Segments);
after.AddRange(segments.ToArray<string>());
return new FdbDirectoryPath(after.ToArray());
}
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
public IEnumerator<string> GetEnumerator()
{
return ((IEnumerable<string>) GetSegments()).GetEnumerator();
}
public override string ToString()
{
return FormatPath(GetSegments());
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[Pure, NotNull, MethodImpl(MethodImplOptions.AggressiveInlining)]
internal string[] GetSegments() => this.Segments ?? Array.Empty<string>();
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
public string[] ToArray()
{
return GetSegments().ToArray();
}
#if NETCOREAPP || NETSTANDARD2_1
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<string> AsSpan()
{
return GetSegments().AsSpan();
}
#endif
public void CopyTo(string[] array, int offset)
{
GetSegments().CopyTo(array, offset);
}
[Pure]
public static FdbDirectoryPath Create([NotNull, ItemNotNull] IEnumerable<string> segments)
{
Contract.NotNull(segments, nameof(segments));
return new FdbDirectoryPath(segments.ToArray());
}
[Pure]
public static FdbDirectoryPath Create([NotNull] string segment)
{
Contract.NotNull(segment, nameof(segment));
return new FdbDirectoryPath(new [] { segment });
}
#if NETCOREAPP || NETSTANDARD2_1
[Pure]
public static FdbDirectoryPath Create(ReadOnlySpan<char> segment)
{
return Create(segment.ToString());
}
#endif
/// <summary>Convert a tuple representing a path, into a string array</summary>
/// <param name="path">Tuple that should only contain strings</param>
/// <returns>Array of strings</returns>
[Pure]
public static FdbDirectoryPath Create([NotNull] IVarTuple path)
{
Contract.NotNull(path, nameof(path));
return Create(path.ToArray<string>());
}
[Pure]
public static FdbDirectoryPath Create([NotNull, ItemNotNull] params string[] segments)
{
Contract.NotNull(segments, nameof(segments));
return new FdbDirectoryPath(segments);
}
[Pure]
public static FdbDirectoryPath Parse([CanBeNull] string path)
{
if (string.IsNullOrEmpty(path)) return Empty;
var paths = new List<string>();
var sb = new System.Text.StringBuilder();
bool escaped = false;
foreach (var c in path)
{
if (escaped)
{
escaped = false;
sb.Append(c);
continue;
}
switch (c)
{
case '\\':
{
escaped = true;
continue;
}
case '/':
{
if (sb.Length == 0 && paths.Count == 0)
{ // ignore the first '/'
continue;
}
paths.Add(sb.ToString());
sb.Clear();
break;
}
default:
{
sb.Append(c);
break;
}
}
}
if (sb.Length > 0)
{
paths.Add(sb.ToString());
}
return new FdbDirectoryPath(paths.ToArray());
}
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator FdbDirectoryPath([NotNull] string segment)
{
return Create(segment);
}
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator FdbDirectoryPath([NotNull, ItemNotNull] string[] segments)
{
return Create(segments);
}
[Pure, NotNull]
internal static string FormatPath([NotNull, ItemNotNull] string[] paths)
{
Contract.NotNull(paths, nameof(paths));
return string.Join("/", paths.Select(path => path.Contains('\\') || path.Contains('/')
? path.Replace("\\", "\\\\").Replace("/", "\\/")
: path));
}
[Pure, NotNull]
internal IVarTuple ToTuple()
{
return this.IsEmpty ? STuple.Empty : STuple.FromArray(this.Segments);
}
public override int GetHashCode()
{
var segments = GetSegments();
int h = segments.Length;
foreach (var s in segments)
{
h = (h * 31) ^ s.GetHashCode();
}
return h;
}
public override bool Equals(object obj)
{
return obj is FdbDirectoryPath path && Equals(path);
}
[Pure, MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(FdbDirectoryPath other)
{
return this == other;
}
public static bool operator ==(FdbDirectoryPath left, FdbDirectoryPath right)
{
var l = left.GetSegments();
var r = right.GetSegments();
if (l.Length != r.Length) return false;
for (int i = 0; i < l.Length; i++)
{
if (l[i] != r[i]) return false;
}
return true;
}
public static bool operator !=(FdbDirectoryPath left, FdbDirectoryPath right)
{
var l = left.GetSegments();
var r = right.GetSegments();
if (l.Length != r.Length) return true;
for (int i = 0; i < l.Length; i++)
{
if (l[i] != r[i]) return true;
}
return false;
}
}
}
| 26.94152 | 94 | 0.697634 | [
"BSD-3-Clause"
] | laibulle/foundationdb-dotnet-client | FoundationDB.Client/Layers/Directories/FdbDirectoryPath.cs | 9,216 | 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("ObjectContextApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ObjectContextApp")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e61f117e-dda9-4692-8a1b-9e496f76d918")]
// 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.837838 | 84 | 0.749286 | [
"MIT"
] | 6e3veR6k/codewars-csharp | resources/pro-csharp-7-master/Chapter_17/ObjectContextApp/ObjectContextApp/Properties/AssemblyInfo.cs | 1,403 | 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.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Microsoft.EntityFrameworkCore.Infrastructure
{
/// <summary>
/// <para>
/// A base type with a simple API surface for configuring a <see cref="ConventionAnnotatable" />.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
[DebuggerDisplay("Builder {" + nameof(Metadata) + ",nq}")]
public abstract class AnnotatableBuilder<TMetadata, TModelBuilder> : IConventionAnnotatableBuilder
where TMetadata : ConventionAnnotatable
where TModelBuilder : IConventionModelBuilder
{
/// <summary>
/// Creates a new instance of <see cref="AnnotatableBuilder{TMetadata, TModelBuilder}" />
/// </summary>
protected AnnotatableBuilder(TMetadata metadata, TModelBuilder modelBuilder)
{
Metadata = metadata;
ModelBuilder = modelBuilder;
}
/// <summary>
/// Gets the item being configured.
/// </summary>
public virtual TMetadata Metadata { get; }
/// <summary>
/// Gets the model builder.
/// </summary>
public virtual TModelBuilder ModelBuilder { get; }
/// <summary>
/// Sets the annotation with given key and value on this object using given configuration source.
/// Overwrites the existing annotation if an annotation with the specified name already exists.
/// </summary>
/// <param name="name"> The key of the annotation to be set. </param>
/// <param name="value"> The value to be stored in the annotation. </param>
/// <param name="configurationSource"> The configuration source of the annotation to be set. </param>
/// <returns> The same builder so that multiple calls can be chained. </returns>
public virtual AnnotatableBuilder<TMetadata, TModelBuilder>? HasAnnotation(
string name,
object? value,
ConfigurationSource configurationSource)
=> HasAnnotation(name, value, configurationSource, canOverrideSameSource: true);
private AnnotatableBuilder<TMetadata, TModelBuilder>? HasAnnotation(
string name,
object? value,
ConfigurationSource configurationSource,
bool canOverrideSameSource)
{
var existingAnnotation = Metadata.FindAnnotation(name);
if (existingAnnotation != null)
{
if (Equals(existingAnnotation.Value, value))
{
existingAnnotation.UpdateConfigurationSource(configurationSource);
return this;
}
if (!CanSetAnnotationValue(existingAnnotation, value, configurationSource, canOverrideSameSource))
{
return null;
}
Metadata.SetAnnotation(name, value, configurationSource);
return this;
}
Metadata.AddAnnotation(name, value, configurationSource);
return this;
}
/// <summary>
/// Sets the annotation with given key and value on this object using given configuration source.
/// Overwrites the existing annotation if an annotation with the specified name already exists.
/// Removes the annotation if <see langword="null" /> value is specified.
/// </summary>
/// <param name="name"> The key of the annotation to be set. </param>
/// <param name="value"> The value to be stored in the annotation. </param>
/// <param name="configurationSource"> The configuration source of the annotation to be set. </param>
/// <returns> The same builder so that multiple calls can be chained. </returns>
public virtual AnnotatableBuilder<TMetadata, TModelBuilder>? HasNonNullAnnotation(
string name,
object? value,
ConfigurationSource configurationSource)
=> value == null
? RemoveAnnotation(name, configurationSource)
: HasAnnotation(name, value, configurationSource, canOverrideSameSource: true);
/// <summary>
/// Returns a value indicating whether an annotation with the given name and value can be set from this configuration source.
/// </summary>
/// <param name="name"> The name of the annotation to be added. </param>
/// <param name="value"> The value to be stored in the annotation. </param>
/// <param name="configurationSource"> The configuration source of the annotation to be set. </param>
/// <returns> <see langword="true" /> if the annotation can be set, <see langword="false" /> otherwise. </returns>
public virtual bool CanSetAnnotation(string name, object? value, ConfigurationSource configurationSource)
{
var existingAnnotation = Metadata.FindAnnotation(name);
return existingAnnotation == null
|| CanSetAnnotationValue(existingAnnotation, value, configurationSource, canOverrideSameSource: true);
}
private static bool CanSetAnnotationValue(
ConventionAnnotation annotation,
object? value,
ConfigurationSource configurationSource,
bool canOverrideSameSource)
{
if (Equals(annotation.Value, value))
{
return true;
}
var existingConfigurationSource = annotation.GetConfigurationSource();
return configurationSource.Overrides(existingConfigurationSource)
&& (configurationSource != existingConfigurationSource
|| canOverrideSameSource);
}
/// <summary>
/// Removes any annotation with the given name.
/// </summary>
/// <param name="name"> The name of the annotation to remove. </param>
/// <param name="configurationSource"> The configuration source of the annotation to be set. </param>
/// <returns> The same builder so that multiple calls can be chained. </returns>
public virtual AnnotatableBuilder<TMetadata, TModelBuilder>? RemoveAnnotation(
string name,
ConfigurationSource configurationSource)
{
if (!CanRemoveAnnotation(name, configurationSource))
{
return null;
}
Metadata.RemoveAnnotation(name);
return this;
}
/// <summary>
/// Returns a value indicating whether an annotation with the given name can be removed using this configuration source.
/// </summary>
/// <param name="name"> The name of the annotation to remove. </param>
/// <param name="configurationSource"> The configuration source of the annotation to be set. </param>
/// <returns> <see langword="true" /> if the annotation can be removed, <see langword="false" /> otherwise. </returns>
public virtual bool CanRemoveAnnotation(string name, ConfigurationSource configurationSource)
{
var existingAnnotation = Metadata.FindAnnotation(name);
return existingAnnotation == null
|| configurationSource.Overrides(existingAnnotation.GetConfigurationSource());
}
/// <summary>
/// Copies all the explicitly configured annotations from the given object ovewriting any existing ones.
/// </summary>
/// <param name="annotatable"> The object to copy annotations from. </param>
public virtual void MergeAnnotationsFrom(TMetadata annotatable)
=> MergeAnnotationsFrom(annotatable, ConfigurationSource.Explicit);
/// <summary>
/// Copies all the configured annotations from the given object ovewriting any existing ones.
/// </summary>
/// <param name="annotatable"> The object to copy annotations from. </param>
/// <param name="minimalConfigurationSource"> The minimum configuration source for an annoptation to be copied. </param>
public virtual void MergeAnnotationsFrom(TMetadata annotatable, ConfigurationSource minimalConfigurationSource)
{
foreach (var annotation in annotatable.GetAnnotations())
{
var configurationSource = annotation.GetConfigurationSource();
if (configurationSource.Overrides(minimalConfigurationSource))
{
HasAnnotation(
annotation.Name,
annotation.Value,
configurationSource,
canOverrideSameSource: false);
}
}
}
/// <inheritdoc />
IConventionModelBuilder IConventionAnnotatableBuilder.ModelBuilder
{
[DebuggerStepThrough] get => ModelBuilder;
}
/// <inheritdoc />
IConventionAnnotatable IConventionAnnotatableBuilder.Metadata
{
[DebuggerStepThrough] get => Metadata;
}
/// <inheritdoc />
[DebuggerStepThrough]
IConventionAnnotatableBuilder? IConventionAnnotatableBuilder.HasAnnotation(string name, object? value, bool fromDataAnnotation)
=> HasAnnotation(name, value, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionAnnotatableBuilder? IConventionAnnotatableBuilder.HasNonNullAnnotation(
string name,
object? value,
bool fromDataAnnotation)
=> HasNonNullAnnotation(name, value, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionAnnotatableBuilder.CanSetAnnotation(string name, object? value, bool fromDataAnnotation)
=> CanSetAnnotation(name, value, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
IConventionAnnotatableBuilder? IConventionAnnotatableBuilder.HasNoAnnotation(string name, bool fromDataAnnotation)
=> RemoveAnnotation(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
/// <inheritdoc />
[DebuggerStepThrough]
bool IConventionAnnotatableBuilder.CanRemoveAnnotation(string name, bool fromDataAnnotation)
=> CanRemoveAnnotation(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);
}
}
| 47.156118 | 139 | 0.636901 | [
"MIT"
] | FelicePollano/efcore | src/EFCore/Infrastructure/AnnotatableBuilder.cs | 11,176 | C# |
using DnDGen.Infrastructure.Selectors.Collections;
using System;
using System.Linq;
using DnDGen.TreasureGen.Selectors.Selections;
using DnDGen.TreasureGen.Tables;
namespace DnDGen.TreasureGen.Selectors.Collections
{
internal class ArmorDataSelector : IArmorDataSelector
{
private readonly ICollectionSelector innerSelector;
public ArmorDataSelector(ICollectionSelector innerSelector)
{
this.innerSelector = innerSelector;
}
public ArmorSelection Select(string name)
{
var data = innerSelector.SelectFrom(TableNameConstants.Collections.Set.ArmorData, name).ToArray();
var selection = new ArmorSelection();
selection.ArmorBonus = Convert.ToInt32(data[DataIndexConstants.Armor.ArmorBonus]);
selection.ArmorCheckPenalty = Convert.ToInt32(data[DataIndexConstants.Armor.ArmorCheckPenalty]);
selection.MaxDexterityBonus = Convert.ToInt32(data[DataIndexConstants.Armor.MaxDexterityBonus]);
return selection;
}
}
}
| 34.354839 | 110 | 0.719249 | [
"MIT"
] | DnDGen/TreasureGen | DnDGen.TreasureGen/Selectors/Collections/ArmorDataSelector.cs | 1,067 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementSByte15()
{
var test = new VectorGetAndWithElement__GetAndWithElementSByte15();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSByte15
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 15, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]);
bool succeeded = !expectedOutOfRangeException;
try
{
SByte result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
SByte insertedValue = TestLibrary.Generator.GetSByte();
try
{
Vector256<SByte> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 15, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((SByte)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
SByte insertedValue = TestLibrary.Generator.GetSByte();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<SByte>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(15 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(15 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(15 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(15 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(SByte result, SByte[] values, [CallerMemberName] string method = "")
{
if (result != values[15])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.GetElement(15): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<SByte> result, SByte[] values, SByte insertedValue, [CallerMemberName] string method = "")
{
SByte[] resultElements = new SByte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(SByte[] result, SByte[] values, SByte insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 15) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[15] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithElement(15): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 41.637555 | 428 | 0.574095 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/General/Vector256_1/GetAndWithElement.SByte.15.cs | 9,535 | C# |
// <copyright file="HttprequestParsers.cs" company="Microsoft">
// Copyright 2013 Microsoft 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.
// </copyright>
// -----------------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.Shared.Protocol
{
using System.Net.Http;
using System.Linq;
using System;
using System.Collections.Generic;
internal static partial class HttpRequestParsers
{
internal static string GetAuthorization(HttpRequestMessage request)
{
return request.Headers.Authorization != null ? request.Headers.Authorization.ToString() : null;
}
internal static string GetDate(HttpRequestMessage request)
{
return request.Headers.Date != null ? request.Headers.Date.ToString() : null;
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A ContentType string.</returns>
internal static string GetContentType(HttpRequestMessage request)
{
return request.Content?.Headers.ContentType != null ? request.Content?.Headers.ContentType.ToString() : null;
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A quoted ContentRange string.</returns>
internal static string GetContentRange(HttpRequestMessage request)
{
return request.Content?.Headers.ContentRange != null ? request.Content.Headers.ContentRange.ToString() : null;
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A the content range header string.</returns>
internal static string GetContentRangeHeader(HttpRequestMessage request)
{
IEnumerable<string> rangeHeaderValue;
if(request.Headers.TryGetValues(Constants.HeaderConstants.RangeHeader, out rangeHeaderValue))
{
return rangeHeaderValue.FirstOrDefault();
}
return null;
}
/// <summary>
/// Gets the ContentMD5 from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A ContentMD5 string.</returns>
internal static string GetContentMD5(HttpRequestMessage request)
{
return request.Content?.Headers.ContentMD5 != null ? Convert.ToBase64String(request.Content.Headers.ContentMD5) : null;
}
/// <summary>
/// Gets the content CRC64 from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A content CRC64 string.</returns>
internal static string GetContentCRC64(HttpRequestMessage request)
{
return GetHeader(request, Constants.HeaderConstants.ContentCrc64Header);
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A quoted ETag string.</returns>
internal static string GetContentLocation(HttpRequestMessage request)
{
return request.Content?.Headers.ContentLocation != null ? request.Content.Headers.ContentLocation.ToString() : null;
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A quoted ETag string.</returns>
internal static long? GetContentLength(HttpRequestMessage request)
{
return request.Content?.Headers.ContentLength;
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A quoted ETag string.</returns>
internal static string GetContentLanguage(HttpRequestMessage request)
{
return request.Content?.Headers.ContentLanguage != null ? request.Content.Headers.ContentLanguage.ToString() : null;
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A quoted ETag string.</returns>
internal static string GetContentEncoding(HttpRequestMessage request)
{
return request.Content?.Headers.ContentEncoding != null ? request.Content.Headers.ContentEncoding.ToString() : null;
}
/// <summary>
/// Gets an ETag from a request.
/// </summary>
/// <param name="request">The web request.</param>
/// <returns>A quoted ETag string.</returns>
internal static string GetContentDisposition(HttpRequestMessage request)
{
return request.Content?.Headers.ContentDisposition != null ? request.Content.Headers.ContentDisposition.ToString() : null;
}
internal static string GetIfMatch(HttpRequestMessage request)
{
return request.Headers.IfMatch != null ? request.Headers.IfMatch.ToString() : null;
}
internal static string GetIfNoneMatch(HttpRequestMessage request)
{
return request.Headers.IfNoneMatch != null ? request.Headers.IfNoneMatch.ToString() : null;
}
internal static string GetIfModifiedSince(HttpRequestMessage request)
{
return request.Headers.IfModifiedSince != null ? request.Headers.IfModifiedSince.ToString() : null;
}
internal static string GetIfUnModifiedSince(HttpRequestMessage request)
{
return request.Headers.IfUnmodifiedSince != null ? request.Headers.IfUnmodifiedSince.ToString() : null;
}
internal static string GetCacheControl(HttpRequestMessage request)
{
return request.Headers.CacheControl != null ? request.Headers.CacheControl.ToString() : null;
}
internal static List<string> GetAllHeaders(HttpRequestMessage request)
{
if (request.Content != null)
{
return request.Headers.Concat(request.Content.Headers).Select(r => r.Key).ToList();
}
return request.Headers.Select(r => r.Key).ToList();
}
internal static string GetHeader(HttpRequestMessage request, string headerName)
{
if (request.Content != null && request.Content.Headers.Contains(headerName))
{
return request.Content.Headers.GetValues(headerName).First();
}
else if (request.Headers.Contains(headerName))
{
return request.Headers.GetValues(headerName).First();
}
else
{
return null;
}
}
}
} | 40.072539 | 135 | 0.599043 | [
"Apache-2.0"
] | Azure/azure-storage-net | Test/Common/Core/HttpRequestParsers.cs | 7,734 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace VkNet.Model.RequestParams
{
/// <summary>
/// Параметры метода board.getTopics
/// </summary>
[Serializable]
public class BoardGetTopicsParams
{
/// <summary>
/// Идентификатор владельца страницы (пользователь или сообщество). Обратите
/// внимание, идентификатор сообщества в
/// параметре owner_id необходимо указывать со знаком "-" — например, owner_id=-1
/// соответствует идентификатору
/// сообщества ВКонтакте API (club1) целое число, по умолчанию идентификатор
/// текущего пользователя.
/// </summary>
[JsonProperty(propertyName: "group_id")]
public long? GroupId { get; set; }
/// <summary>
/// Cписок идентификаторов тем, которые необходимо получить (не более 100).
/// </summary>
[JsonProperty(propertyName: "topic_ids")]
public IEnumerable<long> TopicIds { get; set; }
/// <summary>
/// Порядок, в котором необходимо вернуть список тем.
/// </summary>
[JsonProperty(propertyName: "order")]
public int? Order { get; set; }
/// <summary>
/// Сдвиг, необходимый для получения конкретной выборки результатов. целое число.
/// </summary>
[JsonProperty(propertyName: "offset")]
public long? Offset { get; set; }
/// <summary>
/// Число комментариев, которые необходимо получить. По умолчанию — 10,
/// максимальное значение — 100. положительное
/// число.
/// </summary>
[JsonProperty(propertyName: "count")]
public long? Count { get; set; }
/// <summary>
/// Если указать в качестве этого параметра 1, то будет возвращена информация о
/// пользователях, являющихся создателями
/// тем или оставившими в них последнее сообщение. По умолчанию 0.
/// </summary>
[JsonProperty(propertyName: "extended")]
public bool? Extended { get; set; }
/// <summary>
/// Набор флагов, определяющий, необходимо ли вернуть вместе с информацией о темах
/// текст первых и последних сообщений в
/// них..
/// </summary>
[JsonProperty(propertyName: "preview")]
public int? Preview { get; set; }
/// <summary>
/// Количество символов, по которому нужно обрезать первое и последнее сообщение.
/// Укажите 0, если Вы не хотите обрезать
/// сообщение. (по умолчанию — 90).
/// </summary>
[JsonProperty(propertyName: "preview_length")]
public int? PreviewLength { get; set; }
}
} | 31.945946 | 84 | 0.689509 | [
"MIT"
] | DeNcHiK3713/vk | VkNet/Model/RequestParams/Board/BoardGetTopicsParams.cs | 3,242 | C# |
// Copyright 2020 Google 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.
namespace NtApiDotNet.Win32.Security.Authentication.Kerberos
{
#pragma warning disable 1591
/// <summary>
/// Kerberos Message Type.
/// </summary>
public enum KerberosMessageType
{
UNKNOWN = 0,
KRB_AS_REQ = 10,
KRB_AS_REP = 11,
KRB_TGS_REQ = 12,
KRB_TGS_REP = 13,
KRB_AP_REQ = 14,
KRB_AP_REP = 15,
KRB_TGT_REQ = 16,
KRB_TGT_REP = 17,
KRB_SAFE = 20,
KRB_PRIV = 21,
KRB_CRED = 22,
KRB_AS_REP_ENC_PART = 25,
KRB_TGS_REP_ENC_PART = 26,
KRB_CRED_ENC_PART = 29,
KRB_ERROR = 30,
}
}
| 30.439024 | 76 | 0.646635 | [
"Apache-2.0"
] | avboy1337/sandbox-attacksurface-analysis-tools | NtApiDotNet/Win32/Security/Authentication/Kerberos/KerberosMessageType.cs | 1,250 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.400)
// Version 5.400.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Details for an event that discovers the rectangle that the mouse has to leave to begin dragging.
/// </summary>
public class ButtonDragRectangleEventArgs : EventArgs
{
#region Instance Fields
private Rectangle _dragRect;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ButtonDragRectangleEventArgs class.
/// </summary>
/// <param name="point">Left mouse down point.</param>
public ButtonDragRectangleEventArgs(Point point)
{
Point = point;
_dragRect = new Rectangle(Point, Size.Empty);
_dragRect.Inflate(SystemInformation.DragSize);
PreDragOffset = true;
}
#endregion
#region Point
/// <summary>
/// Gets access to the left mouse down point.
/// </summary>
public Point Point { get; }
#endregion
#region DragRect
/// <summary>
/// Gets access to the drag rectangle area.
/// </summary>
public Rectangle DragRect
{
get => _dragRect;
set => _dragRect = value;
}
#endregion
#region PreDragOffset
/// <summary>
/// Gets and sets the need for pre drag offset events.
/// </summary>
public bool PreDragOffset { get; set; }
#endregion
}
}
| 32.577465 | 157 | 0.57847 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.400 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/EventArgs/ButtonDragRectangleEventArgs.cs | 2,316 | C# |
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNetCore.Common;
namespace Renci.SshNetCore.Tests.Classes
{
[TestClass]
public class ForwardedPortLocalTest_Stop_PortDisposed
{
private ForwardedPortLocal _forwardedPort;
private IList<EventArgs> _closingRegister;
private IList<ExceptionEventArgs> _exceptionRegister;
[TestInitialize]
public void Setup()
{
Arrange();
Act();
}
[TestCleanup]
public void Cleanup()
{
if (_forwardedPort != null)
{
_forwardedPort.Dispose();
_forwardedPort = null;
}
}
protected void Arrange()
{
_closingRegister = new List<EventArgs>();
_exceptionRegister = new List<ExceptionEventArgs>();
_forwardedPort = new ForwardedPortLocal("boundHost", "host", 22);
_forwardedPort.Closing += (sender, args) => _closingRegister.Add(args);
_forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
_forwardedPort.Dispose();
}
protected void Act()
{
_forwardedPort.Stop();
}
[TestMethod]
public void IsStartedShouldReturnFalse()
{
Assert.IsFalse(_forwardedPort.IsStarted);
}
[TestMethod]
public void ClosingShouldNotHaveFired()
{
Assert.AreEqual(0, _closingRegister.Count);
}
[TestMethod]
public void ExceptionShouldNotHaveFired()
{
Assert.AreEqual(0, _exceptionRegister.Count);
}
}
}
| 26.179104 | 87 | 0.580388 | [
"MIT"
] | rintindon/SSH.NET.dotnetcore | src/Renci.SshNet.Core.Test/Classes/ForwardedPortLocalTest_Stop_PortDisposed.cs | 1,756 | C# |
using Algorand;
using Algorand.V2;
using System;
using System.Configuration;
using System.Threading.Tasks;
using Tinyman.V1;
using Tinyman.V1.Model;
namespace Tinyman.VerboseSwapExample {
class Program {
static async Task Main(string[] args) {
var settings = ConfigurationManager.AppSettings;
var mnemonic = settings.Get("Account.Mnemonic");
if (String.IsNullOrWhiteSpace(mnemonic)) {
throw new Exception("'Account.Mnemonic' key is not set in App.Config.");
}
var account = new Account(mnemonic);
// Initialize the client
var appId = Constant.TestnetValidatorAppId;
var url = Constant.AlgodTestnetHost;
var token = String.Empty;
var httpClient = HttpClientConfigurator.ConfigureHttpClient(url, token);
var client = new TinymanClient(httpClient, url, appId);
// Ensure the account is opted in
var isOptedIn = await client.IsOptedInAsync(account.Address);
if (!isOptedIn) {
var txParams = await client.FetchTransactionParamsAsync();
// Use utility method to create the transaction group
var optInTxGroup = TinymanTransaction
.PrepareAppOptinTransactions(appId, account.Address, txParams);
// Sign the transactions sent from the account,
// the LogicSig transactions will already be signed
for (var i = 0; i < optInTxGroup.Transactions.Length; i++) {
var tx = optInTxGroup.Transactions[i];
// Inspect transaction
// Sign transaction
if (tx.sender.Equals(account.Address)) {
optInTxGroup.SignedTransactions[i] = account.SignTransaction(tx);
}
}
var optInResult = await client.SubmitAsync(optInTxGroup);
Console.WriteLine($"Opt-in successful, transaction ID: {optInResult.TxId}");
}
// Get the assets
var tinyUsdc = await client.FetchAssetAsync(21582668);
var algo = await client.FetchAssetAsync(0);
// Get the pool
var pool = await client.FetchPoolAsync(algo, tinyUsdc);
// Get a quote to swap 1 Algo for tinyUsdc
var amountIn = Algorand.Utils.AlgosToMicroalgos(1.0);
var quote = pool.CalculateFixedInputSwapQuote(new AssetAmount(algo, amountIn), 0.05);
// Check the quote, ensure it's something that you want to execute
// Perform the swap
try {
var txParams = await client.FetchTransactionParamsAsync();
// Use utility method to create the transaction group
var swapTxGroup = TinymanTransaction.PrepareSwapTransactions(
appId,
quote.AmountIn,
quote.AmountOutWithSlippage,
pool.LiquidityAsset,
quote.SwapType,
account.Address,
txParams);
// Sign the transactions sent from the account,
// the LogicSig transactions will already be signed
for (var i = 0; i < swapTxGroup.Transactions.Length; i++) {
var tx = swapTxGroup.Transactions[i];
// Inspect transaction
// Sign transaction
if (tx.sender.Equals(account.Address)) {
swapTxGroup.SignedTransactions[i] = account.SignTransaction(tx);
}
}
var swapResult = await client.SubmitAsync(swapTxGroup);
Console.WriteLine($"Swap complete, transaction ID: {swapResult.TxId}");
} catch (Exception ex) {
Console.WriteLine($"An error occured: {ex.Message}");
}
Console.WriteLine("Example complete.");
}
}
}
| 28.313043 | 88 | 0.703931 | [
"MIT"
] | geoffodonnell/dotnet-tinyman-sdk | example/Tinyman.VerboseSwapExample/Program.cs | 3,258 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Albatross.Cryptography.Core {
public interface ICreateHash {
byte[] Create(string text);
int HashSize { get; }
}
}
| 18.181818 | 39 | 0.745 | [
"MIT"
] | RushuiGuan/framework | src/Albatross.Cryptography/Core/ICreateHash.cs | 202 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
#if UNITTEST
namespace Microsoft.Diagnostics.Monitoring.TestCommon
#else
namespace Microsoft.Diagnostics.Monitoring.WebApi
#endif
{
internal static class CancellationTokenSourceExtensions
{
/// <summary>
/// Handles all exception when calling <see cref="CancellationTokenSource.Cancel()"/>.
/// </summary>
public static void SafeCancel(this CancellationTokenSource source)
{
try
{
source.Cancel();
}
catch
{
}
}
}
}
| 26.466667 | 94 | 0.629723 | [
"MIT"
] | ScriptBox21/dotnet-monitor | src/Microsoft.Diagnostics.Monitoring.WebApi/CancellationTokenSourceExtensions.cs | 796 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace TernaryTree
{
// TODO: Error Handling and Documentation. Follow Microsoft lead with interfaces.
// TODO: More unit tests. Check line coverage.
// TODO: Consider storing a KeyValuePair at node.Data. This would do away with all the string building.
/// <summary>
/// Provides a structure for storing key value pairs.
/// Key must be a <code>string</code>.
/// Provides fast insert and lookup operations.
/// Provides regex matching for keys.
/// </summary>
public class TernaryTree<V> :
IDictionary<string, V>,
ICollection<KeyValuePair<string, V>>,
IEnumerable<KeyValuePair<string, V>>,
IEnumerable // TODO: We're not doing this right. It's supposed to be an enumeration of the <V>, not the string.
// TODO: Non-Generic Interfaces?
{
#region Fields and Properties
/// <summary>
/// An entry point to the data structure.
/// </summary>
internal Node<V> Head;
/// <summary>
/// Gets the number of keys in the <see cref="TernaryTree"/>.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Gets a value indicating whether this <see cref="TernaryTree"/> is
/// read-only.
/// </summary>
public bool IsReadOnly { get { return false; } }
/// <summary>
/// Gets a value indicating whether this <see cref="TernaryTree"/> has
/// a fixed size.
/// </summary>
public bool IsFixedSize { get { return false; } }
// TODO: Concurrency
/// <summary>
/// Gets a value indicating whether access to the <see cref="TernaryTree"/>
/// is synchronized (thread safe).
/// </summary>
public bool IsSynchronized { get { return false; } }
/// <summary>
/// Gets an object that can be used to synchronize access to the
/// <see cref="TernaryTree"/>
/// </summary>
public object SyncRoot { get { return this; } }
#endregion
#region Static 'Constructors'
public static TernaryTree<V> Create(ICollection<string> keySet)
{
TernaryTree<V> tree = new TernaryTree<V>();
foreach (string key in keySet)
{
tree.Add(key);
}
return tree;
}
public static TernaryTree<V> Create(ICollection<KeyValuePair<string, V>> keyValueSet)
{
TernaryTree<V> tree = new TernaryTree<V>();
foreach (KeyValuePair<string, V> keyValuePair in keyValueSet)
{
tree.Add(keyValuePair.Key, keyValuePair.Value);
}
return tree;
}
public static TernaryTree<V> Create(IDictionary<string, V> keyValueSet)
{
TernaryTree<V> tree = new TernaryTree<V>();
foreach (KeyValuePair<string, V> keyValuePair in keyValueSet)
{
tree.Add(keyValuePair.Key, keyValuePair.Value);
}
return tree;
}
#endregion
#region Indexers
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public V this[string key]
{
get
{
TryGetValue(key, out V value);
return value;
}
set
{
Add(key, value);
}
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <remarks>
/// This is a relatively expensive operation.
/// Time and space complexity increase linearly with index.
/// </remarks>
public string this[int index]
{
get
{
if (index >= Count || index < 0)
{
throw new IndexOutOfRangeException();
}
_getKeyAtIndex(Head, new StringBuilder(), ref index, out string s);
return s;
}
}
#endregion
#region Collections and Enumerators
/// <summary>
///
/// </summary>
/// <returns></returns>
public ICollection<string> Keys()
{
List<string> _keyList = new List<string>();
_getBranchKeys(Head, new StringBuilder(), _keyList);
return _keyList;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ICollection<V> Values()
{
List<V> _valueList = new List<V>();
_getBranchValues(Head, _valueList);
return _valueList;
}
/// <summary>
///
/// </summary>
/// <param name="pattern">A regular expression to match.</param>
/// <returns>A collection of keys matching the regular expression.</returns>
public ICollection<string> Match(string pattern)
{
TernaryTreeSearch<V> search = new TernaryTreeSearch<V>(pattern);
return search.Match(this);
}
/// <summary>
///
/// </summary>
/// <param name="pattern">A <see cref="TernaryTreeSearch{V}"/>
/// which has been configured to match a regular expression.</param>
/// <returns>A collection of keys matchig the regular expression.</returns>
public ICollection<string> Match(TernaryTreeSearch<V> pattern) => pattern.Match(this);
/// <summary>
///
/// </summary>
/// <param name="prefix">The prefix to match.</param>
/// <returns>A collection of keys matching the prefix.</returns>
public ICollection<string> MatchPrefix(string prefix)
{
List<string> keys = new List<string>();
Node<V> node = _getFinalNode(prefix, 0, Head);
_getBranchKeys(node, new StringBuilder(), keys);
return keys;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
ICollection<string> IDictionary<string, V>.Keys => Keys();
/// <summary>
///
/// </summary>
/// <returns></returns>
ICollection<V> IDictionary<string, V>.Values => Values();
/// <summary>
///
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return new TernaryTreeEnumerator<V>(this);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
IEnumerator<KeyValuePair<string, V>> IEnumerable<KeyValuePair<string, V>>.GetEnumerator()
{
return new TernaryTreeEnumerator<V>(this);
}
#endregion
#region Remaining Interface Implimentation
/// <summary>
/// Adds a key-value pair to the <see cref="TernaryTree"/>.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add.</param>
public void Add(string key, V value = default(V))
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException(nameof(key));
}
if (Head == null)
{
Head = new Node<V> { Value = key[0] };
}
Node<V> nd = _insertKey(key, 0, Head) ?? throw new ArgumentException(nameof(key));
nd.Data = value;
Count++;
}
/// <summary>
/// Adds a key-value pair to the <see cref="TernaryTree"/>.
/// </summary>
/// <param name="item">A <see cref="KeyValuePair"/> containing a
/// <code>string</code> key and a <code>V</code> value.</param>
public void Add(KeyValuePair<string, V> item) => Add(item.Key, item.Value);
/// <summary>
///
/// </summary>
public void Clear()
{
Head = null;
Count = 0;
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Contains(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException(nameof(key));
}
if (Count == 0)
{
return false;
}
Node<V> node = _getFinalNode(key, 0, Head);
if (node == null)
{
return false;
}
else
{
return true;
}
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(KeyValuePair<string, V> item)
{
// TODO: This has to also chek that values are equal. How do we compare V for equality?
return Contains(item.Key);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool ContainsKey(string key)
{
return Contains(key);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
/// <param name="arrayIndex"></param>
public void CopyTo(KeyValuePair<string, V>[] array, int arrayIndex)
{
_ = array ?? throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
{
throw new IndexOutOfRangeException();
}
// TODO: ICollection API docs want me to do a check for multidimensional array.
// How do I check for multidimensional array?
// Is it even possible to call this with a multidimensional array?
// Seems like it wouldn't compile, given the above signature. (Test this.)
if (Count > array.Length - arrayIndex) // TODO: Test for off by one.
{
throw new ArgumentException($"{nameof(array)} does not have sufficient space");
}
List<string> keys = new List<string>();
_getBranchKeys(Head, new StringBuilder(), keys);
for (int i = 0; i < keys.Count; i++)
{
TryGetValue(keys[i], out V value);
KeyValuePair<string, V> kvPair = new KeyValuePair<string, V>(keys[i], value);
array[arrayIndex++] = kvPair;
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException(nameof(key));
}
Node<V> node = _getFinalNode(key, 0, Head);
if (node == null)
{
return false;
}
node.Data = default(V);
node.IsFinalNode = false;
_pruneDeadBranch(node);
Count--;
return true;
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Remove(KeyValuePair<string, V> item)
{
return Remove(item.Key);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool TryGetValue(string key, out V value)
{
Node<V> node = _getFinalNode(key, 0, Head);
if (node != null)
{
value = node.Data;
return true;
}
value = default(V);
return false;
}
#endregion
#region Private Methods
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="pos"></param>
/// <param name="node"></param>
/// <returns></returns>
private Node<V> _insertKey(string key, int pos, Node<V> node)
{
char keyChar = key[pos];
// Character matches this Node
if (keyChar == node.Value)
{
// This is the last Node for this key
if (pos == key.Length - 1)
{
// Check key collision (identical key already exists)
if (node.IsFinalNode)
{
return null;
}
else
{
node.IsFinalNode = true;
return node;
}
}
// There's more key characters to add
if (node.Equal == null)
{
// TODO: Abstract out Node creation in this method
node.Equal = new Node<V>
{
Value = key[pos + 1],
Parent = node
};
}
return _insertKey(key, ++pos, node.Equal);
}
// Character is lower
else if (keyChar < node.Value)
{
if (node.Smaller == null)
{
node.Smaller = new Node<V>
{
Value = key[pos],
Parent = node
};
}
return _insertKey(key, pos, node.Smaller);
}
// Character is higher
else
{
if (node.Bigger == null)
{
node.Bigger = new Node<V>
{
Value = key[pos],
Parent = node
};
}
return _insertKey(key, pos, node.Bigger);
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="pos"></param>
/// <param name="node"></param>
/// <returns></returns>
private Node<V> _getFinalNode(string key, int pos, Node<V> node)
{
char keyChar = key[pos];
if (keyChar == node.Value)
{
if (pos == key.Length - 1)
{
return node;
}
else if (node.Equal != null)
{
return _getFinalNode(key, ++pos, node.Equal);
}
else return null;
}
else if (keyChar < node.Value)
{
if (node.Smaller != null)
{
return _getFinalNode(key, pos, node.Smaller);
}
else return null;
}
else if (node.Bigger != null)
{
return _getFinalNode(key, pos, node.Bigger);
}
else return null;
}
/// <summary>
///
/// </summary>
/// <param name="head"></param>
/// <param name="keyBuild"></param>
/// <param name="keySet"></param>
private void _getBranchKeys(Node<V> head, StringBuilder keyBuild, IList<string> keySet)
{
if (head.Smaller != null)
{
_getBranchKeys(head.Smaller, new StringBuilder(keyBuild.ToString()), keySet);
}
StringBuilder oldString = new StringBuilder(keyBuild.ToString());
keyBuild.Append(head.Value);
// TODO: Maybe this should be a LinkedList instead of a List?
// Seems like performance would be better.
if (head.IsFinalNode)
{
keySet.Add(keyBuild.ToString());
}
if (head.Equal != null)
{
_getBranchKeys(head.Equal, keyBuild, keySet);
}
if (head.Bigger != null)
{
_getBranchKeys(head.Bigger, oldString, keySet);
}
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
/// <param name="valueSet"></param>
private void _getBranchValues(Node<V> node, IList<V> valueSet)
{
if (node.Smaller != null)
{
_getBranchValues(node.Smaller, valueSet);
}
if (node.IsFinalNode)
{
valueSet.Add(node.Data);
}
if (node.Equal != null)
{
_getBranchValues(node.Equal, valueSet);
}
if (node.Bigger != null)
{
_getBranchValues(node.Bigger, valueSet);
}
}
// TODO: Replace stringbuilder with plain string.
// We end up making a new string builder nearly every step anyway.
// Also, recursive calls allocate new copies of ints and strings (right?), so
// might as well make use of it by doing concatenations there.
private void _getKeyAtIndex(Node<V> node, StringBuilder keyBuild, ref int index, out string s)
{
if (node.Smaller != null)
{
_getKeyAtIndex(node.Smaller, new StringBuilder(keyBuild.ToString()), ref index, out s);
if (!string.IsNullOrEmpty(s))
{
return;
}
}
StringBuilder oldString = new StringBuilder(keyBuild.ToString());
keyBuild.Append(node.Value);
if (node.IsFinalNode)
{
index--;
if (index < 0)
{
s = keyBuild.ToString();
return;
}
}
if (node.Equal != null)
{
_getKeyAtIndex(node.Equal, keyBuild, ref index, out s);
if (!string.IsNullOrEmpty(s))
{
return;
}
}
if (node.Bigger != null)
{
_getKeyAtIndex(node.Bigger, oldString, ref index, out s);
if (!string.IsNullOrEmpty(s))
{
return;
}
}
s = default(string);
}
/// <summary>
/// Removes a branch of unused <see cref="Node"/>s, starting
/// from a leaf and moving up the branch. Only
/// removes <see cref="Node"/>s that have no children. Stops when
/// encountering the first non-removeable <see cref="Node"/>.
/// </summary>
/// <param name="node">The leaf <see cref="Node"/> to check for removal.</param>
private void _pruneDeadBranch(Node<V> node)
{
if (node.Parent == null)
{
return;
}
if (node.Smaller == null && node.Equal == null && node.Bigger == null)
{
Node<V> next = node.Parent;
if (next.Smaller != null && next.Smaller == node)
{
next.Smaller = null;
}
else if (next.Equal != null && next.Equal == node)
{
next.Equal = null;
}
else if (next.Bigger != null && next.Bigger == node)
{
next.Bigger = null;
}
_pruneDeadBranch(next);
}
}
#endregion
}
}
| 31.274571 | 121 | 0.458872 | [
"MIT"
] | agless/Data_Structures | TernaryTree/TernaryTree.cs | 20,049 | C# |
#nullable enable
using System;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace FbxTools.Internal
{
/// <summary>ASCII string which has its own memory by itself.</summary>
[DebuggerDisplay("{ToString()}")]
[StructLayout(LayoutKind.Sequential)]
internal unsafe readonly struct RawStringMem : IDisposable, IEquatable<RawStringMem>
{
private readonly UnmanagedHandle _handle;
private readonly int _byteLength;
public UnmanagedHandle Handle => _handle;
public readonly int ByteLength => _byteLength;
public readonly IntPtr Ptr => _handle.Ptr;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal RawStringMem(int byteLength)
{
Debug.Assert(byteLength >= 0);
if(byteLength == 0) {
this = default;
}
else {
_handle = UnmanagedAllocator.Alloc(byteLength);
_byteLength = byteLength;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly override string ToString()
{
if(_byteLength == 0) { return string.Empty; }
return Encoding.ASCII.GetString((byte*)Ptr, _byteLength);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Span<byte> AsSpan()
{
#if NETSTANDARD2_0
return new Span<byte>((void*)Ptr, _byteLength);
#else
return MemoryMarshal.CreateSpan(ref Unsafe.AsRef<byte>((void*)Ptr), _byteLength);
#endif
}
public RawString AsRawString() => new RawString(Ptr, _byteLength);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
UnmanagedAllocator.Free(_handle);
Unsafe.AsRef(_handle) = UnmanagedHandle.Null;
Unsafe.AsRef(_byteLength) = 0;
}
public override bool Equals(object? obj) => obj is RawStringMem str && Equals(str);
public bool Equals(RawStringMem other) => _handle == other._handle && _byteLength == other._byteLength;
public override int GetHashCode() => HashCode.Combine(_handle, _byteLength);
public static implicit operator RawString(RawStringMem str) => str.AsRawString();
}
}
| 32.438356 | 111 | 0.642736 | [
"MIT"
] | ikorin24/FbxParser | FbxParser/Internal/RawStringMem.cs | 2,370 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DataBoxEdge
{
/// <summary>
/// The Data Box Edge/Gateway device.
/// API Version: 2020-09-01.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:databoxedge:Device")]
public partial class Device : Pulumi.CustomResource
{
/// <summary>
/// Type of compute roles configured.
/// </summary>
[Output("configuredRoleTypes")]
public Output<ImmutableArray<string>> ConfiguredRoleTypes { get; private set; } = null!;
/// <summary>
/// The Data Box Edge/Gateway device culture.
/// </summary>
[Output("culture")]
public Output<string> Culture { get; private set; } = null!;
/// <summary>
/// The status of the Data Box Edge/Gateway device.
/// </summary>
[Output("dataBoxEdgeDeviceStatus")]
public Output<string?> DataBoxEdgeDeviceStatus { get; private set; } = null!;
/// <summary>
/// The Description of the Data Box Edge/Gateway device.
/// </summary>
[Output("description")]
public Output<string> Description { get; private set; } = null!;
/// <summary>
/// The device software version number of the device (eg: 1.2.18105.6).
/// </summary>
[Output("deviceHcsVersion")]
public Output<string> DeviceHcsVersion { get; private set; } = null!;
/// <summary>
/// The Data Box Edge/Gateway device local capacity in MB.
/// </summary>
[Output("deviceLocalCapacity")]
public Output<double> DeviceLocalCapacity { get; private set; } = null!;
/// <summary>
/// The Data Box Edge/Gateway device model.
/// </summary>
[Output("deviceModel")]
public Output<string> DeviceModel { get; private set; } = null!;
/// <summary>
/// The Data Box Edge/Gateway device software version.
/// </summary>
[Output("deviceSoftwareVersion")]
public Output<string> DeviceSoftwareVersion { get; private set; } = null!;
/// <summary>
/// The type of the Data Box Edge/Gateway device.
/// </summary>
[Output("deviceType")]
public Output<string> DeviceType { get; private set; } = null!;
/// <summary>
/// The details of Edge Profile for this resource
/// </summary>
[Output("edgeProfile")]
public Output<Outputs.EdgeProfileResponse> EdgeProfile { get; private set; } = null!;
/// <summary>
/// The etag for the devices.
/// </summary>
[Output("etag")]
public Output<string?> Etag { get; private set; } = null!;
/// <summary>
/// The Data Box Edge/Gateway device name.
/// </summary>
[Output("friendlyName")]
public Output<string> FriendlyName { get; private set; } = null!;
/// <summary>
/// Msi identity of the resource
/// </summary>
[Output("identity")]
public Output<Outputs.ResourceIdentityResponse?> Identity { get; private set; } = null!;
/// <summary>
/// The etag for the devices.
/// </summary>
[Output("kind")]
public Output<string> Kind { get; private set; } = null!;
/// <summary>
/// The location of the device. This is a supported and registered Azure geographical region (for example, West US, East US, or Southeast Asia). The geographical region of a device cannot be changed once it is created, but if an identical geographical region is specified on update, the request will succeed.
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// The description of the Data Box Edge/Gateway device model.
/// </summary>
[Output("modelDescription")]
public Output<string> ModelDescription { get; private set; } = null!;
/// <summary>
/// The object name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The number of nodes in the cluster.
/// </summary>
[Output("nodeCount")]
public Output<int> NodeCount { get; private set; } = null!;
/// <summary>
/// The details of the move operation on this resource.
/// </summary>
[Output("resourceMoveDetails")]
public Output<Outputs.ResourceMoveDetailsResponse> ResourceMoveDetails { get; private set; } = null!;
/// <summary>
/// The Serial Number of Data Box Edge/Gateway device.
/// </summary>
[Output("serialNumber")]
public Output<string> SerialNumber { get; private set; } = null!;
/// <summary>
/// The SKU type.
/// </summary>
[Output("sku")]
public Output<Outputs.SkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// DataBoxEdge Resource
/// </summary>
[Output("systemData")]
public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!;
/// <summary>
/// The list of tags that describe the device. These tags can be used to view and group this device (across resource groups).
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// The Data Box Edge/Gateway device timezone.
/// </summary>
[Output("timeZone")]
public Output<string> TimeZone { get; private set; } = null!;
/// <summary>
/// The hierarchical type of the object.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Device resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Device(string name, DeviceArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:databoxedge:Device", name, args ?? new DeviceArgs(), MakeResourceOptions(options, ""))
{
}
private Device(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:databoxedge:Device", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/latest:Device"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190301:Device"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190701:Device"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20190801:Device"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20200501preview:Device"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20200901:Device"},
new Pulumi.Alias { Type = "azure-nextgen:databoxedge/v20200901preview:Device"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Device resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Device Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Device(name, id, options);
}
}
public sealed class DeviceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The status of the Data Box Edge/Gateway device.
/// </summary>
[Input("dataBoxEdgeDeviceStatus")]
public InputUnion<string, Pulumi.AzureNextGen.DataBoxEdge.DataBoxEdgeDeviceStatus>? DataBoxEdgeDeviceStatus { get; set; }
/// <summary>
/// The device name.
/// </summary>
[Input("deviceName")]
public Input<string>? DeviceName { get; set; }
/// <summary>
/// The etag for the devices.
/// </summary>
[Input("etag")]
public Input<string>? Etag { get; set; }
/// <summary>
/// Msi identity of the resource
/// </summary>
[Input("identity")]
public Input<Inputs.ResourceIdentityArgs>? Identity { get; set; }
/// <summary>
/// The location of the device. This is a supported and registered Azure geographical region (for example, West US, East US, or Southeast Asia). The geographical region of a device cannot be changed once it is created, but if an identical geographical region is specified on update, the request will succeed.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The resource group name.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The SKU type.
/// </summary>
[Input("sku")]
public Input<Inputs.SkuArgs>? Sku { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// The list of tags that describe the device. These tags can be used to view and group this device (across resource groups).
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public DeviceArgs()
{
}
}
}
| 38.939929 | 316 | 0.580762 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataBoxEdge/Device.cs | 11,020 | C# |
using Common.Common;
using Common.Converter;
using Common.Dto;
using Common.Enums;
using Common.Tools;
using Data.Controller;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
namespace Data.Services
{
public delegate void WirelessSwitchDownloadEventHandler(IList<WirelessSwitchDto> wirelessSwitchList, bool success, string response);
public delegate void WirelessSwitchToggleEventHandler(bool success, string response);
public delegate void WirelessSwitchAddEventHandler(bool success, string response);
public delegate void WirelessSwitchUpdateEventHandler(bool success, string response);
public delegate void WirelessSwitchDeleteEventHandler(bool success, string response);
public class WirelessSwitchService
{
private const string TAG = "WirelessSwitchService";
private const int TIMEOUT = 5 * 60 * 1000;
private readonly DownloadController _downloadController;
private static WirelessSwitchService _instance = null;
private static readonly object _padlock = new object();
private IList<WirelessSwitchDto> _wirelessSwitchList = new List<WirelessSwitchDto>();
private Timer _downloadTimer;
WirelessSwitchService()
{
_downloadController = new DownloadController();
_downloadController.OnDownloadFinished += _wirelessSwitchDownloadFinished;
_downloadTimer = new Timer(TIMEOUT);
_downloadTimer.Elapsed += _downloadTimer_Elapsed;
_downloadTimer.AutoReset = true;
_downloadTimer.Start();
}
public event WirelessSwitchDownloadEventHandler OnWirelessSwitchDownloadFinished;
private void publishOnWirelessSwitchDownloadFinished(IList<WirelessSwitchDto> wirelessSwitchList, bool success, string response)
{
OnWirelessSwitchDownloadFinished?.Invoke(wirelessSwitchList, success, response);
}
public event WirelessSwitchToggleEventHandler OnWirelessSwitchToggleFinished;
private void publishOnWirelessSwitchToggleFinished(bool success, string response)
{
OnWirelessSwitchToggleFinished?.Invoke(success, response);
}
public event WirelessSwitchAddEventHandler OnWirelessSwitchAddFinished;
private void publishOnWirelessSwitchAddFinished(bool success, string response)
{
OnWirelessSwitchAddFinished?.Invoke(success, response);
}
public event WirelessSwitchUpdateEventHandler OnWirelessSwitchUpdateFinished;
private void publishOnWirelessSwitchUpdateFinished(bool success, string response)
{
OnWirelessSwitchUpdateFinished?.Invoke(success, response);
}
public event WirelessSwitchDeleteEventHandler OnWirelessSwitchDeleteFinished;
private void publishOnWirelessSwitchDeleteFinished(bool success, string response)
{
OnWirelessSwitchDeleteFinished?.Invoke(success, response);
}
public static WirelessSwitchService Instance
{
get
{
lock (_padlock)
{
if (_instance == null)
{
_instance = new WirelessSwitchService();
}
return _instance;
}
}
}
public IList<WirelessSwitchDto> WirelessSwitchList
{
get
{
return _wirelessSwitchList.OrderBy(wirelessSwitch => wirelessSwitch.TypeId).ToList();
}
}
public WirelessSwitchDto GetByTypeId(int typeId)
{
WirelessSwitchDto foundWirelessSwitch = _wirelessSwitchList
.Where(wirelessSwitch => wirelessSwitch.TypeId == typeId)
.Select(wirelessSwitch => wirelessSwitch)
.FirstOrDefault();
return foundWirelessSwitch;
}
public WirelessSwitchDto GetByName(string name)
{
WirelessSwitchDto foundWirelessSwitch = _wirelessSwitchList
.Where(wirelessSwitch => wirelessSwitch.Name.Equals(name))
.Select(wirelessSwitch => wirelessSwitch)
.FirstOrDefault();
return foundWirelessSwitch;
}
public IList<WirelessSwitchDto> FoundWirelessSwitches(string searchKey)
{
if (searchKey == string.Empty)
{
return _wirelessSwitchList;
}
List<WirelessSwitchDto> foundWirelessSwitchList = _wirelessSwitchList
.Where(wirelessSwitch => wirelessSwitch.ToString().Contains(searchKey))
.Select(wirelessSwitch => wirelessSwitch)
.OrderBy(wirelessSwitch => wirelessSwitch.Area)
.ToList();
return foundWirelessSwitchList;
}
public void LoadWirelessSwitchList()
{
loadWirelessSwitchListAsync();
}
public void ToggleWirelessSwitch(WirelessSwitchDto wirelessSwitch)
{
Logger.Instance.Debug(TAG, string.Format("Toggle switch {0}", wirelessSwitch));
toggleWirelessSwitchAsync(wirelessSwitch.Name);
}
public void ToggleWirelessSwitch(string wirelessSwitchName)
{
Logger.Instance.Debug(TAG, string.Format("Toggle switch {0}", wirelessSwitchName));
toggleWirelessSwitchAsync(wirelessSwitchName);
}
public void AddWirelessSwitch(WirelessSwitchDto wirelessSwitch)
{
Logger.Instance.Debug(TAG, string.Format("AddWirelessSwitch: add switch {0}", wirelessSwitch));
addWirelessSwitchAsync(wirelessSwitch);
}
public void UpdateWirelessSwitch(WirelessSwitchDto wirelessSwitch)
{
Logger.Instance.Debug(TAG, string.Format("UpdateWirelessSwitch: update switch {0}", wirelessSwitch));
updateWirelessSwitchAsync(wirelessSwitch);
}
public void DeleteWirelessSwitch(WirelessSwitchDto wirelessSwitch)
{
Logger.Instance.Debug(TAG, string.Format("DeleteWirelessSwitch: delete switch {0}", wirelessSwitch));
deleteWirelessSwitchAsync(wirelessSwitch);
}
private void _downloadTimer_Elapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
loadWirelessSwitchListAsync();
}
private async Task loadWirelessSwitchListAsync()
{
UserDto user = SettingsController.Instance.User;
if (user == null)
{
publishOnWirelessSwitchDownloadFinished(null, false, "No user");
return;
}
string requestUrl = string.Format("http://{0}{1}{2}&password={3}&action={4}",
SettingsController.Instance.ServerIpAddress, Constants.ACTION_PATH,
user.Name, user.Passphrase,
LucaServerAction.GET_SWITCHES.Action);
_downloadController.SendCommandToWebsite(requestUrl, DownloadType.WirelessSwitch);
}
private async Task toggleWirelessSwitchAsync(string switchName)
{
UserDto user = SettingsController.Instance.User;
if (user == null)
{
publishOnWirelessSwitchToggleFinished(false, "No user");
return;
}
string action = LucaServerAction.TOGGLE_SWITCH.Action + switchName;
string requestUrl = string.Format("http://{0}{1}{2}&password={3}&action={4}",
SettingsController.Instance.ServerIpAddress, Constants.ACTION_PATH,
user.Name, user.Passphrase,
action);
_downloadController.OnDownloadFinished += _toggleWirelessSwitchFinished;
_downloadController.SendCommandToWebsite(requestUrl, DownloadType.WirelessSwitchToggle);
}
private async Task addWirelessSwitchAsync(WirelessSwitchDto wirelessSwitch)
{
UserDto user = SettingsController.Instance.User;
if (user == null)
{
publishOnWirelessSwitchAddFinished(false, "No user");
return;
}
string requestUrl = string.Format("http://{0}{1}{2}&password={3}&action={4}",
SettingsController.Instance.ServerIpAddress, Constants.ACTION_PATH,
user.Name, user.Passphrase,
wirelessSwitch.CommandAdd);
_downloadController.OnDownloadFinished += _addWirelessSwitchFinished;
_downloadController.SendCommandToWebsite(requestUrl, DownloadType.WirelessSwitchAdd);
}
private async Task updateWirelessSwitchAsync(WirelessSwitchDto wirelessSwitch)
{
UserDto user = SettingsController.Instance.User;
if (user == null)
{
publishOnWirelessSwitchUpdateFinished(false, "No user");
return;
}
string requestUrl = string.Format("http://{0}{1}{2}&password={3}&action={4}",
SettingsController.Instance.ServerIpAddress, Constants.ACTION_PATH,
user.Name, user.Passphrase,
wirelessSwitch.CommandUpdate);
_downloadController.OnDownloadFinished += _updateWirelessSwitchFinished;
_downloadController.SendCommandToWebsite(requestUrl, DownloadType.WirelessSwitchUpdate);
}
private async Task deleteWirelessSwitchAsync(WirelessSwitchDto wirelessSwitch)
{
UserDto user = SettingsController.Instance.User;
if (user == null)
{
publishOnWirelessSwitchDeleteFinished(false, "No user");
return;
}
string requestUrl = string.Format("http://{0}{1}{2}&password={3}&action={4}",
SettingsController.Instance.ServerIpAddress, Constants.ACTION_PATH,
user.Name, user.Passphrase,
wirelessSwitch.CommandDelete);
_downloadController.OnDownloadFinished += _deleteWirelessSwitchFinished;
_downloadController.SendCommandToWebsite(requestUrl, DownloadType.WirelessSwitchDelete);
}
private void _wirelessSwitchDownloadFinished(string response, bool success, DownloadType downloadType, object additional)
{
if (downloadType != DownloadType.WirelessSwitch)
{
return;
}
if (response.Contains("Error") || response.Contains("ERROR"))
{
Logger.Instance.Error(TAG, response);
publishOnWirelessSwitchDownloadFinished(null, false, response);
return;
}
if (!success)
{
Logger.Instance.Error(TAG, "Download was not successful!");
publishOnWirelessSwitchDownloadFinished(null, false, response);
return;
}
IList<WirelessSwitchDto> wirelessSwitchList = JsonDataToWirelessSwitchConverter.Instance.GetList(response);
if (wirelessSwitchList == null)
{
Logger.Instance.Error(TAG, "Converted wirelessSwitchList is null!");
publishOnWirelessSwitchDownloadFinished(null, false, response);
return;
}
_wirelessSwitchList = wirelessSwitchList.OrderBy(wirelessSwitch => wirelessSwitch.TypeId).ToList();
publishOnWirelessSwitchDownloadFinished(_wirelessSwitchList, true, response);
}
private void _toggleWirelessSwitchFinished(string response, bool success, DownloadType downloadType, object additional)
{
if (downloadType != DownloadType.WirelessSwitchToggle)
{
return;
}
_downloadController.OnDownloadFinished -= _toggleWirelessSwitchFinished;
if (response.Contains("Error") || response.Contains("ERROR") || response.Contains("0"))
{
Logger.Instance.Error(TAG, response);
publishOnWirelessSwitchToggleFinished(false, response);
return;
}
if (!success)
{
Logger.Instance.Error(TAG, "Setting was not successful!");
publishOnWirelessSwitchToggleFinished(false, response);
return;
}
publishOnWirelessSwitchToggleFinished(true, response);
loadWirelessSwitchListAsync();
}
private void _addWirelessSwitchFinished(string response, bool success, DownloadType downloadType, object additional)
{
if (downloadType != DownloadType.WirelessSwitchAdd)
{
return;
}
_downloadController.OnDownloadFinished -= _addWirelessSwitchFinished;
if (response.Contains("Error") || response.Contains("ERROR") || response.Contains("0"))
{
Logger.Instance.Error(TAG, response);
publishOnWirelessSwitchAddFinished(false, response);
return;
}
if (!success)
{
Logger.Instance.Error(TAG, "Adding was not successful!");
publishOnWirelessSwitchAddFinished(false, response);
return;
}
publishOnWirelessSwitchAddFinished(true, response);
loadWirelessSwitchListAsync();
}
private void _updateWirelessSwitchFinished(string response, bool success, DownloadType downloadType, object additional)
{
if (downloadType != DownloadType.WirelessSwitchUpdate)
{
return;
}
_downloadController.OnDownloadFinished -= _updateWirelessSwitchFinished;
if (response.Contains("Error") || response.Contains("ERROR") || response.Contains("0"))
{
Logger.Instance.Error(TAG, response);
publishOnWirelessSwitchUpdateFinished(false, response);
return;
}
if (!success)
{
Logger.Instance.Error(TAG, "Updating was not successful!");
publishOnWirelessSwitchUpdateFinished(false, response);
return;
}
publishOnWirelessSwitchUpdateFinished(true, response);
loadWirelessSwitchListAsync();
}
private void _deleteWirelessSwitchFinished(string response, bool success, DownloadType downloadType, object additional)
{
if (downloadType != DownloadType.WirelessSwitchDelete)
{
return;
}
_downloadController.OnDownloadFinished -= _deleteWirelessSwitchFinished;
if (response.Contains("Error") || response.Contains("ERROR") || response.Contains("0"))
{
Logger.Instance.Error(TAG, response);
publishOnWirelessSwitchDeleteFinished(false, response);
return;
}
if (!success)
{
Logger.Instance.Error(TAG, "Deleting was not successful!");
publishOnWirelessSwitchDeleteFinished(false, response);
return;
}
publishOnWirelessSwitchDeleteFinished(true, response);
loadWirelessSwitchListAsync();
}
public void Dispose()
{
Logger.Instance.Debug(TAG, "Dispose");
_downloadController.OnDownloadFinished -= _wirelessSwitchDownloadFinished;
_downloadController.OnDownloadFinished -= _toggleWirelessSwitchFinished;
_downloadController.OnDownloadFinished -= _addWirelessSwitchFinished;
_downloadController.OnDownloadFinished -= _updateWirelessSwitchFinished;
_downloadController.OnDownloadFinished -= _deleteWirelessSwitchFinished;
_downloadController.Dispose();
_downloadTimer.Elapsed -= _downloadTimer_Elapsed;
_downloadTimer.AutoReset = false;
_downloadTimer.Stop();
}
}
}
| 38.780952 | 136 | 0.621562 | [
"MIT"
] | FriedrichWilhelmNietzsche/LucaHome-WPFApplication | Data/Services/WirelessSwitchService.cs | 16,290 | C# |
using System.Collections.Generic;
using System.Linq;
namespace FF12RNGHelper.Core
{
/// <summary>
/// The ChestFutureRng object represents the entire
/// foreseeable future of chest related events.
/// </summary>
public class ChestFutureRng : IFutureRng
{
#region privates
private readonly List<ChestFutureRngInstance> _futureRng;
private readonly List<AdvanceDirections> _advanceDirections;
#endregion privates
#region construction/initialization
public ChestFutureRng()
{
_futureRng = new List<ChestFutureRngInstance>();
_advanceDirections = new List<AdvanceDirections>();
}
#endregion construction/initialization
#region public methods
public int GetTotalFutureRngPositions()
{
return _futureRng.Count;
}
/// <summary>
/// Return the number of AdvanceDirections available
/// </summary>
public int GetAdvanceDirectionsCount()
{
return _advanceDirections.Count;
}
/// <summary>
/// Add an RNG instance to the FutureRng object
/// </summary>
public void AddNextRngInstance(ChestFutureRngInstance rngInstance)
{
_futureRng.Add(rngInstance);
}
/// <summary>
/// Gets the RNG position at a given index
/// </summary>
public ChestFutureRngInstance GetRngInstanceAt(int position)
{
return _futureRng.ElementAt(position);
}
/// <summary>
/// Get the Advance Directions for a chest at a given index
/// </summary>
public AdvanceDirections GetAdvanceDirectionsAtIndex(int position)
{
return _advanceDirections.ElementAt(position);
}
/// <summary>
/// Add an AdvanceDirections to the FutureRng object
/// </summary>
/// <param name="advanceDirections"></param>
public void AddAdvanceDirections(AdvanceDirections advanceDirections)
{
_advanceDirections.Add(advanceDirections);
}
#endregion public methods
}
#region public types
/// <summary>
/// A ChestFutureRngInstance represents a single
/// step into the future
/// </summary>
public class ChestFutureRngInstance
{
public bool IsPastRng;
public int Index;
public int CurrentHeal;
public int RandToPercent;
public List<ChestReward> ChestRewards;
public ChestFutureRngInstance(int chestCount)
{
IsPastRng = false;
Index = -1;
CurrentHeal = -1;
RandToPercent = -1;
ChestRewards = new List<ChestReward>();
for (int i = 0; i < chestCount; i++)
{
ChestRewards.Add(new ChestReward());
}
}
}
/// <summary>
/// A ChestReward represents the results of a single chest
/// for a single ChestFutureRngInstance
/// </summary>
public class ChestReward
{
public bool ChestWillSpawn;
public int GilAmount;
public RewardType Reward;
public ChestReward()
{
ChestWillSpawn = false;
GilAmount = -1;
Reward = RewardType.Gil;
}
}
/// <summary>
/// This class is used to store the recommended
/// actions based on info provided
/// </summary>
public class AdvanceDirections
{
public int AdvanceToAppear;
public int AdvanceForItem;
}
/// <summary>
/// Enumeration of the possible chest rewards
/// </summary>
public enum RewardType
{
Gil,
Item1,
Item2
}
#endregion public types
} | 26 | 77 | 0.583203 | [
"MIT"
] | Hoishin/RNGHelper | src/Core/ChestFutureRng.cs | 3,824 | C# |
using System;
namespace CuvooApi.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Describes a type model.
/// </summary>
public abstract class ModelDescription
{
public string Documentation { get; set; }
public Type ModelType { get; set; }
public string Name { get; set; }
}
} | 20.6875 | 51 | 0.616314 | [
"Apache-2.0"
] | adriespina/testcuv | CuvooApi/CuvooApi/Areas/HelpPage/ModelDescriptions/ModelDescription.cs | 331 | C# |
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AppKit;
using Foundation;
using Microsoft.FSharp.Core;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Utilities;
using MonoDevelop.Components.Commands;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Ide.CodeFormatting;
using MonoDevelop.Ide.Commands;
using MonoDevelop.Ide.FindInFiles;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Projects;
using Vim.Extensions;
using Vim.Interpreter;
using Vim.VisualStudio;
using Vim.VisualStudio.Specific;
using Export = System.ComponentModel.Composition.ExportAttribute ;
namespace Vim.Mac
{
[Export(typeof(IVimHost))]
[Export(typeof(VimCocoaHost))]
[ContentType(VimConstants.ContentType)]
[TextViewRole(PredefinedTextViewRoles.Editable)]
internal sealed class VimCocoaHost : IVimHost
{
private readonly ITextBufferFactoryService _textBufferFactoryService;
private readonly ICocoaTextEditorFactoryService _textEditorFactoryService;
private readonly ISmartIndentationService _smartIndentationService;
private readonly IExtensionAdapterBroker _extensionAdapterBroker;
private IVim _vim;
internal const string CommandNameGoToDefinition = "MonoDevelop.Refactoring.RefactoryCommands.GotoDeclaration";
[ImportingConstructor]
public VimCocoaHost(
ITextBufferFactoryService textBufferFactoryService,
ICocoaTextEditorFactoryService textEditorFactoryService,
ISmartIndentationService smartIndentationService,
IExtensionAdapterBroker extensionAdapterBroker)
{
VimTrace.TraceSwitch.Level = System.Diagnostics.TraceLevel.Verbose;
Console.WriteLine("Loaded");
_textBufferFactoryService = textBufferFactoryService;
_textEditorFactoryService = textEditorFactoryService;
_smartIndentationService = smartIndentationService;
_extensionAdapterBroker = extensionAdapterBroker;
}
public bool AutoSynchronizeSettings => false;
public DefaultSettings DefaultSettings => DefaultSettings.GVim74;
public string HostIdentifier => VimSpecificUtil.HostIdentifier;
public bool IsAutoCommandEnabled => false;
public bool IsUndoRedoExpected => _extensionAdapterBroker.IsUndoRedoExpected ?? false;
public int TabCount => IdeApp.Workbench.Documents.Count;
public bool UseDefaultCaret => true;
public event EventHandler<TextViewEventArgs> IsVisibleChanged;
public event EventHandler<TextViewChangedEventArgs> ActiveTextViewChanged;
public event EventHandler<BeforeSaveEventArgs> BeforeSave;
private ITextView TextViewFromDocument(Document document)
{
return document?.GetContent<ITextView>();
}
private Document DocumentFromTextView(ITextView textView)
{
return IdeApp.Workbench.Documents.FirstOrDefault(doc => TextViewFromDocument(doc) == textView);
}
private Document DocumentFromTextBuffer(ITextBuffer textBuffer)
{
return IdeApp.Workbench.Documents.FirstOrDefault(doc => doc.TextBuffer == textBuffer);
}
private static NSSound GetBeepSound()
{
using (var stream = typeof(VimCocoaHost).Assembly.GetManifestResourceStream("Vim.Mac.Resources.beep.wav"))
using (NSData data = NSData.FromStream(stream))
{
return new NSSound(data);
}
}
readonly Lazy<NSSound> beep = new Lazy<NSSound>(() => GetBeepSound());
public void Beep()
{
beep.Value.Play();
}
public void BeginBulkOperation()
{
}
public void Close(ITextView textView)
{
Dispatch(FileCommands.CloseFile);
}
public void CloseAllOtherTabs(ITextView textView)
{
Dispatch(FileTabCommands.CloseAllButThis);
}
public void CloseAllOtherWindows(ITextView textView)
{
Dispatch(FileTabCommands.CloseAllButThis);
}
/// <summary>
/// Create a hidden ITextView. It will have no roles in order to keep it out of
/// most plugins
/// </summary>
public ITextView CreateHiddenTextView()
{
return _textEditorFactoryService.CreateTextView(
_textBufferFactoryService.CreateTextBuffer(),
_textEditorFactoryService.NoRoles);
}
public void DoActionWhenTextViewReady(FSharpFunc<Unit, Unit> action, ITextView textView)
{
// Perform action if the text view is still open.
if (!textView.IsClosed && !textView.InLayout)
{
action.Invoke(null);
}
}
public void EndBulkOperation()
{
}
public void EnsurePackageLoaded()
{
LoggingService.LogDebug("EnsurePackageLoaded");
}
// TODO: Same as WPF version
/// <summary>
/// Ensure the given SnapshotPoint is visible on the screen
/// </summary>
public void EnsureVisible(ITextView textView, SnapshotPoint point)
{
try
{
// Intentionally breaking up these tasks into different steps. The act of making the
// line visible can actually invalidate the ITextViewLine instance and cause it to
// throw when we access it for making the point visible. Breaking it into separate
// steps so each one has to requery the current and valid information
EnsureLineVisible(textView, point);
EnsureLinePointVisible(textView, point);
}
catch (Exception)
{
// The ITextViewLine implementation can throw if this code runs in the middle of
// a layout or if the line believes itself to be invalid. Hard to completely guard
// against this
}
}
/// <summary>
/// Do the vertical scrolling necessary to make sure the line is visible
/// </summary>
private void EnsureLineVisible(ITextView textView, SnapshotPoint point)
{
const double roundOff = 0.01;
var textViewLine = textView.GetTextViewLineContainingBufferPosition(point);
if (textViewLine == null)
{
return;
}
switch (textViewLine.VisibilityState)
{
case VisibilityState.FullyVisible:
// If the line is fully visible then no scrolling needs to occur
break;
case VisibilityState.Hidden:
case VisibilityState.PartiallyVisible:
{
ViewRelativePosition? pos = null;
if (textViewLine.Height <= textView.ViewportHeight + roundOff)
{
// The line fits into the view. Figure out if it needs to be at the top
// or the bottom
pos = textViewLine.Top < textView.ViewportTop
? ViewRelativePosition.Top
: ViewRelativePosition.Bottom;
}
else if (textViewLine.Bottom < textView.ViewportBottom)
{
// Line does not fit into view but we can use more space at the bottom
// of the view
pos = ViewRelativePosition.Bottom;
}
else if (textViewLine.Top > textView.ViewportTop)
{
pos = ViewRelativePosition.Top;
}
if (pos.HasValue)
{
textView.DisplayTextLineContainingBufferPosition(point, 0.0, pos.Value);
}
}
break;
case VisibilityState.Unattached:
{
var pos = textViewLine.Start < textView.TextViewLines.FormattedSpan.Start && textViewLine.Height <= textView.ViewportHeight + roundOff
? ViewRelativePosition.Top
: ViewRelativePosition.Bottom;
textView.DisplayTextLineContainingBufferPosition(point, 0.0, pos);
}
break;
}
}
/// <summary>
/// Do the horizontal scrolling necessary to make the column of the given point visible
/// </summary>
private void EnsureLinePointVisible(ITextView textView, SnapshotPoint point)
{
var textViewLine = textView.GetTextViewLineContainingBufferPosition(point);
if (textViewLine == null)
{
return;
}
const double horizontalPadding = 2.0;
const double scrollbarPadding = 200.0;
var scroll = Math.Max(
horizontalPadding,
Math.Min(scrollbarPadding, textView.ViewportWidth / 4));
var bounds = textViewLine.GetCharacterBounds(point);
if (bounds.Left - horizontalPadding < textView.ViewportLeft)
{
textView.ViewportLeft = bounds.Left - scroll;
}
else if (bounds.Right + horizontalPadding > textView.ViewportRight)
{
textView.ViewportLeft = (bounds.Right + scroll) - textView.ViewportWidth;
}
}
public void FindInFiles(string pattern, bool matchCase, string filesOfType, VimGrepFlags flags, FSharpFunc<Unit, Unit> action)
{
var find = new FindReplace();
var options = new FilterOptions
{
CaseSensitive = matchCase,
RegexSearch = true,
};
var scope = new ShellWildcardSearchScope(_vim.VimData.CurrentDirectory, filesOfType);
using (var monitor = IdeApp.Workbench.ProgressMonitors.GetSearchProgressMonitor(true))
{
var results = find.FindAll(scope, monitor, pattern, null, options, System.Threading.CancellationToken.None);
foreach (var result in results)
{
//TODO: Cancellation?
monitor.ReportResult(result);
}
}
action.Invoke(null);
}
public void FormatLines(ITextView textView, SnapshotLineRange range)
{
var startedWithSelection = !textView.Selection.IsEmpty;
textView.Selection.Clear();
textView.Selection.Select(range.ExtentIncludingLineBreak, false);
// FormatBuffer command actually formats the selection
Dispatch(CodeFormattingCommands.FormatBuffer);
if (!startedWithSelection)
{
textView.Selection.Clear();
}
}
public FSharpOption<ITextView> GetFocusedTextView()
{
var doc = IdeServices.DocumentManager.ActiveDocument;
return FSharpOption.CreateForReference(TextViewFromDocument(doc));
}
public string GetName(ITextBuffer textBuffer)
{
if (textBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDocument) && textDocument.FilePath != null)
{
return textDocument.FilePath;
}
else
{
LoggingService.LogWarning("VsVim: Failed to get filename of textbuffer.");
return "";
}
}
//TODO: Copied from VsVimHost
public FSharpOption<int> GetNewLineIndent(ITextView textView, ITextSnapshotLine contextLine, ITextSnapshotLine newLine, IVimLocalSettings localSettings)
{
//if (_vimApplicationSettings.UseEditorIndent)
//{
var indent = _smartIndentationService.GetDesiredIndentation(textView, newLine);
if (indent.HasValue)
{
return FSharpOption.Create(indent.Value);
}
else
{
// If the user wanted editor indentation but the editor doesn't support indentation
// even though it proffers an indentation service then fall back to what auto
// indent would do if it were enabled (don't care if it actually is)
//
// Several editors like XAML offer the indentation service but don't actually
// provide information. User clearly wants indent there since the editor indent
// is enabled. Do a best effort and use Vim style indenting
return FSharpOption.Create(EditUtil.GetAutoIndent(contextLine, localSettings.TabStop));
}
//}
//return FSharpOption<int>.None;
}
public int GetTabIndex(ITextView textView)
{
var notebooks = WindowManagement.GetNotebooks();
foreach (var notebook in notebooks)
{
var index = notebook.FileNames.IndexOf(GetName(textView.TextBuffer));
if (index != -1)
{
return index;
}
}
return -1;
}
public WordWrapStyles GetWordWrapStyle(ITextView textView)
{
throw new NotImplementedException();
}
public bool GoToDefinition()
{
return Dispatch(CommandNameGoToDefinition);
}
public bool GoToGlobalDeclaration(ITextView textView, string identifier)
{
return Dispatch(CommandNameGoToDefinition);
}
public bool GoToLocalDeclaration(ITextView textView, string identifier)
{
return Dispatch(CommandNameGoToDefinition);
}
private void OpenTab(string fileName)
{
Project project = null;
IdeApp.Workbench.OpenDocument(fileName, project);
}
public void GoToTab(int index)
{
var activeNotebook = WindowManagement.GetNotebooks().First(n => n.IsActive);
var fileName = activeNotebook.FileNames[index];
OpenTab(fileName);
}
private void SwitchToNotebook(Notebook notebook)
{
OpenTab(notebook.FileNames[notebook.ActiveTab]);
}
public void GoToWindow(ITextView textView, WindowKind direction, int count)
{
// In VSMac, there are just 2 windows, left and right
var notebooks = WindowManagement.GetNotebooks();
if (notebooks.Length > 0 && notebooks[0].IsActive && (direction == WindowKind.Right || direction == WindowKind.Previous || direction == WindowKind.Next))
{
SwitchToNotebook(notebooks[1]);
}
if (notebooks.Length > 0 && notebooks[1].IsActive && (direction == WindowKind.Left || direction == WindowKind.Previous || direction == WindowKind.Next))
{
SwitchToNotebook(notebooks[0]);
}
}
public bool IsDirty(ITextBuffer textBuffer)
{
var doc = DocumentFromTextBuffer(textBuffer);
return doc.IsDirty;
}
public bool IsFocused(ITextView textView)
{
return TextViewFromDocument(IdeServices.DocumentManager.ActiveDocument) == textView;
}
public bool IsReadOnly(ITextBuffer textBuffer)
{
var doc = DocumentFromTextBuffer(textBuffer);
return doc.IsViewOnly;
}
public bool IsVisible(ITextView textView)
{
return IdeServices.DocumentManager.Documents.Select(TextViewFromDocument).Any(v => v == textView);
}
public bool LoadFileIntoExistingWindow(string filePath, ITextView textView)
{
// filePath can be a wildcard representing multiple files
// e.g. :e ~/src/**/*.cs
var files = ShellWildcardExpansion.ExpandWildcard(filePath, _vim.VimData.CurrentDirectory);
try
{
foreach (var file in files)
{
OpenTab(file);
}
return true;
}
catch
{
return false;
}
}
public FSharpOption<ITextView> LoadFileIntoNewWindow(string filePath, FSharpOption<int> line, FSharpOption<int> column)
{
if (File.Exists(filePath))
{
var document = IdeApp.Workbench.OpenDocument(filePath, null, line.SomeOrDefault(0), column.SomeOrDefault(0)).Result;
var textView = TextViewFromDocument(document);
return FSharpOption.CreateForReference(textView);
}
return FSharpOption<ITextView>.None;
}
public void Make(bool jumpToFirstError, string arguments)
{
Dispatch(ProjectCommands.Build);
}
public bool NavigateTo(VirtualSnapshotPoint point)
{
var tuple = SnapshotPointUtil.GetLineNumberAndOffset(point.Position);
var line = tuple.Item1;
var column = tuple.Item2;
var buffer = point.Position.Snapshot.TextBuffer;
var fileName = GetName(buffer);
try
{
IdeApp.Workbench.OpenDocument(fileName, null, line, column).Wait(System.Threading.CancellationToken.None);
return true;
}
catch
{
return false;
}
}
public FSharpOption<ListItem> NavigateToListItem(ListKind listKind, NavigationKind navigationKind, FSharpOption<int> argumentOption, bool hasBang)
{
if (listKind == ListKind.Error)
{
var errors = IdeServices.TaskService.Errors;
if (errors.Count > 0)
{
var argument = argumentOption.IsSome() ? new int?(argumentOption.Value) : null;
var currentIndex = errors.CurrentLocationTask == null ? -1 : errors.IndexOf(errors.CurrentLocationTask);
var index = GetListItemIndex(navigationKind, argument, currentIndex, errors.Count);
if (index.HasValue)
{
var errorItem = errors.ElementAt(index.Value);
errors.CurrentLocationTask = errorItem;
errorItem.SelectInPad();
errorItem.JumpToPosition();
// Item number is one-based.
var listItem = new ListItem(index.Value + 1, errors.Count, errorItem.Message);
return FSharpOption.CreateForReference(listItem);
}
}
}
return FSharpOption<ListItem>.None;
}
/// <summary>
/// Convert the specified navigation instructions into an index for the
/// new list item
/// </summary>
/// <param name="navigationKind">the kind of navigation</param>
/// <param name="argument">an optional argument for the navigation</param>
/// <param name="current">the zero-based index of the current list item</param>
/// <param name="length">the length of the list</param>
/// <returns>a zero-based index into the list</returns>
private static int? GetListItemIndex(NavigationKind navigationKind, int? argument, int? current, int length)
{
var argumentOffset = argument ?? 1;
var currentIndex = current ?? -1;
var newIndex = -1;
// The 'first' and 'last' navigation kinds are one-based.
switch (navigationKind)
{
case NavigationKind.First:
newIndex = argument.HasValue ? argument.Value - 1 : 0;
break;
case NavigationKind.Last:
newIndex = argument.HasValue ? argument.Value - 1 : length - 1;
break;
case NavigationKind.Next:
newIndex = currentIndex + argumentOffset;
break;
case NavigationKind.Previous:
newIndex = currentIndex - argumentOffset;
break;
default:
Contract.Assert(false);
break;
}
if (newIndex >= 0 && newIndex < length)
{
return newIndex;
}
return null;
}
public bool OpenLink(string link)
{
return NSWorkspace.SharedWorkspace.OpenUrl(new NSUrl(link));
}
public void OpenListWindow(ListKind listKind)
{
if (listKind == ListKind.Error)
{
GotoPad("MonoDevelop.Ide.Gui.Pads.ErrorListPad");
return;
}
if (listKind == ListKind.Location)
{
// This abstraction is not quite right as VSMac can have multiple search results pads open
GotoPad("SearchPad - Search Results - 0");
return;
}
}
private void GotoPad(string padId)
{
var pad = IdeApp.Workbench.Pads.FirstOrDefault(p => p.Id == padId);
pad?.BringToFront(true);
}
public void Quit()
{
IdeApp.Exit();
}
public bool Reload(ITextView textView)
{
var doc = DocumentFromTextView(textView);
doc.Reload();
return true;
}
/// <summary>
/// Run the specified command on the supplied input, capture it's output and
/// return it to the caller
/// </summary>
public RunCommandResults RunCommand(string workingDirectory, string command, string arguments, string input)
{
// Use a (generous) timeout since we have no way to interrupt it.
var timeout = 30 * 1000;
// Avoid redirection for the 'open' command.
var doRedirect = !arguments.StartsWith("/c open ", StringComparison.CurrentCulture);
//TODO: '/c is CMD.exe specific'
if(arguments.StartsWith("/c ", StringComparison.CurrentCulture))
{
arguments = "-c " + arguments.Substring(3);
}
// Populate the start info.
var startInfo = new ProcessStartInfo
{
WorkingDirectory = workingDirectory,
FileName = "zsh",
Arguments = arguments,
UseShellExecute = false,
RedirectStandardInput = doRedirect,
RedirectStandardOutput = doRedirect,
RedirectStandardError = doRedirect,
CreateNoWindow = true,
};
// Start the process and tasks to manage the I/O.
try
{
var process = Process.Start(startInfo);
if (doRedirect)
{
var stdin = process.StandardInput;
var stdout = process.StandardOutput;
var stderr = process.StandardError;
var stdinTask = Task.Run(() => { stdin.Write(input); stdin.Close(); });
var stdoutTask = Task.Run(stdout.ReadToEnd);
var stderrTask = Task.Run(stderr.ReadToEnd);
if (process.WaitForExit(timeout))
{
return new RunCommandResults(process.ExitCode, stdoutTask.Result, stderrTask.Result);
}
}
else
{
if (process.WaitForExit(timeout))
{
return new RunCommandResults(process.ExitCode, String.Empty, String.Empty);
}
}
throw new TimeoutException();
}
catch (Exception ex)
{
return new RunCommandResults(-1, "", ex.Message);
}
}
public void RunCSharpScript(IVimBuffer vimBuffer, CallInfo callInfo, bool createEachTime)
{
throw new NotImplementedException();
}
public void RunHostCommand(ITextView textView, string commandName, string argument)
{
Dispatch(commandName, argument);
}
public bool Save(ITextBuffer textBuffer)
{
var doc = DocumentFromTextBuffer(textBuffer);
try
{
doc.Save();
return true;
}
catch (Exception)
{
return false;
}
}
public bool SaveTextAs(string text, string filePath)
{
try
{
File.WriteAllText(filePath, text);
return true;
}
catch (Exception)
{
return false;
}
}
public bool ShouldCreateVimBuffer(ITextView textView)
{
return textView.Roles.Contains(PredefinedTextViewRoles.PrimaryDocument);
}
public bool ShouldIncludeRcFile(VimRcPath vimRcPath)
{
return File.Exists(vimRcPath.FilePath);
}
public void SplitViewHorizontally(ITextView value)
{
Dispatch("MonoDevelop.Ide.Commands.ViewCommands.SideBySideMode");
}
public void SplitViewVertically(ITextView value)
{
Dispatch("MonoDevelop.Ide.Commands.ViewCommands.SideBySideMode");
}
public void StartShell(string workingDirectory, string file, string arguments)
{
IdeServices.DesktopService.OpenTerminal(workingDirectory);
}
public bool TryCustomProcess(ITextView textView, InsertCommand command)
{
//throw new NotImplementedException();
return false;
}
public void VimCreated(IVim vim)
{
_vim = vim;
}
public void VimRcLoaded(VimRcState vimRcState, IVimLocalSettings localSettings, IVimWindowSettings windowSettings)
{
//throw new NotImplementedException();
}
bool Dispatch(object command, string argument = null)
{
try
{
return IdeApp.CommandService.DispatchCommand(command, argument);
}
catch
{
return false;
}
}
}
}
| 36.163804 | 165 | 0.561148 | [
"Apache-2.0"
] | FelixBoers/VsVim | Src/VimMac/VimHost.cs | 27,378 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.ProjectModel;
namespace NuGet.PackageManagement.VisualStudio
{
public class VSRestoreSettingsUtilities
{
public static string AdditionalValue = "$Additional$";
public static string GetPackagesPath(ISettings settings, PackageSpec project)
{
// Set from Settings if not given. Clear is not an option here.
if (string.IsNullOrEmpty(project.RestoreMetadata.PackagesPath))
{
return SettingsUtility.GetGlobalPackagesFolder(settings);
}
// Resolve relative paths
return UriUtility.GetAbsolutePathFromFile(
sourceFile: project.RestoreMetadata.ProjectPath,
path: project.RestoreMetadata.PackagesPath);
}
/// <summary>
/// This method receives the entries in the following format
/// [ [ [values..] AdditionalValue ] additionalValues..]
/// It then outputs a tuple where the entries before AdditionalValue are in Item1 and the additionalValues are in item2.
/// All values are optional.
/// For correctness the input to this method should have been created by calling <see cref="GetEntriesWithAdditional(string[], string[])"/>
/// </summary>
private static Tuple<IList<string>, IList<string>> ProcessEntriesWithAdditional(IEnumerable<string> entries)
{
var actualEntries = new List<string>();
var additionalEntries = new List<string>();
var readingAdditional = false;
foreach (var entry in entries)
{
if (StringComparer.Ordinal.Equals(AdditionalValue, entry))
{
readingAdditional = true;
}
else
{
if (readingAdditional)
{
additionalEntries.Add(entry);
}
else
{
actualEntries.Add(entry);
}
}
}
return new Tuple<IList<string>, IList<string>>(actualEntries, additionalEntries);
}
public static IList<PackageSource> GetSources(ISettings settings, PackageSpec project)
{
var results = ProcessEntriesWithAdditional(project.RestoreMetadata.Sources.Select(e => e.Source).ToList());
var sources = results.Item1;
var additionalSources = results.Item2;
var processedSources = (
ShouldReadFromSettings(sources) ?
SettingsUtility.GetEnabledSources(settings).Select(e => e.Source) :
HandleClear(sources))
.Concat(additionalSources);
// Resolve relative paths
return processedSources.Select(e => new PackageSource(
UriUtility.GetAbsolutePathFromFile(
sourceFile: project.RestoreMetadata.ProjectPath,
path: e)))
.ToList();
}
public static IList<string> GetFallbackFolders(ISettings settings, PackageSpec project)
{
var results = ProcessEntriesWithAdditional(project.RestoreMetadata.FallbackFolders);
var fallbackFolders = results.Item1;
var additionalFallbackFolders = results.Item2;
var processedFallbackFolders = (
ShouldReadFromSettings(fallbackFolders) ?
SettingsUtility.GetFallbackPackageFolders(settings) :
HandleClear(fallbackFolders))
.Concat(additionalFallbackFolders);
// Resolve relative paths
return processedFallbackFolders.Select(e =>
UriUtility.GetAbsolutePathFromFile(
sourceFile: project.RestoreMetadata.ProjectPath,
path: e))
.ToList();
}
private static bool ShouldReadFromSettings(IEnumerable<string> values)
{
return !values.Any() && !MSBuildRestoreUtility.ContainsClearKeyword(values);
}
public static IEnumerable<string> HandleClear(IEnumerable<string> values)
{
if ((MSBuildRestoreUtility.ContainsClearKeyword(values)))
{
return Enumerable.Empty<string>();
}
return values;
}
/// <summary>
/// This method combine the values and additionalValues into a format as below
/// [ [ [values..] AdditionalValue ] additionalValues..]
/// IF additionalValues does not have any elements then the additionalValue keyword will not be added, the return value will be equivalent to the first element, whatever it may be.
/// The <see cref="ProcessEntriesWithAdditional(IEnumerable{string})"/>does the reverse.
/// </summary>
public static IEnumerable<string> GetEntriesWithAdditional(string[] values, string[] additional)
{
return additional.Length != 0 ?
(values.Concat(new string[] { AdditionalValue }).Concat(additional)) :
values;
}
}
}
| 39.556338 | 188 | 0.593199 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/VSRestoreSettingsUtilities.cs | 5,617 | C# |
using System;
using System.Diagnostics;
using System.Linq;
using FhirStarter.STU3.Detonator.DotNetCore3.Filter;
using FhirStarter.STU3.Detonator.DotNetCore3.Formatters;
using FhirStarter.STU3.Instigator.DotNetCore3.Configuration;
using FhirStarter.STU3.Instigator.DotNetCore3.Diagnostics;
using FhirStarter.STU3.Instigator.DotNetCore3.Helper;
using FhirStarter.STU3.Instigator.DotNetCore3.Model;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FhirStarter.STU3.Twisted.DotNetCore3
{
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)
{
FhirDotnet3Setup(services);
}
// copy this method to your Startup
public void FhirDotnet3Setup(IServiceCollection services)
{
var appSettings =
StartupConfigHelper.BuildConfigurationFromJson(AppContext.BaseDirectory, "appsettings.json");
FhirStarterConfig.SetupFhir(services, appSettings, CompatibilityVersion.Version_3_0);
var detonator = FhirStarterConfig.GetDetonatorAssembly(appSettings["FhirStarterSettings:FhirDetonatorAssembly"]);
var instigator = FhirStarterConfig.GetInstigatorAssembly(appSettings["FhirStarterSettings:FhirInstigatorAssembly"]);
services.Configure<FhirStarterSettings>(appSettings.GetSection(nameof(FhirStarterSettings)));
services.AddRouting();
services.AddControllers(controller =>
{
controller.OutputFormatters.Clear();
controller.InputFormatters.Clear();
controller.RespectBrowserAcceptHeader = true;
// output
controller.OutputFormatters.Add(new JsonFhirFormatterDotNetCore3());
controller.OutputFormatters.Add(new XmlFhirSerializerOutputFormatterDotNetCore3());
controller.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
// input
controller.InputFormatters.Add(new JsonFhirInputFormatter());
controller.InputFormatters.Add(new XmlFhirSerializerInputFormatterDotNetCore3());
controller.Filters.Add(typeof(FhirExceptionFilter));
})
.AddApplicationPart(instigator).AddApplicationPart(detonator).AddControllersAsServices()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddHttpContextAccessor();
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
config.OutputFormatters.Add(new JsonFhirFormatterDotNetCore3());
config.OutputFormatters.Add(new XmlFhirSerializerOutputFormatterDotNetCore3());
config.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
});
services.AddSingleton<DiagnosticObserver>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
DiagnosticListener diagnosticListenerSource, DiagnosticObserver diagnosticObserver)
{
diagnosticListenerSource.Subscribe(diagnosticObserver);
app.UseRouting();
app.UseAuthorization();
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 41.616162 | 128 | 0.674515 | [
"MIT"
] | Helse-Nord-IKT-Integrasjonsutvikling/FhirStarter.DotNetCore3.0 | src/STU3/FhirStarter.STU3.Twisted.DotNetCore3/Startup.cs | 4,120 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/IPTypes.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IP_ADDR_STRING" /> struct.</summary>
public static unsafe partial class IP_ADDR_STRINGTests
{
/// <summary>Validates that the <see cref="IP_ADDR_STRING" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IP_ADDR_STRING>(), Is.EqualTo(sizeof(IP_ADDR_STRING)));
}
/// <summary>Validates that the <see cref="IP_ADDR_STRING" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IP_ADDR_STRING).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IP_ADDR_STRING" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IP_ADDR_STRING), Is.EqualTo(48));
}
else
{
Assert.That(sizeof(IP_ADDR_STRING), Is.EqualTo(40));
}
}
}
}
| 35.772727 | 145 | 0.632147 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/IPTypes/IP_ADDR_STRINGTests.cs | 1,576 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;
using log4net;
using Xiant.Common;
using Xiant.Filer.Core;
using Xiant.Filer.Resources;
using OLK = Microsoft.Office.Interop.Outlook;
namespace Xiant.Filer.UI.Common
{
public class FolderPickerViewResources
{
public FolderPickerViewResources()
{
Title = Strings.FolderPickerDialogTitle;
OkayButtonCaption = Strings.FilerOK;
NewFolderVisible = true;
}
public string Title { get; set; }
public string OkayButtonCaption { get; set; }
public string Instructions { get; set; }
public bool NewFolderVisible { get; set; }
}
public static class OpenFolderPickerDialog
{
public static OLK.MAPIFolder PickFolder(OLK.NameSpace session, IFolders folders, IntPtr parentHandle, OLK.MAPIFolder selectedFolder)
{
var viewResources = new FolderPickerViewResources
{
Title = Strings.OpenFolderPickerDialogTitle,
Instructions = Strings.OpenFolderPickerDialogInstructions,
OkayButtonCaption = Strings.FilerOpen,
NewFolderVisible = false
};
return FolderPickerDialog.PickFolder(session, folders, parentHandle, viewResources, FolderReference.FromFolder(selectedFolder));
}
}
public static class MoveToFolderPickerDialog
{
public static OLK.MAPIFolder PickFolder(OLK.NameSpace session, IFolders folders, IntPtr parentHandle, MoveToFolderType moveType, OutlookSelection selection)
{
UpdateLastSelected(session);
var isMultipleSelect = selection?.IsMultipleSelect ?? false;
var isMultipleThreads = selection?.IsMultipleThreads ?? false;
var viewResources = new FolderPickerViewResources { Instructions = CreateInstructionsString(moveType, isMultipleSelect, isMultipleThreads) };
var pickedFolder = FolderPickerDialog.PickFolder(session, folders, parentHandle, viewResources, LastSelected);
if (null != pickedFolder && FilerConfig.Singleton.RememberLastMoveToFolder) LastSelected = FolderReference.FromFolder(pickedFolder);
return pickedFolder;
}
private static FolderReference LastSelected { get; set; }
private static void UpdateLastSelected(OLK._NameSpace session)
{
OLK.MAPIFolder mailbox = null;
OLK.MAPIFolder inbox = null;
try
{
if (null != LastSelected)
return;
inbox = session.GetDefaultFolder(OLK.OlDefaultFolders.olFolderInbox);
mailbox = inbox.Parent as OLK.MAPIFolder;
LastSelected = FolderReference.FromFolder(mailbox ?? inbox);
}
finally
{
if (null != mailbox)
{
RCWHelper.Release(mailbox);
mailbox = null;
}
if (null != inbox)
{
RCWHelper.Release(inbox);
inbox = null;
}
}
}
private static string CreateInstructionsString(MoveToFolderType moveType, bool isMultipleSelect, bool isMultipleThreads)
{
string moveSpecificString;
switch (moveType)
{
case MoveToFolderType.Message:
moveSpecificString = isMultipleSelect ?
Strings.FolderPickerInstructionsMultipleMessages :
Strings.FolderPickerInstructionsSingleMessage;
break;
case MoveToFolderType.Thread:
moveSpecificString = isMultipleThreads ?
Strings.FolderPickerInstructionsMultipleThreads :
Strings.FolderPickerInstructionsSingleThread;
break;
case MoveToFolderType.PreviousInThread:
moveSpecificString = isMultipleThreads ?
Strings.FolderPickerInstructionsMultiplePreviousThreads :
Strings.FolderPickerInstructionsSinglePreviousThread;
break;
case MoveToFolderType.Sender:
moveSpecificString = isMultipleSelect ?
Strings.FolderPickerInstructionsMultipleSenders :
Strings.FolderPickerInstructionsSingleSender;
break;
case MoveToFolderType.PreviousFromSender:
moveSpecificString = isMultipleSelect ?
Strings.FolderPickerInstructionsMultiplePreviousSenders :
Strings.FolderPickerInstructionsSinglePreviousSender;
break;
default:
moveSpecificString = Strings.FolderPickerInstructionsUnknown;
break;
}
return string.Format(CultureInfo.CurrentCulture, Strings.FolderPickerInstructionsFullString, moveSpecificString);
}
}
internal static class FolderPickerDialog
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static OLK.MAPIFolder PickFolder(OLK.NameSpace session, IFolders folders, IntPtr parentHandle, FolderPickerViewResources viewResources, FolderReference selectedFolder)
{
OLK.MAPIFolder pickedFolder = null;
if (null == SynchronizationContext.Current) SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
var view = new FolderPickerView(viewResources);
var model = new FolderPickerViewModel(new FolderSetViewModel(folders, SynchronizationContext.Current), session, folders);
var helper = new WindowInteropHelper(view) { Owner = parentHandle };
try
{
model.SelectedFolder = selectedFolder;
view.DataContext = model;
view.Height = Math.Max(FilerConfig.Singleton.MoveToFolderSize.Height, view.MinHeight);
view.Width = Math.Max(FilerConfig.Singleton.MoveToFolderSize.Width, view.MinWidth);
view.ShowDialog();
RememberSize(view);
if (model.UserSelectedOutlookFolderPicker)
{
try
{
pickedFolder = session.PickFolder();
}
catch (COMException cex)
{
ComTracing.WriteError("Exception with Outlook Folder Picker dialog", cex, Log);
}
}
else if (model.SelectionAccepted)
{
var folder = model.SelectedFolder;
pickedFolder = session.GetFolderFromID(folder.EntryId, folder.StoreId);
}
}
finally
{
view.DataContext = null;
model.Dispose();
}
return pickedFolder;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Catch any exceptions caused by the Save()")]
private static void RememberSize(FrameworkElement view)
{
try
{
FilerConfig.Singleton.MoveToFolderSize = new Size(view.Width, view.Height);
FilerConfig.Singleton.Save();
}
catch(Exception ex)
{
Log.Error(ex);
}
}
}
}
| 39.879397 | 182 | 0.595388 | [
"Apache-2.0"
] | VulcanTechnologies/XiantFiler | Filer.Addin.UI.Common/FolderPicker/FolderPickerDialog.cs | 7,938 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Maui.Controls.Internals;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Handlers;
namespace Microsoft.Maui.Controls
{
public partial class Application : Element, IResourcesProvider, IApplicationController, IElementConfiguration<Application>, IVisualTreeElement
{
readonly WeakEventManager _weakEventManager = new WeakEventManager();
Task<IDictionary<string, object>>? _propertiesTask;
readonly Lazy<PlatformConfigurationRegistry<Application>> _platformConfigurationRegistry;
readonly Lazy<IResourceDictionary> _systemResources;
IAppIndexingProvider? _appIndexProvider;
ReadOnlyCollection<Element>? _logicalChildren;
static readonly SemaphoreSlim SaveSemaphore = new SemaphoreSlim(1, 1);
public Application()
{
SetCurrentApplication(this);
_systemResources = new Lazy<IResourceDictionary>(() =>
{
var systemResources = DependencyService.Get<ISystemResourcesProvider>().GetSystemResources();
systemResources.ValuesChanged += OnParentResourcesChanged;
return systemResources;
});
_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<Application>>(() => new PlatformConfigurationRegistry<Application>(this));
}
internal void PlatformServicesSet()
{
_lastAppTheme = RequestedTheme;
}
public void Quit()
{
Handler?.Invoke(ApplicationHandler.TerminateCommandKey);
}
public IAppLinks AppLinks
{
get
{
if (_appIndexProvider == null)
throw new ArgumentException("No IAppIndexingProvider was provided");
if (_appIndexProvider.AppLinks == null)
throw new ArgumentException("No AppLinks implementation was found, if in Android make sure you installed the Microsoft.Maui.Controls.AppLinks");
return _appIndexProvider.AppLinks;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void SetCurrentApplication(Application value) => Current = value;
public static Application? Current { get; set; }
Page? _pendingMainPage;
public Page? MainPage
{
get
{
if (Windows.Count == 0)
return _pendingMainPage;
return Windows[0].Page;
}
set
{
if (MainPage == value)
return;
OnPropertyChanging();
if (Windows.Count == 0)
{
_pendingMainPage = value;
}
else
{
Windows[0].Page = value;
}
OnPropertyChanged();
}
}
[Obsolete("Properties API is obsolete, use Essentials.Preferences instead.")]
public IDictionary<string, object> Properties
{
get
{
if (_propertiesTask == null)
{
_propertiesTask = GetPropertiesAsync();
}
return _propertiesTask.Result;
}
}
internal override IReadOnlyList<Element> LogicalChildrenInternal =>
_logicalChildren ??= new ReadOnlyCollection<Element>(InternalChildren);
[EditorBrowsable(EditorBrowsableState.Never)]
public NavigationProxy? NavigationProxy { get; private set; }
internal IResourceDictionary SystemResources => _systemResources.Value;
ObservableCollection<Element> InternalChildren { get; } = new ObservableCollection<Element>();
[EditorBrowsable(EditorBrowsableState.Never)]
public void SetAppIndexingProvider(IAppIndexingProvider provider)
{
_appIndexProvider = provider;
}
ResourceDictionary? _resources;
bool IResourcesProvider.IsResourcesCreated => _resources != null;
public ResourceDictionary Resources
{
get
{
if (_resources != null)
return _resources;
_resources = new ResourceDictionary();
((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged;
return _resources;
}
set
{
if (_resources == value)
return;
OnPropertyChanging();
if (_resources != null)
((IResourceDictionary)_resources).ValuesChanged -= OnResourcesChanged;
_resources = value;
OnResourcesChanged(value);
if (_resources != null)
((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged;
OnPropertyChanged();
}
}
public OSAppTheme UserAppTheme
{
get => _userAppTheme;
set
{
_userAppTheme = value;
TriggerThemeChangedActual(new AppThemeChangedEventArgs(value));
}
}
public OSAppTheme RequestedTheme => UserAppTheme == OSAppTheme.Unspecified ? Device.PlatformServices.RequestedTheme : UserAppTheme;
public static Color? AccentColor { get; set; }
public event EventHandler<AppThemeChangedEventArgs> RequestedThemeChanged
{
add => _weakEventManager.AddEventHandler(value);
remove => _weakEventManager.RemoveEventHandler(value);
}
bool _themeChangedFiring;
OSAppTheme _lastAppTheme;
OSAppTheme _userAppTheme = OSAppTheme.Unspecified;
[EditorBrowsable(EditorBrowsableState.Never)]
public void TriggerThemeChanged(AppThemeChangedEventArgs args)
{
if (UserAppTheme != OSAppTheme.Unspecified)
return;
TriggerThemeChangedActual(args);
}
void TriggerThemeChangedActual(AppThemeChangedEventArgs args)
{
// On iOS the event is triggered more than once.
// To minimize that for us, we only do it when the theme actually changes and it's not currently firing
if (_themeChangedFiring || RequestedTheme == _lastAppTheme)
return;
try
{
_themeChangedFiring = true;
_lastAppTheme = RequestedTheme;
_weakEventManager.HandleEvent(this, args, nameof(RequestedThemeChanged));
}
finally
{
_themeChangedFiring = false;
}
}
public event EventHandler<ModalPoppedEventArgs>? ModalPopped;
public event EventHandler<ModalPoppingEventArgs>? ModalPopping;
public event EventHandler<ModalPushedEventArgs>? ModalPushed;
public event EventHandler<ModalPushingEventArgs>? ModalPushing;
internal void NotifyOfWindowModalEvent(EventArgs eventArgs)
{
switch (eventArgs)
{
case ModalPoppedEventArgs poppedEvents:
ModalPopped?.Invoke(this, poppedEvents);
break;
case ModalPoppingEventArgs poppingEvents:
ModalPopping?.Invoke(this, poppingEvents);
break;
case ModalPushedEventArgs pushedEvents:
ModalPushed?.Invoke(this, pushedEvents);
break;
case ModalPushingEventArgs pushingEvents:
ModalPushing?.Invoke(this, pushingEvents);
break;
default:
break;
}
}
public event EventHandler<Page>? PageAppearing;
public event EventHandler<Page>? PageDisappearing;
[Obsolete("Properties API is obsolete, use Essentials.Preferences instead.")]
public Task SavePropertiesAsync() =>
Dispatcher.DispatchIfRequiredAsync(async () =>
{
try
{
await SetPropertiesAsync();
}
catch (Exception exc)
{
this.FindMauiContext()?.CreateLogger<Application>()?.LogWarning(exc, "Exception while saving Application Properties");
}
});
public IPlatformElementConfiguration<T, Application> On<T>() where T : IConfigPlatform
{
return _platformConfigurationRegistry.Value.On<T>();
}
protected virtual void OnAppLinkRequestReceived(Uri uri)
{
}
protected override void OnParentSet()
{
throw new InvalidOperationException("Setting a Parent on Application is invalid.");
}
protected virtual void OnResume()
{
}
protected virtual void OnSleep()
{
}
protected virtual void OnStart()
{
}
internal static void ClearCurrent() => Current = null;
internal static bool IsApplicationOrNull(object? element) =>
element == null || element is IApplication;
internal static bool IsApplicationOrWindowOrNull(object? element) =>
element == null || element is IApplication || element is IWindow;
internal override void OnParentResourcesChanged(IEnumerable<KeyValuePair<string, object>> values)
{
if (!((IResourcesProvider)this).IsResourcesCreated || Resources.Count == 0)
{
base.OnParentResourcesChanged(values);
return;
}
var innerKeys = new HashSet<string>();
var changedResources = new List<KeyValuePair<string, object>>();
foreach (KeyValuePair<string, object> c in Resources)
innerKeys.Add(c.Key);
foreach (KeyValuePair<string, object> value in values)
{
if (innerKeys.Add(value.Key))
changedResources.Add(value);
}
OnResourcesChanged(changedResources);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void SendOnAppLinkRequestReceived(Uri uri)
{
OnAppLinkRequestReceived(uri);
}
internal void SendResume()
{
Current = this;
OnResume();
}
internal void SendSleep()
{
OnSleep();
#pragma warning disable CS0618 // Type or member is obsolete
SavePropertiesAsync().FireAndForget();
#pragma warning restore CS0618 // Type or member is obsolete
}
internal Task SendSleepAsync()
{
OnSleep();
#pragma warning disable CS0618 // Type or member is obsolete
return SavePropertiesAsync();
#pragma warning restore CS0618 // Type or member is obsolete
}
internal void SendStart()
{
OnStart();
}
async Task<IDictionary<string, object>> GetPropertiesAsync()
{
var deserializer = DependencyService.Get<IDeserializer>();
if (deserializer == null)
{
Current?.FindMauiContext()?.CreateLogger<Application>()?.LogWarning("No IDeserializer was found registered");
return new Dictionary<string, object>(4);
}
IDictionary<string, object> properties = await deserializer.DeserializePropertiesAsync().ConfigureAwait(false);
if (properties == null)
properties = new Dictionary<string, object>(4);
return properties;
}
internal void OnPageAppearing(Page page)
=> PageAppearing?.Invoke(this, page);
internal void OnPageDisappearing(Page page)
=> PageDisappearing?.Invoke(this, page);
async Task SetPropertiesAsync()
{
await SaveSemaphore.WaitAsync();
try
{
#pragma warning disable CS0618 // Type or member is obsolete
await DependencyService.Get<IDeserializer>().SerializePropertiesAsync(Properties);
#pragma warning restore CS0618 // Type or member is obsolete
}
finally
{
SaveSemaphore.Release();
}
}
protected internal virtual void CleanUp()
{
// Unhook everything that's referencing the main page so it can be collected
// This only comes up if we're disposing of an embedded Forms app, and will
// eventually go away when we fully support multiple windows
// TODO MAUI
//if (_mainPage != null)
//{
// InternalChildren.Remove(_mainPage);
// _mainPage.Parent = null;
// _mainPage = null;
//}
NavigationProxy = null;
}
IReadOnlyList<Maui.IVisualTreeElement> IVisualTreeElement.GetVisualChildren() => this.Windows;
}
} | 26.765 | 149 | 0.730245 | [
"MIT"
] | andreas-nesheim/maui | src/Controls/src/Core/Application.cs | 10,706 | C# |
namespace Uspelite.Web.Models.Authors
{
using System;
using System.Collections.Generic;
using System.Linq;
using Articles;
using AutoMapper;
using Common;
using Data.Models;
using Images;
using Infrastructure.Mapping.Contracts;
using Videos;
using Base;
public class AuthorsUserViewModel : PaginationModel, IMapFrom<User>, IHaveCustomMappings
{
public string Id { get; set; }
public string FullName { get; set; }
public string ShortInfo { get; set; }
public ImageViewModel ProfileImage { get; set; }
public ICollection<AuthorArticleViewModel> UserArticles { get; set; }
public ICollection<SocialProfileViewModel> SocialProfiles { get; set; }
public void CreateMappings(IMapperConfiguration configuration)
{
configuration.CreateMap<User, AuthorsUserViewModel>()
.ForMember(x => x.FullName, opt => opt.MapFrom(x => x.FirstName + " " + x.LastName))
.ForMember(x => x.ProfileImage, opt => opt.MapFrom(x => x.ProfileImages.FirstOrDefault()));
}
}
} | 30.864865 | 116 | 0.640981 | [
"Apache-2.0"
] | siderisltd/UspeliteProject | Uspelite.Web/Models/Authors/AuthorsUserViewModel.cs | 1,144 | 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 directconnect-2012-10-25.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.DirectConnect.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeConnectionLoa Request Marshaller
/// </summary>
public class DescribeConnectionLoaRequestMarshaller : IMarshaller<IRequest, DescribeConnectionLoaRequest> , 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((DescribeConnectionLoaRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeConnectionLoaRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.DirectConnect");
string target = "OvertureService.DescribeConnectionLoa";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-10-25";
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.IsSetConnectionId())
{
context.Writer.WritePropertyName("connectionId");
context.Writer.Write(publicRequest.ConnectionId);
}
if(publicRequest.IsSetLoaContentType())
{
context.Writer.WritePropertyName("loaContentType");
context.Writer.Write(publicRequest.LoaContentType);
}
if(publicRequest.IsSetProviderName())
{
context.Writer.WritePropertyName("providerName");
context.Writer.Write(publicRequest.ProviderName);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DescribeConnectionLoaRequestMarshaller _instance = new DescribeConnectionLoaRequestMarshaller();
internal static DescribeConnectionLoaRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeConnectionLoaRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.213675 | 158 | 0.607487 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/DirectConnect/Generated/Model/Internal/MarshallTransformations/DescribeConnectionLoaRequestMarshaller.cs | 4,354 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using DefaultApiClientService.Client;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Simple.OData.Client;
namespace TestCommon
{
public class OdataClient: ODataClient
{
public OdataClient(IConfiguration configuration) : base($"{new Uri(configuration["ClientAddress"])}api/")
{
}
}
}
| 23.409091 | 113 | 0.747573 | [
"MIT"
] | Platonenkov/DefaultApiClientServiceController | Test/TestCommon/OdataClient.cs | 517 | C# |
//By Dominic Brodeur-Gendron & Patrice Le Nouveau
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public static class GameEffect {
#region SHAKE
static bool perlinMode;
static float perlinSpeed;
public static void Shake(GameObject obj)
{
ShakeEffect (obj, 1, .2f, Vector3.zero, false);
}
public static void Shake(GameObject obj,float intensity)
{
ShakeEffect (obj, intensity, .2f, Vector3.zero, false);
}
public static void Shake(GameObject obj,float intensity,float time)
{
ShakeEffect (obj, intensity, time, Vector3.zero, false);
}
public static void ShakeDynamic(GameObject obj)
{
ShakeEffect (obj, 1, .2f, Vector3.zero, true);
}
public static void ShakeDynamic(GameObject obj,float intensity)
{
ShakeEffect (obj, intensity, .2f, Vector3.zero, true);
}
public static void ShakeDynamic(GameObject obj,float intensity,float time)
{
ShakeEffect (obj, intensity, time, Vector3.zero, true);
}
public static void ShakeRotation(GameObject obj, float intensity, Vector3 rotation, float time)
{
ShakeEffect (obj, intensity, time, rotation, true);
}
public static void ShakeModeSetPerlin(bool perlinModeOn, float speed)
{
perlinMode = perlinModeOn;
perlinSpeed = speed;
}
static void ShakeEffect(GameObject obj, float intensity, float time, Vector3 rotation, bool isDynamic)
{
if (obj.GetComponent<_GEffect.ShakeClass>() == null)
{
obj.AddComponent<_GEffect.ShakeClass>();
_GEffect.ShakeClass shake = obj.GetComponent<_GEffect.ShakeClass>();
shake.Init(intensity, time, rotation, isDynamic);
if(perlinMode)
{
shake.SetPerlinMode(perlinSpeed);
}
}
}
#endregion
#region Freeze Frame
/// <summary>
/// Freeze frame, useful when dealing with multicamera
/// </summary>
/// <param name="gameObject"></param>
/// <param name="sec"></param>
public static void FreezeFrame(GameObject gameObject, float sec)
{
if (gameObject.GetComponent<_GEffect.FreezeFrameClass>() == null)
gameObject.AddComponent<_GEffect.FreezeFrameClass>().freezeSec = sec;
}
/// <summary>
/// Freezes frame.
/// </summary>
/// <param name="sec">Sec.</param>
public static void FreezeFrame(float sec)
{
if (Camera.main.gameObject.GetComponent<_GEffect.FreezeFrameClass> () == null)
Camera.main.gameObject.AddComponent<_GEffect.FreezeFrameClass> ().freezeSec = sec;
}
/// <summary>
/// Freezes the frame with default value of 0.1.
/// </summary>
public static void FreezeFrame()
{
if (Camera.main.gameObject.GetComponent<_GEffect.FreezeFrameClass> () == null)
Camera.main.gameObject.AddComponent<_GEffect.FreezeFrameClass> ().freezeSec = .1f;
}
#endregion
#region Sprite & Color
/// <summary>
/// Sins the gradient.
/// </summary>
/// <returns>The gradient.</returns>
public static Color ColorLerp(Color color1, Color32 color2, float t)
{
return new Color
(
Mathf.Lerp (color1.r, color2.r, t),
Mathf.Lerp (color1.g, color2.g, t),
Mathf.Lerp (color1.b, color2.b, t),
Mathf.Lerp (color1.a, color2.a, t)
);
}
public static Color SinGradient(Color color1, Color color2, float speed)
{
float t = (Mathf.Sin(Time.timeSinceLevelLoad * speed)+1) / 2;
Color color = Color.Lerp(color1, color2,t);
return color;
}
public static Color SinGradient(Color color1, Color color2, float time, float speed)
{
float t = (Mathf.Sin(time * speed)+1) / 2;
Color color = Color.Lerp(color1, color2,t);
return color;
}
public static void FlashSprite(GameObject obj, Color color,float duration)
{
if (obj.GetComponent<_GEffect.FlashSpriteClass> () == null)
{
obj.AddComponent<_GEffect.FlashSpriteClass> ();
_GEffect.FlashSpriteClass flashSprite = obj.GetComponent<_GEffect.FlashSpriteClass> ();
flashSprite.flashColor = color;
flashSprite.duration = duration;
flashSprite.flashSpriteEnum = _GEffect.FlashSpriteClass.FlashSpriteType.Simple;
}
}
public static void FlashSprite(GameObject obj, Color color,float duration, int flashCount)
{
if (obj.GetComponent<_GEffect.FlashSpriteClass> () == null)
{
obj.AddComponent<_GEffect.FlashSpriteClass> ();
_GEffect.FlashSpriteClass flashSprite = obj.GetComponent<_GEffect.FlashSpriteClass> ();
flashSprite.flashColor = color;
flashSprite.duration = duration;
flashSprite.flashCount = flashCount;
flashSprite.flashSpriteEnum = _GEffect.FlashSpriteClass.FlashSpriteType.Multiple;
}
}
public static void FlashSpriteLerp(GameObject obj, Color color,float duration)
{
if (obj.GetComponent<_GEffect.FlashSpriteClass> () == null)
{
obj.AddComponent<_GEffect.FlashSpriteClass> ();
_GEffect.FlashSpriteClass flashSprite = obj.GetComponent<_GEffect.FlashSpriteClass> ();
flashSprite.flashColor = color;
flashSprite.speed = duration;
flashSprite.flashSpriteEnum = _GEffect.FlashSpriteClass.FlashSpriteType.Lerp;
}
}
public static void FlashCamera(Color color, float time)
{
if(Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> () == null)
Camera.main.gameObject.AddComponent<_GEffect.FlashCameraClass> ();
Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> ().Flash (color,null, time,null);
}
public static void FlashCamera(Sprite image, float time)
{
if(Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> () == null)
Camera.main.gameObject.AddComponent<_GEffect.FlashCameraClass> ();
Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> ().Flash (Color.white,image, time,null);
}
public static void FlashCamera(Color color, float time,Transform canvas)
{
if(Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> () == null)
Camera.main.gameObject.AddComponent<_GEffect.FlashCameraClass> ();
Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> ().Flash (color,null, time,canvas);
}
public static void FlashCamera(Sprite image, float time,Transform canvas)
{
if(Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> () == null)
Camera.main.gameObject.AddComponent<_GEffect.FlashCameraClass> ();
Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> ().Flash (Color.white,image, time,canvas);
}
public static void FlashCamera(Color color,Sprite image, float time,Transform canvas)
{
if(Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> () == null)
Camera.main.gameObject.AddComponent<_GEffect.FlashCameraClass> ();
Camera.main.gameObject.GetComponent<_GEffect.FlashCameraClass> ().Flash (color,image, time,canvas);
}
#endregion
public static void DestroyChilds(Transform parent)
{
if (parent.childCount != 0)
{
int childs = parent.childCount;
for (int i = 0; i <= childs - 1; i++)
MonoBehaviour.Destroy (parent.GetChild (i).gameObject);
}
}
public static void DestroyChilds(GameObject parent)
{
GameEffect.DestroyChilds (parent.transform);
}
}
public static class GamePhysics
{
public static Vector3 BallisticVelocity(Transform origin, Transform target)
{
return BallisticVelocity(origin.position, target.position);
}
public static Vector3 BallisticVelocity(Vector3 origin, Vector3 target)
{
Vector3 dir = target - origin;
dir.y = 0;
float dist = dir.magnitude;
float vel = Mathf.Sqrt (dist * Physics.gravity.magnitude);
return vel * dir.normalized;
}
public static Vector3 BallisticVelocity(Transform origin, Transform target, float angle)
{
return BallisticVelocity(origin.position, target.position, angle);
}
public static Vector3 BallisticVelocity(Vector3 origin, Vector3 target, float angle)
{
Vector3 dir = target - origin;
float h = dir.y;
dir.y = 0;
float dist = dir.magnitude;
float a = angle * Mathf.Deg2Rad;
dir.y = dist * Mathf.Tan (a);
dist += h / Mathf.Tan (a);
float vel = Mathf.Sqrt (dist * Physics.gravity.magnitude / Mathf.Sin(2.5f * a));
return vel * dir.normalized ;
}
public class Projectile
{
float g;
float h;
Vector3 startPosition;
Vector3 endPosition;
LaunchData launchData;
public float TimeToTarget { get { return launchData.timeToTarget; } }
public Projectile(Vector3 startPosition, Vector3 endPosition, float height, float gravity)
{
g = gravity;
h = height;
this.startPosition = startPosition;
this.endPosition = endPosition;
launchData = CalculateLaunchData(startPosition, endPosition);
}
public Vector3 GetPositionAtTime(float currentTime)
{
return CalculatePositionAtTime(launchData, startPosition, currentTime);
}
public Vector3[] GetPointsOnCurve(int resolution)
{
Vector3[] positions = new Vector3[resolution];
for (int i = 0; i < resolution; i++)
{
float currentTime = i / (float)(resolution-1) * TimeToTarget;
positions[i] = GetPositionAtTime(currentTime);
}
return positions;
}
Vector3 CalculatePositionAtTime(LaunchData launchData, Vector3 startPosition, float currentTime)
{
Vector3 displacement = launchData.initialVelocity * currentTime + Vector3.up * g * currentTime * currentTime / 2f;
return startPosition + displacement;
}
LaunchData CalculateLaunchData(Vector3 startPosition, Vector3 endPosition)
{
float displacementY = endPosition.y - startPosition.y;
Vector3 displacementXZ = new Vector3(
endPosition.x - startPosition.x,
0,
endPosition.z - startPosition.z
);
float time = (Mathf.Sqrt(-2 * h / g) + Mathf.Sqrt(2 * (displacementY - h) / g));
Vector3 velocityY = Vector3.up * Mathf.Sqrt(-2 * g * h);
Vector3 velocityXZ = displacementXZ / time;
return new LaunchData(velocityXZ + velocityY * -Mathf.Sign(g), time);
}
struct LaunchData
{
public readonly Vector3 initialVelocity;
public readonly float timeToTarget;
public LaunchData(Vector3 initialVelocity, float timeToTarget)
{
this.initialVelocity = initialVelocity;
this.timeToTarget = timeToTarget;
}
}
}
}
public static class GameMath
{
///// <summary>
/// Calculate the horizontal position of a given index if you have n objects.
/// Everything will be align by center
/// Ideally, you call this function in a for loop to position every objects
///
/// for(i ...)
/// objects[i].position = new Vector2(CenterAlign(objects.length, dist, i), yPos);
/// </summary>
/// <returns>The horizontal position</returns>
/// <param name="NumberOfObject">Number of objects.</param>
/// <param name="distance">Distance between each objects.</param>
/// <param name="i">The index of the object.</param>
public static float CenterAlign(int NumberOfObject, float distance, int i)
{
return ((i - (((NumberOfObject) - 1) / 2)) * distance) - (((NumberOfObject + 1) % 2) * (distance / 2));
}
public static float PerlinNoiseNegOneToOne(float x, float y)
{
return (Mathf.PerlinNoise(x,y) * 2) - 1;
}
public static Vector3 SphericalRotation(float radius, float theta, float phi)
{
float x = radius * Mathf.Sin(theta) * Mathf.Cos(phi);
float y = radius * Mathf.Sin(theta) * Mathf.Sin(phi);
float z = radius * Mathf.Cos(theta);
return new Vector3(x, y, z);
}
/// <summary>
/// A tester
/// </summary>
/// <param name="i"></param>
/// <param name="width"></param>
/// <returns></returns>
public static Vector2 GetXYFromIndex(int i, int width)
{
float x = (float)i % width;
float y = (float)i / width;
return new Vector2(x, y);
}
public static int GetIndexFromXY(int x, int y, int width)
{
return y * width + x;
}
#region Curves
public static float Stretch(float A, float stretchAmount)
{
if (A > 1)
A = 1;
float C = Mathf.Abs (A - .5f);
return .5f + stretchAmount + ((C + .5f) * stretchAmount);
}
/// <summary>
/// Return a log function between 0 and 1
/// </summary>
/// <param name="x">The x coordinate.</param>
public static float Log01(float t)
{
return Mathf.Log10 ((t + .11f) * 9f);
}
/// <summary>
/// Return a smooth Sigmoid between 0 and 1
/// </summary>
/// <param name="x">The t coordinate between 0 and 1.</param>
public static float Sigmoid01(float t)
{
return Mathf.Clamp01 (1 / (1 + Mathf.Exp (-(10 * t - 5.1f))));
}
/// <summary>
/// Return a steep sigmoid between 0 and 1
/// </summary>
/// <param name="t">The t coordinate between 0 and 1.</param>
public static float SteepSigmoid01(float t)
{
return Mathf.Clamp01 (1 / (1 + Mathf.Exp (-(30 * t - 15))));
}
/// <summary>
/// Return a zigzag from 0 to 1
/// </summary>
/// <returns>The zag01.</returns>
/// <param name="t">T.</param>
public static float ZigZag01(float t)
{
return Mathf.Clamp01((.9f * Mathf.Sin (t * 1.37f) + .1f * Mathf.Sin (t * 1.37f * 15)) * 1.02f);
}
public static float ExtremeExp01(float t)
{
return Mathf.Clamp01 (5.9f * Mathf.Exp(t * 10 - 11.77f));
}
/// <summary>
/// Bounce between 0 and 1
/// </summary>
public static float Bounce01(float t) //from Mathfx
{
return Mathf.Abs (Mathf.Sin (6.28f * (t + 1) * (t + 1)) * (1 - t));
}
#endregion
#region Distance
public static bool IsMinimumDistance(GameObject object1,GameObject object2,float minimumDistance)
{
if (Mathf.Abs(object1.transform.position.x - object2.transform.position.x) < minimumDistance &&
Mathf.Abs(object1.transform.position.y - object2.transform.position.y) < minimumDistance &&
Mathf.Abs(object1.transform.position.z - object2.transform.position.z) < minimumDistance)
return true;
return false;
}
public static bool IsMinimumDistance(Transform object1,Transform object2,float minimumDistance)
{
if (Mathf.Abs(object1.position.x - object2.position.x) < minimumDistance &&
Mathf.Abs(object1.position.y - object2.position.y) < minimumDistance &&
Mathf.Abs(object1.position.z - object2.position.z) < minimumDistance)
return true;
return false;
}
public static bool IsMinimumDistance(Vector3 object1,Vector3 object2,float minimumDistance)
{
if (Mathf.Abs(object1.x - object2.x) < minimumDistance &&
Mathf.Abs(object1.y - object2.y) < minimumDistance &&
Mathf.Abs(object1.z - object2.z) < minimumDistance)
return true;
return false;
}
public static bool IsMinimumDistance(Vector2 object1,Vector2 object2,float minimumDistance)
{
if (Mathf.Abs(object1.x - object2.x) < minimumDistance &&
Mathf.Abs(object1.y - object2.y) < minimumDistance)
return true;
return false;
}
public static float DistanceXY(GameObject object1,GameObject object2)
{
return Mathf.Sqrt
(
Mathf.Pow((object1.transform.position.x - object2.transform.position.x), 2) +
Mathf.Pow((object1.transform.position.y - object2.transform.position.y), 2)
);
}
public static float DistanceXY(Transform transform1,Transform transform2)
{
return Mathf.Sqrt
(
Mathf.Pow((transform1.position.x - transform2.position.x), 2) +
Mathf.Pow((transform1.position.y - transform2.position.y), 2)
);
}
public static float DistanceXZ(GameObject object1,GameObject object2)
{
return Mathf.Sqrt
(
Mathf.Pow((object1.transform.position.x - object2.transform.position.x), 2) +
Mathf.Pow((object1.transform.position.z - object2.transform.position.z), 2)
);
}
public static float DistanceXZ(Transform transform1,Transform transform2)
{
return Mathf.Sqrt
(
Mathf.Pow((transform1.position.x - transform2.position.x), 2) +
Mathf.Pow((transform1.position.z - transform2.position.z), 2)
);
}
public static float DistanceYZ(GameObject object1,GameObject object2)
{
return Mathf.Sqrt
(
Mathf.Pow((object1.transform.position.y - object2.transform.position.y), 2) +
Mathf.Pow((object1.transform.position.z - object2.transform.position.z), 2)
);
}
public static float DistanceYZ(Transform transform1,Transform transform2)
{
return Mathf.Sqrt
(
Mathf.Pow((transform1.position.y - transform2.position.y), 2) +
Mathf.Pow((transform1.position.z - transform2.position.z), 2)
);
}
#endregion
#region Vectors
public static Vector3 GetNormal(Vector3 p1, Vector3 p2, Vector3 p3)
{
return Vector3.Cross(p2 - p1, p3 - p1).normalized;
}
public static Vector2 PolarToCartesian(float radius, float theta)
{
float x = radius * Mathf.Cos(theta);
float y = radius * Mathf.Sin(theta);
return new Vector2(x, y);
}
public static Vector3[] GetPointOnCurvedVector(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, int resolution)
{
Vector3[] points = new Vector3[resolution];
for (int i = 0; i < resolution; i++)
{
float t = (float)i / (resolution - 1);
points[i] = GetPointOnBezier(p1, p2, p3, p4, t);
}
return points;
}
public static Vector3 GetPointOnBezier(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
oneMinusT * oneMinusT * oneMinusT * p0 +
3f * oneMinusT * oneMinusT * t * p1 +
3f * oneMinusT * t * t * p2 +
t * t * t * p3;
}
/// <summary>
/// Give 3 positions, this will return a list of points that will start at previous and end at next curving by current
/// </summary>
/// <param name="previous"></param>
/// <param name="current"></param>
/// <param name="next"></param>
/// <param name="resolution"></param>
/// <returns></returns>
public static Vector3[] GetPointOnCurvedVector(Vector3 start, Vector3 middle, Vector3 end, int resolution)
{
Vector3 dir = (middle - start);
Vector3 currentDestination = middle + dir;
Vector3[] points = new Vector3[resolution];
for (int i = 0; i < resolution; i++)
{
float t = (float) i / (resolution - 1);
Vector3 lerp1 = Vector3.Lerp(middle, currentDestination, t);
Vector3 lerp2 = Vector3.Lerp(middle, end, t);
points[i] = Vector3.Lerp(lerp1, lerp2, t);
}
return points;
}
#if NET_VERSION_4_5
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public static Vector3 RotateAroundAxisNormalized(Vector3 direction, Vector3 axisNormalized, float angle)
{
Vector3 a_dotDA = axisNormalized * Vector3.Dot(direction, axisNormalized);
return a_dotDA + (direction - a_dotDA) * Mathf.Cos(angle) + Vector3.Cross(direction, axisNormalized) * Mathf.Sin(angle);
}
public static Vector3 RotateAroundAxis(Vector3 direction, Vector3 axis, float angle)
{
Vector3 proj = Projection(direction, axis);
Vector3 rej = Rejection(direction, axis);
return proj + rej * Mathf.Cos(angle) + Vector3.Cross(direction, axis) * Mathf.Sin(angle);
}
public static Vector3 Projection(Vector3 a, Vector3 b)
{
return (Vector3.Dot(a, b) / Vector3.Dot(b, b)) * b;
}
public static Vector3 Rejection(Vector3 a, Vector3 b)
{
return a - Projection(a, b);
}
/// <summary>
/// </summary>
/// <param name="radiusAndTheta">A Vector2 containing x = radius, y = theta</param>
/// <returns></returns>
public static Vector2 PolarToCartesian(Vector2 radiusAndTheta)
{
return PolarToCartesian(radiusAndTheta.x, radiusAndTheta.y);
}
/// <summary>
/// Start with a x,y and receive a Vector2(Radius, Theta)
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public static Vector2 CartesianToPolar(Vector2 position)
{
float r = Mathf.Sqrt(position.x * position.x + position.y * position.y);
float theta = Mathf.Atan2(position.y, position.x);
return new Vector2(r, theta);
}
public static Vector2 CartesianToPolar(float x, float y)
{
return CartesianToPolar(new Vector2(x,y));
}
public static Vector2 RotateVector(float angle, Vector2 point)
{
float a = angle * Mathf.PI / 180;
float cosA = Mathf.Cos(a);
float sinA = Mathf.Sin(a);
Vector2 newPoint =
new Vector2(
(point.x * cosA - point.y * sinA),
(point.x * sinA + point.y * cosA)
);
return newPoint;
}
public static Vector3 RotateVectorX(float angle, Vector3 point)
{
Vector2 vec = RotateVector(angle, new Vector2(point.z, point.y));
return new Vector3(point.x, vec.y, vec.x);
}
public static Vector3 RotateVectorZ(float angle, Vector3 point)
{
Vector2 vec = RotateVector(angle, new Vector2(point.x, point.y));
return new Vector3(vec.y, vec.x, point.z);
}
public static Vector3 RotateVectorY(float angle, Vector3 point)
{
Vector2 vec = RotateVector(angle, new Vector2 (point.x, point.z));
return new Vector3 (vec.x, point.y, vec.y);
}
public static Vector2 RandomRotateVector(Vector2 vector, float min, float max)
{
return RotateVector(Random.Range(min, max), vector);
}
public static Vector2 RandomRotateVectorX(Vector3 vector, float min, float max)
{
return RotateVectorX(Random.Range(min, max), vector);
}
public static Vector2 RandomRotateVectorY(Vector3 vector, float min, float max)
{
return RotateVectorY(Random.Range(min, max), vector);
}
public static Vector2 RandomRotateVectorZ(Vector3 vector, float min, float max)
{
return RotateVectorZ(Random.Range(min, max), vector);
}
public static Vector2 PolarRose(float theta, float k, float radius)
{
float r = radius * Mathf.Cos(k * theta);
float x = r * Mathf.Cos(theta);
float y = r * Mathf.Sin(theta);
return new Vector2(x, y);
}
public static Vector2[] GetPolarRoseCoordinate(float k, float radius, int resolution)
{
return GetPolarRoseCoordinate(k, radius, resolution, 1);
}
public static Vector2[] GetPolarRoseCoordinate(float k, float radius, int resolution, float numberLoop)
{
Vector2[] points = new Vector2[resolution];
for (int i = 0; i < resolution; i++)
{
float t = (float)i / (resolution-1);
float theta = Mathf.Lerp(0, Mathf.PI * 2 * numberLoop, t);
points[i] = PolarRose(theta, k, radius);
}
return points;
}
public static Vector3[] GetPolarRoseCoordinateVector3(float k, float radius, int resolution)
{
return GetPolarRoseCoordinateVector3(k, radius, resolution, 1);
}
public static Vector3[] GetPolarRoseCoordinateVector3(float k, float radius, int resolution, float numberLoop)
{
Vector2[] points = GetPolarRoseCoordinate(k, radius, resolution, numberLoop);
Vector3[] points3 = new Vector3[resolution];
for (int i = 0; i < points3.Length; i++)
{
points3[i] = points[i];
}
return points3;
}
/// <summary>
/// Return the angle of two vectors from -180 to 180 degree
/// </summary>
public static float Angle(Vector3 from, Vector3 to)
{
return (Vector3.Angle (from,to))* (-Mathf.Sign (Vector3.Cross (from, to).y));
}
/// <summary>
/// Return the angle of two vectors from -180 to 180 degree (to test lol)
/// </summary>
public static float Angle(Vector2 from, Vector2 to)
{
///to test
return (Vector2.Angle (from,to))* (-Mathf.Sign (Vector3.Cross (from, to).y));
}
#endregion
}
#region hidden functions
namespace _GEffect
{
public class FreezeFrameClass : MonoBehaviour {
public float freezeSec;
void Start()
{
StartCoroutine (FreezeFrameEffect());
}
IEnumerator FreezeFrameEffect()
{
Time.timeScale = 0f;
float pauseEndTime = Time.realtimeSinceStartup + freezeSec;
while (Time.realtimeSinceStartup < pauseEndTime)
yield return 0;
Time.timeScale = 1;
Destroy (this);
}
}
public class ShakeClass : MonoBehaviour
{
float intensity;
float currentTime;
float time;
Vector3 rotation;
bool isDynamic;
bool isPerlinMode = false;
Vector3 originalPos;
Vector3 originalRotation;
Vector3 perlinSeeds;
float perlinSpeed;
public void SetPerlinMode(float speed)
{
isPerlinMode = true;
perlinSpeed = speed;
}
public void Init(float intensity, float time, Vector3 rotation, bool isDynamic)
{
this.intensity = intensity;
this.currentTime = time;
this.time = time;
this.rotation = rotation;
this.isDynamic = isDynamic;
perlinSeeds = Random.insideUnitSphere * 50;
}
void OnEnable()
{
originalPos = transform.localPosition;
originalRotation = transform.localEulerAngles;
}
void Update()
{
if (isDynamic)
{
originalPos = transform.localPosition;
}
}
void LateUpdate()
{
if (currentTime > 0)
{
float t = currentTime / time;
float currentIntensity = Mathf.Lerp(0, intensity, GameMath.Log01(t));
if (isPerlinMode)
{
transform.localEulerAngles = originalRotation + RandomRotationPerlin();
transform.localPosition = originalPos + RandomPerlinPosition() * currentIntensity;
}
else
{
transform.localEulerAngles = originalRotation + RandomRotation();
transform.localPosition = originalPos + Random.insideUnitSphere * currentIntensity;
}
currentTime -= Time.deltaTime;
}
else
{
currentTime = 0f;
transform.localPosition = originalPos;
transform.localEulerAngles = originalRotation;
Destroy(this);
}
}
Vector3 RandomPerlinPosition()
{
perlinSeeds += Vector3.one * Time.deltaTime * perlinSpeed;
return new Vector3(
GameMath.PerlinNoiseNegOneToOne(perlinSeeds.x, perlinSeeds.y),
GameMath.PerlinNoiseNegOneToOne(perlinSeeds.x, perlinSeeds.z),
GameMath.PerlinNoiseNegOneToOne(perlinSeeds.y, perlinSeeds.z)
);
}
Vector3 RandomRotation()
{
if(rotation == Vector3.zero)
{
return Vector3.zero;
}
else
{
return new Vector3(
rotation.x * Random.Range(-1.0f,1.0f),
rotation.y * Random.Range(-1.0f,1.0f),
rotation.z * Random.Range(-1.0f,1.0f)
);
}
}
Vector3 RandomRotationPerlin()
{
if(rotation == Vector3.zero)
{
return Vector3.zero;
}
else
{
return RandomPerlinPosition();
}
}
}
public class FlashSpriteClass : MonoBehaviour
{
public enum FlashSpriteType
{
Multiple, Simple, Lerp
};
public FlashSpriteType flashSpriteEnum;
Color originalColor;
public Color flashColor;
public float speed, duration;
float t;
public int flashCount;
SpriteRenderer spriteRender;
void Start()
{
spriteRender = gameObject.GetComponent<SpriteRenderer> ();
originalColor = spriteRender.color;
if (flashSpriteEnum == FlashSpriteType.Simple)
{
StartCoroutine(simpleFlash ());
}
else if (flashSpriteEnum == FlashSpriteType.Multiple)
{
StartCoroutine(multipleFlash ());
}
}
void Update()
{
if (flashSpriteEnum == FlashSpriteType.Lerp)
{
lerpFlash ();
}
}
IEnumerator simpleFlash()
{
spriteRender.color = flashColor;
yield return new WaitForSeconds (duration);
spriteRender.color = originalColor;
Destroy (this);
}
IEnumerator multipleFlash()
{
float splitTime = (duration / flashCount) / 2;
for(int i = 0; i < flashCount; i++)
{
spriteRender.color = flashColor;
yield return new WaitForSeconds (splitTime);
spriteRender.color = originalColor;
yield return new WaitForSeconds (splitTime);
}
Destroy (this);
}
void lerpFlash()
{
t += Time.deltaTime / speed;
spriteRender.color = new Color
(
Mathf.Lerp(originalColor.r, flashColor.r,t),
Mathf.Lerp(originalColor.g, flashColor.g,t),
Mathf.Lerp(originalColor.b, flashColor.b,t),
Mathf.Lerp(originalColor.a, flashColor.a,t)
);
if (t > 1)
{
spriteRender.color = originalColor;
Destroy (this);
}
}
}
public class FlashCameraClass : MonoBehaviour
{
float t = 0;
float speed;
GameObject screen;
Color color;
Image image;
bool isFlashing = false;
bool isIncreasing = true;
Transform canvas;
void Awake()
{
screen = new GameObject ();
screen.AddComponent<Image> ();
screen.GetComponent<Image> ().raycastTarget = false;
screen.name = "Flashing Screen";
screen.GetComponent<Image> ().color = new Color (0, 0, 0, 0);
}
void SetCanvas()
{
if(canvas == null)
screen.transform.SetParent (GameObject.Find ("Canvas").transform, true);
else
screen.transform.SetParent (canvas, true);
screen.GetComponent<Image> ().rectTransform.sizeDelta = new Vector2 (Screen.width, Screen.height);
screen.GetComponent<Image> ().rectTransform.localPosition = Vector2.zero;
}
public void Flash(Color _color, Sprite sprite, float time, Transform _canvas)
{
if (_canvas != null)
{
if(canvas != _canvas)
canvas = _canvas;
SetCanvas ();
}
speed = 1 / time;
t = 0;
color = _color;
screen.GetComponent<Image> ().sprite = sprite;
isIncreasing = true;
isFlashing = true;
}
void Update()
{
if (!isFlashing)
return;
t += Time.deltaTime * speed * 2;
if (isIncreasing)
{
screen.GetComponent<Image> ().color = new Color (color.r, color.g, color.b, Mathf.Lerp (0, color.a, t));
if (t > 1)
{
isIncreasing = false;
t = 0;
}
}
else
{
screen.GetComponent<Image> ().color = new Color (color.r, color.g, color.b, Mathf.Lerp (color.a, 0, t));
if (t > 1)
isFlashing = false;
}
}
}
}
#endregion
| 29.035171 | 128 | 0.649141 | [
"MIT"
] | DominicBg/GenericCharacterController | Assets/UnityLibs/Util and extensions/GameEffect.cs | 30,547 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
namespace EGS
{
/// <summary>
/// The controller for the base mob.
/// </summary>
public class BaseMobController : FSMNavMeshController
{
//=====================================================================
#region Instance variables
//=====================================================================
[SerializeField] private IdleStateSO _idleStateData = default;
[SerializeField] private ChaseStateSO _chaseStateData = default;
[SerializeField] private AttackStateSO _attackStateData = default;
#endregion
//=====================================================================
#region Properties
//=====================================================================
/// <summary>
/// The idle state of the entity.
/// </summary>
public BaseMobIdleState IdleState { get; private set; }
/// <summary>
/// The chase state of the entity.
/// </summary>
public BaseMobChaseState ChaseState { get; private set; }
/// <summary>
/// The attack state of the entity.
/// </summary>
public BaseMobAttackState AttackState { get; private set; }
#endregion
//=====================================================================
#region MonoBehaviour
//=====================================================================
protected override void Start()
{
base.Start();
InitVars();
}
protected void OnDrawGizmos()
{
DrawGizmos();
}
#endregion
//=====================================================================
#region Initialization
//=====================================================================
private new void InitVars()
{
IdleState = new BaseMobIdleState(this, _idleStateData);
ChaseState = new BaseMobChaseState(this, _chaseStateData);
AttackState = new BaseMobAttackState(this, _attackStateData);
FiniteStateMachine.Initialize(ChaseState);
}
#endregion
//=====================================================================
#region Gizmos
//=====================================================================
/// <summary>
/// Draws gizmos for the detection ranges.
/// </summary>
private void DrawGizmos()
{
try
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(
transform.position + new Vector3(_attackStateData.range, 0, 0),
_attackStateData.radiusOfAttack);
}
catch (System.Exception)
{
Debug.Log(name + " does not have data to draw gizmos");
}
}
#endregion
//=====================================================================
#region Player range detection
//=====================================================================
/// <summary>
/// Checks whether a player is within the min agro range.
/// </summary>
public virtual bool IsPlayerInAgroRange()
{
Player player = GetClosestPlayer();
if (player == null)
return false;
return Vector3.SqrMagnitude(
transform.position - player.GameObject.transform.position) <
999999999;
}
/// <summary>
/// Checks whether a player is within attack range.
/// </summary>
public virtual bool IsPlayerInAttackRange()
{
Player player = GetClosestPlayer();
if (player == null)
return false;
return Vector3.SqrMagnitude(
transform.position - player.GameObject.transform.position) <=
_attackStateData.range * _attackStateData.range;
}
#endregion
//=====================================================================
#region Attacking action
//=====================================================================
/// <summary>
/// To be called if the when the attack state is entered.
/// </summary>
public void StartAttacking()
{
InvokeRepeating("Attack", 0, 1f);
}
/// <summary>
/// To be called if the when the attack state is entered.
/// </summary>
public void StopAttacking()
{
CancelInvoke();
}
/// <summary>
/// Hurts player if detected by overlap sphere.
/// </summary>
public void Attack()
{
Debug.Log("Attack triggered");
Vector3 directionOfPlayer = GetPlayerDirection();
WeaponSelector.UseSelectedWeapon(directionOfPlayer);
}
protected Vector3 GetPlayerDirection()
{
return (GetClosestPlayer().GameObject.transform.position - transform.position).normalized;
}
#endregion
}
}
| 34.72549 | 102 | 0.435535 | [
"MIT"
] | sirpaulmcd/Elite-Gardening-Squad-Open | EntitySystem/BaseMob/Scripts/BaseMobController.cs | 5,313 | 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("Transport Price")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Transport Price")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("69a72d80-6ca9-46e0-b9b7-f9efbe41a900")]
// 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.918919 | 84 | 0.744833 | [
"MIT"
] | ChrisPam/ProgrammingBasics | Transport Price/Properties/AssemblyInfo.cs | 1,406 | C# |
namespace BlobService.Core
{
public class Constants
{
public static string SASQueryStringKey = "saskey";
public static int DefaultBlobSizeLimitInMB = 50;
}
}
| 20.777778 | 58 | 0.673797 | [
"MIT"
] | BlobService/BlobService | BlobService.Core/Constants.cs | 189 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AElf.CrossChain
{
public interface ICrossChainDataProvider
{
Task<List<SideChainBlockData>> GetSideChainBlockDataAsync(Hash currentBlockHash, long currentBlockHeight);
Task<bool> ValidateSideChainBlockDataAsync(List<SideChainBlockData> sideChainBlockData,
Hash currentBlockHash, long currentBlockHeight);
Task<List<ParentChainBlockData>> GetParentChainBlockDataAsync(Hash currentBlockHash, long currentBlockHeight);
Task<bool> ValidateParentChainBlockDataAsync(List<ParentChainBlockData> parentChainBlockData,
Hash currentBlockHash, long currentBlockHeight);
Task<CrossChainBlockData> GetIndexedCrossChainBlockDataAsync(Hash currentBlockHash, long currentBlockHeight);
Task<CrossChainBlockData> GetCrossChainBlockDataForNextMiningAsync(Hash currentBlockHash, long currentBlockHeight);
CrossChainBlockData GetUsedCrossChainBlockDataForLastMiningAsync(Hash blockHash, long previousBlockHeight);
Task<ChainInitializationContext> GetChainInitializationContextAsync(int chainId, Hash blockHash, long blockHeight);
Task RegisterNewChainsAsync(Hash blockHash, long blockHeight);
Task HandleNewLibAsync(LastIrreversibleBlockDto lastIrreversibleBlockDto);
}
} | 48.428571 | 123 | 0.798673 | [
"MIT"
] | quangdo3112/AElf | src/AElf.CrossChain.Core/Services/ICrossChainDataProvider.cs | 1,356 | C# |
/*
Copyright 2012 Stefano Chizzolini. http://www.pdfclown.org
Contributors:
* Stefano Chizzolini (original code developer, http://www.stefanochizzolini.it)
This file should be part of the source code distribution of "PDF Clown library" (the
Program): see the accompanying README files for more info.
This Program is free software; you can redistribute it and/or modify it under the terms
of the GNU Lesser General Public License as published by the Free Software Foundation;
either version 3 of the License, or (at your option) any later version.
This Program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY,
either expressed or implied; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the License for more details.
You should have received a copy of the GNU Lesser General Public License along with this
Program (see README files); if not, go to the GNU website (http://www.gnu.org/licenses/).
Redistribution and use, with or without modification, are permitted provided that such
redistributions retain the above copyright notice, license and disclaimer, along with
this list of conditions.
*/
using org.pdfclown.tokens;
using System.Collections.Generic;
namespace org.pdfclown.objects
{
/**
<summary>Visitor object.</summary>
*/
public class Visitor
: IVisitor
{
public virtual PdfObject Visit(
ObjectStream obj,
object data
)
{
foreach(PdfDataObject value in obj.Values)
{value.Accept(this, data);}
return obj;
}
public virtual PdfObject Visit(
PdfArray obj,
object data
)
{
foreach(PdfDirectObject item in obj)
{
if(item != null)
{item.Accept(this, data);}
}
return obj;
}
public virtual PdfObject Visit(
PdfBoolean obj,
object data
)
{return obj;}
public PdfObject Visit(
PdfDataObject obj,
object data
)
{return obj.Accept(this, data);}
public virtual PdfObject Visit(
PdfDate obj,
object data
)
{return obj;}
public virtual PdfObject Visit(
PdfDictionary obj,
object data
)
{
foreach(PdfDirectObject value in obj.Values)
{
if(value != null)
{value.Accept(this, data);}
}
return obj;
}
public virtual PdfObject Visit(
PdfIndirectObject obj,
object data
)
{
PdfDataObject dataObject = obj.DataObject;
if(dataObject != null)
{dataObject.Accept(this, data);}
return obj;
}
public virtual PdfObject Visit(
PdfInteger obj,
object data
)
{return obj;}
public virtual PdfObject Visit(
PdfName obj,
object data
)
{return obj;}
public virtual PdfObject Visit(
PdfReal obj,
object data
)
{return obj;}
public virtual PdfObject Visit(
PdfReference obj,
object data
)
{
obj.IndirectObject.Accept(this, data);
return obj;
}
public virtual PdfObject Visit(
PdfStream obj,
object data
)
{return obj;}
public virtual PdfObject Visit(
PdfString obj,
object data
)
{return obj;}
public virtual PdfObject Visit(
PdfTextString obj,
object data
)
{return obj;}
public virtual PdfObject Visit(
XRefStream obj,
object data
)
{return obj;}
}
} | 22.850649 | 91 | 0.641375 | [
"Apache-2.0"
] | XoriantOpenSource/PDFClown | dotNET/pdfclown.lib/src/org/pdfclown/objects/Visitor.cs | 3,519 | C# |
/*
The MIT License (MIT)
Copyright 2021 Adam Reilly, Call to Action Software LLC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Cta.UI
{
/// <summary>
/// Attach to Unity GameObjects to associate them with EntityCombatEventTextDisplaySystem
/// </summary>
[UnityEngine.AddComponentMenu("")]
public class EntityCombatEventTextDisplaySystemBootstrap : SystemBootstrap<EntityCombatEventTextDisplaySystem>
, ISystemBootstrap<IEntityEventTextDisplaySystem>
{
[TypeConstraint(typeof(IEntityEventTextDisplayMenu))]
public UnityEngine.GameObject displayMenuInternal;
public ReferencePointType displayRefPoint = ReferencePointType.UI_00;
public IEntityEventTextDisplaySystem GetSystem(ISystemAccessSystem systemAccessor, IEntityConversionSystem conversionSystem) { return GetOrCreateSystem(systemAccessor, conversionSystem); }
protected override EntityCombatEventTextDisplaySystem CreateSystem(ISystemAccessSystem systemAccessor, IEntityConversionSystem conversionSystem)
{
return new EntityCombatEventTextDisplaySystem(displayRefPoint,
displayMenuInternal.GetComponent<IEntityEventTextDisplayMenu>());
}
}
}
| 63.257143 | 460 | 0.787263 | [
"MIT"
] | areilly711/CtaApi | Unity/CtaApi/Packages/com.calltoaction.ctaapi/CtaUnity/Runtime/Scripts/UI/EntityCombatEventTextDisplaySystemBootstrap.cs | 2,214 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Francesco Pighi <francesco.pighi@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Paramore.Brighter.Outbox.MsSql;
using Xunit;
namespace Paramore.Brighter.Tests.Outbox.MsSql
{
[Trait("Category", "MSSQL")]
[Collection("MSSQL OutBox")]
public class SqlOutboxWritingMessagesTests : IDisposable
{
private readonly MsSqlTestHelper _msSqlTestHelper;
private readonly Message _messageEarliest;
private readonly Message _messageLatest;
private IEnumerable<Message> _retrievedMessages;
private readonly MsSqlOutbox _sqlOutbox;
public SqlOutboxWritingMessagesTests()
{
_msSqlTestHelper = new MsSqlTestHelper();
_msSqlTestHelper.SetupMessageDb();
_sqlOutbox = new MsSqlOutbox(_msSqlTestHelper.OutboxConfiguration);
_messageEarliest = new Message(new MessageHeader(Guid.NewGuid(), "Test", MessageType.MT_COMMAND, DateTime.UtcNow.AddHours(-3)), new MessageBody("Body"));
_sqlOutbox.Add(_messageEarliest);
var message2 = new Message(new MessageHeader(Guid.NewGuid(), "Test2", MessageType.MT_COMMAND, DateTime.UtcNow.AddHours(-2)), new MessageBody("Body2"));
_sqlOutbox.Add(message2);
_messageLatest = new Message(new MessageHeader(Guid.NewGuid(), "Test3", MessageType.MT_COMMAND, DateTime.UtcNow.AddHours(-1)), new MessageBody("Body3"));
_sqlOutbox.Add(_messageLatest);
}
[Fact]
public void When_Writing_Messages_To_The_Outbox()
{
_retrievedMessages = _sqlOutbox.Get();
//_should_read_first_message_last_from_the__message_store
_retrievedMessages.Last().Id.Should().Be(_messageEarliest.Id);
//_should_read_last_message_first_from_the__message_store
_retrievedMessages.First().Id.Should().Be(_messageLatest.Id);
//_should_read_the_messages_from_the__message_store
_retrievedMessages.Should().HaveCount(3);
}
private void Release()
{
_msSqlTestHelper.CleanUpDb();
}
public void Dispose()
{
GC.SuppressFinalize(this);
Release();
}
~SqlOutboxWritingMessagesTests()
{
Release();
}
}
} | 38.544444 | 165 | 0.705391 | [
"MIT"
] | SVemulapalli/Brighter | tests/Paramore.Brighter.Tests/Outbox/MsSql/When_writing_messages_to_the_message_store.cs | 3,478 | C# |
using UnityEngine;
public class IAPTest : MonoBehaviour {
private void Update() {
// if (Input.GetKeyDown(KeyCode.A)) IAP.m.BuyRemoveAds();
// if (Input.GetKeyDown(KeyCode.Z)) IAP.m.Buy50Gems();
// if (Input.GetKeyDown(KeyCode.E)) IAP.m.Buy200Gems();
// if (Input.GetKeyDown(KeyCode.R)) IAP.m.BuySeasonPass();
// if (Input.GetKeyDown(KeyCode.T)) IAP.m.RestorePurchases();
}
}
| 35.416667 | 69 | 0.632941 | [
"MIT"
] | henriforshort/PushNShove | Assets/Scripts/IAPTest.cs | 425 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.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.DynamoDBv2.Model
{
/// <summary>
/// Your request rate is too high. The AWS SDKs for DynamoDB automatically retry requests
/// that receive this exception. Your request is eventually successful, unless your retry
/// queue is too large to finish. Reduce the frequency of requests and use exponential
/// backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error
/// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public partial class ProvisionedThroughputExceededException : AmazonDynamoDBException
{
/// <summary>
/// Constructs a new ProvisionedThroughputExceededException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ProvisionedThroughputExceededException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ProvisionedThroughputExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ProvisionedThroughputExceededException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ProvisionedThroughputExceededException
/// </summary>
/// <param name="innerException"></param>
public ProvisionedThroughputExceededException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ProvisionedThroughputExceededException
/// </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 ProvisionedThroughputExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ProvisionedThroughputExceededException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ProvisionedThroughputExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the ProvisionedThroughputExceededException 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 ProvisionedThroughputExceededException(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
}
} | 51.039063 | 184 | 0.69478 | [
"Apache-2.0"
] | JeffAshton/aws-sdk-net | sdk/src/Services/DynamoDBv2/Generated/Model/ProvisionedThroughputExceededException.cs | 6,533 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Groups the information computed by MakeOverriddenOrHiddenMembers.
/// </summary>
internal sealed class OverriddenOrHiddenMembersResult
{
public static readonly OverriddenOrHiddenMembersResult Empty =
new OverriddenOrHiddenMembersResult(
ImmutableArray<Symbol>.Empty,
ImmutableArray<Symbol>.Empty
);
private readonly ImmutableArray<Symbol> _overriddenMembers;
public ImmutableArray<Symbol> OverriddenMembers
{
get { return _overriddenMembers; }
}
private readonly ImmutableArray<Symbol> _hiddenMembers;
public ImmutableArray<Symbol> HiddenMembers
{
get { return _hiddenMembers; }
}
private OverriddenOrHiddenMembersResult(
ImmutableArray<Symbol> overriddenMembers,
ImmutableArray<Symbol> hiddenMembers
)
{
_overriddenMembers = overriddenMembers;
_hiddenMembers = hiddenMembers;
}
public static OverriddenOrHiddenMembersResult Create(
ImmutableArray<Symbol> overriddenMembers,
ImmutableArray<Symbol> hiddenMembers
)
{
if (overriddenMembers.IsEmpty && hiddenMembers.IsEmpty)
{
return Empty;
}
else
{
return new OverriddenOrHiddenMembersResult(overriddenMembers, hiddenMembers);
}
}
internal static Symbol GetOverriddenMember(
Symbol substitutedOverridingMember,
Symbol overriddenByDefinitionMember
)
{
Debug.Assert(!substitutedOverridingMember.IsDefinition);
if ((object)overriddenByDefinitionMember != null)
{
NamedTypeSymbol overriddenByDefinitionContaining =
overriddenByDefinitionMember.ContainingType;
NamedTypeSymbol overriddenByDefinitionContainingTypeDefinition =
overriddenByDefinitionContaining.OriginalDefinition;
for (
NamedTypeSymbol baseType =
substitutedOverridingMember.ContainingType.BaseTypeNoUseSiteDiagnostics;
(object)baseType != null;
baseType = baseType.BaseTypeNoUseSiteDiagnostics
)
{
if (
TypeSymbol.Equals(
baseType.OriginalDefinition,
overriddenByDefinitionContainingTypeDefinition,
TypeCompareKind.ConsiderEverything2
)
)
{
if (
TypeSymbol.Equals(
baseType,
overriddenByDefinitionContaining,
TypeCompareKind.ConsiderEverything2
)
)
{
return overriddenByDefinitionMember;
}
return overriddenByDefinitionMember.OriginalDefinition.SymbolAsMember(
baseType
);
}
}
throw ExceptionUtilities.Unreachable;
}
return null;
}
/// <summary>
/// It is not suitable to call this method on a <see cref="OverriddenOrHiddenMembersResult"/> object
/// associated with a member within substituted type, <see cref="GetOverriddenMember(Symbol, Symbol)"/>
/// should be used instead.
/// </summary>
internal Symbol GetOverriddenMember()
{
foreach (var overriddenMember in _overriddenMembers)
{
if (
overriddenMember.IsAbstract
|| overriddenMember.IsVirtual
|| overriddenMember.IsOverride
)
{
return overriddenMember;
}
}
return null;
}
}
}
| 34.642336 | 111 | 0.550569 | [
"MIT"
] | belav/roslyn | src/Compilers/CSharp/Portable/Symbols/OverriddenOrHiddenMembersResult.cs | 4,748 | C# |
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreOData.Service.Database;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNet.OData.Query;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace AspNetCoreOData.Service.Controllers
{
[Authorize(Policy = "ODataServiceApiPolicy", AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ODataRoutePrefix("ContactType")]
public class ContactTypeController : ODataController
{
private AdventureWorks2016Context _db;
public ContactTypeController(AdventureWorks2016Context AdventureWorks2016Context)
{
_db = AdventureWorks2016Context;
}
[ODataRoute()]
[EnableQuery(PageSize = 20, AllowedQueryOptions = AllowedQueryOptions.All)]
public IActionResult Get()
{
return Ok(_db.ContactTypes.AsQueryable());
}
[ODataRoute()]
[EnableQuery(PageSize = 20, AllowedQueryOptions = AllowedQueryOptions.All)]
public IActionResult Get([FromODataUri] int key)
{
return Ok(_db.ContactTypes.Find(key));
}
[ODataRoute()]
[HttpPost]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IActionResult Post(ContactType contactType)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_db.ContactTypes.AddOrUpdate(contactType);
_db.SaveChanges();
return Created(contactType);
}
[ODataRoute("({key})")]
[HttpPut]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IActionResult Put([FromODataUri] int key, ContactType contactType)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != contactType.ContactTypeId)
{
return BadRequest();
}
_db.ContactTypes.AddOrUpdate(contactType);
_db.SaveChanges();
return Updated(contactType);
}
[ODataRoute("")]
[HttpDelete]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IActionResult Delete([FromODataUri] int key)
{
var entityInDb = _db.ContactTypes.SingleOrDefault(t => t.ContactTypeId == key);
_db.ContactTypes.Remove(entityInDb);
_db.SaveChanges();
return NoContent();
}
[ODataRoute()]
[HttpPatch]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IActionResult Patch([FromODataUri] int key, Delta<ContactType> delta)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var contactType = _db.ContactTypes.Single(t => t.ContactTypeId == key);
delta.Patch(contactType);
_db.SaveChanges();
return Updated(contactType);
}
/// <summary>
/// This is a Odata Action for complex data changes...
/// </summary>
[HttpPost]
[ODataRoute("Default.ChangePersonStatus")]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IActionResult ChangePersonStatus(ODataActionParameters parameters)
{
if (ModelState.IsValid)
{
var level = parameters["Level"];
// SAVE THIS TO THE DATABASE OR WHATEVER....
}
return Ok(true);
}
}
}
| 31.341463 | 114 | 0.582101 | [
"MIT"
] | damienbod/AspNetCoreOData | AspNetCoreOData.Service/Controllers/ContactTypeController.cs | 3,857 | C# |
using System.Data.Entity.ModelConfiguration;
namespace OrganizationRegister.Store.CodeFirst.Model.Configuration
{
internal class WebPageConfiguration : EntityTypeConfiguration<WebPage>
{
public WebPageConfiguration()
{
HasKey(address => address.Id);
Property(address => address.Url).IsRequired();
Property(address => address.Name).IsRequired();
}
}
} | 28.266667 | 74 | 0.665094 | [
"MIT"
] | City-of-Helsinki/organisaatiorekisteri | Source/OrganizationRegister.Store.CodeFirst/Model/Configuration/WebPageConfiguration.cs | 424 | C# |
namespace WOD.Game.Server.Core.NWScript.Enum.Creature
{
public enum CreatureSize
{
Invalid,
Tiny,
Small,
Medium,
Large,
Huge
}
} | 15.666667 | 53 | 0.526596 | [
"MIT"
] | Cavcode/WOD_NWN | WOD.Game.Server/Core/NWScript/Enum/Creature/CreatureSize.cs | 188 | C# |
using System.Web;
using System.Web.Mvc;
namespace IntroduccionAMSCognitiveServices
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 20.357143 | 80 | 0.680702 | [
"MIT"
] | efonsecab/IntroProgramacion | src/IntroduccionAMSCognitiveServicesSln/IntroduccionAMSCognitiveServices/App_Start/FilterConfig.cs | 287 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using XE = System.Xml.Linq.XElement;
using C = Bugfree.OracleHospitality.Clients.PosParselets.Constants;
using static Bugfree.OracleHospitality.Clients.ParserHelpers;
namespace Bugfree.OracleHospitality.Clients.PosParselets
{
// Parses <Type tid="12">Accept Coupon</Type>
public class ActionType : IResponseElement
{
// We don't expose the "Accept Coupon" value because it maps one-to-one
// to TransactionId. We do, however, assert that it has the correct
// value.
public TransactionId Id { get; }
// According to POS API spec, Page 28.
public enum TransactionId
{
None,
AcceptCoupon = 12
}
readonly Dictionary<TransactionId, string> TidToString = new Dictionary<TransactionId, string>
{
{ TransactionId.AcceptCoupon, "Accept Coupon" }
};
public ActionType(XE actionType)
{
if (actionType == null)
throw new ArgumentNullException(nameof(actionType));
var tidAttribute = actionType.Attribute(C.tid);
var tidAttributeValue = int.Parse(tidAttribute.Value);
if (!Enum.IsDefined(typeof(TransactionId), tidAttributeValue))
throw new ArgumentException($"Unknown {nameof(C.tid)} '{tidAttributeValue}'");
Id = (TransactionId)int.Parse(tidAttribute.Value);
var success = TidToString.TryGetValue(Id, out var value);
if (!success)
throw new ArgumentException($"{nameof(TidToString)} mapping doesn't contain {nameof(TransactionId)} with value {tidAttribute.Value}");
if (value != actionType.Value)
throw new ArgumentException($"Expected Action Type element to have value '{value}'. Was '{actionType.Value}'");
// UNDOCUMENTED: type or length of Action/Type content. We can only
// assume an Ax of sufficient length to represent every
// TransactionId in textual form.
FieldTypes.AssertA25(actionType.Value);
}
}
public class ActionDataValue
{
public string Value { get; }
public ActionDataValue(string value)
{
// UNDOCUMENTED: POS API spec, Page 28 states that Data element's
// content is limited to 80 characters, but not which characters.
// From the table on Page 28, '/' isn't part of the existing Ax set
// and it's unclear whether it's correct to add it so we check
// length only.
const int DataElementValueMaxLength = 80;
if (value.Length > DataElementValueMaxLength)
throw new ArgumentException($"Expected Data element value to be less than {DataElementValueMaxLength} characters");
Value = value;
}
}
// Parses <Data pid="9">1004019</Data>
public class ActionData : IResponseElement
{
public PromptId Id { get; }
public ActionDataValue Value { get; }
// According to POS API spec, Page 28
public enum PromptId
{
None,
PleaseEnterCoupon = 9
}
public ActionData(XE actionData)
{
var pidAttribute = actionData.Attribute(C.pid);
var pidAttributeValue = int.Parse(pidAttribute.Value);
if (!Enum.IsDefined(typeof(PromptId), pidAttributeValue))
throw new ArgumentException($"Unknown {nameof(C.pid)} '{pidAttributeValue}'");
Id = (PromptId)pidAttributeValue;
Value = new ActionDataValue(actionData.Value);
}
}
// Parses <Code>10DKK</Code>
public class ActionCode : IResponseElement
{
public string Value { get; }
public ActionCode(XE actionCode)
{
// UNDOCUMENTED: here Code is short for coupon code, and so we
// assume its format is what ISSUE_COUPON operation uses for
// <CouponCode>.
if (string.IsNullOrWhiteSpace(actionCode.Value))
throw new ArgumentException($"{nameof(C.Action)}/{nameof(C.Code)} value must not be null or whitespace");
Value = actionCode.Value;
}
}
public class ActionTextValue
{
public string Value { get; }
public ActionTextValue(string value)
{
// UNDOCUMENTED: POS API spec, Page 28, states that text content is
// limited to 80 characters but not which characters of
// FieldTypes.Ax. Content is input by a human configuring the coupon
// and real world usage includes ",", ":", and " ".
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"{nameof(C.Text)} must contain non-whitespace characters");
const int MinValue = 1;
const int MaxValue = 80;
if (value.Length < MinValue || value.Length > MaxValue)
throw new ArgumentException($"{nameof(C.Text)} content not expected to be in range [{MinValue},{MaxValue}] characters");
Value = value;
}
}
// Parses <Text>Coupon: 10 DKK, Always Valid</Text>
public class ActionText : IResponseElement
{
public ActionTextValue Value { get; }
public ActionText(XE actionText)
{
Value = new ActionTextValue(actionText.Value);
}
}
public class Action : IResponseElement
{
public ActionType Type { get; }
public ActionData Data { get; }
public ActionCode Code { get; }
public ActionText Text { get; }
public Action(XE action)
{
var typeElement = ExpectElement(action, C.Type);
Type = new ActionType(typeElement);
var dataElement = ExpectElement(action, C.Data);
Data = new ActionData(dataElement);
// UNDOCUMENTED: POS API spec, Page 27, states that each <Action>
// element must contain <Type>, <Data>, and <Text> elements. It's
// unclear why <Code>, short for coupon code, is left out. It's part
// of the response of the COUPON_INQUIRY operation. Perhaps it isn't
// always part of the response of other operations or perhaps
// documentation is out of date.
var codeElement = ExpectElement(action, C.Code);
Code = new ActionCode(codeElement);
var textElement = ExpectElement(action, C.Text);
Text = new ActionText(textElement);
}
}
public class Actions : IResponseElement
{
/* Parses input of the form:
<Actions>
<Action>
<Type tid=""12"">Accept Coupon</Type>
<Data pid=""9"">1004019</Data>
<Code>10DKK</Code>
<Text>Coupon: 10 DKK, Always Valid</Text>
</Action>
</Actions>
*/
public ReadOnlyCollection<Action> Values { get; }
public Actions(XE actions)
{
var actionElements = ExpectElements(actions, C.Action);
Values = Array.AsReadOnly(actionElements.Select(ae => new Action(ae)).ToArray());
}
}
} | 37.641026 | 150 | 0.598093 | [
"BSD-2-Clause"
] | ronnieholm/Bugfree.OracleHospitality | src/Bugfree.OracleHospitality.Clients/PosParselets/Actions.cs | 7,342 | C# |
using System;
using System.Reflection;
// ReSharper disable once RedundantUsingDirective
using Imported.PeanutButter.Utils;
namespace NExpect.Implementations
{
internal static class TypeExtensions
{
private static readonly BindingFlags _findPublicPropertyAnywhereInInheritenceChain =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy;
internal static PropertyInfo GetPublicInstanceProperty(this Type t, string name)
{
return t.GetProperty(name, _findPublicPropertyAnywhereInInheritenceChain);
}
internal static PropertyInfo[] GetPublicInstanceProperties(this Type t)
{
return t.GetProperties(_findPublicPropertyAnywhereInInheritenceChain);
}
internal static T TryGetPropertyValue<T>(
this object o,
string prop)
{
var propInfo = o.GetType().GetPublicInstanceProperty(prop);
if (propInfo == null)
return default(T);
try
{
return (T) propInfo.GetValue(o);
}
catch
{
return default(T);
}
}
}
} | 30.45 | 92 | 0.619869 | [
"BSD-3-Clause"
] | fluffynuts/NExpect | src/NExpect/Implementations/TypeExtensions.cs | 1,220 | 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.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Rds.Model.V20140815;
namespace Aliyun.Acs.Rds.Transform.V20140815
{
public class TerminateMigrateTaskResponseUnmarshaller
{
public static TerminateMigrateTaskResponse Unmarshall(UnmarshallerContext context)
{
TerminateMigrateTaskResponse terminateMigrateTaskResponse = new TerminateMigrateTaskResponse();
terminateMigrateTaskResponse.HttpResponse = context.HttpResponse;
terminateMigrateTaskResponse.RequestId = context.StringValue("TerminateMigrateTask.RequestId");
return terminateMigrateTaskResponse;
}
}
}
| 37.05 | 99 | 0.765857 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-rds/Rds/Transform/V20140815/TerminateMigrateTaskResponseUnmarshaller.cs | 1,482 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DynamicProgramming
{
class SubSetSumRecursive
{
public void Main()
{
int[] arr = { 2, 3, 8, 12 };
int sum = 11;
int n = 4;
bool[,] t = new bool[n + 1, sum + 1];
bool result = SubSetSum(arr, sum, n, t);
Console.WriteLine("the result is {0}",result);
}
public bool SubSetSum(int[] arr,int sum,int n,bool[,] t)
{
if (n == 0 && sum==0)
{
return true;
}
if(n==0 && sum != 0)
{
return false;
}
if(sum==0 && n != 0)
{
return true;
}
if (arr[n - 1] <= sum)
{
return t[n, sum] = SubSetSum(arr,sum-arr[n-1],n-1,t) || SubSetSum(arr,sum,n-1,t);
}
else
{
return t[n, sum] = SubSetSum(arr, sum, n - 1, t);
}
}
}
}
| 24.363636 | 97 | 0.384328 | [
"MIT"
] | manas1803/Algoritms | Dynamic Programming/Code/DynamicProgramming/DynamicProgramming/SubSetSumRecursive.cs | 1,074 | 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("TupleExample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TupleExample")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("58c31173-86bd-4b1f-abcb-6bb86e1945d7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757 | 84 | 0.745168 | [
"MIT"
] | tanvirIqbal/Visual-Studio-Project | TupleExample/TupleExample/Properties/AssemblyInfo.cs | 1,400 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DescriptorToCommand.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "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 (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DescriptorToCommand.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;
}
}
}
}
| 43.765625 | 185 | 0.615494 | [
"Apache-2.0"
] | Silverfeelin/NPP-Starbound-DescriptorToCommand | DescriptorToCommand/Properties/Resources.Designer.cs | 2,803 | C# |
/*
* This message is auto generated by ROS#. Please DO NOT modify.
* Note:
* - Comments from the original code will be written in their own line
* - Variable sized arrays will be initialized to array of size 0
* Please report any issues at
* <https://github.com/siemens/ros-sharp>
*/
namespace RosSharp.RosBridgeClient.MessageTypes.Roborts
{
public class RobotDamage : Message
{
public const string RosMessageName = "roborts_msgs/RobotDamage";
// robot damage
public const byte ARMOR = 0;
public const byte OFFLINE = 1;
public const byte EXCEED_HEAT = 2;
public const byte EXCEED_POWER = 3;
public byte damage_type { get; set; }
public const byte FORWARD = 0;
public const byte LEFT = 1;
public const byte BACKWARD = 2;
public const byte RIGHT = 3;
public byte damage_source { get; set; }
public RobotDamage()
{
this.damage_type = 0;
this.damage_source = 0;
}
public RobotDamage(byte damage_type, byte damage_source)
{
this.damage_type = damage_type;
this.damage_source = damage_source;
}
}
}
| 28.255814 | 72 | 0.61893 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Webb-Bing/ARMS_RMUA2021_SImulation | Assets/RosSharpMessages/Roborts/msg/RobotDamage.cs | 1,215 | C# |
using Microsoft.Extensions.Configuration;
using System.Configuration;
using Thriot.Messaging.Services.Storage;
namespace Thriot.Messaging.WebApi
{
public class ConnectionStringResolver : IConnectionStringResolver
{
private readonly IConfiguration _configuration;
public ConnectionStringResolver(IConfiguration configuration)
{
_configuration = configuration;
}
public string ConnectionString => _configuration[$"ConnectionString:MessagingConnection"];
}
} | 29.055556 | 98 | 0.745698 | [
"MIT"
] | kpocza/thriot | Service/Messaging/Thriot.Messaging.WebApi/ConnectionStringResolver.cs | 525 | C# |
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using POESKillTree.Localization;
using POESKillTree.Model;
using POESKillTree.Utils;
namespace POESKillTree.Views
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
// The flag whether application exit is in progress.
bool IsExiting = false;
// The flag whether it is safe to exit application.
bool IsSafeToExit = false;
// Single instance of persistent data.
private static readonly PersistentData PrivatePersistentData = new PersistentData();
// Expose persistent data.
public static PersistentData PersistentData { get { return PrivatePersistentData; } }
// The Mutex for detecting running application instance.
private Mutex RunningInstanceMutex;
// The name of RunningInstanceMutex.
private static string RunningInstanceMutexName { get { return POESKillTree.Properties.Version.AppId; } }
// Invoked when application is about to exit.
private void App_Exit(object sender, ExitEventArgs e)
{
if (IsExiting) return;
IsExiting = true;
try
{
// Try to aquire mutex.
if (RunningInstanceMutex.WaitOne(0))
{
PrivatePersistentData.SavePersistentDataToFile();
IsSafeToExit = true;
RunningInstanceMutex.ReleaseMutex();
}
}
catch
{
// Too late to report anything.
}
}
// Invoked when application is being started up (before MainWindow creation).
private void App_Startup(object sender, StartupEventArgs e)
{
// Set main thread apartment state.
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
// Set AppUserModelId of current process.
TaskbarHelper.SetAppUserModelId();
// Create Mutex if this is first instance.
try
{
RunningInstanceMutex = Mutex.OpenExisting(RunningInstanceMutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
bool created = false;
RunningInstanceMutex = new Mutex(false, RunningInstanceMutexName, out created);
if (!created) throw new Exception("Unable to create application mutex");
}
// Load persistent data.
try
{
PrivatePersistentData.LoadPersistentDataFromFile();
}
catch (Exception ex)
{
MessageBox.Show("An error occurred during a load operation.\n\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
// Initialize localization.
L10n.Initialize(PrivatePersistentData);
}
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
if (!Debugger.IsAttached)
{
Exception theException = e.Exception;
string theErrorPath = AppData.GetFolder(true) + "debug.txt";
using (System.IO.TextWriter theTextWriter = new System.IO.StreamWriter(theErrorPath, true))
{
DateTime theNow = DateTime.Now;
theTextWriter.WriteLine("The error time: " + theNow.ToShortDateString() + " " +
theNow.ToShortTimeString());
while (theException != null)
{
theTextWriter.WriteLine("Exception: " + theException.ToString());
theException = theException.InnerException;
}
}
MessageBox.Show("The program crashed. A stack trace can be found at:\n" + theErrorPath);
e.Handled = true;
Application.Current.Shutdown();
}
}
// Invoked when Windows is being shutdown or user is being logged off.
protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
{
base.OnSessionEnding(e);
// Cancel session ending unless it's safe to exit.
e.Cancel = !IsSafeToExit;
// If Exit event wasn't raised yet, perform explicit shutdown (Windows 7 bug workaround).
if (!IsExiting) Shutdown();
}
}
}
| 38.015873 | 149 | 0.562004 | [
"MIT"
] | nikibobi/PoESkillTree | WPFSKillTree/Views/App.xaml.cs | 4,667 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Synapse.Latest.Inputs
{
/// <summary>
/// VNet properties for managed integration runtime.
/// </summary>
public sealed class IntegrationRuntimeVNetPropertiesArgs : Pulumi.ResourceArgs
{
[Input("publicIPs")]
private InputList<string>? _publicIPs;
/// <summary>
/// Resource IDs of the public IP addresses that this integration runtime will use.
/// </summary>
public InputList<string> PublicIPs
{
get => _publicIPs ?? (_publicIPs = new InputList<string>());
set => _publicIPs = value;
}
/// <summary>
/// The name of the subnet this integration runtime will join.
/// </summary>
[Input("subnet")]
public Input<string>? Subnet { get; set; }
/// <summary>
/// The ID of the VNet that this integration runtime will join.
/// </summary>
[Input("vNetId")]
public Input<string>? VNetId { get; set; }
public IntegrationRuntimeVNetPropertiesArgs()
{
}
}
}
| 29.723404 | 91 | 0.614173 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Synapse/Latest/Inputs/IntegrationRuntimeVNetPropertiesArgs.cs | 1,397 | C# |
namespace Connect4
{
sealed class Node
{
/// <summary>
/// Player that will play the next token
/// </summary>
private Connect4Player m_WhoseTurnItIs = null;
/// <summary>
/// Current state of the game stored in the node
/// </summary>
private GameGrid m_Grid = null;
/// <summary>
/// Depth of the node, the greater the number, the deeper in the tree
/// </summary>
private int m_Depth = new int();
/// <summary>
/// Column played since the last game state
/// </summary>
private int m_TokenAddedInColumn = new int();
/// <summary>
/// Create a new node.
/// </summary>
/// <param name="p_WhoseTurnItIs"> Whose turn it is to play. </param>
/// <param name="p_Grid"> The current grid. </param>
/// <param name="p_ColumnPlayed"> In which column we played to reach this node. </param>
/// <param name="m_depth"> The depth of the node. </param>
public Node(Connect4Player p_WhoseTurnItIs, GameGrid p_Grid, int p_ColumnPlayed, int m_depth)
{
m_WhoseTurnItIs = p_WhoseTurnItIs;
m_Grid = p_Grid;
m_TokenAddedInColumn = p_ColumnPlayed;
m_Depth = m_depth;
}
/// <summary>
/// Get whose turn it is to play.
/// </summary>
public Connect4Player WhoseTurnItIs
{
get
{
return m_WhoseTurnItIs;
}
}
/// <summary>
/// Get the grid of the node.
/// </summary>
public GameGrid Grid
{
get
{
return m_Grid;
}
}
/// <summary>
/// Get the depth of the node.
/// </summary>
public int Depth
{
get
{
return m_Depth;
}
}
/// <summary>
/// Get the column we played in to reach this node.
/// </summary>
public int TokenAddedInColumn
{
get
{
return m_TokenAddedInColumn;
}
}
}
} | 26.535714 | 101 | 0.48183 | [
"MIT"
] | LucasBousselet/SmartConnect4 | Connect4/Connect4/Minimax/Node.cs | 2,231 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace VueExample.Models
{
[Table("Wafer_Map_Parameters")]
public class WaferMap
{
[Column("id_wmp")]
public int Id { get; set; }
[Column("Wafer_id")]
public string WaferId { get; set; }
[Column("Orientation")]
public string Orientation { get; set; }
}
}
| 23.6 | 51 | 0.654661 | [
"MIT"
] | 7is7/SVR2.0 | Models/WaferMap.cs | 472 | C# |
//
// EnumFlagAttribute.cs
//
// Author:
// ${wuxingogo} <52111314ly@gmail.com>
//
// Copyright (c) 2016 ly-user
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using UnityEngine;
namespace wuxingogo.Runtime
{
public class EnumFlagAttribute : PropertyAttribute
{
public string enumName;
public EnumFlagAttribute() {}
public EnumFlagAttribute(string name)
{
enumName = name;
}
}
}
| 18.428571 | 76 | 0.687984 | [
"MIT"
] | ClassWarhammer/Base1 | WuxingogoRuntime/Attribute/EnumFlagAttribute.cs | 518 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System;
using System.ComponentModel;
using JetBrains.Annotations;
using NHibernate;
using OpenIddict.Core;
using OpenIddict.NHibernate;
using OpenIddict.NHibernate.Models;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Exposes the necessary methods required to configure the OpenIddict NHibernate services.
/// </summary>
public class OpenIddictNHibernateBuilder
{
/// <summary>
/// Initializes a new instance of <see cref="OpenIddictNHibernateBuilder"/>.
/// </summary>
/// <param name="services">The services collection.</param>
public OpenIddictNHibernateBuilder([NotNull] IServiceCollection services)
=> Services = services ?? throw new ArgumentNullException(nameof(services));
/// <summary>
/// Gets the services collection.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public IServiceCollection Services { get; }
/// <summary>
/// Amends the default OpenIddict NHibernate configuration.
/// </summary>
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictNHibernateBuilder"/>.</returns>
public OpenIddictNHibernateBuilder Configure([NotNull] Action<OpenIddictNHibernateOptions> configuration)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
Services.Configure(configuration);
return this;
}
/// <summary>
/// Configures the NHibernate stores to use the specified session factory
/// instead of retrieving it from the dependency injection container.
/// </summary>
/// <param name="factory">The <see cref="ISessionFactory"/>.</param>
/// <returns>The <see cref="OpenIddictNHibernateBuilder"/>.</returns>
public OpenIddictNHibernateBuilder UseSessionFactory([NotNull] ISessionFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return Configure(options => options.SessionFactory = factory);
}
/// <summary>
/// Configures OpenIddict to use the default OpenIddict Entity Framework entities, with the specified key type.
/// </summary>
/// <returns>The <see cref="OpenIddictNHibernateBuilder"/>.</returns>
public OpenIddictNHibernateBuilder ReplaceDefaultEntities<TKey>()
where TKey : IEquatable<TKey>
=> ReplaceDefaultEntities<OpenIddictApplication<TKey>,
OpenIddictAuthorization<TKey>,
OpenIddictScope<TKey>,
OpenIddictToken<TKey>, TKey>();
/// <summary>
/// Configures OpenIddict to use the specified entities, derived from the default OpenIddict Entity Framework entities.
/// </summary>
/// <returns>The <see cref="OpenIddictNHibernateBuilder"/>.</returns>
public OpenIddictNHibernateBuilder ReplaceDefaultEntities<TApplication, TAuthorization, TScope, TToken, TKey>()
where TApplication : OpenIddictApplication<TKey, TAuthorization, TToken>
where TAuthorization : OpenIddictAuthorization<TKey, TApplication, TToken>
where TScope : OpenIddictScope<TKey>
where TToken : OpenIddictToken<TKey, TApplication, TAuthorization>
where TKey : IEquatable<TKey>
{
Services.Configure<OpenIddictCoreOptions>(options =>
{
options.DefaultApplicationType = typeof(TApplication);
options.DefaultAuthorizationType = typeof(TAuthorization);
options.DefaultScopeType = typeof(TScope);
options.DefaultTokenType = typeof(TToken);
});
return this;
}
}
}
| 42.660194 | 127 | 0.638371 | [
"Apache-2.0"
] | khandakerakash/openiddict-core | src/OpenIddict.NHibernate/OpenIddictNHibernateBuilder.cs | 4,396 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.