content
stringlengths
23
1.05M
using System.Linq.Expressions; using System.Reflection; namespace Phnx { /// <summary> /// Extensions for <see cref="ErrorMessage"/> /// </summary> internal static class ReflectionErrorMessageExtensions { /// <summary> /// An error to describe that the <see cref="Expression"/> does not point to a field or property /// </summary> /// <param name="factory">The error factory that this method extends</param> /// public static string ExpressionIsNotPropertyOrFieldAccess(this ErrorMessage factory) => "Expression is not a field or property access"; /// <summary> /// An error to describe that the <see cref="MemberInfo"/> does not point to a field or property /// </summary> /// <param name="factory">The error factory that this method extends</param> /// public static string MemberIsNotPropertyOrField(this ErrorMessage factory) => "Member is not a field or property access"; } }
using System; using System.IO; namespace Mono.Debugger.Soft { public enum ILExceptionHandlerType { Catch = ExceptionClauseFlags.None, Filter = ExceptionClauseFlags.Filter, Finally = ExceptionClauseFlags.Finally, Fault = ExceptionClauseFlags.Fault, } public class ILExceptionHandler { public int TryOffset { get; internal set; } public int TryLength { get; internal set; } public ILExceptionHandlerType HandlerType { get; internal set; } public int HandlerOffset { get; internal set; } public int HandlerLength { get; internal set;} public int FilterOffset { get; internal set; } public TypeMirror CatchType { get; internal set; } internal ILExceptionHandler (int try_offset, int try_length, ILExceptionHandlerType handler_type, int handler_offset, int handler_length) { TryOffset = try_offset; TryLength = try_length; HandlerType = handler_type; HandlerOffset = handler_offset; HandlerLength = handler_length; } } }
namespace Telerik.Data.Core { /// <summary> /// Base class for <see cref="FilterDescription"/>. /// </summary> internal abstract class FilterDescription : DescriptionBase { } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Lake<T> : IEnumerable<T> { private List<T> collection; public Lake(List<T> elements) { this.collection = elements; } public IEnumerator<T> GetEnumerator() { for(var i = 0; i < this.collection.Count; i++) { yield return this.collection[i]; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } }
using System; using System.IO; using uNet2.Channel; using uNet2.Packet; using uNet2.SocketOperation; using uRAT.CoreClientPlugin.ExtendedSystemInformation.Packets; using uRAT.CoreClientPlugin.Tools; namespace uRAT.CoreClientPlugin.ExtendedSystemInformation.Operations { public class ExtendedInformationOperation : SocketOperationBase { public override int OperationId { get { return 2; } } //TODO: make better public override void PacketReceived(IDataPacket packet, IChannel sender) { if (packet is FetchExtendedInformationPacket) { var returnInfoPacket = new FetchExtendedInformationPacket(); var geoIpInfo = GeoIpHelper.FetchInformation(); returnInfoPacket.CountryCode = geoIpInfo.CountryCode; returnInfoPacket.CountryName = geoIpInfo.CountryName; returnInfoPacket.TimeZone = geoIpInfo.TimeZone; returnInfoPacket.Latitude = geoIpInfo.Latitude; returnInfoPacket.Longitude = geoIpInfo.Longitude; returnInfoPacket.InstalledAntivirus = SystemInformationHelper.FetchInstalledAntivirus(); returnInfoPacket.InstalledFirewall = SystemInformationHelper.FetchInstalledFirewall(); returnInfoPacket.ThisPath = Path.GetDirectoryName(typeof (ExtendedInformationOperation).Assembly.Location); var friendlyName = SystemInformationHelper.Name; var edition = SystemInformationHelper.Edition; var ptrSize = SystemInformationHelper.Bits; var sp = SystemInformationHelper.ServicePack; var operatingSystem = string.Concat(friendlyName, " ", edition, " x", +ptrSize, " ", sp); var computerName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; var isAdmin = SystemInformationHelper.IsAdministrator(); returnInfoPacket.OperatingSystem = operatingSystem; returnInfoPacket.IsAdmin = isAdmin; returnInfoPacket.ComputerName = computerName; returnInfoPacket.InstallDate = new DateTime(); var upTime = SystemInformationHelper.GetSystemRunningTime(); returnInfoPacket.RunningTime = string.Format("{0}h {1}m {2}s", upTime.Hours, upTime.Minutes, upTime.Seconds); SendPacket(returnInfoPacket); } } public override void PacketSent(IDataPacket packet, IChannel targetChannel) { } public override void SequenceFragmentReceived(SequenceFragmentInfo fragmentInfo) { } public override void Disconnected() { } } }
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.Json.DataContractJsonSerializer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.Json.IXmlJsonReaderInitializer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.Json.IXmlJsonWriterInitializer))] [assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.Json.JsonReaderWriterFactory))]
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace UnshieldSharp { internal static class Extensions { /// <summary> /// Read a null-terminated string from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static string ReadNullTerminatedString(this Stream stream) { List<byte> buffer = new List<byte>(); byte b; while ((b = (byte)stream.ReadByte()) != 0x00) { buffer.Add(b); } return Encoding.UTF8.GetString(buffer.ToArray()); } /// <summary> /// Read a string whose length is determined by a 1-byte header from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static string ReadUInt8HeaderedString(this Stream stream) { byte len = stream.ReadUInt8(); byte[] buf = stream.ReadBytes(len); return Encoding.ASCII.GetString(buf, 0, len); } /// <summary> /// Read a string whose length is determined by a 2-byte header from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static string ReadUInt16HeaderedString(this Stream stream) { ushort len = stream.ReadUInt16(); byte[] buf = stream.ReadBytes(len); return Encoding.ASCII.GetString(buf, 0, len); } /// <summary> /// Read a byte from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static byte ReadUInt8(this Stream stream) { byte[] buffer = new byte[1]; stream.Read(buffer, 0, buffer.Length); return buffer[0]; } /// <summary> /// Read a ushort from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static ushort ReadUInt16(this Stream stream) { byte[] buffer = new byte[2]; stream.Read(buffer, 0, buffer.Length); return BitConverter.ToUInt16(buffer, 0); } /// <summary> /// Read a uint from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static uint ReadUInt32(this Stream stream) { byte[] buffer = new byte[4]; stream.Read(buffer, 0, buffer.Length); return BitConverter.ToUInt32(buffer, 0); } /// <summary> /// Read a ulong from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static ulong ReadUInt64(this Stream stream) { byte[] buffer = new byte[8]; stream.Read(buffer, 0, buffer.Length); return BitConverter.ToUInt64(buffer, 0); } /// <summary> /// Read a byte array from the stream /// </summary> /// <param name="stream">Stream to read from</param> public static byte[] ReadBytes(this Stream stream, int count) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } } }
using System; using System.Collections.Generic; namespace Meceqs.AspNetCore.Receiving { public class DefaultMessagePathConvention : IMessagePathConvention { private static readonly List<string> _suffixesToRemove = new List<string> { "Command", "Event", "Message", "Query", "Request" }; public string GetPathForMessage(Type messageType) { Guard.NotNull(messageType, nameof(messageType)); string messageName = messageType.Name; foreach (var suffix in _suffixesToRemove) { if (messageName.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { messageName = messageName.Substring(0, messageName.Length - suffix.Length); break; } } return messageName; } } }
using System.Collections.Generic; namespace Basset.Spotify { public class GetSearchParams : QueryMap { public string Query { get; set; } public string Type { get; set; } public int Limit { get; set; } = 5; public override IDictionary<string, string> CreateQueryMap() { var dict = new Dictionary<string, string>(); dict["limit"] = Limit.ToString(); dict["type"] = Type; dict["q"] = Query; return dict; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pancake.ManagedGeometry.Factory { public static class PolygonFactory { public static Polygon RegularCircumscribed(int side, double circumscribedRadius, Coord2d basePt = default, double baseAngle = 0.0) { var ptArray = new Coord2d[side]; for(var i = 0; i < ptArray.Length; i++) { var ang = Math.PI * 2 / side * i + baseAngle; ptArray[i] = new Coord2d(circumscribedRadius * Math.Cos(ang) + basePt.X, circumscribedRadius * Math.Sin(ang) + basePt.Y); } return Polygon.CreateByRef(ptArray); } public static Polygon RegularInscribed(int side, double inscribedRadius, Coord2d basePt = default, double baseAngle = 0.0) { var radius = inscribedRadius / Math.Cos(Math.PI / side); return RegularCircumscribed(side, radius, basePt, baseAngle); } public const int DEFAULT_CIRCLE_DIVISION = 64; public const int MINIMAL_CIRCLE_DIVISION = 6; public static Polygon TessellatedCircle(double radius, int division = DEFAULT_CIRCLE_DIVISION, Coord2d basePt = default) { return RegularCircumscribed(division, radius, basePt); } public static Polygon TessellatedCircleWithinAbsoluteError(double radius, double error, Coord2d basePt = default) { var delta = Math.Acos(1 - error / radius); if (delta <= 0) // Error is larger compared to the radius. // Happens with fixed error and ultra-small radius. // Use the default tesslation to avoid underflow. return TessellatedCircle(radius, MINIMAL_CIRCLE_DIVISION, basePt); delta = Math.Ceiling(Math.PI / delta); var division = (delta < MINIMAL_CIRCLE_DIVISION) ? MINIMAL_CIRCLE_DIVISION : (int)delta; return RegularCircumscribed(division, radius, basePt); } public static Polygon Rectangle(Coord2d pt1, Coord2d pt2) { var bbox = new BoundingBox2d(pt1, pt2); return bbox.ToPolygon(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Microsoft.Deployment.DotNet.Releases.Tests { public class ProductCollectionTests : TestBase { [Fact] public async Task ItReturnsAllSupportPhases() { var products = await ProductCollection.GetFromFileAsync(@"data\\releases-index.json", false); var supportPhases = products.GetSupportPhases(); Assert.Equal(3, supportPhases.Count()); Assert.Contains(SupportPhase.EOL, supportPhases); Assert.Contains(SupportPhase.LTS, supportPhases); Assert.Contains(SupportPhase.Preview, supportPhases); } [Fact] public async Task ItThrowsIfPathIsNull() { Func<Task> f = async () => await ProductCollection.GetFromFileAsync((string)null, false); var exception = await Assert.ThrowsAsync<ArgumentNullException>(f); } [Fact] public async Task ItThrowsIfPathIsEmpty() { Func<Task> f = async () => await ProductCollection.GetFromFileAsync("", false); var exception = await Assert.ThrowsAsync<ArgumentException>(f); Assert.Equal("Value cannot be empty (path).", exception.Message); } [Fact] public async Task ItThrowsIfFileDoesNotExitAndCannotBeDownloaded() { Func<Task> f = async () => await ProductCollection.GetFromFileAsync("data.json", false); var exception = await Assert.ThrowsAsync<FileNotFoundException>(f); Assert.Equal("Could not find the specified file: data.json", exception.Message); } [Fact] public async Task ItThrowsIfReleasesUriIsNull() { Func<Task> f = async () => await ProductCollection.GetAsync((string)null); var exception = await Assert.ThrowsAsync<ArgumentNullException>(f); } [Fact] public async Task ItThrowsIfReleasesUriIsEmpty() { Func<Task> f = async () => await ProductCollection.GetAsync(""); var exception = await Assert.ThrowsAsync<ArgumentException>(f); Assert.Equal("Value cannot be empty (releasesIndexUri).", exception.Message); } } }
namespace BillsToPay.Domain.Interfaces.Services { using BillsToPay.Domain.Entities; using System; using System.Collections.Generic; using System.Threading.Tasks; public interface IServiceBase<T> : IDisposable where T : EntityBase { Task<T> Add(T entity); Task<T> Update(Guid id, T entity); Task Delete(Guid id); Task<T> Get(Guid id); Task<IEnumerable<T>> List(); } }
using Oddin.OddsFeedSdk.API.Entities.Abstractions; using Oddin.OddsFeedSdk.Common; using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; namespace Oddin.OddsFeedSdk.API.Abstractions { internal interface ISportDataBuilder { Task<IEnumerable<ISport>> BuildSports(IEnumerable<CultureInfo> locales); IEnumerable<ITournament> BuildTournaments(IEnumerable<URN> ids, URN sportId, IEnumerable<CultureInfo> locales); ITournament BuildTournament(URN id, URN sportId, IEnumerable<CultureInfo> locales); ISport BuildSport(URN id, IEnumerable<CultureInfo> locales); IEnumerable<ICompetitor> BuildCompetitors(IEnumerable<URN> ids, IEnumerable<CultureInfo> cultures); IEnumerable<IMatch> BuildMatches(IEnumerable<URN> ids, IEnumerable<CultureInfo> cultures); IMatch BuildMatch(URN id, IEnumerable<CultureInfo> cultures, URN sportId = null); ICompetitor BuildCompetitor(URN id, IEnumerable<CultureInfo> cultures); IFixture BuildFixture(URN id, IEnumerable<CultureInfo> cultures); IMatchStatus BuildMatchStatus(URN id, IEnumerable<CultureInfo> cultures); } }
using System; namespace ALS.Glance.Models.Core.Interfaces { /// <summary> /// Model interface containing metadata about the creation /// </summary> public interface IHaveCreatedMeta { /// <summary> /// The <see cref="DateTime"/> when the model was created /// </summary> DateTimeOffset? CreatedOn { get; set; } /// <summary> /// The identity of who created the model /// </summary> // string CreatedBy { get; set; } } }
// MainViewModel.cs // using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using TwitFaves.Data; namespace TwitFaves { public class MainViewModel : ViewModel { private ITwitterService _twitterService; public MainViewModel(ITwitterService twitterService) { _twitterService = twitterService; } public Async<IEnumerable> GetTweets(string userName) { Async<IEnumerable> asyncTweets = new Async<IEnumerable>(); _twitterService.GetTweets(userName, delegate(IEnumerable<Tweet> tweets) { if (tweets == null) { asyncTweets.Complete(new Exception("Favorites for '" + userName + "' could not be loaded.")); } else { IEnumerable<TweetGroup> groupedTweets = tweets.AsQueryable(). OrderByDescending(t => t.Date). GroupByContiguous<Tweet, int, TweetGroup>( t => TweetGroup.GetDaysGroupValue(t), EqualityComparer<int>.Default, (t, d) => new TweetGroup(t, d)); asyncTweets.Complete(groupedTweets); } }); return asyncTweets; } public Async<Profile> GetProfile(string userName) { Async<Profile> asyncProfile = new Async<Profile>(); _twitterService.GetProfile(userName, delegate(Profile profile) { if (profile == null) { asyncProfile.Complete(new Exception("The profile for '" + userName + "' could not be loaded.")); } else { asyncProfile.Complete(profile); } }); return asyncProfile; } } }
// Prexonite // // Copyright (c) 2014, Christian Klauser // 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. // The names of the 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.Reflection; using System.Reflection.Emit; using Prexonite.Compiler.Cil; using Prexonite.Types; namespace Prexonite.Commands.Core.PartialApplication; public class FlippedFunctionalPartialCallCommand : PCommand, ICilExtension { #region Singleton pattern public static FlippedFunctionalPartialCallCommand Instance { get; } = new(); private FlippedFunctionalPartialCallCommand() { } public const string Alias = @"pa\flip\call"; #endregion public override PValue Run(StackContext sctx, PValue[] args) { if (args.Length < 1) return PType.Null; var closed = new PValue[args.Length - 1]; Array.Copy(args, 1, closed, 0, args.Length - 1); return sctx.CreateNativePValue(new FlippedFunctionalPartialCall(args[0], closed)); } bool ICilExtension.ValidateArguments(CompileTimeValue[] staticArgv, int dynamicArgc) { return true; } private ConstructorInfo _functionPartialCallCtorCache; private ConstructorInfo _functionPartialCallCtor { get { return _functionPartialCallCtorCache ??= typeof (FlippedFunctionalPartialCall).GetConstructor(new[] {typeof (PValue), typeof (PValue[])}); } } void ICilExtension.Implement(CompilerState state, Instruction ins, CompileTimeValue[] staticArgv, int dynamicArgc) { _ImplementCtorCall(state, ins, staticArgv, dynamicArgc, _functionPartialCallCtor); } internal static void _ImplementCtorCall(CompilerState state, Instruction ins, CompileTimeValue[] staticArgv, int dynamicArgc, ConstructorInfo partialCallCtor) { //the call subject is not part of argv var argc = staticArgv.Length + dynamicArgc - 1; if (argc == 0) { //there is no subject, just load null state.EmitLoadNullAsPValue(); return; } //We don't actually need static arguments, just emit the corresponding opcodes foreach (var compileTimeValue in staticArgv) compileTimeValue.EmitLoadAsPValue(state); //pack arguments (including static ones) into the argv array, but exclude subject (the first argument) state.FillArgv(argc); state.ReadArgv(argc); //call constructor of FunctionalPartialCall state.Il.Emit(OpCodes.Newobj, partialCallCtor); //wrap in PValue if (ins.JustEffect) { state.Il.Emit(OpCodes.Pop); } else { state.EmitStoreTemp(0); state.EmitLoadLocal(state.SctxLocal); state.EmitLoadTemp(0); state.EmitVirtualCall(Compiler.Cil.Compiler.CreateNativePValue); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Maticsoft.DBUtility; namespace DAL.PublicService { public class aq_CeleWhere { #region 返回号码归属地 /// <summary> /// 返回商品列表 /// </summary> /// public string GetLocalState(string strNumber) { string strLocal = "归属地未知"; StringBuilder sql = new StringBuilder(); sql.AppendFormat(" SELECT Province_Code + State_Name + Operator_Name AS LocalState FROM AQ_CeleWhere "); sql.AppendFormat(" WHERE Seven_No=@Seven_No"); IList<System.Data.SqlClient.SqlParameter> paras = new List<System.Data.SqlClient.SqlParameter>() { new System.Data.SqlClient.SqlParameter("@Seven_No", strNumber.Substring(0,7)) }; DataSet ds = DbHelperSQL.Query(sql.ToString(), paras.ToArray()); if (null != ds && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { strLocal = ds.Tables[0].Rows[0]["LocalState"].ToString(); } return strLocal; } #endregion #region 返回号码归属省份 /// <summary> /// 返回商品列表 /// </summary> /// public string GetLocalProvinceName(string strNumber) { string strLocal = "归属地未知"; StringBuilder sql = new StringBuilder(); sql.AppendFormat(" SELECT Province_Code LocalState FROM AQ_CeleWhere "); sql.AppendFormat(" WHERE Seven_No=@Seven_No"); IList<System.Data.SqlClient.SqlParameter> paras = new List<System.Data.SqlClient.SqlParameter>() { new System.Data.SqlClient.SqlParameter("@Seven_No", strNumber.Substring(0,7)) }; DataSet ds = DbHelperSQL.Query(sql.ToString(), paras.ToArray()); if (null != ds && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { strLocal = ds.Tables[0].Rows[0]["LocalState"].ToString(); } return strLocal; } #endregion #region 返回号码归属地州 /// <summary> /// 返回商品列表 /// </summary> /// public string GetLocalStateName(string strNumber) { string strLocal = "归属地未知"; StringBuilder sql = new StringBuilder(); sql.AppendFormat(" SELECT State_Name AS LocalState FROM AQ_CeleWhere "); sql.AppendFormat(" WHERE Seven_No=@Seven_No"); IList<System.Data.SqlClient.SqlParameter> paras = new List<System.Data.SqlClient.SqlParameter>() { new System.Data.SqlClient.SqlParameter("@Seven_No", strNumber.Substring(0,7)) }; DataSet ds = DbHelperSQL.Query(sql.ToString(), paras.ToArray()); if (null != ds && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { strLocal = ds.Tables[0].Rows[0]["LocalState"].ToString(); } return strLocal; } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Volo.Abp.BlobStoring; namespace AbpVue.Files.Container { [BlobContainerName("profile-pictures")] public class ProfilePictureContainer { } }
using System; using Windows.UI.Xaml.Data; namespace Flantter.MilkyWay.Views.Converters { public sealed class DoublePlusConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { return value is double ? (double) value + double.Parse((string) parameter) : 0; } public object ConvertBack(object value, Type targetType, object parameter, string language) { return value is double ? (double) value - double.Parse((string) parameter) : 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Beatrice.Configuration { public class DeviceDefinition { public static readonly string[] KnownDeviceTypes = new[] { "action.devices.types.CAMERA", "action.devices.types.DISHWASHER", "action.devices.types.DRYER", "action.devices.types.LIGHT", "action.devices.types.OUTLET", "action.devices.types.SCENE", "action.devices.types.SWITCH", "action.devices.types.THERMOSTAT", "action.devices.types.VACUUM", "action.devices.types.WASHER", }; public string Id { get; set; } public string Name { get; set; } public string[] Nicknames { get; set; } public string RoomHint { get; set; } public string Type { get; set; } public FeatureDefinition[] Features { get; set; } } }
namespace ConnectServer { public class Config { public ushort Port { get; set; } public ushort UdpPort { get; set; } } }
using System.Data.Entity; namespace Tools.database.VersionControl { internal class VersionContext : DBContext { #region Constructors /// <summary> /// Standard-Konstruktor /// </summary> /// <param name="nameOrConnectionString"> /// Der Connection-String in dem die Tabellen fürdie Version angelegt sind /// </param> public VersionContext(string nameOrConnectionString) : base(nameOrConnectionString) { } #endregion Constructors #region Properties public DbSet<DBVersion> DBVersions { get; set; } #endregion Properties #region Methods protected override void OnModelCreating(DbModelBuilder modelBuilder) { new DBVersionMap().MapEntity(modelBuilder); base.OnModelCreating(modelBuilder); } #endregion Methods } }
using System.Collections; using UnityEngine; using UnityEngine.EventSystems; public class ButtonFirstSelected : MonoBehaviour { void OnEnable() { StartCoroutine(SelectButtonRoutine()); } IEnumerator SelectButtonRoutine() { yield return null; EventSystem.current.SetSelectedGameObject(null); EventSystem.current.SetSelectedGameObject(gameObject); } }
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. namespace EdFi.Ods.AdminApp.Management.Azure { public class AzurePerformanceTier : Enumeration<AzurePerformanceTier> { private AzurePerformanceTier(int value, string displayName, string code) : base(value, displayName) { Code = code; } public static bool operator <(AzurePerformanceTier lhs, AzurePerformanceTier rhs) { return lhs.Value < rhs.Value; } public static bool operator >(AzurePerformanceTier lhs, AzurePerformanceTier rhs) { return lhs.Value > rhs.Value; } public string Code { get; } public static readonly AzurePerformanceTier Unknown = new AzurePerformanceTier(-1, "Unknown", ""); public static readonly AzurePerformanceTier Free = new AzurePerformanceTier(0, "Free", "F"); public static readonly AzurePerformanceTier Shared = new AzurePerformanceTier(1, "Shared", "D"); public static readonly AzurePerformanceTier Basic = new AzurePerformanceTier(2, "Basic", "B"); public static readonly AzurePerformanceTier Standard = new AzurePerformanceTier(3, "Standard", "S"); public static readonly AzurePerformanceTier Premium = new AzurePerformanceTier(4, "Premium","P"); } }
namespace PredictMyCarAPp { public class FeatureCounter { public int IDCounter { get; set; } public int IsEmployedCounter { get; set; } public int IsUnEmployedCounter { get; set; } public int IsPensionerCounter { get; set; } public int IsOtherCounter { get; set; } public int HasShiftWorkCounter { get; set; } public int WorksFrom9Till5Counter { get; set; } public int HasPartTimeJobCounter { get; set; } public int HasFullTimeJobCounter { get; set; } public int IsSickCounter { get; set; } public int IsOnVacationCounter { get; set; } public int IsInHomeOfficeCounter { get; set; } public int WorksInTheCompanyCounter { get; set; } public int NeedsCarToCommuteToCompanyCounter { get; set; } public int NeedsCarForShoppingTripCounter { get; set; } public int NeedsCarForOtherTripCounter { get; set; } public void AddPerson(Person person) { if (person == null) { return; } IDCounter++; if (person.IsEmployed) { IsEmployedCounter++; } if (person.IsUnEmployed) { IsUnEmployedCounter++; } if (person.IsPensioner) { IsPensionerCounter++; } if (person.IsOther) { IsOtherCounter++; } if (person.HasShiftWork) { HasShiftWorkCounter++; } if (person.WorksFrom9Till5) { WorksFrom9Till5Counter++; } if (person.HasPartTimeJob) { HasPartTimeJobCounter++; } if (person.HasFullTimeJob) { HasFullTimeJobCounter++; } if (person.IsSick) { IsSickCounter++; } if (person.IsOnVacation) { IsOnVacationCounter++; } if (person.IsInHomeOffice) { IsInHomeOfficeCounter++; } if (person.WorksInTheCompany) { WorksInTheCompanyCounter++; } if (person.NeedsCarToCommuteToCompany) { NeedsCarToCommuteToCompanyCounter++; } if (person.NeedsCarForShoppingTrip) { NeedsCarForShoppingTripCounter++; } if (person.NeedsCarForOtherTrip) { NeedsCarForOtherTripCounter++; } } } }
//! \file ArcAN21.cs //! \date Sun Apr 30 21:04:25 2017 //! \brief KaGuYa script engine animation resource. // // Copyright (C) 2017 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Windows.Media; namespace GameRes.Formats.Kaguya { class PL10Entry : PackedEntry { public int FrameIndex; public int RleStep; } [Export(typeof(ArchiveFormat))] public class PL10Opener : ArchiveFormat { public override string Tag { get { return "PL10/KAGUYA"; } } public override string Description { get { return "KaGuYa script engine animation resource"; } } public override uint Signature { get { return 0x30314C50; } } // 'PL10' public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public PL10Opener() { Extensions = new string[] { "plt" }; } public override ArcFile TryOpen(ArcView file) { uint current_offset = 4; int frame_count = file.View.ReadUInt16(current_offset); if (!IsSaneCount(frame_count)) return null; current_offset += 0x12; string base_name = Path.GetFileNameWithoutExtension(file.Name); var dir = new List<Entry>(frame_count); var info = new ImageMetaData { OffsetX = file.View.ReadInt32(current_offset), OffsetY = file.View.ReadInt32(current_offset + 4), Width = file.View.ReadUInt32(current_offset + 8), Height = file.View.ReadUInt32(current_offset + 12), }; int channels = file.View.ReadInt32(current_offset + 0x10); info.BPP = channels * 8; current_offset += 0x14; var entry = new PL10Entry { FrameIndex = 0, Name = string.Format("{0}#{1:D2}", base_name, 0), Type = "image", Offset = current_offset, Size = (uint)channels * info.Width * info.Height, IsPacked = false, }; dir.Add(entry); current_offset += entry.Size; for (int i = 1; i < frame_count; ++i) { int step = file.View.ReadByte(current_offset++); if (0 == step) return null; uint packed_size = file.View.ReadUInt32(current_offset); uint unpacked_size = (uint)(channels * (info.OffsetX + (int)info.Width) * (info.OffsetY + (int)info.Height)); current_offset += 4; entry = new PL10Entry { FrameIndex = i, Name = string.Format("{0}#{1:D2}", base_name, i), Type = "image", Offset = current_offset, Size = packed_size, UnpackedSize = unpacked_size, IsPacked = true, RleStep = step, }; dir.Add(entry); current_offset += packed_size; } return new PL10Archive(file, this, dir, info); } public override Stream OpenEntry(ArcFile arc, Entry entry) { var anent = entry as PL10Entry; var input = arc.File.CreateStream(entry.Offset, entry.Size); if (null == anent || !anent.IsPacked) return input; using (input) { var data = DecompressRLE(input, anent.UnpackedSize, anent.RleStep); return new BinMemoryStream(data); } } public override IImageDecoder OpenImage(ArcFile arc, Entry entry) { var anarc = (PL10Archive)arc; var anent = (PL10Entry)entry; var pixels = anarc.GetFrame(anent.FrameIndex); return new BitmapDecoder(pixels, anarc.ImageInfo); } internal static byte[] DecompressRLE(IBinaryStream input, uint unpacked_size, int rle_step) { var output = new byte[unpacked_size]; for (int i = 0; i < rle_step; ++i) { byte v1 = input.ReadUInt8(); output[i] = v1; int dst = i + rle_step; while (dst < output.Length) { byte v2 = input.ReadUInt8(); output[dst] = v2; dst += rle_step; if (v2 == v1) { int count = input.ReadUInt8(); if (0 != (count & 0x80)) count = input.ReadUInt8() + ((count & 0x7F) << 8) + 128; while (count-- > 0 && dst < output.Length) { output[dst] = v2; dst += rle_step; } if (dst < output.Length) { v2 = input.ReadUInt8(); output[dst] = v2; dst += rle_step; } } v1 = v2; } } return output; } } class PL10Archive : ArcFile { byte[][] Frames; public readonly ImageMetaData ImageInfo; public PL10Archive(ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, ImageMetaData base_info) : base(arc, impl, dir) { Frames = new byte[dir.Count][]; ImageInfo = base_info; } public byte[] GetFrame(int index) { if (index >= Frames.Length) throw new ArgumentException("index"); if (null != Frames[index]) return Frames[index]; var entry = Dir.ElementAt(index); byte[] pixels; using (var stream = OpenEntry(entry)) { pixels = new byte[stream.Length]; stream.Read(pixels, 0, pixels.Length); } if (index > 0) { var prev_frame = GetFrame(index - 1); for (int i = 0; i < pixels.Length; ++i) pixels[i] += prev_frame[i]; } Frames[index] = pixels; return pixels; } } }
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Your use of this SDK or tool is subject to the Oculus SDK License Agreement, available at https://developer.oculus.com/licenses/oculussdk/ Unless required by applicable law or agreed to in writing, the Utilities SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using UnityEngine; using UnityEngine.Assertions; namespace Oculus.Interaction.Input { public class HandSkeletonOVR : MonoBehaviour, IHandSkeletonProvider { private readonly HandSkeleton[] _skeletons = { null, null }; public HandSkeleton this[Handedness handedness] => _skeletons[(int)handedness]; protected void Awake() { _skeletons[0] = CreateSkeletonData(Handedness.Left); _skeletons[1] = CreateSkeletonData(Handedness.Right); } public static HandSkeleton CreateSkeletonData(Handedness handedness) { HandSkeleton handSkeleton = new HandSkeleton(); // When running in the editor, the call to load the skeleton from OVRPlugin may fail. Use baked skeleton // data. if (handedness == Handedness.Left) { ApplyToSkeleton(OVRSkeletonData.LeftSkeleton, handSkeleton); } else { ApplyToSkeleton(OVRSkeletonData.RightSkeleton, handSkeleton); } return handSkeleton; } private static void ApplyToSkeleton(in OVRPlugin.Skeleton2 ovrSkeleton, HandSkeleton handSkeleton) { int numJoints = handSkeleton.joints.Length; Assert.AreEqual(ovrSkeleton.NumBones, numJoints); for (int i = 0; i < numJoints; ++i) { ref var srcPose = ref ovrSkeleton.Bones[i].Pose; handSkeleton.joints[i] = new HandSkeletonJoint() { pose = new Pose() { position = srcPose.Position.FromFlippedXVector3f(), rotation = srcPose.Orientation.FromFlippedXQuatf() }, parent = ovrSkeleton.Bones[i].ParentBoneIndex }; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace ExecutionsViewer.App.Database.Tables { public class MainFeature { public int Id { get; set; } // [Required] // public Version FirstVersion { get; set; } // public int? FirstVersionId { get; set; } public string FeatureName { get; set; } public virtual ICollection<TestClass> TestClasses { get; set; } = new List<TestClass>(); public virtual ICollection<Version> Versions { get; set; } = new List<Version>(); public virtual ICollection<Feature> Features { get; set; } = new List<Feature>(); public MainFeature() { } public MainFeature(string featureName) { this.FeatureName = featureName; } } }
using System; namespace Elders.Skynet.Core { public interface IMessageContext { string SenderName { get; } Guid ConnectionId { get; } void Respond(IMessage message); } }
using System.Collections.Generic; using FreeSequencer.Tracks; using UnityEngine; namespace FreeSequencer { public enum StartMode { OnStart, OnButton } public enum UpdateType { Normal, Fixed } public class Sequence : MonoBehaviour { public int FrameRate; public int Length; public UpdateType UpdateTypeMode; public List<AnimatedGameObject> Objects = new List<AnimatedGameObject>(); public StartMode StartMode; private void OnStart() { if (StartMode == StartMode.OnStart) { StartSequence(); } } public void StartSequence() { foreach (AnimatedGameObject animatedGameObject in Objects) { foreach (BaseTrack baseTrack in animatedGameObject.Tracks) { var animationTrack = baseTrack as AnimationTrack; if (animationTrack != null) { StartAnimationTrack(animationTrack, animatedGameObject.GameObject); } } } } private void StartAnimationTrack(AnimationTrack animationTrack, GameObject trackGameObject) { var animator = trackGameObject.GetComponent<Animator>(); animator.SetTrigger(this.gameObject.name); } } }
using TechSolutionsLibs.Models; using Microsoft.EntityFrameworkCore; namespace TechSolutionsLibs.Settings.Interface { public interface IEmployeeActivityDBContext { DbSet<EmployeeActivity> EmployeeActivity { get; set; } void SaveChanges(); } }
using System; using System.Collections.Generic; using System.Windows.Forms; namespace T8SuitePro { public partial class frmUpdateAvailable : DevExpress.XtraEditors.XtraForm { /// <summary> /// Required designer variable. /// </summary> public frmUpdateAvailable() { // Required for Windows Form Designer support InitializeComponent(); } private void simpleButton1_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; this.Close(); } private void simpleButton2_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } public void SetVersionNumber(string version) { labelControl2.Text = "Available version: " + version; } private void simpleButton3_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("IEXPLORE.EXE", "http://develop.trionictuning.com/T8Suite/Notes.xml" ); } private void frmUpdateAvailable_Load(object sender, EventArgs e) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Localization { using System.Collections; using System.Globalization; public class CultureInfoComparer : IComparer { private readonly string _compare; /// <summary> /// Initializes a new instance of the <see cref="CultureInfoComparer"/> class. /// </summary> /// <param name="compareBy"></param> public CultureInfoComparer(string compareBy) { this._compare = compareBy; } /// <inheritdoc/> public int Compare(object x, object y) { switch (this._compare.ToUpperInvariant()) { case "ENGLISH": return ((CultureInfo)x).EnglishName.CompareTo(((CultureInfo)y).EnglishName); case "NATIVE": return ((CultureInfo)x).NativeName.CompareTo(((CultureInfo)y).NativeName); default: return ((CultureInfo)x).Name.CompareTo(((CultureInfo)y).Name); } } } }
using System; using System.Collections.Generic; using System.Web; namespace EmpMan.Web.Models { public class AppUserViewModel { public string Id { set; get; } public string FullName { set; get; } public string BirthDay { set; get; } public string Email { set; get; } public string Password { set; get; } public string UserName { set; get; } public string Address { get; set; } public string PhoneNumber { set; get; } public string Avatar { get; set; } public bool Status { get; set; } public string Gender { get; set; } public string AccountCompany { get; set; } /// <summary> /// Code team trực thuộc của user /// </summary> public int? TeamID { get; set; } /// <summary> /// Code phòng ban trực thuộc của user /// </summary> public int? DeptID { get; set; } /// <summary> /// Code công ty trực thuộc của user /// </summary> public int? CompanyID { get; set; } /// <summary> /// Code nhân viên /// </summary> public int? EmpID { get; set; } /// <summary> /// Năm xử lý /// </summary> public int? ProcessingYear { get; set; } public ICollection<string> Roles { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace CATHODE.Misc { /* Handles CATHODE REDS.BIN files */ public class RenderableElementsBIN { private string filepath; public alien_reds_header header; public List<alien_reds_entry> entries; /* Load the file */ public RenderableElementsBIN(string path) { filepath = path; BinaryReader stream = new BinaryReader(File.OpenRead(path)); header = Utilities.Consume<alien_reds_header>(ref stream); entries = Utilities.ConsumeArray<alien_reds_entry>(ref stream, header.EntryCount); stream.Close(); } /* Save the file */ public void Save() { FileStream stream = new FileStream(filepath, FileMode.Create); Utilities.Write<alien_reds_header>(ref stream, header); for (int i = 0; i < entries.Count; i++) Utilities.Write<alien_reds_entry>(ref stream, entries[i]); stream.Close(); } /* Data accessors */ public int EntryCount { get { return entries.Count; } } public List<alien_reds_entry> Entries { get { return entries; } } public alien_reds_entry GetEntry(int i) { return entries[i]; } /* Data setters */ public void SetEntry(int i, alien_reds_entry content) { entries[i] = content; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct alien_reds_header { public int EntryCount; }; [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct alien_reds_entry { public int UnknownZeros0_; public int ModelIndex; public byte UnknownZeroByte0_; public int UnknownZeros1_; public int MaterialLibraryIndex; public byte UnknownZeroByte1_; public int ModelLODIndex; // NOTE: Not sure, looks like it. public byte ModelLODPrimitiveCount; // NOTE: Sure it is primitive count, not sure about the ModelLOD part. }; }
@model SharpCms.Core.DataObjects.Element @{ var headerstyle = Model.Parameters(x => x.Name.Equals("headerstyle")).Value.ToString(); var tagname = "h1"; switch (headerstyle) { case "Header1": tagname = "h1"; break; case "Header2": tagname = "h1"; break; case "Header3": tagname = "h1"; break; } } <@tagname> @Model.Parameters(x => x.Name.Equals("text")).Value </@tagname>
using EmpMan.Data.Infrastructure; using EmpMan.Data.Repositories; using EmpMan.Model.Models; namespace EmpMan.Service { public interface IFeedbackService { Feedback Create(Feedback feedback); void Save(); } public class FeedbackService : IFeedbackService { private IFeedbackRepository _feedbackRepository; private IUnitOfWork _unitOfWork; public FeedbackService(IFeedbackRepository feedbackRepository, IUnitOfWork unitOfWork) { _feedbackRepository = feedbackRepository; _unitOfWork = unitOfWork; } public Feedback Create(Feedback feedback) { return _feedbackRepository.Add(feedback); } public void Save() { _unitOfWork.Commit(); } } }
// Copyright 2015 Xamarin Inc. All rights reserved. using System; namespace CoreFoundation { // note: Make sure names are identical/consistent with NSUrlError.* // they share the same values but there's more entries in CFNetworkErrors public enum CFNetworkErrors { HostNotFound = 1, HostUnknown = 2, SocksUnknownClientVersion = 100, SocksUnsupportedServerVersion = 101, Socks4RequestFailed = 110, Socks4IdentdFailed = 111, Socks4IdConflict = 112, Socks4UnknownStatusCode = 113, Socks5BadState = 120, Socks5BadResponseAddr = 121, Socks5BadCredentials = 122, Socks5UnsupportedNegotiationMethod = 123, Socks5NoAcceptableMethod = 124, FtpUnexpectedStatusCode = 200, HttpAuthenticationTypeUnsupported = 300, HttpBadCredentials = 301, HttpConnectionLost = 302, HttpParseFailure = 303, HttpRedirectionLoopDetected = 304, HttpBadURL = 305, HttpProxyConnectionFailure = 306, HttpBadProxyCredentials = 307, PacFileError = 308, PacFileAuth = 309, HttpsProxyConnectionFailure = 310, HttpsProxyFailureUnexpectedResponseToConnectMethod = 311, // same names as NSUrlError - begin BackgroundSessionInUseByAnotherProcess = -996, BackgroundSessionWasDisconnected = -997, // same names as NSUrlError - end Unknown = -998, // same names as NSUrlError - begin Cancelled = -999, BadURL = -1000, TimedOut = -1001, UnsupportedURL = -1002, CannotFindHost = -1003, CannotConnectToHost = -1004, NetworkConnectionLost = -1005, DNSLookupFailed = -1006, HTTPTooManyRedirects = -1007, ResourceUnavailable = -1008, NotConnectedToInternet = -1009, RedirectToNonExistentLocation = -1010, BadServerResponse = -1011, UserCancelledAuthentication = -1012, UserAuthenticationRequired = -1013, ZeroByteResource = -1014, CannotDecodeRawData = -1015, CannotDecodeContentData = -1016, CannotParseResponse = -1017, InternationalRoamingOff = -1018, CallIsActive = -1019, DataNotAllowed = -1020, RequestBodyStreamExhausted = -1021, AppTransportSecurityRequiresSecureConnection = -1022, FileDoesNotExist = -1100, FileIsDirectory = -1101, NoPermissionsToReadFile = -1102, DataLengthExceedsMaximum = -1103, FileOutsideSafeArea = -1104, SecureConnectionFailed = -1200, ServerCertificateHasBadDate = -1201, ServerCertificateUntrusted = -1202, ServerCertificateHasUnknownRoot = -1203, ServerCertificateNotYetValid = -1204, ClientCertificateRejected = -1205, ClientCertificateRequired = -1206, CannotLoadFromNetwork = -2000, CannotCreateFile = -3000, CannotOpenFile = -3001, CannotCloseFile = -3002, CannotWriteToFile = -3003, CannotRemoveFile = -3004, CannotMoveFile = -3005, DownloadDecodingFailedMidStream = -3006, DownloadDecodingFailedToComplete =-3007, // same names as NSUrlError - end CannotParseCookieFile = -4000, NetServiceUnknown = -72000, NetServiceCollision = -72001, NetServiceNotFound = -72002, NetServiceInProgress = -72003, NetServiceBadArgument = -72004, NetServiceCancel = -72005, NetServiceInvalid = -72006, NetServiceTimeout = -72007, NetServiceDnsServiceFailure = -73000 } }
using System; using System.Collections; using System.Collections.Generic; using Ploeh.AutoFixture.Kernel; using Xunit; using Xunit.Extensions; namespace Ploeh.AutoFixtureUnitTest.Kernel { public class EnumeratorRelayTest { [Fact] public void SutIsISpecimenBuilder() { var sut = new EnumeratorRelay(); Assert.IsAssignableFrom<ISpecimenBuilder>(sut); } [Fact] public void CreateWithNullContextThrows() { var sut = new EnumeratorRelay(); var dummyRequest = new object(); Assert.Throws<ArgumentNullException>(() => sut.Create(dummyRequest, null)); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(1)] [InlineData(typeof(object))] [InlineData(typeof(string))] [InlineData(typeof(int))] [InlineData(typeof(Version))] public void CreateWithNoEnumeratorRequestReturnsCorrectResult( object request) { var sut = new EnumeratorRelay(); var dummyContext = new DelegatingSpecimenContext(); var result = sut.Create(request, dummyContext); var expectedResult = new NoSpecimen(request); Assert.Equal(expectedResult, result); } [Theory] [InlineData(typeof (IEnumerator<object>), typeof (object))] [InlineData(typeof (IEnumerator<string>), typeof (string))] [InlineData(typeof (IEnumerator<int>), typeof (int))] [InlineData(typeof (IEnumerator<Version>), typeof (Version))] public void CreateWithEnumeratorRequestReturnsCorrectResult( Type request, Type itemType) { var expectedRequest = typeof (IEnumerable<>).MakeGenericType(itemType); var enumerable = (IList) Activator.CreateInstance( typeof (List<>).MakeGenericType(itemType)); var context = new DelegatingSpecimenContext { OnResolve = r => expectedRequest.Equals(r) ? (object)enumerable : new NoSpecimen(r) }; var sut = new EnumeratorRelay(); var result = sut.Create(request, context); var expectedResult = enumerable.GetEnumerator(); Assert.Equal(expectedResult, result); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(typeof(object))] [InlineData(typeof(object[]))] public void CreateReturnsCorrectResultWhenContextReturnsNonEnumerableResult( object response) { var request = typeof(IEnumerator<object>); var context = new DelegatingSpecimenContext { OnResolve = r => response }; var sut = new EnumeratorRelay(); var result = sut.Create(request, context); var expectedResult = new NoSpecimen(request); Assert.Equal(expectedResult, result); } } }
using System.Threading.Tasks; using Orckestra.Composer.Search.Parameters; using Orckestra.Composer.Search.ViewModels; namespace Orckestra.Composer.Search.Services { public interface ICategoryBrowsingViewService { Task<CategoryBrowsingViewModel> GetCategoryBrowsingViewModelAsync(GetCategoryBrowsingViewModelParam param); } }
namespace Astrid { public interface IDeviceManager { GraphicsDevice GraphicsDevice { get; } InputDevice InputDevice { get; } AudioDevice AudioDevice { get; } } }
namespace Blog.Services.Data { using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Blog.Data.Common.Repositories; using Blog.Data.Models; using Blog.Services.Data.Contracts; using Blog.Services.Mapping; public class CategoriesService : ICategoriesService { private readonly IDeletableEntityRepository<Category> categoryRepository; public CategoriesService(IDeletableEntityRepository<Category> categoryRepository) { this.categoryRepository = categoryRepository; } public async Task CreateAsync(string name) { var categoryExists = this.categoryRepository .AllAsNoTracking() .Any(x => x.Name == name); if (categoryExists) { return; } var category = new Category { Name = name, }; await this.categoryRepository.AddAsync(category); await this.categoryRepository.SaveChangesAsync(); } public IEnumerable<TModel> GetAll<TModel>() => this.categoryRepository .AllAsNoTracking() .To<TModel>() .ToList(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using BlazorApp.Model; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace BlazorApp.Pages { public partial class Login { [Inject] public ILogger<Login> Logger { get; set; } //[Inject] // public IHttpContextAccessor ContextAccessor { get; set; } public LoginModel LoginModel { get; set; } = new LoginModel(); private async Task HandleValidSubmitAsync() { Logger.LogInformation("Process login..."); if (LoginModel.Username == "demo" && LoginModel.Password == "demo") { var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Demo"), new Claim(ClaimTypes.Email, "ImageApp.freddycoder.com") }; var claimIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); //await ContextAccessor.HttpContext.SignInAsync( // CookieAuthenticationDefaults.AuthenticationScheme, // new ClaimsPrincipal(claimIdentity)); } } } }
using System; using System.Drawing; using System.IO; using System.Reflection; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using Microsoft.Win32; using PluginCore.Managers; namespace PluginCore.Helpers { public class PathHelper { /// <summary> /// Path to the current application directory /// </summary> public static string BaseDir => PluginBase.MainForm.StandaloneMode ? AppDir : UserAppDir; /// <summary> /// Path to the main application directory /// </summary> public static string AppDir => appDir ??= Path.GetDirectoryName(GetAssemblyPath(Assembly.GetExecutingAssembly())); static string appDir; /// <summary> /// Path to the user's application directory /// </summary> public static string UserAppDir => userAppDir ??= Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DistroConfig.DISTRIBUTION_NAME); static string userAppDir; /// <summary> /// Path to the docs directory /// </summary> public static string DocDir => Path.Combine(AppDir, "Docs"); /// <summary> /// Path to the data directory /// </summary> public static string DataDir => Path.Combine(BaseDir, "Data"); /// <summary> /// Path to the snippets directory /// </summary> public static string SnippetDir { get { var path = PluginBase.Settings.CustomSnippetDir; return Directory.Exists(path) ? path : Path.Combine(BaseDir, "Snippets"); } } /// <summary> /// Path to the templates directory /// </summary> public static string TemplateDir { get { var path = PluginBase.Settings.CustomTemplateDir; return Directory.Exists(path) ? path : Path.Combine(BaseDir, "Templates"); } } /// <summary> /// Path to the project templates directory /// </summary> public static string ProjectsDir { get { var path = PluginBase.Settings.CustomProjectsDir; return Directory.Exists(path) ? path : Path.Combine(AppDir, "Projects"); } } /// <summary> /// Path to the settings directory /// </summary> public static string SettingDir => Path.Combine(BaseDir, "Settings"); /// <summary> /// Path to the custom shortcut directory /// </summary> public static string ShortcutsDir => Path.Combine(SettingDir, "Shortcuts"); /// <summary> /// Path to the themes directory /// </summary> public static string ThemesDir => Path.Combine(SettingDir, "Themes"); /// <summary> /// Path to the user project templates directory /// </summary> public static string UserProjectsDir => Path.Combine(UserAppDir, "Projects"); /// <summary> /// Path to the user lirbrary directory /// </summary> public static string UserLibraryDir => Path.Combine(UserAppDir, "Library"); /// <summary> /// Path to the library directory /// </summary> public static string LibraryDir => Path.Combine(AppDir, "Library"); /// <summary> /// Path to the plugin directory /// </summary> public static string PluginDir => Path.Combine(AppDir, "Plugins"); /// <summary> /// Path to the users plugin directory /// </summary> public static string UserPluginDir => Path.Combine(UserAppDir, "Plugins"); /// <summary> /// Path to the tools directory /// </summary> public static string ToolDir => Path.Combine(AppDir, "Tools"); /// <summary> /// Resolve the path to the mm.cfg file /// </summary> public static string ResolveMMConfig() { var homePath = Environment.GetEnvironmentVariable("HOMEPATH"); if (homePath != null) { var homeDrive = Environment.GetEnvironmentVariable("HOMEDRIVE"); if (!string.IsNullOrEmpty(homeDrive)) { try { var tempPath = homeDrive + homePath; var security = Directory.GetAccessControl(tempPath); var rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier)); var currentUser = WindowsIdentity.GetCurrent(); foreach (FileSystemAccessRule rule in rules) { if (currentUser.User.Equals(rule.IdentityReference) && rule.AccessControlType.Equals(AccessControlType.Allow)) { return Path.Combine(tempPath, "mm.cfg"); } } } catch {} // Not working... } } string userProfile = Environment.GetEnvironmentVariable(PlatformHelper.IsRunningOnWindows() ? "USERPROFILE" : "HOME"); return Path.Combine(userProfile, "mm.cfg"); } /// <summary> /// Resolve a path which may be: /// - absolute or /// - relative to base path /// </summary> public static string ResolvePath(string path) => ResolvePath(path, null); /// <summary> /// Resolve a path which may be: /// - absolute or /// - relative to a specified path, or /// - relative to base path /// </summary> public static string? ResolvePath(string path, string relativeTo) { if (string.IsNullOrEmpty(path)) return null; bool isPathNetworked = path.StartsWithOrdinal("\\\\") || path.StartsWithOrdinal("//"); bool isPathAbsSlashed = (path.StartsWith('\\') || path.StartsWith('/')) && !isPathNetworked; if (isPathAbsSlashed) path = Path.GetPathRoot(AppDir) + path.Substring(1); if (Path.IsPathRooted(path) || isPathNetworked) return path; string resolvedPath; if (relativeTo != null) { resolvedPath = Path.Combine(relativeTo, path); if (Directory.Exists(resolvedPath) || File.Exists(resolvedPath)) return resolvedPath; } if (!PluginBase.MainForm.StandaloneMode) { resolvedPath = Path.Combine(UserAppDir, path); if (Directory.Exists(resolvedPath) || File.Exists(resolvedPath)) return resolvedPath; } resolvedPath = Path.Combine(AppDir, path); if (Directory.Exists(resolvedPath) || File.Exists(resolvedPath)) return resolvedPath; return null; } /// <summary> /// Converts a long path to a short representative one using ellipsis if necessary /// </summary> public static string GetCompactPath(string path) { try { if (Win32.ShouldUseWin32()) { const int max = 64; var sb = new StringBuilder(max); Win32.PathCompactPathEx(sb, path, max, 0); return sb.ToString(); } const string pattern = @"^(w+:|)([^]+[^]+).*([^]+[^]+)$"; const string replacement = "$1$2...$3"; if (Regex.IsMatch(path, pattern)) return Regex.Replace(path, pattern, replacement); return path; } catch (Exception ex) { ErrorManager.ShowError(ex); return path; } } /// <summary> /// Converts a long filename to a short one /// </summary> public static string GetShortPathName(string longName) { try { if (Win32.ShouldUseWin32()) { int max = longName.Length + 1; StringBuilder sb = new StringBuilder(max); Win32.GetShortPathName(longName, sb, max); return sb.ToString(); } return longName; // For other platforms } catch (Exception ex) { ErrorManager.ShowError(ex); return longName; } } /// <summary> /// Converts a short filename to a long one /// </summary> public static string GetLongPathName(string shortName) { try { if (Win32.ShouldUseWin32()) { StringBuilder longNameBuffer = new StringBuilder(256); Win32.GetLongPathName(shortName, longNameBuffer, longNameBuffer.Capacity); return longNameBuffer.ToString(); } return shortName; // For other platforms } catch (Exception ex) { ErrorManager.ShowError(ex); return shortName; } } /// <summary> /// Gets the correct physical path from the file system /// </summary> public static string GetPhysicalPathName(string path) { try { if (Win32.ShouldUseWin32()) { int rgflnOut = 0; var r = Win32.SHILCreateFromPath(path, out var ppidl, ref rgflnOut); if (r == 0) { StringBuilder sb = new StringBuilder(260); if (Win32.SHGetPathFromIDList(ppidl, sb)) { char sep = Path.DirectorySeparatorChar; char alt = Path.AltDirectorySeparatorChar; return sb.ToString().Replace(alt, sep); } } } return path; } catch (Exception ex) { ErrorManager.ShowError(ex); return path; } } /// <summary> /// Finds an app from 32-bit or 64-bit program files directories /// </summary> public static string FindFromProgramFiles(string partialPath) { // This return always x86, FlashDevelop is x86 string programFiles = Environment.GetEnvironmentVariable("ProgramFiles"); string toolPath = Path.Combine(programFiles, partialPath); if (File.Exists(toolPath)) return toolPath; if (programFiles.Contains(" (x86)")) // Is the app in x64 program files? { toolPath = Path.Combine(programFiles.Replace(" (x86)", ""), partialPath); if (File.Exists(toolPath)) return toolPath; } return string.Empty; } /// <summary> /// Gets the 32-bit Java install path /// </summary> public static string GetJavaInstallPath() { string javaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\"; using var rk = Registry.LocalMachine.OpenSubKey(javaKey); string currentVersion = rk.GetValue("CurrentVersion").ToString(); using var key = rk.OpenSubKey(currentVersion); return key.GetValue("JavaHome").ToString(); } static string GetAssemblyPath(Assembly assembly) { var codeBase = assembly.CodeBase; if (!codeBase.ToLower().StartsWith(Uri.UriSchemeFile)) return assembly.Location; // Skip over the file:// part var start = Uri.UriSchemeFile.Length + Uri.SchemeDelimiter.Length; if (codeBase[start] == '/') // third slash means a local path { // Handle Windows Drive specifications if (codeBase[start + 2] == ':') ++start; // else leave the last slash so path is absolute } else // It's either a Windows Drive spec or a share { if (codeBase[start + 1] != ':') start -= 2; // Back up to include two slashes } return codeBase.Substring(start); } public class Ellipsis { /// <summary> /// Specifies ellipsis format and alignment. /// </summary> [Flags] public enum EllipsisFormat { /// <summary> /// Text is not modified. /// </summary> None = 0, /// <summary> /// Text is trimmed at the end of the string. An ellipsis (...) is drawn in place of remaining text. /// </summary> End = 1, /// <summary> /// Text is trimmed at the begining of the string. An ellipsis (...) is drawn in place of remaining text. /// </summary> Start = 2, /// <summary> /// Text is trimmed in the middle of the string. An ellipsis (...) is drawn in place of remaining text. /// </summary> Middle = 3, /// <summary> /// Preserve as much as possible of the drive and filename information. Must be combined with alignment information. /// </summary> Path = 4, /// <summary> /// Text is trimmed at a word boundary. Must be combined with alignment information. /// </summary> Word = 8 } /// <summary> /// String used as a place holder for trimmed text. /// </summary> public const string EllipsisChars = "..."; static readonly Regex prevWord = new Regex(@"\W*\w*$", RegexOptions.Compiled); static readonly Regex nextWord = new Regex(@"\w*\W*", RegexOptions.Compiled); /// <summary> /// Truncates a text string to fit within a given width by replacing trimmed text with ellipses. /// </summary> /// <param name="text">String to be trimmed.</param> /// <param name="font">Font to be used to measure the text.</param> /// <param name="proposedWidth">The target width to accomodate the text.</param> /// <param name="options">Format and alignment of ellipsis.</param> /// <returns>This function returns text trimmed to the specified witdh.</returns> public static string Compact(string text, Font font, int proposedWidth, EllipsisFormat options) { if (string.IsNullOrEmpty(text)) return text; // no alignment information if (((EllipsisFormat.Path | EllipsisFormat.Start | EllipsisFormat.End | EllipsisFormat.Middle) & options) == 0) return text; if (font is null) throw new ArgumentNullException(nameof(font)); Size s = TextRenderer.MeasureText(text, font); // control is large enough to display the whole text if (s.Width <= proposedWidth) return text; string pre = ""; string mid = text; string post = ""; bool isPath = (EllipsisFormat.Path & options) != 0; // split path string into <drive><directory><filename> if (isPath) { pre = Path.GetPathRoot(text); mid = Path.GetDirectoryName(text).Substring(pre.Length); post = Path.GetFileName(text); } int len = 0; int seg = mid.Length; string fit = ""; // find the longest string that fits into // the control boundaries using bisection method while (seg > 1) { seg -= seg / 2; int left = len + seg; int right = mid.Length; if (left > right) continue; if ((EllipsisFormat.Middle & options) == EllipsisFormat.Middle) { right -= left / 2; left -= left / 2; } else if ((EllipsisFormat.Start & options) != 0) { right -= left; left = 0; } // trim at a word boundary using regular expressions if ((EllipsisFormat.Word & options) != 0) { if ((EllipsisFormat.End & options) != 0) { left -= prevWord.Match(mid, 0, left).Length; } if ((EllipsisFormat.Start & options) != 0) { right += nextWord.Match(mid, right).Length; } } // build and measure a candidate string with ellipsis string tst = mid.Substring(0, left) + EllipsisChars + mid.Substring(right); // restore path with <drive> and <filename> if (isPath) tst = Path.Combine(pre, tst, post); s = TextRenderer.MeasureText(tst, font); // candidate string fits into control boundaries, try a longer string // stop when seg <= 1 if (s.Width <= proposedWidth) { len += seg; fit = tst; } } if (len == 0) // string can't fit into control { // "path" mode is off, just return ellipsis characters if (!isPath) return EllipsisChars; // <directory> is empty if (mid.Length == 0) { // <drive> is empty, return compacted <filename> if (pre.Length == 0) return Compact(text, font, proposedWidth, options & ~EllipsisFormat.Path); // we compare ellipsis and <drive> to get the shorter string testEllipsis = Path.Combine(EllipsisChars, "."); testEllipsis = testEllipsis.Substring(0, testEllipsis.Length - 1); if (TextRenderer.MeasureText(testEllipsis, font).Width < TextRenderer.MeasureText(pre, font).Width) pre = EllipsisChars; } else { // "C:\...\filename.ext" No need to check for drive, but generates extra check if (pre.Length > 0) { fit = Path.Combine(pre, EllipsisChars, post); s = TextRenderer.MeasureText(fit, font); if (s.Width <= proposedWidth) return fit; } pre = EllipsisChars; } // Try "...\filename.ext" or "c:\filename.ext" fit = Path.Combine(pre, post); s = TextRenderer.MeasureText(fit, font); // if still not fit then return "...\f...e.ext" if (s.Width > proposedWidth) { fit = Path.Combine(pre, Compact(post, font, proposedWidth - TextRenderer.MeasureText(fit.Substring(0, fit.Length - post.Length), font).Width, options & ~EllipsisFormat.Path)); } } return fit; } } } }
// Copyright (c) Oleksandr Viktor (UkrGuru). All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.ComponentModel.DataAnnotations; namespace UkrGuru.WebJobs.Data { public partial class JobQueue : Job { } public partial class JobHistory : Job { } public partial class Job : Rule { [Display(Name = "Id")] public int JobId { get; set; } [Display(Name = "Priority")] public Priorities JobPriority { get; set; } = Priorities.Normal; [DisplayFormat(DataFormatString = "{0:HH:mm:ss.fff}")] public DateTime Created { get; set; } [DisplayFormat(DataFormatString = "{0:HH:mm:ss.fff}")] public DateTime? Started { get; set; } [DisplayFormat(DataFormatString = "{0:HH:mm:ss.fff}")] public DateTime? Finished { get; set; } [Display(Name = "More")] public string JobMore { get; set; } [Display(Name = "Status")] public JobStatus JobStatus { get; set; } } }
using System.Collections.Generic; using UnityEngine; namespace ChatFight { public static class List { public static T GetRandom<T>(this List<T> list) { Debug.Assert(list.IsNullOrEmpty() == false, "List can't be null or empty"); return list[Random.Range(0, list.Count)]; } public static T ExtractRandom<T>(this List<T> list) { Debug.Assert(list.IsNullOrEmpty() == false, "List can't be null or empty"); int index = Random.Range(0, list.Count); T item = list[index]; list.RemoveAt(index); return item; } public static List<T> ExtractRandoms<T>(this List<T> list, int amount) { List<T> newList = new List<T>(); while (newList.Count < amount && list.IsNullOrEmpty() == false) { newList.Add(list.ExtractRandom()); } return newList; } public static List<T> GetDistinctRandoms<T>(this List<T> list, int amount) { Debug.Assert(list.IsNullOrEmpty() == false, "List can't be null or empty"); Debug.Assert(amount >= 0, "Can't request a negative amount: " + amount); List<T> newList = new List<T>(amount); List<T> tempList = new List<T>(list); // Try and get random numbers for (int i = 0; i < amount; ++i) { if (tempList.IsNullOrEmpty()) { break; } // Extract the random item var element = ExtractRandom(tempList); newList.Add(element); } return newList; } public static bool IsNullOrEmpty<T>(this List<T> list) { return (list == null) || (list.Count == 0); } public static void RemoveIfContained<T>(this List<T> list, T item) { Debug.Assert(list != null, "List can't be null"); if (list.Contains(item)) { list.Remove(item); } } public static void RemoveIfContained<T>(this List<T> list, List<T> items) { Debug.Assert(list != null, "List can't be null"); foreach (var item in items) { list.RemoveIfContained(item); } } public static List<T> RemoveDuplicates<T>(this List<T> list) { Debug.Assert(list.IsNullOrEmpty() == false, "List can't be null or empty"); List<T> newList = new List<T>(list.Count); foreach (T item in list) { if (newList.Contains(item) == false) { newList.Add(item); } } return newList; } /// Fisher-Yates Shuffle algorithm adapted from: /// http://www.dotnetperls.com/fisher-yates-shuffle /// public static void Shuffle<T>(this List<T> list) { Debug.Assert(list != null, "List can't be null."); int n = list.Count; if (n > 0) { for (int i = 0; i < n; ++i) { // value returns a random number between 0 and 1. // ... It is equivalent to Math.random() in Java. int r = i + (int)(Random.value * (n - i)); T t = list[r]; list[r] = list[i]; list[i] = t; } } } } }
using Fugu.Common; using Fugu.IO.Records; using System; using System.Runtime.CompilerServices; namespace Fugu.IO { /// <summary> /// Writes fundamental structural elements to an <see cref="IWritableTable"/> instance. /// </summary> public sealed class TableWriter { private readonly IWritableTable _table; public TableWriter(IWritableTable table) { Guard.NotNull(table, nameof(table)); _table = table; } public long Offset { get; private set; } public void WriteTableHeader(long minGeneration, long maxGeneration) { var span = GetSpan(); var structSize = Unsafe.SizeOf<TableHeaderRecord>(); var records = span.NonPortableCast<byte, TableHeaderRecord>(); records[0] = new TableHeaderRecord { Magic = 0xDEADBEEFL, FormatVersionMajor = 0, FormatVersionMinor = 1, MinGeneration = minGeneration, MaxGeneration = maxGeneration, HeaderChecksum = 0, // TODO: Calculate for Magic, Major, Minor, generations }; Offset += structSize; } public void WriteCommitHeader(int count) { var span = GetSpan(); var structSize = Unsafe.SizeOf<CommitHeaderRecord>(); var records = span.NonPortableCast<byte, CommitHeaderRecord>(); records[0] = new CommitHeaderRecord { Tag = TableRecordType.CommitHeader, Count = count }; Offset += structSize; } public void WritePut(byte[] key, int valueLength) { var span = GetSpan(); var structSize = Unsafe.SizeOf<PutRecord>(); var records = span.NonPortableCast<byte, PutRecord>(); records[0] = new PutRecord { Tag = CommitRecordType.Put, KeyLength = (short)key.Length, ValueLength = valueLength }; Offset += structSize; span = span.Slice(structSize); key.CopyTo(span); Offset += key.Length; } public void WriteTombstone(byte[] key) { var span = GetSpan(); var structSize = Unsafe.SizeOf<TombstoneRecord>(); var records = span.NonPortableCast<byte, TombstoneRecord>(); records[0] = new TombstoneRecord { Tag = CommitRecordType.Tombstone, KeyLength = (short)key.Length }; Offset += structSize; span = span.Slice(structSize); key.CopyTo(span); Offset += key.Length; } public void WriteCommitFooter(uint commitChecksum) { var span = GetSpan(); var structSize = Unsafe.SizeOf<CommitFooterRecord>(); var records = span.NonPortableCast<byte, CommitFooterRecord>(); records[0] = new CommitFooterRecord { CommitChecksum = commitChecksum }; Offset += structSize; } public void WriteTableFooter(ulong checksum) { var span = GetSpan(); var structSize = Unsafe.SizeOf<TableFooterRecord>(); var records = span.NonPortableCast<byte, TableFooterRecord>(); records[0] = new TableFooterRecord { Tag = TableRecordType.TableFooter, Checksum = checksum, }; Offset += structSize; } public void Write(ReadOnlySpan<byte> source) { var span = GetSpan(); source.CopyTo(span); Offset += source.Length; } private Span<byte> GetSpan() { return _table.GetSpan(Offset); } } }
using System; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace WinFormsFrameworkApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); // create a plot using the primary X and Y axes var sp1 = formsPlot1.Plot.AddSignal(ScottPlot.DataGen.Sin(51)); sp1.XAxisIndex = 0; sp1.YAxisIndex = 0; // create a plot using the secondary X and Y axes var sp2 = formsPlot1.Plot.AddSignal(ScottPlot.DataGen.Cos(51)); sp2.XAxisIndex = 1; sp2.YAxisIndex = 1; // enable tick marks for secondary axes (hidden by default) formsPlot1.Plot.XAxis2.Ticks(true); formsPlot1.Plot.YAxis2.Ticks(true); // set view limits for the primary axis (default axis index is 0) formsPlot1.Plot.SetInnerViewLimits(20, 40, -.5, .5); formsPlot1.Plot.SetOuterViewLimits(0, 51, -1, 1); // set view limits for the secondary axis formsPlot1.Plot.SetInnerViewLimits(20, 40, -.5, .5, xAxisIndex: 1, yAxisIndex: 1); formsPlot1.Plot.SetOuterViewLimits(0, 51, -1, 1, xAxisIndex: 1, yAxisIndex: 1); formsPlot1.Refresh(); } } }
string longestDigitsPrefix(string inputString) { string pattern = @"^(\d+)"; string numbers = Regex.Match(inputString, pattern).Value; return numbers; }
using System; namespace GeoSpace.Engine { public class LandslideInput { public float SlopeAngle { get; set; } public GeneralRiskLevel GeologyPermeability { get; set; } public SlopeAspect SlopeAspect { get; set; } public int Elevation { get; set; } public int DistanceFromRivers { get; set; } public int DistanceFromFaults { get; set; } public LandUse LandUse { get; set; } } }
namespace Ristorante.Demo { using System.Linq; using Messages; public class Kitchen : IHandle<CookOrder> { private readonly Chef[] _chefs; private readonly IHandle<CookOrder> _loadBalancer; public Kitchen(IPublish publisher, Chef[] chefs) { _chefs = chefs; var queues = _chefs.Select(x => new QueuedHandler<CookOrder>(x)).ToArray(); foreach (var queue in queues) { new ThreadBasedProcessor(queue); } _loadBalancer = new CompetingConsumer<CookOrder>(chefs); } public void Handle(CookOrder message) { _loadBalancer.Handle(message); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text.RegularExpressions; using Examine; using Examine.LuceneEngine.SearchCriteria; using OurUmbraco.Repository.Models; namespace OurUmbraco.Repository.Services { public class DocumentationVersionService { public string GetCurrentMajorVersion() { return ConfigurationManager.AppSettings[Constants.AppSettings.DocumentationCurrentMajorVersion]; } public IEnumerable<DocumentationVersion> GetAlternateDocumentationVersions(Uri uri, bool allVersions = false) { var alternativeDocs = new List<DocumentationVersion>(); // first off we have the path, do we need to strip the version number from the file name var isFolder = uri.ToString().EndsWith("/"); var currentFileName = isFolder ? "index" : uri.Segments.LastOrDefault(); if (currentFileName == null) return alternativeDocs; // does current filename include version number // if it ends with a number preceded by "-v", remove the version suffix // for example -v7, -v8, -v9, or -v10 const string pattern = @"-v([0-9]{0,})$"; var match = Regex.Match(currentFileName, pattern, RegexOptions.IgnoreCase); var isCurrentDocumentationPage = match.Success == false; var pathParts = new List<string>(); var maxSegments = uri.Segments.Length; if (!isCurrentDocumentationPage) { maxSegments -= 1; } for (var i = 0; i < maxSegments; i++) { pathParts.Add(uri.Segments[i]); } var baseFileName = string.Empty; if (isCurrentDocumentationPage) { var positionToStripUpTo = currentFileName.LastIndexOf(".", StringComparison.OrdinalIgnoreCase); if (positionToStripUpTo > -1) { baseFileName = currentFileName.Substring(0, positionToStripUpTo); } else if (isFolder) { baseFileName = "index"; } } else { baseFileName = match.Success ? Regex.Replace(currentFileName, pattern, "") : currentFileName; } var joinedPathParts = string.Join("", pathParts); var currentUrl = joinedPathParts.EndsWith(baseFileName) ? joinedPathParts : joinedPathParts + baseFileName; var currentPageUrl = joinedPathParts.EndsWith(currentFileName) ? joinedPathParts : joinedPathParts + currentFileName; //Now we go off to examine, and search for all entries //with path beginning with currentFilePath var searcher = ExamineManager.Instance.SearchProviderCollection["documentationSearcher"]; var searchCriteria = searcher.CreateSearchCriteria(); //path beginning with current filename var query = searchCriteria.Field("__fullUrl", currentUrl.ToLowerInvariant().MultipleCharacterWildcard()).Compile(); var searchResults = searcher.Search(query); if (searchResults.TotalItemCount <= 1 && !allVersions) return alternativeDocs; var versionInfo = searchResults.Select(result => { var version = new DocumentationVersion(); version.Url = result["url"]; version.Version = CalculateVersionInfo(result["versionFrom"], result["versionTo"]); version.VersionFrom = string.IsNullOrWhiteSpace( result["versionFrom"] ) ? new Semver.SemVersion(0) : Semver.SemVersion.Parse(result["versionFrom"]); version.VersionTo = string.IsNullOrWhiteSpace(result["versionTo"]) ? new Semver.SemVersion(0) : Semver.SemVersion.Parse(result["versionTo"]); version.VersionRemoved = result["versionRemoved"]; version.IsCurrentVersion = string.Equals(result["url"], currentUrl, StringComparison.InvariantCultureIgnoreCase); version.IsCurrentPage = string.Equals(result["url"], currentPageUrl, StringComparison.InvariantCultureIgnoreCase); version.MetaDescription = result["meta.Description"]; version.MetaTitle = result["meta.Title"]; version.NeedsV8Update = result["needsV8Update"]; return version; }) .OrderByDescending(v=> v.VersionFrom) .ThenBy(v=>v.VersionTo); alternativeDocs.AddRange(versionInfo); return alternativeDocs; } private string CalculateVersionInfo(string from, string to) { if (string.IsNullOrWhiteSpace(from) && string.IsNullOrWhiteSpace(to)) { return "current"; } else if (string.IsNullOrWhiteSpace(from)) { return "pre " + to; } else if (string.IsNullOrWhiteSpace(to)) { return from + " +"; } else if (to == from) { return from; } else { return from + " - " + to; } } } }
using System.Collections.Generic; using ShardingCore.Core.Internal.Visitors.GroupBys; using ShardingCore.Core.Internal.Visitors.Selects; namespace ShardingCore.Core.Internal.Visitors { /* * @Author: xjm * @Description: * @Date: Wednesday, 13 January 2021 13:13:45 * @Email: 326308290@qq.com */ internal class ExtraEntry { public ExtraEntry(int? skip, int? take, IEnumerable<PropertyOrder> orders, SelectContext selectContext, GroupByContext groupByContext) { Skip = skip; Take = take; Orders = orders; SelectContext = selectContext; GroupByContext = groupByContext; } public int? Skip { get; } public int? Take { get; } public IEnumerable<PropertyOrder> Orders { get; } public SelectContext SelectContext { get; } public GroupByContext GroupByContext { get; } } }
// LongToken.cs // Script#/Core/ScriptSharp // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Diagnostics; using ScriptSharp.Parser; namespace ScriptSharp.CodeModel { internal sealed class LongToken : LiteralToken { private long _value; internal LongToken(long value, string sourcePath, BufferPosition position) : base(LiteralTokenType.Long, sourcePath, position) { _value = value; } public override object LiteralValue { get { return Value; } } public long Value { get { return _value; } } public override string ToString() { return _value.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using NSubstitute.Core; using NSubstitute.Specs.Infrastructure; using NUnit.Framework; namespace NSubstitute.Specs { public class CallActionsSpecs { public class When_finding_matching_actions_for_a_call : ConcernFor<CallActions> { private Action<CallInfo> _firstMatchingAction; private Action<CallInfo> _secondMatchingAction; private Action<CallInfo> _nonMatchingAction; private ICallSpecification _matchingCallSpec; private ICallSpecification _nonMatchingCallSpec; private ICall _call; private IEnumerable<Action<CallInfo>> _result; [Test] public void Should_return_all_actions_that_match_call_specification() { var results = _result.ToArray(); Assert.That(results.Length, Is.EqualTo(2), "Expected two matching actions"); Assert.That(results[0], Is.SameAs(_firstMatchingAction)); Assert.That(results[1], Is.SameAs(_secondMatchingAction)); } public override void Because() { sut.Add(_matchingCallSpec, _firstMatchingAction); sut.Add(_nonMatchingCallSpec, _nonMatchingAction); sut.Add(_matchingCallSpec, _secondMatchingAction); _result = sut.MatchingActions(_call); } public override void Context() { _call = mock<ICall>(); _matchingCallSpec = mock<ICallSpecification>(); _matchingCallSpec.stub(x => x.IsSatisfiedBy(_call)).Return(true); _nonMatchingCallSpec = mock<ICallSpecification>(); _firstMatchingAction = x => { }; _secondMatchingAction = x => { }; _nonMatchingAction = x => { }; } public override CallActions CreateSubjectUnderTest() { return new CallActions(); } } } }
using System; using JetBrains.Annotations; namespace Framework.Validation { /// <summary> /// Legacy /// </summary> public class ValidationException : ValidationExceptionBase { [StringFormatMethod("format")] public ValidationException(string format, params object[] args) : this(string.Format(format, args)) { } public ValidationException(string message) : base(message) { } public ValidationException(string message, Exception inner) : base(message, inner) { } } }
// Copyright (c) 2020 Sergio Aquilini // This code is licensed under MIT license (see LICENSE file for details) using System.Threading.Tasks; using Silverback.Messaging.Broker.Behaviors; using Silverback.Messaging.Messages; using Silverback.Messaging.Serialization; using Silverback.Util; namespace Silverback.Messaging.BinaryFiles { /// <summary> /// Switches to the <see cref="BinaryFileMessageSerializer" /> if the message being consumed is a binary /// message (according to the x-message-type header). /// </summary> public class BinaryFileHandlerConsumerBehavior : IConsumerBehavior { /// <inheritdoc cref="ISorted.SortIndex" /> public int SortIndex => BrokerBehaviorsSortIndexes.Consumer.BinaryFileHandler; /// <inheritdoc cref="IConsumerBehavior.HandleAsync" /> public async Task HandleAsync( ConsumerPipelineContext context, ConsumerBehaviorHandler next) { Check.NotNull(context, nameof(context)); Check.NotNull(next, nameof(next)); context.Envelope = await HandleAsync(context.Envelope).ConfigureAwait(false); await next(context).ConfigureAwait(false); } private static async Task<IRawInboundEnvelope> HandleAsync(IRawInboundEnvelope envelope) { if (envelope.Endpoint.Serializer is BinaryFileMessageSerializer || envelope.Endpoint.Serializer.GetType().IsGenericType && envelope.Endpoint.Serializer.GetType().GetGenericTypeDefinition() == typeof(BinaryFileMessageSerializer<>)) { return envelope; } var messageType = SerializationHelper.GetTypeFromHeaders(envelope.Headers, false); if (messageType == null || !typeof(IBinaryFileMessage).IsAssignableFrom(messageType)) return envelope; var (deserializedObject, deserializedType) = await BinaryFileMessageSerializer.Default.DeserializeAsync( envelope.RawMessage, envelope.Headers, MessageSerializationContext.Empty) .ConfigureAwait(false); // Create typed message for easier specific subscription return SerializationHelper.CreateTypedInboundEnvelope(envelope, deserializedObject, deserializedType); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace EasyCommands.Tests.ScriptTests { [TestClass] public class SimpleRandomTests { [TestMethod] public void RandomNumber() { using (var test = new ScriptTest(@"print ""Next Random: "" + rand 10")) { test.MockNextBoundedRandoms(10, 3); test.RunOnce(); Assert.AreEqual("Next Random: 3", test.Logger[0]); } } [TestMethod] public void RandNumber() { using (var test = new ScriptTest(@"print ""Next Random: "" + rand 10")) { test.MockNextBoundedRandoms(10, 6); test.RunOnce(); Assert.AreEqual("Next Random: 6", test.Logger[0]); } } [TestMethod] public void RandomItemFromList() { using (var test = new ScriptTest(@"print ""Next Random: "" + rand [one, two, three, four, five]")) { test.MockNextBoundedRandoms(5, 3); test.RunOnce(); Assert.AreEqual("Next Random: four", test.Logger[0]); } } } }
using System; using Csla.Serialization; namespace LearnLanguages.DataAccess.Exceptions { [Serializable] public class GetUserFailedException : Exception { public GetUserFailedException(string username) : base(string.Format(DalResources.ErrorMsgUsernameNotFoundException, username)) { Username = username; } public GetUserFailedException(string errorMsg, string username) : base(errorMsg) { Username = username; } public GetUserFailedException(Exception innerException, string username) : base(DalResources.ErrorMsgUsernameNotFoundException, innerException) { Username = username; } public string Username { get; private set; } } }
/* © Siemens AG, 2020 Author: Michael Dyck (m.dyck@gmx.net) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.Events; public class ChooseParameterBase : ScriptableObject { public UnityEvent SaveEvent; public bool settingsSaved = false; public Dictionary<string, int> arrayVariableSizes = new Dictionary<string, int>(); // PROPERTIES public GameObject GameObjectOfInterest { get; set; } public string[] ComponentOptionStrings { get; set; } public Component[] ComponentOptions { get; set; } public string[] VariableOptionStrings { get; set; } public Type[] TypesOfVariableOptions { get; set; } public Component SelectedComponent { get; set; } public Type SelectedVariableType { get; set; } public string SelectedVariable { get; set; } public ParameterHandler ParameterHandlerObject { get; set; } public virtual void OnEnable() { if (SaveEvent == null) SaveEvent = new UnityEvent(); } private Component[] GetSelectedGameObjectScriptComponents(GameObject _evalGameObject) { return _evalGameObject.GetComponents<MonoBehaviour>(); } public void HandleGameObjectComponents() { Component[] components = GetSelectedGameObjectScriptComponents(GameObjectOfInterest); int numOptions = components.Length; ComponentOptionStrings = new string[numOptions]; ComponentOptions = new Component[numOptions]; // fill component options for (int i = 0; i < numOptions; i++) { ComponentOptions[i] = components[i]; ComponentOptionStrings[i] = components[i].GetType().ToString(); } } public void HandleComponentProperties() { const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; FieldInfo[] fields = SelectedComponent.GetType().GetFields(flags); PropertyInfo[] properties = SelectedComponent.GetType().GetProperties(flags); int numFields = fields.Length + properties.Length; VariableOptionStrings = new string[numFields]; TypesOfVariableOptions = new Type[numFields]; for (int i = 0; i < numFields; i++) { if (i < fields.Length) { TypesOfVariableOptions[i] = fields[i].FieldType; VariableOptionStrings[i] = fields[i].Name; } else { TypesOfVariableOptions[i] = properties[i - fields.Length].PropertyType; VariableOptionStrings[i] = properties[i - fields.Length].Name; } } } public void SaveSelectedVariableOptions() { settingsSaved = true; SaveEvent.Invoke(); } }
using Aspose.Cells.Common.Models; using Aspose.Cells.Common.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.IO.Compression; using Newtonsoft.Json.Serialization; namespace Aspose.Cells.Common.Config { public static class ServiceCollectionExtension { public static void AddSharedConfigParams(this IServiceCollection services) { services.AddScoped<IStorageService>(f => new AwsStorageService( new AwsConfig { RegionEndpoint = Configuration.RegionEndpoint, ServiceUrl = Configuration.RegionEndpoint, ForcePathStyle = true, AccessKeyId = Configuration.AccessKeyId, SecretAccessKey = Configuration.SecretAccessKey }, Configuration.Bucket, f.GetService<ILogger<AwsStorageService>>() )); services.Configure<IISServerOptions>(options => { options.MaxRequestBodySize = ViewModel.MaximumUploadFileSize; }); services.Configure<FormOptions>(x => { x.ValueLengthLimit = int.MaxValue; x.MultipartBodyLengthLimit = ViewModel.MaximumUploadFileSize; x.MultipartHeadersLengthLimit = int.MaxValue; }); services.Configure<KestrelServerOptions>(options => { options.Limits.MaxRequestBodySize = ViewModel.MaximumUploadFileSize; }); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromSeconds(10); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); services.AddControllersWithViews() .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore ); services.AddRazorPages().AddRazorRuntimeCompilation(); services.Configure<GzipCompressionProviderOptions>(options => { options.Level = CompressionLevel.Fastest; }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entity; using Data; using Data.Implementation; namespace Business.Implementation { public class TipoCuentaService : ITipoCuentaService { private ITipoCuentaRepository objTipoCuentaRepository = new TipoCuentaRepository(); public bool Delete(int? id) { return objTipoCuentaRepository.Delete(id); } public TipoCuenta FindByID(int? id) { return objTipoCuentaRepository.FindByID(id); } public List<TipoCuenta> FindAll() { return objTipoCuentaRepository.FindAll(); } public bool Insert(TipoCuenta t) { return objTipoCuentaRepository.Insert(t); } public bool Update(TipoCuenta t) { return objTipoCuentaRepository.Update(t); } } }
namespace CSharp6AndRefactoring { using System; public class Sample3Version1 { public event Action<string> onNewMessage; public void SaySomething(string message) { if(onNewMessage != null) { onNewMessage(message); } } } public class Sample3Version2 { public event Action<string> onNewMessage; public void SaySomething(string message) => onNewMessage?.Invoke(message); } }
using UnityEngine; using System.Collections; public abstract class Interactable : Item { protected GameState gameState; public bool _interactable = true; public bool interactable { get { return _interactable; } protected set { _interactable = value; } } public virtual void Start() { gameState = GameObject.Find("GameState").GetComponent<GameState>(); } public bool Interact(GameObject interactor) { if (interactable) { Debug.Log("Using " + interactor + " to interact with " + this.gameObject); InteractAction(interactor); } return interactable; } protected abstract void InteractAction(GameObject interactor); }
using System; using Rg.Plugins.Popup.Extensions; using Xamarin.Forms; namespace ColorPickerDemo { public partial class MainPage : ContentPage { readonly ColorPickerPopup _circlePickerPopup; readonly ColorWheelPopup _wheelPickerPopup; public MainPage() { InitializeComponent(); _circlePickerPopup = new ColorPickerPopup(); _circlePickerPopup.ColorChanged += CircleColorPickerOnColorChanged; _wheelPickerPopup = new ColorWheelPopup(); _wheelPickerPopup.ColorChanged += WheelColorPickerOnColorChanged; } async void OnCirclePickerClicked(object sender, EventArgs e) { CirclePickerButton.IsEnabled = false; await Navigation.PushPopupAsync(_circlePickerPopup); } async void OnWheelPickerClicked(object sender, EventArgs e) { WheelPickerButton.IsEnabled = false; await Navigation.PushPopupAsync(_wheelPickerPopup); } void CircleColorPickerOnColorChanged(object sender, ColorChangedEventArgs args) { BoxView.Color = args.Color; _circlePickerPopup.IsEnabled = true; } void WheelColorPickerOnColorChanged(object sender, ColorChangedEventArgs args) { BoxView.Color = args.Color; _wheelPickerPopup.IsEnabled = true; } } }
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Cactus.Fileserver.Core.Model; namespace Cactus.Fileserver.Core.Config { public interface IFileserverConfig<T> { string Path { get; } Func<IFileStorageService> FileStorage { get; } Func<Func<T, HttpContent, IFileInfo, Task<MetaInfo>>> NewFilePipeline { get; } Func<Func<T, Stream, Task>> GetFilePipeline { get; } } }
using System.Collections; using UnityEngine; using UnityEngine.UI; namespace Scene.Lobby { public class BaseCanvas : MonoBehaviour { [SerializeField] private Text version; [SerializeField] private Text ping; [SerializeField] private CanvasGroup loading; [SerializeField] private Image spinner; [SerializeField] private Image mask; [Space] [SerializeField] private AudioSource music; [Space] [SerializeField] private float fadeInTime; [SerializeField] private float fadeOutTime; [SerializeField] private float iconTurnSpeed; private bool isLoading; private bool busy; void Awake () { fadeInTime = 1 / fadeInTime; fadeOutTime = 1 / fadeOutTime; version.text = "Version\n" + Reference.GameVersion; } void Start () { StopAllCoroutines (); StartCoroutine (MaskOff ()); } void Update () { if (PhotonNetwork.connected) ping.text = "Ping\n" + PhotonNetwork.GetPing (); else ping.text = ""; spinner.rectTransform.Rotate (Vector3.forward * iconTurnSpeed * Time.deltaTime); if (NetworkLobby.isConnecting () && !isLoading) {//for loading StartCoroutine (EnableLoadThread ()); } else if (!NetworkLobby.isConnecting () && isLoading) { StartCoroutine (DisableLoadThread ()); } if (NetworkLobby.isConnecting () & !busy) {//for mask StartCoroutine (MaskOn ()); } } private IEnumerator EnableLoadThread () { float t = 0; isLoading = true; Util.UI.SetAlpha (loading, 0); while (true) { t += Time.deltaTime * fadeInTime; if (t < 1) { float a = Mathf.Lerp (0, 1, Util.LerpType.SmoothStep (t)); Util.UI.SetAlpha (loading, a); yield return null; } else { Util.UI.SetAlpha (loading, 1); break; } } } private IEnumerator DisableLoadThread () { float t = 0; isLoading = false; Util.UI.SetAlpha (loading, 1); while (true) { t += Time.deltaTime * fadeOutTime; if (t < 1) { float a = Mathf.Lerp (1, 0, Util.LerpType.SmoothStep (t)); Util.UI.SetAlpha (loading, a); yield return null; } else { Util.UI.SetAlpha (loading, 0); break; } } } private IEnumerator MaskOff () { float t = 0; while (true) { t += Time.deltaTime * fadeInTime; if (t < 1) { float a = Mathf.Lerp (1, 0, 1f - Util.LerpType.Coserp (t)); Util.UI.SetAlpha (mask, a); Util.Sound.SetVolume (music, 1 - a); yield return null; } else { Util.UI.SetAlpha (mask, 0); break; } } } private IEnumerator MaskOn () { busy = true; float t = 0; while (true) { t += Time.deltaTime * fadeOutTime; if (t < 1) { float a = Mathf.Lerp (0, 1, 1f - Util.LerpType.Sinerp (t)); Util.UI.SetAlpha (mask, a); Util.Sound.SetVolume (music, 1 - a); yield return null; } else { Util.UI.SetAlpha (mask, 1); break; } } } } }
namespace Nexweron.Core.MSK { using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(MSKControllerBase))] abstract public class MSKComponentBase : MonoBehaviour { protected static bool SetStruct<T>(ref T currentValue, T newValue) where T : struct { if (!currentValue.Equals(newValue)) { currentValue = newValue; return true; } return false; } protected static bool SetClass<T>(ref T currentValue, T newValue) where T : class { if (!currentValue.Equals(newValue)) { currentValue = newValue; return true; } return false; } [SerializeField, Tooltip("Component Shader")] protected Shader _shader = null; public Shader shader { get { return _shader; } set { if (SetClass(ref _shader, value)) { _shader = value; UpdateShader(); } } } protected Material _shaderMaterial; protected MSKControllerBase _mskController; private bool _inited = false; protected virtual void Awake() { CheckInit(); UpdateShader(); } protected virtual void Start() { } public void Init(MSKControllerBase mskController) { if (_mskController != mskController) { _mskController = mskController; _inited = _mskController != null; } } protected void CheckInit() { if (!_inited) { Init(GetComponent<MSKControllerBase>()); } } protected void UpdateShader() { var availableShaders = GetAvailableShaders(); if (_shader == null || !availableShaders.Contains(shader.name)) { _shader = Shader.Find(availableShaders[0]); } UpdateShaderMaterial(); } public virtual List<string> GetAvailableShaders() { return null; } public virtual void UpdateShaderProperties() { // } public virtual void UpdateShaderMaterial() { if (_shader != null) { if (_shaderMaterial != null && _shaderMaterial.shader != _shader) { _shaderMaterial.shader = _shader; } else { _shaderMaterial = new Material(_shader); _shaderMaterial.hideFlags = HideFlags.DontSave; } UpdateShaderProperties(); } else { UpdateShader(); } } public abstract void UpdateSourceTexture(); public virtual RenderTexture GetRender(Texture rt_src) { return null; } protected virtual void OnDestroy() { if (_shaderMaterial != null) { DestroyImmediate(_shaderMaterial); } _inited = false; } } }
// System Namespaces // Application Namespaces // Library Namespaces using EasyConsole; namespace CLI.Utility.Extensions { public static class MenuPageExtensions { public static void InputOptions(this MenuPage menuPage, EasyConsole.Menu menu) { var page = (Page)menuPage; if (page.Program.NavigationEnabled && !menu.Contains("Go back")) { menu.Add("Go back", delegate { page.Program.NavigateBack(); }); } menu.Display(); } } }
using System.Collections; using System.Collections.Generic; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Jobs; public class Manager : Patterns.Singleton<Manager> { #region Manager stuff public int MAX_BOIDS = 10000; public GameObject PrefabBoid; public float MaxSpeed = 5.0f; public int BoidCount = 1; public int BoidIncrementCount = 1; public float MinX = -100.0f; public float MaxX = 100.0f; public float MinY = -100.0f; public float MaxY = 100.0f; public UI_Job UiJob; [SerializeField] GameObject[] PrefabObstacles; public bool useRandomRule = true; public bool useCohesionRule = true; public bool useAlignmentRule = true; public bool useSeparationRule = true; public float TickDurationRandom = 1.0f; public float TickDuration = 0.1f; public float weightCohesion = 1.0f; public float weightAlignment = 1.0f; public float weightSeparation = 1.0f; public float weightAvoidObstacles = 1.0f; public float avoidanceRadiusMultiplier = 1.5f; public float visibility = 20.0f; public float separationDistance = 2.0f; public int NumBatches = 1024; #endregion TransformAccessArray transforms; MovementJob movementJob; JobHandle movementJobHandle; RandomMovementJob randomMovementJob; JobHandle randomMovementJobHandle; [NativeDisableContainerSafetyRestriction] NativeArray<Vector3> targetDirections; [NativeDisableContainerSafetyRestriction] NativeArray<Obstacle2> obstacles; NativeArray<Boid2> lastFrameData; NativeArray<Boid2> dbl_buffer_lastFrameData; FlockingJob jobFlocking; JobHandle handleFlocking; [NativeDisableContainerSafetyRestriction] [ReadOnly] NativeArray<Vector3> tgv_flocking; int obstaclesCount = 0; System.Random mSeed; private void OnDisable() { movementJobHandle.Complete(); randomMovementJobHandle.Complete(); handleFlocking.Complete(); transforms.Dispose(); targetDirections.Dispose(); obstacles.Dispose(); tgv_flocking.Dispose(); lastFrameData.Dispose(); dbl_buffer_lastFrameData.Dispose(); } private void Start() { mSeed = new System.Random(); transforms = new TransformAccessArray(0, -1); targetDirections = new NativeArray<Vector3>(MAX_BOIDS, Allocator.Persistent); obstacles = new NativeArray<Obstacle2>(50, Allocator.Persistent); tgv_flocking = new NativeArray<Vector3>(MAX_BOIDS, Allocator.Persistent); lastFrameData = new NativeArray<Boid2>(MAX_BOIDS, Allocator.Persistent); dbl_buffer_lastFrameData = new NativeArray<Boid2>(MAX_BOIDS, Allocator.Persistent); AddBoids(BoidCount); StartCoroutine(Coroutine_Random()); StartCoroutine(Coroutine_Alignment()); } void AddBoids(int count) { movementJobHandle.Complete(); randomMovementJobHandle.Complete(); transforms.capacity = transforms.length + count; for (int i = 0; i < count; ++i) { float x = Random.Range(MinX, MaxX); float y = Random.Range(MinY, MaxY); GameObject obj = Instantiate(PrefabBoid, new Vector3(x, y, 0.0f), Quaternion.identity); transforms.Add(obj.transform); lastFrameData[BoidCount + i] = new Boid2() { pos = new Vector3(x, y, 0.0f), direction = Vector3.zero, speed = MaxSpeed }; } BoidCount = transforms.length; UiJob.SetBoidCount(BoidCount); } void AddObstacle() { movementJobHandle.Complete(); randomMovementJobHandle.Complete(); Vector2 pt = new Vector2( Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y); GameObject obj = Instantiate(PrefabObstacles[Random.Range(0, PrefabObstacles.Length)]); CircleCollider2D coll = obj.GetComponent<CircleCollider2D>(); float radius = 10.0f; if(coll) { radius = coll.radius; } obj.name = "Obstacle_" + obstaclesCount; obj.transform.position = new Vector3(pt.x, pt.y, 0.0f); obstacles[obstaclesCount] = new Obstacle2() { position = new Vector3(pt.x, pt.y, 0.0f), avoidanceRadius = radius * avoidanceRadiusMultiplier }; obstaclesCount++; } void HandleInputs() { if (EventSystem.current.IsPointerOverGameObject() || enabled == false) { return; } if (Input.GetKeyDown(KeyCode.Space)) { AddBoids(BoidIncrementCount); } if (Input.GetMouseButtonDown(2)) { AddObstacle(); } } private void Update() { movementJobHandle.Complete(); randomMovementJobHandle.Complete(); dbl_buffer_lastFrameData.CopyFrom(lastFrameData); HandleInputs(); movementJob = new MovementJob() { MaxSpeed = MaxSpeed, speed = MaxSpeed, deltaTime = Time.deltaTime, targetDirection = targetDirections, targetDirection_Flocking = tgv_flocking, rotationSpeed = 100.0f, MinX = MinX, MaxX = MaxX, MinY = MinY, MaxY = MaxY, bounceWall = true, obstacles = obstacles, obstaclesCount = obstaclesCount, weightAvoidObstacles = weightAvoidObstacles, lastFrameData = lastFrameData }; movementJobHandle = movementJob.Schedule(transforms); JobHandle.ScheduleBatchedJobs(); } IEnumerator Coroutine_Alignment() { while (true) { if (useAlignmentRule) { if (handleFlocking.IsCompleted) { jobFlocking = new FlockingJob() { useAlignmentRule = useAlignmentRule, useCohesionRule = useCohesionRule, useSeparationRule = useSeparationRule, visibility = visibility, weightSeparation = weightSeparation, separationDistance = separationDistance, boidsCount = transforms.length, weightAlignment = weightAlignment, lastFrameData = dbl_buffer_lastFrameData, targetVelocities = tgv_flocking, weightCohesion = weightCohesion }; handleFlocking = jobFlocking.Schedule(transforms.length, NumBatches); } } yield return new WaitForSeconds(TickDuration); } } IEnumerator Coroutine_Random() { while (true) { if (useRandomRule) { randomMovementJob = new RandomMovementJob() { result = targetDirections, weightRandom = 1.0f, rnd = new Unity.Mathematics.Random((uint)mSeed.Next()) }; randomMovementJobHandle = randomMovementJob.Schedule(transforms); } yield return new WaitForSeconds(TickDurationRandom); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using XELibrary; namespace GameStateDemo { public sealed class StartMenuState : BaseGameState, IStartMenuState { private Texture2D texture; public StartMenuState(Game game) : base(game) { game.Services.AddService(typeof(IStartMenuState), this); } public override void Update(GameTime gameTime) { if (Input.WasPressed(0, Buttons.Back, Keys.Escape)) { //go back to title / intro screen GameManager.ChangeState(OurGame.TitleIntroState.Value); } if (Input.WasPressed(0, Buttons.Start, Keys.Enter)) { //got here from our playing state,just pop myself off the stack if (GameManager.ContainsState(OurGame.PlayingState.Value)) GameManager.PopState(); else //starting game, queue first level GameManager.ChangeState(OurGame.StartLevelState.Value); } //options menu if (Input.WasPressed(0, Buttons.Y, Keys.O)) GameManager.PushState(OurGame.OptionsMenuState.Value); base.Update(gameTime); } public override void Draw(GameTime gameTime) { Vector2 pos = new Vector2(TitleSafeArea.Left, TitleSafeArea.Top); OurGame.SpriteBatch.Draw(texture, pos, Color.White); base.Draw(gameTime); } protected override void StateChanged(object sender, EventArgs e) { base.StateChanged(sender, e); if (GameManager.State != this.Value) Visible = true; } protected override void LoadContent() { texture = Content.Load<Texture2D>(@"Textures\startMenu"); } } }
using UnityEngine; using UnityEditor; public class FPSTrackerInit { [MenuItem("Tools/Fps Tracker/Initialization")] static void Init() { GameObject handler = new GameObject(); handler.AddComponent(typeof(FPSTracker)); } }
#region using using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Threading; #endregion namespace ProcessControlStandards.OPC.TestTool { public class WorkerThread : IDisposable { public class Task { public object Argument { get; set; } public Action<Task, DoWorkEventArgs> Do { get; set; } public Action<Task, RunWorkerCompletedEventArgs> Completed { get; set; } } public WorkerThread(string name) { synchronizationContext = SynchronizationContext.Current; newItemEvent = new AutoResetEvent(false); exitThreadEvent = new ManualResetEvent(false); eventArray = new WaitHandle[2]; eventArray[0] = newItemEvent; eventArray[1] = exitThreadEvent; thread = new Thread(ThreadRun) { Name = name }; thread.Start(); } public void Post(Task task) { lock (((ICollection)queue).SyncRoot) { queue.Add(task); newItemEvent.Set(); } } public void Dispose() { exitThreadEvent.Set(); thread.Join(); } private void ThreadRun() { while (WaitHandle.WaitAny(eventArray) != 1) { DoTasks(); } DoTasks(); } private void DoTasks() { List<Task> tasks; lock (((ICollection) queue).SyncRoot) { tasks = new List<Task>(queue); queue.Clear(); } foreach(var task in tasks) DoTask(task); } private void DoTask(Task task) { RunWorkerCompletedEventArgs resultArgs; try { var args = new DoWorkEventArgs(task.Argument); task.Do(task, args); resultArgs = new RunWorkerCompletedEventArgs(args.Result, null, false); } catch (Exception e) { resultArgs = new RunWorkerCompletedEventArgs(null, e, false); } if (task.Completed != null) synchronizationContext.Post(state => task.Completed(task, resultArgs), resultArgs); } private readonly SynchronizationContext synchronizationContext; private readonly EventWaitHandle newItemEvent; private readonly EventWaitHandle exitThreadEvent; private readonly WaitHandle[] eventArray; private readonly List<Task> queue = new List<Task>(); private readonly Thread thread; } }
using System.Runtime.CompilerServices; using ApprovalTests; using NUnit.Framework; using Shouldly; using TestStack.BDDfy.Reporters; namespace TestStack.BDDfy.Tests.Scanner.FluentScanner { [TestFixture] public class FluentWithExamples { [Test] public void FluentCanBeUsedWithExamples() { var story = this .Given(_ => MethodTaking__ExampleInt__(Prop1), false) .And(_ => MethodTaking__ExampleInt__(_.Prop1), false) .And(_ => ADifferentMethodWithRandomArg(2)) .And(_ => ADifferentMethodWith(_prop2)) .When(_ => WhenMethodUsing__ExampleString__()) .And(_ => AndIUseA(multiWordHeading)) .Then(_ => ThenAllIsGood()) .WithExamples(new ExampleTable("Prop 1", "Prop2", "Prop 3", "Multi word heading") { {1, "foo", ExecutionOrder.ConsecutiveAssertion, "" }, {2, "bar", ExecutionOrder.Initialize, "val2" } }) .BDDfy(); var textReporter = new TextReporter(); textReporter.Process(story); Approvals.Verify(textReporter.ToString()); } private void GivenIntWithValue(int differentName) { differentName.ShouldBeOneOf(1, 2); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] public void Inline() { // ReSharper disable once ConvertToConstant.Local var inlineVariable = 0; var story = this .Given(_ => GivenIntWithValue(inlineVariable)) .WithExamples(new ExampleTable("Inline Variable") { 1, 2 }) .BDDfy(); var textReporter = new TextReporter(); textReporter.Process(story); Approvals.Verify(textReporter.ToString()); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] public void ExampleTypeMismatch() { var ex = Should.Throw<UnassignableExampleException>( () => this.Given(() => WrongType.ShouldBe(1), "Given i use an example") .WithExamples(new ExampleTable("Wrong type") { new object(), new object[] { null } }) .BDDfy()); ex.Message.ShouldBe("System.Object cannot be assigned to Int32 (Column: 'Wrong type', Row: 1)"); } private void AndIUseA(string multiWordHeading) { multiWordHeading.ShouldBeOneOf("", "val2"); this.multiWordHeading.ShouldBeOneOf("", "val2"); } private void ADifferentMethodWith(string prop2) { _prop2.ShouldBeOneOf("foo", "bar"); } private void ADifferentMethodWithRandomArg(int foo) { } private void ThenAllIsGood() { } private void WhenMethodUsing__ExampleString__() { _prop2.ShouldBeOneOf("foo", "bar"); Prop_3.ShouldBeOneOf(ExecutionOrder.ConsecutiveAssertion, ExecutionOrder.Initialize); } private void MethodTaking__ExampleInt__(int exampleInt) { exampleInt.ShouldBeInRange(1, 2); } public int WrongType { get; set; } public int Prop1 { get; set; } private string _prop2 = null; private string multiWordHeading = null; public ExecutionOrder Prop_3 { get; set; } } }
using System; using WebApi.Hal; namespace Jobbie.Sample.Scheduler.Contracts.Api { public sealed class ApiError : Representation { public ApiError(Exception exception, bool includeFullDetails) { Error = exception.GetType().Name; Message = exception.Message; if (includeFullDetails) Exception = exception.ToString(); } public ApiError(Exception exception) : this(exception, false) { } public ApiError() { } public string Error { get; } public string Message { get; } public string Exception { get; } } }
using FreeCourse.Web.Models.Orders; using FreeCourse.Web.Services.Interfaces; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FreeCourse.Web.Controllers { public class OrderController : Controller { private readonly IBasketService _basketService; private readonly IOrderService _orderService; public OrderController(IBasketService basketService, IOrderService orderService) { _basketService = basketService; _orderService = orderService; } public async Task<IActionResult> Checkout() { var basket = await _basketService.Get(); ViewBag.basket = basket; return View(new CheckoutInfoInput()); } [HttpPost] public async Task<IActionResult> Checkout(CheckoutInfoInput checkoutInfoInput) { //1. yol senkron iletişim // var orderStatus = await _orderService.CreateOrder(checkoutInfoInput); // 2.yol asenkron iletişim var orderSuspend = await _orderService.SuspendOrder(checkoutInfoInput); if (!orderSuspend.IsSuccessful) { var basket = await _basketService.Get(); ViewBag.basket = basket; ViewBag.error = orderSuspend.Error; return View(); } //1. yol senkron iletişim // return RedirectToAction(nameof(SuccessfulCheckout), new { orderId = orderStatus.OrderId }); //2.yol asenkron iletişim return RedirectToAction(nameof(SuccessfulCheckout), new { orderId = new Random().Next(1, 1000) }); } public IActionResult SuccessfulCheckout(int orderId) { ViewBag.orderId = orderId; return View(); } public async Task<IActionResult> CheckoutHistory() { return View(await _orderService.GetOrder()); } } }
// <copyright file="BaseReferenceFactory.cs" company="Cui Ziqiang"> // Copyright (c) 2017 Cui Ziqiang // </copyright> namespace CrossCutterN.Weaver.Reference { using System; using CrossCutterN.Base.Metadata; using CrossCutterN.Base.Switch; using CrossCutterN.Weaver.Reference.Base.Metadata; using CrossCutterN.Weaver.Reference.Base.Switch; using Mono.Cecil; /// <summary> /// Base reference factory. /// </summary> internal static class BaseReferenceFactory { /// <summary> /// Initializes a new instance of of <see cref="IBaseReference"/> interface. /// </summary> /// <param name="module">The current module that this <see cref="IBaseReference"/> is for.</param> /// <returns>The <see cref="IBaseReference"/> initialized.</returns> public static IBaseReference InitializeBaseReference(ModuleDefinition module) { if (module == null) { throw new ArgumentNullException("module"); } return new BaseReference { MetadataFactory = InitializeMetadataFactory(module), Execution = InitializeExecution(module), ExecutionContext = InitializeExecutionContext(module), Parameter = InitializeParameter(module), CustomAttribute = InitializeCustomAttribute(module), AttributeProperty = InitializeAttributeProperty(module), Return = InitializeReturn(module), Builder = InitializeBuilder(module), BackStage = InitializeBackStage(module), Glancer = InitializeGlancer(module), }; } private static IMetadataFactoryReference InitializeMetadataFactory(ModuleDefinition module) { const string methodInitializeExecution = "InitializeExecution"; const string methodInitializeExecutionContext = "InitializeExecutionContext"; const string methodInitializeParameter = "InitializeParameter"; const string methodInitializeCustomAttribute = "InitializeCustomAttribute"; const string methodInitializeAttributeProperty = "InitializeAttributeProperty"; const string methodInitializeReturn = "InitializeReturn"; var reference = new MetadataFactoryReference(module); var type = typeof(MetadataFactory); reference.InitializeAttributePropertyMethod = type.GetMethod(methodInitializeAttributeProperty); reference.InitializeCustomAttributeMethod = type.GetMethod(methodInitializeCustomAttribute); reference.InitializeExecutionContextMethod = type.GetMethod(methodInitializeExecutionContext); reference.InitializeExecutionMethod = type.GetMethod(methodInitializeExecution); reference.InitializeParameterMethod = type.GetMethod(methodInitializeParameter); reference.InitializeReturnMethod = type.GetMethod(methodInitializeReturn); return reference.Build(); } private static IExecutionBuilderReference InitializeExecution(ModuleDefinition module) { const string methodAddParameter = "AddParameter"; const string methodBuild = "Build"; var reference = new ExecutionBuilderReference(module); var type = typeof(IExecutionBuilder); reference.AddParameterMethod = type.GetMethod(methodAddParameter); reference.ReadOnlyTypeReference = typeof(IExecution); reference.TypeReference = type; reference.BuildMethod = type.GetMethod(methodBuild); return reference.Build(); } private static IExecutionContextReference InitializeExecutionContext(ModuleDefinition module) { var reference = new ExecutionContextReference(module); var type = typeof(IExecutionContext); reference.TypeReference = type; return reference.Build(); } private static IParameterBuilderReference InitializeParameter(ModuleDefinition module) { const string methodAddCustomAttribute = "AddCustomAttribute"; const string methodBuild = "Build"; var reference = new ParameterBuilderReference(module); var type = typeof(IParameterBuilder); reference.AddCustomAttributeMethod = type.GetMethod(methodAddCustomAttribute); reference.ReadOnlyTypeReference = typeof(IParameter); reference.BuildMethod = type.GetMethod(methodBuild); reference.TypeReference = type; return reference.Build(); } private static ICustomAttributeBuilderReference InitializeCustomAttribute(ModuleDefinition module) { const string methodAddAttributeProperty = "AddAttributeProperty"; const string methodBuild = "Build"; var reference = new CustomAttributeBuilderReference(module); var type = typeof(ICustomAttributeBuilder); reference.AddAttributePropertyMethod = type.GetMethod(methodAddAttributeProperty); reference.ReadOnlyTypeReference = typeof(CrossCutterN.Base.Metadata.ICustomAttribute); reference.BuildMethod = type.GetMethod(methodBuild); reference.TypeReference = type; return reference.Build(); } private static IAttributePropertyReference InitializeAttributeProperty(ModuleDefinition module) { var reference = new AttributePropertyReference(module); var type = typeof(IAttributeProperty); reference.TypeReference = type; return reference.Build(); } private static IReturnBuilderReference InitializeReturn(ModuleDefinition module) { const string propertyHasReturn = "HasReturn"; const string propertyValue = "Value"; const string methodBuild = "Build"; var reference = new ReturnBuilderReference(module); var type = typeof(IReturnBuilder); reference.HasReturnSetter = type.GetProperty(propertyHasReturn).GetSetMethod(); reference.ReadOnlyTypeReference = typeof(IReturn); reference.BuildMethod = type.GetMethod(methodBuild); reference.TypeReference = type; reference.ValueSetter = type.GetProperty(propertyValue).GetSetMethod(); return reference.Build(); } private static IAspectSwitchBuilderReference InitializeBuilder(ModuleDefinition module) { const string methodRegisterSwitch = "RegisterSwitch"; const string methodComplete = "Complete"; var reference = new AspectSwitchBuilderReference(module); var type = typeof(IAspectSwitchBuilder); reference.CompleteMethod = type.GetMethod(methodComplete); reference.RegisterSwitchMethod = type.GetMethod(methodRegisterSwitch); return reference.Build(); } private static ISwitchBackStageReference InitializeBackStage(ModuleDefinition module) { const string propertyGlancer = "Glancer"; const string propertyBuilder = "Builder"; var reference = new SwitchBackStageReference(module); var type = typeof(SwitchBackStage); reference.BuilderGetterReference = type.GetProperty(propertyBuilder).GetMethod; reference.GlancerGetterReference = type.GetProperty(propertyGlancer).GetMethod; return reference.Build(); } private static IAspectSwitchGlancerReference InitializeGlancer(ModuleDefinition module) { const string methodIsOn = "IsOn"; var reference = new AspectSwitchGlancerReference(module) { IsOnMethod = typeof(IAspectSwitchGlancer).GetMethod(methodIsOn), }; return reference.Build(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CooQGenerate { class TemplateConfigException : Exception { public TemplateConfigException(String msg) :base(msg) { } public TemplateConfigException(String msg, Exception e) :base(msg, e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using crm_webapi.Models; using AutoMapper; using crm_webapi.Controllers.Users; using crm_webapi.Repositories; using crm_webapi.Exceptions; using crm_webapi.Responses; namespace crm_webapi.Controllers.Groups { [Route("api/[controller]")] public class GroupTeacherController : Controller { private readonly IGroupTeacherRepository _repository; public GroupTeacherController(IGroupTeacherRepository repository) { _repository = repository; } [HttpGet("{id}/groups", Name = "GetTeacherGroups")] public IEnumerable<GroupApiModel> GetGroupsByTeacher(int id) { var groups = _repository.GetGroupsByTeacher(id); var result = Mapper.Map<GroupApiModel[]>(groups); return result; } [HttpGet("{id}/teachers", Name = "GetGroupTeachers")] public IEnumerable<UserApiModel> GetTeachersByGroup(int id) { var users = _repository.GetTeachersByGroup(id); var result = Mapper.Map<UserApiModel[]>(users); return result; } [HttpPost("{groupId}/{teacherId}")] public IActionResult AddGroupTeacher(int groupId, int teacherId) { _repository.AddGroupTeachers(groupId, teacherId); return new NoContentResult(); } [HttpDelete("{groupId}/{teacherId}")] public IActionResult Delete(int groupId, int teacherId) { _repository.RemoveGroupTeacher(groupId, teacherId); return new NoContentResult(); } [HttpGet("{id}/teachers/available", Name = "GetAvailableGroupTeachers")] public PagedResponse<UserApiModel> GetAvailableGroupTeachers(int id, [FromQuery] Parameters parameters) { var teachers = _repository.GetAvailableTeachers(id, parameters); var count = _repository.GetTotalTeachers(id, parameters.Filter); var result = new PagedResponse<UserApiModel>(Mapper.Map<UserApiModel[]>(teachers), count); return result; } [HttpGet("{id}/groups/available", Name = "GetAvailableTeacherGroups")] public PagedResponse<GroupApiModel> GetAvailableTeacherGroups(int id, [FromQuery] Parameters parameters) { var groups = _repository.GetAvailableGroups(id,parameters); var count = _repository.GetTotalGroups(id, parameters.Filter); var result = new PagedResponse<GroupApiModel>(Mapper.Map<GroupApiModel[]>(groups), count); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapping; namespace RunAutoMapper { public class Program { static void Main(string[] args) { var weatherData = new WeatherData { Date = new DateTime(2012, 1, 1), TempHigh = 20, TempMean = 17, // Intentionally set to something other than 15 TempLow = 10, Rainfall = 17, SoilTemp = -1 // Rubbish data to ignore }; var autoMapWeather = new AutoMapWeather(); var weather = autoMapWeather.WeatherDataToWeather(weatherData); } } }
using System; using System.Globalization; using Jaeger.Util; namespace Jaeger { /// <summary> /// Represents a unique 64bit identifier of a span. /// </summary> public readonly struct SpanId { private long Id { get; } public static SpanId NewUniqueId() { return new SpanId(Utils.UniqueId()); } public SpanId(long spanId) { Id = spanId; } public SpanId(TraceId traceId) { Id = traceId.Low; } public bool Equals(SpanId other) { return Id == other.Id; } public override bool Equals(object obj) { return obj is SpanId other && Equals(other); } public override int GetHashCode() { return Id.GetHashCode(); } public override string ToString() { return Id.ToString("x016"); } public byte[] ToByteArray() { return Utils.LongToNetworkBytes(Id); } public static implicit operator long(SpanId s) { return s.Id; } public static SpanId FromString(string from) { if (from.Length > 16) { throw new Exception($"SpanId cannot be longer than 16 hex characters: {from}"); } if (!long.TryParse(from, NumberStyles.HexNumber, null, out var result)) { throw new Exception($"Cannot parse SpanId from string: {from}"); } return new SpanId(result); } } }
using System; using System.Threading.Tasks; using MassTransit; using RtuItLab.Infrastructure.MassTransit.Purchases.Requests; using RtuItLab.Infrastructure.MassTransit.Shops.Requests; using Shops.Domain.Services; namespace Shops.API.Consumers { public class BuyProducts : ShopsBaseConsumer, IConsumer<BuyProductsRequest> { private readonly IBusControl _busControl; private readonly Uri _rabbitMqUrl = new Uri("rabbitmq://localhost/purchasesQueue"); public BuyProducts(IShopsService shopsService, IBusControl busControl) : base(shopsService) { _busControl = busControl; } public async Task Consume(ConsumeContext<BuyProductsRequest> context) { var order = await ShopsService.BuyProducts(context.Message.ShopId, context.Message.Products); await context.RespondAsync(order); var transaction = await ShopsService.CreateTransaction(context.Message.ShopId, order); await ShopsService.AddReceipt(transaction.Receipt); var endpoint = await _busControl.GetSendEndpoint(_rabbitMqUrl); await endpoint.Send(new AddTransactionRequest { User = context.Message.User, Transaction = transaction }); } } }
using Hl7.Fhir.Model; using Pyro.Common.FhirOperation; using Pyro.Common.Search; using Pyro.Common.Tools.UriSupport; namespace Pyro.Common.Service.SearchParameters { public class SearchParametersServiceRequest : ISearchParametersServiceRequest { public ISearchParameterGeneric SearchParameterGeneric { get; set; } public SearchParameterService.SearchParameterServiceType SearchParameterServiceType { get; set; } public OperationClass OperationClass { get; set; } public FHIRAllTypes? ResourceType { get; set; } public IPyroRequestUri RequestUri { get; set; } internal SearchParametersServiceRequest() { } } }
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace Rhea.Model.Apartment { /// <summary> /// 业务记录类 /// </summary> [CollectionName("apartmentTransaction")] public class ApartmentTransaction : MongoEntity { #region Property /// <summary> /// 业务类型 /// </summary> [Required] [BsonElement("type")] [Display(Name = "业务类型")] public int Type { get; set; } /// <summary> /// 办理时间 /// </summary> [BsonDateTimeOptions(Kind = DateTimeKind.Local)] [BsonElement("time")] [DataType(DataType.DateTime)] [Display(Name = "办理时间")] public DateTime Time { get; set; } /// <summary> /// 居住人ID /// </summary> [BsonRepresentation(BsonType.ObjectId)] [BsonElement("inhabitantId")] [Display(Name = "居住人ID")] public string InhabitantId { get; set; } /// <summary> /// 住户姓名 /// </summary> [BsonElement("inhabitantName")] [Display(Name = "住户姓名")] public string InhabitantName { get; set; } /// <summary> /// 操作用户ID /// </summary> [BsonRepresentation(BsonType.ObjectId)] [BsonElement("userId")] [Display(Name = "操作用户ID")] public string UserId { get; set; } /// <summary> /// 操作用户姓名 /// </summary> [BsonElement("userName")] [Display(Name = "操作用户姓名")] public string UserName { get; set; } /// <summary> /// 备注 /// </summary> [BsonElement("remark")] [Display(Name = "备注")] public string Remark { get; set; } /// <summary> /// 状态 /// </summary> [BsonElement("status")] [Display(Name = "状态")] public int Status { get; set; } #endregion //Property } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace Dapper.Easies { public class JoinMetedata { public JoinMetedata(DbObject dbObject, JoinType type, Expression joinExpression, IDbQuery query) { DbObject = dbObject; Type = type; JoinExpression = joinExpression; Query = query; } public DbObject DbObject { get; } public JoinType Type { get; } public Expression JoinExpression { get; } public IDbQuery Query { get; } } }
namespace DragonSpark.Testing.Objects.Composition { public interface IParameterService { object Parameter { get; } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Simple.API.Entity { public class Context : DbContext { public Context(DbContextOptions<Context> options):base(options) { } public DbSet<Product> Products { set; get; } } }
#if NET6_0 public class DocsTests { [Fact] public void Foo() { var solutionDirectory = AttributeReader.GetSolutionDirectory(); var docsDirectory = Path.Combine(solutionDirectory, "../docs"); docsDirectory = Path.GetFullPath(docsDirectory); var includeFile = Path.Combine(docsDirectory, "index.include.md"); var builder = new StringBuilder(); var level = 0; AddFiles(builder, docsDirectory, docsDirectory, ""); foreach (var nestedDirectory in Directory.EnumerateDirectories(docsDirectory)) { AddDirectory(ref level, builder, nestedDirectory, docsDirectory); } File.Delete(includeFile); File.WriteAllText(includeFile, builder.ToString()); } static string GetUrl(string docsDirectory, string file) { var fullPath = Path.GetFullPath(file); var suffix = fullPath.Replace(docsDirectory, "") .Replace('\\', '/'); return $"/docs{suffix}"; } static void AddDirectory(ref int level, StringBuilder builder, string directory, string docsDirectory) { level++; var directoryIndent = new string(' ', level * 2); var url = GetUrl(docsDirectory, directory); builder.AppendLine($"{directoryIndent}* [{Path.GetFileName(directory)}]({url})"); foreach (var nestedDirectory in Directory.EnumerateDirectories(directory)) { AddDirectory(ref level, builder, nestedDirectory, docsDirectory); } AddFiles(builder, directory, docsDirectory, directoryIndent); level--; } static void AddFiles(StringBuilder builder, string directory, string docsDirectory, string directoryIndent) { var readme = Path.Combine(directory, "readme.md"); if (File.Exists(readme)) { AddFile(builder, docsDirectory, readme, directoryIndent); } foreach (var file in Directory.EnumerateFiles(directory, "*.md")) { if (file.EndsWith("readme.md")) { continue; } try { AddFile(builder, docsDirectory, file, directoryIndent); } catch (Exception exception) { throw new($"{exception.Message}. {file}"); } } } static void AddFile(StringBuilder builder, string docsDirectory, string file, string directoryIndent) { var url = GetUrl(docsDirectory, file); var title = File.ReadLines(file) .First()[2..]; builder.AppendLine($"{directoryIndent} * [{title}]({url})"); } } #endif
using System; using System.Collections.Generic; using ValueTuples.Reflection; namespace ValueTuples.Sample { public partial class Pair<T1, T2> { public override string ToString() => $"({Item1}, {Item2})"; } public partial class Pair<T1, T2> { public T1 Item1 { get; set; } public T2 Item2 { get; set; } public Pair() { } public Pair(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } static Pair() { TypeRepository.Register(typeof(Pair<T1, T2>), new PairInfo<T1, T2>()); } } internal struct PairAccessor<T1, T2> : IRecordAccessor { Pair<T1, T2> _value; public PairAccessor(Pair<T1, T2> value) { _value = value; } public object Get(string key) { switch (key) { case "Item1": return _value.Item1; case "Item2": return _value.Item2; default: return null; } } public object Get(int index) { switch (index) { case 0: return _value.Item1; case 1: return _value.Item2; default: return null; } } public void Set(string key, object value) { switch (key) { case "Item1": _value.Item1 = (T1)value; break; case "Item2": _value.Item2 = (T2)value; break; } } public void Set(int index, object value) { switch (index) { case 0: _value.Item1 = (T1)value; break; case 1: _value.Item2 = (T2)value; break; } } } internal class PairInfo<T1, T2> : RecordTypeInfo { public override Type Type => typeof(Pair<T1, T2>); private static readonly RecordFieldInfo[] _fields = { new RecordFieldInfo(TypeRepository.Get(typeof(T1)), "Item1", 0), new RecordFieldInfo(TypeRepository.Get(typeof(T2)), "Item2", 1), }; public override IEnumerable<RecordFieldInfo> Fields => _fields; public override object GetInstance() => new Pair<T1, T2>(); public override Array GetArray(int length) => new Pair<T1, T2>[length]; public override IRecordAccessor GetAccessor(object instance) => new PairAccessor<T1, T2>((Pair<T1, T2>)instance); } }
using FunctionParser; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace VariableNodeParser_utest { //[TestClass] public partial class VariableNodeParser_utest { [TestMethod] [TestCategory("VariableNodeParser")] [TestCategory("RemovePointer")] public void RemovePointer_test_001() { string dataType = "int"; var parser = new VariableNodeParser(); var privateParser = new PrivateObject(parser); string dataTypeWithoutPoitner = (string)privateParser.Invoke("RemovePointer", dataType); Assert.AreEqual("int", dataTypeWithoutPoitner); } [TestMethod] [TestCategory("VariableNodeParser")] [TestCategory("RemovePointer")] public void RemovePointer_test_002() { string dataType = "int*"; var parser = new VariableNodeParser(); var privateParser = new PrivateObject(parser); string dataTypeWithoutPoitner = (string)privateParser.Invoke("RemovePointer", dataType); Assert.AreEqual("int", dataTypeWithoutPoitner); } [TestMethod] [TestCategory("VariableNodeParser")] [TestCategory("RemovePointer")] public void RemovePointer_test_003() { string dataType = "int**"; var parser = new VariableNodeParser(); var privateParser = new PrivateObject(parser); string dataTypeWithoutPoitner = (string)privateParser.Invoke("RemovePointer", dataType); Assert.AreEqual("int", dataTypeWithoutPoitner); } } }
using Revo.Core.Configuration; namespace Revo.EasyNetQ.Configuration { public class EasyNetQConfigurationSection : IRevoConfigurationSection { public bool IsActive { get; set; } public EasyNetQConnectionConfiguration Connection { get; set; } = new EasyNetQConnectionConfiguration("host=localhost"); public EasyNetQSubscriptionsConfiguration Subscriptions { get; set; } = new EasyNetQSubscriptionsConfiguration(); public EasyNetQEventTransportsConfiguration EventTransports { get; set; } = new EasyNetQEventTransportsConfiguration(); } }
namespace FileToVoxCommon.Generator.Shaders.Data { public class ShaderFixLonely : ShaderStep { public override ShaderType ShaderType { get; set; } = ShaderType.FIX_LONELY; public override void ValidateSettings() { } } }
using UnityEngine; using System.Collections; using UnityEngine.Animations; using UnityEngine.Playables; public abstract class ActionManagerBase : EntityBehavior<LifeBody> { public const string AnimTagEnd = "End"; public const string AnimTagBegin = "Begin"; public const string AnimTagGap = "Gap"; public const string AnimTagLock = "Lock"; public abstract AnimatorControllerPlayable CurrentAnimatorPlayable { get; } public abstract bool ChangeAction(RuntimeAnimatorController animatorController); public abstract bool Move(Vector2 movement); public abstract bool Turn(float angle); }
//using System; //using System.Collections.Generic; //using System.Text; //using System.Xml.Serialization; //namespace Analysis.EDM //{ // /// <summary> // /// This class holds a number of ChannelSets, one for each manual state. Instances of this // /// class are usually assembled by accumulation. It has slots for reporting how many // /// channel sets were accumulated for each machine state. // /// </summary> // [Serializable] // [XmlInclude(typeof(TOFChannelSetGroup))] // public class ChannelSetGroup<T> // { // public const int Length = 8; // protected const int rfIndex = 1; // protected const int bIndex = 2; // protected const int eIndex = 4; // public ChannelSet<T>[] ChannelSets; // public ChannelSet<T> ChannelSetForMachineState(bool eState, bool bState, bool rfState) // { // return ChannelSets[machineStateIndex(eState, bState, rfState)]; // } // protected int machineStateIndex(bool eState, bool bState, bool rfState) // { // int index = 0; // if (rfState) index += rfIndex; // if (bState) index += bIndex; // if (eState) index += eIndex; // return index; // } // protected bool eState(int index) // { // return ((index & eIndex) != 0); // } // protected bool bState(int index) // { // return ((index & bIndex) != 0); // } // protected bool rfState(int index) // { // return ((index & rfIndex) != 0); // } // } //}
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Lime; using Tangerine.Core; using Tangerine.UI.Docking; namespace Tangerine.UI.FilesystemView { // TODO: refactor tree manipulation code all over the file // whole pane with all filesystem views public class FilesystemPane { public static FilesystemPane Instance; private Widget dockPanelWidget; private Widget rootWidget; private Panel panel; private List<FilesystemView> views = new List<FilesystemView>(); public FilesystemPane(Panel panel) { Instance = this; this.panel = panel; dockPanelWidget = panel.ContentWidget; CommandHandlerList.Global.Connect(FilesystemCommands.NavigateTo, HandleHavigateTo); CommandHandlerList.Global.Connect(FilesystemCommands.OpenInSystemFileManager, HandleOpenInSystemFileManager); } public void Initialize() { views.Clear(); // clear unwanted Widget references for GC to collect var up = FilesystemUserPreferences.Instance; foreach (var (_, viewNode) in up.ViewRootPerProjectFile) { viewNode.Widget = null; } rootWidget?.UnlinkAndDispose(); var q = new Queue<ViewNode>(); q.Enqueue(up.ViewRoot); while (q.Count != 0) { var n = q.Dequeue(); foreach (var child in n.Children) { child.Parent = n; q.Enqueue(child); } Widget w; if (n is FSViewNode) { var fsView = new FilesystemView(); views.Add(fsView); w = fsView.RootWidget; w.Components.Add(new ViewNodeComponent { ViewNode = n }); fsView.Initialize(); } else if (n is SplitterNode) { var type = (n as SplitterNode).Type; Splitter s = type.MakeSplitter(); s.Stretches = Splitter.GetStretchesList((n as SplitterNode).Stretches, 1, 1); w = s; w.Components.Add(new ViewNodeComponent { ViewNode = n }); // copy pasted line } else { throw new InvalidDataException(); } n.Widget = w; if (n.Parent != null) { n.Parent.Widget.AddNode(w); } else { rootWidget = w; } } dockPanelWidget.PushNode(rootWidget); rootWidget.SetFocus(); } public void Split(FilesystemView fsView, SplitterType type) { var RootWidget = fsView.RootWidget; FSViewNode vn = RootWidget.Components.Get<ViewNodeComponent>().ViewNode as FSViewNode; var newFsView = new FilesystemView(); views.Add(newFsView); var newVn = new FSViewNode { Widget = newFsView.RootWidget, Path = vn.Path, ShowSelectionPreview = vn.ShowSelectionPreview, ShowCookingRulesEditor = vn.ShowCookingRulesEditor, }; // TODO: setup internal stretches of fsView here newFsView.RootWidget.Components.Add(new ViewNodeComponent { ViewNode = newVn }); newFsView.Initialize(); if (vn.Parent == null) { // Root node, need to replace on in UserPreferences Splitter s = type.MakeSplitter(); var up = FilesystemUserPreferences.Instance; var sn = new SplitterNode { Widget = s, Type = type }; up.ViewRoot = sn; newVn.Parent = sn; s.Stretches = Splitter.GetStretchesList(sn.Stretches, 1, 1); sn.Children.Add(vn); sn.Children.Add(newVn); var thisParent = RootWidget.ParentWidget; RootWidget.Unlink(); s.AddNode(RootWidget); s.AddNode(newFsView.RootWidget); s.Components.Add(new ViewNodeComponent { ViewNode = sn }); vn.Parent = sn; thisParent.Nodes.Add(s); // TODO setup stretches ^ } else if (vn.Parent is SplitterNode) { if ((vn.Parent as SplitterNode).Type == type) { var sn = vn.Parent as SplitterNode; var s = sn.Widget; s.Nodes.Insert(s.Nodes.IndexOf(RootWidget), newFsView.RootWidget); newVn.Parent = sn; sn.Children.Insert(sn.Children.IndexOf(vn), newVn); } else { Splitter s = type.MakeSplitter(); var sn = new SplitterNode { Widget = s, Type = type }; s.Components.Add(new ViewNodeComponent { ViewNode = sn }); s.Stretches = Splitter.GetStretchesList(sn.Stretches); var psn = vn.Parent as SplitterNode; // or vn.Parent.Widget int thisIndex = RootWidget.ParentWidget.Nodes.IndexOf(RootWidget); var thisParent = RootWidget.ParentWidget; RootWidget.Unlink(); s.AddNode(RootWidget); s.AddNode(newFsView.RootWidget); sn.Children.Add(vn); sn.Children.Add(newVn); vn.Parent = sn; newVn.Parent = sn; thisParent.Nodes.Insert(thisIndex, s); var ps = psn.Widget; sn.Parent = psn; psn.Children.RemoveAt(thisIndex); psn.Children.Insert(thisIndex, sn); } } else if (vn.Parent is FSViewNode) { // wat } } public void Close(FilesystemView fsView) { views.Remove(fsView); var RootWidget = fsView.RootWidget; ViewNode vn = RootWidget.Components.Get<ViewNodeComponent>().ViewNode; if (vn.Parent == null) { // oh noes can't close root! return; } if (vn.Parent is SplitterNode) { var sn = vn.Parent as SplitterNode; vn.Widget = null; // just in case? sn.Children.Remove(vn); RootWidget.UnlinkAndDispose(); if (sn.Children.Count == 1) { var ovn = sn.Children.First(); if (sn.Parent == null) { // Root => update up var up = FilesystemUserPreferences.Instance; up.ViewRoot = ovn; ovn.Parent = null; ovn.Widget.Unlink(); var pw = sn.Widget.ParentWidget; sn.Widget.UnlinkAndDispose(); pw.AddNode(ovn.Widget); } else { // remap ovn.Parent = sn.Parent; ovn.Widget.Unlink(); var pwIndex = sn.Widget.ParentWidget.Nodes.IndexOf(sn.Widget); var pw = sn.Widget.ParentWidget; sn.Widget.UnlinkAndDispose(); pw.Nodes.Insert(pwIndex, ovn.Widget); ovn.Parent.Children.Remove(sn); ovn.Parent.Children.Insert(pwIndex, ovn); } } else { // wat } } else { // wat } } private void HandleHavigateTo() { if (views.Count == 0) { // In case we start Tangerine with FilesystemPane hidden we want to invoke above added task // which calls initialize for the first time regardless of this pane being hidden or not. dockPanelWidget.Update(0); } var view = views.First(); DockManager.Instance.ShowPanel(panel.Id); var path = FilesystemCommands.NavigateTo.UserData as string; var dir = Path.GetDirectoryName(path); view.GoTo(dir); // kind of force reaction to GoTo with Update(0) view.RootWidget.Update(0); view.SelectAsset(path); FilesystemCommands.NavigateTo.UserData = null; } private void OpenInSystemFileManager(string path) { #if WIN System.Diagnostics.Process.Start("explorer.exe", "/select, \"" + path + "\""); #elif MAC throw new NotImplementedException(); #else throw new NotImplementedException(); #endif } private void HandleOpenInSystemFileManager() { var path = FilesystemCommands.OpenInSystemFileManager.UserData as string; #if WIN path = path.Replace('/', '\\'); #endif var extension = Path.GetExtension(path); if (string.IsNullOrEmpty(extension)) { foreach (string f in Directory.GetFiles(Path.GetDirectoryName(path))) { if (Path.ChangeExtension(f, null) == path && !f.EndsWith(".txt")) { OpenInSystemFileManager(f); break; } } } else { OpenInSystemFileManager(path); } } } }
 using Xamarin.Forms; namespace GeoContacts.Cells { public partial class ContactsGroupHeaderView : ContentView { public ContactsGroupHeaderView() { InitializeComponent (); } } public class ContactsGroupHeader : ViewCell { public ContactsGroupHeader() { View = new ContactsGroupHeaderView(); } } }
using hardforward.Controller; using hardforward.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace hardforward.View { public partial class LogForm : Form { long lastOffset; string filename; Timer timer; const int BACK_OFFSET = 65536; public LogForm(string filename) { this.filename = filename; InitializeComponent(); this.Icon = Icon.FromHandle(Resources.ssw128.GetHicon()); UpdateTexts(); } private void UpdateTexts() { FileMenuItem.Text = I18N.GetString("&File"); OpenLocationMenuItem.Text = I18N.GetString("&Open Location"); ExitMenuItem.Text = I18N.GetString("E&xit"); CleanLogsButton.Text = I18N.GetString("&Clean logs"); ChangeFontButton.Text = I18N.GetString("&Font"); WrapTextCheckBox.Text = I18N.GetString("&Wrap text"); TopMostCheckBox.Text = I18N.GetString("&Top most"); this.Text = I18N.GetString("Log Viewer"); } private void Timer_Tick(object sender, EventArgs e) { UpdateContent(); } private void InitContent() { using (StreamReader reader = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { if (reader.BaseStream.Length > BACK_OFFSET) { reader.BaseStream.Seek(-BACK_OFFSET, SeekOrigin.End); reader.ReadLine(); } string line = ""; while ((line = reader.ReadLine()) != null) LogMessageTextBox.AppendText(line + "\r\n"); LogMessageTextBox.ScrollToCaret(); lastOffset = reader.BaseStream.Position; } } private void UpdateContent() { using (StreamReader reader = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { reader.BaseStream.Seek(lastOffset, SeekOrigin.Begin); string line = ""; bool changed = false; while ((line = reader.ReadLine()) != null) { changed = true; LogMessageTextBox.AppendText(line + "\r\n"); } if (changed) { LogMessageTextBox.ScrollToCaret(); } lastOffset = reader.BaseStream.Position; } } private void LogForm_Load(object sender, EventArgs e) { InitContent(); timer = new Timer(); timer.Interval = 300; timer.Tick += Timer_Tick; timer.Start(); } private void LogForm_FormClosing(object sender, FormClosingEventArgs e) { timer.Stop(); } private void OpenLocationMenuItem_Click(object sender, EventArgs e) { string argument = "/select, \"" + filename + "\""; Console.WriteLine(argument); System.Diagnostics.Process.Start("explorer.exe", argument); } private void ExitMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void LogForm_Shown(object sender, EventArgs e) { LogMessageTextBox.ScrollToCaret(); } private void WrapTextCheckBox_CheckedChanged(object sender, EventArgs e) { LogMessageTextBox.WordWrap = WrapTextCheckBox.Checked; LogMessageTextBox.ScrollToCaret(); } private void CleanLogsButton_Click(object sender, EventArgs e) { LogMessageTextBox.Clear(); } private void ChangeFontButton_Click(object sender, EventArgs e) { FontDialog fd = new FontDialog(); fd.Font = LogMessageTextBox.Font; if (fd.ShowDialog() == DialogResult.OK) { LogMessageTextBox.Font = fd.Font; } } private void TopMostCheckBox_CheckedChanged(object sender, EventArgs e) { this.TopMost = TopMostCheckBox.Checked; } } }
using Microsoft.Extensions.Logging; using OpenQA.Selenium; using SnBatchProcessor.Processor.Scripting; namespace SnBatchProcessor.Selenium.Scripting { public class SeleniumScriptingContext : ScriptingContext, ISeleniumScriptingContext { public SeleniumScriptingContext(string profileName, ILogger logger, IServiceProvider serviceProvider, WebDriver webDriver, IDictionary<string, object> vars, TimeSpan delay) : base(profileName, logger, serviceProvider) { WebDriver = webDriver; Vars = vars; Delay = delay; } public WebDriver WebDriver { get; } public IDictionary<string, object> Vars { get; } public TimeSpan Delay { get; } } }
namespace FinancialIndependencePlanner.IncomeStreams { public interface IncomeStream { } }
using System; struct S { public static implicit operator short? (S s) { return 0; } public static implicit operator short (S s) { throw new ApplicationException (); } } class Program { public static int Main () { S? s = null; S? s2 = new S (); long? i = s; if (i != null) return 1; double? ui = s2; if (ui == null) return 2; return 0; } }