text
stringlengths
13
6.01M
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using PW.InternalMoney.Models; using System.Web; namespace PW.InternalMoney.DataProviders { public static class BalanceProvider { public static BillingAccount GetCurentUserBillingAccount() { var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var currentUser = manager.FindById(HttpContext.Current.User.Identity.GetUserId()); return currentUser.BillingAccount; } } }
using System; using Microsoft.HealthVault.ItemTypes; using Windows.UI.Xaml.Data; namespace HealthVaultMobileSample.UWP.Converters { /// <summary> /// Converts an ApproximateDateTime to a string. /// </summary> public class ApproximateDateTimeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { if (value != null) { var approxDateTime = value as ApproximateDateTime; // If ApproximateDateTime.Description is set, then we don't expect anything else to be present. Just output that content directly. if (!String.IsNullOrEmpty(approxDateTime.Description)) { return approxDateTime.Description; } else { ApproximateDate date = approxDateTime.ApproximateDate; var year = date.Year; var month = (date.Month != null) ? date.Month.Value : 1; var day = (date.Day != null) ? date.Day.Value : 1; DateTime current = new DateTime(year, month, day); return current.ToString(System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern); } } else { return null; } } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
using UnityEngine; using System.Collections; using System; public class CameraFollow : MonoBehaviour { [SerializeField] private float smooth = 2f; [Header("Camera Blocks")] [SerializeField] private Transform topLeft; [SerializeField] private Transform bottomRight; private Transform player; private float camWidth; private float camHeight; private Resolution resolution; void Awake () { player = GameObject.FindGameObjectWithTag("Player").transform; ChangeResolution(); } void LateUpdate () { if (!Screen.currentResolution.Equals(resolution)) { ChangeResolution(); } Vector3 newPosition = new Vector3(player.position.x, player.position.y, transform.position.z); if (newPosition.x - camWidth/2 < topLeft.position.x) newPosition.x = topLeft.position.x + camWidth/2; if (newPosition.y + camHeight/2 > topLeft.position.y) newPosition.y = topLeft.position.y - camHeight/2; if (newPosition.x + camWidth/2 > bottomRight.position.x) newPosition.x = bottomRight.position.x - camWidth/2; if (newPosition.y - camHeight/2 < bottomRight.position.y) newPosition.y = bottomRight.position.y + camHeight/2; transform.position = Vector3.Lerp(transform.position, newPosition, smooth); } private void ChangeResolution() { camHeight = 2*Camera.main.orthographicSize; camWidth = camHeight*Camera.main.aspect; resolution = Screen.currentResolution; } }
using Microsoft.Extensions.Configuration; using Castle.MicroKernel.Registration; using Abp.Events.Bus; using Abp.Modules; using Abp.Reflection.Extensions; using DgKMS.Cube.Configuration; using DgKMS.Cube.EntityFrameworkCore; using DgKMS.Cube.Migrator.DependencyInjection; namespace DgKMS.Cube.Migrator { [DependsOn(typeof(CubeEntityFrameworkModule))] public class CubeMigratorModule : AbpModule { private readonly IConfigurationRoot _appConfiguration; public CubeMigratorModule(CubeEntityFrameworkModule abpProjectNameEntityFrameworkModule) { abpProjectNameEntityFrameworkModule.SkipDbSeed = true; _appConfiguration = AppConfigurations.Get( typeof(CubeMigratorModule).GetAssembly().GetDirectoryPathOrNull() ); } public override void PreInitialize() { Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString( CubeConsts.ConnectionStringName ); Configuration.BackgroundJobs.IsJobExecutionEnabled = false; Configuration.ReplaceService( typeof(IEventBus), () => IocManager.IocContainer.Register( Component.For<IEventBus>().Instance(NullEventBus.Instance) ) ); } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(CubeMigratorModule).GetAssembly()); ServiceCollectionRegistrar.Register(IocManager); } } }
using System; using System.Net; using System.Net.Http; using System.Runtime.Serialization; namespace DFC.ServiceTaxonomy.Events.Services.Exceptions { #pragma warning disable S3925 [Serializable] public class RestHttpClientException : Exception { public HttpStatusCode? StatusCode { get; } public string? ReasonPhrase { get; } public Uri? RequestUri { get; } public string? ErrorResponse { get; } public RestHttpClientException(HttpResponseMessage httpResponseMessage, string errorResponse) : base(GenerateMessage(httpResponseMessage, errorResponse)) { StatusCode = httpResponseMessage.StatusCode; ReasonPhrase = httpResponseMessage.ReasonPhrase; //todo: when is RequestMessage null? RequestUri = httpResponseMessage.RequestMessage!.RequestUri; ErrorResponse = errorResponse; } protected RestHttpClientException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); } private static string GenerateMessage(HttpResponseMessage httpResponseMessage, string errorResponse) { //todo: when is RequestMessage null? return $@"Request '{httpResponseMessage.RequestMessage?.RequestUri}' returned {(int)httpResponseMessage.StatusCode} {httpResponseMessage.ReasonPhrase} Response: {errorResponse}"; } } }
using System; namespace EventLite.MongoDB.DTO { internal class EventStreamDTO { public Guid StreamId { get; set; } public int HeadRevision { get; set; } public int UnsnapshottedCommits { get; set; } public int SnapshotRevision { get; set; } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Constant of type `Vector3`. Inherits from `AtomBaseVariable&lt;Vector3&gt;`. /// </summary> [EditorIcon("atom-icon-teal")] [CreateAssetMenu(menuName = "Unity Atoms/Constants/Vector3", fileName = "Vector3Constant")] public sealed class Vector3Constant : AtomBaseVariable<Vector3> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BinaryOperations { public class MixingInt { /// <summary> /// Inserts bits(from i to j) from the second number to the first using logic operators and masks /// </summary> /// <param name="first">The first number</param> /// <param name="second">The second number</param> /// <param name="i">Start position of insertion</param> /// <param name="j">Finish position of insertion</param> /// <returns></returns> public static int InsertionBits(int first, int second, int i, int j) { Check(i, j); int mask1, mask2; CreateMasks(i, j, out mask1, out mask2); return (first & mask1) | (second & mask2); } private static void CreateMasks(int i, int j, out int mask1, out int mask2) { short bits = 31; int max = int.MaxValue; mask1 = (max >> (bits - j - 1)) ^ -1 | (max >> (bits - i)); mask2 = -1 ^ mask1; } private static void Check(int i, int j) { if (i > 30 || i < 0) throw new ArgumentOutOfRangeException($"{nameof(i)} is out of range."); if (j > 30 || j < 0) throw new ArgumentOutOfRangeException($"{nameof(j)} is out of range."); if (j < i) throw new ArgumentException($"{nameof(i)} cannot be less than {nameof(j)}"); } } }
public class SingleCardValue: CardValue{ private readonly int cardNumber; public SingleCardValue(int card){ this.cardNumber = card; } public override bool CompareValue(CardValue otherValue){ var a = (SingleCardValue)otherValue; return this.cardNumber >= a.cardNumber; } }
using UnityEngine; using UnityEngine.EventSystems; using System.Collections.Generic; public abstract class BasicPiece : MonoBehaviour, Piece, IPointerClickHandler { private Color c; public Color Color { get { if (c == Color.NONE) throw new UnassignedReferenceException ("Piece's color is accessed before it's properly assigned"); return c; } set { c = value; if (value != Color.NONE) { var pac = GetComponent<PieceAppearanceController> (); if (pac != null) pac.Init (c); } } } protected Move move; protected Move capture; public GameManager GameManager { get; set; } Vector3 coordinate; public Vector3 Coordinate { get { return coordinate; } set { coordinate = value; //Move (); } } public BasicPiece() { Color = Color.NONE; } public abstract void Init (Color color); protected void addBasicConstraints() { move.AddConstraint (new BlockConstraint(),new CheckConstraint()); capture.AddConstraint (new BlockAllyAndVoidCapture(), new CheckConstraint ()); } public string GetName () { return this.GetType().Name; } public virtual List<Vector3> GetAvailableMoves (Vector3 startPosition, Board[] boards) { return move.GetMovesFrom (startPosition, boards); } public virtual List<Vector3> GetAvailableCaptures (Vector3 startPosition, Board[] boards) { return capture.GetMovesFrom (startPosition, boards); } public Move GetFormedCapture () { return capture; } public Move GetFormedMove () { return move; } void Awake () { if (GameManager == null) { GameManager = GameObject.FindGameObjectWithTag ("GameController").GetComponent<GameManager> ();; } } #region IPointerClickHandler implementation public void OnPointerClick (PointerEventData eventData) { var player = GameManager.ActivePlayer; if (player != null && player.PlayerType == PlayerType.HUMAN) { var hp = player as HumanPlayer; hp.CellClicked (Coordinate, this); } } #endregion public void Move () { GetComponent<PieceMovementController> ().Coordinate = Coordinate; } public void Destroy () { gameObject.SetActive (false); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.DataAnnotations; namespace Xlns.BusBook.Core.Model { public class Agenzia : ModelEntity { [Required] [Display(Name = "Nome Agenzia")] [StringLength(50, ErrorMessage = "Il campo può essere lungo al massimo 50 caratteri")] public virtual string Nome { get; set; } [Required] [Display(Name = "Ragione Sociale")] [StringLength(100, ErrorMessage = "Il campo può essere lungo al massimo 100 caratteri")] public virtual string RagioneSociale { get; set; } [Required] [Display(Name = "Partita Iva")] [StringLength(13, ErrorMessage = "Il campo può essere lungo al massimo 13 caratteri")] public virtual string PIva { get; set; } public virtual GeoLocation Location { get; set; } [Display(Name="Tel.")] public virtual String Telefono { get; set; } [Display(Name = "Fax")] public virtual String Fax { get; set; } [Required] [Display(Name = "Email")] public virtual string Email { get; set; } public virtual string Skype { get; set; } public virtual string Facebook { get; set; } public virtual string Twitter { get; set; } public virtual IList<Utente> Utenti { get; set; } public virtual IList<Viaggio> Viaggi { get; set; } public override string ToString() { return String.Format("{0} - {1}", Id, Nome); } } }
using System.IO; namespace WoWRegeneration.Repositories { public class WoW54718019 : WoWRepository { public override string GetBaseUrl() { return "http://dist.blizzard.com.edgesuite.net/wow-pod-retail/EU/15890.direct/"; } public override string GetMFilName() { return "wow-18019-7EEF2887F2B28FC3BCB6251A5F9AFC9A.mfil"; } } }
using Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Data.Interfaces { public interface IRegistrationRepository : IRepository<TqRegistrationProfile> { Task<IList<TqRegistration>> BulkInsertOrUpdateRegistrations(List<TqRegistration> entities); Task<IList<TqRegistrationProfile>> BulkInsertOrUpdateTqRegistrations(List<TqRegistrationProfile> entities); Task<bool> BulkInsertOrUpdateTqRegistrations(List<TqRegistrationProfile> entities, List<TqRegistrationPathway> pathwayEntities, List<TqRegistrationSpecialism> specialismEntities); } }
// // DynamicFieldGetterSetter.cs // // Author: // nofanto ibrahim <nofanto.ibrahim@gmail.com> // // Copyright (c) 2011 sejalan // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Collections.Generic; using System.Reflection; namespace Sejalan.Framework.Utility { public class DynamicFieldGetterSetter { private Dictionary<string,GenericGetter> _genericGetters = new Dictionary<string, GenericGetter>(); private Dictionary<string,GenericSetter> _genericSetters = new Dictionary<string, GenericSetter>(); public DynamicFieldGetterSetter (Type objectType) { foreach (PropertyInfo item in objectType.GetProperties(BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public)) { _genericGetters.Add(item.Name,Helper.CreateGetMethod(item)); _genericSetters.Add(item.Name,Helper.CreateSetMethod(item)); } } public object GetColumnValue(string fieldName, object target) { return _genericGetters[fieldName](target); } public void SetColumnValue(string fieldName, object target, object value) { _genericSetters[fieldName](target,value); } } public static class Extensions { public static DynamicFieldGetterSetter GetDynamicFieldGetterSetter<T>(this T objectType) where T :Type { return new DynamicFieldGetterSetter(objectType); } } }
using AutoTests.Framework.Core; using AutoTests.Framework.Core.Utils; using AutoTests.Framework.Web.Configurators; using BoDi; namespace AutoTests.Framework.Web { public class WebDependencies : Dependencies { public WebDependencies(ObjectContainer objectContainer) : base(objectContainer) { } internal UtilsDependencies Utils => ObjectContainer.Resolve<UtilsDependencies>(); public IWebDriverProvider WebDriverProvider => ObjectContainer.Resolve<IWebDriverProvider>(); internal ConfiguratorsDependencies Configurators => ObjectContainer.Resolve<ConfiguratorsDependencies>(); public T GetPage<T>() where T : Page { return ObjectContainer.Resolve<T>(); } public T GetContext<T>() where T : Context { return ObjectContainer.Resolve<T>(); } public T GetScriptLibrary<T>() where T : ScriptLibrary { return ObjectContainer.Resolve<T>(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace ScratchTutorial { public class XmlHeaderReader : IHeaderReader { // TODO: private const string TagTitle = "title"; private const string TagDescription = "description"; protected const string Extension = ".xml"; public string ReadDescription(string path) { path = PathToFile(path); using (var reader = new XmlTextReader(path)) { // TODO: checks reader.MoveToContent(); reader.ReadToDescendant(TagTitle); var title = reader.ReadString(); reader.ReadToNextSibling(TagDescription); var description = reader.ReadString(); return String.Format("{0}\n{1}", title, description); } } public string ReadTitle(string path) { path = PathToFile(path); return Path.GetFileNameWithoutExtension(path); } protected static string PathToFile(string path) { // TODO: remade if (Directory.Exists(path)) { path = Directory.EnumerateFiles(path).FirstOrDefault(x => x.EndsWith(".xml")); } if (!File.Exists(path)) throw new FileNotFoundException(path); if (!path.EndsWith(Extension)) throw new Exception("Ожидался файл XML"); return path; } } }
using System; using System.Windows; namespace Crystal.Plot2D.DataSources { public class NonUniformDataSource2D<T> : INonUniformDataSource2D<T> where T : struct { public NonUniformDataSource2D(double[] xcoordinates, double[] ycoordinates, T[,] data) { XCoordinates = xcoordinates ?? throw new ArgumentNullException(nameof(xcoordinates)); YCoordinates = ycoordinates ?? throw new ArgumentNullException(nameof(ycoordinates)); BuildGrid(); Data = data ?? throw new ArgumentNullException(nameof(data)); } private void BuildGrid() { Grid = new Point[Width, Height]; for (int iy = 0; iy < Height; iy++) { for (int ix = 0; ix < Width; ix++) { Grid[ix, iy] = new Point(XCoordinates[ix], YCoordinates[iy]); } } } public double[] XCoordinates { get; } public double[] YCoordinates { get; } public T[,] Data { get; } public IDataSource2D<T> GetSubset(int x0, int y0, int countX, int countY, int stepX, int stepY) => throw new NotImplementedException(); public void ApplyMappings(DependencyObject marker, int x, int y) => throw new NotImplementedException(); public Point[,] Grid { get; private set; } public int Width => XCoordinates.Length; public int Height => YCoordinates.Length; #pragma warning disable CS0067 // The event 'NonUniformDataSource2D<T>.Changed' is never used public event EventHandler Changed; #pragma warning restore CS0067 // The event 'NonUniformDataSource2D<T>.Changed' is never used #region IDataSource2D<T> Members public Charts.Range<T>? Range => throw new NotImplementedException(); public T? MissingValue => throw new NotImplementedException(); #endregion } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Moq; using NUnit.Framework; using Org.Common.DataProvider; using Org.Common.Domain; using Org.Common.Manager; using Org.DAL.MySql; namespace EmployeePortal.Tests { public abstract class IdentityTestBase { protected static readonly UserManager<EmployeePortalUser> UserManager; protected static readonly SignInManager<EmployeePortalUser> SignInManager; protected static readonly RoleManager<IdentityRole> RoleManager; static IdentityTestBase() { var testServer = new TestServer(new WebHostBuilder().UseStartup<ApiService>() .ConfigureServices(s => { s.AddIdentityCore<EmployeePortalUser>() .AddSignInManager() .AddEntityFrameworkStores<EmployeContext>(); s.AddDbContext<EmployeContext>(o => { o.UseInMemoryDatabase("ec"); }); })); UserManager = testServer.Services.GetService<UserManager<EmployeePortalUser>>(); SignInManager = testServer.Services.GetService<SignInManager<EmployeePortalUser>>(); RoleManager = testServer.Services.GetService<RoleManager<IdentityRole>>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EasyDev.BL; using System.Data; using SQMS.Services.Domain.Vehicle; using log4net; using EasyDev.Util; using System.Web.Script.Serialization; using SQMS.Services.Domain.QualityControl; namespace SQMS.Services { public class VehicleMissionService : GenericService { private static readonly ILog log = LogManager.GetLogger(typeof(VehicleMissionService)); protected override void Initialize() { this.BOName = "VEHICLETASK"; base.Initialize(); } public VehicleTask GetVehicleTaskObj(string id) { string sql = @"SELECT V.TASKID, V.TASKNAME, V.PUBLICTIME, V.STARTTIME, V.ENDTIME, V.MODEL, V.TASKTYPE, V.TRACE, V.CHARGEMAN AS CHARGEMANID, E.EMPNAME AS CHARGEMAN, V.LICENSEPLATENUM, V.ISGASSUPPLIED, V.ISWATERSUPPLIED, V.ISREPAIRED, V.CREATED, V.CREATEDBY, V.MODIFIED, V.MODIFIEDBY, V.ISVOID FROM VEHICLETASK V LEFT JOIN EMPLOYEE E ON E.EMPID = V.CHARGEMAN AND E.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"' WHERE V.TASKID = '" + id + "'"; DataTable dt = new DataTable(); VehicleTask obj = null; try { dt = this.DefaultSession.GetDataTableFromCommand(sql); obj = this.CreateSingleVehicleTask(dt.Rows[0]); } catch (Exception e) { log.Error(e.ToString()); throw; } return obj; } public DataTable GetVehicleTaskDataList(string taskId) { string sql = @"SELECT V.VTDID, V.TASKID, V.VIDEOURL, V.LATITUDE, V.LONGITUDE, V.IMAGEURL, V.TICKETID, V.TICKETTYPE, V.CREATED, V.CREATEDBY, V.MODIFIED, V.MODIFIEDBY, V.ISVOID FROM VEHICLETASKDATA V WHERE V.TASKID = '"+taskId+"'"; DataTable dt = new DataTable(); try { dt = this.DefaultSession.GetDataTableFromCommand(sql); } catch (Exception e) { log.Error(e.ToString()); throw; } return dt; } public List<VehicleTask> CreateVehicleTask(DataTable dt) { List<VehicleTask> list = new List<VehicleTask>(); foreach (DataRow dr in dt.Rows) { list.Add(this.CreateSingleVehicleTask(dr)); } return list; } public VehicleTask CreateSingleVehicleTask(DataRow dr) { VehicleTask obj = new VehicleTask(); obj.ChargeMan = ConvertUtil.ToStringOrDefault(dr["ChargeMan"]); obj.EndTime = ConvertUtil.ToDateTime(dr["EndTime"]); obj.IsGasSupplied = ConvertUtil.ToBool(dr["IsGasSupplied"]); obj.IsRepaired = ConvertUtil.ToBool(dr["IsRepaired"]); obj.IsVoid = ConvertUtil.ToBool(dr["IsVoid"]); obj.IsWaterSupplied = ConvertUtil.ToBool(dr["IsWaterSupplied"]); obj.LicensePlateNum = ConvertUtil.ToStringOrDefault(dr["LicensePlateNum"]); obj.Model = ConvertUtil.ToStringOrDefault(dr["Model"]); obj.PublicTime = ConvertUtil.ToDateTime(dr["PublicTime"]); obj.StartTime = ConvertUtil.ToDateTime(dr["StartTime"]); obj.TaskId = ConvertUtil.ToStringOrDefault(dr["TaskId"]); obj.TaskName = ConvertUtil.ToStringOrDefault(dr["TaskName"]); obj.TaskType = ConvertUtil.ToStringOrDefault(dr["TaskType"]); obj.Trace = new VehicleTrace(); obj.Trace.Points = ConvertUtil.ToStringOrDefault(dr["Trace"]); obj.Trace.Data = this.CreateVehicleTaskData(this.GetVehicleTaskDataList(obj.TaskId)); return obj; } //public List<VehicleTrace> CreateVehicleTrace(string trace, DataTable taskData) //{ // List<Dictionary<string, string>> dict = new List<Dictionary<string, string>>(); // try // { // JavaScriptSerializer s = new JavaScriptSerializer(); // dict = s.Deserialize<List<Dictionary<string, string>>>(trace); // } // catch { } // List<VehicleTrace> list = new List<VehicleTrace>(); // if (dict.Count <= 0) // { // return list; // } // List<VehicleTaskData> data = this.CreateVehicleTaskData(taskData); // foreach (Dictionary<string, string> item in dict) // { // VehicleTrace obj = new VehicleTrace(); // obj.LatLng = new SQMS.Services.Domain.QualityControl.LatLng(ConvertUtil.ToLat(item["Lat"]), ConvertUtil.ToLng(item["Lng"])); // //obj.Data // } //} public List<VehicleTaskData> CreateVehicleTaskData(DataTable dt) { List<VehicleTaskData> list = new List<VehicleTaskData>(); foreach (DataRow dr in dt.Rows) { VehicleTaskData obj = new VehicleTaskData(); obj.ImageUrl = ConvertUtil.ToStringOrDefault(dr["ImageUrl"]); obj.LatLng = new LatLng(ConvertUtil.ToLat(dr["LATITUDE"]), ConvertUtil.ToLng(dr["LONGITUDE"])); obj.TaskId = ConvertUtil.ToStringOrDefault(dr["TaskID"]); obj.TicketId = ConvertUtil.ToStringOrDefault(dr["TicketId"]); obj.TicketType = ConvertUtil.ToStringOrDefault(dr["TicketType"]); obj.VehicleTaskDataId = ConvertUtil.ToStringOrDefault(dr["VTDID"]); obj.VideoUrl = ConvertUtil.ToStringOrDefault(dr["VideoUrl"]); list.Add(obj); } return list; } public DataTable GetVehicleTaskList() { return this.GetVehicleTaskList(""); } public DataTable GetVehicleTaskList(string p) { string sql = @"SELECT V.TASKID, V.TASKNAME, V.PUBLICTIME, V.STARTTIME, V.ENDTIME, V.MODEL, V.TASKTYPE, V.TRACE, V.CHARGEMAN AS CHARGEMANID, E.EMPNAME AS CHARGEMAN, V.LICENSEPLATENUM, V.ISGASSUPPLIED, V.ISWATERSUPPLIED, V.ISREPAIRED, V.CREATED, V.CREATEDBY, V.MODIFIED, V.MODIFIEDBY, V.ISVOID FROM VEHICLETASK V LEFT JOIN EMPLOYEE E ON E.EMPID = V.CHARGEMAN AND E.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"'"; if (!String.IsNullOrEmpty(p)) { sql += " WHERE V.CREATED = TO_DATE('"+p+"', 'yyyy-mm-dd')"; } DataTable dt = new DataTable(); try { dt = this.DefaultSession.GetDataTableFromCommand(sql); } catch (Exception e) { log.Error(e.ToString()); throw; } return dt; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Store; using Newtonsoft.Json; using Pathoschild.SlackArchiveSearch.Framework; using Pathoschild.SlackArchiveSearch.Models; using Directory = System.IO.Directory; using Version = Lucene.Net.Util.Version; namespace Pathoschild.SlackArchiveSearch { /// <summary>The console app entry point.</summary> public static class Program { /********* ** Accessors *********/ /// <summary>The directory to which to write archive data.</summary> private static readonly string DataDirectory = Path.Combine(Path.GetTempPath(), "slack archive search"); /// <summary>The directory to which to write archive data.</summary> private static readonly string IndexDirectory = Path.Combine(DataDirectory, "index"); /// <summary>The number of matches to show on the screen at a time.</summary> const int PageSize = 5; /********* ** Public methods *********/ /// <summary>The console app entry point.</summary> public static void Main() { // load archive data Cache data; while (true) { // choose archive directory Console.WriteLine("Enter the directory path of the Slack archive (or leave it blank to use the last import):"); string archiveDirectory = Console.ReadLine(); // load previous import if (string.IsNullOrWhiteSpace(archiveDirectory)) { Console.WriteLine("Reading cache..."); data = Program.FetchCache(Program.DataDirectory); if (data == null) { Console.WriteLine("There's no cached import available."); continue; } break; } // import new data if (!Directory.Exists(archiveDirectory)) { Console.WriteLine("There's no directory at that path."); continue; } data = Program.ImportArchive(Program.DataDirectory, archiveDirectory); Program.RebuildIndex(data, Program.IndexDirectory); break; } // search archive data while (true) { // show header Console.Clear(); Console.WriteLine($"Found {data.Messages.Length} messages by {data.Users.Count} users in {data.Channels.Count} channels, posted between {data.Messages.Min(p => p.Date.LocalDateTime).ToString("yyyy-MM-dd HH:mm")} and {data.Messages.Max(p => p.Date.LocalDateTime).ToString("yyyy-MM-dd HH:mm")}."); Console.WriteLine($"All times are shown in {TimeZone.CurrentTimeZone.StandardName}."); Console.WriteLine(); Console.WriteLine("┌───Search syntax──────────────"); Console.WriteLine("│ You can enter a simple query to search the message text, or use Lucene"); Console.WriteLine("│ search syntax: https://lucene.apache.org/core/2_9_4/queryparsersyntax.html"); Console.WriteLine("│ Search is not case-sensitive."); Console.WriteLine("│"); Console.WriteLine("│ Available fields:"); Console.WriteLine("│ date (in ISO-8601 format like 2015-01-30T15:00:00, in UTC);"); Console.WriteLine("│ channel (like 'lunch');"); Console.WriteLine("│ user (like 'jesse.plamondon');"); Console.WriteLine("│ text (in slack format)."); Console.WriteLine("│"); Console.WriteLine("│Example searches:"); Console.WriteLine("│ pineapple"); Console.WriteLine("│ channel:lunch user:jesse.plamondon pineapple"); Console.WriteLine("│ channel:(developers OR deployment) text:\"deployed release\""); Console.WriteLine("└──────────────────────────────"); Console.WriteLine(); Console.WriteLine("\nWhat do you want to search?"); Console.Write("> "); // get search string string search = Console.ReadLine(); if (search == null) continue; // show matches Message[] matches = Program.SearchIndex(search, data, Program.IndexDirectory).ToArray(); Program.DisplayResults(matches, data.Channels, data.Users, Program.PageSize); } } /********* ** Private methods *********/ /// <summary>Interactively read data from a Slack archive into the cache.</summary> /// <param name="dataDirectory">The directory from which to load archive data.</param> /// <returns>Returns the cached data if it exists, else <c>null</c>.</returns> private static Cache FetchCache(string dataDirectory) { string cacheFile = Path.Combine(dataDirectory, "cache.json"); if (!File.Exists(cacheFile)) return null; string json = File.ReadAllText(cacheFile); return JsonConvert.DeserializeObject<Cache>(json); } /// <summary>Interactively read data from a Slack archive into the cache.</summary> /// <param name="dataDirectory">The directory to which to write archive data.</param> /// <param name="archiveDirectory">The archive directory to import.</param> private static Cache ImportArchive(string dataDirectory, string archiveDirectory) { // read metadata Console.WriteLine("Reading metadata..."); Dictionary<string, User> users = Program.ReadFile<List<User>>(Path.Combine(archiveDirectory, "users.json")).ToDictionary(p => p.ID); Dictionary<string, Channel> channels = Program.ReadFile<List<Channel>>(Path.Combine(archiveDirectory, "channels.json")).ToDictionary(p => p.ID); // read channel messages Console.WriteLine("Reading channel data..."); List<Message> messages = new List<Message>(); foreach (Channel channel in channels.Values) { foreach (string path in Directory.EnumerateFiles(Path.Combine(archiveDirectory, channel.Name))) { // read messages var channelMessages = Program.ReadFile<List<Message>>(path); foreach (Message message in channelMessages) { // inject message data message.MessageID = Guid.NewGuid().ToString("N"); // inject channel data message.ChannelID = channel.ID; message.ChannelName = channel.Name; // inject user data User user = message.UserID != null && users.ContainsKey(message.UserID) ? users[message.UserID] : null; if (user != null) { message.AuthorName = user.Name; message.AuthorUsername = user.UserName; } else { message.AuthorName = message.CustomUserName ?? message.UserID; message.AuthorUsername = message.CustomUserName ?? message.UserID; } } messages.AddRange(channelMessages); } } // cache data Console.WriteLine("Writing cache..."); Directory.CreateDirectory(dataDirectory); string cacheFile = Path.Combine(dataDirectory, "cache.json"); Cache cache = new Cache { Channels = channels, Users = users, Messages = messages.OrderByDescending(p => p.Date).ToArray() // sort newest first for index }; File.WriteAllText(cacheFile, JsonConvert.SerializeObject(cache)); return cache; } /// <summary>Interactively rebuild the search index.</summary> /// <param name="data">The data to index.</param> /// <param name="indexDirectory">The directory containing the search index.</param> public static void RebuildIndex(Cache data, string indexDirectory) { // clear previous index foreach (string file in Directory.EnumerateFiles(indexDirectory)) File.Delete(file); // build Lucene index Console.WriteLine("Building search index..."); using (FSDirectory directory = FSDirectory.Open(indexDirectory)) using (Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30)) using (IndexWriter writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) { foreach (var message in data.Messages) { Document doc = new Document(); doc.Add(new Field("id", message.MessageID, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("date", message.Date.ToString("o"), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("channel", message.ChannelName, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("user", message.AuthorUsername ?? "", Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("text", message.Text ?? "", Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } writer.Optimize(); writer.Flush(true, true, true); } } /// <summary>Find messages matching an index search.</summary> /// <param name="search">The search query.</param> /// <param name="data">The data to search.</param> /// <param name="indexDirectory">The directory containing the search index.</param> public static IEnumerable<Message> SearchIndex(string search, Cache data, string indexDirectory) { // return all matches for no search if (string.IsNullOrWhiteSpace(search)) { foreach (Message message in data.Messages) yield return message; yield break; } // search index using (FSDirectory directory = FSDirectory.Open(indexDirectory)) using (IndexReader reader = IndexReader.Open(directory, true)) using (Searcher searcher = new IndexSearcher(reader)) using (Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30)) { // build query parser QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_30, new[] { "id", "date", "channel", "user", "text"}, analyzer); parser.DefaultOperator = QueryParser.Operator.AND; parser.AllowLeadingWildcard = true; // search index Query query = parser.Parse(search); ScoreDoc[] hits = searcher.Search(query, null, 1000, Sort.INDEXORDER).ScoreDocs; // return matches foreach (ScoreDoc hit in hits) { Document document = searcher.Doc(hit.Doc); string messageID = document.Get("id"); Message message = data.Messages.FirstOrDefault(p => p.MessageID == messageID); if (message == null) { Console.WriteLine($"ERROR: couldn't find message #{messageID} matching the search index. The search index may be out of sync."); continue; } yield return message; } } } /// <summary>Interactively display search results.</summary> /// <param name="matches">The search results.</param> /// <param name="channels">The known channels.</param> /// <param name="users">The known users.</param> /// <param name="pageSize">The number of items to show on the screen at one time.</param> private static void DisplayResults(Message[] matches, IDictionary<string, Channel> channels, IDictionary<string, User> users, int pageSize) { // no matches if (!matches.Any()) { Console.WriteLine("No matches found. :("); Console.WriteLine("Hit enter to continue."); Console.ReadLine(); return; } // format matches for output string[] output = matches.Select(message => { string formattedText = message.Text != null ? String.Join("\n│ ", message.Text.Split('\n')) : ""; return "┌──────────────────────────────\n" + $"│ Date: {message.Date.LocalDateTime.ToString("yyyy-MM-dd HH:mm")}\n" + $"│ Channel: #{message.ChannelName}\n" + $"│ User: {message.AuthorUsername}\n" + $"| {formattedText}\n" + "└──────────────────────────────\n"; }).ToArray(); // write matches to console int offset = 0; int count = matches.Length; while (true) { Console.Clear(); // print header Console.WriteLine($"Found {count} matches."); // print results Console.WriteLine(String.Join("\n", output.Skip(offset).Take(pageSize))); // print footer Console.WriteLine($"Viewing matches {offset + 1}–{Math.Min(count, offset + 1 + pageSize)} of {count}."); string question = ""; if (offset > 0) question += "[p]revious page "; if (offset + pageSize < count) question += "[n]ext page "; question += "[q]uit"; switch (Program.ReadOption(question, 'p', 'n', 'q')) { case 'p': offset = Math.Max(0, offset - pageSize); continue; case 'n': offset = Math.Min(count, offset + pageSize); continue; case 'q': return; } } } /// <summary>Read an option from the command line.</summary> /// <param name="message">The question to ask.</param> /// <param name="options">The accepted values.</param> private static char ReadOption(string message, params char[] options) { while (true) { Console.WriteLine(message); string response = Console.ReadLine(); if (string.IsNullOrEmpty(response) || !options.Contains(response[0])) { Console.WriteLine("Invalid answer."); continue; } return response[0]; } } /// <summary>Parse a file's JSON contents.</summary> /// <typeparam name="T">The model type matching the file contents.</typeparam> /// <param name="path">The file path.</param> private static T ReadFile<T>(string path) { string json = File.ReadAllText(path); return JsonConvert.DeserializeObject<T>(json, new UnixDateTimeConverter()); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HomeBaseCore.Models { public class DataContext : DbContext { public DbSet<ProfileData> profiles { get; set; } public DbSet<FolderData> folders { get; set; } public DbSet<FileData> files { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=data.db"); } } public class ProfileData { public string ProfileDataID { get; set; } public string ProfileGuid { get; set; } public string Username { get; set; } public string Password { get; set; } } public class FolderData { public string OwnerProfileID { get; set; } public int FolderDataID { get; set; } public int RootFolderID { get; set; } public string FolderPath { get; set; } public string FolderName { get; set; } public string FolderDescription { get; set; } } public class FileData { public int FileDataID { get; set; } public int FolderID { get; set; } public string OwnerProfileID { get; set; } public string FilePath { get; set; } public string FileName { get; set; } public string FileDescription { get; set; } } }
using System; using System.Collections.Generic; namespace Server { public static class Map { static int height, width; public static int Width { get { return width; } } public static int Height { get { return height; } } private static Coord SpawnPoint; public static Coord Spawnpoint{ get { return SpawnPoint; } } private static MapLayer Ground; private static MapLayer Objects; private static MapLayer Blocks; public static void Initialize (int h, int w, Coord spawnpoint) { height = h; width=w; SpawnPoint = spawnpoint; } public static void AddLayer (MapLayer mapLayer) { switch (mapLayer.type) { case LayerType.Blocking: Blocks = mapLayer; break; case LayerType.Ground: Ground=mapLayer; break; case LayerType.Object: Objects = mapLayer; break; } } public static MapLayer GetLayer (LayerType t) { switch (t) { case LayerType.Ground: return Ground; case LayerType.Object: return Objects; } return null; } public static bool withinBounds (Coord position) { if (position.X < 0 || position.Y < 0 || position.X >= width || position.Y >= height) return false; return true; } /* public static bool ValidPosition (Coord position) { if (!withinBounds(position)) return false; foreach(Player p in Network.getPlayers) foreach (Character c in p.chars) if (c.Position==position && c.noclip==false) return false; if (Blocks.TileAt(position) >-1) return false; return true; }*/ public static bool ValidPosition (Coord position, Character moving) { if (!withinBounds (position)) return false; foreach (Player p in Network.Players) foreach (Character c in p.chars) for (int x = 0; x < c.Size; x++) for (int y = 0; y < c.Size; y++) { if (c.Position+new Coord(x,y) == position && c.noclip == false && moving.ID != c.ID) return false; } if (Blocks.TileAt(position) >-1) return false; return true; } public static void ParseMapLayer (LayerType type,int width, int height, string parseData) { int[,] data = new int[width, height]; string[] rows = parseData.Split ('|'); string[] cols; for (int y =0; y < rows.Length;y++) { cols = rows[y].Split(','); for (int x = 0; x < cols.Length;x++) data[x,y] = Int16.Parse(cols[x]); } if (type==LayerType.Blocking) Blocks= new MapLayer(type,width,height,data); if (type==LayerType.Object) Objects= new MapLayer(type,width,height,data); if (type==LayerType.Ground) Ground= new MapLayer(type,width,height,data); } public static bool ChangeObject (int objID, int blocking, int x, int y) { Blocks.tiles[x,y]=blocking; if (Objects.tiles [x, y] == objID) return false; Objects.tiles[x,y]=objID; return true; } public static bool ChangeTile (int tileID, int x, int y) { if (Ground.tiles [x, y] == tileID) return false; Ground.tiles [x, y] = tileID; return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallEnterMaze : MonoBehaviour { public bool mazeActive = false; private void OnCollisionEnter(Collision collision) { GameObject ball = GameObject.Find("aMazeBall"); if (collision.gameObject.name == "aMazeBall") Destroy(ball); mazeActive = true; } }
/**************************************************************** * -------------字符串点阵烧写工具----------------- * 16高点阵中,需要显示中英文字符串,本项目会根据一定格式将字符hex编码 * 下发的单片机中 * *************************************************************/ using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; using CmdHZK; namespace StringGUI { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } /**************************************************************************** * 各种类型定义 ***************************************************************************/ SerialPort ComPort = new SerialPort(); //串口基类 List<customer> ComList = new List<customer>(); //可用串口列表,该列表不是一次性,会刷新 Thread _ComSend = null; //线程还是不要局部变量了 DispatcherTimer AutoSendTick = new DispatcherTimer(); //定时发送线程 private byte[] SendStream; //有效数据流,长度是 private int SendOffset = 0; //发送偏移 private int SendAll = 0; //总数据段数 //各种标志位 private struct Flag_t { public bool IsOpen; //串口是否逻辑打开,注意和SerialPort.IsOpen的实际打开区别 public bool WaitClose; //invoke里判断是否正在关闭串口是否正在关闭串口,执行Application.DoEvents,并阻止再次invoke ,解决关闭串口时,程序假死,具体参见http://news.ccidnet.com/art/32859/20100524/2067861_4.html 仅在单线程收发使用,但是在公共代码区有相关设置,所以未用#define隔离 public bool RecvSta; //当前是否正在接收 public bool Sending; //当前线程是否正在发送中 } private Flag_t UartFlag = new Flag_t(); private struct SendArgv_t//发送数据线程传递参数的结构体格式 { public string data; //发送的数据 public bool hex; //发送模式,是否为16进制 } /**************************************************************************** * 串口配置类,用于combobox的下拉控件。 * Combobox的显示(DisplayMemberPath)类型是String,真实值SelectedValue类型是object * 经过测试,校验位的显示值(Odd,Even)不能直接传入SerialPort,必须使用对应的enum * 停止位使用(1,2)这种可以直接传入SerialPort,使用(One,Two)则不行 ***************************************************************************/ internal class customer { public string com { get; set; } //可用串口 public string BaudRate { get; set; } //波特率 public string Dbits { get; set; } public Parity PbitsValue { get; set; } public string Pbits { get; set; } public string Sbits { get; set; } } /**************************************************************************** * 功能:刷新当前可用串口,并添加到Combobox中 * 描述: * 参数: * 返回:存在串口返回true,不存在返回false ***************************************************************************/ private bool GetPort() { ComList.Clear(); //若不移除,会重复 string[] port = SerialPort.GetPortNames(); //获取可用串口,static方法 if (port.Length > 0) { for (int i = 0; i < port.Length; i++) { ComList.Add(new customer() { com = port[i] }); //使用匿名方法添加串口列表 } w_port.ItemsSource = ComList; //资源路径 w_port.DisplayMemberPath = "com"; //显示路径 w_port.SelectedValuePath = "com"; //值路径 w_port.SelectedIndex = 0; //同上 return true; } else { return false; } } /**************************************************************************** * 功能:当窗口初步生成时,发生 * 描述: * 参数: * 返回: ***************************************************************************/ private void Window_Loaded(object sender, RoutedEventArgs e) { //↓↓↓↓↓↓↓↓↓可用串口下拉控件↓↓↓↓↓↓↓↓↓ if (GetPort() == false) { MessageBox.Show("当前无可用串口!"); } //↑↑↑↑↑↑↑↑↑可用串口下拉控件↑↑↑↑↑↑↑↑↑ //↓↓↓↓↓↓↓↓↓其他默认设置↓↓↓↓↓↓↓↓↓ ComPort.BaudRate = 9600; ComPort.DataBits = 8; ComPort.Parity = Parity.None; ComPort.StopBits = StopBits.Two; ComPort.ReadTimeout = 8000; //读超时8s ComPort.WriteTimeout = 8000; ComPort.ReadBufferSize = 1024; //读数据缓存 ComPort.WriteBufferSize = 1024; w_BtnSend.IsEnabled = false; //发送按钮默认不可用 UartFlag.IsOpen = false; UartFlag.WaitClose = false; UartFlag.RecvSta = true; //↑↑↑↑↑↑↑↑↑其他默认设置↑↑↑↑↑↑↑↑↑ ComPort.DataReceived += InterrputComRecvive; //添加串口接收中断处理 AutoSendTick.Tick += InterruptAutoSend; //定时发送 } /**************************************************************************** * 功能:自动发送 * 描述: * 参数: * 返回: ***************************************************************************/ private void InterruptAutoSend(object sender, EventArgs e) { send(); } private void send() { if (UartFlag.Sending == true) return; //如果当前正在发送,则取消本次发送,本句注释后,可能阻塞在ComSend的lock处 SendArgv_t SendArgv = new SendArgv_t(); SendArgv.data = wpf_SendBox.Text; SendArgv.hex = (bool)wpf_SendHex.IsChecked; _ComSend = new Thread(new ParameterizedThreadStart(ComSend)); //new发送线程,不带参数 _ComSend.Start(SendArgv); } //参数必须是object private void ComSend(object obj) { lock (this)//由于send()中的if (Sending == true) return,所以这里不会产生阻塞,如果没有那句,多次启动该线程,会在此处排队 { SendArgv_t argv = (SendArgv_t)obj; //转换类型,用于提取 UartFlag.Sending = true; byte[] buf = null; //发送数据缓冲区 byte[] data = argv.data; //获取发送框中的数据 try //尝试将发送的数据转为16进制Hex { List<string> sendData16 = new List<string>();//将发送的数据,2个合为1个,然后放在该缓存里 如:123456→12,34,56 for (int i = 0; i < data.Length; i += 2) { sendData16.Add(data.Substring(i, 2)); } buf = new byte[sendData16.Count];//sendBuffer的长度设置为:发送的数据2合1后的字节数 for (int i = 0; i < sendData16.Count; i++) { buf[i] = (byte)(Convert.ToInt32(sendData16[i], 16));//发送数据改为16进制 } } catch //无法转为16进制时,出现异常 { //跨线程访问数据,同步模式 Dispatcher.Invoke((ThreadStart)delegate () { MessageBox.Show("请输入正确的16进制数据"); }, null); UartFlag.Sending = false;//关闭正在发送状态 _ComSend.Abort();//终止本线程 return;//输入的16进制数据错误,无法发送,提示后返回 } } else //ASCII码文本发送 { buf = Encoding.Default.GetBytes(data);//转码,ascii转16进制??? //buf = Convert.ToChar(data) } try //尝试发送数据 { //如果发送字节数大于1000,则每1000字节发送一次 int SendTimes = (buf.Length / 1000);//发送次数 for (int i = 0; i < SendTimes; i++)//每次发送1000Bytes { ComPort.Write(buf, i * 1000, 1000);//发送sendBuffer中从第i * 1000字节开始的1000Bytes //跨线程访问数据,异步模式 Dispatcher.BeginInvoke((ThreadStart)delegate () { wpf_SendCnt.Text = (Convert.ToInt32(wpf_SendCnt.Text) + 1000).ToString();//刷新发送字节数,一次+1000 }, null); } if (buf.Length % 1000 != 0) //发送字节小于1000Bytes或上面发送剩余的数据 { ComPort.Write(buf, SendTimes * 1000, buf.Length % 1000); Dispatcher.BeginInvoke((ThreadStart)delegate () { wpf_SendCnt.Text = (Convert.ToInt32(wpf_SendCnt.Text) + buf.Length % 1000).ToString();//刷新发送字节数 }, null); } } catch//如果无法发送,产生异常 { Dispatcher.BeginInvoke((ThreadStart)delegate () { if (ComPort.IsOpen == false)//如果ComPort.IsOpen == false,说明串口已丢失 { SetComLose();//串口丢失后的设置 } else { MessageBox.Show("无法发送数据,原因未知!"); } }, null); } //sendScrol.ScrollToBottom();//发送数据区滚动到底部 UartFlag.Sending = false;//关闭正在发送状态 _ComSend.Abort();//终止本线程 } } /**************************************************************************** * 功能:串口接收中断处理程序 * 描述:中断是一个单独线程 * 参数: * 返回: ***************************************************************************/ private void InterrputComRecvive(object sender, SerialDataReceivedEventArgs e) { //if (WaitClose) return;//如果正在关闭串口,则直接返回 //Thread.Sleep(10);//发送和接收均为文本时,接收中为加入判断是否为文字的算法,发送你(C4E3),接收可能识别为C4,E3,可用在这里加延时解决 if (UartFlag.RecvSta == true)//如果已经开启接收 { byte[] RecBuf = null;//接收缓冲区 try { RecBuf = new byte[ComPort.BytesToRead]; //接收数据缓存大小 ComPort.Read(RecBuf, 0, RecBuf.Length); //读取数据 } catch { Thread.Sleep(100); //休眠一段时间后再继续接收??? } RecvDataDeal(RecBuf); //接收数据处理 } else//暂停接收 { ComPort.DiscardInBuffer();//清接收缓存 } } private void w_BtnSend_Click(object sender, RoutedEventArgs e) { #region 打开串口 if (UartFlag.IsOpen == false) //当前串口逻辑关闭,按钮功能为打开 { try//尝试打开串口 { ComPort.PortName = w_port.SelectedValue.ToString(); //串口,类型string ComPort.Open(); } catch//如果串口被其他占用,则无法打开 { MessageBox.Show("无法打开串口,请检测此串口是否有效或被其他占用!"); GetPort(); //刷新当前可用串口 return; //无法打开串口,提示后直接返回 } //↓↓↓↓↓↓↓↓↓成功打开串口后的设置↓↓↓↓↓↓↓↓↓ UartFlag.IsOpen = true; //串口打开状态字改为true //↑↑↑↑↑↑↑↑↑成功打开串口后的设置↑↑↑↑↑↑↑↑↑ } #endregion HZK MyHzk = new HZK(); string str = "舒华欢迎您"; byte[] data = MyHzk.GetStringData(str); MyHzk.SaveTxtFile("12.txt", data); Console.ReadKey(); } } }
using CQRSWebAPI.DTOs; using CQRSWebAPI.Extension; using CQRSWebAPI.Redis; using MediatR; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace CQRSWebAPI.Behaviors { public class EventSourceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> { private readonly ILogger<EventSourceBehaviour<TRequest, TResponse>> logger; private readonly IRedisManager redisManager; public EventSourceBehaviour(ILogger<EventSourceBehaviour<TRequest,TResponse>> logger,IRedisManager redisManager) { this.logger = logger; this.redisManager = redisManager; } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { logger.LogInformation("this is in Event Sourcing"); var response = await next(); if (request.GetType().Name.Contains("Command")) { var eventData = new EventData { APIName = request.GetType().Name, Date = DateTime.Now, Request = request.Serilize(), Response = response.Serilize() }; logger.LogInformation("event sourcing successful"); if (!redisManager.CreateEventSourcing(eventData)) logger.LogError("Event Sorcing Error Save!", eventData.Serilize()); } return response; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Mvc5Calculator.Models { public class Converter { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string FromUnit { get; set; } public float FromValue { get; set; } public string ToUnit { get; set; } public float ToValue { get; set; } } //public class ConverterDBContext : DbContext //{ // public DbSet<Converter> Converter { get; set; } //} }
using Alabo.App.Share.HuDong.Domain.Enums; using Alabo.Domains.Entities; using Alabo.Domains.Enums; using Alabo.Web.Mvc.Attributes; using MongoDB.Bson.Serialization.Attributes; using System.ComponentModel.DataAnnotations.Schema; namespace Alabo.App.Share.HuDong.Domain.Entities { [BsonIgnoreExtraElements] [Table("HudongRecord")] [ClassProperty(Name = "互动记录", Icon = "fa fa-cog", SortOrder = 1)] public class HudongRecord : AggregateMongodbUserRoot<HudongRecord> { /// <summary> /// 获奖描述 /// </summary> [BsonRequired] public string Intro { get; set; } /// <summary> /// 状态 /// </summary> [BsonRequired] public AwardStatus HuDongStatus { get; set; } /// <summary> /// 互动类型 /// </summary> public HuDongEnums HuDongType { get; set; } /// <summary> /// 等级 /// </summary> public string Grade { get; set; } /// <summary> /// 奖品类型 /// </summary> public HudongAwardType HuDongActivityType { get; set; } } }
using AlgorithmProblems.Graphs.GraphHelper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Graphs { /// <summary> /// Color the vertices in a graph with 2 different colors such that no 2 connected vertices have the same color /// </summary> class ColorVertices { private static Dictionary<GraphVertex, int> vertexColorDict = new Dictionary<GraphVertex, int>(); /// <summary> /// Color the vertices in a graph with 2 different colors such that no 2 connected vertices have the same color /// /// We do a BFS here and color all odd layer node with the same color /// if you encounter any node in the odd layer with the color of the even layer then return false /// </summary> /// <returns></returns> private static bool ColorVerticesWithDifferentColor(GraphVertex vertex) { Queue<GraphVertex> queueForBFS = new Queue<GraphVertex>(); queueForBFS.Enqueue(vertex); vertexColorDict[vertex] = 0; while(queueForBFS.Count>0) { GraphVertex currentVertex = queueForBFS.Dequeue(); foreach (GraphVertex neighbour in vertex.NeighbourVertices) { if (vertexColorDict.ContainsKey(neighbour) && vertexColorDict[neighbour] == vertexColorDict[currentVertex]) { // This is a visited node // We have hit the case where we cannot meet the condition that 2 vertices of the edge has different color return false; } else if (!vertexColorDict.ContainsKey(neighbour)) { // This is an unvisited node vertexColorDict[neighbour] = (vertexColorDict[currentVertex] + 1) % 2; queueForBFS.Enqueue(neighbour); } } } return true; } public static void TestColorVerticesWithDifferentColor() { DirectedGraph dg = GraphProbHelper.CreateDirectedGraph(); Console.WriteLine("Can the graph nodes be colored: {0}", ColorVerticesWithDifferentColor(dg.AllVertices[2])); dg.RemoveEdge(0, 1); Console.WriteLine("Can the graph nodes be colored: {0}", ColorVerticesWithDifferentColor(dg.AllVertices[2])); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SQMS.Services; using EasyDev.Util; using System.Data; namespace SQMS.Application.Views.Quality { public partial class AnchorContent : SQMSPage<QualityControlService> { public QualityControlService srv = null; /// <summary> /// 常态监控时间点 /// </summary> public string TimeSpot { get { string tmp = ConvertUtil.ToStringOrDefault(ViewState["TIMESPOT"]); if (tmp == null || tmp.Length == 0) { tmp = ConvertUtil.ToStringOrDefault(Request.QueryString["timespot"]); ViewState.Add("TIMESPOT", tmp); } return tmp; } } /// <summary> /// 巡检的起始时间段 /// </summary> public string BeginTime { get { string tmp = ConvertUtil.ToStringOrDefault(ViewState["BEGINTIME"]); if (tmp == null || tmp.Length == 0) { tmp = ConvertUtil.ToStringOrDefault(Request.QueryString["begintime"]); ViewState.Add("BEGINTIME", tmp); } return tmp; } } /// <summary> /// 巡检的结束时间段 /// </summary> public string EndTime { get { string tmp = ConvertUtil.ToStringOrDefault(ViewState["ENDTIME"]); if (tmp == null || tmp.Length == 0) { tmp = ConvertUtil.ToStringOrDefault(Request.QueryString["endtime"]); ViewState.Add("ENDTIME", tmp); } return tmp; } } /// <summary> /// 监控类型 /// </summary> public string Type { get { string tmp = ConvertUtil.ToStringOrDefault(ViewState["TYPE"]); if (tmp == null || tmp.Length == 0) { tmp = ConvertUtil.ToStringOrDefault(Request.QueryString["type"]); ViewState.Add("TYPE", tmp); } return tmp; } } /// <summary> /// 历史日期 /// </summary> public string HistoryDate { get { string tmp = ConvertUtil.ToStringOrDefault(ViewState["HISTORYDATE"]); if (tmp == null || tmp.Length == 0) { tmp = ConvertUtil.ToStringOrDefault(Request.QueryString["date"]); ViewState.Add("HISTORYDATE", tmp); } return tmp; } } /// <summary> /// 监控点ID /// </summary> public string MonitorPointID { get { string tmp = ConvertUtil.ToStringOrDefault(ViewState["MPID"]); if (tmp == null || tmp.Length == 0) { tmp = ConvertUtil.ToStringOrDefault(Request.QueryString["mpid"]); ViewState.Add("MPID", tmp); } return tmp; } } /// <summary> /// 时间项ID /// </summary> public string TimeItemID { get { string tmp = ConvertUtil.ToStringOrDefault(ViewState["TIMEITEMID"]); if (tmp == null || tmp.Length == 0) { tmp = ConvertUtil.ToStringOrDefault(Request.QueryString["timetitemid"]); ViewState.Add("TIMEITEMID", tmp); } return tmp; } } protected void Page_Load(object sender, EventArgs e) { } protected override void OnPreInitializeViewEventHandler(object sender, EventArgs e) { srv = Service as QualityControlService; } protected override void OnInitializeViewEventHandler(object sender, EventArgs e) { this.lstImage.DataSource = ViewData.Tables[srv.BOName+"_Image"]; this.lstImage.DataBind(); this.lstVideo.DataSource = ViewData.Tables[srv.BOName + "_Video"]; this.lstVideo.DataBind(); } protected override void OnLoadDataEventHandler(object sender, EventArgs e) { //获取时间点数据 ViewData = srv.TimeItemService.LoadByCondition("organizationid='" + CurrentUser.OrganizationID + "'"); DataRow drTimeItem = DataSetUtil.GetFirstRowFromDataSet(ViewData,srv.TimeItemService.BOName); int floattime = 0; if (drTimeItem != null) { floattime = Convert.ToInt32(drTimeItem["FLOATTIME"]); } //获取常态或巡检质量数据 ViewData.Merge(srv.FindQualityData(MonitorPointID, this.Type, floattime, this.HistoryDate, TimeSpot, BeginTime, EndTime, "_Image")); ViewData.Merge(srv.FindQualityData(MonitorPointID, this.Type, floattime, this.HistoryDate, TimeSpot, BeginTime, EndTime, "_Video")); } } }
using System; using System.Collections.Generic; using System.Linq; namespace _05._Bomb_Numbers { class Program { static void Main(string[] args) { List<int> numbers = Console.ReadLine() .Split() .Select(int.Parse) .ToList(); List<int> bomb = Console.ReadLine() .Split() .Select(int.Parse) .ToList(); int bombNumber = bomb[0]; int power = bomb[1]; for (int i = 0; i < numbers.Count; i++) { if (numbers[i] == bombNumber ) { numbers = Detonate(numbers, power, i, bombNumber); i--; } } Console.WriteLine(numbers.Sum()); } private static List<int> Detonate(List<int> numbers, int power, int bombNumberIndex, int bombNumber) { if (bombNumberIndex + power >= numbers.Count && bombNumberIndex - power < 0) { numbers.RemoveRange(0, numbers.Count); } else if (bombNumberIndex + power >= numbers.Count) { numbers.RemoveRange(bombNumberIndex - power, numbers.Count - bombNumberIndex + power ); } else if (bombNumberIndex - power < 0) { numbers.RemoveRange(0, bombNumberIndex + power + 1); } else { numbers.RemoveRange(bombNumberIndex - power, power * 2 + 1); } return numbers; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using AutoMapper; using GDS.WebApi.Profiles; namespace GDS.WebApi { public class AutoMapperProfile { public static void Register() { Mapper.Initialize(cfg => { cfg.AddProfile<TemplatePhaseProfile>(); cfg.AddProfile<TemplatePhaseReqProfile>(); cfg.AddProfile<ProjectPreviewProfile>(); }); } } }
using System; using System.Collections.Generic; using System.Collections; using System.Collections.Specialized; namespace LeetCodeTests { public abstract class Problem_0088 { /* 88. Merge Sorted Array Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space(size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. */ public static void Test() { Solution sol = new Solution(); /* var input = new int[] { 2, 7, 11, 15 }; Console.WriteLine($"Input array: {string.Join(", ", input)}"); */ int m = 5; int n = 3; int[] nums1 = new int[] { 1, 3, 5, 0, 0, 0, 0, 0, 0, 0 }; int[] nums2 = new int[] { 2, 4, 6, 8, 10 }; Console.WriteLine($@"For input '{Utils.PrintArray(nums1)}' (m={m}) and '{Utils.PrintArray(nums2)}' (n={n})"); sol.Merge(nums1, m, nums2, n); Console.WriteLine($"Output: '{Utils.PrintArray(nums1)}'"); /* Submission Result: Wrong Answer Input: [0] 0 [1] 1 Output: [0] Expected: [1] */ m = 0; n = 1; nums1 = new int[] { 0 }; nums2 = new int[] { 1 }; Console.WriteLine($@"For input '{Utils.PrintArray(nums1)}' (m={m}) and '{Utils.PrintArray(nums2)}' (n={n})"); sol.Merge(nums1, m, nums2, n); Console.WriteLine($"Output: '{Utils.PrintArray(nums1)}'"); } public class Solution { public void Merge(int[] nums1, int m, int[] nums2, int n) { int insPos = m + n - 1; m--; n--; // change to indexes Func<int[], int, int> getAtIndex = (nums, ind) => { if (ind < 0) return int.MinValue; return nums[ind]; }; while (insPos >= 0) { if (getAtIndex(nums1, m) >= getAtIndex(nums2, n)) { nums1[insPos] = getAtIndex(nums1, m); m--; } else { nums1[insPos] = getAtIndex(nums2, n); n--; } insPos--; } }// } }//public abstract class Problem_ }
namespace Zebble { using System.Runtime.InteropServices; partial class WebViewRenderer { const int URLMON_OPTION_USERAGENT = 0x10000001; [DllImport("urlmon.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved); static void SetDefaultUserAgent() { var userAgent = "Mozilla/5.0 (compatible; MSIE 10.0; WebView/3.0; Windows Phone 10.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 925)"; if (Services.CssEngine.Platform == DevicePlatform.IOS) userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"; if (Services.CssEngine.Platform == DevicePlatform.Android) userAgent = "Mozilla/5.0 (Linux; Android 4.4.2; en-us; SAMSUNG SM-G900T Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.6 Chrome/28.0.1500.94 Mobile Safari/537.36"; UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, userAgent, userAgent.Length, 0); } } }
using System; namespace Task12 { class Program { static void Main(string[] args) { Console.Write("Въведете височина: "); int y = Int32.Parse(Console.ReadLine()); Console.Write("Въвете ширина: "); int x = Int32.Parse(Console.ReadLine()); int a = 0; for (int i = 1; i <= y; i++) { Console.Write("{0} ", i); a += i; for (int j = 1; j < x; j++) { a += y; Console.Write("{0} ", a); } a = 0; Console.WriteLine(); } } } }
using gView.Framework.IO; using gView.Framework.system; namespace gView.Framework.Network { public interface IGraphWeightFeatureClass : IPersistable { int FcId { get; } string FieldName { get; } ISimpleNumberCalculation SimpleNumberCalculation { get; } } }
using UnityEngine; using System.Collections; namespace EventSystem { public class IgnoreRepairUnitEvent : GameEvent { public readonly Unit Unit; public IgnoreRepairUnitEvent (Unit unit) { Unit = unit; } } }
using Library.Entities.Models; using Library.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Library.Entities.Filters { public class BookHistoryFilter : BaseFilter<BookHistory> { public string Name { get; set; } public override (IQueryable<BookHistory> items, Lazy<int> total) ApplyTo(IQueryable<BookHistory> source) { if (!string.IsNullOrEmpty(Name)) source = source.Where(x => x.Book.Name.ToLower().Contains(Name.ToLower())); return base.ApplyTo(source); } } }
using System; using System.Collections.Generic; using Irony.Parsing; using JetBrains.Annotations; namespace iSukces.Code.Irony { public class IronyAutocodeGeneratorModel { [CanBeNull] public SequenceRuleBuilder.TokenInfoResult GetTokenInfoByName(ITokenNameSource src) { var terminalName = src.GetTokenName(); if (Punctuations.ContainsTerminalName(terminalName)) return new SequenceRuleBuilder.TokenInfoResult { IsNoAst = true }; if (ReservedWords.ContainsTerminalName(terminalName)) return new SequenceRuleBuilder.TokenInfoResult { IsNoAst = false }; foreach (var i in BracketsPairs) if (i.Item1 == terminalName.Name || i.Item2 == terminalName.Name) return new SequenceRuleBuilder.TokenInfoResult { IsNoAst = false }; switch (terminalName) { case TokenName tn: { foreach (var i in SpecialTerminals) if (i.Value == tn.Name) return new SequenceRuleBuilder.TokenInfoResult { SpecialTerminal = i.Key }; return null; } } return null; } public IronyAutocodeGeneratorModel WithDelimitedComment(string startSymbol, params string[] endSymbols) { DelimitedComment = new CommentInfo("DelimitedComment", startSymbol, endSymbols); return this; } public IronyAutocodeGeneratorModel WithSingleLineComment(string startSymbol, params string[] endSymbols) { SingleLineComment = new CommentInfo("SingleLineComment", startSymbol, endSymbols); return this; } public TerminalInfo WithTerm(string code, TokenName name) { var termInfo = new TerminalInfo(code, name); Terminals.Add(termInfo); return termInfo; } internal AstTypesInfoDelegate GetAstTypesInfoDelegate(ITokenNameSource src) { { var h = OnGetAstTypesInfoDelegate; if (h != null) { var arg = new OnGetAstTypesInfoDelegateEventArgs(src); h(this, arg); if (arg.Handled) return arg.Result; } } switch (src) { case NonTerminalInfo nti: return AstTypesInfo.BuildFrom(nti, Names); } var exp = src.GetTokenName(); switch (exp) { case TokenName tn: { foreach (var i in SpecialTerminals) if (i.Value == tn.Name) return AstTypesInfo.BuildFrom(i.Key); return null; } } } public NonTerminalInfo Root { get; set; } public CommentInfo SingleLineComment { get; set; } public CommentInfo DelimitedComment { get; set; } public List<NonTerminalInfo> NonTerminals { get; } = new List<NonTerminalInfo>(); public Type DefaultAstBaseClass { get; set; } public List<Tuple<string, string>> BracketsPairs { get; } = new List<Tuple<string, string>>(); public GrammarNames Names { get; set; } public TerminalsList Terminals { get; } = new TerminalsList(); public Dictionary<SpecialTerminalKind, string> SpecialTerminals { get; } = new Dictionary<SpecialTerminalKind, string>(); public NumberOptions CSharpNumberLiteralOptions { get; set; } public TerminalsList ReservedWords { get; } = new TerminalsList(); public TerminalsList Punctuations { get; } = new TerminalsList(); public IDoEvaluateHelper DoEvaluateHelper { get; set; } public event EventHandler<OnGetAstTypesInfoDelegateEventArgs> OnGetAstTypesInfoDelegate; public sealed class OnGetAstTypesInfoDelegateEventArgs : EventArgs { public OnGetAstTypesInfoDelegateEventArgs(ITokenNameSource src) => Source = src; public AstTypesInfoDelegate Result { get; set; } public ITokenNameSource Source { get; } public bool Handled { get; set; } } } }
using UnityEngine; using System.Collections; using System; public class LevelScript : MonoBehaviour { public int levelIndex; public GameObject[] enemies; GameState state; public TransitionPointScript[] portals; public bool isCheckpoint; // Use this for initialization void Start () { state=GameObject.Find ("GameState").GetComponent<GameState> (); portals = GetComponentsInChildren<TransitionPointScript> (); if (!state.enemyState.ContainsKey (levelIndex)) { //è la prima volta che accedo a questo livello, setto tutti a true Debug.Log("First load of this level:"+levelIndex); if (enemies.Length > 0) { bool[] livingEnemies = new bool[enemies.Length]; for (int i = 0; i < enemies.Length; i++) { livingEnemies [i] = true; } state.enemyState.Add (levelIndex, livingEnemies); } else { state.enemyState.Add (levelIndex, new bool[0]); } } else { Debug.Log("Not first load, destroing enemies (level:"+levelIndex+")"); //non è la prima volta che accedo a questo livello, leggo dal dizionario chi uccidere bool[] livingEnemies=state.enemyState[levelIndex]; for (int i = 0; i < livingEnemies.Length; i++) { if (!livingEnemies [i]) { Debug.Log ("killing enemy " + enemies [i]); enemies [i].SetActive (false); } } } if(IsAllEnemyDied ()){ //se sono morti tutti, chiamo la funzione AllEnemyDied Debug.Log("All Enemy of level "+levelIndex+" Died!"); AllEnemyDied(); } if (isCheckpoint) { state.indexLastCheckpointVisited = levelIndex; } } public void EnemyDied(GameObject enemy){ Debug.Log ("enemy ad index " + Array.IndexOf (enemies, enemy) + " died"); state.enemyState [levelIndex] [Array.IndexOf (enemies, enemy)] = false; if(IsAllEnemyDied ()){ //se sono morti tutti, chiamo la funzione AllEnemyDied Debug.Log("All Enemy of level "+levelIndex+" Died!"); AllEnemyDied(); } } public bool IsAllEnemyDied(){ foreach (bool enemy in state.enemyState [levelIndex]) { Debug.Log ("enemy died " + enemy); } bool someoneAlive=Array.Find (state.enemyState [levelIndex], (item) => { return item; }); return !someoneAlive; } void AllEnemyDied(){ //attivo i portali foreach (TransitionPointScript portal in portals) { portal.GetComponent<BoxCollider2D> ().enabled = true; } } public void OnFinishedLoad() { StartCoroutine(CheckCharacterPositions()); } IEnumerator CheckCharacterPositions() { while (true) { yield return new WaitForSeconds(0.1f); GameObject o = GameObject.Find("orfeo"); if (o != null) { Vector3 posOrfeo = o.transform.position; GameObject frame = transform.FindChild("Frame").gameObject; if (Math.Abs(posOrfeo.x - frame.transform.position.x) >= 2.6f || Math.Abs(posOrfeo.y - frame.transform.position.y) >= 5f) { print("Bananaaaaaa"); GameObject.Find("SceneManager").GetComponent<SceneManager>().RepositionateCharacters(false); } } else break; } } }
namespace Crystal.Plot2D.Common { public abstract class UndoAction { public abstract void Do(); public abstract void Undo(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace Task1 { class Program { static void Main(string[] args) { Queue q = new Queue(); q.Enqueue("Nigel"); q.Enqueue("Makuini"); q.Enqueue("Jerome"); q.Enqueue("Makaio"); q.Enqueue("Zane"); // Temp queue Queue q1 = new Queue(q); while (q1.Count != 0) { Console.WriteLine(q1.Dequeue()); } } } }
using System; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; namespace GSVM.Peripherals.IODevices.WindowsInterop { public class KeyboardEventArgs : EventArgs { public Keys KeyCode { get; private set; } public KeyboardEventArgs(Keys keycode) { KeyCode = keycode; } } class KeyboardIntercept { private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private static LowLevelKeyboardProc _proc = HookCallback; private static IntPtr _hookID = IntPtr.Zero; public static event EventHandler<KeyboardEventArgs> KeyboardEvent; public static void Init() { _hookID = SetHook(_proc); } public static void Deinit() { UnhookWindowsHookEx(_hookID); } private static IntPtr SetHook(LowLevelKeyboardProc proc) { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN) { int vkCode = Marshal.ReadInt32(lParam); //Console.WriteLine((Keys)vkCode); KeyboardEvent?.Invoke(null, new KeyboardEventArgs((Keys)vkCode)); } return CallNextHookEx(_hookID, nCode, wParam, lParam); } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterMovement : MonoBehaviour { public float speed = 1.0f; private Vector3 movement; private Animator anim; private Rigidbody modelRigidbody; private void Start() { anim = GetComponent<Animator>(); modelRigidbody = GetComponent<Rigidbody>(); } private void Update() { float x = Input.GetAxis("Horizontal") * -1.0f; float z = Input.GetAxis("Vertical") * -1.0f; movement = new Vector3(x, 0.0f, z).normalized * speed * Time.deltaTime; } private void FixedUpdate() { Move(); } private void Move() { if (movement.magnitude < 0.01f) { anim.SetBool("isWalk", false); return; } modelRigidbody.velocity = movement; modelRigidbody.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), 0.15f); anim.SetBool("isWalk", true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BradfordLaserTagStats { public class Result { public Member Member; public GameData GameData; public Result(Member member, GameData gameData) { Member = member; GameData = gameData; } } }
namespace Triangulation.Core { public static class Constants { private const double _tolerance = 0.0001; public static double TOLERANCE => _tolerance; } }
using System.Threading; namespace WikipediaFramework { public class LanguageLandingPage { public class Language { public static bool IsEnglish() => PageUrlContains("en"); public static bool IsJapanese() => PageUrlContains("ja"); public static bool IsDanish() => PageUrlContains("de"); public static bool IsSpanish() => PageUrlContains("es"); public static bool IsRussian() => PageUrlContains("ru"); public static bool IsFrench() => PageUrlContains("fr"); public static bool IsItalian() => PageUrlContains("it"); public static bool IsChinese() => PageUrlContains("zh"); public static bool IsPortugese() => PageUrlContains("pt"); public static bool IsPolish() => PageUrlContains("pl"); private static bool PageUrlContains(string urlSubString, int timeout=5000) { int currentWaitTime = 0; while (!Browser.Instance.Url.Contains("/" + urlSubString + ".") && currentWaitTime < timeout) { currentWaitTime++; Thread.Sleep(1); } var urlPortions = Browser.Instance.Url.Split('.'); return urlPortions[0].EndsWith(urlSubString); } } } }
using System; using System.Threading; namespace MatrixAdding { public static class MatrixAddExtension { public static double[,] Add(this double[,] matrix1, double[,] matrix2) { if(matrix1.GetLength(0) != matrix2.GetLength(0) || matrix1.GetLength(1) != matrix2.GetLength(1)) { throw new ArgumentException("Matrixes must be the same size."); } double[,] res = new double[matrix1.GetLength(0), matrix1.GetLength(1)]; for(int i = 0;i< res.GetLength(0);i++) { for (int j = 0; j < res.GetLength(1); j++) { res[i, j] = matrix1[i, j] + matrix2[i, j]; } } return res; } public static double[,] Subtract(this double[,] matrix1, double[,] matrix2) { if (matrix1.GetLength(0) != matrix2.GetLength(0) || matrix1.GetLength(1) != matrix2.GetLength(1)) { throw new ArgumentException("Matrixes must be the same size."); } double[,] res = new double[matrix1.GetLength(0), matrix1.GetLength(1)]; for (int i = 0; i < res.GetLength(0); i++) { for (int j = 0; j < res.GetLength(1); j++) { res[i, j] = matrix1[i, j] - matrix2[i, j]; } } return res; } public static double[,] AddMultithreading(this double[,] matrix1, double[,] matrix2, int N) { if (matrix1.GetLength(0) != matrix2.GetLength(0) || matrix1.GetLength(1) != matrix2.GetLength(1)) { throw new ArgumentException("Matrixes must be the same size."); } double[,] res = new double[matrix1.GetLength(0), matrix1.GetLength(1)]; Thread[] threads = new Thread[N]; int step = (int)Math.Ceiling((double)matrix1.GetLength(0) / (double)N); for(int i = 0;i<N;i++) { threads[i] = new Thread((object ind) => { AddPartial(matrix1, matrix2, res, step * (int)ind, step * ((int)ind + 1) >= matrix1.GetLength(0) ? matrix1.GetLength(0) : step * ((int)ind + 1)); }); threads[i].Start(i); } for(int i = 0;i<N;i++) { threads[i].Join(); } return res; } public static double[,] SubtractMultithreading(this double[,] matrix1, double[,] matrix2, int N) { if (matrix1.GetLength(0) != matrix2.GetLength(0) || matrix1.GetLength(1) != matrix2.GetLength(1)) { throw new ArgumentException("Matrixes must be the same size."); } double[,] res = new double[matrix1.GetLength(0), matrix1.GetLength(1)]; Thread[] threads = new Thread[N]; int step = (int)Math.Ceiling((double)matrix1.GetLength(0) / (double)N); for (int i = 0; i < N; i++) { threads[i] = new Thread((object ind) => { SubPartial(matrix1, matrix2, res, step * (int)ind, step * ((int)ind + 1) >= matrix1.GetLength(0) ? matrix1.GetLength(0) : step * ((int)ind + 1)); }); threads[i].Start(i); } for (int i = 0; i < N; i++) { threads[i].Join(); } return res; } static void AddPartial(double[,] matrix1, double[,] matrix2, double[,] res, int startI, int endI) { for (int i = startI; i < endI; i ++) { for (int j = 0; j < matrix1.GetLength(1); j++) { res[i, j] = matrix2[i, j] + matrix1[i, j]; } } } static void SubPartial(double[,] matrix1, double[,] matrix2, double[,] res, int startI, int endI) { for (int i = startI; i < endI; i++) { for (int j = 0; j < matrix1.GetLength(1); j++) { res[i, j] = matrix1[i, j] - matrix2[i, j]; } } } public static double[,] GetRandomMatrix(int n,int m) { Random rand = new Random(); double[,] res = new double[n, m]; for(int i = 0; i<n;i++) { for(int j = 0;j<m;j++) { res[i, j] = rand.NextDouble(); } } return res; } } }
using UnityEngine; public class DefenceInvisableCube : MonoBehaviour { public GameObject invisableWall; public void OnDestroy() { Instantiate(invisableWall, transform.position, transform.rotation); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XH.Domain.Seo.Models { public class SEOMetaData { public virtual string Title { get; set; } public virtual string Description { get; set; } public virtual string Keywords { get; set; } } }
//A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, // // a2 + b2 = c2 // For example, 32 + 42 = 9 + 16 = 25 = 52. // // There exists exactly one Pythagorean triplet for which a + b + c = 1000. // Find the product abc. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace csharp { class Problem039 { public static void Main (string[] args) { var max = PythagoreanParameter ().GroupBy (e => e).OrderByDescending (g => g.Count ()).First (); Console.WriteLine ($"key: {max.Key}, count: {max.Count ()}"); } static IEnumerable<int> PythagoreanParameter() { var maxParameter = 1000; var largestA = maxParameter / 3; for (int p = 1; p <= maxParameter; p++) { for (int a = 1; a <= largestA; a++) { for (int b = a; b <= (p - a) / 2; b++) { if (a * b + b * b == (p - a - b) * (p - a - b)) { yield return p; } } } } } } }
 // ----------------------------------------------------------------------- // <copyright file="CameraPoseFinderParameters.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Kinect.Fusion { using System; using System.Runtime.InteropServices; /// <summary> /// This class is used to setup the volume parameters. /// </summary> [StructLayout(LayoutKind.Sequential)] public sealed class CameraPoseFinderParameters : IEquatable<CameraPoseFinderParameters> { /// <summary> /// The default number of feature sample locations per frame. /// </summary> private const int DefaultFeatureSampleLocationsPerFrame = 500; /// <summary> /// The default maximum pose history. /// </summary> private const int DefaultMaxPoseHistoryCount = 10000; /// <summary> /// The default maximum depth threshold. /// </summary> private const float DefaultMaxDepthThreshold = 4.0f; /// <summary> /// The private member variable to cache the default camera parameters. /// </summary> private static CameraPoseFinderParameters defaultRelocalizationParameters; /// <summary> /// A lock object protecting the default parameter creation. /// </summary> private static object lockObject = new object(); /// <summary> /// Initializes a new instance of the CameraPoseFinderParameters class. /// </summary> /// <param name="featureSampleLocationsPerFrameCount">Number of features to extract per frame. This must be greater /// than 0 and a maximum of 1000.</param> /// <param name="maxPoseHistoryCount">Maximum size of the camera pose finder pose history database. /// This must be greater than 0 and less than 10,000,000.</param> /// <param name="maxDepthThreshold">Maximum depth to be used when choosing a threshold value for each /// sample features. This should be greater than 0.4f and a maximum of the closest working distance /// you expect in your scenario (i.e. if all your reconstruction is at short range 0-2m, set 2.0f here). /// Note that with the there is a trade-off, as setting large distances may make the system less /// discriminative, hence more features may be required to maintain matching performance.</param> public CameraPoseFinderParameters(int featureSampleLocationsPerFrameCount, int maxPoseHistoryCount, float maxDepthThreshold) { FeatureSampleLocationsPerFrame = featureSampleLocationsPerFrameCount; MaxPoseHistory = maxPoseHistoryCount; MaxDepthThreshold = maxDepthThreshold; } /// <summary> /// Prevents a default instance of the CameraPoseFinderParameters class from being created. /// The declaration of the default constructor is used for marshaling operations. /// </summary> private CameraPoseFinderParameters() { } /// <summary> /// Gets the default parameters. /// </summary> public static CameraPoseFinderParameters Defaults { get { lock (lockObject) { if (null == defaultRelocalizationParameters) { defaultRelocalizationParameters = new CameraPoseFinderParameters(DefaultFeatureSampleLocationsPerFrame, DefaultMaxPoseHistoryCount, DefaultMaxDepthThreshold); } } return defaultRelocalizationParameters; } } /// <summary> /// Gets the number of locations to sample features per frame. /// </summary> public int FeatureSampleLocationsPerFrame { get; private set; } /// <summary> /// Gets the maximum size of the camera pose finder pose history database. /// </summary> public int MaxPoseHistory { get; private set; } /// <summary> /// Gets the maximum depth when choosing a threshold value for each sample feature in a key frame. /// </summary> public float MaxDepthThreshold { get; private set; } /// <summary> /// Calculates the hash code of the CameraPoseFinderParameters. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { // XNA-like hash generation return FeatureSampleLocationsPerFrame.GetHashCode() + MaxPoseHistory.GetHashCode() + MaxDepthThreshold.GetHashCode(); } /// <summary> /// Determines if the two objects are equal. /// </summary> /// <param name="other">The object to compare to.</param> /// <returns>This method returns true if they are equal and false otherwise.</returns> public bool Equals(CameraPoseFinderParameters other) { return null != other && FeatureSampleLocationsPerFrame == other.FeatureSampleLocationsPerFrame && MaxPoseHistory == other.MaxPoseHistory && MaxDepthThreshold == other.MaxDepthThreshold; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ARPG.Skill { /// <summary> /// 技能释放器 /// </summary> public class SkillDeployer : MonoBehaviour { private SkillData skillData; /// <summary> /// 由技能管理器提供 /// </summary> public SkillData SkillData { get { return skillData; } set { skillData = value; //创建算法对象 // InitDeplopyer(); } } //选区算法对象 public IAttackSelector selector; //影响效果对象 public IImpactEffect[] effectArray; //初始化释放器 private void InitDeplopyer() { //创建算法对象 //选区 selector = DeployerConfigFactor.CreatAttackSelector(SkillData); //影响 effectArray = DeployerConfigFactor.CreatImpactEffect(SkillData); } //执行算法对象 //释放方式 } }
namespace Sentry.Tests.Protocol; public class SentryIdTests { [Fact] public void ToString_Equal_GuidToStringN() { var expected = Guid.NewGuid(); SentryId actual = expected; Assert.Equal(expected.ToString("N"), actual.ToString()); } [Fact] public void Implicit_ToGuid() { var expected = SentryId.Create(); Guid actual = expected; Assert.Equal(expected.ToString(), actual.ToString("N")); } [Fact] public void Empty_Equal_GuidEmpty() { Assert.Equal(SentryId.Empty.ToString(), Guid.Empty.ToString("N")); } }
using Otiport.API.Contract.Models; using Otiport.API.Data.Entities.Users; namespace Otiport.API.Mappers { public interface IUserMapper { UserModel ToModel(UserEntity entity); UserEntity ToEntity(UserModel model); } }
using UnityEngine; public class Arrow : MonoBehaviour { public float speed; public int damage; public GameObject shooter; void Update() { if (transform.position.sqrMagnitude > 140f) Destroy(gameObject); transform.Translate(Vector3.right * speed * Time.deltaTime); } void OnTriggerEnter2D(Collider2D other) { Debug.Log(other.name); IDamageable damageable = other.GetComponent<IDamageable>(); if (damageable != null && other.gameObject != shooter) damageable.TakeDamage(damage); if (other.gameObject != shooter && other.name != "RoomManager") Destroy(gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(CharacterController))] public class PlayerInput : MonoBehaviour { public float runSpeed = 40f; private CharacterController controller; // Start is called before the first frame update void Start() { controller = GetComponent<CharacterController>(); } // Update is called once per frame void Update() { float value = Input.GetAxis("Horizontal"); bool jump = Input.GetAxis("Jump") > 0; bool crouch = Input.GetKey(KeyCode.LeftControl); controller.Move(value * Time.deltaTime * runSpeed, crouch, jump); } }
using System; using System.Collections.Generic; using System.Linq; namespace DistributedCollections { public class Backplane : IBackplane { private readonly List<BackplaneMessage> store = new List<BackplaneMessage>(1000000); private long count = 0; public void Publish(BackplaneMessage message) { var id = new MessageId(count++, 0); message.Id = id; store.Add(message); } public IEnumerable<BackplaneMessage> ReadMessages(MessageId lastId = default(MessageId)) { var result = store .SkipWhile(m => m.Id.Timestamp != lastId.Timestamp) .ToList(); return result.Count == 0 ? store : result; } public IDistLock CreateLock() { throw new NotImplementedException(); } public ISerializer Serializer => throw new NotImplementedException(); } }
using MahApps.Metro.Controls; using System.Windows; namespace MinecraftToolsBoxSDK { public class HamburgerMenuContentItem : HamburgerMenuItem { FrameworkElement _content; public FrameworkElement Content { get { return _content; } set { _content = value;_content.DataContext = Application.Current.MainWindow; } } } }
using UnityEngine; public class Enemy : MonoBehaviour, ITarget { [SerializeField] Transform _targetTransform; public Transform TargetTransform { get { return _targetTransform; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Domain.Entity; namespace EBS.Query.DTO { public class StocktakingPlanItemDto:StocktakingPlanItem { /// <summary> /// 商品编码 /// </summary> public string ProductCode { get; set; } /// <summary> /// 商品名称 /// </summary> public string ProductName { get; set; } /// <summary> /// 条码 /// </summary> public string BarCode { get; set; } /// <summary> /// 规格 /// </summary> public string Specification { get; set; } public int DifferentQuantity { get{ return base.GetDifferenceQuantity(); }} public decimal CostAmount { get { return base.CostPrice* Quantity; } } public decimal CostCountAmount { get { return base.CostPrice * CountQuantity; } } public decimal CostAmountDifferent { get { return CostCountAmount - CostAmount ; } } public decimal SaleAmout { get { return base.SalePrice * Quantity; } } public decimal SaleCountAmount { get { return base.SalePrice * CountQuantity; } } public decimal SaleAmoutDifferent { get { return SaleCountAmount - SaleAmout ; } } } }
using UnityEngine; [RequireComponent(typeof(Player))] public class PlayerInput : MonoBehaviour { private Vector2 _targetDirection; private Player _player; private bool _wantsToJump; private bool _acceptingInput = true; public Vector2 TargetDirection => _targetDirection; public bool WantsToJump => _wantsToJump; public bool IsAcceptingInput => _acceptingInput; public void ResetJump() { _wantsToJump = false; } public void SetAcceptingInput(bool acceptInput) { _acceptingInput = acceptInput; } private void Awake() { _targetDirection = Vector2.zero; _player = GetComponent<Player>(); } private void Update() { if (!_acceptingInput) return; CheckForPause(); CheckForFireGrapple(); CheckForJump(); UpdateTargetDirection(); } private void CheckForPause() { if (Input.GetKeyDown(KeyCode.Escape)) UIElementController.Instance.TogglePauseMenu(); } private void CheckForFireGrapple() { if (Input.GetKeyDown(KeyCode.Mouse0)) _player.grappling.FireGrapple(); } private void CheckForJump() { if (Input.GetButtonDown("Jump")) _wantsToJump = true; } private void UpdateTargetDirection() { _targetDirection.x = Input.GetAxisRaw("Horizontal"); _targetDirection.y = Input.GetAxisRaw("Vertical"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bitwise_Ops_Week_3 { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to an exercise in C# Bitwise Operators."); Console.WriteLine(); // This program will take two integer inputs and use bitwise operators for output. Console.Write("Enter a number for x: "); string xInt = Console.ReadLine(); int x = Convert.ToInt32(xInt); Console.Write("Enter a number for y: "); string yInt = Console.ReadLine(); int y = Convert.ToInt32(yInt); int AND = x & y; // Compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0. int inclOR = x | y; // Compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0. int exclOR = x ^ y; // Compares two bits and returns 1 if either of the bits are 1, otherwise, it returns 0. Console.WriteLine(); Console.WriteLine($"The AND value of {xInt} and {yInt} is: {AND}"); Console.WriteLine($"The inclusive OR value of {xInt} and {yInt} is: {inclOR}"); Console.WriteLine($"The exclusive OR value of {xInt} and {yInt} is: {exclOR}"); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); } } }
using Loja.Dominio; using Loja.Web.Models; using Loja.Web.Servicos; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Loja.Web.Controllers { public class ProdutoController : Controller { // GET: Produto public ActionResult Produto(string nome) { ProdutoServico produtoServico = ServicoDeDependencias.MontarProdutoServico(); List<Produto> produtos = produtoServico.ListarProdutos(nome); List<ProdutoModel> model = new List<ProdutoModel>(); foreach (Produto produto in produtos) { model.Add(new ProdutoModel(produto)); } return View("Produto", model); } public ActionResult FichaTecnica(int id) { ProdutoServico produtoServico = ServicoDeDependencias.MontarProdutoServico(); Produto produto = produtoServico.BuscarPorId(id); ProdutoModel modelo = new ProdutoModel(produto); return View("FichaTecnica", modelo); } public ActionResult Cadastro() { return View(); } public ActionResult Salvar(ProdutoModel modelo) { ProdutoServico produtoServico = ServicoDeDependencias.MontarProdutoServico(); Produto produto = new Produto(modelo.Id, modelo.Nome, modelo.Valor); if (ModelState.IsValid || (modelo.Id.Equals(0) && modelo.Nome!=null && modelo.Valor!=0)) { produtoServico.SalvarProduto(produto); return View("FichaTecnica", modelo); } ViewBag.Situacao = "Vefirique os dados."; return View("Cadastro"); } public ActionResult Editar(int id) { ProdutoServico produtoServico = ServicoDeDependencias.MontarProdutoServico(); Produto produto = produtoServico.BuscarPorId(id); ProdutoModel modelo = new ProdutoModel(produto); return View("Cadastro", modelo); } } }
namespace Backpressure { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; internal class Subscription : ISubscription { private readonly IDisposable _internalDisposable; private readonly IBackpressureOperator _operator; private bool _disposed; public Subscription( IDisposable internalDisposable, IBackpressureOperator @operator) { this._internalDisposable = internalDisposable; this._operator = @operator; } void IDisposable.Dispose() { if (this._disposed) { return; } this._disposed = true; this._internalDisposable.Dispose(); } public void Unsubscribe() { ((IDisposable)this).Dispose(); } public void Request(int count) { if (this._disposed) { throw new ObjectDisposedException(nameof(Subscription)); } this._operator.Request(count); } } }
using EntityLayer.CustomerDetails; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace EntityLayer.BankProfitAndLoss { public class BankCredit: BankUtility { [Column(TypeName = "decimal(18, 6)")] public decimal CreditAmount { get; set; } ///Navigation property public IEnumerable<CustomerProfile> CustomerProfiles { get; set; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiChain.Framework; using System; using System.Collections.Generic; using System.Text; namespace FiiiChain.Messages { public class NewTxMsg : BasePayload { public string Hash { get; set; } public override void Deserialize(byte[] bytes, ref int index) { var hashBytes = new byte[32]; Array.Copy(bytes, index, hashBytes, 0, hashBytes.Length); index += hashBytes.Length; this.Hash = Base16.Encode(hashBytes); } public override byte[] Serialize() { return Base16.Decode(Hash); } } }
using System.Collections; using UIFrame; //************************************************************************* //@header HOGUIStartTrain //@abstract Initial frame of StartTrain. //@discussion Depend on BaseUIForm. //@author Felix Zhang //@copyright Copyright (c) 2017-2018 FFTAI Co.,Ltd.All rights reserved. //@version v1.0.0 //************************************************************************** namespace FZ.HiddenObjectGame { public class HOGUIStartTrain : BaseUIForm { private void Awake() { // 初始化窗体属性 base.CurrentUIType.UIForms_Type = UIFormType.PopUp; base.CurrentUIType.UIForms_ShowMode = UIFormShow.Normal; base.CurrentUIType.UIForm_LucencyType = UIFormLucenyType.ImPenetrable; //base.Initialize(); // 注册按钮事件 } private void Start() { SendMessage(HiddenObjectMessage.MsgStopGame, "", "False"); StartCoroutine(CountDownNum()); } IEnumerator CountDownNum() { FlowMediator.Instance.Next(); yield return StartCoroutine(MiscUtility.WaitOrPause(1f)); CloseUIForm(HiddenObjectPage.StartTrainPage, true); } } }
using System; using System.Collections.Generic; using System.Linq; using AppKit; using Foundation; namespace TreeView { public class ItemDataSource : NSOutlineViewDataSource { public List<ItemViewModel> Data = new List<ItemViewModel>(); public ItemDataSource() { } public override nint GetChildrenCount(NSOutlineView outlineView, NSObject item) { if (item == null) { return Data?.Count ?? 0; } else { return ((ItemViewModel)item).Children.Count; } } public override NSObject GetChild(NSOutlineView outlineView, nint childIndex, NSObject item) { if (item == null) { return Data[(int)childIndex]; } else { return ((ItemViewModel)item).Children[(int)childIndex]; } } public override bool ItemExpandable(NSOutlineView outlineView, NSObject item) { if (item == null) { return Data[0].Children.Any(); } else { return ((ItemViewModel)item).Children.Any(); } } } public class ItemDelegate : NSOutlineViewDelegate { public ItemDelegate(NSOutlineView outlineView) { outlineView.RegisterNib(new NSNib(nameof(ItemView), NSBundle.MainBundle), nameof(ItemView)); } public override NSView GetView(NSOutlineView outlineView, NSTableColumn tableColumn, NSObject item) { var view = (ItemView)outlineView.MakeView(nameof(ItemView), this); view.ViewModel = (ItemViewModel)item; view.UpdateUI(); return view; } } }
using MahApps.Metro.Controls; using MinecraftToolsBoxSDK; using System.IO; using System.Text; using System.Windows; using System.Windows.Controls; namespace MinecraftToolsBox.Commands { /// <summary> /// PlayerCommands.xaml 的交互逻辑 /// </summary> public partial class PlayerCommands : DockPanel, ICommandGenerator { bool stop = false; CommandsGeneratorTemplate CmdGenerator; public PlayerCommands(CommandsGeneratorTemplate cmdGenerator) { InitializeComponent(); LocX_sp.setNeighbour(null, LocY_sp); LocY_sp.setNeighbour(LocX_sp, LocZ_sp); LocZ_sp.setNeighbour(LocY_sp, null); LocX.setNeighbour(null, LocY); LocY.setNeighbour(LocX, LocZ); LocZ.setNeighbour(LocY, null); CmdGenerator = cmdGenerator; } string Achievement() { string cmd = "/achievement "; if (give.IsChecked == true) cmd += "give "; else cmd += "take "; if (achi.IsChecked == true) { cmd += "achievement."; if (ach.SelectedIndex == 0) cmd = cmd.Substring(0, cmd.Length - 12) + "*"; else cmd += ((ComboBoxItem)ach.SelectedItem).Name + " " + PlayerSelector.GetPlayer(); } else cmd += "stat." + ((ComboBoxItem)Stat.SelectedItem).Name + " " + PlayerSelector.GetPlayer(); return cmd; } public string GenerateCommand() { switch (menu.SelectedIndex) { case 0: if (c1.IsChecked == true) { return "/xp " + exp.Value + " " + PlayerSelector.GetPlayer(); } else if (c2.IsChecked == true) { if (addL.IsChecked == true) return "/xp " + levels.Value + "L " + PlayerSelector.GetPlayer(); else return "/xp " + "-" + levels.Value + "L " + PlayerSelector.GetPlayer(); } else if (c3.IsChecked == true) return "/gamemode " + game_mode.SelectedIndex; else { string loc2 = " "; if (tilde_Copy.IsChecked == true) { loc2 = "~" + LocX_sp.Text + " ~" + LocY_sp.Text + " ~" + LocZ_sp.Text; } else { loc2 = LocX_sp.Text + " " + LocY_sp.Text + " " + LocZ_sp.Text; } return "/spawnpoint " + PlayerSelector.GetPlayer() + loc2; } case 1: if (isPrivate.IsChecked == true) return "/tell " + PlayerSelector.GetPlayer() + " " + msg.Text; else return "/say " + msg.Text; case 2: return Achievement(); case 3: string loc = ""; if (tilde.IsChecked == true) { loc = "~" + LocX.Text + " ~" + LocY.Text + " ~" + LocZ.Text; } else { loc = LocX.Text + " " + LocY.Text + " " + LocZ.Text; } return "/playsound " + sound.Text + " " + PlayerSelector.GetPlayer() + " " + loc + " " + volume.Value + " " + tune.Value + " " + min_volume.Value; case 4: TreeViewItem e = (TreeViewItem)enchant.SelectedItem; if (e == en1 || e == en2 || e == en3 || e == en4 || e == en5 || e == en6 || e == null) return ""; return "/enchant " + PlayerSelector.GetPlayer() + " " + e.Name + " " + en_level.Value; } return ""; } private void Playsound_search(object sender, RoutedEventArgs e) { result.Items.Clear(); result.SelectedIndex = -1; string keyword = sound.Text; FileStream data = new FileStream("data/sound_data.txt", FileMode.Open); StreamReader streamReader = new StreamReader(data, Encoding.Default); streamReader.BaseStream.Seek(0, SeekOrigin.Begin); string strLine = streamReader.ReadLine(); do { string[] split = strLine.Split('='); if (split[1].Contains(keyword)) result.Items.Add(split[0]+"("+split[1]+")"); strLine = streamReader.ReadLine(); } while (strLine != null && strLine != ""); streamReader.Close(); streamReader.Dispose(); data.Close(); data.Dispose(); } private void Level_min_Click(object sender, RoutedEventArgs e) { CmdGenerator.AddCommand("/xp -2147483648L " + PlayerSelector.GetPlayer()); } private void Sp1(object sender, RoutedEventArgs e) { CmdGenerator.AddCommand("/spawnpoint"); } private void Sp2(object sender, RoutedEventArgs e) { CmdGenerator.AddCommand("/spawnpoint "+PlayerSelector.GetPlayer()); } private void AddTarget_Click(object sender, RoutedEventArgs e) { msg.Text += " " + PlayerSelector.GetPlayer() + " "; } private void Select_sound(object sender, SelectionChangedEventArgs e) { string res = (string)result.SelectedItem; if (res == null) return; res = res.Split('(',')')[1]; sound.Text = res; } private void ACHIEVEMENT(object sender, RoutedEventArgs e) { string name = ((Button)sender).Name; name = name.Replace("_", ""); ach.SelectedIndex = int.Parse(name); } private void HamburgerMenu_ItemClick(object sender, ItemClickEventArgs e) { menu.Content = e.ClickedItem; } private void Checked(object sender, RoutedEventArgs e) { if (c1 == null || c2 == null || c3 == null || c4 == null || stop) return; stop = true; c1.IsChecked = false; c2.IsChecked = false; c3.IsChecked = false; c4.IsChecked = false; (sender as RadioButton).IsChecked = true; stop = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Domain.ValueObject; using EBS.Infrastructure.Extension; namespace EBS.Query.DTO { public class StocktakingPlanDto { public int Id { get; set; } public string StoreName { get; set; } public string Code { get; set; } public DateTime StocktakingDate { get; set; } public string StocktakingDateString { get { return StocktakingDate.ToString("yyyy-MM-dd"); } } public StocktakingPlanStatus Status { get; set; } public string StocktakingPlanStatus { get { return Status.Description(); } } public StocktakingPlanMethod Method { get; set; } public string StocktakingPlanMethod { get { return Method.Description(); } } public string CreatedByName { get; set; } } public class SearchStocktakingPlan { public string Code { get; set; } public int Status { get; set; } public DateTime? StocktakingDate { get; set; } public int StoreId { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } } public class SearchStocktakingPlanSummary { public string Code { get; set; } /// <summary> /// 逗号分隔状态值 /// </summary> public string Status { get; set; } public DateTime? StocktakingDate { get; set; } public string StoreId { get; set; } /// <summary> /// 盘点方式:大盘,小盘 /// </summary> public int Method { get; set; } /// <summary> /// 盘点开始日期 /// </summary> public DateTime? StartDate { get; set; } /// <summary> /// 盘点结束日期 /// </summary> public DateTime? EndDate { get; set; } /// <summary> /// 完成 /// </summary> public DateTime? UpdateStartDate { get; set; } public DateTime? UpdateEndDate { get; set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// The statistics class is designed to essentially keep the score of the RTS game /// data points will need to be added to this in the future. /// </summary> public class Statistics { public int unitsDestroyed { get; private set; } public int unitsLost { get; private set; } public int resourcesCollected { get; private set; } public int structuresDestroyed { get; private set; } Statistics() { unitsDestroyed = 0; unitsLost = 0; resourcesCollected = 0; structuresDestroyed = 0; } public void AddUnitDestroyed() { unitsDestroyed++; } public void AddUnitLost() { unitsLost++; } public void AddResources(int in_resources) { resourcesCollected += in_resources; } public void AddStructureDestroyed() { structuresDestroyed++; } } public static class Helper { public enum PlayerType {None, Human, EasyAI, MediumAI, HardAI, CrazyAI} public enum AIProcess {None, Offense, Defense, ResourceManager, PowerManager} public enum Faction {None, EarthAlliance, Virus, AllianceOfTechnology} public enum Team {None, Team1, Team2, Team3, Team4, Team5, Team6, Team7, Team8} public enum Category {None, Vehical, LightUnit, Structure, Construction, Contractor, Shot, Weapon, Mine, Harvester} public enum UnitType {None, AutomatedDrone, TacticalDrone, RapidRocketLauncher, LightTank, MediumTank, Contractor, Harvester, HeavyTank, MobileFortress } public enum BuildingType {None, ControlCenter, MaterialCenter, LightTurret, MediumTurret, HeavyTurret, Reactor, AdvancedReactor, AutomatedDefenseFactory, WeaponsFactory, TechnologyCenter } public static string[] teamTags = new string[]{"Team1", "Team2", "Team3", "Team4", "Team5", "Team6", "Team7", "Team8"}; /// <summary> /// Gets the color of the team. /// </summary> /// <returns>The team color.</returns> /// <param name="unit">Unit.</param> public static Color GetTeamColor(GameObject unit) { if (unit.tag.Equals ("Team1")) { return Color.green; } else if (unit.tag.Equals ("Team2")) { return Color.blue; } else if (unit.tag.Equals ("Team3")) { return Color.red; } else if (unit.tag.Equals ("Team4")) { return Color.cyan; } else if (unit.tag.Equals ("Team5")) { return Color.magenta; } else if (unit.tag.Equals ("Team6")) { return Color.yellow; } else if (unit.tag.Equals ("Team7")) { return Color.grey; } else { return Color.white; } } /// <summary> /// Finds the building of the input type and team nearest to the searching unit /// </summary> /// <returns>The nearest building from team.</returns> /// <param name="searchingUnit">Searching unit.</param> /// <param name="team">Team.</param> /// <param name="buildingType">Building type.</param> public static GameObject FindNearestBuildingFromTeam(GameObject searchingUnit, string team, Helper.BuildingType buildingType) { GameObject target = null; float closest = 99999.0F; GameObject[] teamMates = GameObject.FindGameObjectsWithTag (team); foreach (GameObject teamMate in teamMates) { float distance = Vector3.Distance (searchingUnit.transform.position, teamMate.transform.position); if (teamMate.GetComponent<Information>() != null && teamMate.GetComponent<Information>().buildingType == buildingType && distance < closest) { closest = distance; target = teamMate; } } return target; } /// <summary> /// Finds the nearest target unit to the searching unit who is on the input team /// </summary> /// <returns>The nearest target.</returns> /// <param name="searchingUnit">Searching unit.</param> /// <param name="targetTeam">Target team.</param> public static GameObject FindNearestTargetFromTeam(GameObject searchingUnit, string targetTeam) { GameObject target = null; float closestDistance = 999999.0f; foreach (GameObject enemy in GameObject.FindGameObjectsWithTag(targetTeam)) { if (enemy.GetComponent<Information> () != null && (enemy.GetComponent<Information> ().unitType != UnitType.None || enemy.GetComponent<Information> ().buildingType != BuildingType.None)) { float newDistance = Vector3.Distance (searchingUnit.transform.position, enemy.transform.position); if (newDistance < closestDistance) { closestDistance = newDistance; target = enemy; } } } return target; } public static Vector3 GetTargetIntercept(GameObject unit, GameObject target, float shotSpeed) { if (target == null) { return new Vector3 (0.0f, 0.0f, 0.0f); } Vector3 targetPoint = target.transform.position; Vector3 myVelocity = new Vector3 (0.0f, 0.0f, 0.0f); Vector3 targetVelocity = new Vector3 (0.0f, 0.0f, 0.0f); //Start by getting my velocity if (unit.GetComponent<UnityEngine.AI.NavMeshAgent> () != null) { myVelocity = unit.GetComponent<UnityEngine.AI.NavMeshAgent> ().velocity; } else if (unit.GetComponent<Information> () != null && unit.GetComponent<Information> ().parent != null && unit.GetComponent<Information> ().parent.GetComponent < UnityEngine.AI.NavMeshAgent> () != null) { myVelocity = unit.GetComponent<Information> ().parent.GetComponent < UnityEngine.AI.NavMeshAgent> ().velocity; } else { Debug.Log ("Unable to get unit velocity"); } if (target.GetComponent<UnityEngine.AI.NavMeshAgent> () != null) { targetVelocity = target.GetComponent<UnityEngine.AI.NavMeshAgent> ().velocity; } else if (target.GetComponent<Information> () != null && target.GetComponent<Information> ().parent != null && target.GetComponent<Information> ().parent.GetComponent < UnityEngine.AI.NavMeshAgent> () != null) { targetVelocity = target.GetComponent<Information> ().parent.GetComponent < UnityEngine.AI.NavMeshAgent> ().velocity; } else { Debug.Log ("Unable to get target velocity"); } targetPoint = Helper.FirstOrderIntercept (unit.transform.position, myVelocity, shotSpeed, target.transform.position, targetVelocity); //Now get the enemy's velocity return targetPoint; } /// <summary> /// Firsts the order intercept. Function used to help aim at targets, /// the code was pulled from the unity wiki /// http://wiki.unity3d.com/index.php/Calculating_Lead_For_Projectiles /// </summary> /// <returns>The order intercept.</returns> /// <param name="shooterPosition">Shooter position.</param> /// <param name="shooterVelocity">Shooter velocity.</param> /// <param name="shotSpeed">Shot speed.</param> /// <param name="targetPosition">Target position.</param> /// <param name="targetVelocity">Target velocity.</param> public static Vector3 FirstOrderIntercept ( Vector3 shooterPosition, Vector3 shooterVelocity, float shotSpeed, Vector3 targetPosition, Vector3 targetVelocity ) { Vector3 targetRelativePosition = targetPosition - shooterPosition; Vector3 targetRelativeVelocity = targetVelocity - shooterVelocity; float t = FirstOrderInterceptTime ( shotSpeed, targetRelativePosition, targetRelativeVelocity ); return targetPosition + t*(targetRelativeVelocity); } //first-order intercept using relative target position public static float FirstOrderInterceptTime ( float shotSpeed, Vector3 targetRelativePosition, Vector3 targetRelativeVelocity ) { float velocitySquared = targetRelativeVelocity.sqrMagnitude; if(velocitySquared < 0.001f) return 0f; float a = velocitySquared - shotSpeed*shotSpeed; //handle similar velocities if (Mathf.Abs(a) < 0.001f) { float t = -targetRelativePosition.sqrMagnitude/ ( 2f*Vector3.Dot ( targetRelativeVelocity, targetRelativePosition ) ); return Mathf.Max(t, 0f); //don't shoot back in time } float b = 2f*Vector3.Dot(targetRelativeVelocity, targetRelativePosition); float c = targetRelativePosition.sqrMagnitude; float determinant = b*b - 4f*a*c; if (determinant > 0f) { //determinant > 0; two intercept paths (most common) float t1 = (-b + Mathf.Sqrt(determinant))/(2f*a), t2 = (-b - Mathf.Sqrt(determinant))/(2f*a); if (t1 > 0f) { if (t2 > 0f) return Mathf.Min(t1, t2); //both are positive else return t1; //only t1 is positive } else return Mathf.Max(t2, 0f); //don't shoot back in time } else if (determinant < 0f) //determinant < 0; no intercept path return 0f; else //determinant = 0; one intercept path, pretty much never happens return Mathf.Max(-b/(2f*a), 0f); //don't shoot back in time } /// <summary> /// Finds an enemy target that meets the input specifications /// </summary> /// <returns>The target.</returns> /// <param name="searchingUnit">Searching unit.</param> /// <param name="searchAll">If set to <c>true</c> search all.</param> /// <param name="max_range">Max range.</param> public static GameObject FindNearestTarget(GameObject searchingUnit, bool seekAndDestroy, float max_range, float min_range) { GameObject target = null; float closest_distance = 999999F; foreach (string teamTag in teamTags) { if (!searchingUnit.CompareTag (teamTag)) { //Search all teams except this unit's team foreach (GameObject enemy in GameObject.FindGameObjectsWithTag (teamTag)) { if (enemy.GetComponent<Information> () != null && (enemy.GetComponent<Information> ().unitType != UnitType.None || enemy.GetComponent<Information> ().buildingType != BuildingType.None)) { //Non-aggressive mode, only set targets that are within firing range float distance = Vector3.Distance(enemy.transform.position, searchingUnit.transform.position); if (distance < closest_distance && distance < max_range && distance > min_range) { closest_distance = distance; target = enemy; //Seek-and-destroy mode, searches the map for the next closest enemy unit and destroys it } else if (seekAndDestroy && distance < closest_distance) { closest_distance = distance; target = enemy; } } else if (enemy.GetComponent<Information> () == null) { Debug.LogWarning ("Unit found on a team with no Information script: " + enemy.name); } } } } return target; } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // This source code is licensed under Microsoft Shared Source License // Version 1.0 for Windows CE. // For a copy of the license visit http://go.microsoft.com/?linkid=2933443. // #region Using directives using System; #endregion namespace Microsoft.WindowsMobile.SharedSource.Bluetooth { /// <summary> /// Lists GUIDs for standard Bluetooth services /// </summary> public class StandardServices { /// <summary> /// constructor so default constructor is not created since all methods are static /// </summary> private StandardServices() { ; } /// <summary> /// Guid representing the Serial Port Profile /// </summary> static public Guid SerialPortServiceGuid { get { if (serialPortServiceGuid == Guid.Empty) { serialPortServiceGuid = new Guid(0x00001101, 0x0000, 0x1000, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB); } return serialPortServiceGuid; } } private static Guid serialPortServiceGuid = Guid.Empty; } }
using Citycykler.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Citycykler.AdminPanel { public partial class Noticeable_slet : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataLinqDB db = new DataLinqDB(); int idget = HelperClassAll.HelperClass.ReturnGetId(); var modeler = db.modelers.Where(x => x.fk_noticeable == idget).ToList(); var noticeable = db.Noticeables.FirstOrDefault(i => i.id == idget); if (modeler != null && noticeable != null) { db.modelers.DeleteAllOnSubmit(modeler); db.SubmitChanges(); string UploadMappe = Server.MapPath("../img/");//Hvor skal den gemme billedet henne string ThumpsMappe = Server.MapPath("../img/Thumbs/");//Hvor skal den lave et Thumbs af billedet string Croppedmappe = Server.MapPath("../img/Cropped/");//Det cropped bare billedet så det giver en mindre skørrelse. if (noticeable.img != null) { FileInfo file = new FileInfo(UploadMappe + noticeable.img); FileInfo file2 = new FileInfo(ThumpsMappe + noticeable.img); FileInfo file3 = new FileInfo(Croppedmappe + noticeable.img); file.Delete(); file2.Delete(); file3.Delete(); } db.Noticeables.DeleteOnSubmit(noticeable); db.SubmitChanges(); Response.Redirect("~/AdminPanel/Noticeable.aspx?slet=true"); } } } }
using MMSEApp.ViewModels; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MMSEApp.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CorrectExam : ContentPage { private ExamViewModel examViewModel; public CorrectExam(ExamViewModel examView) { examViewModel = examView; InitializeComponent(); Score.BindingContext = examView; startCorrect(); } private void ClearGrid() { QuestionsGrid.Children.Clear(); // emptys grid } private void AddQuestionEntry(int QColumn, int QRow, int AColumn, int ARow, string question, string binding) { var stack = new StackLayout { Spacing = 10, Orientation = StackOrientation.Vertical }; var Question = new Label { Text = question, FontAttributes = FontAttributes.Bold}; // makes a new label with the question set as its text var Answer = new Label { Text = "Patient Answer: " + binding }; // adds a new entry for answer stack.Children.Add(Question); stack.Children.Add(Answer); var checkbox = new CheckBox(); checkbox.CheckedChanged += new EventHandler<Xamarin.Forms.CheckedChangedEventArgs>(CheckBox_CheckedChanged); QuestionsGrid.Children.Add(stack, QColumn, QRow); // add question to row QuestionsGrid.Children.Add(checkbox, AColumn, ARow); // add answer to row } private void CheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e) { if (e.Value) { examViewModel.ExamScore += 1; } else { examViewModel.ExamScore -= 1; } } private void startCorrect() { ClearGrid(); SectionTitle.Text = "Orientation"; // add first set of questions AddQuestionEntry(0, 0, 1, 0, "What year is it?", examViewModel.OrientationAns1); AddQuestionEntry(0, 1, 1, 1, "What month is it?", examViewModel.OrientationAns2); AddQuestionEntry(0, 2, 1, 2, "What day is it?", examViewModel.OrientationAns3); AddQuestionEntry(0, 3, 1, 3, "What time is it?", examViewModel.OrientationAns4); AddQuestionEntry(0, 4, 1, 4, "What date is it?", examViewModel.OrientationAns5); var backButton = new Button { Text = "Back" }; backButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; backButton.Clicked += new EventHandler(cancelExam); QuestionsGrid.Children.Add(backButton, 0, 5); // add the next var nextButton = new Button { Text = "Next" }; nextButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; nextButton.Clicked += new EventHandler(OrientationQuestionPartTwo); QuestionsGrid.Children.Add(nextButton, 1, 5); } private void OrientationQuestions(object sender, EventArgs e) // first part { startCorrect(); } async void cancelExam(object sender, EventArgs e) { await Navigation.PopAsync(); } private void OrientationQuestionPartTwo(object sender, EventArgs e) // Second part { ClearGrid(); SectionTitle.Text = "Orientation"; // add first set of questions AddQuestionEntry(0, 0, 1, 0, "What Country are we in?", examViewModel.OrientationAns6); AddQuestionEntry(0, 1, 1, 1, "What Town are we in?", examViewModel.OrientationAns7); AddQuestionEntry(0, 2, 1, 2, "What Province are we in?", examViewModel.OrientationAns8); AddQuestionEntry(0, 3, 1, 3, "What Hospital are we in?", examViewModel.OrientationAns9); AddQuestionEntry(0, 4, 1, 4, "What ward are we in?", examViewModel.OrientationAns10); var backButton = new Button { Text = "Back" }; backButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; backButton.Clicked += new EventHandler(OrientationQuestions); QuestionsGrid.Children.Add(backButton, 0, 5); // add the next var nextButton = new Button { Text = "Next" }; nextButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; nextButton.Clicked += new EventHandler(RegistrationQuesitons); QuestionsGrid.Children.Add(nextButton, 1, 5); } private void RegistrationQuesitons(object sender, EventArgs e) // third part { ClearGrid(); SectionTitle.Text = "Registration"; // add second set of questions AddQuestionEntry(0, 0, 1, 0, "This is a chair", examViewModel.RegistrationAns1); AddQuestionEntry(0, 1, 1, 1, "This is a car", examViewModel.RegistrationAns2); AddQuestionEntry(0, 2, 1, 2, "This is a house", examViewModel.RegistrationAns3); // back button var backButton = new Button { Text = "Back" }; backButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; backButton.Clicked += new EventHandler(OrientationQuestionPartTwo); QuestionsGrid.Children.Add(backButton, 0, 5); // next button var nextButton = new Button { Text = "Next" }; nextButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; nextButton.Clicked += new EventHandler(AttentionCalulationQuestions); QuestionsGrid.Children.Add(nextButton, 1, 5); } private void AttentionCalulationQuestions(object sender, EventArgs e) // fourth part { ClearGrid(); SectionTitle.Text = "Attention and Calculation"; AddQuestionEntry(0, 0, 1, 0, "Subtract 7 from 100, Repeat 5 times", examViewModel.AttenCalcAns1); var backButton = new Button { Text = "Back" }; backButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; backButton.Clicked += new EventHandler(RegistrationQuesitons); QuestionsGrid.Children.Add(backButton, 0, 5); // next button var nextButton = new Button { Text = "Next" }; nextButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; nextButton.Clicked += new EventHandler(RecallQuestions); QuestionsGrid.Children.Add(nextButton, 1, 5); } private void RecallQuestions(object sender, EventArgs e) // fifth part { ClearGrid(); SectionTitle.Text = "Recall"; AddQuestionEntry(0, 0, 1, 0, "Can you name the 3 objects u learned in section 2? ", examViewModel.RecallAns1); AddQuestionEntry(0, 1, 1, 1, "", examViewModel.RecallAns2); AddQuestionEntry(0, 2, 1, 2, "", examViewModel.RecallAns3); var backButton = new Button { Text = "Back" }; backButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; backButton.Clicked += new EventHandler(AttentionCalulationQuestions); QuestionsGrid.Children.Add(backButton, 0, 5); // next button var nextButton = new Button { Text = "Next" }; nextButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; nextButton.Clicked += new EventHandler(LanguageQuestions); QuestionsGrid.Children.Add(nextButton, 1, 5); } private void LanguageQuestions(object sender, EventArgs e) // sixth part { ClearGrid(); SectionTitle.Text = "Language"; AddQuestionEntry(0, 0, 1, 0, "Name a pencil and watch", examViewModel.LanguageAns1); AddQuestionEntry(0, 1, 1, 1, "Repeat \"No ifs,ands,or buts\" ", examViewModel.LanguageAns2); AddQuestionEntry(0, 2, 1, 2, "3 stage command ", examViewModel.LanguageAns3); AddQuestionEntry(0, 3, 1, 3, "Read a piece of paper ", examViewModel.LanguageAns4); AddQuestionEntry(0, 4, 1, 4, "write a sentence ", examViewModel.LanguageAns5); var backButton = new Button { Text = "Back" }; backButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; backButton.Clicked += new EventHandler(RecallQuestions); QuestionsGrid.Children.Add(backButton, 0, 5); // next button var nextButton = new Button { Text = "Next" }; nextButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; nextButton.Clicked += new EventHandler(DrawingResult); QuestionsGrid.Children.Add(nextButton, 1, 5); } private void DrawingResult(object sender, EventArgs e) { ClearGrid(); SectionTitle.Text = "Drawing"; AddQuestionEntry(0, 0, 1, 0, "Was the Drawing Correct?", examViewModel.DrawingAns1); var backButton = new Button { Text = "Back" }; backButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; backButton.Clicked += new EventHandler(LanguageQuestions); QuestionsGrid.Children.Add(backButton, 0, 5); // next button var nextButton = new Button { Text = "Save Results" }; nextButton.Style = Application.Current.Resources["blueButtonStyle"] as Style; nextButton.Clicked += new EventHandler(SaveResults); QuestionsGrid.Children.Add(nextButton, 1, 5); } private void SaveResults(object sender, EventArgs e) { examViewModel.SaveExamResult(); Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 3]); Navigation.RemovePage(Navigation.NavigationStack[Navigation.NavigationStack.Count - 2]); Navigation.PopAsync(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class FirstTimeAnim : MonoBehaviour { public bool canvas; public static bool DoTheThing; static bool dis=false; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if(dis){ this.enabled=false; } if(DoTheThing){ if(canvas){ Sequence sq= DOTween.Sequence(); sq.Append(this.transform.GetChild(1).DOScale(1.2f,0.6f)); sq.Append(this.transform.GetChild(1).DOScale(0.0f,0.4f)); this.transform.GetChild(0).GetComponent<RectTransform>().DOAnchorPos3D(new Vector3(-170.0f,-100.0f,0.0f),2.0f); Sequence sq2= DOTween.Sequence(); sq2.Append(this.transform.GetChild(2).DOScale(1.1f,1.5f)); sq2.Append(this.transform.GetChild(2).DOScale(1.0f,0.5f)); sq2.SetDelay(1.2f); Sequence sq3= DOTween.Sequence(); sq3.Append(this.transform.GetChild(3).DOScale(1.1f,1.5f)); sq3.Append(this.transform.GetChild(3).DOScale(1.0f,0.5f)); sq3.SetDelay(2.2f); Sequence sq4= DOTween.Sequence(); sq4.Append(this.transform.GetChild(4).DOScale(1.1f,1.5f)); sq4.Append(this.transform.GetChild(4).DOScale(1.0f,0.5f)); sq4.SetDelay(3.2f); Sequence sq5= DOTween.Sequence(); sq5.Append(this.transform.GetChild(5).DOScale(1.1f,1.5f)); sq5.Append(this.transform.GetChild(5).DOScale(1.0f,0.5f)); sq5.SetDelay(4.2f); }else{ //KongregateAPIBehaviour.SendFirstTimeDone(); Manager.maxBalls=2; BallController.MaxBalls=2; this.GetComponent<Camera>().DOOrthoSize(7.0f,2.0f); this.transform.DOMove(new Vector3(-3.0f,-1.9f,-10.0f),2.0f); GameObject a=GameObject.FindGameObjectWithTag("Opponent"); a.transform.DOScaleY(1.6f,1.5f); Manager.opPaddleSize=1.6f; ParticleSystem.MainModule m= BallController.particleSys.main; m.startSpeed=2; //a.transform.DOMoveY(0.0f,1.5f); //a.GetComponent<OpponentScript>().enabled=false; OpponentScript.size=6; } Manager.FirstTime=false; this.enabled=false; } } public static void disable(){ dis=true; } }
namespace NET_GC { using System; using System.Drawing; public class UnmanagedBitmap : IDisposable { private bool disposed; private readonly GdiBitmapSafeHandle handle; private readonly Bitmap image; public UnmanagedBitmap(string file) { image = (Bitmap) Image.FromFile(file); handle = new GdiBitmapSafeHandle(image.GetHbitmap()); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { image.Dispose(); if (!handle.IsInvalid) { handle.Dispose(); } } disposed = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tareas { public class Dominio: Conexion { private int iduser; private string nombre; private string apellido; private string correo; private string contrasena; public Dominio( string nombre, string apellido, string correo, string contrasena) { this.iduser = iduser; this.nombre = nombre; this.apellido = apellido; this.correo = correo; this.contrasena = contrasena; } public Dominio() { } public string Insertarusuario() { Conexion con = new Conexion(); con.Insertarusuario(nombre,apellido,correo,contrasena ); return "Registrado exitosamente"; } } }
namespace Serilog.PerformanceTests; [SimpleJob(RuntimeMoniker.NetCoreApp21, baseline: true)] [SimpleJob(RuntimeMoniker.NetCoreApp31)] public class SourceContextMatchBenchmark { readonly LevelOverrideMap _levelOverrideMap; readonly Logger _loggerWithOverrides; readonly List<ILogger> _loggersWithFilters = new(); readonly LogEvent _event = Some.InformationEvent(); readonly string[] _contexts; public SourceContextMatchBenchmark() { _contexts = new[] { "Serilog", "MyApp", "MyAppSomething", "MyOtherApp", "MyApp.Something", "MyApp.Api.Models.Person", "MyApp.Api.Controllers.AboutController", "MyApp.Api.Controllers.HomeController", "Api.Controllers.HomeController" }; var overrides = new Dictionary<string, LoggingLevelSwitch> { ["MyApp"] = new(LogEventLevel.Debug), ["MyApp.Api.Controllers"] = new(LogEventLevel.Information), ["MyApp.Api.Controllers.HomeController"] = new(LogEventLevel.Warning), ["MyApp.Api"] = new(LogEventLevel.Error) }; _levelOverrideMap = new(overrides, LogEventLevel.Fatal, null); var loggerConfiguration = new LoggerConfiguration().MinimumLevel.Fatal(); foreach (var @override in overrides) { loggerConfiguration = loggerConfiguration.MinimumLevel.Override(@override.Key, @override.Value); foreach (var ctx in _contexts) { _loggersWithFilters.Add( new LoggerConfiguration().MinimumLevel.Verbose() .Filter.ByIncludingOnly(Matching.FromSource(@override.Key)) .WriteTo.Sink<NullSink>() .CreateLogger() .ForContext(Constants.SourceContextPropertyName, ctx)); } } _loggerWithOverrides = loggerConfiguration.WriteTo.Sink<NullSink>().CreateLogger(); } [Benchmark] public void Filter_MatchingFromSource() { for (var i = 0; i < _loggersWithFilters.Count; ++i) { _loggersWithFilters[i].Write(_event); } } [Benchmark] public void Logger_ForContext() { for (var i = 0; i < _contexts.Length; ++i) { _loggerWithOverrides.ForContext(Constants.SourceContextPropertyName, _contexts[i]); } } [Benchmark] public void LevelOverrideMap_GetEffectiveLevel() { for (var i = 0; i < _contexts.Length; ++i) { _levelOverrideMap.GetEffectiveLevel(_contexts[i], out _, out _); } } }
using MikeGrayCodes.Authentication.Domain.Entities.ApplicationUser.Events; using MikeGrayCodes.BuildingBlocks.Infrastructure.SeedWork; namespace MikeGrayCodes.Authentication.Application.Users { public class ApplicationUserCreatedNotification : DomainEventNotification<ApplicationUserCreatedDomainEvent> { public ApplicationUserCreatedNotification(ApplicationUserCreatedDomainEvent domainEvent) : base(domainEvent) { } } }
using ecommerce.ecommerceClasses; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace ecommerce { public partial class updateTransactionScreen : ecommerce.Form1 { public static string code; public updateTransactionScreen() { InitializeComponent(); } private void updateTransactionScreen_Load(object sender, EventArgs e) { TransactionDAO transactionDAO = new TransactionDAO(); Transaction transaction = transactionDAO.GetTransaction(code); this.statusLabel.Text = "Update Transaction"; this.statusStrip1.Refresh(); this.transactionCode.Enabled = false; this.transactionCode.Text = code; this.quantity.Text = transaction.Quantity.ToString(); this.product.Text = transaction.Product.Name; this.client.Text = transaction.Client.Name; this.product.Enabled = false; this.client.Enabled = false; } private void addproductbtn_Click_1(object sender, EventArgs e) { TransactionDAO transactionDAO = new TransactionDAO(); Transaction transaction = new Transaction(); transaction.Code = code; transaction.Quantity = int.Parse(this.quantity.Text); this.message.ForeColor = Color.OrangeRed; try { if (transaction.Product.Quantity < transaction.Quantity) { throw new INSUFFICIENT_QUANTITY("There's not a susfficiant Quantity to accept your transaction"); } transactionDAO.updateTransaction(transaction); this.message.Text = "The Selected Transaction Has Been Updated With Success"; }catch(INSUFFICIENT_QUANTITY exception) { this.message.Text = "An Error Has Occured While Updating The Selected Transaction"; string title = "Exception"; string message = exception.Message; MessageBox.Show(message, title); } } } }
namespace Strings { public class StringRotationDetector { /** * The aim is to write a method DetectRotation(string, string => bool) * Given an stringToCheck, find if that string is a rotation of the referenceString. */ public bool CheckRotation(string referenceString, string stringToCheck) { if (referenceString.Length != stringToCheck.Length) return false; return (stringToCheck + stringToCheck).Contains(referenceString); } } }
using GesCMS.Core.Common; namespace GesCMS.Core.Entities { public class WidgetInPagePriority : BaseEntity { public byte Priority { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace Leaf { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; const int numPlayers = 2; List<Leaf> leaves = new List<Leaf>(numPlayers); Texture2D leafTexture; Texture2D vectorTexture; Texture2D anchorTexture; const int borderY = 200; const int borderX = 100; int screenX = 0; int screenY = 0; int screenWidth; int maxScreenWidth; int screenHeight; int maxScreenHeight; double screenRatio; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = ScreenData.Get().GetFullScreenWidth(); graphics.PreferredBackBufferHeight = ScreenData.Get().GetFullScreenHeight(); //graphics.IsFullScreen = true; graphics.ApplyChanges(); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { screenWidth = ScreenData.Get().GetFullScreenWidth(); maxScreenWidth = screenWidth * 2; screenHeight = ScreenData.Get().GetFullScreenHeight(); maxScreenHeight = screenHeight * 2; screenRatio = screenWidth / ScreenData.Get().GetFullScreenWidth(); leaves.Add(new Leaf(new KeySet(Keys.Up, Keys.Down, Keys.Left, Keys.Right), Color.GreenYellow)); leaves.Add(new Leaf(new KeySet(Keys.W, Keys.S, Keys.A, Keys.D), Color.DarkRed)); leaves.RemoveRange(numPlayers, leaves.Count - numPlayers); // TODO: Add your initialization logic here leafTexture = Content.Load<Texture2D>("leaf"); vectorTexture = Content.Load<Texture2D>("Vector"); anchorTexture = Content.Load<Texture2D>("Anchor"); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); KeyHandler.Get().UpdateKeyboardHandler(); foreach (Leaf leaf in leaves) { leaf.Update(); // Updates the player's leaf. } CheckMapBounds(); base.Update(gameTime); } public void CheckMapBounds() { int minObjX = screenX + screenWidth/2; int maxObjX = screenX + screenWidth/2; int minObjY = screenY + screenHeight/2; int maxObjY = screenY + screenHeight/2; if (screenRatio > 1) // If the screen is larger than normal, then set it back to normal { int deltaScreen = screenWidth - ScreenData.Get().GetFullScreenWidth(); if (deltaScreen > 0) { screenX += deltaScreen / 2; screenWidth = ScreenData.Get().GetFullScreenWidth(); } deltaScreen = screenHeight - ScreenData.Get().GetFullScreenHeight(); if (deltaScreen > 0) { screenY += deltaScreen / 2; screenHeight = ScreenData.Get().GetFullScreenHeight(); } } foreach (Leaf leaf in leaves) { if (leaf.pos.x > maxObjX) maxObjX = (int)leaf.pos.x; else if (leaf.pos.x < minObjX) minObjX = (int)leaf.pos.x; if (leaf.pos.y > maxObjY) maxObjY = (int)leaf.pos.y; else if (leaf.pos.y < minObjY) minObjY = (int)leaf.pos.y; } // Hard bounds on max and min obj X; if (minObjX < -ScreenData.Get().GetFullScreenWidth()) minObjX = -ScreenData.Get().GetFullScreenWidth(); if (maxObjX > ScreenData.Get().GetFullScreenWidth() + screenWidth) maxObjX = ScreenData.Get().GetFullScreenWidth() + screenWidth; if (minObjX < screenX + borderX) // Check to see if there's an object OOB Left screenX = minObjX - borderX; // Correct OOB Left if (maxObjX > screenX + screenWidth - borderX) // Check to see if there's an object OOB Right { // We need to move the screen to the right if (maxObjX - minObjX > screenWidth - (2 * borderX)) // Check to see if both objects can fit on the screen { // No, so we need to scale up the screen screenWidth = maxObjX - screenX + borderX; // Correct OOB Right } else // Yes, we can move the screen to the right { screenX = maxObjX + borderX - screenWidth; // Correct OOB Right } } if (minObjY < screenY + borderY) // Check to see if there's an object OOB Top screenY = minObjY - borderY; // Correct OOB Top if (maxObjY > screenY + screenHeight - borderY) // Check to see if there's an object OOB Bottom { // We need to move the screen down if (maxObjY - minObjY > screenHeight - (2 * borderY)) // Check to see if both objects can fit on the screen { // No, so we need to scale up the screen screenHeight = maxObjY - screenY + borderY; // Correct OOB Bottom int delta = screenHeight - maxScreenHeight; if (delta > 0) // If we're already stretched too thin, drop the top guy. { screenHeight = maxScreenHeight; screenY += delta; } } else // Yes, we can move the screen down { screenY = maxObjY + borderY - screenHeight; // Correct OOB Bottom } } double widthRatio = screenWidth / (double)ScreenData.Get().GetFullScreenWidth(); double heightRatio = screenHeight / (double)ScreenData.Get().GetFullScreenHeight(); screenRatio = (widthRatio > heightRatio ? widthRatio : heightRatio); // Set to the greater ratio } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); GraphicsDevice.Clear(Color.CornflowerBlue); foreach (Leaf leaf in leaves) { DrawLeaf(leaf); } base.Draw(gameTime); spriteBatch.End(); } public void DrawLeaf(Leaf leaf) { spriteBatch.Draw(leafTexture, new Rectangle(ScreenX(leaf.pos.x), ScreenY(leaf.pos.y), (int)(leafTexture.Width / screenRatio), (int)(leafTexture.Height / screenRatio)), null, leaf.color, (float)leaf.angle.val, new Vector2(leafTexture.Width / 2, 0), SpriteEffects.None, 0); spriteBatch.Draw(anchorTexture, new Rectangle(ScreenX(leaf.anchor.x), ScreenY(leaf.anchor.y), (int)(anchorTexture.Width / screenRatio), (int)(anchorTexture.Height / screenRatio)), leaf.color); //DrawVector(leaf.acc, Color.Red); //DrawVector(leaf.vel, Color.Blue); //DrawVector(leaf.gravity, Color.Black); } public void DrawVector(PhysicsVector vec, Color color, Leaf leaf) { //spriteBatch.Draw(vectorTexture, new Rectangle(leaf.pos.x, leaf.pos.y, (int)(vec.magnitude * 20), vectorTexture.Height/2), null, color, (float)vec.direction.val, new Vector2(0, 0), SpriteEffects.None, 0); } public int ScreenX(double val) { return (int)((val - screenX) / screenRatio); } public int ScreenY(double val) { return (int)((val - screenY) / screenRatio); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameplayManager : MonoBehaviour { /* These are the possible enemies that you can face */ public GameObject circleEnemy; public GameObject hexagonBomb; public GameObject pointPrefab; public GameObject playerPrefab; GameObject point; GameObject player; public GameObject firstBoss; public GameObject secondBoss; public GameObject thirdBoss; GameObject canvas; public GameObject scoreboardPrefab; public GameObject stageMessagesPrefab; GameObject scoreboard; GameObject stageMessages; public GameObject lossMenuPrefab; GameObject lossMenu; GameObject musicManager; MusicManager musicManagerScript; StageMessagesController stageMessagesScript; PointController pointController; bool inMove; bool gameEnded; SettingsManager settingsManager; /* These are for coordinates of the screen */ float topEdgeY; float botEdgeY; float screenHeight; float leftEdgeX; float rightEdgeX; float screenWidth; /* These are for the drop position of entities that are offscreen like horizontal and vertical balls, these are just guidelines though and actual values set below */ float vertDropPos; float horDropPos; /* These control where the horizontal and vertical balls can spawn. Min means where y is lowest. */ float farRightCircleDropPosX; float farLeftCircleDropPosX; float minHorCircleDropPosY; float maxHorCircleDropPosY; /*Gap time is time where no move is happening */ float gapTimePatternMoves; float gapTimeRainMoves; float gapTimeStairMoves; float gapTimeDiagonalMoves; /* This is the number of balls in random attacks like rain */ int numBallsRandomAttacks; /* These are default values for the starting acceleration of the balls */ float startingAccelVertCircles = 7.2f; float startingAccelHorCircles = 7.2f; float startingAccelDefaultCircles = 7.2f; /* Current values for acceleration of the balls */ float currAccelVertCircles; float currAccelHorCircles; float currAccelDefaultCircles; Vector2 lowerLeftCornerDropPos; Vector2 UpperRightCornerDropPos; float lowerLeftToTopRightDropAngle; /* When objects are placed they have to have an orientation, most shouldn't be rotated so just keep a default orientaiton. */ Quaternion defaultOrientation = new Quaternion(0, 0, 0, 0); float timeGameStarted; float timeSinceGameStarted; float timeToWaitVertCircleFall; float timeToWaitHorCircleFall; readonly int NUM_MOVES_LEVEL_ONE = 9; readonly int NUM_MOVES_LEVEL_TWO = 10; readonly int NUM_MOVES_LEVEL_THREE = 12; readonly int NUM_MOVES_LEVEL_FOUR = 15; int level; // Use this for initialization void Start() { Cursor.visible = false; //player = GameObject.FindGameObjectWithTag("Player"); inMove = false; gameEnded = false; musicManager = GameObject.FindWithTag("MusicManager"); musicManagerScript = musicManager.GetComponent<MusicManager>(); point = Instantiate(pointPrefab, new Vector2(100, 100), new Quaternion(0, 0, 0, 0)); player = Instantiate(playerPrefab, new Vector2(0, 0), new Quaternion(0, 0, 0, 0)); settingsManager = GameObject.Find("Settings Manager").GetComponent<SettingsManager>(); canvas = GameObject.Find("Canvas"); scoreboard = Instantiate(scoreboardPrefab, canvas.transform); //stageMessages = Instantiate(stageMessagesPrefab, canvas.transform); currAccelVertCircles = startingAccelVertCircles; currAccelHorCircles = startingAccelHorCircles; currAccelDefaultCircles = startingAccelDefaultCircles; timeGameStarted = Time.time; timeSinceGameStarted = 0; lowerLeftCornerDropPos = new Vector2(-horDropPos, -vertDropPos); UpperRightCornerDropPos = new Vector2(horDropPos, vertDropPos); lowerLeftToTopRightDropAngle = Mathf.Atan((UpperRightCornerDropPos.y - lowerLeftCornerDropPos.y) / (UpperRightCornerDropPos.x - lowerLeftCornerDropPos.x)); pointController = point.GetComponent<PointController>(); level = 1; settingsManager = settingsManager.GetComponent<SettingsManager>(); SetScreenCoordinates(); if (level == 1) { musicManagerScript.PlayFirstLevel(); } } void SetScreenCoordinates() { topEdgeY = settingsManager.GetTopWallPositionY(); botEdgeY = settingsManager.GetBottomWallPositionY(); screenHeight = settingsManager.GetScreenHeight(); leftEdgeX = settingsManager.GetLeftWallPositionX(); rightEdgeX = settingsManager.GetRightWallPositionX(); screenWidth = settingsManager.GetScreenWidth(); vertDropPos = topEdgeY + 1; horDropPos = rightEdgeX + 1; farRightCircleDropPosX = rightEdgeX - 0.5f; farLeftCircleDropPosX = leftEdgeX + 0.5f; minHorCircleDropPosY = botEdgeY + 0.5f; maxHorCircleDropPosY = topEdgeY - 0.5f; } // Update is called once per frame void Update() { timeSinceGameStarted = Time.time - timeGameStarted; if (inMove || gameEnded || timeSinceGameStarted < 1) { return; } /*currAccelVertCircles = (Mathf.Log(timeSinceGameStarted) * 0.5f) + startingAccelVertCircles; currAccelHorCircles = (Mathf.Log(timeSinceGameStarted) * 0.5f) + startingAccelHorCircles; currAccelDefaultCircles = (Mathf.Log(timeSinceGameStarted) * 0.5f) + startingAccelDefaultCircles;*/ timeToWaitVertCircleFall = Mathf.Sqrt(2 * screenHeight / currAccelVertCircles); timeToWaitHorCircleFall = Mathf.Sqrt(2 * screenWidth / currAccelVertCircles); /*int move = UnityEngine.Random.Range(0, numMoves); DoRandomMove(move);*/ UpdateDifficulty(); inMove = true; if (level == 1) { DoMoveLevelOne(); } else if (level == 2) { FirstBoss(); } else if (level == 3) { DoMoveLevelTwo(); } else if (level == 4) { SecondBoss(); } else if (level == 5) { DoMoveLevelThree(); } else if (level == 6) { ThirdBoss(); } else if (level == 7) { DoMoveLevelFour(); } else { DoMoveLevelFour(); } } void DoMoveLevelOne() { int move = UnityEngine.Random.Range(0, NUM_MOVES_LEVEL_ONE); DoMoveLevelOne(move); //StartCoroutine(DiagonalCirclesRightToLeft()); //return; } void DoMoveLevelOne(int move) { switch (move) { case 0: StartCoroutine(StairLeftToRight()); break; case 1: StartCoroutine(StairRightToLeft()); break; case 2: StartCoroutine(StairTopToBottom()); break; case 3: StartCoroutine(StairBottomToTop()); break; case 4: StartCoroutine(Snowflake()); break; case 5: StartCoroutine(RainRandomDown()); break; case 6: StartCoroutine(BubbleUp()); break; case 7: StartCoroutine(RainRandomLeft()); break; case 8: StartCoroutine(RainRandomRight()); break; } } void DoMoveLevelTwo() { Debug.Log("Doing Level Two!!!"); int numMoves = NUM_MOVES_LEVEL_TWO; inMove = true; int move = UnityEngine.Random.Range(0, numMoves); if (move < NUM_MOVES_LEVEL_ONE) { DoMoveLevelOne(move); return; } switch (move) { case 9: StartCoroutine(RandomMines()); break; } } void DoMoveLevelThree() { } void DoMoveLevelFour() { } void DoRandomMove(int move) { inMove = true; //FirstBoss(); //StartCoroutine(RandomMines()); //return; switch (move) { case 0: StartCoroutine(BritishFlag()); break; case 1: StartCoroutine(StairLeftToRight()); break; case 2: StartCoroutine(StairRightToLeft()); break; case 3: StartCoroutine(Snowflake()); break; case 4: StartCoroutine(RainRandomDown()); break; case 5: StartCoroutine(BubbleUp()); break; case 6: StartCoroutine(RainRandomLeft()); break; case 7: StartCoroutine(RainRandomRight()); break; case 8: StartCoroutine(RandomMines()); break; case 9: StartCoroutine(StairTopToBottom()); break; case 10: StartCoroutine(StairBottomToTop()); break; } } IEnumerator VerticalCrossingMove() { for (float currX = farLeftCircleDropPosX + 1; currX <= farRightCircleDropPosX; currX += 2f) { Instantiate(circleEnemy, new Vector2(currX, vertDropPos), defaultOrientation); } for (float currX = farLeftCircleDropPosX; currX <= farRightCircleDropPosX - 1; currX += 2f) { Instantiate(circleEnemy, new Vector2(currX, -vertDropPos), defaultOrientation); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator HorizontalCrossingMove() { for (float currY = minHorCircleDropPosY; currY <= maxHorCircleDropPosY; currY += 2f) { break; } yield return new WaitForEndOfFrame(); } void StairAttack() { int numMoves = 5; int move = UnityEngine.Random.Range(0, numMoves); switch (move) { case 0: StartCoroutine(StairBottomToTop()); break; case 1: StartCoroutine(StairTopToBottom()); break; case 2: StartCoroutine(StairLeftToRight()); break; case 3: StartCoroutine(StairRightToLeft()); break; case 4: StartCoroutine(Snowflake()); break; } } void RandomAttack() { int numMoves = 4; int move = UnityEngine.Random.Range(0, numMoves); switch (move) { case 0: StartCoroutine(RainRandomDown()); break; case 1: StartCoroutine(BubbleUp()); break; case 2: StartCoroutine(RainRandomLeft()); break; case 3: StartCoroutine(RainRandomRight()); break; } } IEnumerator BritishFlag() { //Debug.Log("British Flag"); //float gapTime = 0.1f - Mathf.Log(timeSinceGameStarted) * 0.005f; int numBalls = 8; for (int i = 0; i < numBalls; i++) { GameObject verticalFaller = Instantiate(circleEnemy, new Vector2(0, vertDropPos), defaultOrientation); GameObject verticalRiser = Instantiate(circleEnemy, new Vector2(0, -vertDropPos), defaultOrientation); verticalFaller.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, -currAccelVertCircles)); verticalRiser.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, currAccelVertCircles)); GameObject circleLeftToRight = Instantiate(circleEnemy, new Vector2(-horDropPos, 0), defaultOrientation); GameObject circleRightToLeft = Instantiate(circleEnemy, new Vector2(horDropPos, 0), defaultOrientation); circleLeftToRight.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(currAccelHorCircles, 0)); circleRightToLeft.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelHorCircles, 0)); GameObject circleLowerLeft = Instantiate(circleEnemy, new Vector2(-horDropPos, -vertDropPos), defaultOrientation); GameObject circleUpperLeft = Instantiate(circleEnemy, new Vector2(-horDropPos, vertDropPos), defaultOrientation); GameObject circleLowerRight = Instantiate(circleEnemy, new Vector2(horDropPos, -vertDropPos), defaultOrientation); GameObject circleUpperRight = Instantiate(circleEnemy, new Vector2(horDropPos, vertDropPos), defaultOrientation); //Cos and Sin to make them go from corner to corner and not a 45 degree angle since map is not a square circleLowerLeft.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(currAccelDefaultCircles * Mathf.Cos(lowerLeftToTopRightDropAngle), currAccelDefaultCircles * Mathf.Sin(lowerLeftToTopRightDropAngle))); circleUpperLeft.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(currAccelDefaultCircles * Mathf.Cos(lowerLeftToTopRightDropAngle), -currAccelDefaultCircles * Mathf.Sin(lowerLeftToTopRightDropAngle))); circleLowerRight.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelDefaultCircles * Mathf.Cos(lowerLeftToTopRightDropAngle), currAccelDefaultCircles * Mathf.Sin(lowerLeftToTopRightDropAngle))); circleUpperRight.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelDefaultCircles * Mathf.Cos(lowerLeftToTopRightDropAngle), -currAccelDefaultCircles * Mathf.Sin(lowerLeftToTopRightDropAngle))); yield return new WaitForSeconds(gapTimePatternMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator StairLeftToRight() { //Debug.Log("Rain Left"); //float gapTime = 0.1f - Mathf.Log(timeSinceGameStarted) * 0.005f; for (float currX = farLeftCircleDropPosX; currX <= farRightCircleDropPosX - 1; currX += 1f) { GameObject verticalFaller = Instantiate(circleEnemy, new Vector2(currX, vertDropPos), defaultOrientation); GameObject verticalRiser = Instantiate(circleEnemy, new Vector2(currX, -vertDropPos), defaultOrientation); verticalFaller.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, -currAccelVertCircles)); verticalRiser.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, currAccelVertCircles)); yield return new WaitForSeconds(gapTimeStairMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator StairRightToLeft() { //Debug.Log("Rain Right"); //float gapTime = 0.1f - Mathf.Log(timeSinceGameStarted) * 0.005f; for (float currX = farRightCircleDropPosX; currX >= farLeftCircleDropPosX + 1; currX -= 1) { GameObject verticalFaller = Instantiate(circleEnemy, new Vector2(currX, vertDropPos), defaultOrientation); GameObject verticalRiser = Instantiate(circleEnemy, new Vector2(currX, -vertDropPos), defaultOrientation); verticalFaller.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, -currAccelVertCircles)); verticalRiser.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, currAccelVertCircles)); yield return new WaitForSeconds(gapTimeStairMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator Snowflake() { //Debug.Log("Rain Sides"); //float gapTime = 0.1f - Mathf.Log(timeSinceGameStarted) * 0.005f; for (float currX = farRightCircleDropPosX; currX > 0.5f; currX -= 0.9f) { if (currX > farRightCircleDropPosX - 3) { GameObject circleLeftToRight = Instantiate(circleEnemy, new Vector2(-horDropPos, 0), defaultOrientation); GameObject circleRightToLeft = Instantiate(circleEnemy, new Vector2(horDropPos, 0), defaultOrientation); circleLeftToRight.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(currAccelHorCircles, 0)); circleRightToLeft.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelHorCircles, 0)); } GameObject verticalFaller_1 = Instantiate(circleEnemy, new Vector2(currX, vertDropPos), defaultOrientation); GameObject verticalRiser_1 = Instantiate(circleEnemy, new Vector2(currX, -vertDropPos), defaultOrientation); GameObject verticalFaller_2 = Instantiate(circleEnemy, new Vector2(-currX, vertDropPos), defaultOrientation); GameObject verticalRiser_2 = Instantiate(circleEnemy, new Vector2(-currX, -vertDropPos), defaultOrientation); verticalFaller_1.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, -currAccelVertCircles)); verticalFaller_2.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, -currAccelVertCircles)); verticalRiser_1.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, currAccelVertCircles)); verticalRiser_2.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, currAccelVertCircles)); yield return new WaitForSeconds(gapTimeStairMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator RainRandomDown() { //Debug.Log("Rain Random Down"); //float gapTime = 0.11f - Mathf.Log(timeSinceGameStarted) * 0.015f; for (int i = 0; i < numBallsRandomAttacks; i++) { GameObject verticalFaller_1 = Instantiate(circleEnemy, new Vector2(UnityEngine.Random.Range(farLeftCircleDropPosX, farRightCircleDropPosX), vertDropPos), defaultOrientation); verticalFaller_1.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, -currAccelVertCircles)); yield return new WaitForSeconds(gapTimeRainMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator BubbleUp() { //Debug.Log("Bubble Up"); //float gapTime = 0.11f - Mathf.Log(timeSinceGameStarted) * 0.015f; for (int i = 0; i < numBallsRandomAttacks; i++) { GameObject verticalRiser_1 = Instantiate(circleEnemy, new Vector2(UnityEngine.Random.Range(farLeftCircleDropPosX, farRightCircleDropPosX), -vertDropPos), defaultOrientation); verticalRiser_1.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(0, currAccelVertCircles)); yield return new WaitForSeconds(gapTimeRainMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator RainRandomLeft() { //Debug.Log("Rain Random Left"); //float gapTime = 0.11f - Mathf.Log(timeSinceGameStarted) * 0.015f; for (int i = 0; i < numBallsRandomAttacks; i++) { GameObject circleLeftToRight = Instantiate(circleEnemy, new Vector2(-horDropPos, UnityEngine.Random.Range(minHorCircleDropPosY, maxHorCircleDropPosY)), defaultOrientation); circleLeftToRight.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(currAccelHorCircles, 0)); yield return new WaitForSeconds(gapTimeRainMoves); } yield return new WaitForSeconds(timeToWaitHorCircleFall); inMove = false; } IEnumerator RainRandomRight() { //Debug.Log("Rain Random Right"); //float gapTime = 0.11f - Mathf.Log(timeSinceGameStarted) * 0.015f; for (int i = 0; i < numBallsRandomAttacks; i++) { GameObject circleRightToLeft = Instantiate(circleEnemy, new Vector2(horDropPos, UnityEngine.Random.Range(minHorCircleDropPosY, maxHorCircleDropPosY)), defaultOrientation); circleRightToLeft.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelHorCircles, 0)); yield return new WaitForSeconds(gapTimeRainMoves); } yield return new WaitForSeconds(timeToWaitHorCircleFall); inMove = false; } IEnumerator RandomMines() { //Debug.Log("Random Mines"); float gapTime = 0.8f; int numMines = 6; float minMinePosX = -5.5f; float maxMinePosX = 5.5f; float minMinePosY = -4.25f; float maxMinePosY = 4.25f; Vector2 nextMinePos; for (int i = 0; i < numMines; i++) { do { nextMinePos = new Vector2(UnityEngine.Random.Range(minMinePosX, maxMinePosX), UnityEngine.Random.Range(minMinePosY, maxMinePosY)); } while (!isValidPos(nextMinePos)); Instantiate(hexagonBomb, nextMinePos, defaultOrientation); yield return new WaitForSeconds(gapTime); } inMove = false; } IEnumerator StairTopToBottom() { //float gapTime = 0.1f - Mathf.Log(timeSinceGameStarted) * 0.005f; for (float currY = maxHorCircleDropPosY; currY > minHorCircleDropPosY; currY -= 1) { GameObject circleLeftToRight = Instantiate(circleEnemy, new Vector2(-horDropPos, currY), defaultOrientation); GameObject circleRightToLeft = Instantiate(circleEnemy, new Vector2(horDropPos, currY), defaultOrientation); circleLeftToRight.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(currAccelHorCircles, 0)); circleRightToLeft.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelHorCircles, 0)); yield return new WaitForSeconds(gapTimeStairMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator StairBottomToTop() { //float gapTime = 0.1f - Mathf.Log(timeSinceGameStarted) * 0.005f; for (float currY = minHorCircleDropPosY; currY < maxHorCircleDropPosY; currY += 1) { GameObject circleLeftToRight = Instantiate(circleEnemy, new Vector2(-horDropPos, currY), defaultOrientation); GameObject circleRightToLeft = Instantiate(circleEnemy, new Vector2(horDropPos, currY), defaultOrientation); circleLeftToRight.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(currAccelHorCircles, 0)); circleRightToLeft.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelHorCircles, 0)); yield return new WaitForSeconds(gapTimeStairMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator DiagonalCirclesRightToLeft() { //float gapTime = 0.3f - Mathf.Log(timeSinceGameStarted) * 0.005f; for (float currX = farLeftCircleDropPosX; currX <= farRightCircleDropPosX + 16.5; currX += 1.5f) { GameObject circle = Instantiate(circleEnemy, new Vector2(currX, -vertDropPos), defaultOrientation); circle.GetComponent<CircleEnemyController>().SetAcceleration(new Vector2(-currAccelDefaultCircles * Mathf.Cos(lowerLeftToTopRightDropAngle), currAccelDefaultCircles * Mathf.Sin(lowerLeftToTopRightDropAngle))); yield return new WaitForSeconds(gapTimeDiagonalMoves); } yield return new WaitForSeconds(timeToWaitVertCircleFall); inMove = false; } IEnumerator floaterAllSidesAttack() { yield return new WaitForEndOfFrame(); } IEnumerator floaterFromTopAttack() { yield return new WaitForEndOfFrame(); } /*IEnumerator HastagMove() { }*/ void FirstBoss() { GameObject firstBossController = Instantiate(firstBoss, new Vector2(0, 0), defaultOrientation); firstBossController.GetComponent<FirstBossController>().SetGameManager(gameObject); musicManagerScript.PlayFirstBoss(); //GameObject secondBossController = Instantiate(secondBoss, new Vector2(0, 0), defaultOrientation); //Instantiate(thirdBoss, new Vector2(0, 0), defaultOrientation); } void SecondBoss() { GameObject secondBossController = Instantiate(secondBoss, new Vector2(0, 0), defaultOrientation); secondBossController.GetComponent<SecondBossController>().SetGameManager(gameObject); StartCoroutine(SecondBossMines()); } IEnumerator SecondBossMines() { float gapTime = 0.8f; float minMinePosX = -5.5f; float maxMinePosX = 5.5f; float minMinePosY = -4.25f; float maxMinePosY = 4.25f; Vector2 nextMinePos; while (level == 4) { do { nextMinePos = new Vector2(UnityEngine.Random.Range(minMinePosX, maxMinePosX), UnityEngine.Random.Range(minMinePosY, maxMinePosY)); } while (!isValidPos(nextMinePos)); Instantiate(hexagonBomb, nextMinePos, defaultOrientation); yield return new WaitForSeconds(gapTime); } } void ThirdBoss() { Instantiate(thirdBoss, new Vector2(0, vertDropPos), defaultOrientation); } public void EndFirstBoss() { StartCoroutine(EndBoss()); //Debug.Log("Finished first boss"); scoreboard.GetComponent<Scoreboard>().AddPoints(5); //stageMessagesScript.DisplayFirstStageCompleted(); } public void EndSecondBoss() { StartCoroutine(EndBoss()); scoreboard.GetComponent<Scoreboard>().AddPoints(5); //stageMessagesScript.DisplaySecondStageCompleted(); } public void EndThirdBoss() { StartCoroutine(EndBoss()); scoreboard.GetComponent<Scoreboard>().AddPoints(5); //stageMessagesScript.DisplayThirdStageCompleted(); } IEnumerator EndBoss() { yield return new WaitForSeconds(1f); inMove = false; IncrementLevel(); } public void EndGame() { gameEnded = true; Cursor.visible = true; SendEndGameMessages(); } void SendEndGameMessages() { scoreboard.GetComponent<Scoreboard>().ChangeHighScore(); } public float GetTimeSinceGameStarted() { return timeSinceGameStarted; } public void IncrementLevel() { //Debug.Log("Increment Level!"); pointController.SetIsWorthPoint(!pointController.GetIsWorthPoint()); StartCoroutine(IncrementLevelHelper()); } IEnumerator IncrementLevelHelper() { while (inMove) { yield return new WaitForEndOfFrame(); } level++; UpdateDifficulty(); } public bool IsGameEnded() { return gameEnded; } void UpdateDifficulty() { currAccelVertCircles = (level * 0.05f) + startingAccelVertCircles; currAccelHorCircles = (level * 0.05f) + startingAccelHorCircles; currAccelDefaultCircles = (level * 0.05f) + startingAccelDefaultCircles; gapTimePatternMoves = 0.1f - level * 0.002f;; gapTimeRainMoves = 0.1f - level * 0.005f;; gapTimeStairMoves = 0.1f - level * 0.002f;; gapTimeDiagonalMoves = 0.28f - level * 0.0025f; numBallsRandomAttacks = (int) Mathf.Floor(2.5f / gapTimeRainMoves); } bool isValidPos(Vector2 pos) { bool isValidPlayer; if (player != null) { isValidPlayer = Mathf.Abs(pos.x - player.transform.position.x) > 0.3f || Mathf.Abs(pos.y - player.transform.position.y) > 0.3f; } else { isValidPlayer = false; } bool isValidPoint = Mathf.Abs(pos.x - point.transform.position.x) > 0.3f || Mathf.Abs(pos.y - point.transform.position.y) > 0.3f; return (isValidPlayer && isValidPoint); } public float getFarRightCircleDropPosX() { return farRightCircleDropPosX; } public float getMaxHorCircleDropPosY() { return maxHorCircleDropPosY; } public float getVertDropPos() { return vertDropPos; } public float getHorDropPos() { return horDropPos; } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using CrudIrpf.Repository; using CrudIrpf.Domain; namespace CrudIrpf.Controllers { [ApiController] [Route("api/[controller]")] public class IrpfController : ControllerBase { private readonly ICrudIrpfRepository _repo; public IrpfController(ICrudIrpfRepository repo) { this._repo = repo; } [HttpGet] public async Task<IActionResult> Get() { try { var result = await _repo.GetAllIrpfAsync(); return Ok(result); } catch (System.Exception) { return this.StatusCode(StatusCodes.Status500InternalServerError); } } [HttpGet("{IrpfId}")] public async Task<IActionResult> Get(int IrpfId) { try { var result = await _repo.GetIrpfByIdAsync(IrpfId); return Ok(result); } catch (System.Exception) { return this.StatusCode(StatusCodes.Status500InternalServerError); } } [HttpPost] public async Task<IActionResult> Post(Irpf irpf) { try { _repo.Add(irpf); if (await _repo.SaveChangesAsync()) return Created($"/irpf/{irpf.Id}", irpf); } catch (System.Exception) { return this.StatusCode(StatusCodes.Status500InternalServerError); } return BadRequest(); } [HttpPut] public async Task<IActionResult> Put(Irpf model) { try { var irpf = await _repo.GetIrpfByIdAsync(model.Id); if (irpf == null) return NotFound(); _repo.Update(model); if (await _repo.SaveChangesAsync()) return Created($"/irpf/{model.Id}", model); } catch (System.Exception) { return this.StatusCode(StatusCodes.Status500InternalServerError); } return BadRequest(); } [HttpDelete("{IrpfId}")] public async Task<IActionResult> Delete(int IrpfId) { try { var irpf = await _repo.GetIrpfByIdAsync(IrpfId); if (irpf == null) return NotFound(); _repo.Delete(irpf); if (await _repo.SaveChangesAsync()) return Ok("{}"); } catch (System.Exception) { return this.StatusCode(StatusCodes.Status500InternalServerError); } return BadRequest(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StateExample.Safe { class NightState : IState { private static NightState _instance = new NightState(); private NightState() { } public static IState Instance => _instance; public void DoAlarm(IContext context) { context.CallSecurityCenter("非常ベル(夜間)"); } public void DoClock(IContext context, int hour) { if (9 <= hour && hour < 17) { context.ChangeState(DayState.Instance); } } public void DoPhone(IContext context) { context.CallSecurityCenter("夜間の通話録音"); } public void DoUse(IContext context) { context.RecordLog("非常:夜間の金庫使用"); } public override string ToString() { return "[夜間]"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LightMovement : MonoBehaviour { public new Transform transform; public int rotationAngle; public void FixedUpdate() { transform.Rotate(new Vector3(rotationAngle, 0, 0) * Time.deltaTime); } }
using System.IO; namespace HTBUtilities { public class HTBZipEntry { public readonly Stream Stream; public readonly string Name; public HTBZipEntry(Stream stream, string name) { Stream = stream; Name = name; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering.LWRP; public class Rune : DraggingElement { ParticleSystem particle; Animator anim; private string animBool="Stay"; public AudioClip clip; public GameObject breaking; SpriteRenderer curSprite; Light2D light; IMouseEventListener[] mouseListeners; protected override void Awake() { base.Awake(); particle = GetComponent<ParticleSystem>(); anim = GetComponent<Animator>(); curSprite = GetComponent<SpriteRenderer>(); light = GetComponentInChildren<Light2D>(); mouseListeners = GetComponents<IMouseEventListener>(); } private void OnEnable() { ResetState(); } private void OnMouseEnter() { if (particle != null) particle.Play(); if (anim != null) anim.SetBool("Stay", true); if (clip != null) { AudioManager.instance.FadeSound(true, clip); } if (mouseListeners != null && mouseListeners.Length != 0) { for (int i = 0; i < mouseListeners.Length; i++) { mouseListeners[i].Enter(); } } } private void OnMouseExit() { if (particle != null) {particle.Stop(); particle.Clear(); } if (anim != null) anim.SetBool("Stay", false); if (clip != null) { AudioManager.instance.FadeSound(false, clip); } if (mouseListeners!=null && mouseListeners.Length!=0) { for (int i = 0; i < mouseListeners.Length; i++) { mouseListeners[i].Exit(); } } } protected override void Dragging() { base.Dragging(); OnMouseExit(); } public override void OnMouseUp() { base.OnMouseUp(); if (breaking.activeInHierarchy) return; OnMouseEnter(); } /// <summary> /// fade sound in audiosource /// </summary> /// <param name="IsRise">true for up volume</param> /// <returns></returns> protected override void OnMouseDown() { if (Deleting.deleteMod) { Break(); } } /// <summary> /// break rune (deleting whith anim) /// </summary> public void Break() { breaking.SetActive(true); if (Deleting.deleteMod) AudioManager.instance.PlaySoundOfBreak(); } public void HideNormalRune() { curSprite.enabled = false; light.enabled = false; if (clip != null) { AudioManager.instance.FadeSound(false, clip); } } private void ResetState() { curSprite.enabled = true; light.enabled = true; breaking.SetActive(false); OnMouseExit(); } } public interface IMouseEventListener { void Enter(); void Exit(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Locadora.Domain.Repositories { public interface IFilmeRepository : IRepository<Filme> { Task<Filme> GetByName(string nome); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BarraLeather.Models { public class UserLoging { public string nombre { get; set; } public string clave { get; set; } public bool remeber { get; set; } } public class EstatusLog { public EstatusLog() { success = true; } public bool error { get; set; } public bool success { get; set; } public string errorMsg { get; set; } } }
using System; using System.Net.Http; using System.Net; using System.IO; using System.Threading.Tasks; using System.Xml; namespace WeatherService { public class WeatherService { private HttpClient request; public WeatherService() { request = new HttpClient(); } public Stream GetStream(string location) { Task<Stream> stream = request.GetStreamAsync(string.Format(WeatherAuthenticator.Url, location)); stream.Wait(); return stream.Result; } private string Parse(string s, string name) { XmlDocument doc = new XmlDocument(); doc.LoadXml(s); XmlNode node = doc.SelectSingleNode(name); return node.InnerText; } public ImmediateWeather GetWeather(Stream s) { ImmediateWeather weather = new ImmediateWeather(); StreamReader sr = new StreamReader(s); string response = sr.ReadToEnd(); weather.temp = decimal.Parse(Parse(response, "/root/current/temp_f")); weather.windSpeed = decimal.Parse(Parse(response, "/root/current/wind_mph")); weather.windDir = Parse(response, "/root/current/wind_dir"); weather.clouds = Parse(response, "/root/current/condition/text"); weather.city = Parse(response, "/root/location/name"); weather.state = Parse(response, "/root/location/region"); weather.country = Parse(response, "/root/location/country"); return weather; } } }
using System.Web.Mvc; namespace AttendanceWebApp.Controllers { public class ShiftScheduleController : Controller { // GET: ShiftSchedule public ActionResult SSDLUP() { if (Session["EmpUnqId"] != null && Session["UserRole"] != null) { return View(); } else { return RedirectToAction("Index", "Login"); } } public ActionResult SSUpdate() { return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); } public ActionResult SSRelease() { return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); } public ActionResult SSReport() { return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); } public ActionResult SSHRReport() { return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); } public ActionResult SSEmployee() { return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); } public ActionResult SSOpenMonth() { return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); } //public ActionResult ShiftChange() //{ // return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); //} //public ActionResult ReleaseShiftChange() //{ // return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); //} //public ActionResult ShiftChangePosting() //{ // return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); //} //public ActionResult ShiftChangeReportHR() //{ // return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); //} //public ActionResult ShiftChangeUploadTemplate() //{ // return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); //} //public ActionResult ShiftChangeReportSupervisor() //{ // return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); //} //public ActionResult MyShiftChangeReport() //{ // return Session["EmpUnqId"] != null && Session["UserRole"] != null ? View() : (ActionResult)RedirectToAction("Index", "Login"); //} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyOrcAi : MonoBehaviour { int i = 0; public static float damage = 50f; float xtnoe = 0.0f; float ytnoe = 0.0f; float sqrtmeplz = 9.0f; float xt = 0.0f; //the x position of the target float yt = 0.0f; //the y position of the target float xe = 0.0f; //the x position of the enemy float ye = 0.0f; //the y position of the enemy float dadis = 0.0f; //to do math of distance from target float trudis = 10.0f; //distance from target protected float angle = 0.0f; //angle of where to move float xm = 1.0f; //how much he moves in x direction float ym = 1.0f; //how much he moves in y direction float speed = 0.025f; //his speed GameObject cube = null; GameObject jab = null; protected GameObject target = null; //the orc's current target. // Use this for initialization protected void Start() { damage = 7f; cube = GameObject.Find("Cube"); jab = GameObject.Find("jab"); target = cube; name = "orc"; jab.gameObject.SetActive(false); } // Update is called once per frame public void Update() { target = cube; trudis = findDistanceToTarget(); angle = findAngleToTarget(); if (trudis < 2) { if (i >= 45) { jab.gameObject.SetActive(true); } if (i >= 55) { i = 0; jab.gameObject.SetActive(false); } i++; } else { xm = Mathf.Cos(angle) * speed; ym = Mathf.Sin(angle) * speed; transform.eulerAngles = new Vector3(0, 0, angle * 180 / Mathf.PI - 90); transform.position = new Vector2(transform.position.x + xm, transform.position.y + ym); } } protected float findAngleToTarget() //finds the angle between the orc and the target { xt = target.transform.position.x; yt = target.transform.position.y; xtnoe = xt - transform.position.x; ytnoe = yt - transform.position.y; return Mathf.Atan2(ytnoe, xtnoe); } protected float findDistanceToTarget() { xt = target.transform.position.x; yt = target.transform.position.y; xe = transform.position.x; ye = transform.position.y; sqrtmeplz = (xe - xt) * (xe - xt) + (ye - yt) * (ye - yt); dadis = Mathf.Sqrt(sqrtmeplz); return dadis; } private void OnDestroy() { GameObject.Find("ScoreCounter").GetComponent<score>().scoreCounter += 1; } }
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace gView.Framework.Azure.Storage { public class TableStorage { private string _connectionString; public bool Init(string initialParameter) { _connectionString = initialParameter; return true; } async public Task<bool> CreateTableAsync(string tableName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the table if it doesn't exist. CloudTable table = tableClient.GetTableReference(tableName); await table.CreateIfNotExistsAsync(); return true; } #region Insert async private Task<bool> InsertEntity(string tableName, TableEntity entity, bool mergeIfExists = false) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table = tableClient.GetTableReference(tableName); // Create the TableOperation object that inserts the customer entity. TableOperation inserOperation = mergeIfExists ? TableOperation.InsertOrMerge(entity) : TableOperation.Insert(entity); // Execute the insert operation. await table.ExecuteAsync(inserOperation); return true; } async public Task<bool> InsertEntitiesAsync<T>(string tableName, T[] entities) where T : ITableEntity { if (entities == null || entities.Length == 0) { return true; } CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table = tableClient.GetTableReference(tableName); var partitionKeys = entities.Select(e => e.PartitionKey).Distinct(); if (partitionKeys != null) { foreach (string partitionKey in partitionKeys) { if (String.IsNullOrWhiteSpace(partitionKey)) { continue; } // Create the batch operation. TableBatchOperation batchOperation = new TableBatchOperation(); int counter = 0; foreach (var entity in entities.Where(e => e?.PartitionKey == partitionKey)) { batchOperation.Insert(entity); if (++counter == 100) { var result = await table.ExecuteBatchAsync(batchOperation); batchOperation = new TableBatchOperation(); counter = 0; } } if (counter > 0) { // Execute the batch operation. var result = await table.ExecuteBatchAsync(batchOperation); } } } return true; } #endregion #region Query async public Task<T[]> AllEntitiesAsync<T>(string tableName) where T : ITableEntity, new() { return await AllTableEntities<T>(tableName, String.Empty); } async public Task<T[]> AllEntitiesAsync<T>(string tableName, string partitionKey) where T : ITableEntity, new() { return await AllTableEntities<T>(tableName, partitionKey); } async private Task<T[]> AllTableEntities<T>(string tableName, string partitionKey) where T : ITableEntity, new() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "people" table. CloudTable table = tableClient.GetTableReference(tableName); TableQuery<T> query = String.IsNullOrWhiteSpace(partitionKey) ? new TableQuery<T>() : new TableQuery<T>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey)); List<T> entities = new List<T>(); foreach (var entity in await ExecuteQueryAsync<T>(table, query)) { entities.Add(entity/*.ConvertTo<T>()*/); } return entities.ToArray(); } async private Task<List<T>> ExecuteQueryAsync<T>(CloudTable table, TableQuery<T> query) where T : ITableEntity, new() { List<T> results = new List<T>(); TableQuerySegment<T> currentSegment = null; if (query.TakeCount > 0) { // Damit Top Query funktioniert while (results.Count < query.TakeCount && (currentSegment == null || currentSegment.ContinuationToken != null)) { currentSegment = await table.ExecuteQuerySegmentedAsync(query, currentSegment != null ? currentSegment.ContinuationToken : null); results.AddRange(currentSegment.Results); } } else { TableContinuationToken continuationToken = null; do { currentSegment = await table.ExecuteQuerySegmentedAsync(query, continuationToken); continuationToken = currentSegment.ContinuationToken; results.AddRange(currentSegment.Results); } while (continuationToken != null); } return results; } #endregion #region Helper private string QueryComp(QueryComparer[] whereComparer, int index) { if (whereComparer == null) { return QueryComparisons.Equal; } switch (whereComparer[index]) { case QueryComparer.Equal: return QueryComparisons.Equal; case QueryComparer.GreaterThan: return QueryComparisons.GreaterThan; case QueryComparer.GreaterThanOrEqual: return QueryComparisons.GreaterThanOrEqual; case QueryComparer.LessThan: return QueryComparisons.LessThan; case QueryComparer.LessThanOrEqual: return QueryComparisons.LessThanOrEqual; case QueryComparer.NotEqual: return QueryComparisons.NotEqual; } return QueryComparisons.Equal; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kingdee.BOS.Core.DynamicForm.PlugIn.Args { public static class EndOperationTransactionArgsExtension { public static EndSetStatusTransactionArgs AsEndSetStatusTransactionArgs(this EndOperationTransactionArgs args) { return args.AsType<EndSetStatusTransactionArgs>(); } } }
namespace EPI.Sorting { /// <summary> /// Write a function that takes two input sorted arrays and updates the first to the combined /// entries of the two arrays in sorted order. /// Assume the first array has enough empty entries at the end to hold the final result /// </summary> /// <example> /// {5,13,17, , , , , } and {3,7,11,19} updates the first array to {3,5,7,11,13,19, } /// </example> public static class InPlaceMergeSort { public static void Sort(int?[] A, int?[] B) { // calculate non-empty entries in A // empty entries are denoted as null int i = 0; while (A[i] != null) { i++; } int j = B.Length; int writeIndex = i + j - 1; --i; --j; while (i >= 0 && j >= 0) { if(A[i] > B[j]) { A[writeIndex--] = A[i--]; } else { A[writeIndex--] = B[j--]; } } // if A has remaining items, they are already sorted in the right place // add any remaining items in B while (j >= 0) { A[writeIndex--] = B[j--]; } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IdentityServer3.Core.Models; using IdentityServer3.Core.Services; using IdentityServer3.Shaolinq.DataModel.Interfaces; using IdentityServer3.Shaolinq.Mapping; namespace IdentityServer3.Shaolinq.Stores { public class ScopeStore : IScopeStore { private readonly IIdentityServerScopeDataAccessModel dataModel; public ScopeStore(IIdentityServerScopeDataAccessModel dataModel) { this.dataModel = dataModel; } public Task<IEnumerable<Scope>> FindScopesAsync(IEnumerable<string> scopeNames) { var query = from scope in dataModel.Scopes join sc in dataModel.ScopeClaims on scope equals sc.Scope into g from scopeClaim in g.DefaultIfEmpty() select new { Scope = scope, ScopeClaim = scopeClaim }; if (scopeNames != null && scopeNames.Any()) { query = query.Where(x => scopeNames.Contains(x.Scope.Name)); } var scopes = query.ToLookup(x => x.Scope, x => x.ScopeClaim); var model = scopes.Select(x => x.ToModel()); return Task.FromResult(model); } public Task<IEnumerable<Scope>> GetScopesAsync(bool publicOnly = true) { var query = from scope in dataModel.Scopes join scopeClaim in dataModel.ScopeClaims.DefaultIfEmpty() on scope equals scopeClaim.Scope select new { Scope = scope, ScopeClaim = scopeClaim }; if (publicOnly) { query = query.Where(x => x.Scope.ShowInDiscoveryDocument); } var scopes = query.ToLookup(x => x.Scope, x => x.ScopeClaim); var model = scopes.Select(x => x.ToModel()); return Task.FromResult(model); } } }
using RTBid.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RTBid.Core.Domain { public class Category { public int CategoryId { get; set; } public string CategoryName { get; set; } public string CategoryDescription { get; set; } public string IconName { get; set; } public DateTime CreatedDate { get; set; } public virtual ICollection<Product> Products { get; set; } public Category() { } public Category(CategoryModel model) { this.Update(model); this.CreatedDate = DateTime.Now; } public void Update(CategoryModel model) { CategoryId = model.CategoryId; CategoryName = model.CategoryName; CategoryDescription = model.CategoryDescription; } } }
using UnityEngine; using System.Collections; using UnityStandardAssets.ImageEffects; public class AllScripts : MonoBehaviour { public CameraWobble cameraWobble; public SlowMoScript slowMoScript; public FishEyeScript fishEyeScript; public Camera mainCam; public GameManager gameManager; public CharacterController characterController; public Rigidbody firstPersonRigid; public Bloom bloom; public CameraFade cameraFade; public AudioSource mainMusic, alarm; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }