content
stringlengths
23
1.05M
using Disqord.Serialization.Json; namespace Disqord.Gateway.Api.Models { public class UpdateVoiceStateJsonModel : JsonModel { [JsonProperty("guild_id")] public Snowflake GuildId; [JsonProperty("channel_id")] public Snowflake ChannelId; [JsonProperty("self_mute")] public bool SelfMute; [JsonProperty("self_deaf")] public bool SelfDeaf; } }
using uTinyRipper.Converters; using uTinyRipper.YAML; namespace uTinyRipper.Classes { public sealed class AudioReverbZone : Behaviour { public AudioReverbZone(AssetInfo assetInfo) : base(assetInfo) { } /// <summary> /// Less than 5.6.0 /// </summary> public static bool HasRoomRolloffFactor(Version version) => version.IsLess(5, 6); public override void Read(AssetReader reader) { base.Read(reader); MinDistance = reader.ReadSingle(); MaxDistance = reader.ReadSingle(); ReverbPreset = reader.ReadInt32(); Room = reader.ReadInt32(); RoomHF = reader.ReadInt32(); DecayTime = reader.ReadSingle(); DecayHFRatio = reader.ReadSingle(); Reflections = reader.ReadInt32(); ReflectionsDelay = reader.ReadSingle(); Reverb = reader.ReadInt32(); ReverbDelay = reader.ReadSingle(); HFReference = reader.ReadSingle(); if (HasRoomRolloffFactor(reader.Version)) { RoomRolloffFactor = reader.ReadSingle(); } Diffusion = reader.ReadSingle(); Density = reader.ReadSingle(); LFReference = reader.ReadSingle(); RoomLF = reader.ReadInt32(); } protected override YAMLMappingNode ExportYAMLRoot(IExportContainer container) { YAMLMappingNode node = base.ExportYAMLRoot(container); node.Add(MinDistanceName, MinDistance); node.Add(MaxDistanceName, MaxDistance); node.Add(ReverbPresetName, ReverbPreset); node.Add(RoomName, Room); node.Add(RoomHFName, RoomHF); node.Add(DecayTimeName, DecayTime); node.Add(DecayHFRatioName, DecayHFRatio); node.Add(ReflectionsName, Reflections); node.Add(ReflectionsDelayName, ReflectionsDelay); node.Add(ReverbName, Reverb); node.Add(ReverbDelayName, ReverbDelay); node.Add(HFReferenceName, HFReference); node.Add(DiffusionName, Diffusion); node.Add(DensityName, Density); node.Add(LFReferenceName, LFReference); node.Add(RoomLFName, RoomLF); return node; } public float MinDistance { get; set; } public float MaxDistance { get; set; } public int ReverbPreset { get; set; } public int Room { get; set; } public int RoomHF { get; set; } public int RoomLF { get; set; } public float DecayTime { get; set; } public float DecayHFRatio { get; set; } public int Reflections { get; set; } public float ReflectionsDelay { get; set; } public int Reverb { get; set; } public float ReverbDelay { get; set; } public float HFReference { get; set; } public float RoomRolloffFactor { get; set; } public float LFReference { get; set; } public float Diffusion { get; set; } public float Density { get; set; } public const string MinDistanceName = "m_MinDistance"; public const string MaxDistanceName = "m_MaxDistance"; public const string ReverbPresetName = "m_ReverbPreset"; public const string RoomName = "m_Room"; public const string RoomHFName = "m_RoomHF"; public const string DecayTimeName = "m_DecayTime"; public const string DecayHFRatioName = "m_DecayHFRatio"; public const string ReflectionsName = "m_Reflections"; public const string ReflectionsDelayName = "m_ReflectionsDelay"; public const string ReverbName = "m_Reverb"; public const string ReverbDelayName = "m_ReverbDelay"; public const string HFReferenceName = "m_HFReference"; public const string DiffusionName = "m_Diffusion"; public const string DensityName = "m_Density"; public const string LFReferenceName = "m_LFReference"; public const string RoomLFName = "m_RoomLF"; } }
using System.Collections.Generic; namespace TicketBOT.JIRA.Models { public class ServiceDesk { public string id { get; set; } public string projectId { get; set; } public string projectName { get; set; } public string projectKey { get; set; } public string email { get; set; } public Links _links { get; set; } } public class ServicedeskDetails { public int size { get; set; } public int start { get; set; } public int limit { get; set; } public bool isLastPage { get; set; } public Links _links { get; set; } public IList<ServiceDesk> values { get; set; } } }
using System.Data; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.Extensions.Configuration; using Serilog; using Serilog.Events; using Serilog.Filters; using Serilog.Sinks.MSSqlServer; namespace GRA.Web { public class LogConfig { private const string ErrorControllerName = "GRA.Controllers.ErrorController"; private const string ApplicationEnrichment = "Application"; private const string VersionEnrichment = "Version"; private const string IdentifierEnrichment = "Identifier"; private const string InstanceEnrichment = "Instance"; private const string RemoteAddressEnrichment = "RemoteAddress"; public LoggerConfiguration Build(IConfiguration config, string instance, string[] args) { var applicationName = Assembly.GetExecutingAssembly().GetName().Name; var version = Assembly.GetExecutingAssembly().GetName().Version; LoggerConfiguration loggerConfig = new LoggerConfiguration() .ReadFrom.Configuration(config) .Enrich.WithProperty(ApplicationEnrichment, applicationName) .Enrich.WithProperty(VersionEnrichment, version) .Enrich.FromLogContext() .WriteTo.Console(); string rollingLogLocation = config[ConfigurationKey.RollingLogPath]; if (!string.IsNullOrEmpty(rollingLogLocation)) { if (!rollingLogLocation.EndsWith(Path.DirectorySeparatorChar)) { rollingLogLocation += Path.DirectorySeparatorChar; } rollingLogLocation += "log-"; string rollingLogFile = rollingLogLocation + instance + "-{Date}.txt"; loggerConfig.WriteTo.Logger(_ => _ .Filter.ByExcluding(Matching.FromSource(ErrorControllerName)) .WriteTo.RollingFile(rollingLogFile)); string httpErrorFileTag = config[ConfigurationKey.RollingLogHttp]; if (!string.IsNullOrEmpty(httpErrorFileTag)) { string httpLogFile = rollingLogLocation + instance + "-" + httpErrorFileTag + "-{Date}.txt"; loggerConfig.WriteTo.Logger(_ => _ .Filter.ByIncludingOnly(Matching.FromSource(ErrorControllerName)) .WriteTo.RollingFile(httpLogFile)); } } string sqlLog = config.GetConnectionString(ConfigurationKey.CSSqlServerSerilog); if (!string.IsNullOrEmpty(sqlLog)) { loggerConfig .WriteTo.Logger(_ => _ .Filter.ByExcluding(Matching.FromSource(ErrorControllerName)) .WriteTo.MSSqlServer(sqlLog, "Logs", autoCreateSqlTable: true, restrictedToMinimumLevel: LogEventLevel.Information, columnOptions: new ColumnOptions { AdditionalDataColumns = new DataColumn[] { new DataColumn(ApplicationEnrichment, typeof(string)) { MaxLength = 255 }, new DataColumn(VersionEnrichment, typeof(string)) { MaxLength = 255 }, new DataColumn(IdentifierEnrichment, typeof(string)) { MaxLength = 255 }, new DataColumn(InstanceEnrichment, typeof(string)) { MaxLength = 255 }, new DataColumn(RemoteAddressEnrichment, typeof(string)) { MaxLength = 255 } } })); } return loggerConfig; } } }
using Logic.JudgementForms.BehaviourContratcs; using Logic.JudgementForms.PredicateForm.BehaviourContracts; namespace Logic.JudgementForms.PredicateForm { class PredicateForm { private readonly IPredicateForm _form; public PredicateForm() { _form = new EmptyForm(); } public PredicateForm(IPredicateForm form) { _form = form; } public IPredicateForm Form { get { return (IPredicateForm)_form; } } } }
namespace MassTransit.Monitoring.Performance { using System; public interface IMessagePerformanceCounter { /// <summary> /// A message was consumed, including the consume duration /// </summary> /// <param name="duration"></param> void Consumed(TimeSpan duration); /// <summary> /// A message faulted while being consumed /// </summary> /// <param name="duration"></param> void ConsumeFaulted(TimeSpan duration); /// <summary> /// A message was sent /// </summary> void Sent(); /// <summary> /// A message was published /// </summary> void Published(); /// <summary> /// A publish faulted /// </summary> void PublishFaulted(); /// <summary> /// A send faulted /// </summary> void SendFaulted(); } }
using System; using System.Collections.Generic; using System.Text; namespace Objectiks.Engine.Query { public class QueryParameters : List<QueryParameter> { } public class QueryParameter { public string Field { get; set; } public object Value { get; set; } public OperationType Operator { get; set; } public ParameterType Type { get; set; } } }
using System.Collections.Generic; namespace SizeOnDisk.Shell { public class ShellCommandRoot { public string ContentType { get; set; } public string PerceivedType { get; set; } public ShellCommandSoftware Default { get; set; } public IList<ShellCommandSoftware> Softwares { get; } = new List<ShellCommandSoftware>(); } }
using UnityEngine; using System.Collections; public class WrapProjectilesAroundWorld : MonoBehaviour { public GameObject LeftEdge; public GameObject RightEdge; public float Border; void Start () { } void Update () { var left = Camera.main.ViewportToWorldPoint (new Vector3 (0.0f, 0.5f)); this.LeftEdge.transform.position = new Vector3(left.x, 0.0f); var right = Camera.main.ViewportToWorldPoint (new Vector3 (1.0f, 0.5f)); this.RightEdge.transform.position = new Vector3(right.x, 0.0f); Projectile[] projectiles = FindObjectsOfType(typeof(Projectile)) as Projectile[]; foreach (Projectile projectile in projectiles) { var p = projectile.gameObject.transform.position; var lx = this.LeftEdge.transform.position.x; var rx = this.RightEdge.transform.position.x; if (p.x < lx) { projectile.gameObject.transform.position = new Vector3 (rx - this.Border, p.y, p.z); } else if (p.x > rx) { projectile.gameObject.transform.position = new Vector3 (lx + this.Border, p.y, p.z); } } } }
using NPoco; using Umbraco.Core.Migrations.Expressions.Alter.Expressions; using Umbraco.Core.Migrations.Expressions.Alter.Table; namespace Umbraco.Core.Migrations.Expressions.Alter { /// <summary> /// Implements <see cref="IAlterBuilder"/>. /// </summary> public class AlterBuilder : IAlterBuilder { private readonly IMigrationContext _context; public AlterBuilder(IMigrationContext context) { _context = context; } /// <inheritdoc /> public IAlterTableBuilder Table(string tableName) { var expression = new AlterTableExpression(_context) { TableName = tableName }; return new AlterTableBuilder(_context, expression); } } }
namespace Client.Features.Edge { using BlazorState; using System.Collections.Generic; using System.Linq; public partial class EdgeCurrencyWalletsState : State<EdgeCurrencyWalletsState> { public EdgeCurrencyWalletsState() { EdgeCurrencyWallets = new Dictionary<string, EdgeCurrencyWallet>(); } public Dictionary<string, EdgeCurrencyWallet> EdgeCurrencyWallets { get; set; } public EdgeCurrencyWallet SelectedEdgeCurrencyWallet { get { if (SelectedEdgeCurrencyWalletId != null && EdgeCurrencyWallets.ContainsKey(SelectedEdgeCurrencyWalletId)) { return EdgeCurrencyWallets[SelectedEdgeCurrencyWalletId]; }; if (EdgeCurrencyWallets.Count > 0) { return EdgeCurrencyWallets.First().Value; } return null; } } public string SelectedEdgeCurrencyWalletId { get; set; } public override void Initialize() => EdgeCurrencyWallets = new Dictionary<string, EdgeCurrencyWallet>(); } }
namespace Xamarin.CommunityToolkit.PlatformConfiguration.AndroidSpecific { public enum NavigationBarStyle { Default = 0, LightContent = 1, DarkContent = 2 } }
using DataHelper; using Il2CppSystem.Collections.Generic; namespace GunfireLib.Data { public static class MobileBulletData { public static Dictionary<int, itemdataclass> attributeList; public static System.Collections.Generic.Dictionary<int, Classes.ItemDataClass> parsedAttributeList = new System.Collections.Generic.Dictionary<int, Classes.ItemDataClass>(); internal static void Setup() { attributeList = mobilebulletdata.GetData(); foreach (KeyValuePair<int, itemdataclass> bullet in attributeList) { parsedAttributeList.Add(bullet.Key, new Classes.ItemDataClass(bullet.Key, attributeList)); } } } }
using System; namespace transfluent { public class RestUrl { //public enum TransfluentMethodType { Hello, Authenticate, Register, Languages, Text, Texts, TextStatus, //TextsTranslate, TextWordCount, CombinedTexts_Send, CombinedTexts_Translate }; private static string baseServiceUrl = "https://transfluent.com/v2/"; public static Route GetRouteAttribute(Type callToGetUrlFor) { object[] routeable = callToGetUrlFor.GetCustomAttributes(typeof(Route), true); if(routeable.Length == 0) { throw new Exception("tried to get a url from a non-routable object:" + callToGetUrlFor.GetType()); } return (routeable[0] as Route); } public static string GetURL(ITransfluentParameters callToGetUrlFor) { return baseServiceUrl + GetRouteAttribute(callToGetUrlFor.GetType()).route; } } }
using DotLiquid; using System.Text.RegularExpressions; namespace GitWebLinks; public static class RemoteServerTests { public class SingleStaticServer { private readonly RemoteServer _server = new( new StaticServer( "http://example.com:8000", "ssh://git@example.com:9000" ) ); [Fact] public async Task ShouldReturnNullWhenThereIsNoMatch() { Assert.Null(await _server.MatchAsync("http://example.com:10000/foo/bar")); } [Fact] public async Task ShouldReturnTheServerWhenMatchingToTheHttpAddress() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("http://example.com:8000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldReturnTheServerwhenMatchingToTheSshAddressWithTheSshProtocol() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("ssh://git@example.com:9000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldReturnTheServerWhenMatchingToTheSshAddressWithoutTheSshProtocol() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("git@example.com:9000/foo/bar"), StaticServerComparer.Instance ); } } public class MultipleStaticServers { private readonly RemoteServer _server = new( new IServer[] { new StaticServer("http://example.com:8000","ssh://git@example.com:9000"), new StaticServer("http://test.com:6000","ssh://git@test.com:7000") } ); [Fact] public async Task ShouldReturnNullWhenThereIsNoMatch() { Assert.Null(await _server.MatchAsync("http://example.com:10000/foo/bar")); } [Fact] public async Task ShouldReturnTheMatchingServerWhenMatchingToTheHttpAddress() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("http://example.com:8000/foo/bar"), StaticServerComparer.Instance ); Assert.Equal( new StaticServer("http://test.com:6000", "ssh://git@test.com:7000"), await _server.MatchAsync("http://test.com:6000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldReturnTheMatchingServerWhenMatchingToTheSshAddressWithTheSshProtocol() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("ssh://git@example.com:9000/foo/bar"), StaticServerComparer.Instance ); Assert.Equal( new StaticServer("http://test.com:6000", "ssh://git@test.com:7000"), await _server.MatchAsync("ssh://git@test.com:7000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldReturnTheMatchingServerWhenMatchingToTheSshAddressWithoutTheSshProtocol() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("git@example.com:9000/foo/bar"), StaticServerComparer.Instance ); Assert.Equal( new StaticServer("http://test.com:6000", "ssh://git@test.com:7000"), await _server.MatchAsync("git@test.com:7000/foo/bar"), StaticServerComparer.Instance ); } } public class SingleDynamicServer { private readonly RemoteServer _server = new( new DynamicServer( new Regex("http://(.+)\\.example\\.com:8000"), Template.Parse("http://example.com:8000/repos/{{ match[1] }}"), Template.Parse("ssh://git@example.com:9000/_{{ match[1] }}") ) ); [Fact] public async Task ShouldReturnNullWhenThereIsNoMatch() { Assert.Null(await _server.MatchAsync("http://example.com:8000/foo/bar")); } [Fact] public async Task ShouldCreateTheDetailsOfTheMatchingServer() { Assert.Equal( new StaticServer("http://example.com:8000/repos/foo", "ssh://git@example.com:9000/_foo"), await _server.MatchAsync("http://foo.example.com:8000/bar/meep"), StaticServerComparer.Instance ); } } public class MultipleDynamicServers { private readonly RemoteServer _server = new( new IServer[] { new DynamicServer( new Regex("http://(.+)\\.example\\.com:8000"), Template.Parse("http://example.com:8000/repos/{{ match[1] }}"), Template.Parse("ssh://git@example.com:9000/_{{ match[1] }}") ), new DynamicServer( new Regex("ssh://git@example\\.com:9000/_([^/]+)"), Template.Parse("http://example.com:8000/repos/{{ match[1] }}"), Template.Parse("ssh://git@example.com:9000/_{{ match[1] }}") ) } ); [Fact] public async Task ShouldReturnNullWhenThereIsNoMatch() { Assert.Null(await _server.MatchAsync("http://example.com:8000/foo/bar")); } [Fact] public async Task ShouldCreateTheDetailsOfTheMatchingServer() { Assert.Equal( new StaticServer("http://example.com:8000/repos/foo", "ssh://git@example.com:9000/_foo"), await _server.MatchAsync("http://foo.example.com:8000/bar/meep"), StaticServerComparer.Instance ); Assert.Equal( new StaticServer("http://example.com:8000/repos/foo", "ssh://git@example.com:9000/_foo"), await _server.MatchAsync("ssh://git@example.com:9000/_foo/bar"), StaticServerComparer.Instance ); } } public class MixedStaticAndDynamicServers { private readonly RemoteServer _server = new( new IServer[] { new DynamicServer( new Regex("http://(.+)\\.example\\.com:8000"), Template.Parse("http://example.com:8000/repos/{{ match[1] }}"), Template.Parse("ssh://git@example.com:9000/_{{ match[1] }}") ), new StaticServer( "http://example.com:10000", "ssh://git@example.com:11000" ) } ); [Fact] public async Task ShouldReturnNullWhenThereIsNoMatch() { Assert.Null(await _server.MatchAsync("http://example.com:7000/foo/bar")); } [Fact] public async Task ShouldReturnTheMatchingServerWhenMatchingToTheStaticServer() { Assert.Equal( new StaticServer("http://example.com:10000", "ssh://git@example.com:11000"), await _server.MatchAsync("http://example.com:10000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldCreateTheDetailsOfTheMatchingServerWhenMatchingToTheDynamicServer() { Assert.Equal( new StaticServer("http://example.com:8000/repos/foo", "ssh://git@example.com:9000/_foo"), await _server.MatchAsync("http://foo.example.com:8000/bar/meep"), StaticServerComparer.Instance ); } } public class StaticServerFactory { private IEnumerable<StaticServer> _source; private readonly RemoteServer _server; public StaticServerFactory() { _source = new[] { new StaticServer("http://example.com:8000","ssh://git@example.com:9000"), new StaticServer("http://test.com:6000","ssh://git@test.com:7000") }; _server = new RemoteServer(() => Task.FromResult(_source)); } [Fact] public async Task ShouldReturnNullWhenThereIsNoMatch() { Assert.Null(await _server.MatchAsync("http://example.com:9000/foo/bar")); } [Fact] public async Task ShouldReturnTheMatchingServerWhenMatchingToTheHttpAddress() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("http://example.com:8000/foo/bar"), StaticServerComparer.Instance ); Assert.Equal( new StaticServer("http://test.com:6000", "ssh://git@test.com:7000"), await _server.MatchAsync("http://test.com:6000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldReturnTheMatchingServerWhenMatchingToTheSshAddress() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("ssh://git@example.com:9000/foo/bar"), StaticServerComparer.Instance ); Assert.Equal( new StaticServer("http://test.com:6000", "ssh://git@test.com:7000"), await _server.MatchAsync("ssh://git@test.com:7000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldReturnTheMatchingServerWhenTheRemoteUrlIsAnHttpAddresAndTheServerHasNoSshUrl() { _source = new[] { new StaticServer("http://example.com:8000", null) }; Assert.Equal( new StaticServer("http://example.com:8000", null), await _server.MatchAsync("http://example.com:8000/foo/bar"), StaticServerComparer.Instance ); } [Fact] public async Task ShouldNotReturnMatchWhenTheRemoteUrlIsAnSshAddressAndTheServerHNoSshURL() { _source = new[] { new StaticServer("http://example.com:8000", null) }; Assert.Null(await _server.MatchAsync("ssh://git@test.com:7000/foo/bar")); } [Fact] public async Task ShouldNotCacheTheServersReturnedFromTheFactory() { Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("http://example.com:8000/foo/bar"), StaticServerComparer.Instance ); _source = new[] { new StaticServer("http://test.com:6000", "ssh://git@test.com:7000") }; Assert.Null(await _server.MatchAsync("http://example.com:8000/foo/bar")); _source = new[] { new StaticServer("http://example.com:8000", "ssh://git@example.com:9000") }; Assert.Equal( new StaticServer("http://example.com:8000", "ssh://git@example.com:9000"), await _server.MatchAsync("http://example.com:8000/foo/bar"), StaticServerComparer.Instance ); } } private class StaticServerComparer : IEqualityComparer<StaticServer?> { public static StaticServerComparer Instance { get; } = new StaticServerComparer(); public bool Equals(StaticServer? x, StaticServer? y) { if (x is null) { return y is null; } if (y is null) { return false; } return string.Equals(x.Http, y.Http, StringComparison.Ordinal) && string.Equals(x.Ssh, y.Ssh, StringComparison.Ordinal); } public int GetHashCode(StaticServer? obj) { return 0; } } }
@{ ViewData["Title"] = "Sign up Success"; } <h2>@ViewData["Title"]</h2> <h3>You have successfully signed up. Please follow the <a href="https://github.com/mspnp/multitenant-saas-guidance/blob/master/docs/running-the-app.md#assign-application-roles">documentation to assign application roles</a>.</h3>
using System; using System.Collections.Generic; using System.Collections.Specialized; using SDNUOJ.Controllers.Exception; using SDNUOJ.Configuration; using SDNUOJ.Entity; namespace SDNUOJ.Controllers.Core { /// <summary> /// 配置文件管理类 /// </summary> internal static class ConfigurationFileManager { /// <summary> /// 获取配置信息 /// </summary> /// <returns>配置信息</returns> public static IMethodResult AdminGetConfigPairList() { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } NameValueCollection col = ConfigurationManager.GetConfigCollection(); List<KeyValuePair<String, String>> list = new List<KeyValuePair<String, String>>(); foreach (String key in col.AllKeys) { list.Add(new KeyValuePair<String, String>(key, col[key])); } return MethodResult.Success(list); } /// <summary> /// 保存配置到配置文件 /// </summary> /// <param name="col">配置信息</param> public static IMethodResult AdminSaveToConfig(NameValueCollection col) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!ConfigurationManager.SaveToConfig(col)) { return MethodResult.FailedAndLog("The configuration has not been modified!"); } return MethodResult.SuccessAndLog("Admin update web.config"); } } }
using System; namespace SilentOrbit.Parsing { /// <summary> /// Helps to send only a subtree of the document to an ITagOutput /// Not used at the moment /// </summary> public abstract class NestedTagOutput : ITagOutput { /// <summary> /// Current root being sent /// </summary> Tag subTag; /// <summary> /// Where to send all messages /// </summary> ITagOutput subOutput; protected NestedTagOutput() { } protected abstract ITagOutput ParseTag(Tag tag); #region ITagOutput implementation public void ParsedAttribute(Tag tag, TagNamespace ns, string key, string val) { if (subOutput != null) subOutput.ParsedAttribute(tag, ns, key, val); } public void ParsedOpeningTag(Tag tag) { if (subOutput == null) { subOutput = ParseTag(tag); if (subOutput == null) return; subTag = tag; } subOutput.ParsedOpeningTag(tag); } public void ParsedClosingTag(Tag tag) { if (subOutput != null) subOutput.ParsedClosingTag(tag); if (subTag == tag) { subOutput = null; subTag = null; } } public void ParsedText(string decodedText) { if (subOutput != null) subOutput.ParsedText(decodedText); } public abstract void ParseError(string message); #endregion } }
using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Gadgetry.Tasks; /// <summary> /// A feature used to interact with the <b>"tasks"</b> functionality of a <see cref="Gadget"/>. /// </summary> public class GadgetTasksFeature : IGadgetRunFeature { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal readonly List<GadgetTask> tasks = new(); /// <summary> /// A collection of all <see cref="GadgetTask"/> that are associated with the <see cref="Gadget"/>. /// </summary> /// <remarks> /// These tasks are executed during the <see cref="GadgetRuntime"/> execution. /// </remarks> public IReadOnlyList<GadgetTask> Tasks => tasks; /// <summary> /// Creates a new instance of the <see cref="GadgetTasksFeature"/> class. /// </summary> public GadgetTasksFeature() { } async Task IGadgetRunFeature.RunAsync(GadgetRuntime gadgetRuntime, CancellationToken cancellationToken) { var awaitAll = new List<Task>(); foreach (var task in Tasks) { var taskRunner = Task.Run(() => task.TaskCallback(gadgetRuntime, cancellationToken), cancellationToken); awaitAll.Add(taskRunner); } foreach (var awaitTarget in awaitAll) { await awaitTarget; } } }
using AlwaysEncryptedSample.Models; namespace AlwaysEncryptedSample.Migrations { using System.Data.Entity.Migrations; internal sealed class AuthConfiguration : DbMigrationsConfiguration<AuthDbContext> { public AuthConfiguration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; ContextKey = "AlwaysEncryptedSample.Models.AuthDbContext"; } /// <remarks>This method will be called after migrating to the latest version.</remarks> protected override void Seed(AuthDbContext context) { } } internal sealed class AppConfiguration : DbMigrationsConfiguration<ApplicationDbContext> { public AppConfiguration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; ContextKey = "AlwaysEncryptedSample.Models.AuthDbContext"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ffsti.Library; using FluentAssertions; using Xunit; namespace Ffsti.Library.Tests.ExtensionMethods { public class StringExtensionMethodsTests { [Theory] [InlineData("68752076000107")] [InlineData("68.752.076/0001-07")] public void ValidateCnpj_ShouldBeTrue(string value) { var isValid = value.ValidateCnpj(); isValid.Should().BeTrue(); } [Theory] [InlineData("68752076000108")] [InlineData("68.752.076/0001-08")] public void ValidateCnpj_ShouldBeFalse(string value) { var isValid = value.ValidateCnpj(); isValid.Should().BeFalse(); } } }
using System.Collections.Generic; using System.Runtime.Serialization; using ReactiveUI; using SimpleDraw.ViewModels.Primitives; namespace SimpleDraw.ViewModels.Media { [DataContract(IsReference = true)] public class RelativePointViewModel : ViewModelBase { private PointViewModel _point; private RelativeUnit _unit; [DataMember(IsRequired = false, EmitDefaultValue = true)] public PointViewModel Point { get => _point; set => this.RaiseAndSetIfChanged(ref _point, value); } [DataMember(IsRequired = false, EmitDefaultValue = true)] public RelativeUnit Unit { get => _unit; set => this.RaiseAndSetIfChanged(ref _unit, value); } public RelativePointViewModel() { } public RelativePointViewModel(PointViewModel point, RelativeUnit unit) { _point = point; _unit = unit; } public RelativePointViewModel(double x, double y, RelativeUnit unit) { _point = new PointViewModel(x, y); _unit = unit; } public RelativePointViewModel CloneSelf(Dictionary<ViewModelBase, ViewModelBase> shared) { if (shared.TryGetValue(this, out var value)) { return value as RelativePointViewModel; } var copy = new RelativePointViewModel() { Point = _point?.CloneSelf(shared), Unit = _unit }; shared[this] = copy; return copy; } public override ViewModelBase Clone(Dictionary<ViewModelBase, ViewModelBase> shared) { return CloneSelf(shared); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; namespace SimpleAI.Behaviours { /// <summary> /// This behaviour allows to define a list of point which should be visited in /// a sequential fashion. When last point is reached, the whole behaviour starts /// over, going to point #1 and repeating sequence. /// /// How it works: /// A list of AIBehaviourGoto instances is being build and added to local /// subbehaviours container. /// </summary> public class AIBehaviourCyclicRoute : AIBehaviour { protected List<AINode> nodesToVisit; protected bool initialized; protected int sequenceCounter; public AIBehaviourCyclicRoute() { initialized = false; nodesToVisit = new List<AINode>(); } ~AIBehaviourCyclicRoute() { } public void AddPoint(ref AINode intermediateNode) { nodesToVisit.Add(intermediateNode); } public override void Reset() { sequenceCounter = 0; this.state = AIBehaviourState.Idle; base.Reset(); } public override void OnBehaviourFinish(int finishedBehaviour) { base.OnBehaviourFinish(finishedBehaviour); sequenceCounter++; if (sequenceCounter > nodesToVisit.Count - 1) { this.Reset(); } else { // stop actor for a moment, until we get new desired direction this.character.DesiredOrientation = new Vector3(0); this.character.DesiredDirection = this.character.DesiredOrientation; } } protected void OnSubbehaviourFinish(int finishedSubBehaviour) { if (finishedSubBehaviour >= nodesToVisit.Count) { this.Reset(); } } public override void Iterate(Microsoft.Xna.Framework.GameTime gameTime) { if (!initialized) { subbehaviours = new AISubbehaviours(nodesToVisit.Count); if (character != null) { // 1 add goto behaviour from character position to first node AIBehaviour newBehaviour = new AIBehaviourGoTo(); newBehaviour.Character = this.character; newBehaviour.Map = this.map; // loop for (int index = 0; index < nodesToVisit.Count - 1; index++) { AIBehaviour newIBehaviour = new AIBehaviourGoTo(); newIBehaviour.Character = this.character; newIBehaviour.Map = this.map; ((AIBehaviourGoTo)(newIBehaviour)).StartNode = nodesToVisit[index]; ((AIBehaviourGoTo)(newIBehaviour)).EndNode = nodesToVisit[index + 1]; subbehaviours.Add(ref newIBehaviour); } newBehaviour = new AIBehaviourGoTo(); newBehaviour.Character = this.character; newBehaviour.Map = this.map; ((AIBehaviourGoTo)(newBehaviour)).StartNode = nodesToVisit[nodesToVisit.Count - 1]; ((AIBehaviourGoTo)(newBehaviour)).EndNode = nodesToVisit[0]; subbehaviours.Add(ref newBehaviour); // add goto behaviour from last position to first position } initialized = true; } base.Iterate(gameTime); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DSharpPlus.Entities; namespace DSharpPlus.SlashCommands.Entities.Builders { public class InteractionApplicationCommandCallbackDataBuilder : IBuilder<InteractionApplicationCommandCallbackData> { public bool? TextToSpeech { get; set; } public string? Content { get; set; } public List<DiscordEmbed> Embeds { get; set; } = new(); public List<IMention> AllowedMentions { get; set; } = new(); public InteractionApplicationCommandCallbackDataBuilder() { } public InteractionApplicationCommandCallbackDataBuilder WithTTS() { TextToSpeech = true; return this; } public InteractionApplicationCommandCallbackDataBuilder WithContent(string content) { Content = content; return this; } public InteractionApplicationCommandCallbackDataBuilder WithEmbed(DiscordEmbed embed) { Embeds.Add(embed); return this; } public InteractionApplicationCommandCallbackDataBuilder WithAllowedMention(IMention mention) { AllowedMentions.Add(mention); return this; } public InteractionApplicationCommandCallbackData Build() { if (Embeds.Count <= 0 && (Content is null || Content == "")) throw new Exception("Either an embed or content is required."); return new InteractionApplicationCommandCallbackData() { AllowedMentions = AllowedMentions.Count > 0 ? AllowedMentions : null, Embeds = Embeds.Count > 0 ? Embeds.ToArray() : null, Content = Content, TextToSpeech = TextToSpeech }; } } }
// ---------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------- using System; using System.ComponentModel; using System.Windows.Media.Imaging; using ODataWinPhoneQuickstart; namespace ODataWinPhoneQuickstart.DataServiceContext.Netflix { // Extend the Title class to bind to the media resource URI. public partial class Title { private BitmapImage _image; // Returns the media resource URI for binding. public BitmapImage DefaultImage { get { if (_image == null) { // Get the URI for the media resource stream. return App.ViewModel.GetImage(this); } else { return _image; } } set { _image = value; OnPropertyChanged("DefaultImage"); } } } }
using System; namespace LibCommon.Enums { /// <summary> /// 设备网络类型 /// </summary> [Serializable] public enum DeviceNetworkType { Mobile, //移动网络 Fixed //固定网络 } }
// ---------------------------------------------------------- // <project>QCV</project> // <author>Christoph Heindl</author> // <copyright>Copyright (c) Christoph Heindl 2010</copyright> // <license>New BSD</license> // ---------------------------------------------------------- using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.Serialization; using Emgu.CV; using Emgu.CV.Structure; using QCV.Base.Extensions; namespace QCV.Toolbox { /// <summary> /// A filter that records a video. /// </summary> [Base.Addin] [Serializable] public class RecordVideo : Base.Resource, Base.IFilter, ISerializable { /// <summary> /// Videowriter backend /// </summary> private VideoWriter _vw = null; /// <summary> /// Path to record to /// </summary> private string _path = "video.avi"; /// <summary> /// The key name to fetch the image from the bundle. /// </summary> private string _bag_name = "source"; /// <summary> /// Target frames per second /// </summary> private int _fps = 30; /// <summary> /// Frame width /// </summary> private int _frame_width = 320; /// <summary> /// Frame height /// </summary> private int _frame_height = 200; /// <summary> /// Initializes a new instance of the RecordVideo class. /// </summary> public RecordVideo() {} /// <summary> /// Initializes a new instance of the RecordVideo class. /// </summary> /// <param name="info">Serialization info</param> /// <param name="context">Streaming context</param> protected RecordVideo(SerializationInfo info, StreamingContext context) { _path = (string)info.GetValue("path", typeof(string)); _bag_name = (string)info.GetValue("bag_name", typeof(string)); _fps = (int)info.GetValue("fps", typeof(int)); _frame_width = (int)info.GetValue("frame_width", typeof(int)); _frame_height = (int)info.GetValue("frame_height", typeof(int)); } /// <summary> /// Gets or sets the target frame height /// </summary> public int FrameHeight { get { return _frame_height; } set { _frame_height = value; } } /// <summary> /// Gets or sets the target frame width /// </summary> public int FrameWidth { get { return _frame_width; } set { _frame_width = value; } } /// <summary> /// Gets or sets the target frames per second. /// </summary> public int FPS { get { return _fps; } set { _fps = value; } } /// <summary> /// Gets or sets the path of the output video file. /// </summary> public string VideoPath { get { return _path; } set { _path = value; } } /// <summary> /// Gets or sets the key of the image to use as video input in the bundle. /// </summary> public string BagName { get { return _bag_name; } set { _bag_name = value; } } /// <summary> /// Execute the filter. /// </summary> /// <param name="b">Bundle of information</param> public void Execute(Dictionary<string, object> b) { if (_vw == null) { _vw = new VideoWriter(_path, _fps, _frame_width, _frame_height, true); } Image<Bgr, byte> i = b.GetImage(_bag_name); Size s = i.Size; if (s.Width != _frame_width || s.Height != _frame_height) { i = i.Resize(_frame_width, _frame_height, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR); } _vw.WriteFrame(i); } /// <summary> /// Get object data for serialization. /// </summary> /// <param name="info">Serialization info</param> /// <param name="context">Streaming context</param> public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("path", _path); info.AddValue("bag_name", _bag_name); info.AddValue("fps", _fps); info.AddValue("frame_width", _frame_width); info.AddValue("frame_height", _frame_height); } /// <summary> /// Dispose managed resources. /// </summary> protected override void DisposeManaged() { _vw.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using Common.SemanticAnalysis; using Common; namespace DaedalusCompiler.Compilation { enum IfLabelType { ElseIfBlockStart = 0, ElseBlockStart = 1, EndOfIfStatement = 2, } enum WhileLabelType { Start = 0, End = 1, } class LabelManager { private int _nextIfLabelIndex; private int _nextWhileLabelIndex; private int _nextElseIfLabelSubIndex; public LabelManager() { _nextIfLabelIndex = 0; _nextWhileLabelIndex = 0; } public void StartNextIfStatement() { _nextIfLabelIndex++; _nextElseIfLabelSubIndex = 0; } public string GenerateIfLabel(IfLabelType ifLabelType) { string labelId = _nextIfLabelIndex.ToString("0000"); string label = ""; switch (ifLabelType) { case IfLabelType.ElseIfBlockStart: label = $"else_if_{++_nextElseIfLabelSubIndex}"; break; case IfLabelType.ElseBlockStart: label = "else"; break; case IfLabelType.EndOfIfStatement: label = "endif"; break; } return $"#{labelId}_{label}"; } public void StartNextWhileStatement() { _nextWhileLabelIndex++; } public string GenerateWhileLabel(WhileLabelType whileLabelType) { string labelId = _nextWhileLabelIndex.ToString("0000"); string label = ""; switch (whileLabelType) { case WhileLabelType.Start: label = "while"; break; case WhileLabelType.End: label = "endwhile"; break; } return $"#{labelId}_{label}"; } } public class AssemblyBuildingVisitor : AbstractSyntaxTreeBaseGenericVisitor<List<AssemblyElement>> { private readonly Dictionary<string, Symbol> _symbolTable; private readonly LabelManager _labelManager; private bool _nestedAttributesFound; private readonly InstanceSymbol _helperInstance; private static string HELPER_INSTANCE = ".HELPER_INSTANCE"; public AssemblyBuildingVisitor(Dictionary<string, Symbol> symbolTable) { _symbolTable = symbolTable; _labelManager = new LabelManager(); _nestedAttributesFound = false; _helperInstance = new InstanceSymbol(HELPER_INSTANCE, null); if (_symbolTable.Count > 0) { _helperInstance.Index = _symbolTable.Values.Last().Index + 1; } } public new Dictionary<string, Symbol> VisitTree(AbstractSyntaxTree tree) { base.VisitTree(tree); if (_nestedAttributesFound) { _symbolTable[HELPER_INSTANCE] = _helperInstance; } return _symbolTable; } private AssemblyElement GetParameterPush(Symbol symbol) { switch (symbol.BuiltinType) { case SymbolType.Instance: return new PushInstance(symbol); default: return new PushVar(symbol); } } private AssemblyElement GetAssignInstruction(Symbol symbol) { switch (symbol.BuiltinType) { case SymbolType.Int: return new Assign(); case SymbolType.String: return new AssignString(); case SymbolType.Func: return new AssignFunc(); case SymbolType.Float: return new AssignFloat(); case SymbolType.Instance: case SymbolType.Class: return new AssignInstance(); } throw new Exception(); } protected override List<AssemblyElement> VisitFunctionDefinition(FunctionDefinitionNode node) { List<AssemblyElement> instructions = ((BlockSymbol)node.Symbol).Instructions; if (node.IsExternal) { return instructions; } for (int i = node.ParameterNodes.Count - 1; i >= 0; i--) { ParameterDeclarationNode parameterNode = node.ParameterNodes[i]; instructions.AddRange(Visit(parameterNode)); } foreach (StatementNode bodyNode in node.BodyNodes) { instructions.AddRange(Visit(bodyNode)); } instructions.Add(new Ret()); return instructions; } protected override List<AssemblyElement> VisitInstanceDefinition(InstanceDefinitionNode node) { List<AssemblyElement> instructions = ((BlockSymbol)node.Symbol).Instructions; if (node.InheritanceParentReferenceNode.Symbol is PrototypeSymbol prototypeSymbol) { instructions.Add(new Call(prototypeSymbol)); } foreach (StatementNode bodyNode in node.BodyNodes) { instructions.AddRange(Visit(bodyNode)); } instructions.Add(new Ret()); return instructions; } protected override List<AssemblyElement> VisitPrototypeDefinition(PrototypeDefinitionNode node) { List<AssemblyElement> instructions = ((BlockSymbol)node.Symbol).Instructions; foreach (StatementNode bodyNode in node.BodyNodes) { instructions.AddRange(Visit(bodyNode)); } instructions.Add(new Ret()); return instructions; } protected override List<AssemblyElement> VisitIfStatement(IfStatementNode node) { _labelManager.StartNextIfStatement(); string statementEndLabel = _labelManager.GenerateIfLabel(IfLabelType.EndOfIfStatement); string elseStartLabel = _labelManager.GenerateIfLabel(IfLabelType.ElseBlockStart); List<AssemblyElement> instructions = new List<AssemblyElement>(); List<ConditionalNode> conditionalNodes = new List<ConditionalNode>(); conditionalNodes.Add(node.IfNode); conditionalNodes.AddRange(node.ElseIfNodes); foreach (ConditionalNode conditionalNode in conditionalNodes) { instructions.AddRange(Visit(conditionalNode.ConditionNode)); bool isLastIteration = conditionalNode == conditionalNodes.Last(); if (isLastIteration) { if (node.ElseNodeBodyNodes!=null) { instructions.Add(new JumpIfToLabel(elseStartLabel)); foreach (StatementNode bodyNode in conditionalNode.BodyNodes) { instructions.AddRange(Visit(bodyNode)); } instructions.Add(new JumpToLabel(statementEndLabel)); } else { instructions.Add(new JumpIfToLabel(statementEndLabel)); foreach (StatementNode bodyNode in conditionalNode.BodyNodes) { instructions.AddRange(Visit(bodyNode)); } } } else { string nextJumpLabel = _labelManager.GenerateIfLabel(IfLabelType.ElseIfBlockStart); instructions.Add(new JumpIfToLabel(nextJumpLabel)); foreach (StatementNode bodyNode in conditionalNode.BodyNodes) { instructions.AddRange(Visit(bodyNode)); } instructions.Add(new JumpToLabel(statementEndLabel)); instructions.Add(new AssemblyLabel(nextJumpLabel)); } } if (node.ElseNodeBodyNodes != null) { instructions.Add(new AssemblyLabel(elseStartLabel)); foreach (StatementNode bodyNode in node.ElseNodeBodyNodes) { instructions.AddRange(Visit(bodyNode)); } } instructions.Add(new AssemblyLabel(statementEndLabel)); return instructions; } protected override List<AssemblyElement> VisitWhileStatement(WhileStatementNode node) { _labelManager.StartNextWhileStatement(); string startLabel = _labelManager.GenerateWhileLabel(WhileLabelType.Start); string endLabel = _labelManager.GenerateWhileLabel(WhileLabelType.End); List<AssemblyElement> instructions = new List<AssemblyElement>(); instructions.Add(new AssemblyLabel(startLabel)); instructions.AddRange(Visit(node.ConditionNode)); instructions.Add(new JumpIfToLabel(endLabel)); foreach (StatementNode bodyNode in node.BodyNodes) { List<AssemblyElement> bodyInstructions = Visit(bodyNode); foreach (AssemblyElement instruction in bodyInstructions) { if (instruction is JumpToLoopStart) { instructions.Add(new JumpToLabel(startLabel)); } else if (instruction is JumpToLoopEnd) { instructions.Add(new JumpToLabel(endLabel)); } else { instructions.Add(instruction); } } } instructions.Add(new JumpToLabel(startLabel)); instructions.Add(new AssemblyLabel(endLabel)); return instructions; } protected override List<AssemblyElement> VisitParameterDeclaration(ParameterDeclarationNode node) { return new List<AssemblyElement> { GetParameterPush(node.Symbol), GetAssignInstruction(node.Symbol), }; } protected override List<AssemblyElement> VisitParameterArrayDeclaration(ParameterArrayDeclarationNode node) { return new List<AssemblyElement> { GetParameterPush(node.Symbol), GetAssignInstruction(node.Symbol), }; } protected override List<AssemblyElement> VisitReference(ReferenceNode referenceNode) { int index; List<AssemblyElement> instructions = new List<AssemblyElement>(); if (referenceNode.DoesHaveNestedAttributes) { //TODO check in game if it does work correctly _nestedAttributesFound = true; instructions.Add(new PushVar(_helperInstance)); instructions.Add(new PushVar(referenceNode.BaseSymbol)); instructions.Add(new Assign()); for (int i = 0; i < referenceNode.PartNodes.Count - 1; ++i) { ReferencePartNode partNode = referenceNode.PartNodes[i]; switch (partNode) { case AttributeNode attributeNode: if (attributeNode.Symbol is InstanceSymbol || (attributeNode.Symbol is VarSymbol varSymbol && varSymbol.BuiltinType == SymbolType.Instance)) { instructions.Add(new PushVar(_helperInstance)); instructions.Add(new SetInstance(_helperInstance)); if (attributeNode.ArrayIndexNode == null) { instructions.Add(new PushVar(attributeNode.Symbol)); } else { index = (int) ((IntValue) attributeNode.ArrayIndexNode.Value).Value; instructions.Add(new PushArrayVar(attributeNode.Symbol, index)); } instructions.Add(new Assign()); } break; } } } index = -1; if (referenceNode.IndexNode != null) { index = (int) ((IntValue) referenceNode.IndexNode.Value).Value; } if (referenceNode.BaseSymbol != referenceNode.Symbol) { if (referenceNode.DoesHaveNestedAttributes) { instructions.Add(new SetInstance(_helperInstance)); } else { instructions.Add(new SetInstance(referenceNode.BaseSymbol)); } } if (index > 0) { instructions.Add(new PushArrayVar(referenceNode.Symbol, index)); } else if (referenceNode.DoCastToInt) { instructions.Add(new PushInt(referenceNode.Symbol.Index)); } else if (referenceNode.Symbol.BuiltinType == SymbolType.Instance) { instructions.Add(new PushInstance(referenceNode.Symbol)); } else { instructions.Add(new PushVar(referenceNode.Symbol)); } return instructions; } protected override List<AssemblyElement> VisitIntegerLiteral(IntegerLiteralNode node) { int intValue = (int) node.Value; if (node.DoCastToFloat) { float floatValue = node.Value; intValue = BitConverter.ToInt32(BitConverter.GetBytes(floatValue), 0); } return new List<AssemblyElement>{ new PushInt(intValue) }; } protected override List<AssemblyElement> VisitFloatLiteral(FloatLiteralNode node) { float floatValue = node.Value; int intValue = BitConverter.ToInt32(BitConverter.GetBytes(floatValue), 0); return new List<AssemblyElement>{ new PushInt(intValue) }; } protected override List<AssemblyElement> VisitStringLiteral(StringLiteralNode node) { return new List<AssemblyElement> { new PushVar(node.Symbol) }; } protected override List<AssemblyElement> VisitAssignment(AssignmentNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); instructions.AddRange(Visit(node.RightSideNode)); instructions.AddRange(Visit(node.LeftSideNode)); instructions.Add(GetAssignInstruction(node.LeftSideNode.Symbol)); return instructions; } protected override List<AssemblyElement> VisitCompoundAssignment(CompoundAssignmentNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); instructions.AddRange(Visit(node.RightSideNode)); instructions.AddRange(Visit(node.LeftSideNode)); switch (node.Operator) { case CompoundAssignmentOperator.Add: instructions.Add(new AssignAdd()); break; case CompoundAssignmentOperator.Sub: instructions.Add(new AssignSubtract()); break; case CompoundAssignmentOperator.Mult: instructions.Add(new AssignMultiply()); break; case CompoundAssignmentOperator.Div: instructions.Add(new AssignDivide()); break; } return instructions; } protected override List<AssemblyElement> VisitBinaryExpression(BinaryExpressionNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); instructions.AddRange(Visit(node.RightSideNode)); instructions.AddRange(Visit(node.LeftSideNode)); switch (node.Operator) { case BinaryOperator.Mult: instructions.Add(new Multiply()); break; case BinaryOperator.Div: instructions.Add(new Divide()); break; case BinaryOperator.Modulo: instructions.Add(new Modulo()); break; case BinaryOperator.Add: instructions.Add(new Add()); break; case BinaryOperator.Sub: instructions.Add(new Subtract()); break; case BinaryOperator.ShiftLeft: instructions.Add(new ShiftLeft()); break; case BinaryOperator.ShiftRight: instructions.Add(new ShiftRight()); break; case BinaryOperator.Less: instructions.Add(new Less()); break; case BinaryOperator.Greater: instructions.Add(new Greater()); break; case BinaryOperator.LessOrEqual: instructions.Add(new LessOrEqual()); break; case BinaryOperator.GreaterOrEqual: instructions.Add(new GreaterOrEqual()); break; case BinaryOperator.Equal: instructions.Add(new Equal()); break; case BinaryOperator.NotEqual: instructions.Add(new NotEqual()); break; case BinaryOperator.BinAnd: instructions.Add(new BitAnd()); break; case BinaryOperator.BinOr: instructions.Add(new BitOr()); break; case BinaryOperator.LogAnd: instructions.Add(new LogAnd()); break; case BinaryOperator.LogOr: instructions.Add(new LogOr()); break; } return instructions; } protected override List<AssemblyElement> VisitUnaryExpression(UnaryExpressionNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); instructions.AddRange(Visit(node.ExpressionNode)); if (node.DoGenerateOperatorInstruction) { switch (node.Operator) { case UnaryOperator.Minus: instructions.Add(new Minus()); break; case UnaryOperator.Not: instructions.Add(new Not()); break; case UnaryOperator.Negate: instructions.Add(new Negate()); break; case UnaryOperator.Plus: instructions.Add(new Plus()); break; } } return instructions; } protected override List<AssemblyElement> VisitReturnStatement(ReturnStatementNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); if (node.ExpressionNode != null) { instructions.AddRange(Visit(node.ExpressionNode)); } instructions.Add(new Ret()); return instructions; } protected override List<AssemblyElement> VisitBreakStatement(BreakStatementNode node) { return new List<AssemblyElement> { new JumpToLoopEnd() }; } protected override List<AssemblyElement> VisitContinueStatement(ContinueStatementNode node) { return new List<AssemblyElement> { new JumpToLoopStart() }; } protected override List<AssemblyElement> VisitFunctionCall(FunctionCallNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); foreach (ExpressionNode argumentNode in node.ArgumentNodes) { instructions.AddRange(Visit(argumentNode)); } FunctionSymbol symbol = (FunctionSymbol) node.FunctionReferenceNode.Symbol; if (symbol.IsExternal) { instructions.Add(new CallExternal(symbol)); } else { instructions.Add(new Call(symbol)); } return instructions; } protected override List<AssemblyElement> VisitVarDeclaration(VarDeclarationNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); if (node.RightSideNode != null) { instructions.AddRange(Visit(node.RightSideNode)); instructions.Add(new PushVar(node.Symbol)); instructions.Add(GetAssignInstruction(node.Symbol)); } return instructions; } protected override List<AssemblyElement> VisitVarArrayDeclaration(VarArrayDeclarationNode node) { List<AssemblyElement> instructions = new List<AssemblyElement>(); if (node.ElementNodes != null) { int index = 0; foreach (ExpressionNode elementNode in node.ElementNodes) { instructions.AddRange(Visit(elementNode)); if (index > 0) { instructions.Add(new PushArrayVar(node.Symbol, index)); } else { instructions.Add(new PushVar(node.Symbol)); } instructions.Add(GetAssignInstruction(node.Symbol)); index++; } } return instructions; } protected override List<AssemblyElement> VisitConstDefinition(ConstDefinitionNode node) { return new List<AssemblyElement>(); } protected override List<AssemblyElement> VisitConstArrayDefinition(ConstArrayDefinitionNode node) { return new List<AssemblyElement>(); } protected override List<AssemblyElement> VisitClassDefinition(ClassDefinitionNode node) { return new List<AssemblyElement>(); } protected override List<AssemblyElement> VisitNull(NullNode node) { return new List<AssemblyElement> { new PushNullInstance(), }; } protected override List<AssemblyElement> VisitNoFunc(NoFuncNode node) { return new List<AssemblyElement> { new PushInt(-1), }; } } }
// 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; using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class FunctionExtensions { public static HashSet<T> TransitiveClosure<T>( this Func<T, IEnumerable<T>> relation, T item) { var closure = new HashSet<T>(); var stack = new Stack<T>(); stack.Push(item); while (stack.Count > 0) { T current = stack.Pop(); foreach (var newItem in relation(current)) { if (closure.Add(newItem)) { stack.Push(newItem); } } } return closure; } } }
using System; namespace Raven.Database.FileSystem.Synchronization { public class DataInfo { public string Name { get; set; } public DateTime LastModified { get; set; } public long Length { get; set; } } }
using Realmar.DataBindings.Editor.TestFramework.Sandbox.UUT; namespace Realmar.DataBindings.Editor.TestFramework.Sandbox { internal interface IPropertyBinding : IBinding<BindingAttribute> { IUUTBindingObject Target { get; } IUUTBindingObject Source { get; } } }
using System.Collections.Generic; namespace Synnduit.Configuration { /// <summary> /// Exposes the configuration that controls the application's migration logging /// behavior. /// </summary> internal interface IMigrationLoggingConfiguration { /// <summary> /// Gets the collection of <see cref="EntityTransactionOutcome"/> values /// identifying entity transactions that should be excluded from logging. /// </summary> IEnumerable<EntityTransactionOutcome> ExcludedOutcomes { get; } /// <summary> /// Gets a value indicating whether the source system entity should be recorded in /// the log. /// </summary> bool SourceSystemEntity { get; } /// <summary> /// Gets a value indicating whether the destination system entity should be /// recorded in the log. /// </summary> bool DestinationSystemEntity { get; } /// <summary> /// Gets a value indicating whether individual value changes should be recorded in /// the log. /// </summary> bool ValueChanges { get; } /// <summary> /// Gets or sets a value indicating whether an entity transaction should always be /// logged if there is at least one message associated with it. /// </summary> bool AlwaysLogMessages { get; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using VIPBrowserLibrary.BBS.X2ch; namespace VIPBrowser.ch2Browser { public partial class AllLoginDialog : Form { /// <summary> /// プログラムの設定情報を表します /// </summary> public VIPBrowserLibrary.Setting.SettingSerial SettingData { get; set; } public AllLoginDialog() { InitializeComponent(); this.Load += AllLoginDialog_Load; } void AllLoginDialog_Load(object sender, EventArgs e) { this.isBeLoginLabel.Text = this.SettingData.IsBeLogin.ToString(); this.isRokkaLoginLabel.Text = this.SettingData.IsRoninLogined.ToString(); this.isP2LoginLabel.Text = this.SettingData.IsP2Login.ToString(); if (this.SettingData.IsBeLogin) { this.beLoginoroutButton.Text = "ログアウト"; } if (this.SettingData.IsRoninLogined) { this.rokkaLoginoroutButton.Text = "ログアウト"; } if (this.SettingData.IsP2Login) { this.p2LoginoroutButton.Text = "ログアウト"; } } private async void beLoginoroutButton_Click(object sender, EventArgs e) { BeLogin bl = new BeLogin(); if (!Boolean.Parse(this.isBeLoginLabel.Text)) { if (String.IsNullOrWhiteSpace(this.user.Text) || String.IsNullOrWhiteSpace(this.password.Text)) return; bool b = await bl.Login(this.user.Text, this.password.Text); if (b) { MessageBox.Show("ログインに成功しました"); this.isBeLoginLabel.Text = "True"; this.SettingData.IsBeLogin = true; this.beLoginoroutButton.Text = "ログアウト"; } else { MessageBox.Show("ログインに失敗しました"); this.beLoginoroutButton.Text = "ログイン"; this.SettingData.IsBeLogin = false; } } else { bl.Logout(); this.isBeLoginLabel.Text = "False"; MessageBox.Show("ログアウトに成功しました"); this.SettingData.IsBeLogin = false; this.beLoginoroutButton.Text = "ログイン"; } } private void rokkaLoginoroutButton_Click(object sender, EventArgs e) { if (!Boolean.Parse(this.isRokkaLoginLabel.Text)) { if (String.IsNullOrWhiteSpace(this.user.Text) || String.IsNullOrWhiteSpace(this.password.Text)) return; bool b = Ronin.Login(this.user.Text, this.password.Text); if (b) { MessageBox.Show("ログインに成功しました"); this.isRokkaLoginLabel.Text = "True"; this.SettingData.IsRoninLogined = true; this.rokkaLoginoroutButton.Text = "ログアウト"; } else { MessageBox.Show("ログインに失敗しました"); this.rokkaLoginoroutButton.Text = "ログイン"; this.SettingData.IsRoninLogined = false; } } else { Ronin.Logout(); this.isRokkaLoginLabel.Text = "False"; MessageBox.Show("ログアウトに成功しました"); this.SettingData.IsRoninLogined = false; this.rokkaLoginoroutButton.Text = "ログイン"; } } private void p2LoginoroutButton_Click(object sender, EventArgs e) { } } }
using EnvDTE; using System; using System.Collections.Generic; namespace ApertureLabs.VisualStudio.SDK.Extensions.V2 { public static class DTEExtensions { public static IEnumerable<string> GetSelectedItemPaths( this EnvDTE80.DTE2 dte) { if (dte == null) throw new ArgumentNullException(nameof(dte)); var items = (Array)dte.ToolWindows.SolutionExplorer.SelectedItems; foreach (UIHierarchyItem selItem in items) { var item = selItem.Object as ProjectItem; if (item != null && item.Properties != null) yield return item.Properties.Item("FullPath").Value.ToString(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using Gimela.Common.ExceptionHandling; using Gimela.Media.Video.DirectShow; using Gimela.Rukbat.DVC.BusinessEntities; namespace Gimela.Rukbat.DVC.BusinessLogic { public class FilterManager : IFilterManager { private bool _disposed = false; private IList<CameraFilter> _cameraFilters; private IList<DesktopFilter> _desktopFilters; private System.Threading.Timer _adjustFilterTimer = null; public FilterManager() { _cameraFilters = GetCameraFilters(); // 获取所有本地USB摄像机 _desktopFilters = GetDesktopFilters(); // 获取所有本地桌面屏幕 _adjustFilterTimer = new System.Threading.Timer(OnAdjustFilterTimer, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5)); } #region IFilterManager Members public event EventHandler<FilterRemovedEventArgs> FilterRemoved; public bool IsFilterExist(FilterType filterType, string filterId) { bool isExist = false; switch (filterType) { case FilterType.LocalCamera: isExist = GetCameraFilters().FirstOrDefault(f => f.Id == filterId) != null; break; case FilterType.LocalDesktop: isExist = GetDesktopFilters().FirstOrDefault(f => f.Id == filterId) != null; break; } return isExist; } public IList<CameraFilter> GetCameraFilters() { List<CameraFilter> filters = new List<CameraFilter>(); try { FilterInfoCollection localFilters = new FilterInfoCollection(FilterCategory.VideoInputDevice); for (int i = 0; i < localFilters.Count; i++) { CameraFilter filter = new CameraFilter(localFilters[i].MonikerString) { Name = localFilters[i].Name }; filters.Add(filter); } } catch (ApplicationException ex) { ExceptionHandler.Handle(ex); } return filters; } public IList<DesktopFilter> GetDesktopFilters() { List<DesktopFilter> filters = new List<DesktopFilter>(); try { Screen[] screens = Screen.AllScreens; for (int i = 0; i < screens.Length; i++) { DesktopFilter filter = new DesktopFilter(i) { Name = screens[i].DeviceName }; filter.IsPrimary = screens[i].Primary; filter.Bounds = screens[i].Bounds; filters.Add(filter); } } catch (ApplicationException ex) { ExceptionHandler.Handle(ex); } return filters; } #endregion private void OnAdjustFilterTimer(object state) { AdjustFilter(); } private void AdjustFilter() { IList<CameraFilter> cameraFilters = GetCameraFilters(); IList<DesktopFilter> desktopFilters = GetDesktopFilters(); foreach (var item in _cameraFilters) { if (cameraFilters.Select(c => c.Id == item.Id).Count() <= 0) { RaiseFilterRemoved(FilterType.LocalCamera, item.Id); } } foreach (var item in _desktopFilters) { if (desktopFilters.Select(c => c.Id == item.Id).Count() <= 0) { RaiseFilterRemoved(FilterType.LocalDesktop, item.Id); } } _cameraFilters = cameraFilters; _desktopFilters = desktopFilters; } private void RaiseFilterRemoved(FilterType filterType, string filterId) { if (FilterRemoved != null) { FilterRemoved(this, new FilterRemovedEventArgs(filterType, filterId)); } } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { if (_adjustFilterTimer != null) { _adjustFilterTimer.Change(Timeout.Infinite, Timeout.Infinite); _adjustFilterTimer.Dispose(); _adjustFilterTimer = null; } } _disposed = true; } } #endregion } }
using System; using System.Drawing; using System.Drawing.Imaging; namespace RemoteDesktop { static class Program { public static StartWindow form; public static ServerWindow sw; public static ClientWindow cw; static void Main() { StartWindow.Start(); } } }
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace OpenSearch.Client { public class KeywordAttribute : OpenSearchDocValuesPropertyAttributeBase, IKeywordProperty { public KeywordAttribute() : base(FieldType.Keyword) { } double? IKeywordProperty.Boost { get; set; } bool? IKeywordProperty.EagerGlobalOrdinals { get; set; } int? IKeywordProperty.IgnoreAbove { get; set; } bool? IKeywordProperty.Index { get; set; } IndexOptions? IKeywordProperty.IndexOptions { get; set; } string IKeywordProperty.Normalizer { get; set; } bool? IKeywordProperty.Norms { get; set; } string IKeywordProperty.NullValue { get; set; } private IKeywordProperty Self => this; bool? IKeywordProperty.SplitQueriesOnWhitespace { get; set; } // ReSharper disable ArrangeThisQualifier public double Boost { get => Self.Boost.GetValueOrDefault(); set => Self.Boost = value; } public bool EagerGlobalOrdinals { get => Self.EagerGlobalOrdinals.GetValueOrDefault(); set => Self.EagerGlobalOrdinals = value; } public int IgnoreAbove { get => Self.IgnoreAbove.GetValueOrDefault(); set => Self.IgnoreAbove = value; } public bool Index { get => Self.Index.GetValueOrDefault(); set => Self.Index = value; } public IndexOptions IndexOptions { get => Self.IndexOptions.GetValueOrDefault(); set => Self.IndexOptions = value; } public string NullValue { get => Self.NullValue; set => Self.NullValue = value; } public bool Norms { get => Self.Norms.GetValueOrDefault(true); set => Self.Norms = value; } public bool SplitQueriesOnWhitespace { get => Self.SplitQueriesOnWhitespace.GetValueOrDefault(false); set => Self.SplitQueriesOnWhitespace = value; } public string Normalizer { get => Self.Normalizer; set => Self.Normalizer = value; } // ReSharper restore ArrangeThisQualifier } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WeatherShare.Data; using WeatherShare.Models; namespace WeatherShare.Controllers { [Route("api/[controller]")] [ApiController] public class WeatherReportsController : ControllerBase { private readonly WeatherReportContext _context; public WeatherReportsController(WeatherReportContext context) { _context = context; } // GET: api/WeatherReports [HttpGet] public async Task<ActionResult<IEnumerable<WeatherReport>>> GetReports() { return await _context.Reports.ToListAsync(); } // GET: api/WeatherReports/5 [HttpGet("{id}")] public async Task<ActionResult<WeatherReport>> GetWeatherReport(Guid id) { var weatherReport = await _context.Reports.FindAsync(id); if (weatherReport == null) { return NotFound(); } return weatherReport; } // PUT: api/WeatherReports/5 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPut("{id}")] public async Task<IActionResult> PutWeatherReport(Guid id, WeatherReport weatherReport) { if (id != weatherReport.WeatherReportId) { return BadRequest(); } _context.Entry(weatherReport).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WeatherReportExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/WeatherReports // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPost] public async Task<ActionResult<WeatherReport>> PostWeatherReport(WeatherReport weatherReport) { _context.Reports.Add(weatherReport); await _context.SaveChangesAsync(); return CreatedAtAction("GetWeatherReport", new { id = weatherReport.WeatherReportId }, weatherReport); } // DELETE: api/WeatherReports/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteWeatherReport(Guid id) { var weatherReport = await _context.Reports.FindAsync(id); if (weatherReport == null) { return NotFound(); } _context.Reports.Remove(weatherReport); await _context.SaveChangesAsync(); return NoContent(); } private bool WeatherReportExists(Guid id) { return _context.Reports.Any(e => e.WeatherReportId == id); } } }
using PhasedBinding.Framework; using PhasedBinding.Models; using PhasedBinding.Services; namespace PhasedBinding.ViewModels { public class LunchMenuViewModel : BindableBase { private LunchMenuService _service = new LunchMenuService(); public LunchMenuViewModel() { } public string IntroText { get; } = "A Lunch"; private LunchMenu _lunchMenu; public LunchMenu LunchMenu { get => _lunchMenu; set => Set(ref _lunchMenu, value); } } }
namespace WebShop.Services { public enum BestellStatus { Rechnung, Nachnahme, NichtLieferbar } }
namespace AdventureWorks.Services.Entities { public partial class CurrencyRate { public string RateString => $"$1 = {EndOfDayRate} {ToCurrencyCodeObject.CurrencyCode}"; } }
using Newtonsoft.Json; using System; using System.IO; using System.Collections.Generic; namespace DynamicPDF.Api { /// <summary> /// Represents font. /// </summary> public class Font { private static Font timesRoman = null; private static Font timesBold = null; private static Font timesItalic = null; private static Font timesBoldItalic = null; private static Font helvetica = null; private static Font helveticaBold = null; private static Font helveticaOblique = null; private static Font helveticaBoldOblique = null; private static Font courier = null; private static Font courierBold = null; private static Font courierOblique = null; private static Font courierBoldOblique = null; private static Font symbol = null; private static Font zapfDingbats = null; private static bool loadRequired = true; private static object lockObject = new object(); private static List<FontInformation> fontDetails = new List<FontInformation>(); private static string pathToFontsResourceDirectory = ""; FontResource resource; static Font() { try { string windDir = Environment.GetEnvironmentVariable("WINDIR"); if (windDir != null && windDir.Length > 0) { pathToFontsResourceDirectory = System.IO.Path.Combine(windDir, "Fonts"); } } catch (Exception) { } } internal Font() { } internal Font(FontResource fontResource, string resourceName = null) { this.resource = fontResource; ResourceName = resourceName; Name = System.Guid.NewGuid().ToString(); } /// <summary> /// Initializes a new instance of the <see cref="Font"/> class /// using the font name that is present in the cloud resource manager. /// </summary> /// <param name="cloudResourceName">The font name present in the cloud resource manager.</param> public Font(string cloudResourceName) { this.ResourceName = cloudResourceName; Name = System.Guid.NewGuid().ToString(); } [JsonProperty] internal string Name { get; set; } internal FontResource Resource { get { return resource; } } /// <summary> /// Gets or sets a boolean indicating whether to embed the font. /// </summary> public bool? Embed { get; set; } /// <summary> /// Gets or sets a boolean indicating whether to subset embed the font. /// </summary> public bool? Subset { get; set; } /// <summary> /// Gets or sets a name for the font resource. /// </summary> public string ResourceName { get; set; } /// <summary> /// Gets the Times Roman core font with Latin 1 encoding. /// </summary> public static Font TimesRoman { get { if (timesRoman == null) { timesRoman = new Font(); timesRoman.Name = "timesRoman"; } return timesRoman; } } /// <summary> /// Gets the Times Bold core font with Latin 1 encoding. /// </summary> public static Font TimesBold { get { if (timesBold == null) { timesBold = new Font(); timesBold.Name = "timesBold"; } return timesBold; } } /// <summary> /// Gets the Times Italic core font with Latin 1 encoding. /// </summary> public static Font TimesItalic { get { if (timesItalic == null) { timesItalic = new Font(); timesItalic.Name = "timesItalic"; } return timesItalic; } } /// <summary> /// Gets the Times Bold Italic core font with Latin 1 encoding. /// </summary> public static Font TimesBoldItalic { get { if (timesBoldItalic == null) { timesBoldItalic = new Font(); timesBoldItalic.Name = "timesBoldItalic"; } return timesBoldItalic; } } /// <summary> /// Gets the Helvetica core font with Latin 1 encoding. /// </summary> public static Font Helvetica { get { if (helvetica == null) { helvetica = new Font(); helvetica.Name = "helvetica"; } return helvetica; } } /// <summary> /// Gets the Helvetica Bold core font with Latin 1 encoding. /// </summary> public static Font HelveticaBold { get { if (helveticaBold == null) { helveticaBold = new Font(); helveticaBold.Name = "helveticaBold"; } return helveticaBold; } } /// <summary> /// Gets the Helvetica Oblique core font with Latin 1 encoding. /// </summary> public static Font HelveticaOblique { get { if (helveticaOblique == null) { helveticaOblique = new Font(); helveticaOblique.Name = "helveticaOblique"; } return helveticaOblique; } } /// <summary> /// Gets the Helvetica Bold Oblique core font with Latin 1 encoding. /// </summary> public static Font HelveticaBoldOblique { get { if (helveticaBoldOblique == null) { helveticaBoldOblique = new Font(); helveticaBoldOblique.Name = "helveticaBoldOblique"; } return helveticaBoldOblique; } } /// <summary> /// Gets the Courier core font with Latin 1 encoding. /// </summary> public static Font Courier { get { if (courier == null) { courier = new Font(); courier.Name = "courier"; } return courier; } } /// <summary> /// Gets the Courier Bold core font with Latin 1 encoding. /// </summary> public static Font CourierBold { get { if (courierBold == null) { courierBold = new Font(); courierBold.Name = "courierBold"; } return courierBold; } } /// <summary> /// Gets the Courier Oblique core font with Latin 1 encoding. /// </summary> public static Font CourierOblique { get { if (courierOblique == null) { courierOblique = new Font(); courierOblique.Name = "courierOblique"; } return courierOblique; } } /// <summary> /// Gets the Courier Bold Oblique core font with Latin 1 encoding. /// </summary> public static Font CourierBoldOblique { get { if (courierBoldOblique == null) { courierBoldOblique = new Font(); courierBoldOblique.Name = "courierBoldOblique"; } return courierBoldOblique; } } /// <summary> /// Gets the Symbol core font. /// </summary> public static Font Symbol { get { if (symbol == null) { symbol = new Font(); symbol.Name = "symbol"; } return symbol; } } /// <summary> /// Gets the Zapf Dingbats core font. /// </summary> public static Font ZapfDingbats { get { if (zapfDingbats == null) { zapfDingbats = new Font(); zapfDingbats.Name = "zapfDingbats"; } return zapfDingbats; } } /// <summary> /// Initializes a new instance of the <see cref="Font"/> class /// using the file path of the font and resource name. /// </summary> /// <param name="filePath">The file path of the font file.</param> /// <param name="resourceName">The resource name for the font.</param> public static Font FromFile(string filePath, string resourceName = null) { FontResource resource = new FontResource(filePath, resourceName); Font font = new Font(resource, resource.ResourceName); return font; } /// <summary> /// Initializes a new instance of the <see cref="Font"/> class /// using the stream of the font file and resource name. /// </summary> /// <param name="stream">The stream of the font file.</param> /// <param name="resourceName">The resource name for the font.</param> public static Font FromStream(Stream stream, string resourceName = null) { FontResource resource = new FontResource(stream, resourceName); return new Font(resource, resource.ResourceName); } /// <summary> /// Initializes a new instance of the <see cref="Font"/> class /// using the system font name and resource name. /// </summary> /// <param name="fontName">The name of the font in the system.</param> /// <param name="resourceName">The resource name for the font.</param> public static Font FromSystem(string fontName, string resourceName = null) { FontResource fontResource; if (fontName == null) return null; if (fontName == string.Empty || fontName.Length < 1) return null; fontName = fontName.Replace("-", string.Empty); fontName = fontName.Replace(" ", string.Empty); if (loadRequired) { LoadFonts(); } foreach (FontInformation fontDetail in fontDetails) { if (fontDetail.FontName.ToUpper() == fontName.ToUpper()) { fontResource = new FontResource(fontDetail.FilePath, resourceName); return new Font(fontResource, fontResource.ResourceName); } } return null; } private static void LoadFonts() { lock (lockObject) { if (loadRequired) { if (pathToFontsResourceDirectory != null && pathToFontsResourceDirectory != string.Empty) { DirectoryInfo di = new DirectoryInfo(pathToFontsResourceDirectory); FileInfo[] allFiles = di.GetFiles(); Stream reader; FullNameTable nameTable; foreach (FileInfo file in allFiles) { reader = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); nameTable = ReadFontNameTable(reader); if (nameTable != null) { fontDetails.Add(new FontInformation(nameTable.FontName, file.FullName)); } } } } } } private static FullNameTable ReadFontNameTable(Stream reader) { FullNameTable nameTable = null; try { reader.Seek(4, SeekOrigin.Begin); int intTableCount = (reader.ReadByte() << 8) | reader.ReadByte(); if (intTableCount > 0) { byte[] bytTableDirectory = new byte[intTableCount * 16]; reader.Seek(12, SeekOrigin.Begin); reader.Read(bytTableDirectory, 0, intTableCount * 16); for (int i = 0; i < bytTableDirectory.Length; i += 16) { switch (BitConverter.ToInt32(bytTableDirectory, i)) { case 1701667182: // "name" nameTable = new FullNameTable(reader, bytTableDirectory, i); break; } } } } catch { } return nameTable; } } }
using System; using System.Reflection; [assembly: AssemblyDescription("ESerializer A serializer specific for EPiServers content types and objects")] [assembly: AssemblyTitle("ESerializer")] [assembly: AssemblyProduct("ESerializer")] [assembly: AssemblyCopyright("Copyright 2019 Emil Olsson")] [assembly: AssemblyTrademark("566cd76339a12ee35e6f01600ff979bec36a333d")] [assembly: AssemblyVersion("0.6.0.1610")] [assembly: AssemblyFileVersion("0.6.0.1610")] [assembly: AssemblyInformationalVersion("0.6.0.1610")] [assembly: CLSCompliant(false)]
using System; using System.Collections.Generic; namespace ICanHasDotnetCore.Plumbing.Extensions { public static class StringExtensions { public static bool EqualsOrdinalIgnoreCase(this string str, string value) => str.Equals(value, StringComparison.OrdinalIgnoreCase); public static bool StartsWithOrdinalIgnoreCase(this string str, string value) => str.StartsWith(value, StringComparison.OrdinalIgnoreCase); public static string CommaSeperate(this IEnumerable<object> items) => string.Join(", ", items); } }
// 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.Text.Json.Serialization; namespace CaptainHook.AzureDevOps.Payload { /// <summary> /// Merge Commit Information /// </summary> public class GitMergeCommit { /// <summary> /// Commit Id /// </summary> [JsonPropertyName("commitId")] public string CommitId { get; set; } /// <summary> /// Commit Url /// </summary> [JsonPropertyName("url")] public Uri Url { get; set; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using CCIA.Models; using CCIA.Services; using Microsoft.Extensions.Hosting; using System.Security.Claims; using System.Threading.Tasks; using System; using Microsoft.EntityFrameworkCore; using Thinktecture; namespace CCIA { public class Startup { public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; Env = env; } public IConfiguration Configuration { get; } public IWebHostEnvironment Env { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped<IIdentityService, IdentityService>(); services.AddScoped<INotificationService, NotificationService>(); services.AddScoped<IFileIOService, FileIOService>(); services.AddControllersWithViews(); IMvcBuilder builder = services.AddRazorPages(); #if DEBUG if (Env.IsDevelopment()) { builder.AddRazorRuntimeCompilation(); } #endif //services.AddDbContext<CCIAContext>(); services.AddDbContextPool<CCIAContext>( o => { o.UseSqlServer(Configuration.GetConnectionString("CCIACoreContext"), sqlOptions => { sqlOptions.UseNetTopologySuite(); sqlOptions.AddRowNumberSupport(); }); o.UseLoggerFactory(CCIAContext.GetLoggerFactory()); }); services.AddAuthentication("Cookies") // Sets the default scheme to cookies .AddCookie("Cookies", options => { options.AccessDeniedPath = "/account/denied"; options.LoginPath = "/account/login"; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.SlidingExpiration = true; }) .AddCAS("CAS",o => { o.CasServerUrlBase = Configuration["CasBaseUrl"]; // Set in `appsettings.json` file. o.SignInScheme = "Cookies"; o.Events.OnCreatingTicket = async context => { var identity = (ClaimsIdentity) context.Principal.Identity; var assertion = context.Assertion; if (identity == null) { return; } var kerb = assertion.PrincipalName; if (string.IsNullOrWhiteSpace(kerb)) return; var identityService = services.BuildServiceProvider().GetService<IIdentityService>(); var user = await identityService.GetByKerberos(kerb); if (user == null || !user.CCIAAccess) { return; } var existingClaim = identity.FindFirst(ClaimTypes.Name); if(existingClaim != null) { identity.RemoveClaim(identity.FindFirst(ClaimTypes.Name)); } identity.AddClaim(new Claim(ClaimTypes.Name, user.Id)); identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName)); identity.AddClaim(new Claim(ClaimTypes.Surname, user.LastName)); identity.AddClaim(new Claim("name", user.Name)); identity.AddClaim(new Claim(ClaimTypes.Email, user.Email)); existingClaim = identity.FindFirst(ClaimTypes.NameIdentifier); if(existingClaim != null) { identity.RemoveClaim(identity.FindFirst(ClaimTypes.NameIdentifier)); } identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, kerb)); identity.AddClaim(new Claim(ClaimTypes.Role, "Employee")); if(user.CoreStaff) { identity.AddClaim(new Claim(ClaimTypes.Role, "CoreStaff")); } if(user.Admin) { identity.AddClaim(new Claim(ClaimTypes.Role, "Admin")); } if(user.ConditionerStatusUpdate || user.Admin) { identity.AddClaim(new Claim(ClaimTypes.Role, "ConditionerStatusUpdate")); } if(user.EditVarieties) { identity.AddClaim(new Claim(ClaimTypes.Role, "EditVarieties")); } context.Principal.AddIdentity(identity); await Task.FromResult(0); }; }); // Add application services. services.AddTransient<IEmailSender, EmailSender>(); services.AddScoped<IFullCallService, FullCallService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseCookiePolicy(new CookiePolicyOptions() { MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.Lax }); } else { app.UseExceptionHandler("/Home/Error"); app.UseCookiePolicy(); } app.UseStaticFiles(); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapAreaControllerRoute( name: "Client_route", areaName: "Client", pattern: "client/{controller}/{action=Index}/{id?}" ); endpoints.MapAreaControllerRoute( name: "Admin_route", areaName: "Admin", pattern: "admin/{controller}/{action=Index}/{id?}" ); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Root}/{action=Index}/{id?}"); }); } } }
//--------------------------------------------------------------------------------------------------- // <auto-generated> // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // Generated by DynamicsCrm.DevKit - https://github.com/phuocle/Dynamics-Crm-DevKit // </auto-generated> //--------------------------------------------------------------------------------------------------- using Microsoft.Xrm.Sdk; using System; using System.Diagnostics; namespace Abc.LuckyStar2.Shared.Entities.SdkMessageProcessingStepImageOptionSets { public enum ComponentState { /// <summary> /// Deleted = 2 /// </summary> Deleted = 2, /// <summary> /// Deleted_Unpublished = 3 /// </summary> Deleted_Unpublished = 3, /// <summary> /// Published = 0 /// </summary> Published = 0, /// <summary> /// Unpublished = 1 /// </summary> Unpublished = 1 } public enum ImageType { /// <summary> /// Both = 2 /// </summary> Both = 2, /// <summary> /// PostImage = 1 /// </summary> PostImage = 1, /// <summary> /// PreImage = 0 /// </summary> PreImage = 0 } } namespace Abc.LuckyStar2.Shared.Entities { public partial class SdkMessageProcessingStepImage : EntityBase { public struct Fields { public const string Attributes = "attributes"; public const string ComponentState = "componentstate"; public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string CustomizationLevel = "customizationlevel"; public const string Description = "description"; public const string EntityAlias = "entityalias"; public const string ImageType = "imagetype"; public const string IntroducedVersion = "introducedversion"; public const string IsManaged = "ismanaged"; public const string MessagePropertyName = "messagepropertyname"; public const string ModifiedBy = "modifiedby"; public const string ModifiedOn = "modifiedon"; public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; public const string Name = "name"; public const string OrganizationId = "organizationid"; public const string OverwriteTime = "overwritetime"; public const string RelatedAttributeName = "relatedattributename"; public const string SdkMessageProcessingStepId = "sdkmessageprocessingstepid"; public const string SdkMessageProcessingStepImageId = "sdkmessageprocessingstepimageid"; public const string SdkMessageProcessingStepImageIdUnique = "sdkmessageprocessingstepimageidunique"; public const string SolutionId = "solutionid"; public const string SupportingSolutionId = "supportingsolutionid"; public const string VersionNumber = "versionnumber"; } public const string EntityLogicalName = "sdkmessageprocessingstepimage"; public const int EntityTypeCode = 4615; [DebuggerNonUserCode()] public SdkMessageProcessingStepImage() { Entity = new Entity(EntityLogicalName); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SdkMessageProcessingStepImage(Guid SdkMessageProcessingStepImageId) { Entity = new Entity(EntityLogicalName, SdkMessageProcessingStepImageId); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SdkMessageProcessingStepImage(string keyName, object keyValue) { Entity = new Entity(EntityLogicalName, keyName, keyValue); PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SdkMessageProcessingStepImage(Entity entity) { Entity = entity; PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SdkMessageProcessingStepImage(Entity entity, Entity merge) { Entity = entity; foreach (var property in merge?.Attributes) { var key = property.Key; var value = property.Value; Entity[key] = value; } PreEntity = CloneThisEntity(Entity); } [DebuggerNonUserCode()] public SdkMessageProcessingStepImage(KeyAttributeCollection keys) { Entity = new Entity(EntityLogicalName, keys); PreEntity = CloneThisEntity(Entity); } /// <summary> /// <para>Comma-separated list of attributes that are to be passed into the SDK message processing step image.</para> /// <para>String - MaxLength: 100000</para> /// <para>Attributes</para> /// </summary> [DebuggerNonUserCode()] public string Attributes { get { return Entity.GetAttributeValue<string>(Fields.Attributes); } set { Entity.Attributes[Fields.Attributes] = value; } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - Picklist</para> /// <para>Component State</para> /// </summary> [DebuggerNonUserCode()] public Abc.LuckyStar2.Shared.Entities.SdkMessageProcessingStepImageOptionSets.ComponentState? ComponentState { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.ComponentState); if (value == null) return null; return (Abc.LuckyStar2.Shared.Entities.SdkMessageProcessingStepImageOptionSets.ComponentState)value.Value; } } /// <summary> /// <para>Unique identifier of the user who created the SDK message processing step image.</para> /// <para>ReadOnly - Lookup</para> /// <para>Created By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedBy); } } /// <summary> /// <para>Date and time when the SDK message processing step image was created.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para> /// <para>Created On</para> /// </summary> [DebuggerNonUserCode()] public DateTime? CreatedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.CreatedOn); } } /// <summary> /// <para>Unique identifier of the delegate user who created the sdkmessageprocessingstepimage.</para> /// <para>ReadOnly - Lookup</para> /// <para>Created By (Delegate)</para> /// </summary> [DebuggerNonUserCode()] public EntityReference CreatedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.CreatedOnBehalfBy); } } /// <summary> /// <para>Customization level of the SDK message processing step image.</para> /// <para>ReadOnly - Integer - MinValue: -255 - MaxValue: 255</para> /// <para></para> /// </summary> [DebuggerNonUserCode()] public int? CustomizationLevel { get { return Entity.GetAttributeValue<int?>(Fields.CustomizationLevel); } } /// <summary> /// <para>Description of the SDK message processing step image.</para> /// <para>String - MaxLength: 256</para> /// <para>Description</para> /// </summary> [DebuggerNonUserCode()] public string Description { get { return Entity.GetAttributeValue<string>(Fields.Description); } set { Entity.Attributes[Fields.Description] = value; } } /// <summary> /// <para>Key name used to access the pre-image or post-image property bags in a step.</para> /// <para>String - MaxLength: 256</para> /// <para>Entity Alias</para> /// </summary> [DebuggerNonUserCode()] public string EntityAlias { get { return Entity.GetAttributeValue<string>(Fields.EntityAlias); } set { Entity.Attributes[Fields.EntityAlias] = value; } } /// <summary> /// <para>Type of image requested.</para> /// <para>Picklist</para> /// <para>Image Type</para> /// </summary> [DebuggerNonUserCode()] public Abc.LuckyStar2.Shared.Entities.SdkMessageProcessingStepImageOptionSets.ImageType? ImageType { get { var value = Entity.GetAttributeValue<OptionSetValue>(Fields.ImageType); if (value == null) return null; return (Abc.LuckyStar2.Shared.Entities.SdkMessageProcessingStepImageOptionSets.ImageType)value.Value; } set { if (value.HasValue) Entity.Attributes[Fields.ImageType] = new OptionSetValue((int)value.Value); else Entity.Attributes[Fields.ImageType] = null; } } /// <summary> /// <para>Version in which the form is introduced.</para> /// <para>String - MaxLength: 48</para> /// <para>Introduced Version</para> /// </summary> [DebuggerNonUserCode()] public string IntroducedVersion { get { return Entity.GetAttributeValue<string>(Fields.IntroducedVersion); } set { Entity.Attributes[Fields.IntroducedVersion] = value; } } /// <summary> /// <para>ReadOnly - Boolean</para> /// <para></para> /// </summary> [DebuggerNonUserCode()] public bool? IsManaged { get { return Entity.GetAttributeValue<bool?>(Fields.IsManaged); } } /// <summary> /// <para>Name of the property on the Request message.</para> /// <para>String - MaxLength: 256</para> /// <para>Message Property Name</para> /// </summary> [DebuggerNonUserCode()] public string MessagePropertyName { get { return Entity.GetAttributeValue<string>(Fields.MessagePropertyName); } set { Entity.Attributes[Fields.MessagePropertyName] = value; } } /// <summary> /// <para>Unique identifier of the user who last modified the SDK message processing step.</para> /// <para>ReadOnly - Lookup</para> /// <para>Modified By</para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedBy); } } /// <summary> /// <para>Date and time when the SDK message processing step was last modified.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateAndTime</para> /// <para>Modified By</para> /// </summary> [DebuggerNonUserCode()] public DateTime? ModifiedOnUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.ModifiedOn); } } /// <summary> /// <para>Unique identifier of the delegate user who last modified the sdkmessageprocessingstepimage.</para> /// <para>ReadOnly - Lookup</para> /// <para>Modified By (Delegate)</para> /// </summary> [DebuggerNonUserCode()] public EntityReference ModifiedOnBehalfBy { get { return Entity.GetAttributeValue<EntityReference>(Fields.ModifiedOnBehalfBy); } } /// <summary> /// <para>Name of SdkMessage processing step image.</para> /// <para>String - MaxLength: 256</para> /// <para>Name</para> /// </summary> [DebuggerNonUserCode()] public string Name { get { return Entity.GetAttributeValue<string>(Fields.Name); } set { Entity.Attributes[Fields.Name] = value; } } /// <summary> /// <para>Unique identifier of the organization with which the SDK message processing step is associated.</para> /// <para>ReadOnly - Lookup</para> /// <para></para> /// </summary> [DebuggerNonUserCode()] public EntityReference OrganizationId { get { return Entity.GetAttributeValue<EntityReference>(Fields.OrganizationId); } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - DateTimeBehavior: UserLocal - DateTimeFormat: DateOnly</para> /// <para>Record Overwrite Time</para> /// </summary> [DebuggerNonUserCode()] public DateTime? OverwriteTimeUtc { get { return Entity.GetAttributeValue<DateTime?>(Fields.OverwriteTime); } } /// <summary> /// <para>Name of the related entity.</para> /// <para>String - MaxLength: 256</para> /// <para>Related Attribute Name</para> /// </summary> [DebuggerNonUserCode()] public string RelatedAttributeName { get { return Entity.GetAttributeValue<string>(Fields.RelatedAttributeName); } set { Entity.Attributes[Fields.RelatedAttributeName] = value; } } /// <summary> /// <para>Unique identifier of the SDK message processing step.</para> /// <para>Lookup</para> /// <para>SDK Message Processing Step</para> /// </summary> [DebuggerNonUserCode()] public EntityReference SdkMessageProcessingStepId { get { return Entity.GetAttributeValue<EntityReference>(Fields.SdkMessageProcessingStepId); } set { Entity.Attributes[Fields.SdkMessageProcessingStepId] = value; } } /// <summary> /// <para>Unique identifier of the SDK message processing step image entity.</para> /// <para>Primary Key - Uniqueidentifier</para> /// <para></para> /// </summary> [DebuggerNonUserCode()] public Guid SdkMessageProcessingStepImageId { get { return Id; } set { Entity.Attributes[Fields.SdkMessageProcessingStepImageId] = value; Entity.Id = value; } } /// <summary> /// <para>Unique identifier of the SDK message processing step image.</para> /// <para>ReadOnly - Uniqueidentifier</para> /// <para></para> /// </summary> [DebuggerNonUserCode()] public Guid? SdkMessageProcessingStepImageIdUnique { get { return Entity.GetAttributeValue<Guid?>(Fields.SdkMessageProcessingStepImageIdUnique); } } /// <summary> /// <para>Unique identifier of the associated solution.</para> /// <para>ReadOnly - Uniqueidentifier</para> /// <para>Solution</para> /// </summary> [DebuggerNonUserCode()] public Guid? SolutionId { get { return Entity.GetAttributeValue<Guid?>(Fields.SolutionId); } } /// <summary> /// <para>For internal use only.</para> /// <para>ReadOnly - Uniqueidentifier</para> /// <para>Solution</para> /// </summary> [DebuggerNonUserCode()] public Guid? SupportingSolutionId { get { return Entity.GetAttributeValue<Guid?>(Fields.SupportingSolutionId); } } /// <summary> /// <para>Number that identifies a specific revision of the step image.</para> /// <para>ReadOnly - BigInt</para> /// <para></para> /// </summary> [DebuggerNonUserCode()] public long? VersionNumber { get { return Entity.GetAttributeValue<long?>(Fields.VersionNumber); } } } }
using System.Collections.Generic; using System.Collections.ObjectModel; using OpenQA.Selenium; namespace Basin.Selenium { public sealed class Elements : ReadOnlyCollection<IWebElement> { public Elements(IList<IWebElement> list) : base(list) { } public By FoundBy { get; set; } public bool IsEmpty => Count == 0; } }
using HedefSagliksa.Business.Abstract; using HedefSagliksa.DataAccess.Abstract; using HedefSagliksa.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace HedefSagliksa.Business.Concrete { public class CommentManager : ICommentService { private readonly ICommentDal _commentDal; public CommentManager(ICommentDal commentDal) { _commentDal = commentDal; } public void Add(Comment entity) { _commentDal.Add(entity); } public void Delete(Comment entity) { _commentDal.Delete(entity); } public Comment Get(Expression<Func<Comment, bool>> filter) { return _commentDal.Get(filter); } public List<Comment> GetAll(Expression<Func<Comment, bool>> filter = null) { return _commentDal.GetAll(filter); } public void Update(Comment entity) { _commentDal.Update(entity); } } }
using System; using Events; using UnityEngine; using UnityEngine.UI; namespace Timer { public class TimerUI : MonoBehaviour { [SerializeField] private Text timerText; private void Awake() { if (PlayerPrefs.GetInt("timerToggle", 0) == 0) { timerText.text = ""; return; } MessageHandler.Instance().SubscribeMessage<TimerEvent>(UpdateTimer); } private void UpdateTimer(TimerEvent obj) { var timeSpan = TimeSpan.FromSeconds(obj.timePassed); timerText.text = timeSpan.ToString(@"mm\:ss\:ff"); } private void OnDestroy() { MessageHandler.Instance().UnsubscribeMessage<TimerEvent>(UpdateTimer); } } }
using System; using System.Collections.Generic; namespace addressBook.Objects { public class contact { private string _name; private string _phoneNumber; private string _address; private int _id; private static List<contact> _listContact = new List<contact>(); public contact(string name, string phoneNumber, string address) { SetInfo(name, phoneNumber, address); _listContact.Add(this); _id = _listContact.Count; } public string GetName() { return _name; } public string GetPhoneNumber() { return _phoneNumber; } public string GetAddress() { return _address; } public int GetID() { return _id; } public void SetInfo(string name, string phoneNumber, string address) { _name = name; _phoneNumber = phoneNumber; _address = address; } public static List<contact> ShowAll() { return _listContact; } public static void ClearAll() { _listContact.Clear(); } public static contact Find(int searchID) { return _listContact[searchID - 1]; } } }
namespace MLSoftware.OTA { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")] public partial class AccommodationInfoTypeResort { private string _resortCode; private string _resortName; private string _destinationCode; private DestinationLevelType _destinationLevel; private string _destinationName; [System.Xml.Serialization.XmlAttributeAttribute()] public string ResortCode { get { return this._resortCode; } set { this._resortCode = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string ResortName { get { return this._resortName; } set { this._resortName = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string DestinationCode { get { return this._destinationCode; } set { this._destinationCode = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public DestinationLevelType DestinationLevel { get { return this._destinationLevel; } set { this._destinationLevel = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string DestinationName { get { return this._destinationName; } set { this._destinationName = value; } } } }
using System.Collections.Concurrent; using System.Diagnostics; using AutoMapper; using AutoMapperTest; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; namespace AutoMapperTest { public class BenchmarkTest { UserDO userDO = new() { UserAge = 1, UserName = "123", UserNick = "666" }; Mapper mapper; public BenchmarkTest() { var config = new MapperConfiguration(cfg => cfg.CreateMap<UserDO, UserEntity>()); mapper = new Mapper(config); } [Benchmark] public void AutoMapperCache() { for (int i = 0; i < 1_000_000; i++) { GetMapper((typeof(UserDO).ToString() + typeof(UserEntity).ToString()).GetHashCode().ToString(), () => new MapperConfiguration(cfg => { cfg.CreateMap<UserDO, UserEntity>(); }).CreateMapper()).Map<UserEntity>(userDO); } } [Benchmark] public void AutoMapper() { for (int i = 0; i < 1_000_000; i++) { mapper.Map<UserEntity>(userDO); } } [Benchmark] public void 原生() { for (int i = 0; i < 1_000_000; i++) { UserEntity user = new() { UserName = userDO.UserName, UserAge = userDO.UserAge, UserNick = userDO.UserNick, }; } } private static readonly ConcurrentDictionary<string, IMapper> cacheDic = new(); private static IMapper GetMapper(string key, Func<IMapper> func) { if (cacheDic.TryGetValue(key, out IMapper? mapper)) { return mapper; } else { //内存保护 if (cacheDic.Count > 10000) { throw new OverflowException("Capinfo.MUSC.BDP.Core AutoMapperHelper报错:目前Mapper过多,请考虑您是否正常调用此方法"); } return cacheDic.GetOrAdd(key, func()); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Unit { m, dm, cm, mm, m2, dm2, cm2, mm2, m3, dm3, l, cm3, ml, mm3 }; public static class IntExtensions { /// <summary> /// Return all non-zero items in integer array. /// </summary> public static int[] GetNonZeroItems(this int[] array) { List<int> nonZeroItems = new List<int>(); for(int i = 0; i < array.Length; i++) { if(array[i] != 0) { nonZeroItems.Add(array[i]); } } return nonZeroItems.ToArray(); } /// <summary> /// Convert from m3 to dm3. /// </summary> public static int Convert(this int value, Unit unitOld, Unit unitNew) { throw new System.NotImplementedException(); } }
using System; using System.Numerics; class SecretNumbers { static void Main(string[] args) { string n = Console.ReadLine(); BigInteger nAsBigBigInteger= BigInteger.Parse(n); BigInteger oddNum = 0; BigInteger evenNum = 0; //Loop for the ODD numbers in the sequence for (BigInteger i = n.Length; i > 0; i -= 2) { BigInteger num = BigInteger.Parse(n[i - 1] - '0'); BigInteger allSum = BigInteger.Parse(num * Math.Pow((n.Length - i) + 1, 2)); oddNum += allSum; } //Loop for the EVEN numbers in the sequnce for (BigInteger i = n.Length - 1; i > 0; i -= 2) { BigInteger num = n[i - 1] - '0'; BigInteger position = (n.Length - i) + 1; BigInteger allNum = num * num * position; evenNum += allNum; } BigInteger evenAndOdd = oddNum + evenNum; string evenAndOddStr = evenAndOdd.ToString(); //Alpha sequence goes here BigInteger r = evenAndOdd % 26; string alphabetLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; BigInteger firstLetter = r; BigInteger secondNumInSecretSum = (evenAndOddStr[evenAndOddStr.Length - 1]) - '0'; string secret = ""; if (evenAndOddStr[evenAndOddStr.Length - 1] == '0') { Console.WriteLine(evenAndOddStr); Console.WriteLine("{0} has no secret alpha-sequence", n); } else if (firstLetter + secondNumInSecretSum <= 26) { BigInteger third = firstLetter + secondNumInSecretSum; for (BigInteger = BigInteger.Parse(irstLetter); i < third; i++) { secret += alphabetLetters[i]; } Console.WriteLine(evenAndOdd); Console.WriteLine(secret); } else { BigInteger third = firstLetter + secondNumInSecretSum; BigInteger fourth = third - 26; //bool stop = false; BigIntegerindex = 0; for (BigIntegeri = (int)firstLetter; i < alphabetLetters.Length; i++, index++) { secret += alphabetLetters[i]; if (i == 25) { i = -1; } if (index == third) { break; } //if (third > 26 && i == (alphabetLetters.Length - 1)) //{ // if (fourth < 52) // { // for (BigIntegerj = 0; j < fourth; j++) // { // secret += alphabetLetters[j]; // } // stop = true; // } //} } string fin = secret.Substring(0, (int)secondNumInSecretSum); Console.WriteLine(evenAndOdd); Console.WriteLine(fin); } } }
using System; using System.Collections.Generic; using System.Text; using PetaTest; using ToolGood.Algorithm; namespace ToolGood.Algorithm2.Test.Tests { [TestFixture] public class IssuesTest { [Test] public void issues_12() { AlgorithmEngine engine = new AlgorithmEngine(); var dt = engine.TryEvaluate("Year(44406)=2021", false); Assert.AreEqual(dt, true); dt = engine.TryEvaluate("MONTH(44406)=7", false); Assert.AreEqual(dt, true); dt = engine.TryEvaluate("DAY(44406)=29", false); Assert.AreEqual(dt, true); int num = engine.TryEvaluate("date(2011,2,2)", 0); Assert.AreEqual(num, 40576); } [Test] public void issues_13() { AlgorithmEngine engine = new AlgorithmEngine(); var dt = engine.TryEvaluate("days360(date(2020,5,31),date(2023,12,15))", 0); Assert.AreEqual(dt, 1275); } } }
using System; using System.Collections.Generic; using System.Data; using System.Threading.Tasks; namespace Spiffy { /// <summary> /// Represents the ability to obtain new unit instances to perform /// database-bound tasks transactionally, as well as query /// the database directly. /// </summary> /// <typeparam name="TConn">The IDbConnectionFactory to use for connection creation.</typeparam> public class DbFixture<TConn> : IDbFixture<TConn> where TConn : IDbConnectionFactory { private readonly TConn _connectionFactory; /// <summary> /// Constitute a DbFixture from a IDbConnectionFactory /// </summary> /// <param name="connectionFactory"></param> public DbFixture(TConn connectionFactory) { if (connectionFactory == null) throw new ArgumentNullException(nameof(connectionFactory)); _connectionFactory = connectionFactory; } /// <summary> /// Create a new IDbBatch, which represents a database unit of work. /// </summary> /// <returns></returns> public IDbBatch NewBatch() { var conn = _connectionFactory.NewConnection(); conn.TryOpenConnection(); var tran = conn.TryBeginTransaction(); return new DbBatch(conn, tran); } /// <summary> /// Execute parameterized query and return rows affected. /// </summary> /// <param name="sql"></param> /// <param name="param"></param> /// <returns></returns> public int Exec(string sql, DbParams param = null) => Batch(b => b.Exec(sql, param)); /// <summary> /// Execute parameterized query multiple times /// </summary> /// <param name="sql"></param> /// <param name="param"></param> /// <returns></returns> public void ExecMany(string sql, IEnumerable<DbParams> param) => Do(b => b.ExecMany(sql, param)); /// <summary> /// Execute parameterized query and return single-value. /// </summary> /// <param name="sql"></param> /// <param name="param"></param> /// <returns></returns> public object Scalar(string sql, DbParams param = null) => Batch(b => b.Scalar(sql, param)); /// <summary> /// Execute parameterized query, enumerate all records and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <param name="param"></param> /// <returns></returns> public IEnumerable<T> Query<T>(string sql, DbParams param, Func<IDataReader, T> map) => Batch(b => b.Query(sql, param, map)); /// <summary> /// Execute query, enumerate all records and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <returns></returns> public IEnumerable<T> Query<T>(string sql, Func<IDataReader, T> map) => Batch(b => b.Query(sql, map)); /// <summary> /// Execute paramterized query, read only first record and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <param name="param"></param> /// <returns></returns> public T QuerySingle<T>(string sql, DbParams param, Func<IDataReader, T> map) => Batch(b => b.QuerySingle(sql, param, map)); /// <summary> /// Execute query, read only first record and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <returns></returns> public T QuerySingle<T>(string sql, Func<IDataReader, T> map) => Batch(b => b.QuerySingle(sql, map)); /// <summary> /// Asynchronously execute parameterized query and return rows affected. /// </summary> /// <param name="sql"></param> /// <param name="param"></param> /// <returns></returns> public Task<int> ExecAsync(string sql, DbParams param = null) => BatchAsync(b => b.ExecAsync(sql, param)); /// <summary> /// Asynchronously execute parameterized query and return rows affected. /// </summary> /// <param name="sql"></param> /// <param name="paramList"></param> /// <returns></returns> public Task ExecManyAsync(string sql, IEnumerable<DbParams> paramList) => DoAsync(b => b.ExecManyAsync(sql, paramList)); /// <summary> /// Asynchronously execute parameterized query and return single-value. /// </summary> /// <param name="sql"></param> /// <param name="param"></param> /// <returns></returns> public Task<object> ScalarAsync(string sql, DbParams param = null) => BatchAsync(b => b.ScalarAsync(sql, param)); /// <summary> /// Asynchronously execute parameterized query, enumerate all records and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <param name="param"></param> /// <returns></returns> public Task<IEnumerable<T>> QueryAsync<T>(string sql, DbParams param, Func<IDataReader, T> map) => BatchAsync(b => b.QueryAsync(sql, param, map)); /// <summary> /// Asynchronously execute query, enumerate all records and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <returns></returns> public Task<IEnumerable<T>> QueryAsync<T>(string sql, Func<IDataReader, T> map) => BatchAsync(b => b.QueryAsync(sql, map)); /// <summary> /// Asynchronously execute paramterized query, read only first record and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <param name="param"></param> /// <returns></returns> public Task<T> QuerySingleAsync<T>(string sql, DbParams param, Func<IDataReader, T> map) => BatchAsync(b => b.QuerySingleAsync(sql, param, map)); /// <summary> /// Asynchronously execute query, read only first record and apply mapping. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sql"></param> /// <param name="map"></param> /// <returns></returns> public Task<T> QuerySingleAsync<T>(string sql, Func<IDataReader, T> map) => BatchAsync(b => b.QuerySingleAsync(sql, map)); private T Batch<T>(Func<IDbBatch, T> func) { var batch = NewBatch(); var result = func(batch); batch.Commit(); return result; } private async Task<T> BatchAsync<T>(Func<IDbBatch, Task<T>> func) { var batch = NewBatch(); var result = await func(batch); batch.Commit(); return result; } private void Do(Action<IDbBatch> func) { var batch = NewBatch(); func(batch); batch.Commit(); } private async Task DoAsync(Func<IDbBatch, Task> func) { var batch = NewBatch(); await func(batch); batch.Commit(); } } }
namespace SPOEmulators.EmulatedTypes { using System; using Microsoft.QualityTools.Testing.Fakes.Shims; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Fakes; internal class SimWebCollection : CollectionIsolator<Web, WebCollection, ShimWebCollection> { public SimWeb Parent { get; private set; } public SimWebCollection(SimWeb parent) : this(ShimRuntime.CreateUninitializedInstance<WebCollection>(), parent) { } public SimWebCollection(WebCollection instance, SimWeb parent) : base(instance) { Parent = parent; this.Fake.AddWebCreationInformation = (options) => AddWeb(options).Instance; new SimClientObjectCollection(this.Instance); } public SimWeb AddWeb(WebCreationInformation options) { var url = new Uri(Parent.Url.TrimEnd('/') + '/' + options.Url); var simWeb = new SimWeb { Title = options.Title, Url = url.AbsoluteUri.TrimEnd('/'), ServerRelativeUrl = url.AbsolutePath, Description = options.Description }; // todo: add other properties this.Add(simWeb.Instance); return simWeb; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GUC.WorldObjects; using GUC.Scripting; using GUC.Models; namespace GUC.Animations { /// <summary> /// Handle for an active animation (for progress etc.). /// </summary> public partial class ActiveAni { struct TimeActionPair { public float Frame; public long Time; public Action Callback; } Model model; /// <summary> The animated model which is playing this animation. </summary> public Model Model { get { return this.model; } } float fpsMult; /// <summary> The value with which the frame speed is multiplied. </summary> public float FrameSpeedMultiplier { get { return this.fpsMult; } } /// <summary> The frame speed with which the active animation is being played. </summary> public float FPS { get { return this.ani.FPS * this.fpsMult; } } Animation ani; /// <summary> The Animation which is being active. </summary> public Animation Ani { get { return this.ani; } } /// <summary> The AniJob of the active animation. </summary> public AniJob AniJob { get { return this.ani.AniJob; } } long startTime; long endTime; public bool IsIdleAni { get { return this.endTime < 0; } } internal ActiveAni(Model model) { this.model = model ?? throw new ArgumentNullException("Model is null!"); } public float GetProgress() { return endTime < 0 ? 0 : (float)(GameTime.Ticks - this.startTime) / (this.endTime - this.startTime); } float totalFinishedFrames; // frames from previous animations List<TimeActionPair> actionPairs = new List<TimeActionPair>(1); void AddPair(float frame, Action callback, long time) { TimeActionPair pair = new TimeActionPair(); pair.Frame = frame; pair.Callback = callback; pair.Time = time < 0 ? long.MaxValue : time; for (int i = 0; i < actionPairs.Count; i++) if (time > actionPairs[i].Time) { actionPairs.Insert(i, pair); return; } actionPairs.Add(pair); } float cachedProgress = 0; FrameActionPair[] cachedPairs = null; bool cachedStuff = false; internal void Start(Animation ani, float fpsMult, float progress, FrameActionPair[] pairs) { if (!this.Model.Vob.IsSpawned) { this.ani = ani; this.fpsMult = fpsMult; this.cachedProgress = progress; this.cachedPairs = pairs; this.cachedStuff = true; return; } else { cachedStuff = false; this.cachedPairs = null; } this.ani = ani; this.fpsMult = fpsMult; this.totalFinishedFrames = 0; float numFrames = ani.GetFrameNum(); if (numFrames > 0) { float coeff = TimeSpan.TicksPerSecond / (ani.FPS * fpsMult); float duration = numFrames * coeff; startTime = GameTime.Ticks - (long)(progress * duration); endTime = startTime + (long)duration; if (pairs != null && pairs.Length > 0) { for (int i = pairs.Length - 1; i >= 0; i--) { FrameActionPair pair = pairs[i]; if (pair.Callback != null) { AddPair(pair.Frame, pair.Callback, startTime + (long)(pair.Frame * coeff)); } } } } else // idle ani { endTime = -1; } } internal void Stop() { cachedStuff = false; this.cachedPairs = null; if (this.actionPairs.Count > 0) { // fire all callbacks which should happen when or after the last nextAni ends float lastFrame = this.totalFinishedFrames; AniJob nextAniJob = this.AniJob; while (nextAniJob != null && this.model.TryGetAniFromJob(nextAniJob, out Animation nextAni)) { lastFrame += nextAni.GetFrameNum(); nextAniJob = nextAniJob.NextAni; } for (int i = 0; i < actionPairs.Count; i++) { if (this.actionPairs[i].Frame >= lastFrame) this.actionPairs[i].Callback(); else break; } this.actionPairs.Clear(); } this.ani = null; } internal void OnTick(long now) { if (cachedStuff) { this.Start(ani, fpsMult, cachedProgress, cachedPairs); } if (!this.IsIdleAni) { if (now < endTime) // still playing { for (int i = actionPairs.Count - 1; i >= 0; i--) { var current = actionPairs[i]; if (now < current.Time) break; actionPairs.RemoveAt(i); current.Callback(); if (this.ani == null) // ani is stopped break; } } else { AniJob nextAniJob = this.AniJob.NextAni; if (nextAniJob != null) { if (model.TryGetAniFromJob(nextAniJob, out Animation nextAni)) { Continue(nextAni); // there is a nextAni, continue playing it return; } } // fire all remaining actions actionPairs.ForEach(p => p.Callback()); actionPairs.Clear(); // end this animation model.EndAni(this.ani); this.ani = null; } } } void Continue(Animation nextAni) { float oldFrameNum = this.ani.GetFrameNum(); float newFrameNum = nextAni.GetFrameNum(); if (newFrameNum > 0) { float coeff = TimeSpan.TicksPerSecond / (nextAni.FPS * fpsMult); this.startTime = this.endTime; this.endTime = this.startTime + (long)(newFrameNum * coeff); for (int i = 0; i < actionPairs.Count; i++) { var pair = actionPairs[i]; pair.Frame = pair.Frame - oldFrameNum; // new frame pair.Time = startTime + (long)(pair.Frame * coeff); } } else { endTime = -1; } this.totalFinishedFrames += oldFrameNum; this.ani = nextAni; } } }
using FluentValidation; using Next.Cqrs.Commands; using Next.Validation.Fluent; namespace Next.Application.Validation.Fluent { public class AggregateCommandValidator : FluentValidator<IAggregateCommand> { public AggregateCommandValidator() { RuleFor(o => o.Id) .NotNull() .WithErrorCode("InvalidEntityId") .WithMessage("Invalid aggregate identifier."); RuleFor(o => o.Id.Value) .NotEmpty() .WithErrorCode("InvalidEntityId") .WithMessage("Invalid aggregate identifier."); } } }
namespace VaporStore.Data.Models { using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Enums; public class Purchase { public Purchase() { } public Purchase(Game game, PurchaseType type, Card card, string productKey, DateTime date) { this.Game = game; this.Type = type; this.Card = card; this.ProductKey = productKey; this.Date = date; } [Key] public int Id { get; set; } public PurchaseType Type { get; set; } [RegularExpression(@"^[\dA-Z]{4}-[\dA-Z]{4}-[\dA-Z]{4}$")] public string ProductKey { get; set; } public DateTime Date { get; set; } [ForeignKey(nameof(Card))] public int CardId { get; set; } public Card Card { get; set; } [ForeignKey(nameof(Game))] public int GameId { get; set; } public Game Game { get; set; } } }
using DotNetDevOps.Extensions.EAVFramework; using DotNetDevOps.Extensions.EAVFramework.Shared; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using System; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Security.Claims; using System.Text.Json.Serialization; namespace EAVFW.Extensions.SecurityModel { [BaseEntity] [Serializable] [GenericTypeArgument(ArgumentName = "TIdentity", ManifestKey = "Identity")] public class BaseOwnerEntity<TIdentity> : BaseIdEntity<TIdentity> where TIdentity : DynamicEntity { [DataMember(Name = "ownerid")] [JsonProperty("ownerid")] [JsonPropertyName("ownerid")] public Guid? OwnerId { get; set; } [ForeignKey("OwnerId")] [DataMember(Name = "owner")] [JsonProperty("owner")] [JsonPropertyName("owner")] public TIdentity Owner { get; set; } } }
using Godot; using System; public class chest : StaticBody2D { private bool nearChest = false; private bool isOpen = false; private bool isCrying = false; private AnimationTree animationTree; private AnimationNodeStateMachinePlayback animationState; public override void _Ready() { animationTree = GetNode<AnimationTree>("AnimationTree"); animationState = (AnimationNodeStateMachinePlayback)animationTree.Get("parameters/playback"); } public override void _Process(float delta) { if(Input.IsActionJustPressed("interact") && nearChest == true) { animationState.Travel("open chest"); isOpen = true; } else if(Input.IsActionJustPressed("interact") && isCrying == true) { animationState.Travel("close chest"); isCrying = false; } else if(nearChest == false && isOpen == true) { animationState.Travel("close chest"); isOpen = false; } } private void _on_Area2D_area_entered(Area2D hitbox) { if (hitbox.Name == "weapon") { isCrying = true; animationState.Travel("crying chest 1"); } nearChest = true; } private void _on_Area2D_area_exited(Area2D hitbox) { nearChest = false; } }
using AntDesign; using EntityG.Contracts.Requests.Identity; using EntityG.Contracts.Responses.Identity; using EntityG.Shared.Wrapper; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ConfirmButtons = AntDesign.ConfirmButtons; using ConfirmResult = AntDesign.ConfirmResult; namespace EntityG.Client.Pages.Roles { public partial class Roles { public List<RoleResponse> RoleList = new List<RoleResponse>(); private RoleResponse _role = new RoleResponse(); private string searchString = ""; private static string CREATED_ROLE = "Created Role"; private bool RoleDiaglogVisiable { get; set; } private Form<RoleResponse> RoleDiaglogForm { get; set; } private string RoleDiaglogTitle { get; set; } private bool IsLoading { get; set; } protected override async Task OnInitializedAsync() { await GetRolesAsync(); } private async Task GetRolesAsync() { IsLoading = true; var response = await _roleManager.GetRolesAsync(); if (response.Succeeded) { RoleList = response.Data.ToList(); } else { foreach (var message in response.Messages) { } } IsLoading = false; } private void Create() { _role = new RoleResponse(); RoleDiaglogTitle = "Create role"; RoleDiaglogVisiable = true; } private void Edit(string id) { _role = new RoleResponse { Id = id, Name = RoleList.FirstOrDefault(x => x.Id.Equals(id))?.Name }; RoleDiaglogTitle = "Update role"; RoleDiaglogVisiable = true; } private async Task SaveAsync(RoleResponse item) { var roleRequest = new RoleRequest() { Name = item.Name, Id = item.Id }; var result = await _roleManager.SaveAsync(roleRequest); if (result.Succeeded) { RoleDiaglogVisiable = false; await GetRolesAsync(); } else { foreach (var message in result.Messages) { await _message.Error(message); } } } private async Task DeleteRole(RoleResponse role) { var response = await _roleManager.DeleteAsync(role.Id); if (response.Succeeded) { RoleList.Remove(role); await GetRolesAsync(); } else { foreach (var message in response.Messages) { await _message.Error(message); } } } private async Task ShowDeleteConfirm(RoleResponse role) { var content = $"Are you sure to delete role '{role.Name}' ?"; var title = "Delete confirmation"; var confirmResult = await _confirmService.Show(content, title, ConfirmButtons.YesNo); if (confirmResult == ConfirmResult.Yes) { await DeleteRole(role); } } private void ManagePermissions(string roleId) { _navigationManager.NavigateTo($"/identity/role-permissions/{roleId}"); } private async Task HandleRoleDiaglogOk() { if (this.RoleDiaglogForm.Validate()) { await SaveAsync(_role); } } private void HandleRoleDiaglogCancel() { RoleDiaglogVisiable = false; } } }
using PhotoShop.Core.Interfaces; using MediatR; using System; namespace PhotoShop.Core.Common { public class AuthenticatedRequest<TResponse> : IAuthenticatedRequest, IRequest<TResponse> { public Guid CurrentUserId { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; public delegate void NextPageBtnClickHandler(ICutsceneController controller); public interface ICutsceneController { void ShowPagedDialog(bool show); void AnimateTextInPagedDialog(string text, Action completion); Coroutine StartCoroutine(IEnumerator routine); void StopCoroutine(Coroutine routine); GameObject InstantiatePrefab(string id, Vector3 position, Quaternion rotation); void DestroyObject(string name); } public interface IPagedDialogController { void AttachToNextBtnClickEvent(NextPageBtnClickHandler eventHandler); void DetachFromNextBtnClickEvent(NextPageBtnClickHandler eventHandler); void AnimateTextInDialogPage(string pageText, Action completion); } public class CutsceneController : MonoBehaviour , ICutsceneController , IPagedDialogController { public GameObject cutsceneCanvas; public GameObject dialogPanel; public Text dialogText; public float dialogTextSpeed; public GameObject nextPageButtonObj; public CutscenePrefabs prefabs; private CutsceneQueue _cutsceneQueue; private event NextPageBtnClickHandler NextPageBtnClicked; private Coroutine _pagedDialogAnimationCoroutine; private CutsceneQueue _pagedDialogCutsceneQueue; public void RunCutscene(Cutscene cutscene, Action completion) { cutsceneCanvas.SetActive(true); var context = new CutsceneQueueContext(this, () => { cutsceneCanvas.SetActive(false); completion(); }); _cutsceneQueue = new CutsceneQueue(cutscene, context); _cutsceneQueue.Run(); } public void ShowPagedDialog(bool show) { dialogPanel.SetActive(show); } public void AnimateTextInPagedDialog(string text, Action completion) { IEnumerable<DialogPage> dialogPages = GetDialogPages(text); var cutscene = new Cutscene(); foreach (var page in dialogPages) { cutscene.Add(new DialogPageAction(page, this)); } var context = new CutsceneQueueContext(this, completion); _pagedDialogCutsceneQueue = new CutsceneQueue(cutscene, context); _pagedDialogCutsceneQueue.Run(); } public GameObject InstantiatePrefab(string id, Vector3 position, Quaternion rotation) { var prefabObj = prefabs.GetPrefab(id); if (prefabObj == null) return null; return Instantiate(prefabObj, position, rotation); } public void DestroyObject(string name) { var obj = this.transform.Find(name); if (obj == null) return; Destroy(obj); } private IEnumerable<DialogPage> GetDialogPages(string text) { var textGenerator = dialogText.cachedTextGenerator; var currentText = text; var visibleText = text; List<DialogPage> dialogPages = new List<DialogPage>(); var generationSettings = dialogText.GetGenerationSettings(dialogText.rectTransform.rect.size); do { textGenerator.Populate(currentText, generationSettings); var visibleCharCount = textGenerator.characterCountVisible; visibleText = currentText.Substring(0, visibleCharCount); dialogPages.Add(new DialogPage(visibleText)); currentText = currentText.Substring(visibleText.Length); } while (currentText.Length > 0); return dialogPages; } public void OnNextPageBtnClick() { NextPageBtnClicked(this); } public void AttachToNextBtnClickEvent(NextPageBtnClickHandler eventHandler) { NextPageBtnClicked += eventHandler; } public void DetachFromNextBtnClickEvent(NextPageBtnClickHandler eventHandler) { NextPageBtnClicked -= eventHandler; } public void AnimateTextInDialogPage(string pageText, Action completion) { if (_pagedDialogAnimationCoroutine != null) { StopCoroutine(_pagedDialogAnimationCoroutine); } _pagedDialogAnimationCoroutine = StartCoroutine(AnimateTextInDialogPageCoroutine(pageText, completion)); } private IEnumerator AnimateTextInDialogPageCoroutine(string pageText, Action completion) { for (var i = 0; i <= pageText.Length; i++) { dialogText.text = pageText.Substring(0, i); yield return new WaitForSeconds(dialogTextSpeed); } completion(); } }
using System.Threading.Tasks; using Abp.Auditing; using Abp.Timing; using tibs.stem.Auditing; using tibs.stem.Auditing.Dto; using tibs.stem.Authorization.Users; using Shouldly; using Xunit; namespace tibs.stem.Tests.Auditing { public class AuditLogAppService_Tests : AppTestBase { private readonly IAuditLogAppService _auditLogAppService; public AuditLogAppService_Tests() { _auditLogAppService = Resolve<IAuditLogAppService>(); } [Fact] public async Task Should_Get_Audit_Logs() { //Arrange UsingDbContext( context => { context.AuditLogs.Add( new AuditLog { TenantId = AbpSession.TenantId, UserId = AbpSession.UserId, ServiceName = "ServiceName-Test-1", MethodName = "MethodName-Test-1", Parameters = "{}", ExecutionTime = Clock.Now.AddMinutes(-1), ExecutionDuration = 123 }); context.AuditLogs.Add( new AuditLog { TenantId = AbpSession.TenantId, ServiceName = "ServiceName-Test-2", MethodName = "MethodName-Test-2", Parameters = "{}", ExecutionTime = Clock.Now, ExecutionDuration = 456 }); }); //Act var output = await _auditLogAppService.GetAuditLogs(new GetAuditLogsInput { StartDate = Clock.Now.AddMinutes(-10), EndDate = Clock.Now.AddMinutes(10) }); output.TotalCount.ShouldBe(2); output.Items[0].ServiceName.ShouldBe("ServiceName-Test-2"); output.Items[0].UserName.ShouldBe(null); output.Items[1].ServiceName.ShouldBe("ServiceName-Test-1"); output.Items[1].UserName.ShouldBe(User.AdminUserName, StringCompareShould.IgnoreCase); } } }
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using Microsoft.WindowsAzure.MobileServices; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace DeviceTests.Shared.TestPlatform { public class E2ETestBase { public readonly string MobileServiceRuntimeUrl = "https://zumo-e2etest-net4.azurewebsites.net"; /// <summary> /// If you have registered an entire push infrastructure, feel free to enable the push tests. /// Push Tests are not run by default. /// </summary> public readonly bool EnablePushTests = false; static MobileServiceClient staticClient; /// <summary> /// Get a client pointed at the test server without request logging. /// </summary> /// <returns>The test client.</returns> public MobileServiceClient GetClient() { if (staticClient == null) { staticClient = new MobileServiceClient(MobileServiceRuntimeUrl, new LoggingHttpHandler()); } return staticClient; } } class LoggingHttpHandler : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Console.WriteLine(" >>> {0} {1} {2}", request.Method, request.RequestUri, request.Content?.ReadAsStringAsync().Result); HttpResponseMessage response = await base.SendAsync(request, cancellationToken); Console.WriteLine(" <<< {0} {1} {2}", (int)response.StatusCode, response.ReasonPhrase, response.Content?.ReadAsStringAsync().Result); return response; } } }
using System; using System.Collections.Generic; using System.Text; namespace TypeSafe.Http.Net { public interface IDeserializationStrategyFactory { /// <summary> /// Creates a serialization strategy for the provided <see cref="contentType"/>. /// </summary> /// <param name="contentType">Non-null non-empty content type.</param> /// <returns>A request serialization strategy if found.</returns> IResponseDeserializationStrategy DeserializerFor(string contentType); } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.TestHost; namespace OSharp.UnitTest.Infrastructure { public abstract class AspNetCoreUnitTestBase<TStartup> where TStartup : class { protected AspNetCoreUnitTestBase() { var builder = CreateWebHostBuilder(); Server = CreateTestServer(builder); Client = Server.CreateClient(); ServerProvider = Server.Host.Services; } public TestServer Server { get; } public HttpClient Client { get; } public IServiceProvider ServerProvider { get; set; } protected virtual IWebHostBuilder CreateWebHostBuilder() { return new WebHostBuilder().UseStartup<TStartup>(); } protected virtual TestServer CreateTestServer(IWebHostBuilder builder) { return new TestServer(builder); } } }
using SeemplestLight.PortableCore.Timing; using SeemplestLight.PortableCore.Tracing; using System.Threading; namespace SeemplestLight.Net46.Core.Tracing { /// <summary> /// This class defines a trace log item /// </summary> public class TraceEntry: TraceEntryBase { /// <summary> /// Fills up properties that are not defined explicitly. /// </summary> public override void EnsureProperties() { // --- Provide a timestamp if (!TimestampUtc.HasValue) { TimestampUtc = DateTimeProvider.GetCurrenDateTimeUtc(); } // --- Provide the current machine's name as server name if (HostName == null) { //HostName = EnvironmentProvider.GetHostName(); } // --- Provide thread information if (!ThreadId.HasValue) { ThreadId = Thread.CurrentThread.ManagedThreadId; } } } }
using System.Collections.Generic; namespace ScotlandsMountains.Domain { public class Root { public IList<Classification> Classifications { get; set; } public IList<Section> Sections { get; set; } public IList<County> Counties { get; set; } public IList<Map> Maps { get; set; } public IList<Mountain> Mountains { get; set; } } }
using System.Collections.Generic; using UnityEngine; using System.Linq; using SanAndreasUnity.Importing.Items; using SanAndreasUnity.Importing.Items.Definitions; using SanAndreasUnity.Behaviours; using SanAndreasUnity.Behaviours.Vehicles; namespace SanAndreasUnity.UI { public class VehicleSpawnerWindow : PauseMenuWindow { private List<IGrouping<VehicleType, VehicleDef>> vehicleGroupings = null; private int[] columnWidths = new int[]{ 120, 120, 30, 70 }; VehicleSpawnerWindow() { // set default parameters this.windowName = "Vehicle Spawner"; this.useScrollView = true; } void Start () { this.RegisterButtonInPauseMenu (); // adjust rect //float windowWidth = 400; //float windowHeight = Mathf.Min (700, Screen.height * 0.7f); //this.windowRect = Utilities.GUIUtils.GetCornerRect (SanAndreasUnity.Utilities.ScreenCorner.TopRight, // new Vector2 (windowWidth, windowHeight), new Vector2 (20, 20)); this.windowRect = Utilities.GUIUtils.GetCenteredRectPerc( new Vector2(0.4f, 0.8f) ); } void GetVehicleDefs() { // get all vehicle definitions var allVehicles = Item.GetDefinitions<VehicleDef> (); // group them by type var groupings = allVehicles.GroupBy (v => v.VehicleType); this.vehicleGroupings = groupings.ToList (); } protected override void OnWindowGUI () { if (Behaviours.Loader.HasLoaded && null == this.vehicleGroupings) { GetVehicleDefs (); } if (null == this.vehicleGroupings) return; GUILayout.Space (10); // for each vehicle, display a button which spawns it foreach (var grouping in this.vehicleGroupings) { GUILayout.Label (grouping.Key.ToString ()); GUILayout.Space (10); // table columns // GUILayout.BeginHorizontal(); // GUILayout.Label ("Game name", GUILayout.Width (this.columnWidths [0])); // GUILayout.Label ("Class name", GUILayout.Width (this.columnWidths [1])); // GUILayout.Label ("Id", GUILayout.Width (this.columnWidths [2])); // GUILayout.Label ("Frequency", GUILayout.Width (this.columnWidths [3])); // GUILayout.EndHorizontal (); // // GUILayout.Space (10); // display all vehicles of this type foreach (var v in grouping) { //GUILayout.BeginHorizontal (); if (GUILayout.Button (v.GameName, GUILayout.Width(this.columnWidths[0]))) { if (Utilities.NetUtils.IsServer) { if (Ped.Instance != null) Vehicle.CreateInFrontOf (v.Id, Ped.Instance.transform); } else if (Net.PlayerRequests.Local != null) { Net.PlayerRequests.Local.RequestVehicleSpawn(v.Id); } } //GUILayout.Label (v.ClassName, GUILayout.Width (this.columnWidths [1])); //GUILayout.Label (v.Id.ToString(), GUILayout.Width (this.columnWidths [2])); //GUILayout.Label (v.Frequency.ToString(), GUILayout.Width (this.columnWidths [3])); //GUILayout.EndHorizontal (); } GUILayout.Space (10); } GUILayout.Space (20); } } }
// // Copyright (c) Antmicro // Copyright (c) Realtime Embedded // // This file is part of the Emul8 project. // Full license details are defined in the 'LICENSE' file. // using System; using Emul8.Peripherals.Input; using System.Collections.Generic; using Emul8.Logging; using Emul8.Core; namespace Emul8.Peripherals.USB { public class USBTablet :IUSBPeripheral, IAbsolutePositionPointerInput { public USBTablet(Machine machine) { this.machine = machine; Reset(); } public event Action<uint> SendInterrupt; public event Action <uint> SendPacket { add {} remove {} } public USBDeviceSpeed GetSpeed() { return USBDeviceSpeed.Low; } public void ClearFeature(USBPacket packet, USBSetupPacket setupPacket) { throw new NotImplementedException(); } public byte[] GetConfiguration() { throw new NotImplementedException(); } public void SetAddress(uint address) { deviceAddress = address; } public byte[] GetInterface(USBPacket packet, USBSetupPacket setupPacket) { throw new NotImplementedException(); } public byte[] GetStatus(USBPacket packet, USBSetupPacket setupPacket) { var arr = new byte[2]; return arr; } public void SetConfiguration(USBPacket packet, USBSetupPacket setupPacket) { } public void SetDescriptor(USBPacket packet, USBSetupPacket setupPacket) { throw new NotImplementedException(); } public void SetFeature(USBPacket packet, USBSetupPacket setupPacket) { throw new NotImplementedException(); } public void SetInterface(USBPacket packet, USBSetupPacket setupPacket) { throw new NotImplementedException(); } public byte[] ProcessVendorGet(USBPacket packet, USBSetupPacket setupPacket) { throw new NotImplementedException(); } public void ProcessVendorSet(USBPacket packet, USBSetupPacket setupPacket) { throw new NotImplementedException(); } public byte[] ProcessClassGet(USBPacket packet, USBSetupPacket setupPacket) { return controlPacket; } public void ProcessClassSet(USBPacket packet, USBSetupPacket setupPacket) { } public void SetDataToggle(byte endpointNumber) { throw new NotImplementedException(); } public void CleanDataToggle(byte endpointNumber) { throw new NotImplementedException(); } public bool GetDataToggle(byte endpointNumber) { throw new NotImplementedException(); } public void ToggleDataToggle(byte endpointNumber) { throw new NotImplementedException(); } public uint GetAddress() { return deviceAddress; } public byte[] WriteInterrupt(USBPacket packet) { lock(thisLock) { if(changeState) { buffer[5] = 0; changeState = false; return this.buffer; } else return null; } } public byte[] GetDataBulk(USBPacket packet) { return null; } public byte[] GetDataControl(USBPacket packet) { return controlPacket; } public byte GetTransferStatus() { return 0; } public byte[] GetDescriptor(USBPacket packet, USBSetupPacket setupPacket) { DescriptorType type; type = (DescriptorType)((setupPacket.value & 0xff00) >> 8); uint index = (uint)(setupPacket.value & 0xff); switch(type) { case DescriptorType.Device: controlPacket = new byte[deviceDescriptor.ToArray().Length]; deviceDescriptor.ToArray().CopyTo(controlPacket, 0); return deviceDescriptor.ToArray(); case DescriptorType.Configuration: controlPacket = new byte[configurationDescriptor.ToArray().Length]; configurationDescriptor.ToArray().CopyTo(controlPacket, 0); controlPacket = tabletConfigDescriptor; return configurationDescriptor.ToArray(); case DescriptorType.DeviceQualifier: controlPacket = new byte[deviceQualifierDescriptor.ToArray().Length]; deviceQualifierDescriptor.ToArray().CopyTo(controlPacket, 0); return deviceQualifierDescriptor.ToArray(); case DescriptorType.InterfacePower: throw new NotImplementedException("Interface Power Descriptor is not yet implemented. Please contact AntMicro for further support."); case DescriptorType.OtherSpeedConfiguration: controlPacket = new byte[otherConfigurationDescriptor.ToArray().Length]; otherConfigurationDescriptor.ToArray().CopyTo(controlPacket, 0); return otherConfigurationDescriptor.ToArray(); case DescriptorType.String: if(index == 0) { stringDescriptor = new StringUSBDescriptor(1); stringDescriptor.LangId[0] = EnglishLangId; } else { stringDescriptor = new StringUSBDescriptor(stringValues[setupPacket.index][index]); } controlPacket = new byte[stringDescriptor.ToArray().Length]; stringDescriptor.ToArray().CopyTo(controlPacket, 0); return stringDescriptor.ToArray(); case (DescriptorType)0x22: controlPacket = tabletHIDReportDescriptor; break; default: this.Log(LogLevel.Warning, "Unsupported mouse request!!!"); return null; } return null; } public void WriteDataBulk(USBPacket packet) { } public void WriteDataControl(USBPacket packet) { } public void Reset() { x = y = 0; otherConfigurationDescriptor = new ConfigurationUSBDescriptor(); deviceQualifierDescriptor = new DeviceQualifierUSBDescriptor(); endpointDescriptor = new EndpointUSBDescriptor[3]; for(int i = 0; i < NumberOfEndpoints; i++) { endpointDescriptor[i] = new EndpointUSBDescriptor(); } fillEndpointsDescriptors(endpointDescriptor); interfaceDescriptor[0].EndpointDescriptor = endpointDescriptor; configurationDescriptor.InterfaceDescriptor = interfaceDescriptor; mstate = 0; changeState = false; buffer = new byte[6]; } public void Press(MouseButton button) { machine.ReportForeignEvent(button, PressInner); } public void Release(MouseButton button) { machine.ReportForeignEvent(button, ReleaseInner); } public void MoveTo(int x, int y) { machine.ReportForeignEvent(x, y, MoveToInner); } public int MaxX { get { return 32767; } } public int MaxY { get { return 32767; } } public int MinX { get { return 0; } } public int MinY { get { return 0; } } private void MoveToInner(int x, int y) { lock(thisLock) { this.x = x; this.y = y; buffer[0] = mstate; buffer[1] = (byte)(x & byte.MaxValue); // x small buffer[2] = (byte)((x >> 8) & 127); // x big buffer[3] = (byte)(y & byte.MaxValue); // y small buffer[4] = (byte)((y >> 8) & 127); // y big changeState = true; } Refresh(); } private void PressInner(MouseButton button) { lock(thisLock) { mstate = (byte)button; buffer[0] = mstate; buffer[1] = (byte)(x & byte.MaxValue); // x small buffer[2] = (byte)((x >> 8) & 127); // x big buffer[3] = (byte)(y & byte.MaxValue); // y small buffer[4] = (byte)((y >> 8) & 127); // y big changeState = true; } Refresh(); } private void ReleaseInner(MouseButton button) { lock(thisLock) { buffer[0] = mstate = 0; buffer[1] = (byte)(x & byte.MaxValue); // x small buffer[2] = (byte)((x >> 8) & 127); // x big buffer[3] = (byte)(y & byte.MaxValue); // y small buffer[4] = (byte)((y >> 8) & 127); // y big changeState = true; } Refresh(); } private void fillEndpointsDescriptors(EndpointUSBDescriptor[] endpointDesc) { endpointDesc[0].EndpointNumber = 1; endpointDesc[0].InEnpoint = true; endpointDesc[0].TransferType = EndpointUSBDescriptor.TransferTypeEnum.Interrupt; endpointDesc[0].MaxPacketSize = 0x0008; endpointDesc[0].SynchronizationType = EndpointUSBDescriptor.SynchronizationTypeEnum.NoSynchronization; endpointDesc[0].UsageType = EndpointUSBDescriptor.UsageTypeEnum.Data; endpointDesc[0].Interval = 0x0a; } private void Refresh() { if(deviceAddress != 0) { SendInterrupt(deviceAddress); } } private const byte NumX = 28; private const byte NumY = 16; private const ushort EnglishLangId = 0x09; private const byte NumberOfEndpoints = 2; private uint deviceAddress; private Object thisLock = new Object(); private DeviceQualifierUSBDescriptor deviceQualifierDescriptor; private ConfigurationUSBDescriptor otherConfigurationDescriptor; private StringUSBDescriptor stringDescriptor = null; private EndpointUSBDescriptor[] endpointDescriptor; private byte[] controlPacket; private Byte[] buffer; private int x; private int y; private byte mstate = 0; private bool changeState = false; private readonly Machine machine; private Dictionary<ushort, string[]> stringValues = new Dictionary<ushort, string[]>() { {EnglishLangId, new string[] { "", "1", "HID Tablet", "AntMicro", "", "", "HID Tablet", "Configuration" } } }; private InterfaceUSBDescriptor[] interfaceDescriptor = new[] {new InterfaceUSBDescriptor { AlternateSetting = 0, InterfaceNumber = 0x00, NumberOfEndpoints = 1, InterfaceClass = 0x03, InterfaceProtocol = 0x02, InterfaceSubClass = 0x01, InterfaceIndex = 0x07 } }; private ConfigurationUSBDescriptor configurationDescriptor = new ConfigurationUSBDescriptor() { ConfigurationIndex = 0, SelfPowered = true, NumberOfInterfaces = 1, RemoteWakeup = true, MaxPower = 50, //500mA ConfigurationValue = 1 }; private StandardUSBDescriptor deviceDescriptor = new StandardUSBDescriptor { DeviceClass = 0x00, DeviceSubClass = 0x00, USB = 0x0100, DeviceProtocol = 0x00, MaxPacketSize = 8, VendorId = 0x80ee, ProductId = 0x0021, Device = 0x0000, ManufacturerIndex = 3, ProductIndex = 2, SerialNumberIndex = 1, NumberOfConfigurations = 1 }; private byte[] tabletConfigDescriptor = { 0x09, 0x02, 0x22, 0x00, 0x01, 0x01, 0x05, 0xa0, 50, 0x09, 0x04, 0x00, 0x00, 0x01, 0x03, 0x01, 0x02, 0x07, 0x09, 0x21, 0x01, 0x00, 0x00, 0x01, 0x22, 74, 0, 0x07, 0x05, 0x81, 0x03, 0x04, 0x00, 0x0a }; private byte[] tabletHIDReportDescriptor = { 0x05, 0x01, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, 0x95, 0x01, 0x75, 0x05, 0x81, 0x01, 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x26, 0xff, 0x7f, 0x35, 0x00, 0x46, 0xff, 0x7f, 0x75, 0x10, 0x95, 0x02, 0x81, 0x02, 0x05, 0x01, 0x09, 0x38, 0x15, 0x81, 0x25, 0x7f, 0x35, 0x00, 0x45, 0x00, 0x75, 0x08, 0x95, 0x01, 0x81, 0x06, 0xc0, 0xc0, }; } }
using DX.Cqrs.Mongo.Facade; using Xunit; using Xunit.Abstractions; namespace DX.Testing { [Collection("BSON")] public class MongoFeature : BsonSerializationFeature { protected ITestOutputHelper Output { get; } internal MongoTestEnvironment Env { get; set; } internal MongoFacade DB { get; set; } public MongoFeature(ITestOutputHelper output) => Output = output; public override void Background() { base.Background(); USING["a mongo DB"] = () => Env = new MongoTestEnvironment(Output); AND["a mongo facade"] = () => DB = Env.GetFacade(); } } }
using System; using DevExpress.ExpressApp.Editors; using DevExpress.ExpressApp.Model; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using Xpand.Extensions.StringExtensions; using EditorAliases = Xpand.Extensions.XAF.Attributes.EditorAliases; namespace Xpand.XAF.Modules.Blazor.Editors { [PropertyEditor(typeof(object), EditorAliases.MarkupContent,false)] public class MarkupContentPropertyEditor : ComponentPropertyEditor { public MarkupContentPropertyEditor(Type objectType, IModelMemberViewItem model) : base(objectType, model) { } protected override RenderFragment CreateViewComponentCore(object dataContext) => Render; protected override RenderFragment RenderComponent() => Render; private void Render(RenderTreeBuilder builder) { builder.AddMarkupContent(0, $"{PropertyValue}".StringFormat(Model.DisplayFormat)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes { /// <summary> /// Contains operation for working with SSH Shell. /// </summary> [TestClass] public class ShellStreamTest : TestBase { } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using JuloUtil; using JuloAudio; namespace JuloMenuSystem { public class VolumeItem : Item { public bool value = true; public float volume = 1f; public SoundSource soundSource; public Sprite onIcon; public Sprite offIcon; Image iconImage; Slider slider; public override void onStart() { iconImage = JuloFind.byName<Image>("Icon", this); slider = JuloFind.byName<Slider>("Slider", this); _setValue(value); _setVolume(volume); } public override bool click(MenuSystem menuSystem) { if(soundSource.isOn != value) { Debug.LogWarning("Is not equal"); } setValue(!soundSource.isOn); if(value && volume <= 0f) { _setVolume(0.7f); slider.value = volume; } return true; } public override bool move(MenuSystem menuSystem, bool direction) { if(direction && volume < 1f) { slider.value = Mathf.Min(1f, slider.value + 0.2f); return true; } else if(!direction && volume > 0f) { slider.value = Mathf.Max(0, slider.value - 0.2f); return true; } else { return false; } } public void onChangeVolume(float newVolume) { setVolume(newVolume); } public void setValue(bool newValue) { if(newValue != value) { _setValue(newValue); } } public void setVolume(float newVolume) { _setVolume(newVolume); if(volume <= 0.001f && value) { volume = 0f; setValue(false); } else if(volume > 0.001f && !value) { setValue(true); } } void _setValue(bool newValue) { value = newValue; soundSource.isOn = value; iconImage.sprite = value ? onIcon : offIcon; } void _setVolume(float newVolume) { volume = newVolume; soundSource.setVolume(volume); } } }
using System; using System.ComponentModel.DataAnnotations; namespace Project.Models.Core.Entities.Base { /// <summary> /// ENTITY BASE ABSTRACT CLASS /// </summary> public abstract class EntityBase : IEntityBase, IRowVersion { /// <summary> /// CREATION DATE /// </summary> public DateTime CreationDate { get; set; } /// <summary> /// MODIFICATION DATE /// </summary> public DateTime ModificationDate { get; set; } /// <summary> /// EXCLUSION DATE /// </summary> public DateTime? ExclusionDate { get; set; } /// <summary> /// ROW VERSION FOR DBCONCURRENCY /// </summary> [Timestamp] public byte[] RowVersion { get; set; } } }
/**************************************************************************** * ____ _ _ * * | _ \ (_) | | * * | |_) | __ _ ___ _ _____ _| | ___ __ _ __ _ ___ _ __ * * | _ < / _` / __| |/ __\ \/ / | / _ \ / _` |/ _` |/ _ \ '__| * * | |_) | (_| \__ \ | (__ > <| |___| (_) | (_| | (_| | __/ | * * |____/ \__,_|___/_|\___/_/\_\______\___/ \__, |\__, |\___|_| * * __/ | __/ | * * |___/ |___/ * * by basicx-StrgV * * https://github.com/basicx-StrgV/BasicxLogger * * * * **************************************************************************/ using System; using System.Threading.Tasks; using BasicxLogger.Base; using BasicxLogger.Files; namespace BasicxLogger { /// <summary> /// File logger that contains everything needed to write a message to a log file. /// </summary> /// <remarks> /// This logger supports the following file formats: txt, log, xml and json /// </remarks> public class FileLogger : ILogger { /// <summary> /// Gets the <see cref="BasicxLogger.Base.ILogFile"/> that is used by the logger. /// </summary> public ILogFile LogFile { get; } = new TxtLogFile( String.Format("{0}/{1}/", Environment.CurrentDirectory, "Logs"), "Log"); /// <summary> /// Gets or Sets the <see cref="BasicxLogger.Timestamp"/> that is used by the logger. /// </summary> public Timestamp MessageTimestamp { get; set; } = Timestamp.Year_Month_Day_Hour24_Min_Sec; /// <summary> /// Gets or Sets a default message tag that will be used if no tag is selected. /// </summary> public LogTag DefaultTag { get; set; } = LogTag.none; /// <summary> /// Gets or Sets if each log entry should contain a unique id or not. /// </summary> public bool UseId { get; set; } = true; /// <summary> /// Initializes a new instance of the <see cref="BasicxLogger.FileLogger"/> class, /// that uses the default settings. /// </summary> public FileLogger() { } /// <summary> /// Initializes a new instance of the <see cref="BasicxLogger.FileLogger"/> class. /// </summary> /// <param name="logFile">The log file of the logger</param> public FileLogger(ILogFile logFile) { LogFile = logFile; } /// <summary> /// Writes the given message to the log file. /// </summary> /// <param name="message">The message that will be writen to the file</param> /// <returns> /// The unique id for the log entry if <see cref="BasicxLogger.FileLogger.UseId"/> is true /// or null if <see cref="BasicxLogger.FileLogger.UseId"/> is false. /// </returns> public string Log(string message) { try { if (UseId) { string id = IdHandler.UniqueId; LogFile.WriteToFile(DefaultTag, MessageTimestamp.GetTimestamp(), message, id); return id; } else { LogFile.WriteToFile(DefaultTag, MessageTimestamp.GetTimestamp(), message); return null; } } catch (Exception e) { throw e; } } /// <summary> /// Writes the given message to the log file. /// </summary> /// <param name="message">The message that will be writen to the file</param> /// <param name="messageTag"> /// A Tag that will be added to the message, to make it easy to distinguish between differen log messages /// </param> /// <returns> /// The unique id for the log entry if <see cref="BasicxLogger.FileLogger.UseId"/> is true /// or null if <see cref="BasicxLogger.FileLogger.UseId"/> is false. /// </returns> public string Log(LogTag messageTag, string message) { try { if (UseId) { string id = IdHandler.UniqueId; LogFile.WriteToFile(messageTag, MessageTimestamp.GetTimestamp(), message, id); return id; } else { LogFile.WriteToFile(messageTag, MessageTimestamp.GetTimestamp(), message); return null; } } catch (Exception e) { throw e; } } /// <summary> /// Asynchronous writes the given message to the log file. /// </summary> /// <param name="message">The message that will be writen to the file</param> /// <returns> /// The unique id for the log entry if <see cref="BasicxLogger.FileLogger.UseId"/> is true /// or null if <see cref="BasicxLogger.FileLogger.UseId"/> is false. /// </returns> public async Task<string> LogAsync(string message) { try { Task<string> logTask = Task.Run(() => Log(message)); await logTask; return logTask.Result; } catch (Exception e) { throw e; } } /// <summary> /// Asynchronous writes the given message to the log file. /// </summary> /// <param name="message">The message that will be writen to the file</param> /// <param name="messageTag"> /// A Tag that will be added to the message, to make it easy to distinguish between differen log messages /// </param> /// <returns> /// The unique id for the log entry if <see cref="BasicxLogger.FileLogger.UseId"/> is true /// or null if <see cref="BasicxLogger.FileLogger.UseId"/> is false. /// </returns> public async Task<string> LogAsync(LogTag messageTag, string message) { try { Task<string> logTask = Task.Run(() => Log(messageTag, message)); await logTask; return logTask.Result; } catch (Exception e) { throw e; } } } }
using UnityEngine.UI; using UnityEngine; public class DisplayHealth : MonoBehaviour { Image fg_healthBar; CharacterHealth char_health; void Awake() { char_health = transform.root.GetComponent<CharacterHealth>(); fg_healthBar = transform.GetChild(1).GetComponent<Image>(); } private void OnEnable() => char_health.HitEvent += UpdateHealthBar; private void OnDisable() => char_health.HitEvent += UpdateHealthBar; void UpdateHealthBar(float new_health, float maxHealth) { fg_healthBar.fillAmount = Mathf.Clamp(new_health/maxHealth, 0, 1f); } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using BAMCIS.PrestoClient.Serialization; using System; using System.Collections.Generic; using System.Linq; namespace BAMCIS.PrestoClient.Model.Sql.Planner.Plan { //[JsonConverter(typeof(PlanNodeConverter))] public abstract class PlanNode { private static readonly Dictionary<Type, PlanNodeType> TypeToDerivedType; private static readonly Dictionary<PlanNodeType, Type> DerivedTypeToType; static PlanNode() { TypeToDerivedType = new Dictionary<Type, PlanNodeType>() { { typeof(PlanNode), PlanNodeType.BASE }, { typeof(AggregationNode), PlanNodeType.AGGREGATION }, { typeof(ApplyNode), PlanNodeType.APPLY }, { typeof(AssignUniqueId), PlanNodeType.ASSIGNUNIQUEID }, { typeof(DeleteNode), PlanNodeType.DELETE }, { typeof(DistinctLimitNode), PlanNodeType.DISTINCTLIMIT }, { typeof(ExchangeNode), PlanNodeType.EXCHANGE }, { typeof(ExplainAnalyzeNode), PlanNodeType.EXPLAINANALYZE }, { typeof(FilterNode), PlanNodeType.FILTER }, { typeof(GroupIdNode), PlanNodeType.GROUPID }, { typeof(IndexJoinNode), PlanNodeType.INDEXJOIN }, { typeof(IndexSourceNode), PlanNodeType.INDEXSOURCE }, { typeof(JoinNode), PlanNodeType.JOIN }, { typeof(LateralJoinNode), PlanNodeType.LATERALJOIN }, { typeof(LimitNode), PlanNodeType.LIMIT }, { typeof(MarkDistinctNode), PlanNodeType.MARKDISTINCT }, { typeof(MetadataDeleteNode), PlanNodeType.METADATADELETE }, { typeof(OutputNode), PlanNodeType.OUTPUT }, { typeof(ProjectNode), PlanNodeType.PROJECT }, { typeof(RemoteSourceNode), PlanNodeType.REMOTESOURCE }, { typeof(RowNumberNode), PlanNodeType.ROWNUMBER }, { typeof(SampleNode), PlanNodeType.SAMPLE }, { typeof(EnforceSingleRowNode), PlanNodeType.SCALAR }, { typeof(SemiJoinNode), PlanNodeType.SEMIJOIN }, { typeof(SortNode), PlanNodeType.SORT }, { typeof(TableFinishNode), PlanNodeType.TABLECOMMIT }, { typeof(TableScanNode), PlanNodeType.TABLESCAN }, { typeof(TableWriterNode), PlanNodeType.TABLEWRITER }, { typeof(TopNNode), PlanNodeType.TOPN }, { typeof(TopNRowNumberNode), PlanNodeType.TOPNROWNUMBER }, { typeof(UnionNode), PlanNodeType.UNION }, { typeof(UnnestNode), PlanNodeType.UNNEST }, { typeof(ValuesNode), PlanNodeType.VALUES }, { typeof(WindowNode), PlanNodeType.WINDOW } }; DerivedTypeToType = TypeToDerivedType.ToDictionary(pair => pair.Value, pair => pair.Key); } public PlanNode(PlanNodeId id) { this.Id = id ?? throw new ArgumentNullException("id"); } [JsonConverter(typeof(StringEnumConverter))] [JsonProperty(PropertyName = "@type")] public PlanNodeType NodeType { get { // This will return the actual type of the class // from derived classes return TypeToDerivedType[this.GetType()]; } } public PlanNodeId Id { get; set; } public static Type GetType(PlanNodeType type) { return DerivedTypeToType[type]; } public abstract IEnumerable<Symbol> GetOutputSymbols(); public abstract IEnumerable<PlanNode> GetSources(); } }
using System.Drawing; using System.IO; using System.Reflection; using System.Windows.Forms; using Engine; namespace SuperAdventure { public partial class WorldMap : Form { readonly Assembly _thisAssembly = Assembly.GetExecutingAssembly(); public WorldMap(Player player) { InitializeComponent(); SetImage(pic_0_2, player.LocationsVisited.Contains(5) ? "HerbalistsGarden" : "FogLocation"); SetImage(pic_1_2, player.LocationsVisited.Contains(4) ? "HerbalistsHut" : "FogLocation"); SetImage(pic_2_0, player.LocationsVisited.Contains(7) ? "FarmFields" : "FogLocation"); SetImage(pic_2_1, player.LocationsVisited.Contains(6) ? "Farmhouse" : "FogLocation"); SetImage(pic_2_2, player.LocationsVisited.Contains(2) ? "TownSquare" : "FogLocation"); SetImage(pic_2_3, player.LocationsVisited.Contains(3) ? "TownGate" : "FogLocation"); SetImage(pic_2_4, player.LocationsVisited.Contains(8) ? "Bridge" : "FogLocation"); SetImage(pic_2_5, player.LocationsVisited.Contains(9) ? "SpiderForest" : "FogLocation"); SetImage(pic_3_2, player.LocationsVisited.Contains(1) ? "Home" : "FogLocation"); } private void SetImage(PictureBox pictureBox, string imageName) { using (Stream resourceStream = _thisAssembly.GetManifestResourceStream( _thisAssembly.GetName().Name + ".Images." + imageName + ".png")) { if (resourceStream != null) { pictureBox.Image = new Bitmap(resourceStream); } } } } }
using helper.mvvm.commands; using System.Collections.ObjectModel; using System.ComponentModel; namespace StreamCompanion.Contract { public interface IViewModel : INotifyPropertyChanged { ActionCommand AddSerieCmd { get; } ActionCommand EditSerieCmd { get; } ActionCommand ForceReloadStreamCmd { get; } ActionCommand ReloadAllCmd { get; } ActionCommand SetAsCurrentlyWatchingCmd { get; } ActionCommand SetAsCompletedCmd { get; } ActionCommand SetAsOnHoldCmd { get; } ActionCommand SetAsDroppedCmd { get; } ActionCommand SetAsPlanToWatchCmd { get; } ActionCommand DoneCmd { get; } ActionCommand CancelCmd { get; } ISerie SelectedItem { get; set; } ObservableCollection<ISerie> Series { get; } ObservableCollection<string> Types { get; } bool IsBusy { get; } bool IsAddNewSerieVisible { get; set; } string NewSerieName{ get; set; } int? NewSerieSeason { get; set; } int? NewSerieCurrentEpisode { get; set; } int? NewSerieMaxEpisodes{ get; set; } string NewSerieComment{ get; set; } string NewSerieType { get; set; } } public enum SerieType { TV, Anime, Cartoon, Movie, OVA, Special, Mixed } public enum Language { Deutsch, English, Français, Español } }
using SoulsFormats; using System.Collections.Generic; using System.Numerics; namespace HKX2 { public partial class hclSimulationSetupMeshMapOptions : IHavokObject { public virtual uint Signature { get => 2828547247; } public bool m_collapseVertices; public float m_collapseThreshold; public hclVertexSelectionInput m_vertexSelection; public virtual void Read(PackFileDeserializer des, BinaryReaderEx br) { m_collapseVertices = br.ReadBoolean(); br.ReadUInt16(); br.ReadByte(); m_collapseThreshold = br.ReadSingle(); m_vertexSelection = new hclVertexSelectionInput(); m_vertexSelection.Read(des, br); } public virtual void Write(PackFileSerializer s, BinaryWriterEx bw) { bw.WriteBoolean(m_collapseVertices); bw.WriteUInt16(0); bw.WriteByte(0); bw.WriteSingle(m_collapseThreshold); m_vertexSelection.Write(s, bw); } } }
namespace MinimaxAI { internal interface INodeMinMax<T> : IDFSNode<T>, IMinMaxOperations<T>, IDebugNode { static T Max { get; set;} static T Min { get; set; } INodeMinMax<T> Parent { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using MegaCasting.DBlib; namespace MegaCasting.WPF.ViewModel { class ViewModelListContact : ViewModelBase { #region Attributes /// <summary> /// Collection de Contact /// </summary> private ObservableCollection<Contact> _Contact; private Contact _SelectedContact; #endregion #region Properties /// <summary> /// Obtient ou définit la collection de Contact /// </summary> public ObservableCollection<Contact> Contacts { get { return _Contact; } set { _Contact = value; } } public Contact SelectedContact { get { return _SelectedContact; } set { _SelectedContact = value; } } #endregion #region Construtor public ViewModelListContact(MegaCastingEntities entities) : base(entities) { this.Entities.Contacts.ToList(); this.Contacts = this.Entities.Contacts.Local; } #endregion #region Method #endregion } }
using SFA.DAS.Notifications.Messages.Commands; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace SFA.DAS.ApprenticeCommitments.Jobs.UnitTests { internal class SendEmailCommandComparer : IEqualityComparer<SendEmailCommand> { public bool Equals([AllowNull] SendEmailCommand x, [AllowNull] SendEmailCommand y) { if (x.TemplateId != y.TemplateId) return false; if (x.RecipientsAddress != y.RecipientsAddress) return false; foreach (var t in x.Tokens) { if (!x.Tokens.TryGetValue(t.Key, out var other)) return false; if (t.Value != other) return false; } return true; } public int GetHashCode([DisallowNull] SendEmailCommand obj) => obj.TemplateId.GetHashCode(); } }
using System; using System.Collections.Generic; using System.Text; namespace FashionNova.Model.Requests { public class NarudzbaStavkeInsertRequest { public int NarudzbaId { get; set; } public int Kolicina { get; set; } public decimal Cijena { get; set; } public decimal? Popust { get; set; } public int ArtikalId { get; set; } } }
namespace MappingSPO.Project.DL.Entities { public partial class UsersGroepEntity { public UsersGroepEntity() { InvoiceCreate = true; InvoiceSearch = true; UserUserGroups = new System.Collections.Generic.List<UserUserGroupEntity>(); InitializePartial(); } public int UserGroupId { get; set; } public string UserGroup { get; set; } public bool IsAdministrator { get; set; } public bool IsPowerUser { get; set; } public bool IsSysGroup { get; set; } public bool? IsManagement { get; set; } public bool? CanChangeEmmaArticles { get; set; } public bool InvoiceCreate { get; set; } public bool InvoiceSearch { get; set; } public bool? EmployeeSearch { get; set; } public bool? EmployeeFinancial { get; set; } public bool? EmployeeChange { get; set; } public bool? ShowOnlyCalculatorBoundCalculations { get; set; } public bool? ShowOnlyOmzetOffertes { get; set; } public System.Collections.Generic.ICollection<UserUserGroupEntity> UserUserGroups { get; set; } partial void InitializePartial(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgoSharp.Types; public class CountableDictionary<KeyType, ValueType> where KeyType : IComparable<KeyType> where ValueType : IComparable<ValueType> { private readonly Dictionary<KeyType, ValueType> dictionary = new(); private readonly AlgoAnalyzer analyzer; public CountableDictionary(AlgoAnalyzer analyzer) { this.analyzer = analyzer; } public Countable<ValueType> this[Countable<KeyType> key] { get { analyzer.Count(1, "Dictionary Get"); return new Countable<ValueType>(dictionary[key.Value], analyzer); } set { dictionary[key.Value] = value.Value; analyzer.Count(1, "Dictionary Set"); } } public IEnumerable<Countable<KeyType>> Keys { get { analyzer.Count(dictionary.Count, "Dictionary Get"); return dictionary.Keys.Select(i => new Countable<KeyType>(i, analyzer)); } } public IEnumerable<Countable<ValueType>> Values { get { analyzer.Count(dictionary.Count, "Dictionary Set"); return dictionary.Values.Select(i => new Countable<ValueType>(i, analyzer)); } } public int Count { get { analyzer.Count(1, "Get Dictionary Count"); return dictionary.Count; } } public bool IsReadOnly => false; public void Add(Countable<KeyType> key, Countable<ValueType> value) { analyzer.Count(1, "Dictionary Add"); dictionary.Add(key.Value, value.Value); } public void Clear() { throw new NotImplementedException(); } public bool Contains(Countable<KeyType> key, Countable<ValueType> value) { analyzer.Count(1, "Dictionary Contains"); return dictionary.ContainsKey(key.Value) && (dictionary[key.Value]?.Equals(value.Value) ?? (value.Value is null)); } public bool ContainsKey(Countable<KeyType> key) { analyzer.Count(1, "Dictionary Contains"); return dictionary.ContainsKey(key.Value); } public void Remove(Countable<KeyType> key) { analyzer.Count(2, "Dictionary Remove"); if(dictionary.ContainsKey(key.Value)) dictionary.Remove(key.Value); } }
//Implementaiton of Breadth first search algorithm // C# program to print BFS traversal from a given source vertex. // BFS(int s) traverses vertices reachable from s. using System; using System.Collections.Generic; namespace BFS { // This class represents a directed graph using adjacency list representation public class Graph { private int V; // No of vertices or nodes private LinkedList<int>[] adj; // A linkedlist array for adjacent nodes // Constructor // Create a graph with v vertices public Graph(int v) { this.V = v; // Since no of nodes are v. So a node can be connected at most no of v vertices adj = new LinkedList<int>[v]; // Initialize each adjacent nodes for(int i = 0; i < v; i++) { adj[i] = new LinkedList<int>(); } } // Method to add an edge in a graph from v to w public void AddEdge(int v, int w) { // Add a new node containing the specific value 'w' at the end of the linked list adj[v].AddLast(w); } // prints BFS traversal from a given source s public void BFS(int s) { // Mark all the vertices as not visited(By default set as false) bool[] visited = new bool[V]; // Create a queue for BFS Queue<int> queue = new Queue<int>(); // Mark the current node as visited and enqueue it // Add it to the queue = enqueue visited[s] = true; queue.Enqueue(s); // Traverse all the vertices while(queue.Count != 0) { // Dequeue a vertex from the queue and print it s = queue.Dequeue(); Console.Write(s + " "); // Get all adjacent vertices of the dequeued vertex s // If the adjacent vertex is not visited, mark it visited and enque it. foreach (int adjVertex in adj[s]) { //If the vertext is not visited if(!visited[adjVertex]) { visited[adjVertex] = true; queue.Enqueue(adjVertex); } } } } } public class Program { // Driver method to test static void Main(string[] args) { // Create a graph with 4 node or vertices Graph g = new Graph(4); // Connect a vertex with other vertex with an edge g.AddEdge(0, 1); g.AddEdge(0, 2); g.AddEdge(1, 2); g.AddEdge(2, 0); g.AddEdge(2, 3); g.AddEdge(3, 3); // Traverse the graph Console.WriteLine("Following is Breadth First Traversal (starting from vertex 2)"); g.BFS(2); // Output // Following is Breadth First Traversal (starting from vertex 2) // 2 0 3 1 // Create a graph with 4 node or vertices Graph h = new Graph(6); // Connect a vertex with other vertex with an edge h.AddEdge(0, 1); h.AddEdge(0, 2); h.AddEdge(1, 0); h.AddEdge(1, 3); h.AddEdge(1, 4); h.AddEdge(2, 4); h.AddEdge(3, 4); h.AddEdge(3, 4); h.AddEdge(4, 5); // Traverse the graph Console.WriteLine("\nFollowing is Breadth First Traversal (starting from vertex 1)"); h.BFS(0); // Output // Following is Breadth First Traversal (starting from vertex 0) // 0 1 2 3 4 5 Console.ReadKey(); } } }
using System; namespace Domain0.Repository.Model { public class Account { public int Id { get; set; } public string Email { get; set; } public decimal? Phone { get; set; } public string Login { get; set; } public string Password { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime? FirstDate { get; set; } public DateTime? LastDate { get; set; } public bool IsLocked { get; set; } } }
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_LuaCameraMonoBehaviour : LuaObject { [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"LuaCameraMonoBehaviour"); createTypeMetatable(l,null, typeof(LuaCameraMonoBehaviour),typeof(LuaMonoBehaviourBase)); } }
using UnityEngine; using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_CanvasRenderer : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.CanvasRenderer o; o=new UnityEngine.CanvasRenderer(); pushValue(l,o); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetColor(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); UnityEngine.Color a1; checkType(l,2,out a1); self.SetColor(a1); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetColor(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); var ret=self.GetColor(); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetAlpha(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); var ret=self.GetAlpha(); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetAlpha(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); System.Single a1; checkType(l,2,out a1); self.SetAlpha(a1); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetMaterial(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); UnityEngine.Material a1; checkType(l,2,out a1); UnityEngine.Texture a2; checkType(l,3,out a2); self.SetMaterial(a1,a2); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetMaterial(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); var ret=self.GetMaterial(); pushValue(l,ret); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetVertices(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==2){ UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); System.Collections.Generic.List<UnityEngine.UIVertex> a1; checkType(l,2,out a1); self.SetVertices(a1); return 0; } else if(argc==3){ UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); UnityEngine.UIVertex[] a1; checkType(l,2,out a1); System.Int32 a2; checkType(l,3,out a2); self.SetVertices(a1,a2); return 0; } LuaDLL.luaL_error(l,"No matched override function to call"); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Clear(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); self.Clear(); return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isMask(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); pushValue(l,self.isMask); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_isMask(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); bool v; checkType(l,2,out v); self.isMask=v; return 0; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_relativeDepth(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); pushValue(l,self.relativeDepth); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_absoluteDepth(IntPtr l) { try { UnityEngine.CanvasRenderer self=(UnityEngine.CanvasRenderer)checkSelf(l); pushValue(l,self.absoluteDepth); return 1; } catch(Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.CanvasRenderer"); addMember(l,SetColor); addMember(l,GetColor); addMember(l,GetAlpha); addMember(l,SetAlpha); addMember(l,SetMaterial); addMember(l,GetMaterial); addMember(l,SetVertices); addMember(l,Clear); addMember(l,"isMask",get_isMask,set_isMask,true); addMember(l,"relativeDepth",get_relativeDepth,null,true); addMember(l,"absoluteDepth",get_absoluteDepth,null,true); createTypeMetatable(l,constructor, typeof(UnityEngine.CanvasRenderer),typeof(UnityEngine.Component)); } }
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using Free = System.Security.SuppressUnmanagedCodeSecurityAttribute; [Free, SFx] public interface IReadOnlySpanFactory<S,T> : IFunc { ReadOnlySpan<T> Invoke(in S src); } [Free, SFx] public interface IReadOnlySpanFactory<H,S,T> : IReadOnlySpanFactory<S,T> where H : struct, IReadOnlySpanFactory<H,S,T> { } }
// Copyright 2014 The Authors Marx-Yu. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace WopiCobaltHost { [DataContract] public class WopiCheckFileInfo { [DataMember] public bool AllowExternalMarketplace { get; set; } [DataMember] public string BaseFileName { get; set; } [DataMember] public string BreadcrumbBrandName { get; set; } [DataMember] public string BreadcrumbBrandUrl { get; set; } [DataMember] public string BreadcrumbDocName { get; set; } [DataMember] public string BreadcrumbDocUrl { get; set; } [DataMember] public string BreadcrumbFolderName { get; set; } [DataMember] public string BreadcrumbFolderUrl { get; set; } [DataMember] public string ClientUrl { get; set; } [DataMember] public bool CloseButtonClosesWindow { get; set; } [DataMember] public string CloseUrl { get; set; } [DataMember] public bool DisableBrowserCachingOfUserContent { get; set; } [DataMember] public bool DisablePrint { get; set; } [DataMember] public bool DisableTranslation { get; set; } [DataMember] public string DownloadUrl { get; set; } [DataMember] public string FileSharingUrl { get; set; } [DataMember] public string FileUrl { get; set; } [DataMember] public string HostAuthenticationId { get; set; } [DataMember] public string HostEditUrl { get; set; } [DataMember] public string HostEmbeddedEditUrl { get; set; } [DataMember] public string HostEmbeddedViewUrl { get; set; } [DataMember] public string HostName { get; set; } [DataMember] public string HostNotes { get; set; } [DataMember] public string HostRestUrl { get; set; } [DataMember] public string HostViewUrl { get; set; } [DataMember] public string IrmPolicyDescription { get; set; } [DataMember] public string IrmPolicyTitle { get; set; } [DataMember] public string OwnerId { get; set; } [DataMember] public string PresenceProvider { get; set; } [DataMember] public string PresenceUserId { get; set; } [DataMember] public string PrivacyUrl { get; set; } [DataMember] public bool ProtectInClient { get; set; } [DataMember] public bool ReadOnly { get; set; } [DataMember] public bool RestrictedWebViewOnly { get; set; } [DataMember] public string SHA256 { get; set; } [DataMember] public string SignoutUrl { get; set; } [DataMember] public long Size { get; set; } [DataMember] public bool SupportsCoauth { get; set; } [DataMember] public bool SupportsCobalt { get; set; } [DataMember] public bool SupportsFolders { get; set; } [DataMember] public bool SupportsLocks { get; set; } [DataMember] public bool SupportsScenarioLinks { get; set; } [DataMember] public bool SupportsSecureStore { get; set; } [DataMember] public bool SupportsUpdate { get; set; } [DataMember] public string TenantId { get; set; } [DataMember] public string TermsOfUseUrl { get; set; } [DataMember] public string TimeZone { get; set; } [DataMember] public bool UserCanAttend { get; set; } [DataMember] public bool UserCanNotWriteRelative { get; set; } [DataMember] public bool UserCanPresent { get; set; } [DataMember] public bool UserCanWrite { get; set; } [DataMember] public string UserFriendlyName { get; set; } [DataMember] public string UserId { get; set; } [DataMember] public string Version { get; set; } [DataMember] public bool WebEditingDisabled { get; set; } } }
// Decompiled with JetBrains decompiler // Type: CocoStudio.ControlLib.FileSuffix // Assembly: CocoStudio.ControlLib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 677D14F9-F98B-4FDA-9ECD-6C6F82FD30A1 // Assembly location: C:\Program Files (x86)\Cocos\Cocos Studio 2\CocoStudio.ControlLib.dll namespace CocoStudio.ControlLib { public static class FileSuffix { public const string CCS = ".ccs"; public const string PlistInfo = ".plistinfo"; public const string CSD = ".csd"; public const string CSI = ".csi"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; using Strive.Core.Interfaces; using Strive.Core.Services.Chat.Channels; using Strive.Core.Services.Chat.Gateways; using Strive.Core.Services.Chat.Notifications; using Strive.Core.Services.Chat.Requests; using Strive.Core.Services.ParticipantsList.Requests; using Strive.Core.Services.Synchronization.Requests; namespace Strive.Core.Services.Chat.UseCases { public class SendChatMessageUseCase : IRequestHandler<SendChatMessageRequest, SuccessOrError<Unit>> { private readonly IMediator _mediator; private readonly IChatRepository _chatRepository; public SendChatMessageUseCase(IMediator mediator, IChatRepository chatRepository) { _mediator = mediator; _chatRepository = chatRepository; } public async Task<SuccessOrError<Unit>> Handle(SendChatMessageRequest request, CancellationToken cancellationToken) { var (participant, _, channel, _) = request; var conferenceId = participant.ConferenceId; var message = await BuildChatMessage(request); var channelId = ChannelSerializer.Encode(channel); var messagesCount = await _chatRepository.AddChatMessageAndGetMessageCount(conferenceId, channelId.ToString(), message); var subscribedParticipants = await _mediator.Send(new FetchSubscribedParticipantsRequest(conferenceId, channelId)); if (channel is PrivateChatChannel privateChatChannel) subscribedParticipants = await UpdateParticipantsSubscriptionsIfNecessary(subscribedParticipants, privateChatChannel, participant.ConferenceId); await _mediator.Publish(new ChatMessageReceivedNotification(conferenceId, subscribedParticipants, message, channel, messagesCount)); await _mediator.Send(new SetParticipantTypingRequest(participant, channel, false)); return Unit.Value; } private async ValueTask<ChatMessage> BuildChatMessage(SendChatMessageRequest request) { var timestamp = DateTimeOffset.UtcNow; var (participant, messageText, _, options) = request; var metadata = await _mediator.Send(new FetchParticipantsMetadataRequest(participant)); var sender = new ChatMessageSender(participant.Id, metadata); return new ChatMessage(sender, messageText, timestamp, options); } private async ValueTask<List<Participant>> UpdateParticipantsSubscriptionsIfNecessary( IReadOnlyList<Participant> subscribedParticipants, PrivateChatChannel channel, string conferenceId) { var result = subscribedParticipants.ToList(); foreach (var participantId in channel.Participants) { if (subscribedParticipants.All(participant => participant.Id != participantId)) { await _mediator.Send(new UpdateSubscriptionsRequest(new Participant(conferenceId, participantId))); result.Add(new Participant(conferenceId, participantId)); } } return result; } } }
using GipfLib.Models; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace GipfLib.AI { public class RandomAI : IGipfAI { private Random _rand = new Random(); private bool _playingWhite; public bool playingWhite { get { return _playingWhite; } } public Move MakeBestMove(Game game) { Board board = game.GetCurrentBoard(); Move move; if ((_playingWhite && board.WhiteToPlay) || (!_playingWhite && !board.WhiteToPlay)) { move = PickBestMove(board); game.TryMakeMove(move); } else { throw new Exception("It is not my move :("); } return move; } public void BeginNewGame(bool playingWhite) { _playingWhite = playingWhite; } Move GetRandomMove(IReadOnlyList<Move> moves) { return moves[_rand.Next(0, moves.Count - 1)]; } public string Name { get { return "RandomAI"; } } public Move PickBestMove(Board board) { IReadOnlyList<Move> moves = board.GetMoves(); return GetRandomMove(moves); } public Task<Move> PickBestMoveAsync(Board board, CancellationToken aiCancelToken) { IReadOnlyList<Move> moves = board.GetMoves(); return Task.FromResult(GetRandomMove(moves)); } } }