content
stringlengths
23
1.05M
using AuditManagementPortalClientMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AuditManagementPortalClientMVC.Providers { public interface IChecklistProvider { public List<CQuestions> ProvideChecklist(string audittype); } }
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; namespace DataAccess { public class EwalletContext : IdentityDbContext<User, IdentityRole<int>, int> { public DbSet<CardAccount> CardAccounts { get; set; } public DbSet<CardApplication> CardOrders { get; set; } public EwalletContext(DbContextOptions<EwalletContext> options) : base(options) { } } }
using System; using BEPUphysics.Entities; using BEPUutilities; namespace BEPUphysics.Constraints.TwoEntity.Joints { /// <summary> /// Constrains two bodies so that they can rotate relative to each other like a modified door hinge. /// Instead of removing two degrees of freedom, only one is removed so that the second connection to the constraint can twist. /// </summary> public class SwivelHingeAngularJoint : Joint, I1DImpulseConstraintWithError, I1DJacobianConstraint { private float accumulatedImpulse; private float biasVelocity; private System.Numerics.Vector3 jacobianA, jacobianB; private float error; private System.Numerics.Vector3 localHingeAxis; private System.Numerics.Vector3 localTwistAxis; private System.Numerics.Vector3 worldHingeAxis; private System.Numerics.Vector3 worldTwistAxis; private float velocityToImpulse; /// <summary> /// Constructs a new constraint which allows relative angular motion around a hinge axis and a twist axis. /// To finish the initialization, specify the connections (ConnectionA and ConnectionB) /// as well as the WorldHingeAxis and WorldTwistAxis (or their entity-local versions). /// This constructor sets the constraint's IsActive property to false by default. /// </summary> public SwivelHingeAngularJoint() { IsActive = false; } /// <summary> /// Constructs a new constraint which allows relative angular motion around a hinge axis and a twist axis. /// </summary> /// <param name="connectionA">First connection of the pair.</param> /// <param name="connectionB">Second connection of the pair.</param> /// <param name="worldHingeAxis">Hinge axis attached to connectionA. /// The connected entities will be able to rotate around this axis relative to each other.</param> /// <param name="worldTwistAxis">Twist axis attached to connectionB. /// The connected entities will be able to rotate around this axis relative to each other.</param> public SwivelHingeAngularJoint(Entity connectionA, Entity connectionB, System.Numerics.Vector3 worldHingeAxis, System.Numerics.Vector3 worldTwistAxis) { ConnectionA = connectionA; ConnectionB = connectionB; WorldHingeAxis = worldHingeAxis; WorldTwistAxis = worldTwistAxis; } /// <summary> /// Gets or sets the hinge axis attached to entity A in its local space. /// </summary> public System.Numerics.Vector3 LocalHingeAxis { get { return localHingeAxis; } set { localHingeAxis = System.Numerics.Vector3.Normalize(value); Matrix3x3.Transform(ref localHingeAxis, ref connectionA.orientationMatrix, out worldHingeAxis); } } /// <summary> /// Gets or sets the twist axis attached to entity B in its local space. /// </summary> public System.Numerics.Vector3 LocalTwistAxis { get { return localTwistAxis; } set { localTwistAxis = System.Numerics.Vector3.Normalize(value); Matrix3x3.Transform(ref localTwistAxis, ref connectionB.orientationMatrix, out worldTwistAxis); } } /// <summary> /// Gets or sets the hinge axis attached to entity A in world space. /// </summary> public System.Numerics.Vector3 WorldHingeAxis { get { return worldHingeAxis; } set { worldHingeAxis = System.Numerics.Vector3.Normalize(value); System.Numerics.Quaternion conjugate; QuaternionEx.Conjugate(ref connectionA.orientation, out conjugate); QuaternionEx.Transform(ref worldHingeAxis, ref conjugate, out localHingeAxis); } } /// <summary> /// Gets or sets the axis attached to the first connected entity in world space. /// </summary> public System.Numerics.Vector3 WorldTwistAxis { get { return worldTwistAxis; } set { worldTwistAxis = System.Numerics.Vector3.Normalize(value); System.Numerics.Quaternion conjugate; QuaternionEx.Conjugate(ref connectionB.orientation, out conjugate); QuaternionEx.Transform(ref worldTwistAxis, ref conjugate, out localTwistAxis); } } #region I1DImpulseConstraintWithError Members /// <summary> /// Gets the current relative velocity between the connected entities with respect to the constraint. /// </summary> public float RelativeVelocity { get { float velocityA, velocityB; //Find the velocity contribution from each connection Vector3Ex.Dot(ref connectionA.angularVelocity, ref jacobianA, out velocityA); Vector3Ex.Dot(ref connectionB.angularVelocity, ref jacobianB, out velocityB); return velocityA + velocityB; } } /// <summary> /// Gets the total impulse applied by this constraint. /// </summary> public float TotalImpulse { get { return accumulatedImpulse; } } /// <summary> /// Gets the current constraint error. /// </summary> public float Error { get { return error; } } #endregion #region I1DJacobianConstraint Members /// <summary> /// Gets the linear jacobian entry for the first connected entity. /// </summary> /// <param name="jacobian">Linear jacobian entry for the first connected entity.</param> public void GetLinearJacobianA(out System.Numerics.Vector3 jacobian) { jacobian = Toolbox.ZeroVector; } /// <summary> /// Gets the linear jacobian entry for the second connected entity. /// </summary> /// <param name="jacobian">Linear jacobian entry for the second connected entity.</param> public void GetLinearJacobianB(out System.Numerics.Vector3 jacobian) { jacobian = Toolbox.ZeroVector; } /// <summary> /// Gets the angular jacobian entry for the first connected entity. /// </summary> /// <param name="jacobian">Angular jacobian entry for the first connected entity.</param> public void GetAngularJacobianA(out System.Numerics.Vector3 jacobian) { jacobian = jacobianA; } /// <summary> /// Gets the angular jacobian entry for the second connected entity. /// </summary> /// <param name="jacobian">Angular jacobian entry for the second connected entity.</param> public void GetAngularJacobianB(out System.Numerics.Vector3 jacobian) { jacobian = jacobianB; } /// <summary> /// Gets the mass matrix of the constraint. /// </summary> /// <param name="outputMassMatrix">Constraint's mass matrix.</param> public void GetMassMatrix(out float outputMassMatrix) { outputMassMatrix = velocityToImpulse; } #endregion /// <summary> /// Solves for velocity. /// </summary> public override float SolveIteration() { float velocityA, velocityB; //Find the velocity contribution from each connection Vector3Ex.Dot(ref connectionA.angularVelocity, ref jacobianA, out velocityA); Vector3Ex.Dot(ref connectionB.angularVelocity, ref jacobianB, out velocityB); //Add in the constraint space bias velocity float lambda = -(velocityA + velocityB) - biasVelocity - softness * accumulatedImpulse; //Transform to an impulse lambda *= velocityToImpulse; //Accumulate the impulse accumulatedImpulse += lambda; //Apply the impulse System.Numerics.Vector3 impulse; if (connectionA.isDynamic) { Vector3Ex.Multiply(ref jacobianA, lambda, out impulse); connectionA.ApplyAngularImpulse(ref impulse); } if (connectionB.isDynamic) { Vector3Ex.Multiply(ref jacobianB, lambda, out impulse); connectionB.ApplyAngularImpulse(ref impulse); } return (Math.Abs(lambda)); } /// <summary> /// Do any necessary computations to prepare the constraint for this frame. /// </summary> /// <param name="dt">Simulation step length.</param> public override void Update(float dt) { //Transform the axes into world space. Matrix3x3.Transform(ref localHingeAxis, ref connectionA.orientationMatrix, out worldHingeAxis); Matrix3x3.Transform(ref localTwistAxis, ref connectionB.orientationMatrix, out worldTwistAxis); //****** VELOCITY BIAS ******// Vector3Ex.Dot(ref worldHingeAxis, ref worldTwistAxis, out error); //Compute the correction velocity. float errorReduction; springSettings.ComputeErrorReductionAndSoftness(dt, 1 / dt, out errorReduction, out softness); biasVelocity = MathHelper.Clamp(error * errorReduction, -maxCorrectiveVelocity, maxCorrectiveVelocity); //Compute the jacobian Vector3Ex.Cross(ref worldHingeAxis, ref worldTwistAxis, out jacobianA); float length = jacobianA.LengthSquared(); if (length > Toolbox.Epsilon) Vector3Ex.Divide(ref jacobianA, (float)Math.Sqrt(length), out jacobianA); else jacobianA = new System.Numerics.Vector3(); jacobianB.X = -jacobianA.X; jacobianB.Y = -jacobianA.Y; jacobianB.Z = -jacobianA.Z; //****** EFFECTIVE MASS MATRIX ******// //Connection A's contribution to the mass matrix float entryA; System.Numerics.Vector3 transformedAxis; if (connectionA.isDynamic) { Matrix3x3.Transform(ref jacobianA, ref connectionA.inertiaTensorInverse, out transformedAxis); Vector3Ex.Dot(ref transformedAxis, ref jacobianA, out entryA); } else entryA = 0; //Connection B's contribution to the mass matrix float entryB; if (connectionB.isDynamic) { Matrix3x3.Transform(ref jacobianB, ref connectionB.inertiaTensorInverse, out transformedAxis); Vector3Ex.Dot(ref transformedAxis, ref jacobianB, out entryB); } else entryB = 0; //Compute the inverse mass matrix velocityToImpulse = 1 / (softness + entryA + entryB); } /// <summary> /// Performs any pre-solve iteration work that needs exclusive /// access to the members of the solver updateable. /// Usually, this is used for applying warmstarting impulses. /// </summary> public override void ExclusiveUpdate() { //****** WARM STARTING ******// //Apply accumulated impulse System.Numerics.Vector3 impulse; if (connectionA.isDynamic) { Vector3Ex.Multiply(ref jacobianA, accumulatedImpulse, out impulse); connectionA.ApplyAngularImpulse(ref impulse); } if (connectionB.isDynamic) { Vector3Ex.Multiply(ref jacobianB, accumulatedImpulse, out impulse); connectionB.ApplyAngularImpulse(ref impulse); } } } }
using Prism.Regions; using Semaphore.UI.ViewModels; namespace Semaphore.Core.ViewModels { public class MainWindowViewModel : ViewModelBase { public MainWindowViewModel(IRegionManager regionManager) : base(regionManager) { } private string _title = "Semaphore.co SMS Client App"; public string Title { get => _title; set => SetProperty(ref _title, value); } } }
using System.Collections.Generic; namespace PactNet.Mocks.MockHttpService.Comparers { using PactNet.Comparers; internal interface IHttpHeaderComparer : IComparer<IDictionary<string, string>> { } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace Kwesoft.Pdf.UnitTests.Internal { [TestFixture] class PdfCrossReferenceTableTests { [Test] public void ConvertToString() { var result = new PdfCrossReferenceTable { ObjectOffsets = new Dictionary<int, int> { { 0, 0 }, { 1, 10 }, { 2, 20 } }, ObjectCount = 3, FirstObjectNumber = 0 }.ToString(); Assert.AreEqual("xref\n0 3\n0000000000 65535 f\n0000000010 00000 n\n0000000020 00000 n\n", result); } } }
using Nethereum.Contracts; using Nethereum.RPC.Eth.DTOs; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Nethereum.BlockchainProcessing.Processing.Logs { public class LogProcessor<TEventDto> : LogProcessorBase<TEventDto> where TEventDto : class, new() { public LogProcessor(Func<IEnumerable<EventLog<TEventDto>>, Task> callBack) { CallBack = callBack; } public Func<IEnumerable<EventLog<TEventDto>>, Task> CallBack { get; protected set; } public override async Task ProcessLogsAsync(params FilterLog[] eventLogs) { var list = eventLogs.DecodeAllEventsIgnoringIndexMisMatches<TEventDto>(); await CallBack(list); } } }
namespace Examples.ContentEditorCulture { public sealed class Constants { public const string TimezoneUserProfileFieldKey = "Timezone"; } }
using Rye.Cache.Redis.Internal; using Rye.Cache.Store; using System; using System.Threading.Tasks; using static CSRedis.CSRedisClient; namespace Rye.Cache.Redis.Store { public class MutilCacheStore : IMutilCacheStore { private readonly IMemoryStore _memoryStore; private readonly IRedisStore _redisStore; private static readonly string SERVICE_ID = Guid.NewGuid().ToString("N"); private static readonly string TOPIC_NAME = "RyeCacheSub"; private readonly SubscribeObject _subscribeObject; public MutilCacheStore(IMemoryStore memoryStore, IRedisStore redisStore) { _memoryStore = memoryStore; _redisStore = redisStore; _subscribeObject = _redisStore.Client.Subscribe((TOPIC_NAME, (msg) => { if (msg == null || string.IsNullOrEmpty(msg.Body)) { return; } var message = msg.Body.ToObject<CacheMessage>(); if (message == null) { return; } OnMessage(message); } )); } #region 多级缓存 private void OnMessage(CacheMessage message) { if (message == null || message.Keys == null || message.ServiceId == SERVICE_ID) //非本程序发送的消息,不做处理 return; //检测缓存是否存在 for (var i = 0; i < message.Keys.Length; i++) { var key = message.Keys[i]; if (string.IsNullOrEmpty(key)) continue; _memoryStore.Remove(key); } } /// <summary> /// 通知其他客户端清理过期缓存 /// </summary> /// <param name="keys"></param> protected void Publish(string[] keys) { if (keys == null) return; _redisStore.Client.Publish(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = keys }.ToJsonString()); } /// <summary> /// 通知其他客户端清理过期缓存 /// </summary> /// <param name="keys"></param> /// <returns></returns> protected async Task PublishAsync(string[] keys) { if (keys == null) return; await _redisStore.Client.PublishAsync(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = keys }.ToJsonString()); } /// <summary> /// 更新一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="data"></param> /// <param name="cacheSeconds"></param> protected void UpdateAndPublish<T>(string key, T data, int cacheSeconds) { if (string.IsNullOrEmpty(key) && Equals(data, default(T))) return; _memoryStore.Set(key, data, cacheSeconds); _redisStore.Client.Publish(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { key } }.ToJsonString()); } /// <summary> /// 更新一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entry"></param> /// <param name="data"></param> protected void UpdateAndPublish<T>(CacheOptionEntry entry, T data) { if (entry == null && Equals(data, default(T))) return; _memoryStore.Set(entry, data); _redisStore.Client.Publish(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { entry.Key } }.ToJsonString()); } /// <summary> /// 更新一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="data"></param> /// <param name="cacheSeconds"></param> /// <returns></returns> protected async Task UpdateAndPublishAsync<T>(string key, T data, int cacheSeconds) { if (string.IsNullOrEmpty(key) && Equals(data, default(T))) return; _memoryStore.Set(key, data, cacheSeconds); await _redisStore.Client.PublishAsync(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { key } }.ToJsonString()); } /// <summary> /// 更新一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entry"></param> /// <param name="data"></param> /// <returns></returns> protected async Task UpdateAndPublishAsync<T>(CacheOptionEntry entry, T data) { if (entry == null && Equals(data, default(T))) return; _memoryStore.Set(entry, data); await _redisStore.Client.PublishAsync(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { entry.Key } }.ToJsonString()); } /// <summary> /// 删除一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <param name="key"></param> protected void RemoveAndPublish(string key) { if (string.IsNullOrEmpty(key)) return; _memoryStore.Remove(key); _redisStore.Client.Publish(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { key } }.ToJsonString()); } /// <summary> /// 删除一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <param name="entry"></param> protected void RemoveAndPublish(CacheOptionEntry entry) { if (entry == null) return; _memoryStore.Remove(entry); _redisStore.Client.Publish(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { entry.Key } }.ToJsonString()); } /// <summary> /// 删除一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <param name="key"></param> /// <returns></returns> protected async Task RemoveAndPublishAsync(string key) { if (string.IsNullOrEmpty(key)) return; _memoryStore.Remove(key); await _redisStore.Client.PublishAsync(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { key } }.ToJsonString()); } /// <summary> /// 删除一级缓存,并通知其他客户端清理过期缓存 /// </summary> /// <param name="entry"></param> /// <returns></returns> protected async Task RemoveAndPublishAsync(CacheOptionEntry entry) { if (entry == null) return; _memoryStore.Remove(entry); await _redisStore.Client.PublishAsync(TOPIC_NAME, new CacheMessage { ServiceId = SERVICE_ID, Keys = new string[] { entry.Key } }.ToJsonString()); } #endregion private bool disposedValue; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _subscribeObject?.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(disposing: true); System.GC.SuppressFinalize(this); } public bool Exists(string key) { Check.NotNullOrEmpty(key, nameof(key)); var exist = _memoryStore.Exists(key); return exist ? exist : _redisStore.Exists(key); } public bool Exists(CacheOptionEntry entry) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); var exist = _memoryStore.Exists(entry.Key); return exist ? exist : _redisStore.Exists(entry.Key); } public async Task<bool> ExistsAsync(string key) { Check.NotNullOrEmpty(key, nameof(key)); var exist = _memoryStore.Exists(key); return exist ? exist : await _redisStore.ExistsAsync(key); } public async Task<bool> ExistsAsync(CacheOptionEntry entry) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); var exist = _memoryStore.Exists(entry.Key); return exist ? exist : await _redisStore.ExistsAsync(entry.Key); } public T Get<T>(string key) { return Get<T>(key, 60); } public Task<T> GetAsync<T>(string key) { return GetAsync<T>(key, 60); } public T Get<T>(string key, int cacheSeconds = 60) { Check.NotNullOrEmpty(key, nameof(key)); var data = _memoryStore.Get<T>(key); if (!Equals(data, default)) return data; data = _redisStore.Get<T>(key); if (!Equals(data, default)) { UpdateAndPublish(key, data, cacheSeconds); } return data; } public T Get<T>(string key, Func<T> func, int cacheSeconds = 60) { Check.NotNullOrEmpty(key, nameof(key)); Check.NotNull(func, nameof(func)); T data = _memoryStore.Get<T>(key); if (!Equals(data, default)) return data; data = _redisStore.Get<T>(key); if (!Equals(data, default)) { UpdateAndPublish(key, data, cacheSeconds); return data; } data = func(); if (Equals(data, default)) return default; _redisStore.Set(key, data, cacheSeconds); UpdateAndPublish(key, data, cacheSeconds); return data; } public T Get<T>(CacheOptionEntry entry) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); var data = _memoryStore.Get<T>(entry.Key); if (!Equals(data, default)) return data; data = _redisStore.Get<T>(entry.Key); if (!Equals(data, default)) { UpdateAndPublish(entry, data); } return data; } public T Get<T>(CacheOptionEntry entry, Func<T> func) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); Check.NotNull(func, nameof(func)); var data = _memoryStore.Get<T>(entry.Key); if (!Equals(data, default)) return data; data = _redisStore.Get<T>(entry.Key); if (!Equals(data, default)) { UpdateAndPublish(entry, data); return data; } data = func(); if (Equals(data, default)) return default; _redisStore.Set(entry, data); UpdateAndPublish(entry, data); return data; } public async Task<T> GetAsync<T>(string key, int cacheSeconds = 60) { Check.NotNullOrEmpty(key, nameof(key)); var data = _memoryStore.Get<T>(key); if (!Equals(data, default)) return data; data = await _redisStore.GetAsync<T>(key); if (!Equals(data, default)) { await UpdateAndPublishAsync(key, data, cacheSeconds); } return data; } public async Task<T> GetAsync<T>(string key, Func<T> func, int cacheSeconds = 60) { Check.NotNullOrEmpty(key, nameof(key)); Check.NotNull(func, nameof(func)); var data = _memoryStore.Get<T>(key); if (!Equals(data, default)) return data; data = await _redisStore.GetAsync<T>(key); if (!Equals(data, default)) { await UpdateAndPublishAsync(key, data, cacheSeconds); return data; } data = func(); if (Equals(data, default)) return default; await _redisStore.SetAsync(key, data, cacheSeconds); await UpdateAndPublishAsync(key, data, cacheSeconds); return data; } public async Task<T> GetAsync<T>(CacheOptionEntry entry) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); var data = _memoryStore.Get<T>(entry.Key); if (!Equals(data, default)) return data; data = await _redisStore.GetAsync<T>(entry.Key); if (!Equals(data, default)) { await UpdateAndPublishAsync(entry, data); } return data; } public async Task<T> GetAsync<T>(CacheOptionEntry entry, Func<T> func) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); Check.NotNull(func, nameof(func)); var data = _memoryStore.Get<T>(entry.Key); if (!Equals(data, default)) return data; data = await _redisStore.GetAsync<T>(entry.Key); if (!Equals(data, default)) { await UpdateAndPublishAsync(entry, data); return data; } data = func(); if (Equals(data, default)) return default; await _redisStore.SetAsync(entry, data); await UpdateAndPublishAsync(entry, data); return data; } public async Task<T> GetAsync<T>(string key, Func<Task<T>> func, int cacheSeconds = 60) { Check.NotNullOrEmpty(key, nameof(key)); Check.NotNull(func, nameof(func)); var data = _memoryStore.Get<T>(key); if (!Equals(data, default)) return data; data = await _redisStore.GetAsync<T>(key); if (!Equals(data, default)) { await UpdateAndPublishAsync(key, data, cacheSeconds); return data; } data = await func(); if (Equals(data, default)) return default; await _redisStore.SetAsync(key, data, cacheSeconds); await UpdateAndPublishAsync(key, data, cacheSeconds); return data; } public async Task<T> GetAsync<T>(CacheOptionEntry entry, Func<Task<T>> func) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); Check.NotNull(func, nameof(func)); var data = _memoryStore.Get<T>(entry.Key); if (!Equals(data, default)) return data; data = await _redisStore.GetAsync<T>(entry.Key); if (!Equals(data, default)) { await UpdateAndPublishAsync(entry, data); return data; } data = await func(); if (Equals(data, default)) return default; _memoryStore.Set(entry, data); await _redisStore.SetAsync(entry, data); await UpdateAndPublishAsync(entry, data); return data; } public void Remove(string key) { Check.NotNullOrEmpty(key, nameof(key)); _redisStore.Remove(key); RemoveAndPublish(key); } public void Remove(CacheOptionEntry entry) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); _redisStore.Remove(entry.Key); RemoveAndPublish(entry.Key); } public async Task RemoveAsync(string key) { Check.NotNullOrEmpty(key, nameof(key)); await _redisStore.RemoveAsync(key); await RemoveAndPublishAsync(key); } public async Task RemoveAsync(CacheOptionEntry entry) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); await _redisStore.RemoveAsync(entry.Key); await RemoveAndPublishAsync(entry.Key); } public void Set<T>(string key, T data, int cacheSeconds = 60) { Check.NotNullOrEmpty(key, nameof(key)); _redisStore.Set(key, data, cacheSeconds); UpdateAndPublish(key, data, cacheSeconds); } public void Set<T>(CacheOptionEntry entry, T data) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); _redisStore.Set(entry.Key, data); UpdateAndPublish(entry, data); } public async Task SetAsync<T>(string key, T data, int cacheSeconds = 60) { Check.NotNullOrEmpty(key, nameof(key)); await _redisStore.SetAsync(key, data, cacheSeconds); await UpdateAndPublishAsync(key, data, cacheSeconds); } public async Task SetAsync<T>(CacheOptionEntry entry, T data) { Check.NotNull(entry, nameof(entry)); Check.NotNullOrEmpty(entry.Key, nameof(entry.Key)); await _redisStore.SetAsync(entry, data); await UpdateAndPublishAsync(entry, data); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Reflection; namespace Crowdin.Api.Protocol { internal static class RequestBodySerializer { public static IEnumerable<(String, Object)> Serialize(Object body) { Type bodyType = body.GetType(); return bodyType .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(ConsiderProperty) .Select(property => (property.ResolveMemberName().ToLower(), GetPropertyValue(body, property))) .SelectMany(ExpandMember); } private static IEnumerable<(String, Object)> ExpandMember(this (String Name, Object Value) member) { return member.Value .ExpandValue() .Select(item => (member.Name + item.Name, item.Value)); } private static IEnumerable<(String Name, Object Value)> ExpandValue(this Object value) { switch (value) { case null: return Enumerable.Empty<(String, Object)>(); case Boolean typedValue: return typedValue.Expand(); case DateTime typedValue: return typedValue.Expand(); case Enum typedValue: return typedValue.Expand(); case StringDictionary typedValue: return typedValue.Expand(); case IDictionary typedValue: return typedValue.Expand(); case IEnumerable typedValue when !(typedValue is String): return typedValue.Expand(); case var obj when (Type.GetTypeCode(obj.GetType()) == TypeCode.Object) && !(obj is FileInfo): return obj.Expand(); default: return new[] { (String.Empty, value) }; } } private static IEnumerable<(String, Object)> Expand(this Boolean value) { yield return (String.Empty, value ? 1 : 0); } private static IEnumerable<(String, Object)> Expand(this DateTime value) { yield return (String.Empty, value.ToString("s")); } private static IEnumerable<(String, Object)> Expand(this Enum value) { Type enumType = value.GetType(); var asNumber = (AsNumberAttribute)Attribute.GetCustomAttribute(enumType, typeof(AsNumberAttribute)); Object resolvedValue; if (asNumber != null) { resolvedValue = Convert.ChangeType(value, Enum.GetUnderlyingType(enumType)); } else { FieldInfo enumField = enumType.GetField(value.ToString()); resolvedValue = ResolveMemberName(enumField).ToLower(); } yield return (String.Empty, resolvedValue); } private static IEnumerable<(String, Object)> Expand(this StringDictionary value) { return value.Keys.Cast<String>() .Select(key => ($"[{key}]", (Object)value[key])) .SelectMany(ExpandMember); } private static IEnumerable<(String, Object)> Expand(this IDictionary value) { return value.Keys.Cast<Object>() .Select(key => ($"[{key}]", value[key])) .SelectMany(ExpandMember); } private static IEnumerable<(String, Object)> Expand(this IEnumerable value) { return value.Cast<Object>() .Select((item, index) => ($"[{index}]", item)) .SelectMany(ExpandMember); } private static IEnumerable<(String, Object)> Expand(this Object value) { Type type = value.GetType(); return type .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(ConsiderProperty) .Select(property => ($"[{property.ResolveMemberName().ToLower()}]", property.GetValue(value))) .SelectMany(ExpandMember); } private static Boolean ConsiderProperty(this PropertyInfo property) { if (!property.CanRead) { return false; } var attribute = (IgnoreAttribute) Attribute.GetCustomAttribute(property, typeof(IgnoreAttribute)); return attribute == null; } private static String ResolveMemberName(this MemberInfo member) { var attribute = (PropertyAttribute) Attribute.GetCustomAttribute(member, typeof(PropertyAttribute)); return attribute?.Name ?? member.Name; } private static Object GetPropertyValue(Object obj, PropertyInfo property) { var required = (RequiredAttribute) Attribute.GetCustomAttribute(property, typeof(RequiredAttribute)); Object value = property.GetValue(obj); if (required == null) { return value; } return value ?? throw new ArgumentException("Value is required.", property.Name); } } }
namespace Bitmex.Client.Websocket.Responses.Instruments { public enum InstrumentMarkMethod { Undefined, FairPrice, LastPrice } }
using System; using System.Collections.Generic; using System.Linq; using Bieb.Domain.Entities; namespace Bieb.Web.Localization { public static class EnumDisplayer { public static string GetResource(LibraryStatus status) { return BiebResources.Enums.ResourceManager.GetString("LibraryStatus" + GetEnumId(status)); } public static string GetResource(Gender gender) { return BiebResources.Enums.ResourceManager.GetString("Gender" + GetEnumId(gender)); } public static string GetResource(Role role) { return BiebResources.Enums.ResourceManager.GetString("Role" + GetEnumId(role)); } private static object GetEnumId(Enum status) { return Convert.ChangeType(status, status.GetTypeCode()); } } }
using Messages.App.Models; using Messages.Data; using Messages.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Messages.App.Controllers { [Route("api/[controller]")] [ApiController] public class MessagesController : Controller { private readonly MessagesDbContext context; public MessagesController(MessagesDbContext context) { this.context = context; } [HttpPost(Name = "Create")] [Route("Create")] public async Task<ActionResult> Create(MessagesCreateInputModel inputModel) { Message message = new Message { Content = inputModel.Content, User = inputModel.User, CreatedOn = DateTime.UtcNow }; await this.context.Messages.AddAsync(message); await this.context.SaveChangesAsync(); return this.Ok(); } [HttpGet(Name = "All")] [Route("All")] public async Task<ActionResult<IEnumerable<Message>>> AllOrderedByCreatedOnAscending() { return this.context .Messages .OrderBy(m => m.CreatedOn) .ToList(); } } }
using System; using CMS.Base.Web.UI; using CMS.DataEngine; using CMS.DocumentEngine; using CMS.FormEngine; using CMS.Helpers; using CMS.LicenseProvider; using CMS.Localization; using CMS.Membership; using CMS.PortalEngine; using CMS.SiteProvider; using CMS.UIControls; public partial class CMSModules_Blogs_Controls_NewBlog : CMSUserControl { #region "Variables" private string mBlogParentPath = ""; private string mBlogSideColumnText = ""; private Guid mBlogTeaser = Guid.Empty; private int mBlogOpenCommentsFor = -1; // blog is opened "Always" by default private string mBlogSendCommentsToEmail = ""; private bool mBlogAllowAnonymousComments = true; private string mBlogModerators = ""; #endregion #region "Public properties" /// <summary> /// Path in the content tree where new blog should be created. /// </summary> public string BlogParentPath { get { return mBlogParentPath; } set { mBlogParentPath = value; } } /// <summary> /// Indicates if user should be redirected to the blog after the blog it is created. /// </summary> public bool RedirectToNewBlog { get; set; } /// <summary> /// Blog side column text. /// </summary> public string BlogSideColumnText { get { return mBlogSideColumnText; } set { mBlogSideColumnText = value; } } /// <summary> /// Blog teaser. /// </summary> public Guid BlogTeaser { get { return mBlogTeaser; } set { mBlogTeaser = value; } } /// <summary> /// Email address where new comments should be sent. /// </summary> public string BlogSendCommentsToEmail { get { return mBlogSendCommentsToEmail; } set { mBlogSendCommentsToEmail = value; } } /// <summary> /// Indicates if blog comments are opened (0 - not opened, -1 - always opened, X - number of days the comments are opened after the post is published). /// </summary> public int BlogOpenCommentsFor { get { return mBlogOpenCommentsFor; } set { mBlogOpenCommentsFor = value; } } /// <summary> /// Indicates if new comments require to be moderated before publishing. /// </summary> public bool BlogModerateComments { get; set; } /// <summary> /// Indicates if security control should be used when inserting new comment. /// </summary> public bool BlogUseCAPTCHAForComments { get; set; } /// <summary> /// Indicates anonymous users can insert comments. /// </summary> public bool BlogAllowAnonymousComments { get { return mBlogAllowAnonymousComments; } set { mBlogAllowAnonymousComments = value; } } /// <summary> /// Users which are allowed to moderate blog comments. Format [username1];[username2];... /// </summary> public string BlogModerators { get { return mBlogModerators; } set { mBlogModerators = value; } } /// <summary> /// Page template which is applied to a new blog. If not specified, page template of the parent document is applied. /// </summary> public string NewBlogTemplate { get; set; } /// <summary> /// Indicates whether permissions are to be checked. /// </summary> public bool CheckPermissions { get; set; } #endregion protected void Page_Load(object sender, EventArgs e) { if (StopProcessing) { Visible = false; } else { // Initialize controls lblName.Text = GetString("Blogs.NewBlog.Name"); lblDescription.Text = GetString("Blogs.NewBlog.Description"); btnOk.Text = GetString("General.OK"); rfvName.ErrorMessage = GetString("Blogs.NewBlog.NameEmpty"); btnOk.Click += btnOk_Click; } } private void btnOk_Click(object sender, EventArgs e) { // Validate all required data for new blog string errorMessage = ValidateData(); if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Blogs, ObjectActionEnum.Insert)) { errorMessage = GetString("cmsdesk.bloglicenselimits"); } // Get current user var user = MembershipContext.AuthenticatedUser; if (errorMessage == "") { // Get parent node for new blog TreeProvider tree = new TreeProvider(user); TreeNode parent = tree.SelectSingleNode(SiteContext.CurrentSiteName, BlogParentPath.TrimEnd('%'), TreeProvider.ALL_CULTURES); if (parent != null) { DataClassInfo blogClass = DataClassInfoProvider.GetDataClassInfo("CMS.Blog"); if (blogClass == null) { return; } // Check if blog is allowed in selected location if (!DocumentHelper.IsDocumentTypeAllowed(parent, blogClass.ClassID)) { lblError.Visible = true; lblError.Text = GetString("Content.ChildClassNotAllowed"); return; } if (!CheckPermissions || user.IsAuthorizedToCreateNewDocument(parent, "cms.blog")) { // Check if blog description allows empty value FormInfo formInfo = new FormInfo(blogClass.ClassFormDefinition); FormFieldInfo fieldInfo = formInfo.GetFormField("BlogDescription"); if ((fieldInfo != null) && !fieldInfo.AllowEmpty && String.IsNullOrWhiteSpace(txtDescription.Text)) { lblError.Visible = true; lblError.Text = GetString("blogs.newblog.descriptionempty"); return; } bool useParentNodeGroupID = tree.UseParentNodeGroupID; TreeNode blogNode; try { // Reflect group document tree.UseParentNodeGroupID = true; // Initialize and create new blog node blogNode = TreeNode.New("cms.blog", tree); blogNode.SetValue("BlogName", txtName.Text.Trim()); blogNode.SetValue("BlogDescription", txtDescription.Text.Trim()); blogNode.SetValue("BlogAllowAnonymousComments", BlogAllowAnonymousComments); blogNode.SetValue("BlogModerateComments", BlogModerateComments); blogNode.SetValue("BlogOpenCommentsFor", BlogOpenCommentsFor); blogNode.SetValue("BlogSendCommentsToEmail", BlogSendCommentsToEmail); blogNode.SetValue("BlogSideColumnText", BlogSideColumnText); blogNode.SetValue("BlogUseCAPTCHAForComments", BlogUseCAPTCHAForComments); blogNode.SetValue("BlogModerators", BlogModerators); if (BlogTeaser == Guid.Empty) { blogNode.SetValue("BlogTeaser", null); } else { blogNode.SetValue("BlogTeaser", BlogTeaser); } blogNode.SetValue("NodeOwner", user.UserID); if (NewBlogTemplate != null) { // Set the default page template if (NewBlogTemplate == "") { blogNode.SetDefaultPageTemplateID(blogClass.ClassDefaultPageTemplateID); } else { // Set the selected template PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(NewBlogTemplate); if (pti != null) { blogNode.NodeTemplateForAllCultures = true; blogNode.NodeTemplateID = pti.PageTemplateId; } } } blogNode.DocumentName = txtName.Text.Trim(); blogNode.DocumentCulture = LocalizationContext.PreferredCultureCode; DocumentHelper.InsertDocument(blogNode, parent, tree); } finally { tree.UseParentNodeGroupID = useParentNodeGroupID; } if (RedirectToNewBlog) { // Redirect to the new blog URLHelper.Redirect(UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(blogNode))); } else { // Display info message lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); } } else { // Not authorized to create blog errorMessage = GetString("blogs.notallowedtocreate"); } } else { // Parent node was not found errorMessage = GetString("Blogs.NewBlog.PathNotFound"); } } if (errorMessage == "") { return; } // Display error message lblError.Visible = true; lblError.Text = errorMessage; } /// <summary> /// Validates form data and returns error message if some error occurs. /// </summary> private string ValidateData() { if (txtName.Text.Trim() == "") { // Blog name is empty return rfvName.ErrorMessage; } if (BlogParentPath.TrimEnd('%') == "") { // Path where blog should be created is empty return GetString("Blogs.NewBlog.PathEmpty"); } if (MembershipContext.AuthenticatedUser.IsPublic()) { // Anonymous user is not allowed to create blog return GetString("Blogs.NewBlog.AnonymousUser"); } return ""; } }
using MimeDetective.Engine; using MimeDetective.Storage; using System; using System.Collections.Immutable; using System.Linq; namespace MimeDetective { public class MimeTypeToFileExtensionLookup { public ImmutableDictionary<string, ImmutableArray<FileExtensionMatch>> Values { get; } public string? TryGetValue(string MimeType) { var ret = default(string?); if (TryGetValues(MimeType).FirstOrDefault() is { } V1) { ret = V1.Extension; } return ret; } public ImmutableArray<FileExtensionMatch> TryGetValues(string MimeType) { var ret = ImmutableArray<FileExtensionMatch>.Empty; if (Values.TryGetValue(MimeType, out var tret)) { ret = tret; } return ret; } internal MimeTypeToFileExtensionLookup(ImmutableArray<Definition> Definitions) { this.Values = ( from x1 in Definitions let mimetype = x1.File.MimeType?.ToLower() where !string.IsNullOrWhiteSpace(mimetype) group x1 by mimetype into G1 let FileExtensions = ( from x2 in G1 from y2 in x2.File.Extensions let extension = y2.ToLower() where !string.IsNullOrWhiteSpace(extension) group x2 by extension into G2 let Matches = G2.Select(x => new DefinitionMatch(x)).ToImmutableArray() let v2 = new FileExtensionMatch() { Extension = G2.Key, Matches = Matches, Points = Matches.Length } orderby v2.Points descending select v2 ).ToImmutableArray() select new { G1.Key, FileExtensions } ).ToImmutableDictionary(x => x.Key, x => x.FileExtensions, StringComparer.InvariantCultureIgnoreCase); } } }
 @{ ViewBag.Title = "ViewStatistic"; } <h2>ViewStatistic</h2>
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Softuni.Community.Data.Models; namespace Softuni.Community.Data.EntityConfigurations { internal class QuestionsTagsConfig : IEntityTypeConfiguration<QuestionsTags> { public void Configure(EntityTypeBuilder<QuestionsTags> builder) { builder .HasKey(x => new { x.TagId, x.QuestionId }); //builder // .HasOne(x => x.Question) // .WithMany(x => x.Tags) // .OnDelete(DeleteBehavior.Restrict); } } }
namespace APIMocker { using System.Collections.Generic; using System.IO; public static class FileScanner { public static Dictionary<string, string> ScanFromMockLibrary() { string currentpath = Directory.GetCurrentDirectory(); string mocklibraryPath = Path.Join(currentpath, "MockLibrary"); return ScanFromDirectory(mocklibraryPath); } public static Dictionary<string, string> ScanFromDirectory(string mockLibraryPath) { var datasets = new Dictionary<string, string>(); foreach (string file in Directory.EnumerateFiles(mockLibraryPath, "*.json")) { string content = File.ReadAllText(file); string filename = Path.GetFileName(file); string key = filename.Replace(".json", ""); datasets.Add(key, content); } return datasets; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace SwmSuite.Data.BusinessObjects { /// <summary> /// Enumerator defining all months. /// </summary> [Serializable] [XmlType( Namespace = "SwmSuite_v1" )] public enum Months { /// <summary> /// January (01). /// </summary> January, /// <summary> /// February (02). /// </summary> February, /// <summary> /// March (03). /// </summary> March, /// <summary> /// April (04). /// </summary> April, /// <summary> /// May (05). /// </summary> May, /// <summary> /// June (06). /// </summary> June, /// <summary> /// July (07). /// </summary> July, /// <summary> /// August (08). /// </summary> August, /// <summary> /// September (09). /// </summary> September, /// <summary> /// October (10). /// </summary> October, /// <summary> /// November (11). /// </summary> November, /// <summary> /// December (12). /// </summary> December } }
 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template and will be re-created if deleted // with default implementation. // </auto-generated> //------------------------------------------------------------------------------ using AppInterfaces.Infrastructure; using System.Data.Entity; namespace RepositoryInfrastructure { /// <summary> /// MyProject implementation of Unit of Work /// </summary> public sealed partial class AppUnitOfWork : UnitOfWork<DbContext>, IAppUnitOfWork { /// <summary> /// BookRepository holder /// </summary> // private MyProject.DB.Repository.BookRepository _bookRepository; /// <summary> /// Gets the BookRepository repository. /// </summary> /// <value> /// The BookRepository repository. /// </value> //MyProject.Interface.Repository.IBookRepository IMyProjectUnitOfWork.BookRepository //{ // get // { // return _bookRepository = // _bookRepository ?? new MyProject.DB.Repository.BookRepository(Context); // } //} } }
using System; using System.Runtime.InteropServices; using static Win32DotNet.Kernel32; using static Win32DotNet.User32; namespace HelloWorld { public static class Program { public static void Main(string[] args) { IntPtr hInstance = GetModuleHandle(null); WNDCLASSEX wc = new WNDCLASSEX { cbSize = (uint)Marshal.SizeOf(typeof(WNDCLASSEX)), style = 0, lpfnWndProc = WindowProc, cbClsExtra = 0, cbWndExtra = 0, hInstance = hInstance, hIcon = LoadIcon(IntPtr.Zero, IDI_APPLICATION), hCursor = LoadCursor(IntPtr.Zero, IDC_ARROW), hbrBackground = (IntPtr)(COLOR_WINDOW + 1), lpszMenuName = null, lpszClassName = typeof(Program).FullName, hIconSm = LoadIcon(IntPtr.Zero, IDI_APPLICATION) }; var windowClass = RegisterClassEx(ref wc); if (windowClass == 0) throw new InvalidOperationException($"RegisterClassEx failed."); var hWnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, typeof(Program).FullName, "Hello World!", WS_MINIMIZEBOX | WS_SYSMENU | WS_OVERLAPPED | WS_CAPTION, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, IntPtr.Zero, IntPtr.Zero, hInstance, IntPtr.Zero); if (hWnd == IntPtr.Zero) throw new InvalidOperationException($"CreateWindowEx failed."); ShowWindow(hWnd, SW_SHOWNORMAL); while (GetMessage(out var message, IntPtr.Zero, 0, 0)) { TranslateMessage(ref message); DispatchMessage(ref message); } } // This ensures the delegate will not be garbage collected as long as the program is running. public static WndProc WindowProc = _WindowProc; private static IntPtr _WindowProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { switch (msg) { case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return IntPtr.Zero; } } }
using Microsoft.AspNetCore.Authorization; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; namespace Easy.Endpoints.TestService.Endpoints.Auth { [Authorize] public class UserInfoEndpoint : IEndpoint { public Task<AuthRequest> HandleAsync(ClaimsPrincipal user, CancellationToken cancellationToken) { return Task.FromResult(FromPrincipal(user)); } private static AuthRequest FromPrincipal(ClaimsPrincipal user) { var name = user.Identity.Name; var roles = user.Claims.Where(r => r.Type == AuthService.RoleClaimType).Select(s => s.Value).ToArray(); return new AuthRequest { Roles = roles, Username = name }; } } }
namespace OwnID.Extensibility.Flow.Contracts { public class AddConnectionRequest : GetStatusRequest { public string Payload { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace ArangoDBNetStandard.DocumentApi.Models { /// <summary> /// Options used when calling ArangoDB PUT document endpoint /// to replace multiple document. /// </summary> public class PutDocumentsQuery { /// <summary> /// Whether to wait until the new documents have been synced to disk. /// </summary> public bool? WaitForSync { get; set; } /// <summary> /// By default, or if this is set to true, the _rev attributes in /// the given documents are ignored. If this is set to false, then /// any _rev attribute given in a body document is taken as a /// precondition. The document is only replaced if the current revision /// is the one specified. /// </summary> public bool? IgnoreRevs { get; set; } /// <summary> /// Whether to return the complete previous revision of the changed /// documents in the result. /// </summary> public bool? ReturnOld { get; set; } /// <summary> /// Whether to return the complete new revision of the changed /// documents in the result. /// </summary> public bool? ReturnNew { get; set; } /// <summary> /// If set to true, an empty object will be returned as response. /// No meta-data will be returned for the created document. /// This option can be used to save some network traffic. /// </summary> public bool? Silent { get; set; } /// <summary> /// Get the set of options in a format suited to a URL query string. /// </summary> /// <returns></returns> internal string ToQueryString() { List<string> query = new List<string>(); if (WaitForSync != null) { query.Add("waitForSync=" + WaitForSync.ToString().ToLower()); } if (ReturnNew != null) { query.Add("returnNew=" + ReturnNew.ToString().ToLower()); } if (ReturnOld != null) { query.Add("returnOld=" + ReturnOld.ToString().ToLower()); } if (IgnoreRevs != null) { query.Add("ignoreRevs=" + IgnoreRevs.ToString().ToLower()); } if (Silent != null) { query.Add("silent=" + Silent.ToString().ToLower()); } return string.Join("&", query); } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; namespace Global.Input { public delegate void RaycastCallback(RaycastHit hit); public class Raycaster { private Dictionary<int, List<RaycastCallback>> _callbacksDict = new Dictionary<int, List<RaycastCallback>>(); private Vector2 _pointer; private Camera _cam; private float _maxRaycastDistance = 100f; public Raycaster() { if (InputManager.IsReady) { InputManager.ActionMaps.Player.UpdatePointer.performed += UpdatePointer; } } public void AddListener(int layer, RaycastCallback callback) { if (!_callbacksDict.ContainsKey(layer)) _callbacksDict[layer] = new List<RaycastCallback>(); if (_callbacksDict[layer].Contains(callback)) Debug.LogWarningFormat("{0} is already registered at index {1}", callback, layer); else _callbacksDict[layer].Add(callback); } public void RemoveListener(int layer, RaycastCallback callback) { if (!_callbacksDict.ContainsKey(layer)) return; var cbs = _callbacksDict[layer]; if (!cbs.Contains(callback)) return; cbs.Remove(callback); if (cbs.Count == 0) _callbacksDict.Remove(layer); } private void UpdatePointer(InputAction.CallbackContext context) { _pointer = context.ReadValue<Vector2>(); } public void Raycast() { var ray = GetCamera().ScreenPointToRay(_pointer); var layersMask = 0; var layers = _callbacksDict.Keys; foreach (var layer in layers) layersMask |= 1 << layer; if (Physics.Raycast(ray, out var hit, _maxRaycastDistance, layersMask)) { var hitLayer = hit.collider.gameObject.layer; if (_callbacksDict.TryGetValue(hitLayer, out var callbacks)) { foreach (var raycastCallback in callbacks) raycastCallback(hit); } } } private Camera GetCamera() { if(_cam == null) _cam = Camera.main; return _cam; } } }
using LottoGame.Games; using LottoGame.ConcreteGames; using System; namespace LottoGame { public class SALotto : GameFactory { readonly IDivisionFactory divisionFactory; public SALotto (IDivisionFactory divisionFactory) { this.divisionFactory = divisionFactory; } public override string GetDivision(int result) { switch (result) { case 1: return divisionFactory.Division1(); case 2: return divisionFactory.Division2(); case 3: return divisionFactory.Division3(); case 4: return divisionFactory.Division4(); case 5: return divisionFactory.Division5(); case 6: return divisionFactory.Division6(); case 7: return divisionFactory.Division7(); case 8: return divisionFactory.Division8(); default: return divisionFactory.NoDivision(); } } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace SchulIT.IccImport.Models { internal class FreeLessonTimespansData { [JsonProperty("free_lessons")] public IList<FreeLessonTimespanData> FreeLessons { get; set; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace Microsoft.Data.Entity.Design.EntityDesigner.View { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Data.Entity.Design.Model; using Microsoft.Data.Entity.Design.Model.Entity; using Microsoft.Data.Entity.Design.Model.Mapping; using Microsoft.Data.Entity.Design.UI.Views.MappingDetails; using Microsoft.Data.Entity.Design.VisualStudio; using Microsoft.Data.Entity.Design.VisualStudio.Package; using Microsoft.VisualStudio.Modeling.Diagrams; using Microsoft.VisualStudio.Modeling.Shell; /// <summary> /// This class will set the focus on the "most-appropriate" DSL node for the give EFObject in the diagrams. /// The diagram selection works as follow: /// 1. Find the match dsl node match in the current active designer view. /// 2. If no match is found, find it in any opened designer doc views. /// </summary> internal static class DSLDesignerNavigationHelper { [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame.Show")] internal static void NavigateTo(EFObject efobject) { if (efobject.RuntimeModelRoot() == null) { // nothing to navigate to, so just return; return; } if (efobject.RuntimeModelRoot() is StorageEntityModel) { // s-space object, so just return; return; } var selectionService = Services.DslMonitorSelectionService; Debug.Assert(selectionService != null, "Could not retrieve IMonitorSelectionService from Escher package."); var foundDSLElementMatchInDiagram = false; if (selectionService != null) { var singleDiagramDocView = selectionService.CurrentDocumentView as SingleDiagramDocView; if (singleDiagramDocView != null) { foundDSLElementMatchInDiagram = NavigateToDSLNodeInDiagram( singleDiagramDocView.Diagram as EntityDesignerDiagram, efobject); if (foundDSLElementMatchInDiagram) { // The code below is added to ensure that the right doc-view is shown and activated. singleDiagramDocView.Frame.Show(); return; } } } // Retrieves the doc data for the efobject. var docdata = VSHelpers.GetDocData(Services.ServiceProvider, efobject.Uri.LocalPath) as ModelingDocData; Debug.Assert(docdata != null, "Could not find get doc data for artifact with URI:" + efobject.Uri.LocalPath); if (docdata != null) { foreach (var docView in docdata.DocViews) { var singleDiagramDocView = docView as SingleDiagramDocView; Debug.Assert( singleDiagramDocView != null, "Why the doc view is not type of SingleDiagramDocView? Actual type:" + docView.GetType().Name); if (docView != null) { foundDSLElementMatchInDiagram = NavigateToDSLNodeInDiagram( singleDiagramDocView.Diagram as EntityDesignerDiagram, efobject); if (foundDSLElementMatchInDiagram) { // The code below is added to ensure that the right doc-view is shown and activated. singleDiagramDocView.Frame.Show(); return; } } } } } /// <summary> /// This class will set the focus on the "most-appropriate" DSL node for the given EFObject and DSL Diagram. It is assumed that the /// EFObject is either a C-Space node, or an M-space node. /// </summary> internal static bool NavigateToDSLNodeInDiagram(EntityDesignerDiagram diagram, EFObject efobject) { var foundDSLElementMatchInDiagram = false; var context = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(efobject.Artifact.Uri); // find the model parent (if this is a c-space object) var cModel = efobject.GetParentOfType(typeof(ConceptualEntityModel)) as ConceptualEntityModel; // by default, we assume that this our c-space object var cspaceEFObject = efobject; EFObject mspaceEFObject = null; if (cModel == null) { var mModel = efobject.GetParentOfType(typeof(MappingModel)) as MappingModel; Debug.Assert(mModel != null, "efobject is neither in c-space or s-space"); // if this is a mapping node, then we want to find the closest corresponding c-space node // to which this mapping node is mapped, and set the focus on that. cspaceEFObject = GetCSpaceEFObjectForMSpaceEFObject(efobject); mspaceEFObject = efobject; } // navigate to the shape in the DSL designer var diagramItemCollection = new DiagramItemCollection(); RetrieveDiagramItemCollectionForEFObject(diagram, cspaceEFObject, diagramItemCollection); if (diagram != null && diagramItemCollection.Count > 0) { diagram.Show(); if (diagram.ActiveDiagramView != null) { diagram.ActiveDiagramView.Focus(); diagram.ActiveDiagramView.Selection.Set(diagramItemCollection); diagram.EnsureSelectionVisible(); } else { // If no active view exists, do the following: // - Set the selection on the first associated views (if any). // - Set InitialSelectionDIagramItemSelectionProperty to prevent the first EntityTypeShape to be selected (default behavior) // This case can happen when the diagram is not initialized or is not fully rendered. diagram.InitialDiagramItemSelection = diagramItemCollection; if (diagram.ClientViews != null && diagram.ClientViews.Count > 0) { foreach (DiagramClientView clientView in diagram.ClientViews) { clientView.Selection.Set(diagramItemCollection); clientView.Selection.EnsureVisible(DiagramClientView.EnsureVisiblePreferences.ScrollIntoViewCenter); break; } } } foundDSLElementMatchInDiagram = true; } if (mspaceEFObject != null) // navigate to the item in the mapping screen (if we are doing MSL items) { var mappingDetailsInfo = context.Items.GetValue<MappingDetailsInfo>(); if (mappingDetailsInfo.MappingDetailsWindow != null) { mappingDetailsInfo.MappingDetailsWindow.NavigateTo(mspaceEFObject); } } return foundDSLElementMatchInDiagram; } /// <summary> /// Given a efobject in m-space (ie, it is defined in the mapping section of the edmx file), find the /// closest object in the c-space (ie, defined in the conceptual schema). We do this by looking /// for binding objects of the current node bound to something in c-space. If there is no such object, we /// recursively call this on efobject's parent. /// </summary> /// <param name="efobject"></param> /// <returns></returns> private static EFObject GetCSpaceEFObjectForMSpaceEFObject(EFObject mspaceEFObject) { EFObject cspaceEFObject = null; var o = mspaceEFObject; // see if this m-space object has a parent of an association set mapping. var asm = mspaceEFObject.GetParentOfType(typeof(AssociationSetMapping)) as AssociationSetMapping; if (asm != null) { var associationSet = asm.Name.Target; if (associationSet != null) { var association = associationSet.Association.Target; if (association != null) { Debug.Assert( association.RuntimeModelRoot() is ConceptualEntityModel, "Expected association to be in C-space, but it is not!"); return association; } } } // see if this is a node that requires the function view in the mapping pane var mfm = mspaceEFObject.GetParentOfType(typeof(ModificationFunctionMapping)) as ModificationFunctionMapping; var context = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(mspaceEFObject.Artifact.Uri); var mappingDetailsInfo = context.Items.GetValue<MappingDetailsInfo>(); if (mfm != null) { mappingDetailsInfo.EntityMappingMode = EntityMappingModes.Functions; } else { mappingDetailsInfo.EntityMappingMode = EntityMappingModes.Tables; } // default case, walk up the model looking for node that has a binding bound to something in c-space. while (cspaceEFObject == null && o != null) { var binding = o as ItemBinding; var container = o as EFContainer; if (binding != null) { // see if this binding is bound to something in c-space cspaceEFObject = GetCSpaceObjectFromBinding(binding); } else if (container != null) { // see if any direct children are bindings bound to something in c-space foreach (var child in container.Children) { // check every binding to see if it is bound to seomthing in cspace var b = child as ItemBinding; if (b != null) { cspaceEFObject = GetCSpaceObjectFromBinding(b); if (cspaceEFObject != null) { // break out of the for loop break; } } } } if (cspaceEFObject == null) { o = o.Parent; } } return cspaceEFObject; } /// <summary> /// Given an item binding, return the target of the binding if it is mapped to something in c-space /// </summary> /// <param name="itemBinding"></param> /// <returns></returns> private static EFObject GetCSpaceObjectFromBinding(ItemBinding itemBinding) { foreach (EFObject dep in itemBinding.ResolvedTargets) { var cModel = dep.RuntimeModelRoot() as ConceptualEntityModel; if (cModel != null) { return dep; } } return null; } /// <summary> /// Given an EFObject, return collection of DiagramItems for it. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void RetrieveDiagramItemCollectionForEFObject( EntityDesignerDiagram diagram, EFObject efobject, DiagramItemCollection diagramItemCollection) { if (efobject == null) { return; } var cModel = efobject.RuntimeModelRoot() as ConceptualEntityModel; if (cModel == null) { // this either isn't a c-space object, or it is the ConceptualEntityModel node, so just return null return; } // if this is a child element of the association, return the diagram item for the association if (!(efobject is Association)) { var association = efobject.GetParentOfType(typeof(Association)) as Association; if (association != null) { RetrieveDiagramItemCollectionForEFObject(diagram, association, diagramItemCollection); return; } } if (efobject is Association) { var shapeElement = GetDesignerShapeElementForEFObject(diagram, efobject); if (shapeElement != null) { diagramItemCollection.Add(new DiagramItem(shapeElement)); return; } } else if (efobject is NavigationProperty) { var np = efobject as NavigationProperty; var shapeElement = GetDesignerShapeElementForEFObject(diagram, np.Parent); var entityTypeShape = shapeElement as EntityTypeShape; if (entityTypeShape != null) { // get the view model navigation property var vmNavProp = diagram.ModelElement.ModelXRef.GetExisting(np) as ViewModel.NavigationProperty; // try to create the DiagramItem from this if (vmNavProp != null) { var index = entityTypeShape.NavigationCompartment.Items.IndexOf(vmNavProp); if (index >= 0) { diagramItemCollection.Add( new DiagramItem( entityTypeShape.NavigationCompartment, entityTypeShape.NavigationCompartment.ListField, new ListItemSubField(index))); return; } } } } else if (efobject is Property) { var prop = efobject as Property; if (prop.IsComplexTypeProperty) { // complex type properties are not supported in the designer return; } var shapeElement = GetDesignerShapeElementForEFObject(diagram, prop.Parent); var entityTypeShape = shapeElement as EntityTypeShape; if (entityTypeShape != null) { // get the view model property var vmProp = diagram.ModelElement.ModelXRef.GetExisting(prop) as ViewModel.Property; if (vmProp != null) { var index = entityTypeShape.PropertiesCompartment.Items.IndexOf(vmProp); if (index >= 0) { diagramItemCollection.Add( new DiagramItem( entityTypeShape.PropertiesCompartment, entityTypeShape.PropertiesCompartment.ListField, new ListItemSubField(index))); return; } } } } else if (efobject is EntityType) { var shapeElement = GetDesignerShapeElementForEFObject(diagram, efobject); if (shapeElement != null) { diagramItemCollection.Add(new DiagramItem(shapeElement)); return; } } else if (efobject is EntitySet) { var es = efobject as EntitySet; foreach (var entityType in es.GetEntityTypesInTheSet()) { if (entityType != null) { RetrieveDiagramItemCollectionForEFObject(diagram, entityType, diagramItemCollection); } } return; } else if (efobject is AssociationSet) { // return a diagram item for the association var associationSet = efobject as AssociationSet; var association = associationSet.Association.Target; if (association != null) { RetrieveDiagramItemCollectionForEFObject(diagram, association, diagramItemCollection); return; } } else if (efobject is AssociationSetEnd) { var associationSetEnd = efobject as AssociationSetEnd; var end = associationSetEnd.Role.Target; if (end != null) { RetrieveDiagramItemCollectionForEFObject(diagram, end, diagramItemCollection); return; } else { var es = associationSetEnd.EntitySet.Target; if (es != null) { RetrieveDiagramItemCollectionForEFObject(diagram, es, diagramItemCollection); return; } } } else if (efobject is PropertyRef) { var pref = efobject as PropertyRef; if (pref.Name.Target != null) { RetrieveDiagramItemCollectionForEFObject(diagram, pref.Name.Target, diagramItemCollection); return; } } else if (efobject is PropertyRefContainer) { var prefContainer = efobject as PropertyRefContainer; // just use the first entry in the list. foreach (var pref in prefContainer.PropertyRefs) { RetrieveDiagramItemCollectionForEFObject(diagram, pref, diagramItemCollection); return; } } else if (efobject is EFAttribute) { // this is an EFAttribute node, so get the DiagramItem for the parent RetrieveDiagramItemCollectionForEFObject(diagram, efobject.Parent, diagramItemCollection); return; } else if (efobject is ConceptualEntityModel) { // nothing in the DSL surface to map to, so return null return; } else if (efobject is ConceptualEntityContainer) { // nothing in the DSL surface to map to, so return null return; } else if (efobject is FunctionImport) { // nothing in the DSL surface to map to, so return null return; } else { Debug.Fail("unexpected type of efobject. type = " + efobject.GetType()); if (efobject.Parent != null) { RetrieveDiagramItemCollectionForEFObject(diagram, efobject.Parent, diagramItemCollection); } } } /// <summary> /// This method will return a DSL ShapeElement for the given efobject. If the given efobject doesn't map to a designer shape, /// then this will look for a designer shape for the object's parent. /// If no designer shape can be found, this will return null. /// </summary> /// <param name="efobject"></param> /// <returns></returns> private static ShapeElement GetDesignerShapeElementForEFObject(EntityDesignerDiagram diagram, EFObject efobject) { ShapeElement shapeElement = null; while (shapeElement == null && efobject != null && ((efobject is ConceptualEntityModel) == false)) { var dslElement = diagram.ModelElement.ModelXRef.GetExisting(efobject); shapeElement = dslElement as ShapeElement; if (shapeElement == null && dslElement != null) { var shapes = PresentationViewsSubject.GetPresentation(dslElement); // just select the first shape for this item if (shapes != null && shapes.Count > 0) { shapeElement = shapes[0] as ShapeElement; } } // walk up the EFObject tree until we find a node that has a ShapeElement. if (shapeElement == null) { efobject = efobject.Parent; } } return shapeElement; } } }
namespace CrackSharp.Core.Des.BruteForce { public interface IBruteForceParams { int MaxTextLength { get; } string Characters { get; } } }
namespace Microsoft.eCommerceOnContainers.Services.Basket.API.Services; public class IdentityService : IIdentityService { #region Fields private IHttpContextAccessor _context; #endregion #region Ctor public IdentityService(IHttpContextAccessor context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } #endregion #region Methods public string GetUserIdentity() { return _context.HttpContext.User.FindFirst("sub").Value; } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Automation; namespace ThunderbirdTray.WindowStateHooks { public class UIAutomation : IWindowStateHook { public event EventHandler<WindowStateChangeEventArgs> WindowStateChange; private AutomationElement automationElement; public bool Hook(IntPtr windowHandle) { if (automationElement == null) { automationElement = AutomationElement.FromHandle(windowHandle); Automation.AddAutomationPropertyChangedEventHandler( automationElement, TreeScope.Element, OnVisualStateChange, new AutomationProperty[] { WindowPattern.WindowVisualStateProperty }); return true; } return false; } private void OnVisualStateChange(object sender, AutomationPropertyChangedEventArgs e) { WindowVisualState visualState = WindowVisualState.Normal; try { visualState = (WindowVisualState)e.NewValue; } catch (InvalidCastException) { // ignore } WindowStateChange?.Invoke(this, new WindowStateChangeEventArgs((WindowState)visualState)); } public bool Unhook() { if (automationElement != null) { Automation.RemoveAutomationPropertyChangedEventHandler(automationElement, OnVisualStateChange); automationElement = null; return true; } return false; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using Microsoft.PowerFx.Core.App.ErrorContainers; using Microsoft.PowerFx.Core.Binding; using Microsoft.PowerFx.Core.Entities; using Microsoft.PowerFx.Core.Errors; using Microsoft.PowerFx.Core.Functions; using Microsoft.PowerFx.Core.Functions.Delegation; using Microsoft.PowerFx.Core.Functions.Delegation.DelegationMetadata; using Microsoft.PowerFx.Core.Localization; using Microsoft.PowerFx.Core.Syntax.Nodes; using Microsoft.PowerFx.Core.Types; using Microsoft.PowerFx.Core.Utils; namespace Microsoft.PowerFx.Core.Texl.Builtins { // Filter(source:*, predicate1:b, [predicate2:b, ...]) // Corresponding DAX function: Filter internal sealed class FilterFunction : FilterFunctionBase { public override bool RequiresErrorContext { get { return true; } } public FilterFunction() : base("Filter", TexlStrings.AboutFilter, FunctionCategories.Table, DType.EmptyTable, -2, 2, int.MaxValue, DType.EmptyTable) { ScopeInfo = new FunctionScopeInfo(this, acceptsLiteralPredicates: false); } public override bool SupportsParamCoercion { get { return true; } } public override IEnumerable<TexlStrings.StringGetter[]> GetSignatures() { // Enumerate just the base overloads (the first 3 possibilities). yield return new[] { TexlStrings.FilterArg1, TexlStrings.FilterArg2 }; yield return new[] { TexlStrings.FilterArg1, TexlStrings.FilterArg2, TexlStrings.FilterArg2 }; yield return new[] { TexlStrings.FilterArg1, TexlStrings.FilterArg2, TexlStrings.FilterArg2, TexlStrings.FilterArg2 }; } public override IEnumerable<TexlStrings.StringGetter[]> GetSignatures(int arity) { if (arity > 2) return GetGenericSignatures(arity, TexlStrings.FilterArg1, TexlStrings.FilterArg2); return base.GetSignatures(arity); } public override bool CheckInvocation(TexlBinding binding, TexlNode[] args, DType[] argTypes, IErrorContainer errors, out DType returnType, out Dictionary<TexlNode, DType> nodeToCoercedTypeMap) { Contracts.AssertValue(args); Contracts.AssertValue(argTypes); Contracts.Assert(args.Length == argTypes.Length); Contracts.AssertValue(errors); nodeToCoercedTypeMap = null; int viewCount = 0; bool fArgsValid = base.CheckInvocation(args, argTypes, errors, out returnType, out nodeToCoercedTypeMap); var dataSourceVisitor = new ViewFilterDataSourceVisitor(binding); // Ensure that all the args starting at index 1 are booleans or view for (int i = 1; i < args.Length; i++) { if (argTypes[i].Kind == DKind.ViewValue) { if (++viewCount > 1) { // Only one view expected errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrOnlyOneViewExpected); fArgsValid = false; continue; } // Use the visitor to get the datasource info and if a view was already used anywhere in the node tree. args[0].Accept(dataSourceVisitor); var dataSourceInfo = dataSourceVisitor.cdsDataSourceInfo; if (dataSourceVisitor.ContainsViewFilter) { // Only one view expected errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrOnlyOneViewExpected); fArgsValid = false; continue; } if (dataSourceInfo != null) { // Verify the view belongs to the same datasource var viewInfo = argTypes[i].ViewInfo.VerifyValue(); if (viewInfo.RelatedEntityName != dataSourceInfo.Name) { errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrViewFromCurrentTableExpected, dataSourceInfo.Name); fArgsValid = false; } } else { errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrBooleanExpected); fArgsValid = false; } continue; } else if (DType.Boolean.Accepts(argTypes[i])) { continue; } else if (!argTypes[i].CoercesTo(DType.Boolean)) { errors.EnsureError(DocumentErrorSeverity.Severe, args[i], TexlStrings.ErrBooleanExpected); fArgsValid = false; continue; } } // The first Texl function arg determines the cursor type, the scope type for the lambda params, and the return type. DType typeScope; fArgsValid &= ScopeInfo.CheckInput(args[0], argTypes[0], errors, out typeScope); Contracts.Assert(typeScope.IsRecord); returnType = typeScope.ToTable(); return fArgsValid; } // Verifies if given callnode can be server delegatable or not. // Return true if // - Arg0 is delegatable ds and supports filter operation. // - All predicates to filter are delegatable if each firstname/binary/unary/dottedname/call node in each predicate satisfies delegation criteria set by delegation strategy for each node. public override bool IsServerDelegatable(CallNode callNode, TexlBinding binding) { Contracts.AssertValue(callNode); Contracts.AssertValue(binding); if (!CheckArgsCount(callNode, binding)) return false; IExternalDataSource dataSource; FilterOpMetadata metadata = null; IDelegationMetadata delegationMetadata = null; if (TryGetEntityMetadata(callNode, binding, out delegationMetadata)) { if (!binding.Document.Properties.EnabledFeatures.IsEnhancedDelegationEnabled || !TryGetValidDataSourceForDelegation(callNode, binding, DelegationCapability.ArrayLookup, out _)) { SuggestDelegationHint(callNode, binding); return false; } metadata = delegationMetadata.FilterDelegationMetadata.VerifyValue(); } else { if (!TryGetValidDataSourceForDelegation(callNode, binding, FunctionDelegationCapability, out dataSource)) return false; metadata = dataSource.DelegationMetadata.FilterDelegationMetadata; } TexlNode[] args = callNode.Args.Children.VerifyValue(); // Validate for each predicate node. for (int i = 1; i < args.Length; i++) { if (!IsValidDelegatableFilterPredicateNode(args[i], binding, metadata)) return false; } return true; } public override bool IsEcsExcemptedLambda(int index) { // All lambdas in filter can be excluded from ECS. return IsLambdaParam(index); } } }
using Newtonsoft.Json; namespace Lexicala.NET.Response.Search { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public class SearchResponse { [JsonProperty("n_results")] public int NResults { get; set; } [JsonProperty("page_number")] public int PageNumber { get; set; } [JsonProperty("results_per_page")] public int ResultsPerPage { get; set; } [JsonProperty("n_pages")] public int NPages { get; set; } [JsonProperty("available_n_pages")] public int AvailableNPages { get; set; } [JsonProperty("results")] public Result[] Results { get; set; } = { }; public ResponseMetadata Metadata { get; set; } = new ResponseMetadata(); } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT license. using System; using System.Collections; using UnityEngine; namespace Microsoft.AppCenter.Unity.Internal.Utils { #if UNITY_WSA_10_0 using WSAApplication = UnityEngine.WSA.Application; #endif public class UnityCoroutineHelper : MonoBehaviour { private static UnityCoroutineHelper Instance { get { var instance = FindObjectOfType<UnityCoroutineHelper>(); if (instance == null) { var gameObject = new GameObject("App Center Helper") { hideFlags = HideFlags.HideAndDontSave }; DontDestroyOnLoad(gameObject); instance = gameObject.AddComponent<UnityCoroutineHelper>(); } return instance; } } #if UNITY_WSA_10_0 public static void StartCoroutine(Func<IEnumerator> coroutine) { if (WSAApplication.RunningOnAppThread()) { Instance.StartCoroutine(coroutine()); } else { WSAApplication.InvokeOnAppThread(() => { Instance.StartCoroutine(coroutine()); }, false); } } #else public static void StartCoroutine(Func<IEnumerator> coroutine) { Instance.StartCoroutine(coroutine()); } #endif } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Microsoft.Extensions.Localization; namespace OrchardCore.Autoroute.Models { public static class AutoroutePartExtensions { public static IEnumerable<ValidationResult> ValidatePathFieldValue(this AutoroutePart autoroute, IStringLocalizer S) { if (autoroute.Path == "/") { yield return new ValidationResult(S["Your permalink can't be set to the homepage, please use the homepage option instead."], new[] { nameof(autoroute.Path) }); } if (HasInvalidCharacters(autoroute.Path)) { var invalidCharactersForMessage = string.Join(", ", AutoroutePart.InvalidCharactersForPath.Select(c => $"\"{c}\"")); yield return new ValidationResult(S["Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", invalidCharactersForMessage], new[] { nameof(autoroute.Path) }); } if (autoroute.Path?.Length > AutoroutePart.MaxPathLength) { yield return new ValidationResult(S["Your permalink is too long. The permalink can only be up to {0} characters.", AutoroutePart.MaxPathLength], new[] { nameof(autoroute.Path) }); } } private static bool HasInvalidCharacters(string path) { // IndexOfAny performs culture-insensitive and case-sensitive search. if (path?.IndexOfAny(AutoroutePart.InvalidCharactersForPath) > -1) { return true; } if (path?.IndexOf(' ', StringComparison.Ordinal) > -1) { return true; } if (path?.IndexOf("//", StringComparison.Ordinal) > -1) { return true; } return false; } } }
namespace AgileObjects.ReadableExpressions.UnitTests.Translations.Reflection { using System; using Common; using ReadableExpressions.Translations.Reflection; #if !NET35 using Xunit; #else using Fact = NUnit.Framework.TestAttribute; [NUnit.Framework.TestFixture] #endif public class WhenWorkingWithClrTypes { [Fact] public void ShouldReturnTheSingletonObjectType() { ClrTypeWrapper.For(typeof(object)).ShouldBeSameAs(ClrTypeWrapper.Object); } [Fact] public void ShouldReturnTheSingletonValueTypeType() { ClrTypeWrapper.For(typeof(ValueType)).ShouldBeSameAs(ClrTypeWrapper.ValueType); } [Fact] public void ShouldReturnTheSingletonAttributeType() { ClrTypeWrapper.For<Attribute>().ShouldBeSameAs(ClrTypeWrapper.Attribute); } [Fact] public void ShouldReturnTheSingletonStringType() { ClrTypeWrapper.For<string>().ShouldBeSameAs(ClrTypeWrapper.String); } [Fact] public void ShouldReturnTheSingletonVoidType() { ClrTypeWrapper.For(typeof(void)).ShouldBeSameAs(ClrTypeWrapper.Void); } [Fact] public void ShouldReturnTheSingletonEnumType() { ClrTypeWrapper.For<Enum>().ShouldBeSameAs(ClrTypeWrapper.Enum); } } }
namespace RazorViewCompress { internal class RazorCompressorFactory : ICompressorFactory { public BaseCompressor CreateCompressor() { return new RazorCompressor(); } } }
@{ ViewData["Title"] = "Globbing Page"; } @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @section footerContent { <!-- File wildcard --> <script asp-src-include="/js/dist/dashboard*.js"></script> <!-- RazorClassLib folder wildcard --> <script asp-src-include="/_content/RazorPagesClassLibrary/**/file.js"></script> <!-- RazorClassLib deep wildcard --> <script asp-src-include="/**/*.js"></script> <!-- RazorClassLib Exclude local --> <script asp-src-exclude="/js/dist/*.js" asp-src-include="**/*.js"></script> <!-- local Exclude lib--> <script asp-src-exclude="/_content/**/*.js" asp-src-include="**/*.js"></script> } Globbing
 using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using MsgReader.Outlook; namespace MsgReaderTests { [TestClass] public class RemoveAttachmentTests { [TestMethod] public void RemoveAttachments() { using (var inputStream = File.OpenRead(Path.Combine("SampleFiles", "EmailWith2Attachments.msg"))) using (var inputMessage = new Storage.Message(inputStream, FileAccess.ReadWrite)) { var attachments = inputMessage.Attachments.ToList(); foreach (var attachment in attachments) inputMessage.DeleteAttachment(attachment); using (var outputStream = new MemoryStream()) { inputMessage.Save(outputStream); using (var outputMessage = new Storage.Message(outputStream)) { var count = outputMessage.Attachments.Count; Assert.IsTrue(count == 0); } } } } } }
using Newtonsoft.Json; namespace CmlLib.Core.Auth { public class MSession { public MSession() { } public MSession(string username, string accesstoken, string uuid) { Username = username; AccessToken = accesstoken; UUID = uuid; } [JsonProperty("username")] public string Username { get; internal set; } [JsonProperty("session")] public string AccessToken { get; internal set; } [JsonProperty("uuid")] public string UUID { get; internal set; } [JsonProperty("clientToken")] public string ClientToken { get; internal set; } public bool CheckIsValid() { return !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(AccessToken) && !string.IsNullOrEmpty(UUID); } public static MSession GetOfflineSession(string username) { var login = new MSession(); login.Username = username; login.AccessToken = "access_token"; login.UUID = "user_uuid"; login.ClientToken = null; return login; } } }
/********************************************************************** * Copyright © 2009, 2010, 2011, 2012 OPC Foundation, Inc. * * The source code and all binaries built with the OPC .NET 3.0 source * code are subject to the terms of the Express Interface Public * License (Xi-PL). See http://www.opcfoundation.org/License/Xi-PL/ * * The source code may be distributed from an OPC member company in * its original or modified form to its customers and to any others who * have software that needs to interoperate with the OPC member's OPC * .NET 3.0 products. No other redistribution is permitted. * * You must not remove this notice, or any other, from this software. * *********************************************************************/ using System; using System.Collections.Generic; using System.ServiceModel; using Xi.Contracts.Data; namespace Xi.Contracts { /// <summary> /// This interface is composed of methods used to retrieve /// data, alarms, and events and their histories from the /// server. /// </summary> [ServiceContract(Namespace = "urn:xi/contracts")] public interface IRead { /// <summary> /// <para>This method is used to read the values of one or more /// data objects in a list. It is also used as a keep-alive for the /// read endpoint by setting the listId parameter to 0. In this case, /// null is returned immediately. </para> /// </summary> /// <param name="contextId"> /// The context identifier. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects to be read. /// Null if this is a keep-alive. /// </param> /// <param name="serverAliases"> /// The server aliases of the data objects to read. When this value is null all elements /// of the list are to be read. /// </param> /// <returns> /// <para>The list of requested values. Each value in this list is identified /// by its client alias. If the server alias for a data object to read /// was not found, an ErrorInfo object will be returned that contains /// the server alias instead of a value, status, and timestamp. </para> /// <para>Returns null if this is a keep-alive.</para> /// </returns> [OperationContract, FaultContract(typeof(XiFault))] DataValueArraysWithAlias ReadData(string contextId, uint listId, List<uint> serverAliases); /// <summary> /// <para>This method is used to read the historical values that fall between /// a start and end time for one or more data objects within a specific data /// journal list.</para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose /// historical values are to be read. /// </param> /// <param name="firstTimeStamp"> /// The filter that specifies the first or beginning (of returned list) /// timestamp for values to be returned. Valid operands include the /// Timestamp (UTC) and OpcHdaTimestampStr constants defined by the /// FilterOperand class. The FilterOperand Operator is used to /// determine if the returned data should include data values /// the occur exactly at the first or second time stamp. If the equals /// operator is specified then values that occur at the first and second /// time stamp will be included in the sample set. Any other operator /// will not include first or second time stamped values. /// </param> /// <param name="secondTimeStamp"> /// The filter that specifies the second or ending (of returned list) /// timestamp for values to be returned. Valid operands include the /// Timestamp (UTC) and OpcHdaTimestampStr constants defined by the /// FilterOperand class. The FilterOperand Operator is not used. /// </param> /// <param name="numValuesPerAlias"> /// The maximum number of JournalDataReturnValues to be returned per alias. /// </param> /// <param name="serverAliases"> /// The list of server aliases for the data objects whose historical /// values are to be read. When this value is null all elements of the list are to be read. /// </param> /// <returns> /// The list of requested historical values, or the reason they could not /// be read. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] JournalDataValues[] ReadJournalDataForTimeInterval(string contextId, uint listId, FilterCriterion firstTimeStamp, FilterCriterion secondTimeStamp, uint numValuesPerAlias, List<uint> serverAliases); /// <summary> /// <para>This method is used to return an in-sequence subset of the /// historical values selected by the last IRead_ReadJournalDataForTimeInterval() /// call issued by the client on this client context. This method is used /// when the number of values to be returned for one or more aliases /// exceeds the number specified by the numValuesPerAlias parameter of the /// IRead_ReadJournalDataForTimeInterval() method. </para> /// <para>The client may have to reissue this call multiple times to /// receive all historical values for all aliases. The client may specify /// a new numValuesPerAlias with each call to this method to better optimize /// its performance. </para> /// <para>The server is responsible for maintaining the list of requested /// aliases for which values remain, and the timestamp of the last value /// sent to the client for each alias. </para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose /// historical values are to be returned. /// </param> /// <param name="numValuesPerAlias"> /// The maximum number of data sample values to be returned per alias. /// </param> /// <returns> /// The next set of remaining values for each alias. If the number of values /// returned for any one alias is less than numValuesPerAlias, then there are /// no additional values to return to the client for that alias. If, however, /// the number returned for any alias is equal to numValuesPerAlias, then the /// client should issue a ReadJournalDataNext() to retrieve any remaining values. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] JournalDataValues[] ReadJournalDataNext(string contextId, uint listId, uint numValuesPerAlias); /// <summary> /// <para>This method is used to read the historical values at specific times for /// one or more data objects within a specific data journal list. If no entry exists /// at the specified time in the data journal for an object, the server creates an /// interpolated value for that time and includes it in the response as though it /// actually existed in the journal.</para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose historical /// values are to be read. /// </param> /// <param name="timestamps"> /// Identifies the timestamps of historical values to be returned for each /// of the requested data objects. /// </param> /// <param name="serverAliases"> /// The list of server aliases for the data objects whose historical /// values are to be read. When this value is null all elements of the list are to be read. /// </param> /// <returns> /// The list of requested historical values, or the reason they could not /// be read. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] JournalDataValues[] ReadJournalDataAtSpecificTimes(string contextId, uint listId, List<DateTime> timestamps, List<uint> serverAliases); /// <summary> /// <para>This method is used to read changed historical values for one /// or more data objects within a specific data journal list. Changed historical /// values are those that were entered into the journal and then changed (corrected) /// by an operator or other user.</para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose historical /// values are to be read. /// </param> /// <param name="firstTimestamp"> /// The filter that specifies the inclusive earliest (oldest) timestamp /// for values to be returned. Valid operands include the Timestamp and /// OpcHdaTimestampStr constants defined by the FilterOperand class. /// </param> /// <param name="secondTimestamp"> /// The filter that specifies the inclusive newest (most recent) timestamp /// for values to be returned. Valid operands include the Timestamp and /// OpcHdaTimestampStr constants defined by the FilterOperand class. /// </param> /// <param name="serverAliases"> /// The list of server aliases for the data objects whose historical /// values are to be read. When this value is null all elements of the /// list are to be read. /// </param> /// <param name="numValuesPerAlias"> /// The maximum number of JournalDataChangedValues to be returned per alias. /// </param> /// <returns> /// The list of requested historical values, or the reason they could not /// be read. If, however, the number returned for any alias is equal to /// numValuesPerAlias, then the client should issue a ReadJournalDataChangesNext() /// to retrieve any remaining values. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] JournalDataChangedValues[] ReadJournalDataChanges(string contextId, uint listId, FilterCriterion firstTimestamp, FilterCriterion secondTimestamp, uint numValuesPerAlias, List<uint> serverAliases); /// <summary> /// <para>This method is used to return an in-sequence subset of the /// historical values selected by the last IRead_ReadJournalDataChanges() /// call issued by the client on this client context. This method is used /// when the number of values to be returned for one or more aliases /// exceeds the number specified by the numValuesPerAlias parameter of the /// IRead_ReadJournalDataChanges() method. </para> /// <para>The client may have to reissue this call multiple times to /// receive all historical values for all aliases. The client may specify /// a new numValuesPerAlias with each call to this method to better optimize /// its performance. </para> /// <para>The server is responsible for maintaining the list of requested /// aliases for which values remain, and the timestamp of the last value /// sent to the client for each alias. </para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose /// historical values are to be returned. /// </param> /// <param name="numValuesPerAlias"> /// The maximum number of JournalDataChangedValues to be returned per alias. /// </param> /// <returns> /// The next set of remaining values for each alias. If the number of values /// returned for any one alias is less than numValuesPerAlias, then there are /// no additional values to return to the client for that alias. If, however, /// the number returned for any alias is equal to numValuesPerAlias, then the /// client should issue a ReadJournalDataChangesNext() to retrieve any remaining /// values. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] JournalDataChangedValues[] ReadJournalDataChangesNext(string contextId, uint listId, uint numValuesPerAlias); /// <summary> /// <para>This method is used to read calculated historical values (e.g. averages or /// interpolations) for one or more data objects within a specific data journal list. /// The time-range used to select the historical values is specified by the client. /// Additionally, the client specifies a calculation period that divides that time /// range into periods. The server calculates a return value for each of these periods.</para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose historical /// values are to be read. /// </param> /// <param name="firstTimestamp"> /// The filter that specifies the inclusive earliest (oldest) timestamp /// for values to be returned. Valid operands include the Timestamp and /// OpcHdaTimestampStr constants defined by the FilterOperand class. /// </param> /// <param name="secondTimestamp"> /// The filter that specifies the inclusive newest (most recent) timestamp /// for values to be returned. Valid operands include the Timestamp and /// OpcHdaTimestampStr constants defined by the FilterOperand class. /// </param> /// <param name="calculationPeriod"> /// The time span used to divide the specified time range into individual periods for /// which return values are calculated. The specified calculation is performed on the /// set of historical values of a data object that fall within each period. /// </param> /// <param name="serverAliasesAndCalculations"> /// The list of server aliases for the data objects whose historical /// values are to be calculated, and the calculation to perform for each. /// </param> /// <returns> /// The set of calculated values. There is one value for each calculation period within /// the specified time range for each specific data object. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] JournalDataValues[] ReadCalculatedJournalData(string contextId, uint listId, FilterCriterion firstTimestamp, FilterCriterion secondTimestamp, TimeSpan calculationPeriod, List<AliasAndCalculation> serverAliasesAndCalculations); /// <summary> /// This method reads the properties associated with a historized data object. /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose property /// values are to be read. /// </param> /// <param name="firstTimestamp"> /// The filter that specifies the inclusive earliest (oldest) timestamp /// for values to be returned. Valid operands include the Timestamp and /// OpcHdaTimestampStr constants defined by the FilterOperand class. /// </param> /// <param name="secondTimestamp"> /// The filter that specifies the inclusive newest (most recent) timestamp /// for values to be returned. Valid operands include the Timestamp and /// OpcHdaTimestampStr constants defined by the FilterOperand class. /// </param> /// <param name="serverAlias"> /// The server alias of the data object whose property values are to be read. /// </param> /// <param name="propertiesToRead"> /// The TypeIds of the properties to read. Each property is identified by /// its property type. /// </param> /// <returns> /// The array of requested property values. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] JournalDataPropertyValue[] ReadJournalDataProperties(string contextId, uint listId, FilterCriterion firstTimestamp, FilterCriterion secondTimestamp, uint serverAlias, List<TypeId> propertiesToRead); /// <summary> /// This method is used to read an event list or a subset of it /// using a filter. /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains alarms and events /// to be read. /// </param> /// <param name="filterSet"> /// The set of filters used to select alarms and events /// to be read. /// </param> /// <returns> /// The list of selected alarms and events. /// Null if no alarms or events were selected. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] EventMessage[] ReadEvents(string contextId, uint listId, FilterSet filterSet); /// <summary> /// <para>This method is used to read a list of historical alarms or /// events. This method only accesses historical events rather /// than also accessing historical data as does the MMS ReadJournal /// service. This is because the return value is strongly typed /// to historical alarms and event messages and not to historical /// data.</para> /// <para>To simplify implementation, clients must first define a /// historical alarm/event list that the server will prepare to access. </para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains historical alarms and /// events that are to be read. /// </param> /// <param name="firstTimestamp"> /// The filter that specifies the first or beginning (of returned list) /// timestamp for event messages to be returned. Valid operands include /// the Timestamp (UTC) constant defined by the FilterOperand class. /// </param> /// <param name="secondTimestamp"> /// The filter that specifies the second or ending (of returned list) /// timestamp for event messages to be returned. Valid operands include /// the Timestamp (UTC) constant defined by the FilterOperand class. /// </param> /// <param name="numEventMessages"> /// The maximum number of EventMessages to be returned. /// </param> /// <param name="filterSet"> /// The set of filters used to select historical alarms and events /// to be read. /// </param> /// <returns> /// The list of selected historical alarms and events. /// Or null if no alarms or events were selected. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] EventMessage[] ReadJournalEvents(string contextId, uint listId, FilterCriterion firstTimestamp, FilterCriterion secondTimestamp, uint numEventMessages, FilterSet filterSet); /// <summary> /// <para>This method is used to return an in-sequence subset of the /// historical events selected by the last ReadJournalEvents() /// call issued by the client on this client context. This method is used /// when the number of EventMessages to be returned exceeds the number specified /// by the numEventMessages parameter of the ReadJournalEvents() method. </para> /// <para>The client may have to reissue this call multiple times to /// receive all historical EventMessages selected by the initial call to /// ReadJournalEvents(). The client may specify a new numEventMessages with each /// call to this method to better optimize its performance. </para> /// </summary> /// <param name="contextId"> /// The context id. /// </param> /// <param name="listId"> /// The server identifier of the list that contains data objects whose /// historical events are to be returned. /// </param> /// <param name="numEventMessages"> /// The maximum number of EventMessages to be returned. /// </param> /// <returns> /// The selected EventMessages. If, however, the number returned is equal to /// numEventMessages, then the client should issue a ReadJournalEventsNext() /// to retrieve any remaining EventMessages. /// </returns> [OperationContract, FaultContract(typeof(XiFault))] EventMessage[] ReadJournalEventsNext(string contextId, uint listId, uint numEventMessages); } }
using System; using System.Text.Json.Serialization; namespace Ycode.AspNetCore.Mvc.GroupVersioning.Test.Models { public class BadRequestResponseModel { public class ErrorModel { [JsonPropertyName("code")] public string Code { get; set; } [JsonPropertyName("message")] public string Message { get; set; } } [JsonPropertyName("error")] public ErrorModel Error { get; set; } } }
using Ultraviolet.Core; using Ultraviolet.Input; using Ultraviolet.Presentation; using Ultraviolet.Presentation.Controls; using Ultraviolet.Presentation.Input; namespace UvDebug.UI.Screens { /// <summary> /// Represents the view model for <see cref="GameMenuScreen"/>. /// </summary> public sealed class GameMenuViewModel { /// <summary> /// Initializes a new instance of the <see cref="GameMenuViewModel"/> class. /// </summary> /// <param name="owner">The <see cref="GameMenuScreen"/> that owns this view model.</param> public GameMenuViewModel(GameMenuScreen owner) { Contract.Require(owner, nameof(owner)); this.owner = owner; } /// <summary> /// Handles the <see cref="View.OpenedEvent"/> attached event. /// </summary> /// <param name="dobj">The object that raised the event.</param> /// <param name="data">The routed event metadata for this event invocation.</param> public void HandleViewOpened(DependencyObject dobj, RoutedEventData data) { if (container != null) container.Focus(); } /// <summary> /// Handles the <see cref="Keyboard.KeyDownEvent"/> attached event for the view's topmost <see cref="Grid"/> instance. /// </summary> /// <param name="dobj">The object that raised the event.</param> /// <param name="device">The <see cref="KeyboardDevice"/> that raised the event.</param> /// <param name="key">The <see cref="Key"/> value that represents the key that was pressed.</param> /// <param name="modifiers">A <see cref="ModifierKeys"/> value indicating which of the key modifiers are currently active.</param> /// <param name="data">The routed event metadata for this event invocation.</param> public void HandleKeyDown(DependencyObject dobj, KeyboardDevice device, Key key, ModifierKeys modifiers, RoutedEventData data) { switch (key) { case Key.AppControlBack: { owner.Ultraviolet.Host.Exit(); data.Handled = true; } break; } } /// <summary> /// Handles the Click event for the "Start" button. /// </summary> public void Click_Start(DependencyObject element, RoutedEventData data) { var playScreen = owner.UIScreenService.Get<GamePlayScreen>(); owner.Ultraviolet.GetUI().GetScreens().CloseThenOpen(owner, playScreen); } /// <summary> /// Handles the Click event for the "Exit" button. /// </summary> public void Click_Exit(DependencyObject element, RoutedEventData data) { owner.Ultraviolet.Host.Exit(); } /// <summary> /// Gets the <see cref="GameMenuScreen"/> that owns the view model. /// </summary> public GameMenuScreen Owner { get { return owner; } } // Property values. private readonly GameMenuScreen owner; // Component references. private readonly Grid container = null; } }
// // MenuScene.cs // ProductName Ling // // Created by toshiki sakamoto on 2020.11.07 // using UnityEngine; using Cysharp.Threading.Tasks; using UniRx; using Ling.Common.Scene.Menu; using Zenject; using Ling.Common.Input; using UnityEngine.InputSystem; using System.Collections.Generic; using Ling.Common.Scene.Battle; namespace Ling.Scenes.Menu { /// <summary> /// Menu Scene /// </summary> public class MenuScene : Common.Scene.Base { #region 定数, class, enum #endregion #region public 変数 #endregion #region private 変数 [Inject] private IInputManager _inputManager; [SerializeField] private MenuModel _model = default; [SerializeField] private MenuView _view = default; [Header("メニューカテゴリコントロール")] [SerializeField] private Category.MenuCategoryBag _bagControl = default; [SerializeField] private Category.MenuCategoryEquip _equipControl = default; [SerializeField] private Category.MenuCategoryOther _otherControl = default; private List<Category.MenuCategoryBase> _categoryControls = new List<Category.MenuCategoryBase>(); #endregion #region プロパティ public override Common.Scene.SceneID SceneID => Common.Scene.SceneID.Menu; #endregion #region public, protected 関数 /// <summary> /// シーンが開始される時 /// </summary> public override void StartScene() { var menuArgument = Argument as MenuArgument; _model.SetArgument(menuArgument); // カテゴリに応じたクラスを生成する foreach (var data in _model.CategoryData) { SetupCategoryControl(data); } var viewParam = new MenuView.Param() { CategoryData = _model.CategoryData, }; _view.Setup(viewParam); // View上でカテゴリが変更された _view.SelectedIndex .Subscribe(index => { _model.SetSelectedCategoryIndex(index); //_view.SetCategoryData(_model.SelectedCategoryData); }).AddTo(this); // カテゴリが切り替わった時、カテゴリコントロール上も変化させる _model.SelectedCategoryData .AsObservable() .Subscribe(categoryData => { // Controlを変更させる ActivateCategoryControl(categoryData); }); // メニューボタンが押されたら閉じる var actionInput = _inputManager.Resolve<InputControls.IActionActions>(); actionInput.Controls.Action.Menu.performed += OnMenuPerformed; // 閉じるボタン _view.CloseButton.OnClickAsObservable() .Subscribe(_ => { // 自分をクローズする _sceneManager.CloseScene(this); }).AddTo(this); } /// <summary> /// StartScene後呼び出される /// </summary> public override void UpdateScene() { } /// <summary> /// シーン終了時 /// </summary> public override void StopScene() { var actionInput = _inputManager.Resolve<InputControls.IActionActions>(); actionInput.Controls.Action.Menu.performed -= OnMenuPerformed; } /// <summary> /// 正規手順でシーンが実行されたのではなく /// 直接起動された場合StartSceneよりも前に呼び出される /// </summary> public override UniTask QuickStartSceneAsync() { Argument = MenuArgument.CreateAtMenu(); return default(UniTask); } #endregion #region private 関数 private void OnMenuPerformed(InputAction.CallbackContext context) { // メニューボタンが押されたら閉じる CloseScene(); } /// <summary> /// カテゴリに応じたControlクラスのSetupを呼び出す /// </summary> private void SetupCategoryControl(MenuCategoryData categoryData) { switch (categoryData.Category) { case MenuDefine.Category.Bag: _bagControl.Setup(); _categoryControls.Add(_bagControl); // アイテムを使用した時 _bagControl.OnUseItem = itemEntity => UseItem(itemEntity); break; // 装備一覧 case MenuDefine.Category.Equip: _equipControl.Setup(); _categoryControls.Add(_equipControl); // 装備したことを伝える _equipControl.OnEquipped = entity => Equip(entity); break; // その他 case MenuDefine.Category.Other: _otherControl.Setup(); _categoryControls.Add(_otherControl); break; } } private void ActivateCategoryControl(MenuCategoryData categoryData) { InactiveAllCategory(); switch (categoryData.Category) { case MenuDefine.Category.Bag: _bagControl.Activate(); break; case MenuDefine.Category.Equip: _equipControl.Activate(); break; case MenuDefine.Category.Other: _otherControl.Activate(); break; } } private void InactiveAllCategory() { foreach (var control in _categoryControls) { control.gameObject.SetActive(false); } } /// <summary> /// アイテムを使用する /// </summary> private void UseItem(Common.Item.ItemEntity itemEntity) { Utility.Log.Print($"アイテムを使用する {itemEntity.ID}, {itemEntity.Name}"); // シーンを戻る var result = BattleResult.CreateAtItemUse(itemEntity); _sceneManager.CloseSceneAsync(this, result).Forget(); } /// <summary> /// 装備した /// </summary> private void Equip(UserData.Equipment.EquipmentUserData entity) { Utility.Log.Print($"アイテムを装備or外す {entity.ID}, {entity.Name}"); // シーンを戻る var result = BattleResult.CreateAtEquip(entity); _sceneManager.CloseSceneAsync(this, result).Forget(); } #endregion #region MonoBegaviour #endregion } }
#region References using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Speedy.Extensions; using Speedy.Sync; #endregion namespace Speedy.Website.Data.Entities { public class AddressEntity : SyncEntity<long> { #region Constructors [SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] public AddressEntity() { Accounts = new List<AccountEntity>(); LinkedAddresses = new List<AddressEntity>(); } #endregion #region Properties /// <summary> /// Represents the "primary" account for the address. /// </summary> public virtual AccountEntity Account { get; set; } /// <summary> /// The ID for the account. /// </summary> public int? AccountId { get; set; } /// <summary> /// The sync ID for the account. /// </summary> public Guid? AccountSyncId { get; set; } /// <summary> /// The people associated with this address. /// </summary> public virtual ICollection<AccountEntity> Accounts { get; set; } /// <summary> /// The city for the address. /// </summary> public string City { get; set; } /// <summary> /// Read only property /// </summary> public string FullAddress => $"{Line1}{Environment.NewLine}{City}, {State} {Postal}"; /// <inheritdoc /> public override long Id { get; set; } /// <summary> /// The line 1 for the address. /// </summary> public string Line1 { get; set; } /// <summary> /// The line 2 for the address. /// </summary> public string Line2 { get; set; } public virtual AddressEntity LinkedAddress { get; set; } public virtual ICollection<AddressEntity> LinkedAddresses { get; set; } public long? LinkedAddressId { get; set; } public Guid? LinkedAddressSyncId { get; set; } /// <summary> /// The postal for the address. /// </summary> public string Postal { get; set; } /// <summary> /// The state for the address. /// </summary> public string State { get; set; } #endregion #region Methods protected override HashSet<string> GetDefaultExclusionsForIncomingSync() { return base.GetDefaultExclusionsForIncomingSync() .Append(nameof(Accounts), nameof(LinkedAddress), nameof(LinkedAddressId), nameof(LinkedAddresses)); } protected override HashSet<string> GetDefaultExclusionsForOutgoingSync() { // Update defaults are the same as incoming sync defaults return GetDefaultExclusionsForIncomingSync(); } protected override HashSet<string> GetDefaultExclusionsForSyncUpdate() { // Update defaults are the same as incoming sync defaults plus some return base.GetDefaultExclusionsForSyncUpdate() .Append(GetDefaultExclusionsForIncomingSync()) .Append(nameof(IsDeleted)); } #endregion } }
using IntegrationTool.SDK.ConfigurationsBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IntegrationTool.Module.LoadFromSharepoint { public class LoadFromSharepointConfiguration : SourceConfiguration { public string ListName { get; set; } public string CamlQueryViewXml { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DumpMemory { public static class Log { [Flags] public enum LogLevel { Debugging, Errors, Warnings, Info } public static LogLevel Level { get; set; } static Log() { #if DEBUG Level = LogLevel.Info | LogLevel.Warnings | LogLevel.Errors | LogLevel.Debugging; #else Level = LogLevel.Info | LogLevel.Warnings | LogLevel.Errors; #endif } private static string _logName { get => $"{new StackTrace().GetFrames().Last().GetMethod().DeclaringType.Name}.cs"; } private static string _timeStamp { get => DateTime.Now.ToLongTimeString(); } public static void Info(string info) { if (Level.HasFlag(LogLevel.Info)) LogOutput(ConsoleColor.Green, info); } public static void Error(string error) { if (Level.HasFlag(LogLevel.Errors)) LogOutput(ConsoleColor.Red, error); } public static void Warning(string warning) { if (Level.HasFlag(LogLevel.Warnings)) LogOutput(ConsoleColor.Yellow, warning); } public static void Debug(string debug) { if (Level.HasFlag(LogLevel.Debugging)) LogOutput(ConsoleColor.Magenta, debug); } private static void LogOutput(ConsoleColor color, string log) { string logPreamble = $"[{_timeStamp}][{_logName}]: "; Console.ForegroundColor = color; Console.Write(logPreamble); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(log); } } }
using Photon.Pun; using TMPro; using UnityEngine; using UnityEngine.UI; namespace PUNLobby { public class NetworkStatusPanel : MonoBehaviour { [SerializeField] private TextMeshProUGUI _statusText; private void Update() { if (_statusText == null) return; _statusText.text = PhotonNetwork.NetworkClientState.ToString(); } } }
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Vod20170321.Models { public class GetAuditHistoryResponse : TeaModel { [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } [NameInMap("Status")] [Validation(Required=true)] public string Status { get; set; } [NameInMap("Total")] [Validation(Required=true)] public long Total { get; set; } [NameInMap("Histories")] [Validation(Required=true)] public List<GetAuditHistoryResponseHistories> Histories { get; set; } public class GetAuditHistoryResponseHistories : TeaModel { [NameInMap("CreationTime")] [Validation(Required=true)] public string CreationTime { get; set; } [NameInMap("Status")] [Validation(Required=true)] public string Status { get; set; } [NameInMap("Reason")] [Validation(Required=true)] public string Reason { get; set; } [NameInMap("Comment")] [Validation(Required=true)] public string Comment { get; set; } [NameInMap("Auditor")] [Validation(Required=true)] public string Auditor { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace kinectApp.Entities.Germs { /* A Default Germ, uses IEntity */ public interface IGerm : IEntity { int Id { get; } int Health { get; } bool IsDead { get; } } }
using Partiality.Modloader; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using UnityEngine; namespace PassiveEnemies { public class PassiveEnemies : PartialityMod { public static Script script; public PassiveEnemies() { this.ModID = "Passive Enemies"; this.Version = "1"; this.author = "Outlander"; } public override void OnEnable() { base.OnEnable(); GameObject go = new GameObject(); script = go.AddComponent<Script>(); script.StatCheck = this; script.Initialise(); } public override void OnDisable() { base.OnDisable(); } } }
namespace _07.CountEachNumberOccurence { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { var array = new int[] { 3, 4, 4, 2, 3, 3, 4, 3, 2 }; var dictionary = new Dictionary<int, int>(); //first decision foreach (var item in array) { if (!dictionary.ContainsKey(item)) { dictionary.Add(item, array.Count(x => x == item)); } } dictionary.ToList().ForEach(x => Console.WriteLine("{0} - {1} times", x.Key, x.Value)); //second decision Console.WriteLine(); array.GroupBy(n => n) .ToList() .ForEach(n => Console.WriteLine("{0} - {1} times", n.Key, n.Count())); } } }
using UnityEngine; using System.Collections; public class PingPongMotion : MonoBehaviour { //Original position private Vector3 OrigPos = Vector3.zero; //Axes to move on public Vector3 MoveAxes = Vector2.zero; //Speed public float Distance = 3f; void Start() { //Copy original position OrigPos = transform.position; } void Update() { //Update platform position with ping pong transform.position = OrigPos + MoveAxes * Mathf.PingPong(Time.time, Distance); } }
using System; namespace Examples.AutoRetry { public interface IWebPageService { [RetryAspect(RetriesCount = 3, DelayMs = 300)] string GetPageContent(string url); } public class WebPageService : IWebPageService { private static readonly double FailureRate = 0.6; private static readonly Random Random = new Random(); public string GetPageContent(string url) { if (Random.NextDouble() < FailureRate) throw new Exception("Network fail"); return url; } } }
// Copyright (c) KhooverSoft. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Khooversoft.Toolbox { /// <summary> /// Page result from stores /// </summary> /// <typeparam name="T">type of elements</typeparam> public class PageResult<T> { public PageResult(IEnumerable<T> items) { Verify.IsNotNull(nameof(items), items); Items = new List<T>(items); } public PageResult(string index, IEnumerable<T> items) : this(items) { Index = index; } public PageResult(IEnumerable<T> items, int skip, int limit, int count) : this(items) { Verify.Assert(skip >= 0, nameof(skip)); Verify.Assert(limit > 0, nameof(limit)); Verify.Assert(count >= 0, nameof(count)); Limit = limit; int nextIndex = skip + limit; Index = nextIndex < count ? nextIndex.ToString() : null; } public string Index { get; } public int Limit { get; } public IEnumerable<T> Items { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Baseline.Validate.Internal.Extensions; namespace Baseline.Validate { /// <summary> /// Base validator used by other validators in the library. Contains common functionality between them all. /// </summary> public abstract partial class BaseValidator<TToValidate> { private readonly ValidationResult _baggedValidationResult; private string ValidatingTypeName { get; } /// <summary> /// Initialises a new instance of the <see cref="BaseValidator{TToValidate}"/> class. /// </summary> protected BaseValidator() { ValidatingTypeName = GetType().ValidatorBaseType()!.GetGenericArguments().First().Name; _baggedValidationResult = new ValidationResult(ValidatingTypeName); } /// <summary> /// Returns a successful validation result with the relevant validating type name set. /// </summary> protected ValidationResult Success() { return new ValidationResult(ValidatingTypeName); } /// <summary> /// Returns the bagged validation result composed from any bagged failures. /// </summary> protected ValidationResult BaggedValidationResult() { return _baggedValidationResult; } private void InitialisePropertyErrorsIfRequired(string property) { if (_baggedValidationResult.Failures.ContainsKey(property)) { return; } _baggedValidationResult.Failures[property] = new List<string>(); } private static string GetNameOfField<TField>(Expression<Func<TToValidate, TField>> expression) { return expression.Body switch { MemberExpression memberExpression => memberExpression.Member.Name, UnaryExpression {Operand: MemberExpression m} => m.Member.Name, _ => string.Empty }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WCMS.Common { public class LogManager { public LogManager() { Loggers = new List<ILogger>(); } public LogManager(IEnumerable<ILogger> loggers) : this() { Loggers.AddRange(loggers); } public void AddFileLogger(string path) { Loggers.Add(new FileLogger(path)); } public void AddConsoleLogger() { Loggers.Add(new ConsoleLogger()); } public void Add(ILogger logger) { Loggers.Add(logger); } public List<ILogger> Loggers { get; set; } public void WriteLine() { WriteLine(string.Empty); } public void WriteLine(string format, params object[] args) { foreach (var logger in Loggers) { logger.WriteLine(format, args); } } } }
/* * Copyright 2019 Carnegie Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Pravala.RemoteLog.View { using System.Collections.Specialized; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Pravala.RemoteLog.Service; /// <summary> /// Interaction logic for LiveView window. /// </summary> public partial class LiveView: Window { #region Fields /// <summary> /// Stores the messages scroll viewer so that we can scroll it to the end. /// </summary> private ScrollViewer messagesScrollViewer; #endregion #region Constructor /// <summary> /// Initializes a new instance of the LiveView class. /// </summary> public LiveView() { this.InitializeComponent(); this.Loaded += this.OnLiveViewLoaded; this.Unloaded += this.OnLiveViewUnloaded; string title = "Remote Log: " + ServiceProvider.RemoteLink.HostName + ":" + ServiceProvider.RemoteLink.Port; this.Title = title; this.TitleTextBlock.Text = title; } #endregion #region Methods /// <summary> /// Listens for changes to messages so that we can keep the viewer scrolled to the bottom. /// </summary> /// <param name="sender">Event source.</param> /// <param name="e">Event arguments.</param> private void OnLiveViewLoaded ( object sender, RoutedEventArgs e ) { if ( VisualTreeHelper.GetChildrenCount ( this.MessagesListBox ) > 0 ) { Border border = ( Border ) VisualTreeHelper.GetChild ( this.MessagesListBox, 0 ); this.messagesScrollViewer = ( ScrollViewer ) VisualTreeHelper.GetChild ( border, 0 ); } ServiceProvider.ViewModel.Messages.CollectionChanged += this.OnMessagesCollectionChanged; } /// <summary> /// Stops listening for message changes. /// </summary> /// <param name="sender">Event source.</param> /// <param name="e">Event arguments.</param> private void OnLiveViewUnloaded ( object sender, RoutedEventArgs e ) { ServiceProvider.ViewModel.Messages.CollectionChanged -= this.OnMessagesCollectionChanged; } /// <summary> /// Scrolls to the bottom of the scroll viewer when a new message is added. /// </summary> /// <param name="sender">Event source.</param> /// <param name="e">Event arguments.</param> private void OnMessagesCollectionChanged ( object sender, NotifyCollectionChangedEventArgs e ) { if ( this.messagesScrollViewer != null ) { this.messagesScrollViewer.ScrollToBottom(); } } /// <summary> /// Stops the logger. /// </summary> /// <param name="sender">Event source.</param> /// <param name="e">Event arguments.</param> private void OnStopButtonClick ( object sender, RoutedEventArgs e ) { if ( ServiceProvider.OutputFile.IsOpen ) { // File open; close the connection (if present), then close the file if ( ServiceProvider.RemoteLink.IsRunning ) { ServiceProvider.RemoteLink.Stop(); } string filename = ServiceProvider.OutputFile.CloseFile(); this.Close(); ServiceProvider.ViewModel.Messages.Clear(); System.Windows.MessageBox.Show ( "Wrote log to: " + filename, "Logging complete" ); } } #endregion } }
public class Graft { public struct VertexPair { public int Source { get; } public int Target { get; } public VertexPair(int source, int target) { Source = source; Target = target; } } public VertexPair[] VertexPairs { get; } public int[] HiddenFaces { get; } public Graft(VertexPair[] vertexPairs, int[] hiddenFaces) { VertexPairs = vertexPairs; HiddenFaces = hiddenFaces; } }
using BluePointLilac.Controls; using BluePointLilac.Methods; using ContextMenuManager.Controls.Interfaces; using ContextMenuManager.Methods; using System; using System.Drawing; using System.IO; using System.Windows.Forms; using static ContextMenuManager.Methods.ObjectPath; namespace ContextMenuManager.Controls { class FoldSubItem : MyListItem { public FoldGroupItem FoldGroupItem { get; set; } public void Indent() { int w = 40.DpiZoom(); this.Controls["Image"].Left += w; this.Controls["Text"].Left += w; } } class FoldGroupItem : MyListItem, IBtnShowMenuItem { private bool isFold; public bool IsFold { get => isFold; set { if(isFold == value) return; isFold = value; FoldMe(value); } } public string GroupPath { get; set; } public PathType PathType { get; set; } public MenuButton BtnShowMenu { get; set; } readonly PictureButton btnFold; readonly PictureButton btnOpenPath; readonly ToolStripMenuItem tsiFoldAll = new ToolStripMenuItem(AppString.Menu.FoldAll); readonly ToolStripMenuItem tsiUnfoldAll = new ToolStripMenuItem(AppString.Menu.UnfoldAll); public FoldGroupItem(string groupPath, PathType pathType) { btnFold = new PictureButton(AppImage.Up); BtnShowMenu = new MenuButton(this); btnOpenPath = new PictureButton(AppImage.Open); if(pathType == PathType.File || pathType == PathType.Directory) { groupPath = Environment.ExpandEnvironmentVariables(groupPath); } string tip = null; Action openPath = null; switch(pathType) { case PathType.File: tip = AppString.Menu.FileLocation; this.Text = Path.GetFileNameWithoutExtension(groupPath); this.Image = ResourceIcon.GetExtensionIcon(groupPath).ToBitmap(); openPath = () => ExternalProgram.JumpExplorer(groupPath, AppConfig.OpenMoreExplorer); break; case PathType.Directory: tip = AppString.Menu.FileLocation; this.Text = Path.GetFileNameWithoutExtension(groupPath); this.Image = ResourceIcon.GetFolderIcon(groupPath).ToBitmap(); openPath = () => ExternalProgram.OpenDirectory(groupPath); break; case PathType.Registry: tip = AppString.Menu.RegistryLocation; openPath = () => ExternalProgram.JumpRegEdit(groupPath, null, AppConfig.OpenMoreRegedit); break; } this.PathType = pathType; this.GroupPath = groupPath; this.Font = new Font(this.Font, FontStyle.Bold); this.AddCtrs(new[] { btnFold, btnOpenPath }); this.ContextMenuStrip.Items.AddRange(new[] { tsiFoldAll, tsiUnfoldAll }); this.MouseDown += (sender, e) => { if(e.Button == MouseButtons.Left) Fold(); }; btnFold.MouseDown += (sender, e) => { Fold(); btnFold.Image = btnFold.BaseImage; }; tsiFoldAll.Click += (sender, e) => FoldAll(true); tsiUnfoldAll.Click += (sender, e) => FoldAll(false); btnOpenPath.MouseDown += (sender, e) => openPath.Invoke(); ToolTipBox.SetToolTip(btnOpenPath, tip); } public void SetVisibleWithSubItemCount() { foreach(Control ctr in this.Parent.Controls) { if(ctr is FoldSubItem item && item.FoldGroupItem == this) { this.Visible = true; return; } } this.Visible = false; } private void Fold() { this.Parent.SuspendLayout(); this.IsFold = !this.IsFold; this.Parent.ResumeLayout(); } private void FoldMe(bool isFold) { btnFold.BaseImage = isFold ? AppImage.Down : AppImage.Up; foreach(Control ctr in this.Parent?.Controls) { if(ctr is FoldSubItem item && item.FoldGroupItem == this) ctr.Visible = !isFold; } } private void FoldAll(bool isFold) { this.Parent.SuspendLayout(); foreach(Control ctr in this.Parent.Controls) { if(ctr is FoldGroupItem groupItem) groupItem.IsFold = isFold; } this.Parent.ResumeLayout(); } } }
using AutoMapper; using CookBook.Common.Enums; using System; namespace CookBook.DAL.Entities { public class IngredientAmountEntity : EntityBase { public double Amount { get; set; } public Unit Unit { get; set; } public Guid RecipeId { get; set; } public RecipeEntity Recipe { get; set; } public Guid IngredientId { get; set; } public IngredientEntity Ingredient { get; set; } } public class IngredientAmountEntityMapperProfile : Profile { public IngredientAmountEntityMapperProfile() { CreateMap<IngredientAmountEntity, IngredientAmountEntity>(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; namespace ZenGlue { public class ZMesh : IDisposable, MaterialMesh { [DllImport("zenglue", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr zg_mesh_init(IntPtr vdfs, string name); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern void zg_mesh_deinit(IntPtr mesh); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern uint zg_mesh_vertex_count(IntPtr mesh); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern ref float3 zg_mesh_vertex_position_get(IntPtr mesh, uint index); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern ref float3 zg_mesh_vertex_normal_get(IntPtr mesh, uint index); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern ref float2 zg_mesh_vertex_texcoord_get(IntPtr mesh, uint index); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern uint zg_mesh_submesh_count(IntPtr mesh); [DllImport("zenglue", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr zg_mesh_submesh_material_texture(IntPtr mesh, uint index); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern uint zg_mesh_submesh_material_color(IntPtr mesh, uint index); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern uint zg_mesh_submesh_element_count(IntPtr mesh, uint submesh); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern uint zg_mesh_submesh_element_get(IntPtr mesh, uint submesh, uint element); [DllImport("zenglue", CallingConvention = CallingConvention.Cdecl)] private static extern uint zg_mesh_vertexindex_get(IntPtr mesh, uint index); private IntPtr handle; public ZMesh(IntPtr nativeptr) { handle = nativeptr; } public ZMesh(VDFS vdfs, string name) { handle = zg_mesh_init(vdfs.NativeHandle(), name); } public uint vertexCount() { return zg_mesh_vertex_count(handle); } public Vector3[] vertexPositions() { var count = vertexCount(); var result = new Vector3[count]; for (uint i = 0; i < count; ++i) result[i] = zg_mesh_vertex_position_get(handle, i).toUnityAbsolute(); return result; } public Vector3[] vertexNormals() { var count = vertexCount(); var result = new Vector3[count]; for (uint i = 0; i < count; ++i) result[i] = zg_mesh_vertex_normal_get(handle, i).toUnityRelative(); return result; } public Vector2[] vertexUVs() { var count = vertexCount(); var result = new Vector2[count]; for (uint i = 0; i < count; ++i) result[i] = zg_mesh_vertex_texcoord_get(handle, i).toUnityRelative(); return result; } public uint submeshCount() { return zg_mesh_submesh_count(handle); } public uint submeshElementCount(uint index) { return zg_mesh_submesh_element_count(handle, index); } public int[] submeshElements(uint index) { var count = submeshElementCount(index); var elements = new int[count]; for (uint e = 0; e < count; e += 3) { elements[e] = (int)zg_mesh_submesh_element_get(handle, index, e); elements[e + 1] = (int)zg_mesh_submesh_element_get(handle, index, e + 2); elements[e + 2] = (int)zg_mesh_submesh_element_get(handle, index, e + 1); } return elements; } public string texture(uint index) { var tex_p = zg_mesh_submesh_material_texture(handle, index); return Marshal.PtrToStringAnsi(tex_p); } public Color color(uint index) { uint c = zg_mesh_submesh_material_color(handle, index); return Common.uintToColor(c); } public uint[] vertexIds() { var result = new uint[zg_mesh_vertex_count(handle)]; for (uint i = 0; i < result.Length; ++i) result[i] = zg_mesh_vertexindex_get(handle, i); return result; } public void Dispose() { zg_mesh_deinit(handle); } } }
using System; using System.Threading.Tasks; using ChainLink.ChainBuilders; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ChainLink.Tests { [TestClass] public class ProcessTests { [TestMethod] public async Task HelloWorldChain() { IChain chain = new Chain(configure => configure.GetResult<string, HelloWorldLink>()); await chain.RunAsync(); } [TestMethod] public async Task ChainLinkArgs() { IChain chain = new Chain(configure => configure.GetResult<string, ReturnArgumentLink>("Hello World")); await chain.RunAsync(); } [TestMethod] public async Task CreateMultiLinkChain() { IChain chain = new Chain( configure => { configure .GetResult<string, ReturnArgumentLink>(" Hello World ") .RunWithInput<TrimInputStringLink>(); }); await chain.RunAsync(); } [TestMethod] public async Task CreateChainWithContextVariables() { IChain chain = new Chain(configure => { configure .Run<SetContextVariableLink>(" Hello World ") .Run<TrimContextVariableStringLink>(); }); await chain.RunAsync(); } [TestMethod] public async Task CreateChainWhereResultIsIgnored() { IChain chain = new Chain(configure => { configure .GetResult<string, HelloWorldLink>() .GetResult<string, HelloWorldLink>(); }); await chain.RunAsync(); } [TestMethod] public async Task CreateChainWithMultipleBranches() { var chain = new Chain(configure => { var helloWorldResult = configure.GetResult<string, HelloWorldLink>(); helloWorldResult.RunWithInput<TrimInputStringLink>(); helloWorldResult.GetResult<string, HelloWorldLink>(); }); await chain.RunAsync(); } [TestMethod] public async Task CreateChainWithDelegates() { const string Expected = "Hello World"; string? trimmedString = null; string? helloWorld = null; IChain chain = new Chain(configure => { var helloWorldResult = configure.Run(() => " Hello World "); helloWorldResult .RunWithInput<string?, TrimInputStringLink>() .RunWithInput(input => trimmedString = input); helloWorldResult .GetResult<string, HelloWorldLink>() .RunWithInput(input => helloWorld = input); }); await chain.RunAsync(); Assert.AreEqual(Expected, trimmedString); Assert.AreEqual(Expected, helloWorld); } [TestMethod] public async Task RunChainWithArgs() { const string Expected = "Hello World"; string? trimmedString = null; IChain<string> chain = new Chain<string>(configure => { configure .RunWithInput<string?, TrimInputStringLink>() .RunWithInput(input => trimmedString = input); }); await chain.RunAsync(" Hello World "); Assert.AreEqual(Expected, trimmedString); } [TestMethod] public async Task RunChainWithArgsIntoDelegate() { const string Expected = "Hello World"; string? trimmedString = null; IChain<string> chain = new Chain<string>(configure => { configure .Run((input) => input.Trim()) .RunWithInput(input => trimmedString = input); }); await chain.RunAsync(" Hello World "); Assert.AreEqual(Expected, trimmedString); } [TestMethod] public async Task ResultsPassedAlong() { const string Expected = "Hello World"; string? trimmedString = null; IChain chain = new Chain(configure => { configure .Run(() => " Hello World ") .RunWithInput(input => Console.Write(input)) .RunWithInput(input => input.Trim()) .Run(() => Console.Write("Hello")) .Run<SetContextVariableLink>("Bar") .RunWithInput(input => trimmedString = input); }); await chain.RunAsync(); Assert.AreEqual(Expected, trimmedString); trimmedString = null; IChain<string> inputChain = new Chain<string>(configure => { configure .Run(input => Console.Write(input)) .RunWithInput(input => input.Trim()) .Run(() => Console.Write("Hello")) .RunWithInput(input => input + " ") .Run(() => Console.Write("Hello")) .RunWithInput<string?, TrimInputStringLink>() .Run(() => Console.Write("Hello")) .Run<SetContextVariableLink>("Bar") .RunWithInput(input => trimmedString = input); }); await chain.RunAsync(); Assert.AreEqual(Expected, trimmedString); } [TestMethod] public async Task InstantiateChainLinks() { const string Expected = "Hello World"; string? trimmedString = null; IChain<string> chain = new Chain<string>(configure => { configure .RunWithInput<string?, TrimInputStringLink>() .RunWithInput(input => trimmedString = input) .GetResult<string, HelloWorldLink>() .Run<SetContextVariableLink>(" Test "); }); await chain.RunAsync(" Hello World "); Assert.AreEqual(Expected, trimmedString); } [TestMethod] public async Task Conditionals() { const string Expected = "Hello World"; string? trimmedString = null; IChain chain = new Chain(configure => { configure .If(() => true) .Run(() => " Hello World ") .If((IChainLinkRunContext context) => true) .RunWithInput<string?, TrimInputStringLink>() .If((input) => input == "Hello World") .RunWithInput(input => trimmedString = input); }); await chain.RunAsync(); Assert.AreEqual(Expected, trimmedString); trimmedString = null; IChain<string> inputChain = new Chain<string>(configure => { configure .If(() => true) .If((input) => input == " Hello World ") .RunWithInput<string?, TrimInputStringLink>() .If((input) => input == "Hello World") .If(() => true) .RunWithInput(input => trimmedString = input); }); await inputChain.RunAsync(" Hello World "); Assert.AreEqual(Expected, trimmedString); } [TestMethod] public async Task ReassignDelegateAndIfBuilders() { const string Expected = "Hello World"; string? trimmedString = null; IChain chain = new Chain(configure => { IResultChainBuilder<string> helloWorld = configure .Run(() => " Hello World ") .If((string input) => input != null); helloWorld = helloWorld.RunWithInput(i => i.Trim()); helloWorld.RunWithInput(i => trimmedString = i); }); await chain.RunAsync(); Assert.AreEqual(Expected, trimmedString); trimmedString = null; IChain<string> inputChain = new Chain<string>(configure => { IInputResultChainBuilder<string, string> helloWorld = configure .If((string input) => input != null); helloWorld = helloWorld.RunWithInput(i => i.Trim()); helloWorld.RunWithInput(i => trimmedString = i); }); await inputChain.RunAsync(" Hello World "); Assert.AreEqual(Expected, trimmedString); } [TestMethod] public async Task Else() { const string Expected = "Hello World"; string? trimmedString = null; string? otherString = Expected; IChain chain = new Chain(configure => { IIfChainBuilder<string> ifHelloWorldNull = configure .Run(() => " Hello World ") .If((string input) => input == null); ifHelloWorldNull.RunWithInput(i => otherString = i); ifHelloWorldNull .Else .RunWithInput(i => i.Trim()) .RunWithInput(i => trimmedString = i); }); await chain.RunAsync(); Assert.AreEqual(Expected, trimmedString); Assert.IsNotNull(otherString); trimmedString = null; IChain<string> inputChain = new Chain<string>(configure => { IInputIfChainBuilder<string, string> ifHelloWorldNull = configure .If((string input) => input == null); ifHelloWorldNull.RunWithInput(i => otherString = i); ifHelloWorldNull .Else .RunWithInput(i => i.Trim()) .RunWithInput(i => trimmedString = i); }); await inputChain.RunAsync(" Hello World "); Assert.AreEqual(Expected, trimmedString); Assert.IsNotNull(otherString); } } }
namespace XPlat.Storage { using System; using XPlat.Foundation.Collections; public class ApplicationDataContainer : IApplicationDataContainer { private readonly ApplicationDataContainerSettings settings; /// <summary> /// Initializes a new instance of the <see cref="ApplicationDataContainer"/> class. /// </summary> /// <param name="locality"> /// The locality. /// </param> /// <param name="name"> /// The name. /// </param> internal ApplicationDataContainer(ApplicationDataLocality locality, string name) { this.Locality = locality; this.Name = name; this.settings = new ApplicationDataContainerSettings(); } /// <inheritdoc /> /// <remarks> /// CreateContainer is not supported by Android. /// </remarks> public IApplicationDataContainer CreateContainer(string name, ApplicationDataCreateDisposition disposition) { throw new NotSupportedException(); } /// <inheritdoc /> public ApplicationDataLocality Locality { get; } /// <inheritdoc /> public string Name { get; } /// <inheritdoc /> public IPropertySet Values => this.settings; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace VoatHub { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class SettingsPage : Page { private Flyout restartNeededFlyout; public SettingsPage() { this.InitializeComponent(); restartNeededFlyout = Resources["RestartNeededFlyout"] as Flyout; var theme = App.Current.RequestedTheme; ThemeComboBox.SelectedItem = theme == ApplicationTheme.Dark ? ThemeDarkItem : ThemeLightItem; } private void ThemeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var combobox = sender as ComboBox; if (combobox.SelectedItem == null) return; var selected = combobox.SelectedItem as ComboBoxItem; var settings = ApplicationData.Current.RoamingSettings; if (selected == ThemeDarkItem) App.ChangeThemeSetting(ApplicationTheme.Dark); else if (selected == ThemeLightItem) App.ChangeThemeSetting(ApplicationTheme.Light); // The try/catch prevents error occured when the initial loading selected changed // trigger that happens before the visual tree is shown. try { restartNeededFlyout.ShowAt(combobox); } catch (ArgumentException) { } } private void BackButton_Click(object sender, RoutedEventArgs e) { if (Frame.CanGoBack) Frame.GoBack(); } } }
using System.Collections.Generic; using Deadspell.Map; using Sirenix.OdinInspector; using UnityEngine; using UnityEngine.Tilemaps; namespace Deadspell.Data { [CreateAssetMenu(menuName = "Deadspell/Maps/Theme")] public class MapTheme : SerializedScriptableObject { public Renderable Default = new Renderable(); public Dictionary<TileType, Renderable> Overrides = new Dictionary<TileType, Renderable>(); public Renderable GetRenderable(TileType tile) { Renderable renderable; if (!Overrides.TryGetValue(tile, out renderable)) { renderable = Default; } return renderable; } public TileBase GetTile(TileType tile, bool greyscale = false) { Renderable renderable; if (!Overrides.TryGetValue(tile, out renderable)) { renderable = Default; } var color = renderable.Color.Value; if (greyscale) { color = new Color(color.grayscale, color.grayscale, color.grayscale, color.a); } return TileCache.GetTile(renderable.Sprite, color); } } }
using System.Collections.Generic; using System.Linq; using Merchello.Core.Models; using NUnit.Framework; namespace Merchello.Tests.Base.Visitors { public class MockLineItemVistor : ILineItemVisitor { private readonly List<ILineItem> _visited; public MockLineItemVistor() { _visited = new List<ILineItem>(); } public void Visit(ILineItem lineItem) { _visited.Add(lineItem); } public IEnumerable<ILineItem> Visited { get { return _visited; } } } }
/* Copyright (c) 2017, pGina Team All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the pGina Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using log4net; namespace pGina.Plugin.MySQLAuth { enum PasswordHashAlgorithm { NONE, MD5, SHA1, SHA256, SHA384, SHA512, SMD5, SSHA1, SSHA256, SSHA384, SSHA512 } class UserEntry { private ILog m_logger = LogManager.GetLogger("MySQLAuth.UserEntry"); private string m_hashedPass; private PasswordHashAlgorithm m_hashAlg; private string m_name; private byte[] m_passBytes; public string Name { get { return m_name; } } public PasswordHashAlgorithm HashAlg { get { return m_hashAlg; } } private string HashedPassword { get { return m_hashedPass; } } public UserEntry(string uname, PasswordHashAlgorithm alg, string hashedPass) { m_name = uname; m_hashAlg = alg; m_hashedPass = hashedPass; if (m_hashAlg != PasswordHashAlgorithm.NONE) m_passBytes = this.Decode(m_hashedPass); else m_passBytes = null; } private byte[] Decode( string hash ) { int encInt = Settings.Store.HashEncoding; Settings.HashEncoding encoding = (Settings.HashEncoding)encInt; if (encoding == Settings.HashEncoding.HEX) return FromHexString(hash); else if (encoding == Settings.HashEncoding.BASE_64) return Convert.FromBase64String(hash); else { m_logger.ErrorFormat("Unrecognized hash encoding! This shouldn't happen."); throw new Exception("Unrecognized hash encoding."); } } public bool VerifyPassword( string plainText ) { if (plainText != null) { // If hash algorithm is NONE, just compare the strings if (HashAlg == PasswordHashAlgorithm.NONE) return plainText.Equals(HashedPassword); // Is it a salted hash? if (HashAlg == PasswordHashAlgorithm.SMD5 || HashAlg == PasswordHashAlgorithm.SSHA1 || HashAlg == PasswordHashAlgorithm.SSHA256 || HashAlg == PasswordHashAlgorithm.SSHA384 || HashAlg == PasswordHashAlgorithm.SSHA512) { return VerifySaltedPassword(plainText); } // If we're here, we have an unsalted hash to compare with, hash and compare // the hashed bytes. byte[] hashedPlainText = HashPlainText(plainText); if (hashedPlainText != null) return hashedPlainText.SequenceEqual(m_passBytes); else return false; } else { return false; } } private bool VerifySaltedPassword(string plainText) { using (HashAlgorithm hasher = GetHasher()) { if (hasher != null) { if (hasher.HashSize % 8 != 0) m_logger.ErrorFormat("WARNING: hash size is not a multiple of 8. Hashes may not be evaluated correctly!"); int hashSizeBytes = hasher.HashSize / 8; if( m_passBytes.Length > hashSizeBytes ) { // Get the salt byte[] salt = new byte[m_passBytes.Length - hashSizeBytes]; Array.Copy(m_passBytes, hashSizeBytes, salt, 0, salt.Length); m_logger.DebugFormat("Found {1} byte salt: [{0}]", string.Join(",", salt), salt.Length); // Get the hash byte[] hashedPassAndSalt = new byte[hashSizeBytes]; Array.Copy(m_passBytes, 0, hashedPassAndSalt, 0, hashSizeBytes); // Build an array with the plain text and the salt byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] plainTextAndSalt = new byte[salt.Length + plainTextBytes.Length]; plainTextBytes.CopyTo(plainTextAndSalt, 0); salt.CopyTo(plainTextAndSalt, plainTextBytes.Length); // Compare the byte arrays byte[] hashedPlainTextAndSalt = hasher.ComputeHash(plainTextAndSalt); return hashedPlainTextAndSalt.SequenceEqual(hashedPassAndSalt); } else { m_logger.ErrorFormat("Found hash of length {0}, expected at least {1} bytes.", m_passBytes.Length, hashSizeBytes); throw new Exception("Hash length is too short, no salt found."); } } } return false; } private byte[] HashPlainText( string plainText ) { if (HashAlg == PasswordHashAlgorithm.NONE) throw new Exception("Tried to hash a password when algorithm is NONE."); byte[] bytes = Encoding.UTF8.GetBytes(plainText); byte[] result = null; using (HashAlgorithm hasher = GetHasher()) { if( hasher != null ) result = hasher.ComputeHash(bytes); } return result; } private HashAlgorithm GetHasher() { switch (HashAlg) { case PasswordHashAlgorithm.NONE: return null; case PasswordHashAlgorithm.MD5: case PasswordHashAlgorithm.SMD5: return MD5.Create(); case PasswordHashAlgorithm.SHA1: case PasswordHashAlgorithm.SSHA1: return SHA1.Create(); case PasswordHashAlgorithm.SHA256: case PasswordHashAlgorithm.SSHA256: return SHA256.Create(); case PasswordHashAlgorithm.SHA512: case PasswordHashAlgorithm.SSHA512: return SHA512.Create(); case PasswordHashAlgorithm.SHA384: case PasswordHashAlgorithm.SSHA384: return SHA384.Create(); default: m_logger.ErrorFormat("Unrecognized hash algorithm!"); return null; } } private string ToHexString(byte[] bytes) { StringBuilder builder = new StringBuilder(); foreach( byte b in bytes ) { builder.Append(b.ToString("x2")); } return builder.ToString(); } private byte[] FromHexString(string hex) { byte[] bytes = null; if (hex.Length % 2 != 0) { hex = hex + "0"; bytes = new byte[hex.Length + 1 / 2]; } else { bytes = new byte[hex.Length / 2]; } for (int i = 0; i < hex.Length / 2; i++ ) { bytes[i] = Convert.ToByte(hex.Substring(i*2, 2), 16); } return bytes; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BubblePops { [System.Serializable] public struct BallSerializedData { public int number; public BubblePops.Balls.BallColors balColor; } public class Level : ScriptableObject { [SerializeField] public BallSerializedData[][] allBallsOnLevel; } }
using System; using System.Collections.Generic; using System.Text; namespace AssemblyInspector.Loader { public enum ResolvedAssemblyResultEnum { NoMatch, ExactMatch, BestMatch, } }
using System.Threading.Tasks; using Havit.AskMe.Web.Blazor.Shared.Contracts.Account; namespace Havit.AskMe.Web.Blazor.Client.Services.Security { public interface IAuthenticationClientFacade { Task<LoginVM> Login(LoginIM inputModel); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Comm100.Domain.Repository; using Comm100.Extension; using Comm100.Runtime.Exception; using FileService.Domain.Entities; using FileService.Domain.Interfaces; using File = FileService.Domain.Entities.File; namespace FileService.Domain.Services { public class FileDomainService : IFileDomainService { private readonly IFileOperation _fileOperation; private readonly IRepository<File> _repository; public FileDomainService(IFileOperation fileOperation,IRepository<File> repository) { this._fileOperation = fileOperation; this._repository = repository; } public void Delete(Guid id) { var file = _repository.Get(id); _repository.Delete(file); _fileOperation.Delete(file.Id); } public Entities.File Get(string fileKey) { throw new NotImplementedException(); } public IList<Entities.File> GetList(FileQueryInput input) { throw new NotImplementedException(); } public FileOutput Read(string fileKey) { var file = _repository.GetAll(e => e.FileKey == fileKey).FirstOrDefault(); if (file == null) { throw new EntityNotFoundException<string>("fileKey",typeof(File)); } var fileOutput = file.MapTo<FileOutput>(); fileOutput.Stream = _fileOperation.Read(file.Id); return fileOutput; } public Entities.File Add(Entities.File file, Stream stream) { var newFile= _repository.Insert(file); var fileKey= _fileOperation.Save(newFile.Id, stream); newFile.FileKey = fileKey; _repository.Update(newFile); return newFile; } } }
using System; using System.Collections.Generic; using Comformation.IntrinsicFunctions; namespace Comformation.EMR.StudioSessionMapping { /// <summary> /// AWS::EMR::StudioSessionMapping /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-studiosessionmapping.html /// </summary> public class StudioSessionMappingResource : ResourceBase { public class StudioSessionMappingProperties { /// <summary> /// IdentityName /// The name of the user or group. For more information, see UserName and DisplayName in the AWS SSO /// Identity Store API Reference. /// Required: Yes /// Type: String /// Minimum: 0 /// Maximum: 256 /// Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]* /// Update requires: Replacement /// </summary> public Union<string, IntrinsicFunction> IdentityName { get; set; } /// <summary> /// IdentityType /// Specifies whether the identity to map to the Amazon EMR Studio is a user or a group. /// Required: Yes /// Type: String /// Allowed values: GROUP | USER /// Update requires: Replacement /// </summary> public Union<string, IntrinsicFunction> IdentityType { get; set; } /// <summary> /// SessionPolicyArn /// The Amazon Resource Name (ARN) for the session policy that will be applied to the user or group. /// Session policies refine Studio user permissions without the need to use multiple IAM user roles. For /// more information, see Create an EMR Studio user role with session policies in the Amazon EMR /// Management Guide. /// Required: Yes /// Type: String /// Minimum: 0 /// Maximum: 256 /// Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]* /// Update requires: No interruption /// </summary> public Union<string, IntrinsicFunction> SessionPolicyArn { get; set; } /// <summary> /// StudioId /// The ID of the Amazon EMR Studio to which the user or group will be mapped. /// Required: Yes /// Type: String /// Minimum: 0 /// Maximum: 256 /// Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]* /// Update requires: Replacement /// </summary> public Union<string, IntrinsicFunction> StudioId { get; set; } } public string Type { get; } = "AWS::EMR::StudioSessionMapping"; public StudioSessionMappingProperties Properties { get; } = new StudioSessionMappingProperties(); } }
using System; using System.Diagnostics; using System.Drawing.Imaging; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Remote; namespace Autodash.MsTest.SeleniumTests { //http://localhost:4444/grid/api/proxy?id=http://10.240.240.74:5555 [TestClass] public class UnitTest1 { private const string GridHubUrl = "http://alexappvm.cloudapp.net:4444/wd/hub"; [TestMethod] public void TestMethod1() { IWebDriver driver = GetDriver(); driver.Navigate().GoToUrl("https://www.etsy.com/"); var txt = driver.FindElement(By.Id("search-query")); txt.SendKeys("jewelry"); txt.SendKeys(OpenQA.Selenium.Keys.Enter); Thread.Sleep(TimeSpan.FromSeconds(2)); bool b = driver.Url.Contains("jewelry"); var screenshooter = ((ITakesScreenshot) driver); Screenshot screenshot = screenshooter.GetScreenshot(); screenshot.SaveAsFile(Path.Combine(Environment.CurrentDirectory, "screenshot.png"), ImageFormat.Png); Assert.IsTrue(b); driver.Quit(); driver.Dispose(); } private static IWebDriver GetDriver() { string hubUrl = Environment.GetEnvironmentVariable("hubUrl") ?? GridHubUrl; string browserName = Environment.GetEnvironmentVariable("browserName") ?? "internet explorer"; string browserVersion = Environment.GetEnvironmentVariable("browserVersion"); Console.WriteLine("Hub Url: " + hubUrl); Console.WriteLine("Browser Name: " + browserName); DesiredCapabilities capabilities; switch (browserName) { case "chrome": capabilities = DesiredCapabilities.Chrome(); break; case "internet explorer": capabilities = DesiredCapabilities.InternetExplorer(); break; case "firefox": capabilities = DesiredCapabilities.Firefox(); break; default: throw new InvalidOperationException("Unknown browser"); } if (!string.IsNullOrEmpty(browserVersion)) capabilities.SetCapability(CapabilityType.Version, browserVersion); IWebDriver driver = new RemoteWebDriver(new Uri(hubUrl), capabilities); return driver; } } }
using System; using System.IO; using Microsoft.Office.Interop.Word; namespace HafiyelnarnurFeferjicher { class Program { static void Main(string[] args) { var applicationClass = new ApplicationClass(); //applicationClass.Visible = false; 默认值就是 false 值 var folder = Environment.CurrentDirectory; string fileName = "1.docx"; fileName = Path.Combine(folder, fileName); fileName = Path.GetFullPath(fileName); // 截图使用只读方式打开,这里传入的要求是绝对路径 Document document = applicationClass.Documents.Open(fileName, ReadOnly: true); var count = 0; foreach (Window documentWindow in document.Windows) { var documentWindowPanes = documentWindow.Panes; for (var index = 0; index < documentWindowPanes.Count; index++) { Pane documentWindowPane = documentWindowPanes[index + 1]; var pagesCount = documentWindowPane.Pages.Count; for (int i = 0; i < pagesCount; i++) { Page page = documentWindowPane.Pages[i + 1]; Console.WriteLine($"{page.Width};{page.Height}"); count++; var file = Path.Combine(folder, $"{count}.png"); var bits = page.EnhMetaFileBits; using (var ms = new MemoryStream((byte[])(bits))) { var image = System.Drawing.Image.FromStream(ms); image.Save(file); } //page.SaveAsPNG(file); // System.Runtime.InteropServices.COMException: '该方法无法用于对那个对象。' } } } document.Close(); } } }
// DigitalRune Engine - Copyright (C) DigitalRune GmbH // This file is subject to the terms and conditions defined in // file 'LICENSE.TXT', which is part of this source code package. using System; using System.Threading.Tasks; using DigitalRune.Editor.Documents; using DigitalRune.Editor.Status; using DigitalRune.Editor.Text; using DigitalRune.Windows.Framework; using static System.FormattableString; namespace DigitalRune.Editor.Shader { partial class ShaderExtension { //-------------------------------------------------------------- #region Fields //-------------------------------------------------------------- #endregion //-------------------------------------------------------------- #region Properties & Events //-------------------------------------------------------------- #endregion //-------------------------------------------------------------- #region Methods //-------------------------------------------------------------- private bool CanAnalyze() { var document = _documentService.ActiveDocument as TextDocument; return !_isBusy && document != null && document.DocumentType.Name == ShaderDocumentFactory.FxFile; } private async void Analyze() { if (_isBusy) return; var document = _documentService.ActiveDocument as TextDocument; if (document == null || document.DocumentType.Name != ShaderDocumentFactory.FxFile) return; Logger.Debug("Analyzing effect {0}.", document.GetName()); bool isSaved = !document.IsUntitled && !document.IsModified; if (!isSaved) isSaved = _documentService.Save(document); if (!isSaved || document.Uri == null) { Logger.Debug("Document was not saved. Analysis canceled by user."); return; } _outputService.Clear(); var status = new StatusViewModel { Message = "Analyzing...", ShowProgress = true, Progress = double.NaN, }; _statusService.Show(status); // Disable buttons to avoid reentrance. _isBusy = true; UpdateCommands(); try { var shaderPerf = Editor.Services.GetInstance<ShaderPerf>().ThrowIfMissing(); var success = await Task.Run(() => shaderPerf.Run(document)); status.Progress = 100; status.IsCompleted = true; if (success) { status.Message = "Analysis succeeded."; } else { _outputService.Show(); status.Message = "Analysis failed."; status.ShowProgress = false; } } catch (Exception exception) { Logger.Warn(exception, "Analysis failed."); _outputService.WriteLine(Invariant($"Exception: {exception.Message}")); _outputService.Show(); status.Message = "Analysis failed."; status.ShowProgress = false; } // Enable buttons. _isBusy = false; UpdateCommands(); status.CloseAfterDefaultDurationAsync().Forget(); } #endregion } }
using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Utilities; // ReSharper disable once CheckNamespace namespace Blueshift.EntityFrameworkCore.MongoDB.Metadata.Builders { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static class MongoDbInternalMetadataBuilderExtensions { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbEntityTypeAnnotations MongoDb([NotNull] this InternalEntityTypeBuilder internalEntityTypeBuilder) => MongoDb(Check.NotNull(internalEntityTypeBuilder, nameof(internalEntityTypeBuilder)).Metadata); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbEntityTypeAnnotations MongoDb([NotNull] this EntityTypeBuilder entityTypeBuilder) => MongoDb(Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder)).Metadata); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbEntityTypeAnnotations MongoDb([NotNull] this IEntityType entityType) => MongoDb(Check.Is<IMutableEntityType>(entityType, nameof(entityType))); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbEntityTypeAnnotations MongoDb([NotNull] this IMutableEntityType mutableEntityType) => new MongoDbEntityTypeAnnotations(Check.NotNull(mutableEntityType, nameof(mutableEntityType))); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbModelAnnotations MongoDb([NotNull] this InternalModelBuilder internalModelBuilder) => MongoDb(Check.NotNull(internalModelBuilder, nameof(internalModelBuilder)).Metadata); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbModelAnnotations MongoDb([NotNull] this ModelBuilder modelBuilder) => MongoDb(Check.NotNull(modelBuilder, nameof(modelBuilder)).Model); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbModelAnnotations MongoDb([NotNull] this IModel model) => MongoDb(Check.Is<IMutableModel>(model, nameof(model))); /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static MongoDbModelAnnotations MongoDb([NotNull] this IMutableModel mutableModel) => new MongoDbModelAnnotations(Check.NotNull(mutableModel, nameof(mutableModel))); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace L2Package.DataStructures { public class UPointRegion { public Index Zone { set; get; } public int iLeaf { set; get; } public byte ZoneNumber { set; get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChangeTiles { class Program { static void Main(string[] args) { var savedMoney = double.Parse(Console.ReadLine()); var floorWidth = double.Parse(Console.ReadLine()); var floorLength = double.Parse(Console.ReadLine()); var triangleSide = double.Parse(Console.ReadLine()); var triangleHeigth = double.Parse(Console.ReadLine()); var priceForPlate = double.Parse(Console.ReadLine()); var paymentToWorker = double.Parse(Console.ReadLine()); var floorArea = floorLength * floorWidth; var plateArea = triangleSide * triangleHeigth / 2; var platesNeeded = Math.Ceiling(floorArea / plateArea) + 5; var moneyNeeded = priceForPlate * platesNeeded + paymentToWorker; if (savedMoney >= moneyNeeded) { Console.WriteLine("{0:f2} lv left.", savedMoney - moneyNeeded); } else { Console.WriteLine("You'll need {0:f2} lv more.", moneyNeeded - savedMoney); } } } }
namespace SteamAutoMarket.UI.Utils.ItemFilters { using SteamAutoMarket.UI.Models; using SteamAutoMarket.UI.Utils.ItemFilters.Strategies; public static class SteamItemsFilters<T> where T : SteamItemsModel { public static readonly ISteamItemsFilter<T> RealGameFilter = new RealGameFilter<T>(); public static readonly ISteamItemsFilter<T> TypeFilter = new TypeFilter<T>(); public static readonly ISteamItemsFilter<T> RarityFilter = new RarityFilter<T>(); public static readonly ISteamItemsFilter<T> MarketableFilter = new MarketableFilter<T>(); public static readonly ISteamItemsFilter<T> TradabilityFilter = new TradabilityFilter<T>(); } }
using NEFBDAACommons.Shared.DynamicQuery; using System; using System.Collections.Generic; namespace NEFBDAACommons.DynamicForms.Attributes { [System.AttributeUsage(System.AttributeTargets.Property)] public abstract class FormAssociationAttributes : System.Attribute { public Type AssociationType { get; set; } public string[] StaticOptions { get; set; } /// <summary> /// show select with add button on form /// </summary> public bool CanBeAddedInline { get; set; } = false; /// <summary> /// name of property which is important to connect this new value with object to which it is going to belong /// for example add user to currently edited company /// </summary> public string ReferencedPropertyNameToAddInline { get; set; } /// <summary> /// value of refenced entity /// </summary> public string ReferencedPropertyValueToAddInline { get; set; } public string[] CanBeAddedInlineForRoles { get; set; } = null; /// <summary> /// if options of this field should be filtered after any other field changed /// for example company changed so i can use only these company users to assign a ticket /// </summary> public string OptionsFilteredOnFieldChanged { get; set; } /// <summary> /// type of query used to filter options /// </summary> public QueryOperatorEnum OptionsFilteredOnFieldOperator { get; set; } = QueryOperatorEnum.Equal; /// <summary> /// value to compare in filter /// </summary> public string OptionsFilteredFieldToCompare { get; set; } public string[] DefaultFilterFieldNames = null; public QueryOperatorEnum[] DefaultFilterFieldOperators = null; public string[] DefaultFilterFieldValues = null; } public class FormOneToManyAssociationAttributeAttribute : FormAssociationAttributes { } public class FormManyToOneAssociationAttributeAttribute : FormAssociationAttributes { } public class FormManyToManyAssociationAttributeAttribute : FormAssociationAttributes { } }
using System.Threading.Tasks; namespace Pass.Components.Dialog; public interface IDialogPresenter { Task Show(IDialog dialog); }
using Prism.Commands; using Prism.Mvvm; using Prism.Navigation; using System; using System.Collections.Generic; using System.Linq; namespace TruthOrDareUI.ViewModels { public class AboutPageViewModel : BindableBase { private readonly INavigationService _navigationService; private DelegateCommand _returnCommand; public DelegateCommand ReturnCommand => _returnCommand ?? (_returnCommand = new DelegateCommand(ExecuteReturnCommand)); public AboutPageViewModel(INavigationService navigationService) { _navigationService = navigationService; } private async void ExecuteReturnCommand() { await _navigationService.GoBackAsync(); } } }
/* * Sometimes you want things to happen * one at a time, first this * then that, then the other * then again, over and over * * You can make it random * or use it in a line * you can have it grow * then shrink the next time */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class toSequence : Verb { //Variables required for this verb //________________________________ [Tooltip("Turn this on to determine if sequence should be random, otherwise it will run the scripts in order")] public bool randomize; //SerializeField is just making this private variable, below, visible in the Unity Editor. [SerializeField] private int currentNumber = 0; [SerializeField] private int numberOfSteps; //_________________________________ public Verb[] triggeredVerbs; void Start() { SetAudio(); if (isActive) PlayAudio(); //Unique verb content //________________________________ //________________________________ //checks the verb toSequence() to check how many trigger verbs are currently in the list. numberOfSteps = triggeredVerbs.Length; //if boolean is true, the starting point for the sequence will be set to random between 0 //and the total number of triggeredVerbs if (randomize) { currentNumber = Random.Range(0, numberOfSteps); } //________________________________ //________________________________ } // FixedUpdate is called once per frame void FixedUpdate() { //Unique verb content //________________________________ //________________________________ if (isActive && numberOfSteps != 0) { EndVerb(); Activate(triggeredVerbs[currentNumber]); if (randomize) { int next = Random.Range(0, numberOfSteps); // the ? and : in this statement are part of a ternary operator // Condition? If true : If false currentNumber = (next == currentNumber) ? ((next + 1) % numberOfSteps) : next; } else { currentNumber = (currentNumber + 1) % numberOfSteps; } } //________________________________ //________________________________ } } /* * This verb is a sequencer that lets you choose an array of verbs to either trigger in order * or else trigger at random, without repeating. */
namespace IntoTheCodeExample.DomainLanguage.Executers.Expression { public class ExpVariable<TType> : ExpTyped<TType> { public ExpVariable(string name) { Name = name; } public string Name; public override TType Compute(Variables runtime) { ValueTyped<TType> value = runtime.GetVariable(Name) as ValueTyped<TType>; return value.Value; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; namespace NPOI.HSLF.Model.TextProperties { /** * DefInition for the common character text property bitset, which * handles bold/italic/underline etc. */ public class CharFlagsTextProp : BitMaskTextProp { public static int BOLD_IDX = 0; public static int ITALIC_IDX = 1; public static int UNDERLINE_IDX = 2; public static int SHADOW_IDX = 4; public static int STRIKETHROUGH_IDX = 8; public static int RELIEF_IDX = 9; public static int RESET_NUMBERING_IDX = 10; public static int ENABLE_NUMBERING_1_IDX = 11; public static int ENABLE_NUMBERING_2_IDX = 12; public static String NAME = "char_flags"; public CharFlagsTextProp():base(2, 0xffff, NAME, new String[] { "bold", // 0x0001 A bit that specifies whether the characters are bold. "italic", // 0x0002 A bit that specifies whether the characters are italicized. "underline", // 0x0004 A bit that specifies whether the characters are underlined. "char_unknown_1", // 0x0008 Undefined and MUST be ignored. "shadow", // 0x0010 A bit that specifies whether the characters have a shadow effect. "fehint", // 0x0020 A bit that specifies whether characters originated from double-byte input. "char_unknown_2", // 0x0040 Undefined and MUST be ignored. "kumi", // 0x0080 A bit that specifies whether Kumimoji are used for vertical text. "strikethrough", // 0x0100 Undefined and MUST be ignored. "emboss", // 0x0200 A bit that specifies whether the characters are embossed. "char_unknown_3", // 0x0400 Undefined and MUST be ignored. "char_unknown_4", // 0x0800 Undefined and MUST be ignored. "char_unknown_5", // 0x1000 Undefined and MUST be ignored. }) { } } }
namespace Port.Server.IntegrationTests.SocketTestFramework { internal sealed class ByteArrayMessageClientFactory : IMessageClientFactory<byte[]> { public IMessageClient<byte[]> Create( INetworkClient networkClient) { return new ByteArrayMessageClient(networkClient); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FlowerAlertPageMongMongHandler : MonoBehaviour { public Text QuoteText; public string[] Quotes; public AudioClip[] Voices; public void OnEnable() { SoundHandler.Instance.MongMongSource.Stop(); SoundHandler.Instance.MongMongSource2.Stop(); int rand = Random.Range(0, Voices.Length); SoundHandler.Instance.MongMongSource.PlayOneShot(Voices[rand]); QuoteText.text = Quotes[rand]; } public void StopVoice() { SoundHandler.Instance.MongMongSource.Stop(); SoundHandler.Instance.MongMongSource2.Stop(); } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; namespace GlobalServer.Properties.Response.Models { public abstract class ResponseBase { protected abstract int GetStatusCode(); protected abstract IHeaderDictionary GetHeaders(); protected abstract string GetContentType(); protected abstract string GetResponse(); protected IHeaderDictionary FromHeaderDescription(IEnumerable<HeaderDescription> headers) { var headerDescriptions = headers as HeaderDescription[] ?? headers.ToArray(); if (headerDescriptions == null || !headerDescriptions.Any()) return new HeaderDictionary(); var headerDictionary = new HeaderDictionary(); foreach (var (key, value) in headerDescriptions) headerDictionary.Add(key, value); return headerDictionary; } public virtual Models.Response GetResponseModel() => new Models.Response { Content = GetResponse(), StatusCode = GetStatusCode(), ContentType = GetContentType(), HeaderDictionary = GetHeaders(), }; } }
using System; using static Ryujinx.Graphics.Gal.Shader.ShaderDecodeHelper; namespace Ryujinx.Graphics.Gal.Shader { static partial class ShaderDecode { private enum IntType { U8 = 0, U16 = 1, U32 = 2, U64 = 3, S8 = 4, S16 = 5, S32 = 6, S64 = 7 } private enum FloatType { F16 = 1, F32 = 2, F64 = 3 } public static void F2f_C(ShaderIrBlock block, long opCode, int position) { EmitF2F(block, opCode, ShaderOper.Cr); } public static void F2f_I(ShaderIrBlock block, long opCode, int position) { EmitF2F(block, opCode, ShaderOper.Immf); } public static void F2f_R(ShaderIrBlock block, long opCode, int position) { EmitF2F(block, opCode, ShaderOper.Rr); } public static void F2i_C(ShaderIrBlock block, long opCode, int position) { EmitF2I(block, opCode, ShaderOper.Cr); } public static void F2i_I(ShaderIrBlock block, long opCode, int position) { EmitF2I(block, opCode, ShaderOper.Immf); } public static void F2i_R(ShaderIrBlock block, long opCode, int position) { EmitF2I(block, opCode, ShaderOper.Rr); } public static void I2f_C(ShaderIrBlock block, long opCode, int position) { EmitI2F(block, opCode, ShaderOper.Cr); } public static void I2f_I(ShaderIrBlock block, long opCode, int position) { EmitI2F(block, opCode, ShaderOper.Imm); } public static void I2f_R(ShaderIrBlock block, long opCode, int position) { EmitI2F(block, opCode, ShaderOper.Rr); } public static void I2i_C(ShaderIrBlock block, long opCode, int position) { EmitI2I(block, opCode, ShaderOper.Cr); } public static void I2i_I(ShaderIrBlock block, long opCode, int position) { EmitI2I(block, opCode, ShaderOper.Imm); } public static void I2i_R(ShaderIrBlock block, long opCode, int position) { EmitI2I(block, opCode, ShaderOper.Rr); } public static void Isberd(ShaderIrBlock block, long opCode, int position) { //This instruction seems to be used to translate from an address to a vertex index in a GS //Stub it as such block.AddNode(new ShaderIrCmnt("Stubbed.")); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), opCode.Gpr8()))); } public static void Mov_C(ShaderIrBlock block, long opCode, int position) { ShaderIrOperCbuf cbuf = opCode.Cbuf34(); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), cbuf))); } public static void Mov_I(ShaderIrBlock block, long opCode, int position) { ShaderIrOperImm imm = opCode.Imm19_20(); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), imm))); } public static void Mov_I32(ShaderIrBlock block, long opCode, int position) { ShaderIrOperImm imm = opCode.Imm32_20(); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), imm))); } public static void Mov_R(ShaderIrBlock block, long opCode, int position) { ShaderIrOperGpr gpr = opCode.Gpr20(); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), gpr))); } public static void Sel_C(ShaderIrBlock block, long opCode, int position) { EmitSel(block, opCode, ShaderOper.Cr); } public static void Sel_I(ShaderIrBlock block, long opCode, int position) { EmitSel(block, opCode, ShaderOper.Imm); } public static void Sel_R(ShaderIrBlock block, long opCode, int position) { EmitSel(block, opCode, ShaderOper.Rr); } public static void Mov_S(ShaderIrBlock block, long opCode, int position) { block.AddNode(new ShaderIrCmnt("Stubbed.")); //Zero is used as a special number to get a valid "0 * 0 + VertexIndex" in a GS ShaderIrNode source = new ShaderIrOperImm(0); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), source))); } private static void EmitF2F(ShaderIrBlock block, long opCode, ShaderOper oper) { bool negA = opCode.Read(45); bool absA = opCode.Read(49); ShaderIrNode operA; switch (oper) { case ShaderOper.Cr: operA = opCode.Cbuf34(); break; case ShaderOper.Immf: operA = opCode.Immf19_20(); break; case ShaderOper.Rr: operA = opCode.Gpr20(); break; default: throw new ArgumentException(nameof(oper)); } operA = GetAluFabsFneg(operA, absA, negA); ShaderIrInst roundInst = GetRoundInst(opCode); if (roundInst != ShaderIrInst.Invalid) { operA = new ShaderIrOp(roundInst, operA); } block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), operA))); } private static void EmitF2I(ShaderIrBlock block, long opCode, ShaderOper oper) { IntType type = GetIntType(opCode); if (type == IntType.U64 || type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } bool negA = opCode.Read(45); bool absA = opCode.Read(49); ShaderIrNode operA; switch (oper) { case ShaderOper.Cr: operA = opCode.Cbuf34(); break; case ShaderOper.Immf: operA = opCode.Immf19_20(); break; case ShaderOper.Rr: operA = opCode.Gpr20(); break; default: throw new ArgumentException(nameof(oper)); } operA = GetAluFabsFneg(operA, absA, negA); ShaderIrInst roundInst = GetRoundInst(opCode); if (roundInst != ShaderIrInst.Invalid) { operA = new ShaderIrOp(roundInst, operA); } bool signed = type >= IntType.S8; int size = 8 << ((int)type & 3); if (size < 32) { uint mask = uint.MaxValue >> (32 - size); float cMin = 0; float cMax = mask; if (signed) { uint halfMask = mask >> 1; cMin -= halfMask + 1; cMax = halfMask; } ShaderIrOperImmf min = new ShaderIrOperImmf(cMin); ShaderIrOperImmf max = new ShaderIrOperImmf(cMax); operA = new ShaderIrOp(ShaderIrInst.Fclamp, operA, min, max); } ShaderIrInst inst = signed ? ShaderIrInst.Ftos : ShaderIrInst.Ftou; ShaderIrNode op = new ShaderIrOp(inst, operA); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } private static void EmitI2F(ShaderIrBlock block, long opCode, ShaderOper oper) { IntType type = GetIntType(opCode); if (type == IntType.U64 || type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } int sel = opCode.Read(41, 3); bool negA = opCode.Read(45); bool absA = opCode.Read(49); ShaderIrNode operA; switch (oper) { case ShaderOper.Cr: operA = opCode.Cbuf34(); break; case ShaderOper.Imm: operA = opCode.Imm19_20(); break; case ShaderOper.Rr: operA = opCode.Gpr20(); break; default: throw new ArgumentException(nameof(oper)); } operA = GetAluIabsIneg(operA, absA, negA); bool signed = type >= IntType.S8; int shift = sel * 8; int size = 8 << ((int)type & 3); if (shift != 0) { operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); } if (size < 32) { operA = ExtendTo32(operA, signed, size); } ShaderIrInst inst = signed ? ShaderIrInst.Stof : ShaderIrInst.Utof; ShaderIrNode op = new ShaderIrOp(inst, operA); block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), op))); } private static void EmitI2I(ShaderIrBlock block, long opCode, ShaderOper oper) { IntType type = GetIntType(opCode); if (type == IntType.U64 || type == IntType.S64) { //TODO: 64-bits support. //Note: GLSL doesn't support 64-bits integers. throw new NotImplementedException(); } int sel = opCode.Read(41, 3); bool negA = opCode.Read(45); bool absA = opCode.Read(49); bool satA = opCode.Read(50); ShaderIrNode operA; switch (oper) { case ShaderOper.Cr: operA = opCode.Cbuf34(); break; case ShaderOper.Immf: operA = opCode.Immf19_20(); break; case ShaderOper.Rr: operA = opCode.Gpr20(); break; default: throw new ArgumentException(nameof(oper)); } operA = GetAluIabsIneg(operA, absA, negA); bool signed = type >= IntType.S8; int shift = sel * 8; int size = 8 << ((int)type & 3); if (shift != 0) { operA = new ShaderIrOp(ShaderIrInst.Asr, operA, new ShaderIrOperImm(shift)); } if (size < 32) { uint mask = uint.MaxValue >> (32 - size); if (satA) { uint cMin = 0; uint cMax = mask; if (signed) { uint halfMask = mask >> 1; cMin -= halfMask + 1; cMax = halfMask; } ShaderIrOperImm min = new ShaderIrOperImm((int)cMin); ShaderIrOperImm max = new ShaderIrOperImm((int)cMax); operA = new ShaderIrOp(signed ? ShaderIrInst.Clamps : ShaderIrInst.Clampu, operA, min, max); } else { operA = ExtendTo32(operA, signed, size); } } block.AddNode(opCode.PredNode(new ShaderIrAsg(opCode.Gpr0(), operA))); } private static void EmitSel(ShaderIrBlock block, long opCode, ShaderOper oper) { ShaderIrOperGpr dst = opCode.Gpr0(); ShaderIrNode pred = opCode.Pred39N(); ShaderIrNode resultA = opCode.Gpr8(); ShaderIrNode resultB; switch (oper) { case ShaderOper.Cr: resultB = opCode.Cbuf34(); break; case ShaderOper.Imm: resultB = opCode.Imm19_20(); break; case ShaderOper.Rr: resultB = opCode.Gpr20(); break; default: throw new ArgumentException(nameof(oper)); } block.AddNode(opCode.PredNode(new ShaderIrCond(pred, new ShaderIrAsg(dst, resultA), false))); block.AddNode(opCode.PredNode(new ShaderIrCond(pred, new ShaderIrAsg(dst, resultB), true))); } private static IntType GetIntType(long opCode) { bool signed = opCode.Read(13); IntType type = (IntType)(opCode.Read(10, 3)); if (signed) { type += (int)IntType.S8; } return type; } private static FloatType GetFloatType(long opCode) { return (FloatType)(opCode.Read(8, 3)); } private static ShaderIrInst GetRoundInst(long opCode) { switch (opCode.Read(39, 3)) { case 1: return ShaderIrInst.Floor; case 2: return ShaderIrInst.Ceil; case 3: return ShaderIrInst.Trunc; } return ShaderIrInst.Invalid; } } }
// This file is part of Core WF which is licensed under the MIT license. // See LICENSE file in the project root for full license information. using System.ComponentModel; namespace System.Activities.XamlIntegration; public sealed class OutArgumentConverter : TypeConverterBase { public OutArgumentConverter() : base(typeof(OutArgument<>), typeof(OutArgumentConverterHelper<>)) { } public OutArgumentConverter(Type type) : base(type, typeof(OutArgument<>), typeof(OutArgumentConverterHelper<>)) { } internal sealed class OutArgumentConverterHelper<T> : TypeConverterHelper<OutArgument<T>> { private readonly ActivityWithResultConverter.ExpressionConverterHelper<Location<T>> _expressionHelper; public OutArgumentConverterHelper() { _expressionHelper = new ActivityWithResultConverter.ExpressionConverterHelper<Location<T>>(true); } public override OutArgument<T> ConvertFromString(string text, ITypeDescriptorContext context) { return new OutArgument<T> { Expression = _expressionHelper.ConvertFromString(text.Trim(), context) }; } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.IO; using Microsoft.CodeAnalysis.Emit; using System.Reflection; namespace Shiny.Calculator.Evaluation { public enum SyntaxRunType { Unknown, Keyword, Identifier, String } public class SyntaxRun { public SyntaxRunType Type { get; set; } public string Value { get; set; } } public class CodeColorizer { private IPrinter _printer; public CodeColorizer(IPrinter printer) { this._printer = printer; } public void Colorize(string source) { var tree = CSharpSyntaxTree.ParseText(source); var walker = new SyntaxRunWalker(); walker.Visit(tree.GetRoot()); var syntax = walker.GetSyntax(); foreach (var s in syntax) { Color runColor = Colors.Gray; if (s.Type == SyntaxRunType.Keyword) runColor = Colors.Blue; else if (s.Type == SyntaxRunType.Identifier) runColor = Colors.White; else if (s.Type == SyntaxRunType.String) runColor = Colors.Gray; else runColor = Colors.DarkGray; _printer.PrintInline(new Run() { Color = runColor, Text = s.Value }); } _printer.Print(); } public class SyntaxRunWalker : SyntaxWalker { private readonly List<SyntaxRun> _result = new List<SyntaxRun>(); public SyntaxRunWalker() : base(SyntaxWalkerDepth.StructuredTrivia) { } public List<SyntaxRun> GetSyntax() { return _result; } protected override void VisitToken(SyntaxToken token) { ProcessTrivia(token.LeadingTrivia); if (token.IsKeyword()) { _result.Add(new SyntaxRun() { Type = SyntaxRunType.Keyword, Value = token.ToString() }); } else { if (token.Kind() == SyntaxKind.IdentifierToken) { _result.Add(new SyntaxRun() { Type = SyntaxRunType.Identifier, Value = token.ToString() }); } else if (token.Kind() == SyntaxKind.StringLiteralToken) { _result.Add(new SyntaxRun() { Type = SyntaxRunType.String, Value = token.ToString() }); } else { _result.Add(new SyntaxRun() { Value = token.ToString() }); } } ProcessTrivia(token.TrailingTrivia); base.VisitToken(token); } private void ProcessTrivia(SyntaxTriviaList list) { foreach (var trivia in list) { if (trivia.Kind() != SyntaxKind.WarningDirectiveTrivia) { _result.Add(new SyntaxRun() { Value = trivia.ToString() }); } } } } } }
using System.Drawing; namespace Utilities { public interface ILoggingProvider { void ReportProgressChanged(int progress); void RaiseError(string error, int rank = 0); void RaiseWarning(string warning, int rank = 0); void RaiseMessage(string message, int rank = 0, bool emphasis = false); void RaiseMessage(string message, Color color, int rank = 0, bool emphasis = false); void RaiseVerbose(string message, int rank = 0, bool emphasis = false); void CheckCancelled(); } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Stations.Models; namespace Stations.Data.Configurations { public class TripConfig : IEntityTypeConfiguration<Trip> { public void Configure(EntityTypeBuilder<Trip> builder) { builder.HasKey(e => e.Id); builder.Property(e => e.DepartureTime).IsRequired(); builder.Property(e => e.ArrivalTime).IsRequired(); builder.Property(e => e.Status).IsRequired().HasDefaultValue(TripStatus.OnTime); builder.HasOne(t => t.OriginStation) .WithMany(os => os.TripsFrom) .HasForeignKey(os => os.OriginStationId) .OnDelete(DeleteBehavior.Restrict); builder.HasOne(t => t.DestinationStation) .WithMany(ds => ds.TripsTo) .HasForeignKey(ds => ds.DestinationStationId) .OnDelete(DeleteBehavior.Restrict); builder.HasOne(t => t.Train) .WithMany(tr => tr.Trips) .HasForeignKey(tr => tr.TrainId) .OnDelete(DeleteBehavior.Restrict); } } }
using Microsoft.EntityFrameworkCore; namespace Factory.Models { public class FactoryContext : DbContext { public DbSet<Engineer> Engineers { get; set; } public DbSet<Location> Locations { get; set; } public DbSet<Machine> Machines { get; set; } public DbSet<EngineerLocationMachine> EngineerLocationMachine { get; set; } public FactoryContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Machine>().HasData( new Machine { MachineId = 1, Name = "Dreamweaver" }, new Machine { MachineId = 2, Name = "Bubblewrappinator" }, new Machine { MachineId = 3, Name = "Laughbox" } ); modelBuilder.Entity<Location>().HasData( new Location { LocationId = 1, Name = "Who-Ville" }, new Location { LocationId = 2, Name = "Mullberry" }, new Location { LocationId = 3, Name = "The Jungle of Nool" } ); } } }
using System; using System.ComponentModel; using System.Windows.Forms; namespace DLC.Framework.UI.Forms { public static class FormsExtensions { /// <summary> /// The DesignMode property does not correctly tell you if you are in design mode. /// InVSDesigner is a corrected version of that property. /// See https://connect.microsoft.com/VisualStudio/feedback/details/553305 /// and http://stackoverflow.com/a/2693338/238419 /// </summary> public static bool InVSDesigner(this Control ctrl) { if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) return true; while (ctrl != null) { if (ctrl.Site != null && ctrl.Site.DesignMode) return true; ctrl = ctrl.Parent; } return false; } } }
// <copyright file="IRewardCycleStorageProvider.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Apps.RewardAndRecognition.Providers { using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Teams.Apps.RewardAndRecognition.Models; /// <summary> /// Interface for reward cycle storage provider. /// </summary> public interface IRewardCycleStorageProvider { /// <summary> /// This method is used to fetch reward cycle details for a given team Id. /// </summary> /// <param name="teamId">Team Id.</param> /// <returns>Reward cycle for a given team Id.</returns> Task<RewardCycleEntity> GetCurrentRewardCycleAsync(string teamId); /// <summary> /// This method is used to fetch punished reward cycle details for a given team Id. /// </summary> /// <param name="teamId">Team Id.</param> /// <returns>Reward cycle for a given team Id.</returns> Task<RewardCycleEntity> GetPublishedRewardCycleAsync(string teamId); /// <summary> /// Store or update reward cycle in table storage. /// </summary> /// <param name="rewardCycleEntity">Represents reward cycle entity used for storage and retrieval.</param> /// <returns><see cref="Task"/> that represents reward cycle entity is saved or updated.</returns> Task<RewardCycleEntity> StoreOrUpdateRewardCycleAsync(RewardCycleEntity rewardCycleEntity); /// <summary> /// This method is used to fetch current reward cycle detail for all teams. /// </summary> /// <returns><see cref="Task"/>Current reward cycle entities for all teams.</returns> Task<List<RewardCycleEntity>> GetCurrentRewardCycleForAllTeamsAsync(); /// <summary> /// This method is used get active reward cycle details for all teams. /// </summary> /// <returns>Reward active cycle for all teams.</returns> Task<List<RewardCycleEntity>> GetActiveRewardCycleForAllTeamsAsync(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.ComponentModel.DataAnnotations; using System.Text; using EPlikt.Models; using EPlikt.Feed; using log4net; using log4net.Config; namespace EPlikt.Controllers { public class EPliktController : ApiController { private static readonly ILog log = LogManager.GetLogger(typeof(EPliktController)); /// <summary> /// Get the main feed. /// </summary> /// <returns>The feed.</returns> [HttpGet] public HttpResponseMessage Feed() { log.Info("Processing feed request."); var res = Request.CreateResponse(HttpStatusCode.OK); try { var feedCreator = new LinqToXmlFeedCreator(); feedCreator.SetFeedSource(new ChalmersFeedSource()); feedCreator.CreateFeed(); res.Content = new StringContent(feedCreator.GetXmlFeedStr(), Encoding.UTF8, "application/rss+xml"); log.Info("Successfully delivered " + feedCreator.GetItemsCount() + " items."); } catch (Exception e) { log.Error(e.Message); res.Content = new StringContent("ERROR: " + e.Message, Encoding.UTF8, "text/plain"); } return res; } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace SwaggerIntegration.Controllers { //This blows up swagger //[ApiVersion("3.0-RC")] //[Route("api/values")] //[ApiController] //public class Values3Controller : Values2Controller //{ // [HttpGet, MapToApiVersion("3.0-RC")] // public ActionResult<IEnumerable<string>> GetV3() // { // return new string[] { "value1v2", "value2v2" }; // } //} //HACK: DONT DO THIS IRL Keep the versions concise per controller [ApiVersion("2.0")] [ApiVersion("2.5", Deprecated = true)] [ApiVersion("3.0")] [ApiVersion("3.0-RC")] [Route("api/values")] [Route("api/v{version:apiVersion}/[controller]")] [ApiController] public class Values2Controller : ControllerBase { /// <summary> /// Gets the API Version. /// </summary> /// <returns>The JSON - controller name and version information.</returns> /// <response code="200">The values were successfully retrieved.</response> /// <response code="404">Not found.</response> [HttpGet] public string Get(ApiVersion apiVersion) => $"Controller = {GetType().Name}\nVersion = {apiVersion}"; [HttpGet, MapToApiVersion("3.0-RC")] public string GetV3(ApiVersion apiVersion) => $"Controller = {GetType().Name}\nVersion = {apiVersion}"; } }
namespace MySharp.Logging.Slf4net { public interface ILoggerFactory { Logger GetLogger(string name); } }