text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2017 { public class Problem06 : AdventOfCodeBase { public override string ProblemName { get { return "Advent of Code 2017: 6"; } } public override string GetAnswer() { return Answer1(Input()); } public override string GetAnswer2() { return Answer2(Input()); } private string Answer1(List<string> input) { var banks = input[0].Split('\t').Select(x => Convert.ToInt32(x)).ToList(); HashSet<string> hash = new HashSet<string>(); int count = 0; do { int highest = FindHighestCount(banks); int spread = banks[highest]; int add = spread / banks.Count; int remainder = spread % banks.Count; int next = highest; banks[highest] = 0; for (int spreadIndex = 1; spreadIndex <= banks.Count; spreadIndex++) { next = (next + 1) % banks.Count; banks[next] += add; if (remainder > 0) { banks[next]++; remainder = Math.Max(remainder - 1, 0); } } count++; string key = string.Join(":", banks); if (hash.Contains(key)) { return count.ToString(); } else { hash.Add(key); } } while (true); } private string Answer2(List<string> input) { var banks = input[0].Split('\t').Select(x => Convert.ToInt32(x)).ToList(); Dictionary<string, int> hash = new Dictionary<string, int>(); int count = 0; do { int highest = FindHighestCount(banks); int spread = banks[highest]; int add = spread / banks.Count; int remainder = spread % banks.Count; int next = highest; banks[highest] = 0; for (int spreadIndex = 1; spreadIndex <= banks.Count; spreadIndex++) { next = (next + 1) % banks.Count; banks[next] += add; if (remainder > 0) { banks[next]++; remainder = Math.Max(remainder - 1, 0); } } count++; string key = string.Join(":", banks); if (hash.ContainsKey(key)) { return (count - hash[key]).ToString(); } else { hash.Add(key, count); } } while (true); } private int FindHighestCount(List<int> banks) { int highestIndex = 0; int highestValue = int.MinValue; for (int index = 0; index < banks.Count; index++) { if (banks[index] > highestValue) { highestValue = banks[index]; highestIndex = index; } } return highestIndex; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using Fireasy.Common.Extensions; using System.Collections; #if !NET35 using System.Dynamic; using Fireasy.Common.Dynamic; #endif using System.Drawing; using System.Data; using Fireasy.Common.Reflection; using System.Collections.ObjectModel; using System.Reflection; namespace Fireasy.Common.Serialization { internal sealed class XmlDeserialize : DeserializeBase { private readonly XmlSerializeOption option; private readonly XmlSerializer serializer; private XmlReader xmlReader; private bool isDisposed; private static MethodInfo mthToArray = typeof(Enumerable).GetMethod(nameof(Enumerable.ToArray), BindingFlags.Public | BindingFlags.Static); internal XmlDeserialize(XmlSerializer serializer, XmlReader reader, XmlSerializeOption option) : base(option) { this.serializer = serializer; xmlReader = reader; this.option = option; } internal T Deserialize<T>() { return (T)Deserialize(typeof(T)); } internal object Deserialize(Type type) { while (xmlReader.NodeType != XmlNodeType.Element && xmlReader.Read()) ; object value = null; if (WithSerializable(type, ref value)) { return value; } if (WithConverter(type, ref value)) { return value; } #if !SILVERLIGHT if (type == typeof(Color)) { //return DeserializeColor(); } #endif if (type == typeof(Type)) { //return DeserializeType(); } #if !NET35 if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type) || type == typeof(object)) { return DeserializeDynamicObject(type); } #endif if (typeof(IDictionary).IsAssignableFrom(type) && type != typeof(string)) { //return DeserializeDictionary(type); } if (typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string)) { return DeserializeList(type); } #if !SILVERLIGHT if (type == typeof(DataSet) || type == typeof(DataTable) || type == typeof(DataRow)) { return new System.Xml.Serialization.XmlSerializer(type).Deserialize(xmlReader); } #endif return DeserializeValue(type); } private bool WithSerializable(Type type, ref object value) { if (typeof(ITextSerializable).IsAssignableFrom(type)) { var obj = type.New<ITextSerializable>(); var rawValue = xmlReader.ReadInnerXml(); if (rawValue != null) { obj.Deserialize(serializer, rawValue); value = obj; } return true; } return false; } private bool WithConverter(Type type, ref object value) { XmlConverter converter; TextConverterAttribute attr; if ((attr = type.GetCustomAttributes<TextConverterAttribute>().FirstOrDefault()) != null && typeof(XmlConverter).IsAssignableFrom(attr.ConverterType)) { converter = attr.ConverterType.New<XmlConverter>(); } else { converter = option.Converters.GetReadableConverter(type, new[] { typeof(XmlConverter) }) as XmlConverter; } if (converter == null || !converter.CanRead) { return false; } value = converter.ReadXml(serializer, xmlReader, type); return true; } private object DeserializeValue(Type type) { var stype = type.GetNonNullableType(); var typeCode = Type.GetTypeCode(stype); if (typeCode == TypeCode.Object) { return ParseObject(type); } if (type.IsNullableType() && xmlReader.HasValue) { return null; } var beStartEle = false; if ((beStartEle = (xmlReader.NodeType == XmlNodeType.Element))) { xmlReader.Read(); } var value = xmlReader.ReadContentAsString(); if (beStartEle) { while (xmlReader.NodeType != XmlNodeType.EndElement && xmlReader.Read()) ; } return value.ToType(type); } #if !NET35 private object DeserializeDynamicObject(Type type) { var dynamicObject = type == typeof(object) ? new ExpandoObject() : type.New<IDictionary<string, object>>(); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { var value = Deserialize(typeof(string)); if (value != null) { dynamicObject.Add(xmlReader.Name, value); } } else if (xmlReader.NodeType == XmlNodeType.EndElement) { break; } } return dynamicObject; } #endif private object DeserializeList(Type listType) { IList container = null; Type elementType = null; #if !NET40 && !NET35 var isReadonly = listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>); #else var isReadonly = listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(ReadOnlyCollection<>); #endif CreateListContainer(listType, out elementType, out container); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == elementType.Name) { container.Add(Deserialize(elementType)); } } if (listType.IsArray) { var invoker = ReflectionCache.GetInvoker(mthToArray.MakeGenericMethod(elementType)); return invoker.Invoke(null, container); } if (isReadonly) { return listType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new[] { container.GetType() }, null).Invoke(new object[] { container }); } return container; } private object ParseObject(Type type) { return type.IsAnonymousType() ? ParseAnonymousObject(type) : ParseGeneralObject(type); } private object ParseGeneralObject(Type type) { if (xmlReader.NodeType == XmlNodeType.None) { return null; } var instance = type.New(); var cache = GetAccessorCache(instance.GetType()); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element && cache.TryGetValue(xmlReader.Name, out PropertyAccessor accessor)) { var value = Deserialize(accessor.PropertyInfo.PropertyType); if (value != null) { accessor.SetValue(instance, value); } } else if (xmlReader.NodeType == XmlNodeType.EndElement) { break; } } return instance; } private object ParseAnonymousObject(Type type) { return null; } /// <summary> /// 释放对象所占用的非托管和托管资源。 /// </summary> /// <param name="disposing">为 true 则释放托管资源和非托管资源;为 false 则仅释放非托管资源。</param> private void Dispose(bool disposing) { if (isDisposed) { return; } if (disposing) { xmlReader.TryDispose(); xmlReader = null; } isDisposed = true; } } }
using System; using System.Linq; using System.Xml; using System.Reflection; using System.Collections.Generic; namespace Logs { [AttributeUsage(AttributeTargets.Field)] public class DescripProp : Attribute { public string Description; private readonly string name; public DescripProp(string name) { this.name = name; } } public struct InfoLogItem { [DescripProp("время создания файла для распознавания")] public string OriginalFileDateTime; //время создания файла для распознавания //WorkClass.newFile public string BeginRecognitionDateTime; //время начала распознавания //WorkClass.newFile public string EndRecognitionDateTime; //время окончания распознавания //WorkClass.newFile public string MoveFileDateTime; //время копирования файла //MainForm.Button3Click public string RecognitionDesignation; //обозначение данное автоматически //MainForm.AddObjectToObjectList public string RecognitionName; //наименование чертежа данное автоматически //MainForm.AddObjectToObjectList public string RecognitionList; //лист чертежа данный автоматически //MainForm.AddObjectToObjectList public string EndDesignation; //конечное обозначение перед перемещением //MainForm.Button3Click public string EndName; //конечное наименование перед перемещением //MainForm.Button3Click public string EndList; //конечный лист чертежа перед перемещением //MainForm.Button3Click public string RecoveryName; //восстановленное наименование файла(для многостр. документов) //MainForm.AddObjectToObjectList public string OriginalFilename; //старое имя перемещаемого файла //WorkClass.newFile public string EndFilename; //новое имя перемещаемого файла //MainForm.Button3Click public string ErrorRecognition; //если поле присутствует и заполнено то ошибка //WorkClass.newFile public string Ramka; //картинка в hex кодах строки //WorkClass.newFile } public class InfoLog { public string sDate; public string sTime; public string SourcePath; public string EndPath; public List<InfoLogItem> Items; } /// <summary> /// Логирование добавляемых файлов /// </summary> public static class InfoLogMain { public static bool WriteInfo(string XMLFilename, InfoLog info) { try { var writer = new System.Xml.Serialization.XmlSerializer(typeof(InfoLog)); var xmlfile = new System.IO.StreamWriter(XMLFilename); writer.Serialize(xmlfile, info); xmlfile.Close(); } catch (Exception) { return false; } return true; } public static InfoLog ReadInfo(string XMLFilename) { InfoLog info = null; try { var reader = new System.Xml.Serialization.XmlSerializer(typeof(InfoLog)); var xmlfile = new System.IO.StreamReader(XMLFilename); info = (InfoLog)reader.Deserialize(xmlfile); xmlfile.Close(); } catch (Exception) { return null; } return info; } public static string GetNewFilename() { return DateTime.Now.ToString("Lo\\g(yyyy-MM-dd)(HH-mm-ss).x\\ml"); } } /*public class InfoLogMain : IDisposable { private readonly XmlWriter file; /// <summary> /// Логирование /// </summary> /// <param name="LogFileName">Имя файла лога</param> /// <param name="SourcePath">Параметр для записи в root лога, папка, откуда перемещаются файлы</param> /// <param name="EndPath">Параметр для записи в root лога, папка, куда перемещаются файлы</param> public InfoLog(string LogFileName, string SourcePath, string EndPath) { var settings = new XmlWriterSettings(); //settings.OmitXmlDeclaration = true; //опуск XML-объявление settings.Indent= true; //отступ для элементов file = XmlWriter.Create(LogFileName, settings); file.WriteStartElement("Logs"); file.WriteAttributeString("Date", DateTime.Now.ToString("d")); file.WriteAttributeString("Time", DateTime.Now.ToString("T")); file.WriteAttributeString("SourcePath", SourcePath); file.WriteAttributeString("EndPath", EndPath); } public void WriteElement(InfoLogItem EL) { file.WriteStartElement("Element"); try { Type t = typeof(InfoLogItem); foreach (var element in t.GetFields(BindingFlags.Public | BindingFlags.Instance)) { var e = element.GetValue(EL); if (e != null) if (e is string) file.WriteElementString(element.Name, e.ToString()); } } finally { file.WriteEndElement(); file.Flush(); } } public void Dispose() //потому что деструктор класса вызывается хаотическит, т.е. file закрывается раньше вызова деструктора { file.WriteEndElement(); file.Close(); } public static string GetNewFilename() { return DateTime.Now.ToString("Lo\\g(yyyy-MM-dd)(HH-mm-ss).x\\ml"); } }*/ }
using Rocket.API.Collections; using Rocket.Core.Logging; using Rocket.Core.Plugins; using Rocket.Unturned.Chat; using SDG.Unturned; using System; namespace MassAirdrop { public class PluginMassAirdrop : RocketPlugin<MassAirdropConfiguration> { public static PluginMassAirdrop Instance; private DateTime? lastdrop = null; private DateTime? started = null; private bool dropNow = false; private int dropped; void FixedUpdate() { if (dropNow == true) { if ((DateTime.Now - started.Value).TotalSeconds < Configuration.Instance.Duration) { LevelManager.airdropFrequency = 0; } else { dropNow = false; Logger.Log(Translate("massdrop_over")); } } else { CheckMassDrop(); } } protected override void Load() { Instance = this; Logger.Log("Mass Airdrop Loaded"); } protected override void Unload() { Logger.Log("Mass Airdrop Unloaded"); } public override TranslationList DefaultTranslations { get { return new TranslationList(){ {"massdrop_comming","Mass Airdrop Incomming!"}, {"massdrop_over","Mass Airdrop Over!"}, }; } } public void MassDrop() { UnturnedChat.Say(Translate("massdrop_comming"), UnityEngine.Color.magenta); Logger.Log(Translate("massdrop_comming")); started = DateTime.Now; dropNow = true; } private void CheckMassDrop() { try { if (State == Rocket.API.PluginState.Loaded && (lastdrop == null || ((DateTime.Now - lastdrop.Value).TotalSeconds > Configuration.Instance.Interval))) { lastdrop = DateTime.Now; MassDrop(); } } catch (Exception ex) { Logger.LogException(ex); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExplosionParticlesDestroy : MonoBehaviour { [SerializeField] float timeToDestroy = 1f; public IEnumerator ExplosionParticlesVFXDestroyer() { yield return new WaitForSeconds(timeToDestroy); Destroy(gameObject); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace RestApiWithDapper.Models { public class Employee { [Key] public int EmployeeId { get; set; } [Required] public string FirstName { get; set; } public string LastName { get; set; } public string Department { get; set; } [Required] public string JobTitle { get; set; } [Required] public string PhoneExtension { get; set; } [Required] public string Salary { get; set; } public string Bonus { get; set; } } }
using LagoVista.Core.Attributes; using LagoVista.UserAdmin.Models; using LagoVista.UserAdmin.Models.Resources; using LagoVista.UserAdmin.Resources; namespace LagoVista.UserAdmin.ViewModels.Organization { [EntityDescription(Domains.OrganizationViewModels, UserAdminResources.Names.InviteUserVM_Title, UserAdminResources.Names.InviteUserVM_Help, UserAdminResources.Names.InviteUserVM_Description, EntityDescriptionAttribute.EntityTypes.ViewModel, typeof(UserAdminResources))] public class InviteUserViewModel { [FormField(LabelResource: UserAdminResources.Names.Common_EmailAddress, FieldType: FieldTypes.Email, IsRequired: true, ResourceType: typeof(UserAdminResources))] public string Email { get; set; } [FormField(LabelResource: UserAdminResources.Names.InviteUser_Name, IsRequired: true, ResourceType: typeof(UserAdminResources))] public string Name { get; set; } [FormField(LabelResource: UserAdminResources.Names.InviteUser_Greeting_Label, FieldType: FieldTypes.MultiLineText, IsRequired: true, ResourceType: typeof(UserAdminResources))] public string Message { get; set; } } }
using System.Linq; using StarBastardCore.Website.Code.Game.Gameworld.Geography.Buildings; namespace StarBastardCore.Website.Code.Game.Gameplay.Actions { public class Build : GameActionBase { public string DestinationPlanetId { get { return Item<string>("DestinationPlanetId"); } set { Parameters["DestinationPlanetId"] = value; } } public string BuildingType { get { return Item<string>("BuildingType"); } set { Parameters["BuildingType"] = value; } } public Build() { } public override void Commit(GameContext entireContext) { var system = entireContext.Systems.Single(x => x.SystemNumber == DestinationPlanetId); if (!system.CanBuild) { return; } system.City.Add(new Farm()); } public Build(GameActionBase action) { Parameters = action.Parameters; } } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI.WebControls; using System.Net; using CIPMSBC; public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // There are currently two places that could route to Camper Holding Page. // 1. When the CIPM is shut-down, typically from August to September // 2. When CIPMS is open for registration, typically in mid-October // The code below fulfills the scenario #1 if (ConfigurationManager.AppSettings["CamperHoldingPageSwithYesNo"] == "Yes") { var clientIp = Request.ServerVariables["REMOTE_ADDR"]; bool allowForTesting = ConfigurationManager.AppSettings["TestingModeIPs"].Split(',').Any(x => x == clientIp); if (!allowForTesting) Response.Redirect(ConfigurationManager.AppSettings["CamperHoldingPageUrl"]); } //Just incase the user did not hit the logout button. if (!IsPostBack) { // if it's localhost (developer machine) if (Request.Url.Host == "localhost") { lblUAT.Visible = true; lblUAT.Text = "This is developer's local machine"; Email.Text = "wenchenglai@gmail.com"; Password.Text = "wayne"; Password.TextMode = TextBoxMode.SingleLine; //txtEmail.Text = "scharfn@gmail.com"; //txtPwd.Text = "fufu4u"; //txtEmail.Text = "ikl1232003@yahoo.com"; //txtPwd.Text = "myaX*6"; } // compare requester (client)'s IP with UATIP else if (Dns.GetHostAddresses(Request.Url.Host)[0].ToString() == ConfigurationManager.AppSettings["UATIP"]) { lblUAT.Visible = true; lblUAT.Text = "This is UAT"; } Session.Abandon(); if (Request.QueryString["RedirectURL"] != null) if (Request.QueryString["RedirectURL"].Contains("TrackMyStatus")) { hdnRedirectURL.Value = Request.QueryString["RedirectURL"].ToString(); } if (Request.QueryString["errorMsg"] != null) { lblErr.Text = "UserID already exists, please use the returning user login below."; } else hdnRedirectURL.Value = string.Empty; FormsAuthentication.SignOut(); } } protected void btnSubmit_Click(object sender, EventArgs e) { string strEmail = Email.Text.Trim(); string isTestMode = ConfigurationManager.AppSettings["TestingMode"]; if (isTestMode == "Yes") { if (strEmail != "wenchenglai@gmail.com" && strEmail != "staci@jewishcamp.org" && strEmail != "rebeccak@jewishcamp.org" && strEmail != "s.myerklein@gmail.com" && strEmail != "Tamar@jewishcamp.org") { lblErr.Text = "The registration system is closed for testing until 11 AM EST on Tuesday, Sept 26th, 2016."; return; } } Administration objAdmin = new Administration(); string strPwd = Password.Text; DataSet ds; bool blnIsUsrAuthorized = objAdmin.ValidateCamper(strEmail, strPwd, out ds); if (blnIsUsrAuthorized == true) { lblErr.Text = ""; Session["UsrID"] = null; Session["CamperLoginID"] = ds.Tables[0].Rows[0]["CamperId"].ToString(); //Set a cookie for authenticated user FormsAuthenticationTicket ticket = new FormsAuthenticationTicket((string)Session["CamperLoginID"], true, 5000); String encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); authCookie.Expires = ticket.Expiration; Response.Cookies.Add(authCookie); if (hdnRedirectURL.Value.Equals(string.Empty)) Response.Redirect("~/CamperOptions.aspx"); else Response.Redirect(hdnRedirectURL.Value); } else lblErr.Text = "Invalid UserID or Password. Please check and re-enter again."; } protected void btnForgot_Click(object sender, EventArgs e) { Administration objAdmin = new Administration(); string strToEmail = Email.Text.Trim(); string FromEmail = ConfigurationManager.AppSettings["EmailFrom"].ToString(); string ReplyAddress = ConfigurationManager.AppSettings["ReplyTo"].ToString(); string FromName = ConfigurationManager.AppSettings["FromName"].ToString(); string Subject = ConfigurationManager.AppSettings["Subject"].ToString(); string sBody; DataSet CamperCredentials; DataRow drEmail; CamperCredentials = objAdmin.GetCamperCredentials(strToEmail); if (CamperCredentials.Tables[0].Rows.Count > 0) { drEmail = CamperCredentials.Tables[0].Rows[0]; sBody = "Your Password is: " + drEmail["Password"].ToString(); } else { sBody = "UserId not found"; } cService.SendMail(strToEmail, null, FromName, FromEmail, ReplyAddress, Subject, sBody); lblErr.Text = "Password sent to your email address"; } protected void btnSubmit1_Click(object sender, EventArgs e) { string strEmail = txtEmail1.Text.Trim(); //string isTestMode = ConfigurationManager.AppSettings["TestingMode"]; //if (isTestMode == "Yes") //{ // if (strEmail != "wenchenglai@gmail.com" && strEmail != "staci@jewishcamp.org" && strEmail != "rebeccak@jewishcamp.org") // { // lblErr.Text = "The registration system is closed for testing until 11 AM EST on Tuesday, Oct 20th, 2015."; // return; // } //} Administration objAdmin = new Administration(); string strPwd = txtPwd1.Text.Trim(); string CamperLoginID; int retValue; DataSet CamperCredentials; CamperCredentials = objAdmin.GetCamperCredentials(strEmail); if (CamperCredentials.Tables[0].Rows.Count > 0) { //lblErr.Text = "UserID already exists, please use the returning user login below."; Response.Redirect("~/Home.aspx?errorMsg=t#error"); } else { retValue = objAdmin.UserRegistration(strEmail, strPwd, out CamperLoginID); Session["CamperLoginID"] = CamperLoginID; Session["UsrID"] = null; // Redirect to the basic camper info page string strRedirURL; strRedirURL = ConfigurationManager.AppSettings["CamperBasicInfo"].ToString(); Server.Transfer(strRedirURL); } } }
// // -------------------------------------------------------------------------- // Gurux Ltd // // // // Filename: $HeadURL: svn://utopia/projects/GXDeviceEditor/Development/AddIns/DLMS/GXManufacturerDevice.cs $ // // Version: $Revision: 870 $, // $Date: 2009-09-29 17:21:48 +0300 (ti, 29 syys 2009) $ // $Author: airija $ // // Copyright (c) Gurux Ltd // //--------------------------------------------------------------------------- // // DESCRIPTION // // This file is a part of Gurux Device Framework. // // Gurux Device Framework is Open Source software; you can redistribute it // and/or modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; version 2 of the License. // Gurux Device Framework 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 General Public License for more details. // // This code is licensed under the GNU General Public License v2. // Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt //--------------------------------------------------------------------------- using System; namespace DLMS { /// <summary> /// Defines the DLMS manufacturer device. /// </summary> internal class GXManufacturerDevice { public int ManufacturerType = 0; string m_Name = string.Empty; int m_ClientIDByteSize = 0; int m_ServerIDByteSize = 0; object m_ClientID = null; object m_ServerID = null; /// <summary> /// Initializes a new instance of the GXManufacturerDevice class. /// </summary> public GXManufacturerDevice(string name, object clientID, object serverID, int manufacturerType) { ManufacturerType = manufacturerType; m_Name = name; m_ClientID = clientID; m_ServerID = serverID; if (clientID is byte) { m_ClientIDByteSize = 1; } else if (clientID is UInt16) { m_ClientIDByteSize = 2; } else if (clientID is UInt32) { m_ClientIDByteSize = 4; } if (serverID is byte) { m_ServerIDByteSize = 1; } else if (serverID is UInt16) { m_ServerIDByteSize = 2; } else if (serverID is UInt32) { m_ServerIDByteSize = 4; } } public string ManufacturerDeviceName { get { return m_Name; } } /// <summary> /// Client identifier /// </summary> public object ClientID { get { return m_ClientID; } } /// <summary> /// The size of the client identifier in bytes. /// </summary> public int ClientIDByteSize { get { return m_ClientIDByteSize; } } /// <summary> /// Server identifier /// </summary> public object ServerID { get { return m_ServerID; } } /// <summary> /// The size of the server identifier in bytes. /// </summary> public int ServerIDByteSize { get { return m_ServerIDByteSize; } } /// <summary> /// Returns a String representation of the value of this instance of the GXManufacturerDevice class. /// </summary> /// <returns>The name of the device.</returns> public override string ToString() { return m_Name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using IdomOffice.Interface.BackOffice.MasterData; using IdomOffice.Interface.BackOffice.PriceLists; namespace V50_IDOMBackOffice.AspxArea.Helper { public class DataManager { public static List<Data> GetPets() { List<Data> pets = new List<Data>(); Data pet1 = new Data("0", "nicht erlaubt"); Data pet2 = new Data("6", "erlaubt bis 6 KG"); Data pet3 = new Data("30", "erlaubt bis 30 KG"); Data pet4 = new Data("99", "erlaubt"); pets.Add(pet1); pets.Add(pet2); pets.Add(pet3); pets.Add(pet4); return pets; } public static List<Data> GetTerraceTypes() { List<Data> types = new List<Data>(); Data data1 = new Data("1", "Typ 1"); Data data2 = new Data("2", "Typ 2"); types.Add(data1); types.Add(data2); return types; } public static List<Data> GetPositions() { List<Data> positions = new List<Data>(); Data position1 = new Data("1", "Standort 1"); Data position2 = new Data("2", "Standort 2"); positions.Add(position1); positions.Add(position2); return positions; } public static List<Data> GetDistances() { List<Data> distances = new List<Data>(); Data distance1 = new Data("1", "Lage 1"); Data distance2 = new Data("2", "Lage 2"); distances.Add(distance1); distances.Add(distance2); return distances; } public static List<Data> GetLanguages() { List<Data> languages = new List<Data>(); Data language1 = new Data("1", "deutsch"); Data language2 = new Data("2", "englisch"); languages.Add(language1); languages.Add(language2); return languages; } public static List<Data> GetRetailPrices() { List<Data> prices = new List<Data>(); Data price1 = new Data(Convert.ToInt32(PriceListType.RetailPrice).ToString(), "RetailPriceForEndUser"); Data price2 = new Data(Convert.ToInt32(PriceListType.WholesalePrices).ToString(), "RetailPriceForPartner"); prices.Add(price1); prices.Add(price2); return prices; } public static List<Data> GetReceiverTypes() { List<Data> types = new List<Data>(); Data type1 = new Data("1", "TravelApplicantPayment"); Data type2 = new Data("2", "ProviderPayment"); types.Add(type1); types.Add(type2); return types; } public static List<Data> GetPaymentTypes() { List<Data> payments = new List<Data>(); Data payment1 = new Data("1", "Bank1"); Data payment2 = new Data("2", "Bank2"); Data payment3 = new Data("3", "CreditCard"); payments.Add(payment1); payments.Add(payment2); payments.Add(payment3); return payments; } public static object GetCheckBoxIndex(string name) { int index = -1; List<int> indexes = new List<int>(); if (name == "Monday") index = 0; else if (name == "Tuesday") index = 1; else if (name == "Wednesday") index = 2; else if (name == "Thursday") index = 3; else if (name == "Friday") index = 4; else if (name == "Saturday") index = 5; else if (name == "Sunday") index = 6; else { indexes.AddRange(new int[] { 0, 1, 2, 3, 4, 5, 6 }); } if (index == -1) return indexes; else return index; } } }
using Controller.ExaminationAndPatientCard; using Model.Secretary; using Model.Users; using ProjekatZdravoKorporacija.ModelDTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; 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; namespace ProjekatZdravoKorporacija.View { /// <summary> /// Interaction logic for DetailsAboutPatient.xaml /// </summary> public partial class DetailsAboutPatient : Page { PatientCardController patientCardController = new PatientCardController(); public DetailsAboutPatient(Object o) { InitializeComponent(); Patient patient = (Patient)o; InitializeWindowInformation(patient); } private void InitializeWindowInformation(Patient patient) { txtName.Text = patient.Name; txtSurname.Text = patient.Surname; txtJmbg.Text = patient.Jmbg; txtDateOfBirth.Text = patient.DateOfBirth.ToShortDateString(); txtGender.Text = patient.Gender.ToString(); txtStreet.Text = patient.HomeAddress; if (patient.City.ZipCode == 0) { txtCity.Text = ""; } else { txtCity.Text = patient.City.Name + " " + patient.City.ZipCode; } txtEmail.Text = patient.Email; txtPhone.Text = patient.Phone; txtUsername.Text = patient.Username; pbPassword.Password = patient.Password; PatientCard patientCard = patientCardController.ViewPatientCard(patient.Jmbg); txtBloodType.Text = patientCard.BloodType.ToString(); txtRh.Text = patientCard.RhFactor.ToString(); txtAllergy.Text = patientCard.Alergies; if (patientCard.HasInsurance) { txtHasOccurance.Text = "Da"; } else { txtHasOccurance.Text = "Ne"; } txtLbo.Text = patientCard.Lbo; string[] parts = patientCard.MedicalHistory.Split(';'); string dates = ""; string desc = ""; string therapy = ""; if (!patientCard.MedicalHistory.Equals("") || !patientCard.MedicalHistory.Equals(";")) { for (int i = 0; i < parts.Length - 1; i++) { string[] paramParts = parts[i].Split(':'); dates += paramParts[0] + "\n"; desc += paramParts[1] + "\n"; therapy += paramParts[2] + "\n"; } txtDate.Text = dates; txtDesc.Text = desc; txtTherapy.Text = therapy; } } private void okBtn_Click(object sender, RoutedEventArgs e) { foreach (Window window in Application.Current.Windows) { if (window.GetType() == typeof(MainWindow)) { (window as MainWindow).Main.Content = new PatientView(); } } } } }
using System; using ServiceDesk.Infrastructure; using ServiceDesk.Ticketing.Domain.TicketAggregate; namespace ServiceDesk.Ticketing.Domain.UserAggregate { public class User : AggregateRoot { internal UserState State { get; set; } public Guid Id { get { return State.Id; } } public User(string SID, string loginName, string displayName, string departament, string location, string email) { State = new UserState { Id = SequencialGuidGenerator.NewSequentialGuid(), SID = SID, LoginName = loginName, DisplayName = displayName, Department = departament, Location = location, Email = email }; } public Requestor CreateRequestorSnapShot() { return new Requestor(State.DisplayName,State.Department, State.Location); } internal User(UserState state) { State = state; } } }
using System.Collections.Generic; namespace CustomersExample { public class Customer { public string Name { get; set; } public string Family { get; set; } } public class CustomerNameComparer : IEqualityComparer<Customer> { public bool Equals(Customer customer1, Customer customer2) { return customer1.Name == customer2.Name; } public int GetHashCode([DisallowNull] Customer customer) { return new { customer.Name}.GetHashCode(); } } public class CustomerFamilyComparer : IEqualityComparer<Customer> { public bool Equals(Customer customer1, Customer customer2) { return customer1.Family == customer2.Family; } public int GetHashCode([DisallowNull] Customer customer) { return new { customer.Family }.GetHashCode(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; using System.IO; using System.Windows; using Google.Protobuf; using System.Drawing.Imaging; namespace RemoteClient { public partial class Server_Client : Form { public string Information = null; public bool connectCheck = false;//连接状态 private int heartNum = 0;//心跳计数 private object locker = new object();//线程锁 private Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public Server_Client() { InitializeComponent(); TextBox.CheckForIllegalCrossThreadCalls = false; richTextBox1.Multiline = true; //将Multiline属性设置为true,实现显示多行 richTextBox1.ScrollBars = RichTextBoxScrollBars.Vertical; richTextBox2.Multiline = true; //将Multiline属性设置为true,实现显示多行 richTextBox2.ScrollBars = RichTextBoxScrollBars.Vertical; textBox1.Text = "127.0.0.1"; textBox2.Text = "9999"; } [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")] private static extern bool BitBlt(//Win32 API的CreateDC, IntPtr hdcDest, // 目标 DC的句柄 int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, // 源DC的句柄 int nXSrc, int nYSrc, System.Int32 dwRop // 光栅的处理数值 ); private void Screen_Test() { while(true) { try { //获得当前屏幕的分辨率 long ImageLength = 0; Screen scr = Screen.PrimaryScreen; Rectangle rc = scr.Bounds; int iWidth = rc.Width; int iHeight = rc.Height; //创建一个和屏幕一样大的Bitmap Image MyImage = new Bitmap(iWidth, iHeight); //从一个继承自Image类的对象中创建Graphics对象 Graphics g = Graphics.FromImage(MyImage); //将屏幕的(0,0)坐标截图内容copy到画布的(0,0)位置,尺寸到校 new Size(iWidth, iHeight) //保存在MyImage中 g.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(iWidth, iHeight)); ///需要将信息组包发送,使得服务端能够正确接收每一个包,区分每一帧图像 ///以字符#123标识一帧的开始加上标识发送类型一共5字节 MemoryStream ms = new MemoryStream(); MyImage.Save(ms, ImageFormat.Jpeg);//保存到流ms中 byte[] arr = ImageToByteArray(MyImage); //发送图片信息 string length = arr.Length.ToString();//图片总长度 string str1 = string.Format("{0}-{1}", "dc", length); byte[] arr1 = Encoding.UTF8.GetBytes(str1); byte[] arrSend1 = new byte[arr1.Length + 1]; arrSend1[0] = 5;//发送图片信息 Buffer.BlockCopy(arr1, 0, arrSend1, 1, arr1.Length); ClientSocket.Send(arrSend1); Thread.Sleep(1000); //发送图片 int end = 1; bool vis = true; ms.Position = 0; while (end != 0) { if (vis) { byte[] arrPictureSend = new byte[1025]; arrPictureSend[0] = 4; end = ms.Read(arrPictureSend, 1, 1024);//end为0标识读取完毕 ClientSocket.Send(arrPictureSend, 0, 1024 + 1, SocketFlags.None); vis = false; } else { byte[] arrPictureSend = new byte[1024]; end = ms.Read(arrPictureSend, 0, 1024); ClientSocket.Send(arrPictureSend, 0, 1024, SocketFlags.None); } } Thread.Sleep(30000); } catch(Exception ex) { MessageBox.Show("截图发送异常!!!"); ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); break; } } } //ImageToByteArray函数 public byte[] ImageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); ///byte[] bytes = ms.GetBuffer();byte[] bytes=ms.ToArray(); 这两句都可以 ///MemoryStream的GetBuffer并不是得到这个流所存储的内容, ///而是返回这个流的基础字节数组,可能包括在扩充的时候一些没有使用到的字节 } private void Server_Client_Load(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e)//IP { } private void textBox2_TextChanged(object sender, EventArgs e)//PORT { } private void button2_Click(object sender, EventArgs e)//连接服务器 { int PORT = Convert.ToInt32(textBox2.Text); IPAddress IP = IPAddress.Parse((string)textBox1.Text); if(textBox1.Text==""||textBox2.Text=="") { MessageBox.Show("请先完成服务器配置!"); return; } try { ClientSocket.Connect(new IPEndPoint(IP, PORT)); if(ClientSocket.Connected)//成功连上服务器 { connectCheck = true; richTextBox1.Text += "连接服务器成功!\r\n"; //心跳包发送线程 /*Thread thread1 = new Thread(Heart); thread1.IsBackground = true; thread1.Start();//将此线程加入就绪队列,等待操作系统调度*/ //截图发送线程 Thread thread_test = new Thread(Screen_Test); thread_test.IsBackground = true; thread_test.Start(); //接收消息线程 Thread thread = new Thread(ReceiveMessage); thread.IsBackground = true; thread.Start(); } else { richTextBox1.Text += "连接服务器失败,请等下再试!"; connectCheck = false; } } catch (Exception ex) { connectCheck = false; richTextBox1.Text += "连接服务器失败!\r\n"; return; } } private void ReceiveMessage() { long TotalLength = 0; //如果位while(true),当窗体关闭之后还会有线程一直在跑,这样服务端就会认为该客户端没断线 while (this.Visible) { byte[] result = new byte[1024 * 1024 * 10]; int ReceiveLength = 0; try { ReceiveLength = ClientSocket.Receive(result); if (result[0] == 0)//表示接收到的是消息 { try { richTextBox1.Text += "接收服务器消息:\r\n"; string str = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1); richTextBox1.Text += str + "\r\n"; } catch (Exception ex) { richTextBox1.Text += "接收服务器消息失败!\r\n"; ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); break; } } if(result[0]==6)//接收到监控端发送来的参数信息 { string Information = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1); Socket_Client sc = new Socket_Client(); sc.Parameter = Information; richTextBox1.Text += "接收修改参数:" + Information + "\r\n"; Status sta = new Status(); if (Information != null) { if (Information[0] == '1') { sta.flag11 = true; sta.pictureBox1.Image = Properties.Resources.led_O; } if (Information[1] == '1') { sta.flag22 = true; sta.pictureBox2.Image = Properties.Resources.led_O; } if (Information[2] == '1') { sta.flag33 = true; sta.pictureBox3.Image = Properties.Resources.led_O; } if (Information[3] == '1') { sta.flag44 = true; sta.pictureBox4.Image = Properties.Resources.led_O; } if (Information[4] == '1') { sta.flag55 = true; sta.pictureBox5.Image = Properties.Resources.led_O; } if (Information[5] == '1') { sta.flag66 = true; sta.pictureBox6.Image = Properties.Resources.led_O; } if (Information[6] == '1') { sta.flag77 = true; sta.pictureBox7.Image = Properties.Resources.led_O; } if (Information[7] == '1') { sta.flag88 = true; sta.pictureBox8.Image = Properties.Resources.led_O; } } //sta.StartPosition = FormStartPosition.CenterScreen; //sta.Show(); } if(result[0]==3)//接收到服务端返回的认证包 { richTextBox2.Text += DateTime.Now+"接受服务器认证包:"; string str = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1); richTextBox2.Text += str + "\r\n"; heartNum = 0;//收到认证包 } if(heartNum>6) { connectCheck = false; MessageBox.Show("服务器可能已经挂掉!"); ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); } if (result[0] == 2) { string fileNameWithLength = Encoding.UTF8.GetString(result, 1, ReceiveLength - 1); string str1 = fileNameWithLength.Split('-').First(); TotalLength = Convert.ToInt64(fileNameWithLength.Split('-').Last()); richTextBox1.Text += "接收服务器后缀名为:" + str1 + "的文件" + "\r\n"; } if (result[0] == 1)//表示接收到的是文件 { try { richTextBox1.Text += "文件总长度" + TotalLength.ToString() + "\r\n"; SaveFileDialog sfd = new SaveFileDialog(); if (sfd.ShowDialog(this) == DialogResult.OK) { string fileSavePath = sfd.FileName;//获取文件保存路径 long receiveLength = 0; bool flag = true; int rec = 0; using (FileStream fs = new FileStream(fileSavePath, FileMode.Create, FileAccess.Write)) { while (TotalLength > receiveLength) { if (flag) { fs.Write(result, 1, ReceiveLength - 1); fs.Flush(); receiveLength += ReceiveLength - 1; flag = false; } else { rec = ClientSocket.Receive(result); fs.Write(result, 0, rec); fs.Flush(); receiveLength += rec; } } richTextBox1.Text += "文件保存成功:" + " " + fileSavePath + "\r\n"; fs.Close(); } } } catch (Exception ex) { richTextBox1.Text += "文件保存失败!\r\n"; MessageBox.Show(ex.Message); connectCheck = false; ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); break; } } } catch (Exception ex) { MessageBox.Show("接收出错,服务器可能已经挂了!"); break; } } } private void button3_Click(object sender, EventArgs e)//发送文件 { if (string.IsNullOrEmpty(textBox3.Text)) { MessageBox.Show("选择要发送的文件!!!"); } else { //采用文件流方式打开文件 using (FileStream fs = new FileStream(textBox3.Text, FileMode.Open)) { long TotalLength = fs.Length;//文件总长度 ScheDule a = new ScheDule(); a.progressBar1.Value = 0;//设置进度条的当前位置为0 a.progressBar1.Minimum = 0; //设置进度条的最小值为0 a.progressBar1.Maximum = Convert.ToInt32(TotalLength);//设置进度条的最大值 richTextBox1.Text += "文件总长度为:" + TotalLength.ToString() + "\r\n"; string fileName = Path.GetFileName(textBox3.Text);//文件名 string fileExtension = Path.GetExtension(textBox3.Text);//扩展名 string str = string.Format("{0}-{1}", fileName, TotalLength); byte[] arr = Encoding.UTF8.GetBytes(str); byte[] arrSend = new byte[arr.Length + 1]; Buffer.BlockCopy(arr, 0, arrSend, 1, arr.Length); arrSend[0] = 2;//发送文件信息 ClientSocket.Send(arrSend); byte[] arrFile = new byte[1024 * 1024 * 10]; int FileLength = 0;//将要发送的文件读到缓冲区 long SendFileLength = 0; bool flag = true; long num1 = 0; while (TotalLength > SendFileLength && (FileLength = fs.Read(arrFile, 0, arrFile.Length)) > 0) { SendFileLength += FileLength; if (flag) { byte[] arrFileSend = new byte[FileLength + 1]; arrFileSend[0] = 1; Buffer.BlockCopy(arrFile, 0, arrFileSend, 1, FileLength); ClientSocket.Send(arrFileSend, 0, FileLength + 1, SocketFlags.None); flag = false; } else { ClientSocket.Send(arrFile, 0, FileLength, SocketFlags.None); } a.progressBar1.Value += FileLength; num1 += FileLength * 100; long num2 = TotalLength; long num = num1 / num2; a.label1.Text = (num1 / num2).ToString() + "%"; a.Show(); Application.DoEvents();//重点,必须加上,否则父子窗体都假死 } try { if (a.progressBar1.Value == a.progressBar1.Maximum) { MessageBox.Show("文件发送完毕!!!"); a.Close(); textBox3.Clear(); fs.Close(); } } catch { MessageBox.Show("文件发送失败!"); a.Close(); textBox3.Clear(); fs.Close(); } } } } private void button4_Click(object sender, EventArgs e)//选择文件 { OpenFileDialog ofd = new OpenFileDialog(); ofd.InitialDirectory = "D:\\"; if (ofd.ShowDialog() == DialogResult.OK) { textBox3.Text += ofd.FileName; } } private void Heart() { while (this.Visible)//窗体关闭循环即结束 { if (connectCheck) { try { string str = "#####"; string Client = ClientSocket.RemoteEndPoint.ToString(); string SendMessage = "接收客户端" + Client + "心跳包:" + DateTime.Now + "\r\n" + str + "\r\n"; byte[] result1 = Encoding.UTF8.GetBytes(SendMessage); byte[] result = new byte[result1.Length + 1]; result[0] = 3; Buffer.BlockCopy(result1, 0, result, 1, result1.Length); ClientSocket.Send(result); heartNum++;//发一个包计数一次,收到返回包时清0,如果三次没收到认证包,则重连 /*Thread thread_test = new Thread(Screen_Test); thread_test.IsBackground = true; thread_test.Start();*/ Thread.Sleep(3000); //获得当前屏幕的分辨率 /*long ImageLength = 0; Screen scr = Screen.PrimaryScreen; Rectangle rc = scr.Bounds; int iWidth = rc.Width; int iHeight = rc.Height; //创建一个和屏幕一样大的Bitmap Image MyImage = new Bitmap(iWidth, iHeight); //从一个继承自Image类的对象中创建Graphics对象 Graphics g = Graphics.FromImage(MyImage); //将屏幕的(0,0)坐标截图内容copy到画布的(0,0)位置,尺寸到校 new Size(iWidth, iHeight) //保存在MyImage中 g.CopyFromScreen(new Point(0, 0), new Point(0, 0), new Size(iWidth, iHeight)); ///需要将信息组包发送,使得服务端能够正确接收每一个包,区分每一帧图像 ///以字符#123标识一帧的开始加上标识发送类型一共5字节 MemoryStream ms = new MemoryStream(); MyImage.Save(ms, ImageFormat.Jpeg);//保存到流ms中 byte[] arr = ImageToByteArray(MyImage); //发送图片信息 string length = arr.Length.ToString();//图片总长度 string str1 = string.Format("{0}-{1}", "dc", length); byte[] arr1 = Encoding.UTF8.GetBytes(str1); byte[] arrSend1 = new byte[arr1.Length + 1]; arrSend1[0] = 5;//发送图片信息 Buffer.BlockCopy(arr1, 0, arrSend1, 1, arr1.Length); ClientSocket.Send(arrSend1); //Thread.Sleep(1000); //发送图片 int end = 1; bool vis = true; ms.Position = 0; while (end != 0) { if (vis) { byte[] arrPictureSend = new byte[1025]; arrPictureSend[0] = 4; end = ms.Read(arrPictureSend, 1, 1024);//end为0标识读取完毕 ClientSocket.Send(arrPictureSend, 0, 1024 + 1, SocketFlags.None); vis = false; } else { byte[] arrPictureSend = new byte[1024]; end = ms.Read(arrPictureSend, 0, 1024); ClientSocket.Send(arrPictureSend, 0, 1024, SocketFlags.None); } } ms.Dispose(); MyImage.Dispose();*/ } catch (Exception ex) { MessageBox.Show("心跳包发送异常!"+ex.ToString()); connectCheck = false; ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); break; } } } } private void button5_Click(object sender, EventArgs e)//发送消息 { try { richTextBox1.Text += "向服务器发送消息:" + textBox4.Text + "\r\n"; string SendMessage = textBox4.Text; string Client = ClientSocket.RemoteEndPoint.ToString(); byte[] result1 = Encoding.UTF8.GetBytes(SendMessage); byte[] result = new byte[result1.Length + 1]; result[0] = 0; Buffer.BlockCopy(result1, 0, result, 1, result1.Length); ClientSocket.Send(result); textBox4.Clear(); } catch (Exception ex) { richTextBox1.Text += "发送消息失败,服务器可能已经关闭!\r\n"; ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); } } private void textBox4_TextChanged(object sender, EventArgs e)//输入消息 { string str = Console.ReadLine(); textBox4.Text += str; } private void textBox3_TextChanged(object sender, EventArgs e)//选择文件 { } private void richTextBox1_TextChanged(object sender, EventArgs e) { richTextBox1.SelectionStart = richTextBox1.Text.Length; //设定光标位置 richTextBox1.ScrollToCaret(); //滚动到光标处 } private void button1_Click(object sender, EventArgs e) { this.Hide(); Socket_Client sc = new Socket_Client(); sc.StartPosition = FormStartPosition.CenterScreen; sc.Show(); // LoginForm dlg = new LoginForm(); //ctrl +k,ctrl+C 实现多行注释 // dlg.ShowDialog(); // 这里ShowDialog方法表示你必须先操作完dlg窗口,才能操作后面的主窗体。 // 如果要登录窗口显示在主窗口的中心,则在显示之前设置如下 // dlg.StartPosition = FormStartPosition.CenterParent; // dlg.ShowDialog(); // 能够这样做的前提是主窗体必须先定义和显示。否则登录窗体可能无法找到父窗体。 //除此之外,也可以手动设置窗口显示的位置,即窗口坐标。 //首先必须把窗体的显示位置设置为手动。 //dlg.StartPosition = FormStartPosition.Manual; //随后获取屏幕的分辨率,也就是显示器屏幕的大小。 //int xWidth = SystemInformation.PrimaryMonitorSize.Width;//获取显示器屏幕宽度 //int yHeight = SystemInformation.PrimaryMonitorSize.Height;//高度 //然后定义窗口位置,以主窗体为例 //mainForm.Location = new Point(xWidth / 2, yHeight / 2);//这里需要再减去窗体本身的宽度和高度的一半 //mainForm.Show(); } private void richTextBox2_TextChanged(object sender, EventArgs e) { richTextBox2.SelectionStart = richTextBox2.Text.Length; //设定光标位置 richTextBox2.ScrollToCaret(); //滚动到光标处 } #region /// <summary> /// 窗体界面关闭之后强制关闭 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> #endregion private void Server_Client_FormClosed(object sender, FormClosedEventArgs e) { Environment.Exit(0);//当窗体关闭之后,强制关闭窗体所有运行线程 } private void button6_Click(object sender, EventArgs e)//参数发送 { string Information = textBox5.Text; if(Information!="") { bool flag = true; for (int i = 0; i < Information.Length; i++) { int num = Information[i] - '0'; if (num != 0 && num != 1) { flag = false; break; } } if (!flag || Information.Length != 8) { MessageBox.Show("请输入8位二进制数!"); return; } } byte[] arr1 = Encoding.UTF8.GetBytes(Information); byte[] arrSend1 = new byte[arr1.Length + 1]; arrSend1[0] = 6;//发送参数信息 Buffer.BlockCopy(arr1, 0, arrSend1, 1, arr1.Length); ClientSocket.Send(arrSend1); richTextBox1.Text += DateTime.Now + ":参数发送成功\r\n"; textBox5.Clear(); } private void textBox5_TextChanged(object sender, EventArgs e)//参数发送 { } } }
using Library.Appenders.Contracts; using Library.Loggers.Contracts; using System; using System.Collections.Generic; using System.Text; namespace Library.Loggers { public class Logger : ILogger { private IAppender consoleAppender; private IAppender fileAppender; public Logger(IAppender consoleAppender) { this.consoleAppender = consoleAppender; } public Logger(IAppender consoleAppender, IAppender fileAppender) :this(consoleAppender) { this.fileAppender = fileAppender; } public void Fatal(string dateTime, string fatalMessage) { this.Append(dateTime, "Fatal", fatalMessage); } public void Critical(string dateTime, string criticalMessage) { this.Append(dateTime, "Critical", criticalMessage); } public void Error(string dateTime, string errorMessage) { this.Append(dateTime, "Error", errorMessage); } public void Info(string dateTime, string infoMessage) { this.Append(dateTime, "Info", infoMessage); } private void Append(string dateTime, string type, string message) { consoleAppender?.Append(dateTime, type, message); fileAppender?.Append(dateTime, type, message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CateringWebAPI.Models.Result { public class E_WorkingHours: E_Response { public List<E_WorkingHoursInfo> content { get; set; } } }
/* SelOption Control represents an option in the Option Group control */ using System; using System.ComponentModel; using System.Windows.Forms; namespace Com.Colin.Win.Customized { /// <summary> /// SelOption control represents an option of the OptionGroup Control /// </summary> [DefaultProperty("Value"), Designer(typeof(SelOptionDesigner)), DefaultEvent("CheckedChanged"), ToolboxItem(false)] public class SelOption : System.Windows.Forms.RadioButton { private int optionValue; public new event EventHandler Enter; public SelOption() { } /// <summary> /// Get/set value associated with this option /// when this option is checked its value becomes the Value of an OptionGrid /// this option is a child of the Radio Button control /// </summary> [Description("Specifies the value associated with this option"), Category("Appearence")] public int Value { get { return this.optionValue; } set { // Check for duplicate values // This is performed only at the design time // If duplicate value found throw exception int oldvalue = this.optionValue; if (this.DesignMode && this.Parent != null && this.Parent.Controls.Count > 0) { foreach (Control cnt in this.Parent.Controls) { if (cnt is SelOption) { SelOption selopt = (SelOption) cnt; if ((this != selopt) && (value == selopt.Value)) throw new ArgumentException("Duplicate Value"); } } } this.optionValue = value; if (oldvalue != value) { if (this.Checked) { this.Checked = false; } else { if (this.Parent !=null && this.Parent is OptionGroup && ((OptionGroup) this.Parent) .Value == value) { this.Checked =true; } } } } } /// <summary> /// Just give a string representation if someone desides to retreive /// </summary> public override string ToString() { string str1 = base.ToString(); return (str1 + ", Checked: " + this.Checked.ToString()); } /// <summary> /// Hide the AutoCheck property as it causes undesired behavior of the OptionGroup control /// </summary> protected new bool AutoCheck { get { return base.AutoCheck; } set { base.AutoCheck=value; } } /// <summary> /// Reintroduce the OnEnter method that does not perform click when a key pressed /// </summary> protected override void OnEnter(EventArgs e) { if ( this.Enter != null ) this.Enter(this, e); } } }
using System; using System.Collections.Generic; using System.Globalization; using Infrastructure.Translations; using NUnit.Framework; using Tests.Utils.TestFixtures; namespace Tests.Unit.Infrastructure.Translations { class TranslationServiceTests : BaseTestFixture { [Test] public void CanTransLateItemWithDefaultCulture() { var translations = new List<Translation> { new Translation("WelcomeMessage", "Hello this is a test", new CultureInfo("en-US")), new Translation("WelcomeMessage", "Hallo dit is een test", new CultureInfo("nl-NL")) }; var translationService = new TranslationService(translations, new CultureInfo("en-US")); Assert.AreEqual("Hello this is a test", translationService.Translate.WelcomeMessage); } [Test] public void CanTranslateItemWithSpecificCulture() { var translations = new List<Translation> { new Translation("WelcomeMessage", "Hello this is a test", new CultureInfo("en-US")), new Translation("WelcomeMessage", "Hallo dit is een test", new CultureInfo("nl-NL")) }; var translationService = new TranslationService(translations, new CultureInfo("en-US")); Assert.AreEqual("Hallo dit is een test", translationService.Translate("WelcomeMessage", new CultureInfo("nl-NL"))); } [Test] public void IfTranslationDoesNotExistCodeIsReturned() { var translations = new List<Translation>(); var translationService = new TranslationService(translations, new CultureInfo("en-US")); Assert.AreEqual("WelcomeMessage", translationService.Translate.WelcomeMessage); } [Test] public void IfTranslationForSpecificCultureDoesNotExistDefaultCutureIsUsed() { var translations = new List<Translation> { new Translation("WelcomeMessage", "Hello this is a test", new CultureInfo("en-US")) }; var translationService = new TranslationService(translations, new CultureInfo("en-US")); Assert.AreEqual("Hello this is a test", translationService.Translate("WelcomeMessage", new CultureInfo("nl-NL"))); } [Test] public void WhenDefaultCultureIsNullServiceWillNotBreak() { var translations = new List<Translation> { new Translation("WelcomeMessage", "Hallo dit is een test", new CultureInfo("nl-NL")) }; var translationService = new TranslationService(translations, null); Assert.AreEqual("WelcomeMessage", translationService.Translate.WelcomeMessage); Assert.AreEqual("Hallo dit is een test", translationService.Translate("WelcomeMessage", new CultureInfo("nl-NL"))); } [Test] [ExpectedException(ExpectedException = typeof(NullReferenceException))] public void ListOfTranslationCannotBeNull() { new TranslationService(null, new CultureInfo("en-US")); } [Test] public void CanTranslateUsingMethodCallInsteadOfProperty() { var translations = new List<Translation> { new Translation("WelcomeMessage", "Hello this is a test", new CultureInfo("en-US")) }; var translationService = new TranslationService(translations, new CultureInfo("en-US")); Assert.AreEqual("Hello this is a test", translationService.Translate("WelcomeMessage")); } [Test] public void CanTranslateUsingEnum() { var translations = new List<Translation> { new Translation("WelcomeMessage", "Hello this is a test", new CultureInfo("en-US")), new Translation("WelcomeMessage", "Hallo dit is een test", new CultureInfo("nl-NL")) }; var translationService = new TranslationService(translations, new CultureInfo("en-US")); Assert.AreEqual("Hello this is a test", translationService.Translate(Test.WelcomeMessage)); Assert.AreEqual("Hallo dit is een test", translationService.Translate(Test.WelcomeMessage, new CultureInfo("nl-NL"))); } private enum Test { WelcomeMessage } } }
/*********************************************************************** * Module: Anamnesis.cs * Author: Dragana Carapic * Purpose: Definition of the Class Doctor.Anamnesis ***********************************************************************/ using Backend.Model.PerformingExamination; using Model.Manager; using System; using System.ComponentModel.DataAnnotations.Schema; namespace Model.PerformingExamination { public class Therapy { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Diagnosis { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int DailyDose { get; set; } [ForeignKey("Drug")] public int IdDrug { get; set; } public virtual Drug Drug { get; set; } [ForeignKey("Examination")] public int IdExamination { get; set; } public virtual Examination Examination { get; set; } public Therapy() { } public Therapy(Drug drug, Examination examination, int id, string diagnosis, DateTime startDate, DateTime endDate, int dailyDose) { if (drug == null) { Drug = new Drug(); } else { Drug = new Drug(drug); } if (examination == null) { Examination = new Examination(); } else { Examination = new Examination(examination); } Id = id; Diagnosis = diagnosis; StartDate = startDate; EndDate = endDate; DailyDose = dailyDose; } public Therapy(Therapy therapy) { if (therapy.Drug == null) { Drug = new Drug(); } else { Drug = new Drug(therapy.Drug); } if (therapy.Examination == null) { Examination = new Examination(); } else { Examination = new Examination(therapy.Examination); } Id = therapy.Id; Diagnosis = therapy.Diagnosis; StartDate = therapy.StartDate; EndDate = therapy.EndDate; DailyDose = therapy.DailyDose; } } }
using Agenda.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Agenda { internal class PersonModel { public PersonModel(Person person) { Id = person.Id; Name = } public int Id { get; set; } public string Name { get; set; } public string Surname { get; set; } public string DateofBirth { get; set; } public string Nationality { get; set; } } }
using SecureNetRestApiSDK.Api.Models; using SNET.Core; namespace SecureNetRestApiSDK.Api.Requests { /// <summary> /// Request class used for issuing a transaction. /// </summary> public class CaptureRequest : SecureNetRequest { #region Properties /// <summary> /// Amount to charge the account. /// </summary> public decimal Amount { get; set; } /// <summary> /// Credit-card-specific data. Required for credit card charges. /// </summary> public Card Card { get; set; } /// <summary> /// Check-specific data. /// </summary> public Check Check { get; set; } /// <summary> /// Contains developer Id and version information related to the integration. /// </summary> public DeveloperApplication DeveloperApplication { get; set; } /// <summary> /// Data from a Vault payment account. Required for transactions where a Vault token is sent in the place of card or check data. /// </summary> public PaymentVaultToken PaymentVaultToken { get; set; } /// <summary> /// Indicates whether the card object is to be added to the vault to be stored as a token. /// </summary> public bool AddToVault { get; set; } /// <summary> /// Indicates whether the card object is to be added to the vault to be stored as a token even if the attempted authorization is declined. /// </summary> public bool AddToVaultOnFailure { get; set; } /// <summary> /// Typically used as an optional field for pin debit processing. The value of cashBackAmount indicates the amount in cash to be given back to the customer during card processing. /// </summary> public decimal CashBackAmount { get; set; } /// <summary> /// Indicates whether it is permissible to authorize less than the total balance available on a prepaid card. /// </summary> public bool AllowPartialChanges { get; set; } /// <summary> /// Additional data to assist in reporting, ecommerce or moto transactions, and level 2 or level 3 processing. Includes user-defined fields and invoice-related information. /// </summary> public ExtendedInformation ExtendedInformation { get; set; } /// <summary> /// Indicates how checks for duplicate transactions should behave. Duplicates are evaluated on the basis of amount, card number, and order ID; these evaluation criteria can be /// extended to also include customer ID, invoice number, or a user-defined field. Valid values for this parameter are: /// 0 - No duplicate check /// 1 - Exception code is returned in case of duplicate /// 2 - Previously existing transaction is returned in case of duplicate /// 3 - Check is performed as above but without using order ID, and exception code is returned in case of duplicate /// The transactionDuplicateCheckIndicator parameter must be enabled in the Virtual Terminal under Tools->Duplicate Transactions. Duplicates are checked only for APPROVED transactions. /// </summary> public int TransactionDuplicateCheckIndicator { get; set; } /// <summary> /// Client-generated unique ID for each transaction, used as a way to prevent the processing of duplicate transactions. The orderId must be unique to the merchant's SecureNet ID; /// however, uniqueness is only evaluated for APPROVED transactions and only for the last 30 days. If a transaction is declined, the corresponding orderId may be used again. /// The orderId is limited to 25 characters; e.g., “CUSTOMERID MMddyyyyHHmmss”. /// </summary> public string OrderId { get; set; } /// <summary> /// Authorization code that was obtained offline /// </summary> public string AuthorizationCode { get; set; } /// <summary> /// Encryption mode for the transaction. Required when using device-based encryption. /// </summary> public Encryption Encryption { get; set; } #endregion #region Methods public override string GetUri() { return "api/Payments/Capture"; } public override HttpMethodEnum GetMethod() { return HttpMethodEnum.POST; } #endregion } }
using System; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Types; using SFA.DAS.ProviderCommitments.Interfaces; namespace SFA.DAS.ProviderCommitments.Web.Services.Cache { public class ChangeEmployerCacheItem : ICacheModel { public Guid Key { get; } public Guid CacheKey => Key; public ChangeEmployerCacheItem(Guid key) { Key = key; } public long AccountLegalEntityId { get; set; } public DeliveryModel? DeliveryModel { get; set; } public bool SkippedDeliveryModelSelection { get; set; } public string StartDate { get; set; } public string EndDate { get; set; } public string EmploymentEndDate { get; set; } public int? Price { get; set; } public int? EmploymentPrice { get; set; } } }
using GraphicalEditor.Constants; using GraphicalEditor.Enumerations; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace GraphicalEditor.Models.MapObjectRelated { public class MapObjectDoor { [JsonIgnore] public Rectangle Rectangle { get; set; } public MapObjectMetrics MapObjectMetrics { get; set; } public MapObjectDoorOrientation MapObjectDoorOrientation { get; set; } public double XShiftFromCenter { get; set; } public double YShiftFromCenter { get; set; } public MapObjectDoor(MapObjectDoorOrientation mapObjectDoorOrientations, double XShift = 0, double YShift = 0) { MapObjectDoorOrientation = mapObjectDoorOrientations; XShiftFromCenter = XShift; YShiftFromCenter = YShift; } public Rectangle GetDoor() { if (MapObjectDoorOrientation == MapObjectDoorOrientation.NONE) GetEmptyDoor(); else GetActualDoor(); return Rectangle; } private void GetActualDoor() { Rectangle = new Rectangle(); Rectangle.Fill = Brushes.DarkSlateGray; Rectangle.Width = DoorWidth; Rectangle.Height = DoorHeight; Rectangle.SetValue(Canvas.LeftProperty, CalculateDoorX()); Rectangle.SetValue(Canvas.TopProperty, CalculateDoorY()); } private void GetEmptyDoor() { Rectangle = new Rectangle(); } private double CalculateDoorX() { switch (MapObjectDoorOrientation) { case MapObjectDoorOrientation.LEFT: return CalculateXForLeft(); case MapObjectDoorOrientation.RIGHT: return CalculateXForRight(); default: return CalculateXShifted(); } } private double CalculateXForLeft() => MapObjectMetrics.XOfCanvas - DoorWidth + AllConstants.RECTANGLE_STROKE_THICKNESS; private double CalculateXForRight() => MapObjectMetrics.XOfCanvas + MapObjectMetrics.WidthOfMapObject - AllConstants.RECTANGLE_STROKE_THICKNESS; private double CalculateDoorY() { switch (MapObjectDoorOrientation) { case MapObjectDoorOrientation.TOP: return CalculateYForTop(); case MapObjectDoorOrientation.BOTTOM: return CalculateYForBottom(); default: return CalculateYShifted(); } } private double CalculateYForTop() => MapObjectMetrics.YOfCanvas - DoorHeight + AllConstants.RECTANGLE_STROKE_THICKNESS; private double CalculateYForBottom() => MapObjectMetrics.YOfCanvas + MapObjectMetrics.HeightOfMapObject - AllConstants.RECTANGLE_STROKE_THICKNESS; private double CalculateXShifted() { double currentShiftedX = MapObjectMetrics.XOfCanvas + MapObjectMetrics.WidthOfMapObject / 2 - DoorWidth / 2 + this.XShiftFromCenter; if (currentShiftedX < MapObjectMetrics.XOfCanvas) return MapObjectMetrics.XOfCanvas; else if (currentShiftedX + DoorWidth > MapObjectMetrics.XOfCanvas + MapObjectMetrics.WidthOfMapObject) return MapObjectMetrics.XOfCanvas + MapObjectMetrics.WidthOfMapObject - DoorWidth; else return currentShiftedX; } private double CalculateYShifted() { double currentShiftedY = MapObjectMetrics.YOfCanvas + MapObjectMetrics.HeightOfMapObject / 2 - DoorHeight / 2 + this.YShiftFromCenter; if (currentShiftedY < MapObjectMetrics.YOfCanvas) return MapObjectMetrics.YOfCanvas; else if (currentShiftedY + DoorHeight > MapObjectMetrics.YOfCanvas + MapObjectMetrics.HeightOfMapObject) return MapObjectMetrics.YOfCanvas + MapObjectMetrics.HeightOfMapObject - DoorHeight; else return currentShiftedY; } private double DoorWidth { get { if (MapObjectDoorOrientation == MapObjectDoorOrientation.TOP || MapObjectDoorOrientation == MapObjectDoorOrientation.BOTTOM) return AllConstants.DOOR_WIDTH; else return AllConstants.DOOR_HEIGHT; } } private double DoorHeight { get { if (MapObjectDoorOrientation == MapObjectDoorOrientation.TOP || MapObjectDoorOrientation == MapObjectDoorOrientation.BOTTOM) return AllConstants.DOOR_HEIGHT; else return AllConstants.DOOR_WIDTH; } } } }
using UnityEngine; public class BuffData : MonoBehaviour { [SerializeField] private CardManager CardManager = null; private CardStatus CreateCardStatus(CardLanes cardLanes) { return CardManager.BoardList[cardLanes.X, cardLanes.Y].GetComponent<CardStatus>(); ; } public void InfernalBuff(CardLanes cardLanes) { var card = CreateCardStatus(cardLanes); card.MyAD++; } public void MountainBuff(CardLanes cardLanes) { var card = CreateCardStatus(cardLanes); card.MyHP++; } public void CloudBuff(CardLanes cardLanes) { CardManager.Skill(cardLanes); } public void OceanBuff(CardLanes cardLanes) { var card = CreateCardStatus(cardLanes); card.IsOcean = true; } public void ElderBuff(CardLanes cardLanes) { var card = CreateCardStatus(cardLanes); card.CreateBuff(); } }
using RockPaperScissors.Basics; namespace RockPaperScissors.Strategies { public class RandomStrategy : IRPSStrategy { public Sign Throw() { return (Sign)IRPSStrategy._random.Next(3); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApp9CronScheduledBackgroudService.Server.BGService.CronExtension; using WebApp9CronScheduledBackgroudService.Server.AppDBContext; namespace WebApp9CronScheduledBackgroudService.Server.BGService.Repository { public class BackgroundContainer : IBackgroundContainer { private List<Promotions> Promotions { get; set; } = new List<Promotions>(); private MyContext _context; public BackgroundContainer(MyContext context) { _context = context; //for (var i = 0; i <= 100; i++) //{ // Promotions.Add(new Promotions // { // Id = i, // Name = $"Promotion {i}", // Cron = DateTime.Now.AddSeconds(i * 10).ToCron(), // EndDate = DateTime.Now.AddSeconds(i * 10) // }) ; //} } protected virtual IQueryable<Promotions> GetQueryable() { IQueryable<Promotions> query = _context.Set<Promotions>(); query = query.Where(x => x.Enabled == true); return query.AsNoTracking(); } public IQueryable<Promotions> GetPromotions() { return GetQueryable(); } public async Task<Promotions> UpdatePromotion(Promotions promotions) { _context.Update(promotions); await _context.SaveChangesAsync(); return promotions; } } }
using System.Collections.Generic; namespace AzureAI.CallCenterTalksAnalysis.Infrastructure.DTOs { internal class AudioVideoAnalysisResult { public SummarizedInsights summarizedInsights { get; set; } } internal class SummarizedInsights { public IList<Keyword> keywords { get; set; } public IList<Sentiment> sentiments { get; set; } public IList<Emotion> emotions { get; set; } public IList<Topic> topics { get; set; } } internal class Instance { public string adjustedStart { get; set; } public string adjustedEnd { get; set; } public string start { get; set; } public string end { get; set; } } internal class Keyword { public int id { get; set; } public string text { get; set; } public double confidence { get; set; } public string language { get; set; } public IList<Instance> instances { get; set; } } internal class Topic { public int id { get; set; } public string name { get; set; } public string referenceId { get; set; } public string referenceType { get; set; } public string iptcName { get; set; } public double confidence { get; set; } public string iabName { get; set; } public string language { get; set; } public IList<Instance> instances { get; set; } } internal class Sentiment { public int id { get; set; } public double averageScore { get; set; } public string sentimentKey { get; set; } public IList<Instance> instances { get; set; } } public class Emotion { public string type { get; set; } public double seenDurationRatio { get; set; } } }
using System; using NUnit.Framework; [TestFixture] class EntpTests25 { [Test] public void GetByPositionThrowException() { IEnterprise enterprise = new Enterprise(); Employee employee = new Employee("pesho", "123", 777, Position.Hr, DateTime.Now); Employee employee1 = new Employee("a", "321", 777, Position.Owner, DateTime.Now); Employee employee2 = new Employee("c", "111", 777, Position.Hr, DateTime.Now); Employee employee3 = new Employee("b", "11111", 777, Position.Developer, DateTime.Now); Assert.Throws<ArgumentException>(() => enterprise.GetByPosition(Position.TeamLead)); } }
using System; namespace Stringconversion { class stringconv { public static void Main(String []args) { int i = 5; double k = 123123.23123; long p = 242.23; float a = 123.452f; bool b = true; string asd= "Asheleon"; dynamic gh = "Not"; Console.WriteLine(i.ToString()); Console.WriteLine(k.ToString()); Console.WriteLine(p.ToInt32()); Console.WriteLine(b.ToString()); Console.WriteLine(asd); Console.WriteLine(gh); } } }
/* * Created by SharpDevelop. * User: admin * Date: 07.07.2012 * Time: 0:48 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.IO; namespace sudoku { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { private int a = 0; private int b = 0; private int c = 0; private int ur=0; private string specznak; private int error=0; private Label [,]lib=new Label[9,9]; private butun but=new butun(); private open_TO_file fole =new open_TO_file(); private bool flag_x_y=true; private bool flag=true; private string slojnost; private string []prave=new string[72]; private int ohibki; private int conTimer; private bool close; public MainForm(string str,string pravela) { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); Initialization_lib(); fole.ToGOOmas("pazel.tt"); fole.Resojes(str); slojnost=pravela; LEppzp(fole.SL); specznak=str; for(int i=0;i<72;i++) { prave[i]=fole.Mas[i]; } timer(); } void PRVL() { if(slojnost=="Легкий") { fole.Open_ToGoo_mas("light.tt"); label89.Text=fole.Str; label86.Text="0"; }else if(slojnost=="Средний") { fole.Open_ToGoo_mas("average.tt"); label89.Text=fole.Str; ohibki=6; label86.Text=ohibki.ToString(); conTimer=6; }else if(slojnost=="Ад...!!") { fole.Open_ToGoo_mas("average.tt"); label89.Text=fole.Str; ohibki=3; label86.Text=ohibki.ToString(); conTimer=8; } } void Initialization_lib() { lib[0,0]=label1; lib[0,1]=label2; lib[0,2]=label3; lib[0,3]=label4; lib[0,4]=label5; lib[0,5]=label6; lib[0,6]=label7; lib[0,7]=label8; lib[0,8]=label9; lib[1,0]=label10; lib[1,1]=label11; lib[1,2]=label12; lib[1,3]=label13; lib[1,4]=label14; lib[1,5]=label15; lib[1,6]=label16; lib[1,7]=label17; lib[1,8]=label18; lib[2,0]=label19; lib[2,1]=label20; lib[2,2]=label21; lib[2,3]=label22; lib[2,4]=label23; lib[2,5]=label24; lib[2,6]=label25; lib[2,7]=label26; lib[2,8]=label27; lib[3,0]=label28; lib[3,1]=label29; lib[3,2]=label30; lib[3,3]=label31; lib[3,4]=label32; lib[3,5]=label33; lib[3,6]=label34; lib[3,7]=label35; lib[3,8]=label36; lib[4,0]=label37; lib[4,1]=label38; lib[4,2]=label39; lib[4,3]=label40; lib[4,4]=label41; lib[4,5]=label42; lib[4,6]=label43; lib[4,7]=label44; lib[4,8]=label45; lib[5,0]=label46; lib[5,1]=label47; lib[5,2]=label48; lib[5,3]=label49; lib[5,4]=label50; lib[5,5]=label51; lib[5,6]=label52; lib[5,7]=label53; lib[5,8]=label54; lib[6,0]=label55; lib[6,1]=label56; lib[6,2]=label57; lib[6,3]=label58; lib[6,4]=label59; lib[6,5]=label60; lib[6,6]=label61; lib[6,7]=label62; lib[6,8]=label63; lib[7,0]=label64; lib[7,1]=label65; lib[7,2]=label66; lib[7,3]=label67; lib[7,4]=label68; lib[7,5]=label69; lib[7,6]=label70; lib[7,7]=label71; lib[7,8]=label72; lib[8,0]=label73; lib[8,1]=label74; lib[8,2]=label75; lib[8,3]=label76; lib[8,4]=label77; lib[8,5]=label78; lib[8,6]=label79; lib[8,7]=label80; lib[8,8]=label81; } void LEppzp(string st) { for(int i=0,y=0;i<9;i++) { for(int o=0;o<9;o++,y++) { if(st[y]!='*') { lib[i,o].Text=st[y].ToString(); lib[i,o].Enabled=false; } else{lib[i,o].Text=" ";} } } } void timer() { timer1.Start(); timer2.Start(); } private void terms(int x,int y) { if (but.ShowDialog() == DialogResult.OK) { for(int i =0;i<9;i++) { if( lib[x,i].Text!=but.STR()&&lib[i,y].Text!=but.STR()) { flag_x_y=true; }else{ if(lib[x,i].Text==but.STR()) lib[x,i].BackColor=Color.Red; else lib[i,y].BackColor=Color.Red; flag_x_y =false; error++; break; } } if((x==0||x<3)&&(y==0||y<3)) { pravela_hoda(0,0,3,3); } else if((x==0||x<3)&&(y==3||y<6)) { pravela_hoda(0,3,3,6); }else if((x==0||x<3)&&(y==6||y<9)) { pravela_hoda(0,6,3,9); }else if((x==3||x<6)&&(y==0||y<3)) { pravela_hoda(3,0,6,3); }else if((x==3||x<6)&&(y==3||y<6)) { pravela_hoda(3,3,6,6); }else if((x==3||x<6)&&(y==6||y<9)) { pravela_hoda(3,6,6,9); }else if((x==6||x<9)&&(y==0||y<3)) { pravela_hoda(6,0,9,3); }else if((x==6||x<9)&&(y==3||y<6)) { pravela_hoda(6,3,9,6); }else if((x==6||x<9)&&(y==6||y<9)) { pravela_hoda(6,6,9,9); } } } private void check(int x,int y) { int i=0; if(flag_x_y==true&&flag==true) lib[x,y].Text=but.STR(); else { MessageBox.Show("эта цифра уже существует"); if(flag_x_y==false) { label85.Text=error.ToString(); }else if(flag==false){ label85.Text=error.ToString(); } if (ohibki ==error) { DialogResult dr=MessageBox.Show("хотите начать заеово ..!?","вы проиграли ...!! Вы злелоли много ошибок",MessageBoxButtons.YesNo); if(dr== DialogResult.Yes) { restaet(); }else if(dr== DialogResult.No) { this.Close(); } } } for(int z=0;z<9;z++) { for(int c=0;c<9;c++) { lib[z,c].BackColor=Color.White; if(lib[z,c].Text.ToString()!=" ") { i++; } } } if(i==81) { the_transition_to_a_new_level level =new the_transition_to_a_new_level(specznak,slojnost); if(level.ShowDialog() == DialogResult.OK) { NEw_Games(); }else if(level.DialogResult== DialogResult.Retry) { restaet(); } else if(level.DialogResult== DialogResult.No) { this.Close(); } } } void restaet() { timer1.Stop(); timer2.Stop(); a=0; c=0; b=0; error=0; fole.Resojes(specznak); LEppzp(fole.SL); PRVL(); timer(); } void pravela_hoda(int x,int y,int c,int b) { for(int t=x;t<c;t++) { for(int v=y;v<b;v++) { if(lib[t,v].Text==but.STR()) { flag=false; lib[t,v].BackColor=Color.Red; } } } } void Click(object sender, EventArgs e) { int x=0,y=0; for (int index_x=0 ; index_x < 9; index_x++) { for(int index_y=0;index_y<9;index_y++) { if (sender as Label == lib[index_x,index_y]) { x=index_x; y=index_y; break; } } if(x!=0&&y!=0) break; } terms(x,y); check(x,y); flag=true; } void Timer1Tick(object sender, EventArgs e) { timer1.Interval = 1000; timer1.Enabled = true; a++; if (a == 60) { b++; a = 0; if (b == 60) { c++; b = 0; } } label82.Text = c.ToString() + ":" + b.ToString() + ":" + a.ToString(); } void NEw_Games() { if(ur<12) { string temp=""; variants varin =new variants(); for(int i=1;i<=12;i++) { if(varin.SSR[i]==specznak) { i=i+1; specznak=varin.SSR[i]; break; } } timer1.Stop(); a=0; b=0; c=0; error=0; for(int i=0;i<72;i++) { if(prave[i]==specznak) { i=i+1; temp=prave[i]; break; } } LEppzp(temp); timer(); // }else { MessageBox.Show("Вы прошли весь уровень","победа..!!"); the_transition_to_a_new_level lev=new the_transition_to_a_new_level(specznak,slojnost); lev.save(); ur++; } } void Button1Click(object sender, EventArgs e) { DialogResult dr=MessageBox.Show("Вы уверены что хотите завершить партию ....!!!","Выход",MessageBoxButtons.YesNo); if(dr==DialogResult.Yes){ close=true; this.Close(); }else if(dr== DialogResult.No) { close=false; } } void MainFormLoad(object sender, EventArgs e) { PRVL(); } void MainFormFormClosed(object sender, FormClosedEventArgs e) { if(close==true) { this.DialogResult= DialogResult.No; }else{ this.DialogResult= DialogResult.OK; } } void Timer2Tick(object sender, EventArgs e) { if(slojnost=="Ад...!!"||slojnost=="Средний") { timer2.Interval = 1000; timer2.Enabled = true; if (conTimer==b||conTimer<b) { timer2.Stop(); timer1.Stop(); DialogResult dr=MessageBox.Show("хотите начать заеово ..!?","вы проиграли ...!!",MessageBoxButtons.YesNo); if(dr== DialogResult.Yes) { restaet(); }else if(dr== DialogResult.No) { this.Close(); } } }else timer2.Stop(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class timer : MonoBehaviour { public float timeStart = 0; public Text textBox; void Start() { textBox.text = timeStart.ToString(); } // Update is called once per frame void Update() { timeStart = timeStart + Time.deltaTime; textBox.text = timeStart.ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MVCnetcore.Models { public class UserLogInModel { public int Id { get; set; } public string Email { get; set; } public string Name { get; set; } public string Password { get; set; } public int IdRoles { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Reflection; using Excel = Microsoft.Office.Interop.Excel; using FXB.Dialog; namespace FXB.Common { public class ExcelUtil { public static void ExportData(DataGridView exportView) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "*.xls|*.*"; if (DialogResult.OK != dlg.ShowDialog()) { return; } string saveFilePath = dlg.FileName; DataExportDlg exportDlg = new DataExportDlg(exportView); exportDlg.Show(); try { object Nothing = Missing.Value; Excel.Application excelApp = new Excel.Application(); if (excelApp == null) { MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel"); return; } Excel.Workbook workBook = excelApp.Workbooks.Add(Nothing); Excel.Worksheet workSheet = workBook.Sheets[1]; workSheet.Name = "导出"; for (int i = 0; i < exportView.ColumnCount; i++) { workSheet.Cells[1, i + 1] = exportView.Columns[i].HeaderText; } for (int r = 0; r < exportView.Rows.Count; r++) { for (int i = 0; i < exportView.ColumnCount; i++) { DataGridViewCheckBoxCell cbCell = exportView.Rows[r].Cells[i] as DataGridViewCheckBoxCell; if (cbCell != null) { bool blValue = (bool)cbCell.Value; workSheet.Cells[r + 2, i + 1] = blValue ? "是" : "否"; } else { string v = exportView.Rows[r].Cells[i].Value.ToString(); if (v.Length > 15) { v = "'" + v; } else { if (exportView.Columns[i].HeaderText == "房号") { v = "'" + v; } } workSheet.Cells[r + 2, i + 1] = v; } } //Application.DoEvents(); } workSheet.Columns.EntireColumn.AutoFit(); workSheet.SaveAs( saveFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing); workBook.Close(false, Type.Missing, Type.Missing); excelApp.Quit(); MessageBox.Show(exportView, "导出数据成功"); //MessageBox.Show("导出数据成功"); } catch (Exception ex) { MessageBox.Show(ex.Message); //System.Environment.Exit(0); } finally { exportDlg.Close(); exportDlg.Dispose(); } } } }
namespace ResolveUR.Library { using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Xml; using static System.String; public class ProjectReferencesResolveUR : IResolveUR { const string Include = "Include"; const string Reference = "Reference"; const string Project = "Project"; static readonly string TempPath = Path.GetTempPath(); string _filePath; bool _isCancel; List<XmlNode> _nodesToRemove; PackageConfig _packageConfig; RefsIgnoredFileManager _refsIgnoredFileManager; public event HasBuildErrorsEventHandler HasBuildErrorsEvent; public event ProjectResolveCompleteEventHandler ProjectResolveCompleteEvent; public string FilePath { get => _filePath; set { _filePath = value; var dirPath = Path.GetDirectoryName(_filePath); if (!ShouldResolvePackage) return; _packageConfig = new PackageConfig { FilePath = value, PackageConfigPath = dirPath + "\\packages.config" }; _refsIgnoredFileManager = new RefsIgnoredFileManager(_filePath); } } public string BuilderPath { get; set; } public bool ShouldResolvePackage { get; set; } // returns false if there were build errors public void Resolve() { _isCancel = false; // do nothing if project already has build errors if (ProjectHasBuildErrors()) { RaiseBuildErrorsEvent(); return; } _nodesToRemove = Resolve(Reference); _nodesToRemove.AddRange(Resolve(Project + Reference)); if (!_nodesToRemove.Any()) return; if (_isCancel) return; _refsIgnoredFileManager.NodesToRemove = _nodesToRemove; _refsIgnoredFileManager.WriteRefsToFile(); if (_isCancel) return; _refsIgnoredFileManager.LaunchRefsFile(); ProjectResolveCompleteEvent?.Invoke(); } public void Cancel() { _isCancel = true; } public void Clean() { _refsIgnoredFileManager.ProcessRefsFromFile(); RemoveNodesInProject(Reference); RemoveNodesInProject(Project + Reference); if (ShouldResolvePackage) ResolvePackages(_nodesToRemove); } List<XmlNode> Resolve(string referenceType) { var originalProjectXmlDocument = GetXmlDocument(); var projectXmlDocument = GetXmlDocument(); var nodesToRemove = new List<XmlNode>(); var itemIndex = 0; XmlNode item; while ((item = GetReferenceGroupItemIn(projectXmlDocument, referenceType, itemIndex)) != null && item.ChildNodes.Count > 0) { if (_isCancel) break; // use string names to match up references, using nodes themselves will mess up references var referenceNodeNames = item.ChildNodes.OfType<XmlNode>().Select(x => x.Attributes?[Include].Value); var nodeNames = referenceNodeNames as IList<string> ?? referenceNodeNames.ToList(); nodesToRemove.AddRange( FindNodesToRemoveForItemGroup(projectXmlDocument, nodeNames, item, referenceType, itemIndex++)); } // restore original project if (itemIndex > 0) originalProjectXmlDocument.Save(FilePath); return nodesToRemove; } void ResolvePackages(IEnumerable<XmlNode> nodesToRemove) { if (!_packageConfig.Load()) return; foreach (var xmlNode in nodesToRemove) { if (_isCancel) break; _packageConfig.Remove(xmlNode); } _packageConfig.Save(); } IEnumerable<XmlNode> FindNodesToRemoveForItemGroup( XmlDocument projectXmlDocument, IList<string> nodeNames, XmlNode item, string referenceType, int itemIndex) { var nodesToRemove = new List<XmlNode>(); var projectXmlDocumentToRestore = GetXmlDocument(); foreach (var referenceNodeName in nodeNames) { if (_isCancel) break; var nodeToRemove = item.ChildNodes.Cast<XmlNode>() .FirstOrDefault(i => i.Attributes != null && i.Attributes[Include].Value == referenceNodeName); if (nodeToRemove?.ParentNode == null) continue; nodeToRemove.ParentNode.RemoveChild(nodeToRemove); projectXmlDocument.Save(FilePath); if (ProjectHasBuildErrors()) { // restore original projectXmlDocumentToRestore.Save(FilePath); // reload item group from doc projectXmlDocument = GetXmlDocument(); item = GetReferenceGroupItemIn(projectXmlDocument, referenceType, itemIndex); if (item == null) break; } else { nodesToRemove.Add(nodeToRemove); projectXmlDocumentToRestore = GetXmlDocument(); } } return nodesToRemove; } void RemoveNodesInProject(string referenceType) { var projectXmlDocument = GetXmlDocument(); var itemIndex = 0; XmlNode item; while ((item = GetReferenceGroupItemIn(projectXmlDocument, referenceType, itemIndex++)) != null && item.ChildNodes.Count > 0) { if (_isCancel) break; for (var i = 0; i < item.ChildNodes.Count;) { if (_isCancel) break; if (_nodesToRemove.Any(x => x.Attributes[0].Value == item.ChildNodes[i].Attributes[0].Value)) item.RemoveChild(item.ChildNodes[i]); else i++; } } projectXmlDocument.Save(FilePath); } XmlDocument GetXmlDocument() { var doc = new XmlDocument(); doc.Load(FilePath); return doc; } XmlNode GetReferenceGroupItemIn(XmlDocument document, string referenceNodeName, int startIndex) { var itemGroups = document.SelectNodes(@"//*[local-name()='ItemGroup']"); if (itemGroups == null || itemGroups.Count == 0) return null; for (var i = startIndex; i < itemGroups.Count; i++) { if (!itemGroups[i].HasChildNodes) return null; if (itemGroups[i].ChildNodes[0].Name == referenceNodeName) return itemGroups[i]; } return null; } bool ProjectHasBuildErrors() { const string logFileName = "buildlog.txt"; const string argumentsFormat = "\"{0}\" /clp:ErrorsOnly /nologo /m /flp:logfile={1};Verbosity=Quiet"; const string error = "error"; var logFile = $"{TempPath}\\{logFileName}"; var startInfo = new ProcessStartInfo { FileName = BuilderPath, Arguments = Format(CultureInfo.CurrentCulture, argumentsFormat, FilePath, logFile), CreateNoWindow = true, UseShellExecute = false, WorkingDirectory = TempPath }; // clear build log file if it was left out for some reason if (File.Exists(logFile)) File.Delete(logFile); var status = 0; using (var exeProcess = Process.Start(startInfo)) { exeProcess?.WaitForExit(); if (exeProcess != null) status = exeProcess.ExitCode; } // open build log to check for errors if (!File.Exists(logFile)) return true; var s = File.ReadAllText(logFile); File.Delete(logFile); // if build error, the reference cannot be removed return status != 0 && (s.Contains(error) || IsNullOrWhiteSpace(s)); } void RaiseBuildErrorsEvent() { HasBuildErrorsEvent?.Invoke(Path.GetFileNameWithoutExtension(FilePath)); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class RoomInformation : MonoBehaviour { public Transform target; private Transform touchObject, textObject; Text roomNameText; Image touchImage; RectTransform roomNameTransform, touchIconTransform, canvasTransform; Vector2 touchPosition, namePosition, targetScreenPosition; bool runOnce = false, isVisible = false, removeInfo = false; Door doorway; Button touchButton; public bool displayInfo = true; Color inactiveColor; NextRoomInfo nextRoom; // Use this for initialization private void Start () { nextRoom = GameObject.Find("NextRoomInfo").GetComponent<NextRoomInfo>(); touchObject = transform.Find("Touch Icon"); textObject = transform.Find("Room Name"); touchImage = touchObject.GetComponent<Image>(); touchIconTransform = touchObject.GetComponent<RectTransform>(); touchButton = touchObject.GetComponent<Button>(); roomNameText = textObject.GetComponent<Text>(); roomNameTransform = textObject.GetComponent<RectTransform>(); transform.parent = GameObject.Find("Canvas").transform; touchButton.onClick.RemoveAllListeners(); //print("ADDING LISTENER"); touchButton.onClick.AddListener(TeleportPlayer); //print("ADDED"); inactiveColor = new Color(0.3f, 0.3f, 0.3f, 0.6f); } public void SetTarget(Transform t){ target = t; //roomNameText.text = t.name; } public void SetDoor(Door d){ doorway = d; } // Update is called once per frame private void Update () { //print(target); if(target != null){ canvasTransform = GameObject.Find("Canvas").GetComponent<RectTransform>(); Vector2 ViewportPosition=Camera.main.WorldToViewportPoint(target.position); Vector2 WorldObject_ScreenPosition =new Vector2( ((ViewportPosition.x*canvasTransform.sizeDelta.x)-(canvasTransform.sizeDelta.x*0.5f)), ((ViewportPosition.y*canvasTransform.sizeDelta.y)-(canvasTransform.sizeDelta.y*0.5f))); touchIconTransform.anchoredPosition=WorldObject_ScreenPosition; roomNameTransform.anchoredPosition = WorldObject_ScreenPosition + new Vector2(50,100); isVisible = true; } if(displayInfo){ if(!removeInfo){ touchImage.color = Color.Lerp(touchImage.color, Color.white, 0.05f); touchIconTransform.sizeDelta = Vector2.Lerp(touchIconTransform.sizeDelta, new Vector2(120,120), 0.05f); if(touchIconTransform.sizeDelta.x >= 100) foreach(Transform t in touchObject.transform){ //t.gameObject.SetActive(true); if(t.GetComponent<Text>()){ t.GetComponent<Text>().color = Color.Lerp(t.GetComponent<Text>().color, Color.white,0.05f); } if(t.GetComponent<RawImage>()){ Color c = t.GetComponent<RawImage>().color; c = Color.Lerp(c, new Color(c.r,c.g,c.b,1),0.05f); t.GetComponent<RawImage>().color = c; } } touchButton.interactable = true; } } else{ if(!removeInfo){ touchImage.color = Color.Lerp(touchImage.color, inactiveColor, 0.05f); touchIconTransform.sizeDelta = Vector2.Lerp(touchIconTransform.sizeDelta, new Vector2(40,40), 0.05f); foreach(Transform t in touchObject.transform){ if(t.GetComponent<Text>()){ t.GetComponent<Text>().color = Color.Lerp(t.GetComponent<Text>().color, new Color(0,0,0,0),0.05f); } if(t.GetComponent<RawImage>()){ Color c = t.GetComponent<RawImage>().color; c = Color.Lerp(c, new Color(c.r,c.g,c.b,0),0.05f); t.GetComponent<RawImage>().color = c; } } touchButton.interactable = false; } } } void TeleportPlayer(){ //print("Teleporting"); removeInfo = true; doorway.StartNewTeleport(); displayInfo = false; nextRoom.ShowRoomInfo(); touchImage.color = new Color(0,0,0,0); transform.Find("Room Name").GetComponent<Text>().color = new Color(0,0,0,0); transform.Find("Touch Icon").GetComponent<Image>().color = new Color(0,0,0,0); transform.Find("Touch Icon").Find("Rotating Image 1").GetComponent<RawImage>().color = new Color(0,0,0,0); transform.Find("Touch Icon").Find("Rotating Image 2").GetComponent<RawImage>().color = new Color(0,0,0,0); transform.Find("Touch Icon").Find("Colour 1").GetComponent<RawImage>().color = new Color(0,0,0,0); transform.Find("Touch Icon").Find("Colour 2").GetComponent<RawImage>().color = new Color(0,0,0,0); transform.Find("Touch Icon").Find("Colour 3").GetComponent<RawImage>().color = new Color(0,0,0,0); //Destroy(transform.Find("Touch Icon").gameObject); //Destroy(transform.Find("Rotating Button").gameObject); Invoke("SelfDestruct", 3); } void SelfDestruct(){ Destroy(gameObject); } void Fade(){ if(isVisible){ roomNameText.color = Color.Lerp(roomNameText.color, new Color(roomNameText.color.a, roomNameText.color.g, roomNameText.color.b, 1), 0.06f); touchImage.color = Color.Lerp(touchImage.color, new Color(touchImage.color.a, touchImage.color.g, roomNameText.color.b, 1), 0.06f); } } }
namespace Dixin.Diagnostics { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Management; using Dixin.Common; using Dixin.Management; using Tutorial; public static partial class ProcessHelper { public static int StartAndWait( string fileName, string arguments, Action<string> outputReceived = null, Action<string> errorReceived = null) { fileName.NotNullOrWhiteSpace(nameof(fileName)); using (Process process = new Process()) { process.StartInfo = new ProcessStartInfo() { FileName = fileName, Arguments = arguments, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }; if (outputReceived != null) { process.OutputDataReceived += (sender, args) => outputReceived(args.Data); } if (errorReceived != null) { process.ErrorDataReceived += (sender, args) => errorReceived(args.Data); } process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); return process.ExitCode; } } } public static partial class ProcessHelper { public static IEnumerable<Win32Process> All (ManagementScope managementScope = null) => Wmi .Query($"SELECT * FROM {Win32Process.WmiClassName}", managementScope) .Select(process => new Win32Process(process)); public static Win32Process ById (uint processId, ManagementScope managementScope = null) => Wmi .Query( $"SELECT * FROM {Win32Process.WmiClassName} WHERE {nameof(Win32Process.ProcessId)} = {processId}", managementScope) .Select(process => new Win32Process(process)).FirstOrDefault(); public static IEnumerable<Win32Process> ByName (string name, ManagementScope managementScope = null) => Wmi .Query( $"SELECT * FROM {Win32Process.WmiClassName} WHERE {nameof(Win32Process.Name)} = '{name}'", managementScope) .Select(process => new Win32Process(process)); } public static partial class ProcessHelper { public static Win32Process ParentProcess(uint childProcessId, ManagementScope managementScope = null) => ById(childProcessId, managementScope)?.ParentProcessId?.Forward(parentProcessId => ById(parentProcessId)); public static IEnumerable<Win32Process> AllParentProcess( uint childProcessId, ManagementScope managementScope = null) { Win32Process parentProcess = ById(childProcessId, managementScope)?.ParentProcessId?.Forward(parentProcessId => ById(parentProcessId)); return parentProcess == null ? Enumerable.Empty<Win32Process>() : Enumerable.Repeat(parentProcess, 1).Concat(parentProcess.ProcessId.HasValue ? AllParentProcess(parentProcess.ProcessId.Value) : Enumerable.Empty<Win32Process>()); } } public static partial class ProcessHelper { public static IEnumerable<Win32Process> ChildProcesses (uint parentProcessId, ManagementScope managementScope = null) => Wmi .Query( $"SELECT * FROM {Win32Process.WmiClassName} WHERE {nameof(Win32Process.ParentProcessId)} = {parentProcessId}", managementScope) .Select(process => new Win32Process(process)); public static IEnumerable<Win32Process> AllChildProcesses (uint parentProcessId, ManagementScope managementScope = null) { IEnumerable<Win32Process> childProcesses = Wmi .Query( $"SELECT * FROM {Win32Process.WmiClassName} WHERE {nameof(Win32Process.ParentProcessId)} = {parentProcessId}", managementScope).Select(process => new Win32Process(process)); return childProcesses.Concat(childProcesses.SelectMany(process => process.ProcessId.HasValue ? AllChildProcesses(process.ProcessId.Value, managementScope) : Enumerable.Empty<Win32Process>())); } } }
namespace SnowDAL.Searching { public class QueryPager : IQueryPaging { public int Skip { get; set; } public int Take { get; set; } } }
using ISE.Framework.Common.Aspects; using ISE.SM.Bussiness; using ISE.SM.Common.Contract; using ISE.SM.Common.DTO; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; namespace ISE.SM.Service { [Intercept] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, UseSynchronizationContext = false, AddressFilterMode = AddressFilterMode.Any)] public class MembershipProviderService :ContextBoundObject, IMembershipProviderService { SecurityUserBussiness userBussiness = new SecurityUserBussiness(); public Framework.Common.Service.Message.ResponseDto RegisterUser(Common.DTO.UserDto userMember) { var response = userBussiness.RegisterUser(userMember); return response; } public Framework.Common.Service.Message.ResponseDto UnRegisterUser(Common.DTO.UserDto userMember) { var response = userBussiness.UnRegisterUser(userMember); return response; } public Framework.Common.Service.Message.ResponseDto AssignAccountAppDomain(Common.DTO.AccountDto account, int appDomain) { var response = userBussiness.AssignAccountAppDomain(account,appDomain); return response; } public Framework.Common.Service.Message.ResponseDto DeAssignAccountAppDomain(Common.DTO.AccountDto account, int appDomain) { var response = userBussiness.DeAssignAccountAppDomain(account, appDomain); return response; } public Common.DTOContainer.AccountDtoContainer GetUserAccounts(Common.DTO.UserDto userMember) { var response = userBussiness.GetUserAccounts(userMember); return response; } public Common.DTO.AccountDto CreateAccount(Common.DTO.AccountDto account, Common.DTO.UserDto user) { AccountBussiness accBs = new AccountBussiness(); var response = accBs.CreateAccount(account, user); return response; } public Framework.Common.Service.Message.ResponseDto DeleteAccount(Common.DTO.AccountDto account) { AccountBussiness accBs = new AccountBussiness(); var response = accBs.DeleteAccount(account); return response; } public Framework.Common.Service.Message.ResponseDto UpdateAccount(Common.DTO.AccountDto account) { AccountBussiness accBs = new AccountBussiness(); var response = accBs.UpdateAccount(account); return response; } public AccountDto ChangePassword(string userName, string newPassword, string currentPassword) { AccountBussiness accBs = new AccountBussiness(); var response = accBs.ChangePassword(userName, currentPassword, newPassword); return response; } public AccountDto ResetPassword(string userName, long userId) { AccountBussiness accBs = new AccountBussiness(); var response = accBs.ResetPassword(userName, userId); return response; } } }
using System; using System.ComponentModel; using Xamarin.Forms; using Student.Models; using Student.ViewModels; namespace Student.Views { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(true)] public partial class ItemsPage : ContentPage { ItemsViewModel viewModel; public ItemsPage() { InitializeComponent(); BindingContext = viewModel = new ItemsViewModel(); } /// <summary> /// Ons the item selected. Open Detail Page. /// </summary> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> async void OnItemSelected(object sender, SelectedItemChangedEventArgs args) { if (!(args.SelectedItem is Item item)) { return; } await Navigation.PushAsync(new ItemDetailPage(new ItemDetailViewModel(item))); // Manually deselect item. ItemsListView.SelectedItem = null; } async void AddItem_Clicked(object sender, EventArgs e) { await Navigation.PushModalAsync(new NavigationPage(new NewItemPage())); } protected override void OnAppearing() { base.OnAppearing(); if (viewModel.Items.Count == 0) viewModel.LoadItemsCommand.Execute(null); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using DataLayer; using MetroRent.Models; using System.IO; using MetroRent.Extensions; using BusinessLogic; namespace MetroRent.Controllers { public class SeekTenantController : Controller { private MetroRentDBContext db = new MetroRentDBContext(); // GET: SeekTenant public ActionResult Index() { var query = (from seekTenantRequest in db.SeekTenantRequests select seekTenantRequest) .OrderByDescending(seekTenantRequest => seekTenantRequest.RequestCreateTime); return View(query.ToList()); } [HttpPost] public ActionResult IndexSearchKeyWord(string keyWord) { if (keyWord.Equals("Description, Name, Phone or Email") || keyWord.Equals("")) { var query = (from seekTenantRequest in db.SeekTenantRequests select seekTenantRequest) .OrderByDescending(seekTenantRequest => seekTenantRequest.RequestCreateTime); return View("Index", query.ToList()); } else { var query = (from seekTenantRequest in db.SeekTenantRequests where seekTenantRequest.Description.Contains(keyWord) || seekTenantRequest.ContactPersonName.Contains(keyWord) || seekTenantRequest.ContactPersonPhone.Contains(keyWord) || seekTenantRequest.ContactPersonEmail.Contains(keyWord) select seekTenantRequest) .OrderByDescending(seekTenantRequest => seekTenantRequest.RequestCreateTime); return View("Index", query.ToList()); } } [HttpPost] public ActionResult Index(string regionFilter) { if (regionFilter == null || regionFilter.Equals("99")) { var query = (from seekRoomRequest in db.SeekTenantRequests select seekRoomRequest) .OrderByDescending(seekTenantRequest => seekTenantRequest.RequestCreateTime); return View(query.ToList()); } else { Region region = Region.DowntownManhattan; if (regionFilter.Equals("0")) { region = Region.DowntownManhattan; } else if (regionFilter.Equals("1")) { region = Region.MidtownManhattan; } else if (regionFilter.Equals("2")) { region = Region.UptownManhattan; } else if (regionFilter.Equals("3")) { region = Region.UpperManhattan; } else if (regionFilter.Equals("4")) { region = Region.RooseveltIsland; } else if (regionFilter.Equals("5")) { region = Region.Brooklyn; } else if (regionFilter.Equals("6")) { region = Region.Queens; } else if (regionFilter.Equals("7")) { region = Region.Bronx; } else if (regionFilter.Equals("8")) { region = Region.StatenIsland; } else if (regionFilter.Equals("9")) { region = Region.NortheastNewJersey; } else if (regionFilter.Equals("10")) { region = Region.WestchesterCounty; } else if (regionFilter.Equals("11")) { region = Region.LongIsland; } var query = (from seekTenantRequest in db.SeekTenantRequests where seekTenantRequest.RoomRegion == region select seekTenantRequest) .OrderByDescending(seekTenantRequest => seekTenantRequest.RequestCreateTime); return View(query.ToList()); } } // GET: SeekTenant/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SeekTenantRequest seekTenantRequest = db.SeekTenantRequests.Find(id); var profileimg = db.ProfileImages.Where(s => s.Username == seekTenantRequest.Username).Select(s => s.filePath).FirstOrDefault(); if (profileimg == null) { profileimg = "~/images/profile/default.png"; } ViewBag.ProfileImg = profileimg; var a=from s in db.RoomImages where s.SeekTenantRequestId ==id select s.filePath; ViewBag.List = a.ToList(); //Select Similar post, i.e. posts with redard to same region var b =db.SeekTenantRequests .AsEnumerable() .Where(w=>w.RoomType.ToString() == seekTenantRequest.RoomType.ToString() && w.Id!= seekTenantRequest.Id) .Select(i => new KeyValuePair<int, string>(i.Id, i.Title)); ViewBag.Similarlist = b.ToList().Take(5); ViewBag.PostId = id; ViewBag.Controller = "SeekTenant"; if (seekTenantRequest == null) { return HttpNotFound(); } return View(seekTenantRequest); } //POST: Send EmailContent Model public ActionResult SendEmail(EmailContent content) { int id = content.PostId; using (var db = new MetroRentDBContext()) { var post = db.SeekTenantRequests.Find(id); SendEmailLogic.SendEmailtoTenantSeeker(post, content); } return RedirectToAction("Details", "SeekTenant", new { Id = id }); } // GET: SeekTenant/Create public ActionResult Create() { if (!User.Identity.IsAuthenticated) { return RedirectToAction("Register", "Account"); } else { SeekTenantRequestViewModel request = new SeekTenantRequestViewModel(); return View(request); } } // POST: SeekTenant/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(SeekTenantRequestViewModel model) { if (!User.Identity.IsAuthenticated) { return RedirectToAction("Login", "Account"); } else if (ModelState.IsValid) { SeekTenantRequest request = new SeekTenantRequest(); request.Username = User.Identity.Name; request.RoomRegion = model.RoomRegion; request.Address = model.Address; request.MonthlyRentalAmount = model.MonthlyRentalAmount; request.RoomType = model.RoomType; request.Gender = model.Gender; request.Description = model.Description; request.RentalStartDate = model.RentalStartDate; request.RequestCreateTime = DateTime.Now; request.ContactPersonName = model.ContactPersonName; request.ContactPersonPhone = model.ContactPersonPhone; request.ContactPersonEmail = model.ContactPersonEmail; request.IsRequestActive = true; request.Title = "Available room in " + request.RoomRegion.DisplayName() + " for $" + request.MonthlyRentalAmount; request.RoomImages = new List<RoomImage>(); for (int i = 0; i < model.File.Count(); i++) { HttpPostedFileBase file = model.File[i]; var path = String.Empty; var uploadDir = Server.MapPath("~/Images/RoomImages"); //string uploadDir = "~\\Images\\RoomImages"; if (file != null && file.ContentLength > 0) { if (!Directory.Exists(uploadDir)) Directory.CreateDirectory(uploadDir); string extension = Path.GetExtension(file.FileName); //get a unique guid for file name bool IsUnique = false; string guid = null; while (!IsUnique) { guid = Guid.NewGuid().ToString(); var newPath = System.IO.Path.Combine(uploadDir, guid); if (!System.IO.File.Exists(newPath)) { IsUnique = true; } } string newName = guid + extension; path = Path.Combine(uploadDir, newName); file.SaveAs(path); RoomImage image = new RoomImage(); image.filePath = "~/Images/RoomImages/" + newName; image.SeekTenantRequestId = request.Id; request.RoomImages.Add(image); db.RoomImages.Add(image); } } if (model.File.Count() == 1 && model.File.First() == null) { RoomImage image = new RoomImage(); image.filePath = "~/Images/RoomImages/" + "room_default.jpg"; image.SeekTenantRequestId = request.Id; request.RoomImages.Add(image); db.RoomImages.Add(image); } db.SeekTenantRequests.Add(request); db.SaveChanges(); return RedirectToAction("Index"); } return View(model); } // GET: SeekTenant/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SeekTenantRequest seekTenantRequest = db.SeekTenantRequests.Find(id); if (seekTenantRequest == null) { return HttpNotFound(); } return View(seekTenantRequest); } // POST: SeekTenant/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Username,Title,RoomRegion,Address,MonthlyRentalAmount,RoomType,Gender,RentalStartDate,RequestCreateTime,ContactPersonName,ContactPersonPhone,ContactPersonEmail,IsRequestActive")] SeekTenantRequest seekTenantRequest) { if (ModelState.IsValid) { db.Entry(seekTenantRequest).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(seekTenantRequest); } // GET: SeekTenant/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } SeekTenantRequest seekTenantRequest = db.SeekTenantRequests.Find(id); if (seekTenantRequest == null) { return HttpNotFound(); } return View(seekTenantRequest); } // POST: SeekTenant/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { SeekTenantRequest seekTenantRequest = db.SeekTenantRequests.Find(id); var images = from c in db.RoomImages where c.SeekTenantRequestId.Equals(id) select c; foreach (var img in images) { string pathToPhoto = img.filePath; System.IO.File.Delete(pathToPhoto); } db.SeekTenantRequests.Remove(seekTenantRequest); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using UnityEngine; using System.Collections; using UnityEngine.InputSystem; [RequireComponent(typeof(Explodable))] public class ExplodeOnClick : MonoBehaviour { private Explodable _explodable; void Start() { _explodable = GetComponent<Explodable>(); //Invoke(nameof(OnMouseDown),10f); } private void OnMouseEnter() { print("MOUSE"); _explodable.explode(); ExplosionForce ef = GameObject.FindObjectOfType<ExplosionForce>(); ef.doExplosion(transform.position); } public void ReadMouse(InputAction.CallbackContext ctx) { if (ctx.phase == InputActionPhase.Performed && Physics.Raycast( Camera.main.ScreenPointToRay( Mouse.current.position.ReadValue()), out RaycastHit hit)) { OnMouseDown(); Debug.LogFormat("You hit [{0}]", hit.collider.gameObject.name); } } void OnMouseDown() { print("MOUSE"); _explodable.explode(); ExplosionForce ef = GameObject.FindObjectOfType<ExplosionForce>(); ef.doExplosion(transform.position); } private void OnMouseUp() { print("MOUSE"); _explodable.explode(); ExplosionForce ef = GameObject.FindObjectOfType<ExplosionForce>(); ef.doExplosion(transform.position); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Calculadora { public partial class Form1 : Form { String operacao = ""; Double valor = 0; public Form1() { InitializeComponent(); } private void btn0_Click(object sender, EventArgs e) { if (valor == 0) { valor = 0; txtVisor.Text = "0"; } else { txtVisor.Text = txtVisor.Text + "0"; valor = Convert.ToDouble(txtVisor.Text); if (operacao == "+") { txtVisor.Text = "0"; valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { txtVisor.Text = "0"; valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { txtVisor.Text = "0"; valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { txtVisor.Text = "0"; valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn1_Click(object sender, EventArgs e) { if (valor == 0) { valor = 1; txtVisor.Text = "1"; } else { txtVisor.Text = txtVisor.Text + "1"; valor = Convert.ToDouble(txtVisor.Text); if (operacao == "+") { txtVisor.Text = "1"; valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { txtVisor.Text = "1"; valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { txtVisor.Text = "1"; valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { txtVisor.Text = "1"; valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btnSomar_Click(object sender, EventArgs e) { operacao = "+"; } private void btnApagar_Click(object sender, EventArgs e) { txtVisor.Text = "0"; operacao = ""; valor = 0; } private void btn2_Click(object sender, EventArgs e) { if (valor == 0) { valor = 2; txtVisor.Text = "2"; } else { txtVisor.Text = txtVisor.Text + "2"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn3_Click(object sender, EventArgs e) { if (valor == 0) { valor = 3; txtVisor.Text = "3"; } else { txtVisor.Text = txtVisor.Text + "3"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn4_Click(object sender, EventArgs e) { if (valor == 0) { valor = 4; txtVisor.Text = "4"; } else { txtVisor.Text = txtVisor.Text + "4"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor* Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn5_Click(object sender, EventArgs e) { if (valor == 0) { valor = 5; txtVisor.Text = "5"; } else { txtVisor.Text = txtVisor.Text + "5"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor* Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn6_Click(object sender, EventArgs e) { if (valor == 0) { valor = 6; txtVisor.Text = "6"; } else { txtVisor.Text = txtVisor.Text + "6"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn7_Click(object sender, EventArgs e) { if (valor == 0) { valor = 7; txtVisor.Text = "7"; } else { txtVisor.Text = txtVisor.Text + "7"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn8_Click(object sender, EventArgs e) { if (valor == 0) { valor = 8; txtVisor.Text = "8"; } else { txtVisor.Text = txtVisor.Text + "8"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btn9_Click(object sender, EventArgs e) { if (valor == 0) { valor = 9; txtVisor.Text = "9"; } else { txtVisor.Text = txtVisor.Text + "9"; if (operacao == "+") { valor = valor + Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "-") { valor = valor - Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "*") { valor = valor * Convert.ToDouble(txtVisor.Text); operacao = ""; } else if (operacao == "/") { valor = valor / Convert.ToDouble(txtVisor.Text); operacao = ""; } } } private void btnSubtrair_Click(object sender, EventArgs e) { operacao = "-"; } private void btnMultiplicar_Click(object sender, EventArgs e) { operacao = "*"; } private void btnDividir_Click(object sender, EventArgs e) { operacao = "/"; } private void btnResultado_Click(object sender, EventArgs e) { txtVisor.Text = valor.ToString(); } private void btnPoint_Click(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VideoGameDependencyInjectionDemo { class Sword : IWeapon { public Sword(string swordName) { SwordName = swordName; } public string SwordName { get; set; } public void AttackWithMe() { Console.WriteLine(SwordName + " slices through the air, devastating all enemies"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Classes { class EighthClass { static private int num = 0; static public void IncreaseNum() { Console.WriteLine(num); num++; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using V50_IDOMBackOffice.AspxArea.BookingTemplate.Models; using V50_IDOMBackOffice.AspxArea.BookingTemplate.Repositorys; namespace V50_IDOMBackOffice.AspxArea.BookingTemplate.Controllers { public class StatusDataDocumentController { public List<StatusDataDocumentViewModel> Init() { return BookingTemplateDataRepository.GetStatusDataDocumentViewModel(); } public void AddStatusDataDocument(StatusDataDocumentViewModel model) { BookingTemplateDataRepository.AddMasterData(model); } public StatusDataDocumentViewModel GetStatusDataDocument(string id) { return BookingTemplateDataRepository.GetStatusDataDocument(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DistCWebSite.Core.Entities; namespace DistCWebSite.Core.Interfaces { public interface ISFEDistributorRepository { int Add(M_SFEDistributor dist); int Update(M_SFEDistributor dist); int Delete(M_SFEDistributor dist); IEnumerable<M_SFEDistributor> GetList(); M_SFEDistributor GetbySFEDistCode(string distCode); M_SFEDistributor GetbySFEDistName(string distName); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace GradConnect.Models { public class CV { [Key] public int Id { get; set; } public string CvName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public string Street { get; set; } public string City { get; set; } public string Email { get; set; } public string Postcode { get; set; } public DateTime DateOfBirth { get; set; } public string PersonalStatement { get; set; } public CV() { Experiences = new List<Experience>(); Educations = new List<Education>(); References = new List<Reference>(); Skills = new List<Skill>(); } //Navigational properties [InverseProperty("User")] public string UserId { get; set; } public virtual User User { get; set; } public List<Experience> Experiences { get; set; } public List<Education> Educations { get; set; } public List<Reference> References { get; set; } public List<Skill> Skills { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Автошкола { public partial class AddEditCarriersStatusesForm : Form { public AddEditCarriersStatusesForm(AutoschoolDataSet.CarriersStatusesDataTable carriersStatusesDataTable, DataRow row) { InitializeComponent(); this.carriersStatusesDataTable = carriersStatusesDataTable; dataRow = row; } BusinessLogic BusinessLogic = new BusinessLogic(); AutoschoolDataSet.CarriersStatusesDataTable carriersStatusesDataTable; DataRow dataRow; private void AddEditCarriersStatusesForm_Load(object sender, EventArgs e) { if (dataRow != null) { CarrierStatusName_textBox.Text = dataRow["Name"].ToString(); } else { CarrierStatusName_textBox.Text = ""; } } private void AddEditCarriersStatusesForm_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult == DialogResult.OK) { try { if (CarrierStatusName_textBox.Text.Trim() == "") { throw new Exception("Не указано наименование статуса ТС"); } if (dataRow != null) { for (int i = 0; i < carriersStatusesDataTable.Rows.Count; i++) { if ((carriersStatusesDataTable[i][0].ToString() != dataRow[0].ToString()) && (carriersStatusesDataTable[i][1].ToString().ToLower() == CarrierStatusName_textBox.Text.Trim().ToLower())) { throw new Exception("Статус ТС с таким наименованием уже имеется в базе"); } } } else { for (int i = 0; i < carriersStatusesDataTable.Rows.Count; i++) { if (carriersStatusesDataTable[i][1].ToString().ToLower() == CarrierStatusName_textBox.Text.Trim().ToLower()) { throw new Exception("Статус ТС с таким наименованием уже имеется в базе"); } } } } catch (Exception exp) { MessageBox.Show(exp.Message, "Ошибка"); e.Cancel = true; return; } if (dataRow != null) { dataRow["Name"] = CarrierStatusName_textBox.Text; } else { carriersStatusesDataTable.AddCarriersStatusesRow(CarrierStatusName_textBox.Text); } } } private void CarrierStatusName_textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((CarrierStatusName_textBox.TextLength - CarrierStatusName_textBox.SelectionLength) >= 50 && (char)e.KeyChar != (Char)Keys.Back) e.Handled = true; else { if ((char)e.KeyChar == (Char)Keys.Back) return; if ((char)e.KeyChar == (Char)Keys.Space) return; if (char.IsLetter(e.KeyChar)) return; e.Handled = true; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class OptionsController : MonoBehaviour { public Dropdown mapSizeDropdown; public Slider volume; public Slider mouseSensitivity; public Dropdown resolutionDropdown; public Slider screenBrightness; OptionsData options; List<int> mapSizeOptions; void Start() { options = XMLController.Instance.Options; if (options == null) options = new OptionsData(); mapSizeOptions = new List<int>{ 5, 10, 15, 25, 40}; if (mapSizeOptions.Contains(options.mapSize)) mapSizeDropdown.value = mapSizeOptions.FindIndex(x => x == options.mapSize); else if (options.mapSize < 100 && options.mapSize > 1) //If the player finds and edits the save file, I'll allow different map sizes but limit them to less than 100, more could crash their computer. mapSizeOptions.Add(options.mapSize); else options.mapSize = mapSizeOptions[3]; //Select the second largest map by default, I think it's the best compromise between looking good and running well for most computers. mapSizeDropdown.AddOptions(mapSizeOptions.ConvertAll(x => x.ToString())); mapSizeDropdown.value = mapSizeOptions.FindIndex(x => x == options.mapSize); volume.value = options.volume; mouseSensitivity.value = options.mouseSensitivity; screenBrightness.value = options.screenBrightness; int resolutionIndex = -1; foreach (Resolution r in Screen.resolutions) { string name = r.width + " X " + r.height; Dropdown.OptionData option = new Dropdown.OptionData(name); //Check for duplicates, because there should be some with different refresh rates. if (resolutionDropdown.options.Find(x => x.text == name) == null) resolutionDropdown.options.Add(option); else continue; if (r.width == options.screenResolution.width && r.height == options.screenResolution.height) resolutionIndex = resolutionDropdown.options.Count - 1; } //If we haven't found the correct resolution, just use the largest one available. if (resolutionIndex == -1) { resolutionIndex = resolutionDropdown.options.Count - 1; options.screenResolution = Screen.resolutions[resolutionIndex]; } resolutionDropdown.value = resolutionIndex; Screen.SetResolution(options.screenResolution.width, options.screenResolution.height, options.fullscreen); } public void OnMapSizeChange(int optionIndex) { options.mapSize = mapSizeOptions[optionIndex]; } public void OnVolumeChange(float vol) { options.volume = vol; } public void OnMouseSensitivityChange(float sensitivity) { options.mouseSensitivity = sensitivity; } public void OnFullscreenChange(bool isOn) { Screen.fullScreen = isOn; options.fullscreen = isOn; } public void OnResolutionChange(int resolutionIndex) { Resolution selected = Screen.resolutions[resolutionIndex]; Screen.SetResolution(selected.width, selected.height, options.fullscreen); options.screenResolution = selected; } public void OnBrightnessChange(float value) { options.screenBrightness = value; } public void OnOptionsExit() { if (Camera.main.GetComponent<ThirdPersonCamera>()) //ToDo: Find a cheaper and cleaner way to do this. Camera.main.GetComponent<ThirdPersonCamera>().ChangeMouseSensitivity(options.mouseSensitivity); XMLController.Instance.Options = options; XMLController.Instance.Save(); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Aranda.Users.BackEnd.Models; namespace Aranda.Users.BackEnd.Repositories.Definition { public interface IUserRepository { User GetUser(string userName, string password); IEnumerable<User> GetAll(Func<User, bool> filter); User AddUser(User user); Task<User> UpdateUser(User user); bool DeleteUser(int userId); } }
using Microsoft.Extensions.Logging; namespace Shared { public class Logger { private static readonly ILoggerFactory loggerFactory = LoggerFactory.Create(builder => _ = builder.AddConsole().SetMinimumLevel(LogLevel.Trace)); public static void Log() { loggerFactory.CreateLogger("Hi").LogInformation("Hi"); } } }
using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Hyprsoft.Dns.Monitor.Providers { public interface IDnsProvider { Task CheckForChangesAsync(string[] domainNames, CancellationToken cancellationToken); } public abstract class DnsProvider : ApiProvider, IDnsProvider { #region Fields private readonly IPublicIpProvider _publicIpProvider; private readonly Dictionary<string, string> _dnsIpAddresses = new(); #endregion #region Constructors public DnsProvider(ILogger logger, IPublicIpProvider provider) : base(logger) => _publicIpProvider = provider; #endregion #region Methods public async Task CheckForChangesAsync(string[] domainNames, CancellationToken cancellationToken = default) { if (domainNames == null || domainNames.Length <= 0) return; var publicIpAddress = await _publicIpProvider.GetPublicIPAddressAsync(cancellationToken); foreach (var domain in domainNames) { if (!_dnsIpAddresses.ContainsKey(domain)) { _dnsIpAddresses[domain] = await GetDnsIpAddressAsync(domain, cancellationToken); Logger.LogInformation($"Current DNS IP address for domain '{domain}' is '{_dnsIpAddresses[domain]}'."); } if (_dnsIpAddresses[domain].Equals(publicIpAddress)) Logger.LogInformation($"Current public IP address for domain '{domain}' is '{publicIpAddress}'. No change detected."); else { Logger.LogInformation($"New public IP address '{publicIpAddress}' detected. Updating DNS record for domain '{domain}'."); await SetDnsIpAddressAsync(domain, publicIpAddress, cancellationToken); _dnsIpAddresses[domain] = publicIpAddress; Logger.LogInformation($"Domain '{domain}' updated successfully to IP address '{_dnsIpAddresses[domain]}'."); } if (cancellationToken.IsCancellationRequested) break; } // for each domain. } protected abstract Task<string> GetDnsIpAddressAsync(string domainName, CancellationToken cancellationToken); protected abstract Task SetDnsIpAddressAsync(string domainName, string ip, CancellationToken cancellationToken); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BusinessLayer { public class FundingSourceCategoryObject { public int FundingCategoryId { get; set; } public string FundingSource { get; set; } public string FundingSourceCategory { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GPUIntanceTest01 : MonoBehaviour { public Transform prefab; public int instancesNumber = 5000; public float instrancesRadius = 50f; private void Start() { for(int i = 0; i < instancesNumber; i ++) { Transform temp = Instantiate(prefab); temp.localPosition = Random.insideUnitSphere * instrancesRadius; temp.SetParent(this.transform); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DATN_Hoa_Yambi.Models { /// <summary> /// Lớp này viết ra để trả ra sức chịu tải của mình. /// /// </summary> public class ketquasucchiutai { public double Pvl { get; set; } public double Pcpt { get; set; } public double Pspt { get; set; } public double Ntc { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LocusNew.Core.ViewModels { public class HomeGlobalSettingsViewModel { public int CityPart1Id { get; set; } public string CityPart1Name { get; set; } public int CityPart1ListingsNumber { get; set; } public string CityPart1Image { get; set; } public string Image1path { get; set; } public int CityPart2Id { get; set; } public string CityPart2Name { get; set; } public int CityPart2ListingsNumber { get; set; } public string CityPart2Image { get; set; } public string Image2path { get; set; } public int CityPart3Id { get; set; } public string CityPart3Name { get; set; } public int CityPart3ListingsNumber { get; set; } public string CityPart3Image { get; set; } public string Image3path { get; set; } public int CityPart4Id { get; set; } public string CityPart4Name { get; set; } public int CityPart4ListingsNumber { get; set; } public string CityPart4Image { get; set; } public string Image4path { get; set; } public int CityPart5Id { get; set; } public string CityPart5Name { get; set; } public int CityPart5ListingsNumber { get; set; } public string CityPart5Image { get; set; } public string Image5path { get; set; } public int CityPart6Id { get; set; } public string CityPart6Name { get; set; } public int CityPart6ListingsNumber { get; set; } public string CityPart6Image { get; set; } public string Image6path { get; set; } public string CityPart1NumberOfListings { get; set; } public string CityPart2NumberOfListings { get; set; } public string CityPart3NumberOfListings { get; set; } public string CityPart4NumberOfListings { get; set; } public string CityPart5NumberOfListings { get; set; } public string CityPart6NumberOfListings { get; set; } } }
using MobileCollector.model; using System; namespace MobileCollector { internal static class Extensions { internal static string toText(this System.IO.Stream stream) { var mstream = new System.IO.MemoryStream(); stream.CopyTo(mstream); var bytes = mstream.ToArray(); return System.Text.Encoding.Default.GetString(bytes); } internal static byte[] toByteArray(this System.IO.Stream stream) { var mstream = new System.IO.MemoryStream(); stream.CopyTo(mstream); var bytes = mstream.ToArray(); return bytes; } internal static string decryptAndGetApiSetting(this System.Json.JsonValue jsonObject, string settingString) { var value = jsonObject[settingString]; if (Constants.ENCRYPTED_ASSETS.Contains(settingString)){ //we decrypt return JhpSecurity.Decrypt(value); } return value; } } }
using Quantum; using Quantum.Operations; using System; using System.Numerics; using System.Collections.Generic; namespace QuantumConsole { public class QuantumTest { public static void Main() { QuantumComputer comp = QuantumComputer.GetInstance(); Register x = comp.NewRegister(0, 2); x.Hadamard(1); x.CNot(target: 0, control: 1); } } }
using System.Collections.Generic; using System; using com.Sconit.Entity.SI.SD_ORD; namespace com.Sconit.Service.SI { public interface ISD_OrderMgr { Entity.SI.SD_ORD.OrderMaster GetOrderByOrderNoAndExtNo(string orderNo, bool includeDetail); Entity.SI.SD_ORD.OrderMaster GetOrder(string orderNo, bool includeDetail); Entity.SI.SD_ORD.OrderMaster GetOrderKeyParts(string orderNo); Entity.SI.SD_ORD.IpMaster GetIp(string ipNo, bool includeDetail); Entity.SI.SD_ORD.IpMaster GetIpByWmsIpNo(string wmsIpNo, bool includeDetail); Entity.SI.SD_ORD.SequenceMaster GetSeq(string seqNo, bool includeDetail); Entity.SI.SD_ORD.PickListMaster GetPickList(string pickListNo, bool includeDetail); string ShipPickList(string pickListNo); Entity.SI.SD_ORD.MiscOrderMaster GetMis(string MisNo); void StartPickList(string pickListNo); void BatchUpdateMiscOrderDetails(string miscOrderNo, IList<string> addHuIdList); void ConfirmMiscOrder(string miscOrderNo, IList<string> addHuIdList); void QuickCreateMiscOrder(IList<string> addHuIdList, string locationCode, string binCode, int type); void StartVanOrder(string orderNo, string location, IList<com.Sconit.Entity.SI.SD_INV.Hu> feedHuList); void StartVanOrder(string orderNo, string feedOrderNo); void PackSequenceOrder(string sequenceNo, List<string> huIdList); void UnPackSequenceOrder(string sequenceNo); void ShipSequenceOrder(string sequenceNo); void ShipSequenceOrderBySupplier(string sequenceNo); Entity.SI.SD_ORD.InspectMaster GetInspect(string inspectNo, bool includeDetail); Entity.SI.SD_INV.Hu GetHuByOrderNo(string orderNo); Boolean VerifyOrderCompareToHu(string orderNo, string huId); List<string> GetProdLineStation(string orderNo, string huId); #region 投料 //投料到生产线 //void FeedProdLineRawMaterial(string productLine, string productLineFacility, string[][] huDetails, bool isForceFeed, DateTime? effectiveDate); void FeedProdLineRawMaterial(string productLine, string productLineFacility, string location, List<com.Sconit.Entity.SI.SD_INV.Hu> hus, bool isForceFeed, DateTime? effectiveDate); //投料到生产单 //void FeedOrderRawMaterial(string orderNo, string[][] huDetails, bool isForceFeed, DateTime? effectiveDate); void FeedOrderRawMaterial(string orderNo, string location, List<com.Sconit.Entity.SI.SD_INV.Hu> hus, bool isForceFeed, DateTime? effectiveDate); //KIT投料到生产单 void FeedKitOrder(string orderNo, string kitOrderNo, bool isForceFeed, DateTime? effectiveDate); //生产单投料到生产单 void FeedProductOrder(string orderNo, string productOrderNo, bool isForceFeed, DateTime? effectiveDate); #endregion void ReturnOrderRawMaterial(string orderNo, string traceCode, int? operation, string opReference, string[][] huDetails, DateTime? effectiveDate); void ReturnProdLineRawMaterial(string productLine, string productLineFacility, string[][] huDetails, DateTime? effectiveDate); string DoShipOrder(List<Entity.SI.SD_ORD.OrderDetailInput> orderDetailInputList, DateTime? effDate, bool isOpPallet = false); string DoReceiveOrder(List<Entity.SI.SD_ORD.OrderDetailInput> orderDetailInputList, DateTime? effDate); string DoReceiveIp(List<Entity.SI.SD_ORD.IpDetailInput> ipDetailInputList, DateTime? effDate); void DoReceiveKit(string kitNo, DateTime? effDate); void DoTransfer(Entity.SI.SD_SCM.FlowMaster flowMaster, List<Entity.SI.SD_SCM.FlowDetailInput> flowDetailInputList, bool isFifo = true, bool isOpPallet = false); void DoPickList(List<Entity.SI.SD_ORD.PickListDetailInput> pickListDetailInputList); void DoAnDon(List<AnDonInput> anDonInputList); void DoKitOrderScanKeyPart(string[][] huDetails, string orderNo); AnDonInput GetKanBanCard(string cardNo); void DoInspect(List<string> huIdList, DateTime? effDate); void DoWorkersWaste(List<string> huIdList, DateTime? effDate); void DoRepackAndShipOrder(List<Entity.SI.SD_INV.Hu> huList, DateTime? effDate); void DoJudgeInspect(Entity.SI.SD_ORD.InspectMaster inspectMaster, List<string> HuIdList, DateTime? effDate); void DoReturnOrder(string flowCode, List<string> huIdList, DateTime? effectiveDate); void KitOrderOffline(string kitOrderNo, List<Entity.SI.SD_ORD.OrderDetailInput> orderDetailInputList, IList<string> feedKitOrderNoList, DateTime? effectiveDate); List<com.Sconit.Entity.SI.SD_ORD.OrderMaster> GetKitBindingOrders(string orderNo); List<string> GetItemTraces(string orderNo); void DoItemTrace(string orderNo, List<string> huIdList); void CancelItemTrace(string orderNo, List<string> huIdList); Entity.SI.SD_INV.Hu DoReceiveProdOrder(string huId); Entity.SI.SD_INV.Hu CancelReceiveProdOrder(string huId); void DoReceiveProdOrder(List<string> huIdList); Entity.SI.SD_INV.Hu DoFilter(string huId, decimal outQty); Entity.SI.SD_INV.Hu StartAging(string huId); Entity.SI.SD_INV.Hu DoAging(string huId); void RecSmallChkSparePart(string huId, string spareItem, string userCode); } }
using EngineLibrary.Graphics; using EngineLibrary.Scripts; using GameLibrary.Components; using GameLibrary.Scripts.Game; using SoundLibrary; namespace GameLibrary.Scripts.Bonuses { /// <summary> /// Класс бонуса, дающего стрелы игроку /// </summary> public class StandartArrowBonus : Script { private SharpAudioVoice _voice; private ColliderComponent _colliderComponent; private ArrowType _type; private int _arrowsCount; /// <summary> /// Конструктор класса /// </summary> /// <param name="type">Тип добавляемых стрел</param> /// <param name="arrowsCount">Количество добавляемых стрел</param> public StandartArrowBonus(SharpAudioVoice voice, ArrowType type, int arrowsCount) { _voice = voice; _type = type; _arrowsCount = arrowsCount; } /// <summary> /// Инициализация класса /// </summary> public override void Init() { _colliderComponent = GameObject.GetComponent<ColliderComponent>(); } /// <summary> /// Обновление поведения /// </summary> /// <param name="delta">Время между кадрами</param> public override void Update(float delta) { if(_colliderComponent.CheckIntersects(out Game3DObject player, "player")) { _voice.Stop(); _voice.Play(); player.GetComponent<PlayerComponent>().AddArrows(_type, _arrowsCount); GameObject.Parent.RemoveChildren(GameObject); _colliderComponent.RemoveCollisionFromScene(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PabloSr_Patrick_Movement : MonoBehaviour { public int speed = 3; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { //When I press left arrow if (Input.GetKey(KeyCode.LeftArrow)) { //Delta time //60fps -> 1/60 frame = 0.016 //30 fps -> 1/30 frame = 0.3333 //3 units per second. Vector3 newPos = new Vector3(-speed*Time.deltaTime, 0, 0); transform.position = transform.position + newPos; } //When I press left arrow else if (Input.GetKey(KeyCode.RightArrow)) { //Delta time //60fps -> 1/60 frame = 0.016 //30 fps -> 1/30 frame = 0.3333 //3 units per second. Vector3 newPos = new Vector3(speed * Time.deltaTime, 0, 0); transform.position = transform.position + newPos; } } }
using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace BridgeProject { public struct ContractStruct { public ContractStruct(int q, CardTrump t, bool c, bool rc) { if((q >= 1 && q <= 7 && (int)t >= 1 && (int)t <= 5 && !(c && rc)) || (q == 0 && t == CardTrump.NotYetDefined && c == false && rc == false)) { this.quantity = q; this.trump = t; this.contra = c; this.recontra = rc; born = true; } else { this.quantity = 0; this.trump = CardTrump.NotYetDefined; this.contra = false; this.recontra = false; born = false; } } bool born; public bool Born { get { return born; } set { if (value == true) { if (!this.Defined) this.Refresh(); } else { Empty(); } } } int quantity; public int Quantity { get { return quantity; } set { if (NoContract == false) { if (IsQuantityGood(value)) quantity = value; } } } public bool IsQuantityGood(int q) { return (q >= 1 && q <= 7); } CardTrump trump; public CardTrump Trump { get { return trump; } set { if (NoContract == false) { if (IsTrumpGood(value)) trump = value; } } } public bool IsTrumpGood(CardTrump t) { return ((int)t >= 1 && (int)t <= 5); } public bool contra; public bool Contra { get { return contra; } set { if (NoContract == false) { contra = value; if (contra) recontra = false; } } } public bool recontra; public bool ReContra { get { return recontra; } set { if (NoContract == false) { recontra = value; if (recontra) contra = false; } } } public static bool operator ==(ContractStruct c1, ContractStruct c2) { return c1.Equals(c2); } public static bool operator !=(ContractStruct c1, ContractStruct c2) { return !c1.Equals(c2); } public override bool Equals(object obj) { if (obj.GetType() != typeof(ContractStruct)) return false; ContractStruct cs = (ContractStruct)obj; return (this.quantity == cs.quantity && this.trump == cs.trump && this.Contra == cs.Contra && this.ReContra == cs.ReContra && this.Born == cs.Born); } public bool Defined { get { return ((born && IsQuantityGood(this.quantity) && IsTrumpGood(this.trump) && !(Contra == true && ReContra == true)) || NoContract); } } public void Empty() { quantity = 0; trump = CardTrump.NotYetDefined; Contra = false; ReContra = false; born = false; } public void Refresh() { quantity = 1; trump = CardTrump.NotYetDefined; Contra = false; ReContra = false; born = true; } public bool NoContract { get { return (born == true && quantity == 0 && trump == CardTrump.NotYetDefined && contra == false && recontra == false); } set { if (value == true) { quantity = 0; trump = CardTrump.NotYetDefined; Contra = false; ReContra = false; born = true; } else { if (NoContract) Refresh(); } } } public String GetString1() { /*if (!Defined) return ""; else*/ return (NoContract ? "-" : quantity.ToString()); } public String GetString2() { /*if (!Defined) return ""; else*/ { switch (Trump) { case CardTrump.Hearts: return "♥"; case CardTrump.Diamonds: return "♦"; case CardTrump.Clubs: return "♣"; case CardTrump.Spades: return "♠"; case CardTrump.NT: return "NT"; default: return ""; } } } public String GetString3() { /*if (!Defined) return ""; else*/ return (this.ReContra ? "**" : (this.Contra ? "*" : "")); } public override string ToString() { return (!Defined ? "" : (GetString1() + GetString2() + GetString3())); } }; public class Contract : BaseChangedData, ISQLSerialize { // Инкапсулируем структуру: ContractStruct val; public ContractStruct GetStruct() { return val; } // Конструкторы: public Contract() { val.Empty(); } public Contract(int q, CardTrump tr, bool co, bool reco) { val = new ContractStruct(q, tr, co, reco); } public Contract(ContractStruct cs) { val = cs; } public Contract(Contract c) { val = c.GetStruct(); } // Change public void Empty() { ContractStruct oldc = val; val.Empty(); if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } public void Refresh() { ContractStruct oldc = val; val.Refresh(); if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } public bool NoContract { get { return val.NoContract; } set { ContractStruct oldc = val; val.NoContract = value; if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } } public void ChangeContract(int q, CardTrump tr, bool co, bool reco) { this.ChangeContract(new ContractStruct(q, tr, co, reco)); } public void ChangeContract(ContractStruct cs) { ContractStruct oldc = val; val = cs; if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } // Copy public void CopyContract(Contract c) { ContractStruct oldc = val; val = c.GetStruct(); if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } // Get&Set public int Quantity { get { return val.Quantity; } set { ContractStruct oldc = val; val.Quantity = value; if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } } public CardTrump Trump { get { return val.Trump; } set { ContractStruct oldc = val; val.Trump = value; if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } } public bool Contra { get { return val.Contra; } set { ContractStruct oldc = val; val.Contra = value; if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } } public bool ReContra { get { return val.ReContra; } set { ContractStruct oldc = val; val.ReContra = value; if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } } // Получение строкового представления контракта public String GetString1() { return val.GetString1(); } public String GetString2() { return val.GetString2(); } public String GetString3() { return val.GetString3(); } public override String ToString() { return (val.ToString()); } // Born & Defined public bool Born { get { return val.Born; } set { ContractStruct oldc = val; val.Born = value; if (oldc != val && IsChangedHandlers()) OnChanged(this, new ChangedEventsArgs(oldc, val)); } } override public bool IsDefined() { return val.Defined; } // Событие изменения контракта /*public class ContractEventsArgs : EventArgs { public ContractStruct OldContractStruct; public ContractStruct NewContractStruct; public ContractEventsArgs(ContractStruct oldc, ContractStruct newc) { OldContractStruct = oldc; NewContractStruct = newc; } } public delegate void ContractHandler(object sender, ContractEventsArgs e); public event ContractHandler ContractChanged;*/ // Сериализация SQL // (3 бита на Quantity, 3 бита на CardTrump, 1 бит на Contra, 1 бит на ReContra) public void _FromDataBase(object v) { if (v == DBNull.Value) { this.Empty(); } else { byte c = (byte) v; this.ChangeContract((int)(c & 7), (CardTrump)((c >> 3) & 7), (((c >> 6) & 1) == 1 ? true : false), (((c >> 7) & 1) == 1 ? true : false)); } } public object _ToDataBase() { if (!this.IsDefined()) { //return "NULL"; return DBNull.Value; } else { byte c = 0; c |= (byte)(this.Quantity & 7); c |= (byte)(((byte)this.Trump & 7) << 3); if (this.Contra) c |= (1 << 6); if (this.ReContra) c |= (1 << 7); //return c.ToString(); return c; } } // Clear public override void Clear() { this.Empty(); } } public partial class ContractSelectControl : BaseSelectControl, IAttachData<Contract>, IDetachData { Font m_font_for_suits; Contract m_contract; public ContractSelectControl() { InitializeComponent(); this.m_contract = null; } public void AttachData(Contract c) { // Присоединение контракта: if (this.m_contract == null) { this.m_contract = c; this.m_contract.Changed += OnDataChanged; // Отрисовать: this.Invalidate(); } } public void DetachData(bool _inv) { // Отсоединение контракта: if (this.m_contract != null) { this.m_contract.Changed -= OnDataChanged; this.m_contract = null; // Отрисовать: if (_inv) this.Invalidate(); } // Закрыть селектор, если он открыт подо мной: if (SelectorOpened) CloseSelector(false); } protected void OnDataChanged(object sender, BaseChangedData.ChangedEventsArgs e) { // ? Возможно: если изменения извне (загрузка из файла), закрыть (или обновить - сложнее) селектор this.Invalidate(); } protected override void OpenSelector() { if (m_contract == null) return; ContractSelector.GetInstance().OpenMe(this, this.SelectorCover, this.ParentForm, this.m_contract); ContractSelector.GetInstance().Closing += OnSelectorClosing; ContractSelector.GetInstance().Closed += OnSelectorClosed; this.SelectorOpened = true; } protected override void CloseSelector(bool saveBeforeClose) { ContractSelector.GetInstance().CloseMe(saveBeforeClose); } void OnSelectorClosing(object sender, SelectorClosingEventArgs e) { //if (!(sender as ContractSelector).IsAttachedToThisControl(this)) // return; if (e != null && e.bSaveBeforeClose == true && this.m_contract != null && e.dataToSaveBeforeClosed != null) { this.m_contract.CopyContract(e.dataToSaveBeforeClosed as Contract); } } void OnSelectorClosed(object sender, EventArgs e) { //if (!(sender as ContractSelector).IsAttachedToThisControl(this)) // return; ContractSelector.GetInstance().Closing -= OnSelectorClosing; ContractSelector.GetInstance().Closed -= OnSelectorClosed; this.SelectorOpened = false; } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); Graphics g = pe.Graphics; // рисуем текст, если контракт определен if (this.m_contract != null && this.m_contract.IsDefined()) { if (this.Focused || SelectorOpened) m_rectf_String.Width -= splitter_width; bool nospace = false; SizeF szf1 = g.MeasureString(m_contract.GetString1(), this.Font); SizeF szf2 = g.MeasureString(m_contract.GetString2(), (m_contract.Trump == CardTrump.NT) ? this.Font : m_font_for_suits); SizeF szf3 = g.MeasureString(m_contract.GetString3(), this.Font); RectangleF rf = new RectangleF(m_rectf_String.X + text_left_offset, m_rectf_String.Y + (m_rectf_String.Height - szf1.Height) / 2, szf1.Width, szf1.Height); if (rf.Right > m_rectf_String.Right) { nospace = true; rf.Width = m_rectf_String.Right - rf.X; } g.DrawString(m_contract.GetString1(), this.Font, m_brush_String, rf, new StringFormat(StringFormatFlags.NoWrap)); if (!nospace) { rf = new RectangleF(rf.Right, 1 + (m_rectf_String.Height - szf2.Height) / 2, szf2.Width, szf2.Height); if (rf.Right > m_rectf_String.Right) { nospace = true; rf.Width = m_rectf_String.Right - rf.X; } g.DrawString(m_contract.GetString2(), (m_contract.Trump == CardTrump.NT) ? this.Font : m_font_for_suits, (m_contract.Trump == CardTrump.Hearts || m_contract.Trump == CardTrump.Diamonds) ? m_brush_String_RED : m_brush_String_BLACK, rf, new StringFormat(StringFormatFlags.NoWrap)); } if (!nospace) { rf = new RectangleF(rf.Right, 1 + (m_rectf_String.Height - szf3.Height) / 2, szf3.Width, szf3.Height); if (rf.Right > m_rectf_String.Right) { nospace = true; rf.Width = m_rectf_String.Right - rf.X; } g.DrawString(m_contract.GetString3(), this.Font, m_brush_String, rf, new StringFormat(StringFormatFlags.NoWrap)); } if (this.Focused || SelectorOpened) m_rectf_String.Width += splitter_width; } } } }
using CreditasChallenge.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CreditasChallenge.Helpers.Tests { [TestClass] public class GuardianTest { [TestMethod] [ExpectedException(typeof(Exception))] public void Guardian_ForNullOrEmpty_ErrorWhenIsEmpty() { Guardian.ForNullOrEmpty(string.Empty, "Value cant be empty"); } [TestMethod] [ExpectedException(typeof(Exception))] public void Guardian_ForNullOrEmpty_ErrorWhenIsNull() { Guardian.ForNullOrEmpty(null, "Value cant be null"); } [TestMethod] [ExpectedException(typeof(Exception))] public void Guardian_ForStringLenght_OutSideLenght() { Guardian.ForStringLength("abcde", 4, "Value cant be greater then Max Lenght"); } [TestMethod] public void Guardian_ForStringLenght_InsideLenght() { Guardian.ForStringLength("abcd", 4, "Value cant be greater then Max Lenght"); } } }
using System.Collections.Generic; using Problem1.Domain; namespace Problem1.Application { public class TripCardService : ITripCardService { private readonly IEqualityComparer<string> _tripCardStringComparer; public TripCardService(IEqualityComparer<string> tripCardStringComparer) { _tripCardStringComparer = tripCardStringComparer; } private class TripCardElement { public TripCardElement(TripCard tripCard, int sourceIndex) { TripCard = tripCard; SourceIndex = sourceIndex; } public TripCard TripCard { get; } public int SourceIndex { get; } } public IReadOnlyList<TripCard> OrderTripCards(IReadOnlyList<TripCard> tripCards) { var destinationToTripCard = new Dictionary<string, TripCardElement>( tripCards.Count, _tripCardStringComparer); // ToDo: обработка InvalidOperationException => набор не соответствует условиям задачи // (имеется две карты с одним и тем же городом назначения) for (var i = 0; i < tripCards.Count; i++) destinationToTripCard.Add(tripCards[i].Destination, new TripCardElement(tripCards[i], i)); // определяем для текущей карты индекс следующего элемента в исходной последовательности var nextTripCardIndex = new int[tripCards.Count]; var firstTripCardIndex = -1; for (var i = 0; i < tripCards.Count; i++) { TripCardElement previousTripCard; if (destinationToTripCard.TryGetValue(tripCards[i].Source, out previousTripCard)) // для предыдущего города текущий элемент - это следующий nextTripCardIndex[previousTripCard.SourceIndex] = i; // Если карточка с указанным городом назначения отсутствует, то текущая карточка - последняя else firstTripCardIndex = i; } // Используя полученную перестановку, строим по исходному // списку элементов новый, но уже упорядоченный в указанной последовательности var sortedTripCards = new List<TripCard>(tripCards.Count); for(int i = 0; i < tripCards.Count; i++) { var currentTripCard = tripCards[firstTripCardIndex]; sortedTripCards.Add(currentTripCard); firstTripCardIndex = nextTripCardIndex[firstTripCardIndex]; } return sortedTripCards; // Послесловие // -------------------------------------------------- // Разумеется, для реализованного алгоритма можно значительно улучшить оценку в худшем, // заменив хэширование на структуру данных, специально предназначенную для работы со строками, - префиксное дерево (Trie) // В этом случае названная оценка O(N * Avg(L)) в среднем превратится в O(N * Max(L)) в худшем. // // НО без реальной необходимости (кому это надо в тестовом задании?!) реализовывать такое решение мне было банально лень =)) } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FocusStart_TeskTask_Java_.Net_ { public class IncreaseNumberComparer : ICompare { public bool isNotCorrectOrder(string line1, string line2) { return Convert.ToInt32(line1) > Convert.ToInt32(line2); } public bool isNextValid(string line1, string line2) { return Convert.ToInt32(line1) < Convert.ToInt32(line2); } } }
using SMG.Common.Algebra; using SMG.Common.Exceptions; using SMG.Common.Gates; using SMG.Common.Transitions; using SMG.Common.Types; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace SMG.Common.Conditions { /// <summary> /// Condition on a single variable for set of values of this variable. /// </summary> /// <remarks> /// <para>This may be either a static state or a transition condition.</para> /// </remarks> public class StateCondition : Condition, IVariableCondition { #region Properties public Variable Variable { get; private set; } public bool PreWildcard { get; private set; } public bool PostWildcard { get; private set; } public int StateIndex { get { throw new InvalidOperationException(); } } /// <summary> /// Variable input states to which this condition applies. /// </summary> public List<int> StateIndexes { get; private set; } public List<int> PostStateIndexes { get; private set; } public bool IsTransition { get { return PostWildcard || PostStateIndexes.Any(); } } public IVariableCondition Parent { get; private set; } #endregion #region Construction public StateCondition(Variable v) { Variable = v; StateIndexes = new List<int>(); PostStateIndexes = new List<int>(); } public StateCondition(Variable v, int stateindex) : this(v) { StateIndexes.Add(stateindex); } public StateCondition(StateCondition parent) : this(parent.Variable) { Parent = parent; } public override ICondition Clone() { var c = new StateCondition(Variable); c.StateIndexes.AddRange(StateIndexes); c.PreWildcard = PreWildcard; c.PostStateIndexes.AddRange(PostStateIndexes); c.PostWildcard = PostWildcard; c.Freeze(); return c; } #endregion #region Diagnostics public override string ToString() { var sb = new StringBuilder(); sb.Append(Variable.Name); sb.Append("("); sb.Append(Variable.Type.GetStateNames(StateIndexes).ToSeparatorList()); if (PostStateIndexes.Any()) { sb.Append(" => "); sb.Append(Variable.Type.GetStateNames(PostStateIndexes).ToSeparatorList()); } sb.Append(")"); return sb.ToString(); } #endregion #region Public Methods /// <summary> /// Sets the PRE states of a state transition condition. /// </summary> /// <param name="names"></param> public void SetPreStates(IdList names) { StateIndexes.AddRange(Variable.Type.GetIndexesOfNames(names)); PreWildcard = names.Wildcard; } public void SetPreStates(IEnumerable<int> indexes) { StateIndexes.AddRange(indexes); } /// <summary> /// Sets the POST states of a state transition condition. /// </summary> /// <param name="names"></param> public void SetPostStates(IdList names) { PostStateIndexes.AddRange(Variable.Type.GetIndexesOfNames(names)); PostWildcard = names.Wildcard; } public void SetPostStates(IEnumerable<int> indexes) { PostStateIndexes.AddRange(indexes); } public IGate CreateElementaryCondition(int stateindex) { if (Variable.Type.IsBoolean) { return new BooleanCondition(this, stateindex); } else { return new ElementaryCondition(this, stateindex); } } #endregion #region Overrides public override IEnumerable<Transition> GetTransitions() { if (PostStateIndexes.Any()) { yield return new Transition(this) { PreStateIndexes = StateIndexes.ToArray(), NewStateIndexes = PostStateIndexes.ToArray() }; } else if (null != Parent) { /*foreach (var e in Parent.GetTransitions()) { yield return e; }*/ throw new NotImplementedException(); } } protected override void BeforeFreeze() { // extend state conditions with complementary indexes var s0 = this.ToString(); if (!StateIndexes.Any()) { Debug.Assert(PreWildcard); if(!PostStateIndexes.Any()) { throw new CompilerException(ErrorCode.BadCondition, "wildcard requires transition."); } // Debug.Assert(PostStateIndexes.Any()); StateIndexes = Variable.Type.GetExcluding(PostStateIndexes).ToList(); } else if (!PostStateIndexes.Any()) { if (PostWildcard) { Debug.Assert(StateIndexes.Any()); PostStateIndexes = Variable.Type.GetExcluding(StateIndexes).ToList(); } } } /// <summary> /// Decomposes the state condition into its elementary parts. /// </summary> /// <param name="mode"></param> /// <returns></returns> public override IGate Decompose(ConditionMode mode) { Freeze(); if(IsTransition && (mode != ConditionMode.Pre && mode != ConditionMode.Post)) { throw new CompilerException(ErrorCode.BadCondition, "state transition cannot be decomposed into a static gate."); } if (Variable.Type.IsBoolean) { return DecomposeBoolean(mode); } else { return DecomposeSimple(mode); } } private IEnumerable<int> GetStateSource(ConditionMode mode) { IEnumerable<int> source; var post = mode == ConditionMode.Post; if (IsTransition && post) { source = PostStateIndexes; } else { source = StateIndexes; } if (!source.Any()) { throw new Exception("unable to decompose " + this + " empty source (" + mode + ")"); } return source; } private IGate DecomposeBoolean(ConditionMode mode) { var source = GetStateSource(mode).ToArray(); if (source.Length > 1) { throw new CompilerException(ErrorCode.ConditionNeverSatisfied, "boolean state condition never satisfied."); } var c = CreateElementaryCondition(source.First()); Gate.TraceDecompose(this, c, "decompose " + mode); return c; } private IGate DecomposeSimple(ConditionMode mode) { var source = GetStateSource(mode); var it = source.GetEnumerator(); IGate r = null; while (it.MoveNext()) { var e = CreateElementaryCondition(it.Current); if (null == r) { r = e; } else { r = Gate.ComposeOR(r, e); } } Debug.Assert(null != r); Gate.TraceDecompose(this, r, "decompose " + mode); return r; } #endregion } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Modulschool.BusinessLogic; using Modulschool.Models; namespace Modulschool.Controllers { [Route("api/animals")] public class AnimalsController: ControllerBase { private readonly GetAnimalsInfoRequestHandler _getAnimalsInfoRequestHandler; public AnimalsController(GetAnimalsInfoRequestHandler getAnimalsInfoRequestHandler) { _getAnimalsInfoRequestHandler = getAnimalsInfoRequestHandler; } [HttpGet("{id}")] public Task<Animal> GetAnimalInfo(int id) { return _getAnimalsInfoRequestHandler.Handle(id); } /*[HttpPut("{id}")] public Task<Animal> PutAnimalInfo(int id,Animal animal) { return _getAnimalsInfoRequestHandler.PutHandle(id,animal); }*/ [HttpPut("{id}")] public void PutAnimalInfo(int id, Animal animal) { _getAnimalsInfoRequestHandler.PutHandle(id, animal); } } }
using jaytwo.Common.Extensions; using jaytwo.Common.Parse; using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace jaytwo.Common.Test.Parse { [TestFixture] public partial class ParseUtilityTests { private static IEnumerable<TestCaseData> ParseByteAllTestValues() { yield return new TestCaseData("255").Returns(255); yield return new TestCaseData("0").Returns(0); yield return new TestCaseData("256").Throws(typeof(OverflowException)); yield return new TestCaseData("-1").Throws(typeof(OverflowException)); yield return new TestCaseData("0").Returns(0); yield return new TestCaseData("123").Returns(123); yield return new TestCaseData(null).Throws(typeof(ArgumentNullException)); yield return new TestCaseData("").Throws(typeof(FormatException)); yield return new TestCaseData("foo").Throws(typeof(FormatException)); yield return new TestCaseData("123.45").Throws(typeof(OverflowException)); yield return new TestCaseData("$123.00", NumberStyles.Currency).Returns(123); yield return new TestCaseData("123.00", NumberStyles.Number).Returns(123); yield return new TestCaseData("123,00", new CultureInfo("pt-BR")).Returns(123); yield return new TestCaseData("123.00", new CultureInfo("en-US")).Returns(123); yield return new TestCaseData("R$123,00", NumberStyles.Currency, new CultureInfo("pt-BR")).Returns(123); yield return new TestCaseData("$123.00", NumberStyles.Currency, new CultureInfo("en-US")).Returns(123); } private static IEnumerable<TestCaseData> ParseByteGoodTestValues() { foreach (var testCase in TestUtility.GetTestCasesWithArgumentTypes<string>(ParseByteAllTestValues())) if (testCase.HasExpectedResult) yield return testCase; } private static IEnumerable<TestCaseData> ParseByteBadTestValues() { foreach (var testCase in TestUtility.GetTestCasesWithArgumentTypes<string>(ParseByteAllTestValues())) if (testCase.ExpectedException != null) yield return testCase; } private static IEnumerable<TestCaseData> TryParseByteBadTestValues() { foreach (var testCase in ParseByteBadTestValues()) yield return new TestCaseData(testCase.Arguments).Returns(null); } private static IEnumerable<TestCaseData> ParseByte_With_styles_GoodTestValues() { return TestUtility.GetTestCasesWithArgumentTypes<string, NumberStyles>(ParseByteAllTestValues()); } private static IEnumerable<TestCaseData> ParseByte_With_formatProvider_GoodTestValues() { return TestUtility.GetTestCasesWithArgumentTypes<string, IFormatProvider>(ParseByteAllTestValues()); } private static IEnumerable<TestCaseData> ParseByte_With_styles_formatProvider_GoodTestValues() { return TestUtility.GetTestCasesWithArgumentTypes<string, NumberStyles, IFormatProvider>(ParseByteAllTestValues()); } [Test] [TestCaseSource("ParseByteGoodTestValues")] public byte ParseUtility_ParseByte(string stringValue) { return ParseUtility.ParseByte(stringValue); } [Test] [ExpectedException] [TestCaseSource("ParseByteBadTestValues")] public byte ParseUtility_ParseByte_Exceptions(string stringValue) { return ParseUtility.ParseByte(stringValue); } [Test] [TestCaseSource("ParseByte_With_styles_formatProvider_GoodTestValues")] public byte ParseUtility_ParseByte_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return ParseUtility.ParseByte(stringValue, styles, formatProvider); } [Test] [TestCaseSource("ParseByte_With_styles_GoodTestValues")] public byte ParseUtility_ParseByte_With_styles(string stringValue, NumberStyles styles) { return ParseUtility.ParseByte(stringValue, styles); } [Test] [TestCaseSource("ParseByte_With_formatProvider_GoodTestValues")] public byte ParseUtility_ParseByte_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return ParseUtility.ParseByte(stringValue, formatProvider); } [Test] [TestCaseSource("ParseByteGoodTestValues")] [TestCaseSource("TryParseByteBadTestValues")] public byte? ParseUtility_TryParseByte(string stringValue) { return ParseUtility.TryParseByte(stringValue); } [Test] [TestCaseSource("ParseByte_With_styles_formatProvider_GoodTestValues")] public byte? ParseUtility_TryParseByte_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return ParseUtility.TryParseByte(stringValue, styles, formatProvider); } [Test] [TestCaseSource("ParseByte_With_styles_GoodTestValues")] public byte? ParseUtility_TryParseByte_With_styles(string stringValue, NumberStyles styles) { return ParseUtility.TryParseByte(stringValue, styles); } [Test] [TestCaseSource("ParseByte_With_formatProvider_GoodTestValues")] public byte? ParseUtility_TryParseByte_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return ParseUtility.TryParseByte(stringValue, formatProvider); } [Test] [TestCaseSource("ParseByteGoodTestValues")] public byte StringExtensions_ParseByte(string stringValue) { return stringValue.ParseByte(); } [Test] [ExpectedException] [TestCaseSource("ParseByteBadTestValues")] public byte StringExtensions_ParseByte_Exceptions(string stringValue) { return stringValue.ParseByte(); } [Test] [TestCaseSource("ParseByte_With_styles_formatProvider_GoodTestValues")] public byte StringExtensions_ParseByte_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return stringValue.ParseByte(styles, formatProvider); } [Test] [TestCaseSource("ParseByte_With_styles_GoodTestValues")] public byte StringExtensions_ParseByte_With_styles(string stringValue, NumberStyles styles) { return stringValue.ParseByte(styles); } [Test] [TestCaseSource("ParseByte_With_formatProvider_GoodTestValues")] public byte StringExtensions_ParseByte_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return stringValue.ParseByte(formatProvider); } [Test] [TestCaseSource("ParseByteGoodTestValues")] [TestCaseSource("TryParseByteBadTestValues")] public byte? StringExtensions_TryParseByte(string stringValue) { return stringValue.TryParseByte(); } [Test] [TestCaseSource("ParseByte_With_styles_formatProvider_GoodTestValues")] public byte? StringExtensions_TryParseByte_With_styles_formatProvider(string stringValue, NumberStyles styles, IFormatProvider formatProvider) { return stringValue.TryParseByte(styles, formatProvider); } [Test] [TestCaseSource("ParseByte_With_styles_GoodTestValues")] public byte? StringExtensions_TryParseByte_With_styles(string stringValue, NumberStyles styles) { return stringValue.TryParseByte(styles); } [Test] [TestCaseSource("ParseByte_With_formatProvider_GoodTestValues")] public byte? StringExtensions_TryParseByte_With_formatProvider(string stringValue, IFormatProvider formatProvider) { return stringValue.TryParseByte(formatProvider); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PartController : MonoBehaviour { public Coordinate CurrentPos = new Coordinate(); public Coordinate InitPos = new Coordinate(); public ComponentType type; public void SetPos(int _x , int _y) { CurrentPos.x = _x; CurrentPos.y = _y; } public void SetInitPos(int _x, int _y) { InitPos.x = _x; InitPos.y = _y; SetPos(_x,_y); } public void SetPos(Coordinate pos) { CurrentPos.x = pos.x; CurrentPos.y = pos.y; } }
using System; using GatewayEDI.Logging; using GatewayEDI.Logging.Formatters; namespace RealtimeLoggingFacade { /// <summary> /// An implementation of the <see cref="ILog"/> interface which logs messages via the log4net framework. /// </summary> public class Log4netLog : FormattableLogBase { /// <summary> /// The log4net log which this class wraps. /// </summary> private readonly log4net.ILog log; /// <summary> /// Constructs an instance of <see cref="Log4netLog"/> by wrapping a log4net log. /// </summary> /// <param name="log">The log4net log to wrap</param> internal Log4netLog(log4net.ILog log) : base(SingleLineFormatter.Instance) { this.log = log; } /// <summary> /// Logs the given message. /// Output depends on the associated log4net configuration. /// </summary> /// <param name="item">A <see cref="LogItem"/> which encapsulates information to be logged.</param> /// <exception cref="ArgumentNullException">If <paramref name="item"/> is a null reference.</exception> public override void Write(LogItem item) { if (item == null) throw new ArgumentNullException("item"); string message = FormatItem(item); switch (item.LogLevel) { case LogLevel.Fatal: log.Fatal(message, item.Exception); break; case LogLevel.Error: log.Error(message, item.Exception); break; case LogLevel.Warn: log.Warn(message, item.Exception); break; case LogLevel.Info: log.Info(message, item.Exception); break; case LogLevel.Debug: log.Debug(message, item.Exception); break; default: log.Info(message, item.Exception); break; } } /// <summary> /// Overriden to delegate to the log4net IsXxxEnabled properties. /// </summary> protected override bool IsLogLevelEnabled(LogLevel level) { switch (level) { case LogLevel.Debug: return log.IsDebugEnabled; case LogLevel.Error: return log.IsErrorEnabled; case LogLevel.Fatal: return log.IsFatalEnabled; case LogLevel.Info: return log.IsInfoEnabled; case LogLevel.Warn: return log.IsWarnEnabled; default: return true; } } #region NDC /// <summary> /// Pushes a new context message on to the stack implementation of the underlying logger. /// </summary> /// <param name="message">The new context message.</param> /// <returns>An IDisposable reference to the stack.</returns> public override IDisposable Push(string message) { return log4net.ThreadContext.Stacks["NDC"].Push(message); } /// <summary> /// Pops a context message off of the stack implementation of the underlying logger. /// </summary> /// <returns>The context message that was on the top of the stack.</returns> public override string Pop() { return log4net.ThreadContext.Stacks["NDC"].Pop(); } /// <summary> /// Clears all the contextual information held on the stack implementation of the underlying logger. /// </summary> public override void ClearNdc() { log4net.ThreadContext.Stacks["NDC"].Clear(); } #endregion #region MDC /// <summary> /// Add an entry to the contextual properties of the underlying logger. /// </summary> /// <param name="key">The key to store the value under.</param> /// <param name="value">The value to store.</param> public override void Set(string key, string value) { log4net.ThreadContext.Properties[key] = value; } /// <summary> /// Gets the context value identified by the <paramref name="key" /> parameter. /// </summary> /// <param name="key">The key to lookup in the underlying logger.</param> /// <returns>The value of the named context property.</returns> public override string Get(string key) { object obj = log4net.ThreadContext.Properties[key]; if (obj == null) { return null; } return obj.ToString(); } /// <summary> /// Removes the key value mapping for the key specified. /// </summary> /// <param name="key">The key to remove.</param> public override void Remove(string key) { log4net.ThreadContext.Properties.Remove(key); } /// <summary> /// Clear all entries in the underlying logger. /// </summary> public override void ClearMdc() { log4net.ThreadContext.Properties.Clear(); } #endregion } }
using System.Collections.Generic; namespace Algorithms.Lib.Interfaces { public interface IGraph : IOrgraph { IReadOnlyCollection<IEdge> Edges { get; } void RemoveEdge(IEdge edge); } }
namespace Fingo.Auth.Domain.Users.Interfaces { public interface IActivateByActivationToken { void Invoke(string activationToken); } }
namespace Pentagon.Extensions.Localization.Interfaces { using JetBrains.Annotations; public interface ICultureContextWriter { void SetLanguage([NotNull] string uiCulture, string culture = null); } }
using System; using System.Collections.Generic; /// <summary> /// Separa classes de uma forma em que elas possam ser chamadas de forma recursiva. /// Classes devem ser possível de serem dispostas em formato de tree. /// </summary> public sealed class Composite : IDesingPattern { public void RunPattern() { // root // / \ // b1 b2 // \ // b3 var root = new CompositeDemo.Branch(); var b1 = new CompositeDemo.Branch(); var b2 = new CompositeDemo.Branch(); var b3 = new CompositeDemo.Branch(); root.Add(b1); root.Add(b2); b2.Add(b3); b1.Add(new CompositeDemo.Leaf(2)); b2.Add(new CompositeDemo.Leaf(2)); b3.Add(new CompositeDemo.Leaf(2)); Console.WriteLine(root.Call()); } } public class CompositeDemo { public interface IComponent { bool IsComposite { get; } virtual void Add(IComponent component) { } virtual void Remove(IComponent component) { } int Call(); } public class Leaf : IComponent { readonly int value; public bool IsComposite { get; } = false; public Leaf(int value) => this.value = value; public int Call() => value; } public class Branch : IComponent { protected List<IComponent> children = new List<IComponent>(); public bool IsComposite { get; } = true; public void Add(IComponent component) => children.Add(component); public void Remove(IComponent component) => children.Remove(component); public int Call() { int sum = 0; foreach (var x in children) sum += x.Call(); return sum; } } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using DojoSurvey.Models; namespace DojoSurvey.Controllers { public class SurveyController : Controller { [HttpGet("")] public IActionResult Index() { return View(); } [HttpPost("result")] public IActionResult Result(User user) { return View(user); } } }
using System.Collections.Generic; using System.Linq; using Conditions; using Conditions.Guards; using Properties.Core.Interfaces; using Properties.Core.Objects; namespace Properties.Core.Services { public class PostcodeAreaService : IPostcodeAreaService { private readonly IPostcodeAreaRepository _postcodeAreaRepository; private readonly IReferenceGenerator _referenceGenerator; public PostcodeAreaService(IPostcodeAreaRepository postcodeAreaRepository, IReferenceGenerator referenceGenerator) { Check.If(postcodeAreaRepository).IsNotNull(); Check.If(referenceGenerator).IsNotNull(); _postcodeAreaRepository = postcodeAreaRepository; _referenceGenerator = referenceGenerator; } public List<Area> GetAllAreas() { return _postcodeAreaRepository.GetAllAreas().OrderBy(x=>x.FriendlyName).ToList(); } public List<PostcodeArea> GetPostcodeAreas() { return _postcodeAreaRepository.GetPostcodeAreas(); } public List<PostcodeArea> GetAvailablePostcodeAreas() { var postcodePrefixes = _postcodeAreaRepository.GetAvailablePropertyPostcodeAreas(); return postcodePrefixes.Select( postcodePrefix => _postcodeAreaRepository.GetPostcodeAreaByPostcodePrefix(postcodePrefix)) .Where(area => area.IsNotNull()) .OrderBy(x=>x.PostcodeAreaFriendlyName) .ToList(); } public PostcodeArea GetPostcodeArea(string postcodeAreaReference) { Check.If(postcodeAreaReference).IsNotNullOrEmpty(); return _postcodeAreaRepository.GetPostcodeArea(postcodeAreaReference); } public string CreatePostcodeArea(PostcodeArea postcodeArea) { Check.If(postcodeArea).IsNotNull(); var result = _postcodeAreaRepository.CreatePostcodeArea(postcodeArea.CreateReference(_referenceGenerator)); return result ? postcodeArea.PostcodeAreaReference : null; } public bool UpdatePostcodeArea(string postcodeAreaReference, PostcodeArea postcodeArea) { Check.If(postcodeAreaReference).IsNotNullOrEmpty(); Check.If(postcodeArea).IsNotNull(); return _postcodeAreaRepository.UpdatePostcodeArea(postcodeAreaReference, postcodeArea); } public bool DeletePostcodeArea(string postcodeAreaReference) { Check.If(postcodeAreaReference).IsNotNullOrEmpty(); return _postcodeAreaRepository.DeletePostcodeArea(postcodeAreaReference); } } }
using Reactive.Flowable.Test; using Reactive.Flowable; using System; using Reactive.Flowable.Flowable; using System.Collections.Concurrent; using System.Threading; namespace AddToObservable { class Program { public static class NonBlockingConsole { private static BlockingCollection<string> m_Queue = new BlockingCollection<string>(); static NonBlockingConsole() { var thread = new Thread( () => { while (true) Console.WriteLine(m_Queue.Take()); }); thread.IsBackground = true; thread.Start(); } public static void WriteLine(string value) { m_Queue.Add(value); } } static void Main(string[] args) { var testf = new TestFlowable(10); var testg = new TestFlowable(10); var testh = new TestFlowable(10); testf .Merge(testg, testh) .Subscribe(x => NonBlockingConsole.WriteLine(x.ToString())); while (true) { if(Console.ReadKey().Key == ConsoleKey.Enter) { break; } } } } }
using System; using System.IO; using System.Reflection; using System.ServiceModel; using System.ServiceProcess; using log4net; namespace NumberToWordsService.WCF { public partial class Service : ServiceBase { private ServiceHost serviceHost; private ILog logger; public Service() { InitializeLog4Net(); this.logger = LogManager.GetLogger(GetType()); InitializeComponent(); } protected override void OnStart(string[] args) { try { logger.Info("Service is starting..."); serviceHost?.Close(); serviceHost = new ServiceHost(typeof(NumberToWordsService)); serviceHost.Open(); logger.Info("Service started."); } catch (Exception ex) { logger.Fatal(ex); } } protected override void OnStop() { } private void InitializeLog4Net() { GlobalContext.Properties["ProjectLogs"] = "Logs"; var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var path = Path.Combine(dir, "log4net.config"); log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(path)); } } }
using System; /* builder: phenixiii build time: 2017-06-04 10:04:01 notes: */ namespace Phenix.Test.使用指南._17._3 { /// <summary> /// /// </summary> [System.Serializable] [System.ComponentModel.DisplayName("")] [Phenix.Core.Mapping.ReadOnly] public class UserRoleReadOnly : UserRole<UserRoleReadOnly> { private UserRoleReadOnly() { //禁止添加代码 } [Newtonsoft.Json.JsonConstructor] private UserRoleReadOnly(bool? isNew, bool? isSelfDirty, bool? isSelfDeleted, long? UR_ID, long? UR_US_ID, long? UR_RL_ID, string inputer, DateTime? inputtime) : base(isNew, isSelfDirty, isSelfDeleted, UR_ID, UR_US_ID, UR_RL_ID, inputer, inputtime) { } } /// <summary> /// 清单 /// </summary> [System.Serializable] [System.ComponentModel.DisplayName("")] public class UserRoleReadOnlyList : Phenix.Business.BusinessListBase<UserRoleReadOnlyList, UserRoleReadOnly> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; namespace Breeze.Helpers { public static class BezierHelper { public static Vector2[] GetBezierApproximation(Vector2[] controlPoints, int outputSegmentCount) { if (controlPoints.Length==4) { Vector2[] points = new Vector2[outputSegmentCount + 1]; for (int i = 0; i <= outputSegmentCount; i++) { double t = (double) i / outputSegmentCount; points[i] = GetBezierPoint(t, controlPoints, 0, controlPoints.Length); } return points; } else { return new Vector2[0]; } } public static Vector2 GetBezierPoint(double t, Vector2[] controlPoints, int index, int count) { if (count == 1) return controlPoints[index]; var P0 = GetBezierPoint(t, controlPoints, index, count - 1); var P1 = GetBezierPoint(t, controlPoints, index + 1, count - 1); return new Vector2((float)((1 - t) * P0.X + t * P1.X), (float)((1 - t) * P0.Y + t * P1.Y)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BookApiProject.Models; namespace BookApiProject.Services { public class CategoryRepository : ICategoryRepository { private BookDbContext _categoryContext; public CategoryRepository(BookDbContext categoryContext) { _categoryContext = categoryContext; } public bool CategoryExists(int categoryId) { return _categoryContext.emsCategories.Any(c => c.Id == categoryId); } public ICollection<Book> GetAllBooksForCategory(int categoryId) { return _categoryContext.emsBookCategories.Where(c => c.CategoryId == categoryId) .Select(b => b.Book).ToList(); } public ICollection<Category> GetCategories() { return _categoryContext.emsCategories.OrderBy(c => c.Name).ToList(); } public ICollection<Category> GetAllCategoriesForABook(int bookId) { return _categoryContext.emsBookCategories. Where(b => b.BookId == bookId). Select(c => c.Category).ToList(); } public Category GetCategory(int categoryId) { return _categoryContext.emsCategories.Where(c => c.Id == categoryId).FirstOrDefault(); } } }
using System.Collections.Generic; namespace Delegates { class Program { static void Main(string[] args) { var pic = new Photo(); var processor = new PhotoProcessor( new PhotoFilters( new List<IEffect>() { new BrightnessEffect(), new ContrastEffect(), new ResizeEffect() }), pic); processor.Process(); } } }
using UnityEngine; using System.Collections; public class ClimberController : MonoBehaviour { private GameController gc; public Player player1; public Player player2; public GameObject mainCamera; public float scrollSpeed; public int time; private bool onlyOnce; private int gameOverState; void Start () { gc = GameController.gc; gc.startGame (time); gameOverState = -1; onlyOnce = false; } // Update is called once per frame void Update () { if (gc.gameTime > 0) { mainCamera.transform.Translate (0f, scrollSpeed * Time.deltaTime, 0f); }else if (!onlyOnce && gc.gameTime <=0 ) { player1.stop = player2.stop = true; onlyOnce = true; gameOverState = 0; if (player1.transform.position.y > player2.transform.position.y + 0.2f) gameOverState = 1; if (player2.transform.position.y > player1.transform.position.y + 0.2f) gameOverState = 2; gc.gameOver (gameOverState); } if (player1.transform.position.y < mainCamera.transform.position.y - 12f) gameOverState = 2; if (player2.transform.position.y < mainCamera.transform.position.y - 12f) gameOverState = 1; if (player1.transform.position.y > 86f) gameOverState = 1; if (player2.transform.position.y > 86f) gameOverState = 2; if (!onlyOnce && gameOverState >= 0) { player1.stop = player2.stop = true; if (Mathf.Abs (player1.transform.position.y - player2.transform.position.y) < 0.2f) gameOverState = 0; gc.overrideTimer = true; gc.gameTime = 0; gc.gameOver (gameOverState); onlyOnce = true; } } }
using UnityEngine; using System.Collections.Generic; using IsoTools; using UnityEngine.UI; namespace Caapora { public class Inventory : MonoBehaviour { private static List<GameObject> itemList = new List<GameObject>(); private static Inventory _instance; void Start () { _instance = this; } public void Awake() { if (_instance == null) { DontDestroyOnLoad(this); _instance = this; } else { if (this != _instance) Destroy(gameObject); } } public static Inventory instance { get { if (_instance == null) { DontDestroyOnLoad(_instance); _instance = FindObjectOfType<Inventory>() as Inventory; } return _instance; } } public static bool isEmpty() { return itemList.Count == 0; } public static GameObject getItem() { return itemList[0]; } public static void AddItem(GameObject item) { itemList.Add(item); } public static void RemoveItem(GameObject item) { if (!isEmpty()) { itemList.Remove(item); } } } }
namespace Application.Utilities { using Common; using Common.Utilities; using Data.Services; using SimpleMVC.Controllers; using User = Models.User; public static class ControllerHelper { public static void SetupNavAndHome(this Controller controller, bool isAuthenticated) { if (!isAuthenticated) { Constants.HomeStart = string.Format(Constants.HomeStartHtml.GetContentByName(), string.Empty); Constants.NavHtml = Constants.NavNotLoggedHtml.GetContentByName(); return; } var homeStartLinkHtml = string.Format(Constants.HomeStartLinksHtml.GetContentByName(), "Owned"); Constants.HomeStart = Constants.HomeStartHtml.GetContentByName().GetHomeStart(homeStartLinkHtml); } public static void SetGameDetails(this Controller controller, Service service, User user, int gameId) { Constants.GameDetailsForm = user == null || service.CheckIfUserIsBuyedGame(user.Id, gameId) ? string.Empty : string.Format(Constants.GameDetailsFormHtml.GetContentByName(), user.Id, gameId); } public static void SetupNavbar(this Service service, User user) { Constants.NavHtml = string.Format( service.IsUserInAdminRole(user) ? Constants.NavLoggedAdminHtml.GetContentByName() : Constants.NavLoggedHtml.GetContentByName(), user.FullName); } } }
using OpenAccessRuntime.common; using OpenAccessRuntime.util; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Telerik.OpenAccess.Metadata; using Telerik.OpenAccess.Metadata.Relational; namespace Sparda.Core.Generation.Sql { public class OracleSqlDriver : SqlDriver { private readonly static IList ORACLE_TYPES; static OracleSqlDriver() { string[] strArrays = new string[] { "BLOB", "BYTE", "BFILE", "CHAR", "CLOB", "CURSOR", "DOUBLE", "DATE", "FLOAT", "INT16", "INT32", "INTERVALDAYTOSECOND", "INTERVALYEARTOMONTH", "LONG", "LONG RAW", "NCHAR", "NVARCHAR", "NUMBER", "NCLOB", "RAW", "ROWID", "SBYTE", "TIMESTAMP", "TIMESTAMPLOCAL", "TIMESTAMPWITHTZ", "UINT16", "UINT32", "VARCHAR", "VARCHAR2" }; OracleSqlDriver.ORACLE_TYPES = new ArrayList(strArrays); } public OracleSqlDriver() { this.rDelim = '"'; this.lDelim = '"'; this.useDelimiter = true; this.guidSortOrder = SqlDriver.GuidSortingOrder_Bin; base.MaxParameters = 0x1f0; base.MaxIndexKeyLengthInBytes = new int?(0x2f6); } private void GenerateCreateColumnAutoInc(MetaTable table, MetaColumn column, DDLAction actions) { string str = base.GenerateIdentifier(table, column, "Seq_", this.MaxLengthConstraintName); //if (this.allObjectList == null || !this.allObjectList.Contains(str.ToUpperInvariant())) //{ string str1 = string.Format("CREATE SEQUENCE \"{0}\" START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCACHE ", str); actions.Buffer.append(str1); actions.Execute(actions.Buffer); //} string str2 = base.GenerateIdentifier(table, column, "Trg_", this.MaxLengthConstraintName); object[] plainName = new object[] { str2, table.Name, str, column.Name }; string str3 = string.Format("CREATE TRIGGER \"{0}\" BEFORE INSERT ON \"{1}\" FOR EACH ROW BEGIN SELECT \"{2}\".nextval INTO :NEW.\"{3}\" FROM dual; END;", plainName); actions.Buffer.append(str3); actions.Execute(actions.Buffer); } #region Override internal override void GenerateCreateTable(MetadataContainer metadataContainer, MetaTable t, DDLAction actions, bool comments) { base.GenerateCreateTable(metadataContainer, t, actions, comments); foreach (var pk in t.Columns.Where(c => c.IsPrimaryKey)) { if (pk.IsBackendCalculated) { this.GenerateCreateColumnAutoInc(t, pk, actions); } } } protected internal override void AppendColumnType(bool forModification, MetaColumn c, CharBuf s, bool useZeroScale) { if (c.SqlType == null) { throw BindingSupportImpl.Instance.internally(string.Concat("sqlType is null: ", c)).Throw(); } if (!c.SqlType.StartsWith("timestamp", StringComparison.OrdinalIgnoreCase)) { base.AppendColumnType(false, c, s, useZeroScale); } else { s.append("TIMESTAMP"); s.append('('); s.append(c.Length.Value); s.append(')'); int num = c.SqlType.IndexOf(' '); if (num > 0) { s.space(); s.append(c.SqlType.Substring(num + 1)); return; } } } protected internal override void AppendCreateColumnNulls(bool forModification, DDLAction actions, MetaTable t, MetaColumn c) { CharBuf buffer = actions.Buffer; if (c.IsNullable == true) { buffer.append(" NOT NULL"); return; } buffer.append(" NULL"); } protected internal override void AppendPrimaryKeyConstraint(MetaTable t, CharBuf s) { s.append("CONSTRAINT "); s.append(this.CorrectName(t.PKConstraintName)); s.append(" PRIMARY KEY ("); this.AppendColumnNameList(t.Columns.Where(c => c.IsPrimaryKey).ToArray(), s); s.append(')'); } public override Backend Backend { get { return Backend.Oracle; } } #endregion } }
// File Prologue // Name: Darren Moody // CS 1400 Section 005 // Project: Lab 24 // Date: 12/03/2013 // // // I declare that the following code was written by me or provided // by the instructor for this project. I understand that copying source // code from any other source constitutes cheating, and that I will receive // a zero on this project if I am found in violation of this policy. // --------------------------------------------------------------------------- using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lab24 { class Program { const int SIZE = 50; static void Main(string[] args) { int arrCount = 0; int[] grades = new int[SIZE]; string myString; string fileDoc = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\"; Console.Write("Please enter a file name in your documents folder: "); string userInput = Console.ReadLine(); string folder = fileDoc + userInput; Console.WriteLine(folder); StreamReader myFile = new StreamReader(folder); do { myString = myFile.ReadLine(); if (myString != null) { grades[arrCount] = int.Parse(myString); Console.WriteLine("{0} \t {1}", arrCount + 1, grades[arrCount]); arrCount++; } } while (myString != null); Console.WriteLine("The average score is {0}", CalcAverage(grades, arrCount)); Console.ReadLine(); } //The CalcAverage() method //Purpose: calculates the average of the scores in the file //Parameters: integer array of scores, and count length of array //Returns: the average of the scores in the file static int CalcAverage(int[] scores, int arrCount) { int sum = 0; for (int i = 0; i < arrCount; i++) { sum += scores[i]; } int average = sum / arrCount; return average; } /*int StreamRead(int arrCount, StreamReader myFile) { string myString; int[] grades = new int[SIZE]; do { myString = myFile.ReadLine(); if (myString != null) { grades[arrCount] = int.Parse(myString); Console.WriteLine("{0} \t {1}", arrCount + 1, grades[arrCount]); int myGrades = grades[arrCount]; return myGrades; arrCount++; } } while (myString != null); }*/ } }
using System; using System.Collections.Generic; using System.Text; namespace MyDictionary { class MyDictionary<K,V> { K[] _array; V[] _array2; K[] _tempArray; V[] _tempArray2; public MyDictionary() { _array = new K[0];//Newlenmiş dizide eleman sayısı verdik. _array2 = new V[0]; } public void Add(K item, V item2) { _tempArray = _array; _tempArray2 = _array2; _array = new K[_array.Length + 1]; _array2 = new V[_array2.Length + 1]; for (int i = 0; i < _tempArray.Length; i++) { _array[i] = _tempArray[i]; _array2[i] = _tempArray2[i]; } _array[_array.Length - 1] = item; _array2[_array2.Length - 1] = item2; } public void List() { foreach (var items in _array2) { Console.WriteLine(items); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BE; using PL.Models; using PL.Views; using System.ComponentModel; using System.Windows; namespace PL.ViewModel { public class ProfileBarIceCreamVM : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public ProfileBarIceCreamModel ProfileBarIceCreamModel { get; set; } private ProfileBarIceCreamUC ProfileBarIceCreamUC; public ProfileBarIceCreamVM(ProfileBarIceCreamUC profileBarIceCreamUC) { ProfileBarIceCreamModel = new ProfileBarIceCreamModel(); ProfileBarIceCreamModel.IceCream = profileBarIceCreamUC.iceCream; this.ProfileBarIceCreamUC = profileBarIceCreamUC; } public string ID { get { return ProfileBarIceCreamUC.iceCream.Id; } } public string ShopID { get { return ProfileBarIceCreamUC.iceCream.ShopId; } } public string Image { get { return ProfileBarIceCreamUC.iceCream.Image; } } public string Taste { get { return ProfileBarIceCreamUC.iceCream.Taste; } } public string Presentation { get { return ProfileBarIceCreamUC.iceCream.Presentation; } } public string Energy { get { return ProfileBarIceCreamUC.iceCream.Energy.ToString(); } } public string Proteins { get { return ProfileBarIceCreamUC.iceCream.Proteins.ToString(); } } public string Calories { get { return ProfileBarIceCreamUC.iceCream.Calories.ToString(); } } public string Grade { get { string[] grade = ProfileBarIceCreamUC.iceCream.Marks.Split(',').ToArray(); return grade[0]; } } public string Comments { set { ProfileBarIceCreamUC.iceCream.comments.Add(value); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Comments")); } } } }
using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace WeddingPlanner.Models { public class Wedding { [Key] public int WeddingId { get; set; } [Required] public string Groom { get; set; } [Required] public string Bride { get; set; } [Required] [DataType(DataType.Date)] // Validate Future Date public DateTime Date { get; set; } [Required] [MinLength(5, ErrorMessage = "Address must be at least 5 characters")] public string Address { get; set; } public int UserId { get; set; } public DateTime CreatedAt { get; set; } = DateTime.Now; public DateTime UpdatedAt { get; set; } = DateTime.Now; public User Planner { get; set; } public List<Response> Responses { get; set; } } public class Response { [Key] public int ResponseId { get; set; } public int WeddingId { get; set; } public int UserId { get; set; } public User Guest { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Net; using SpringHackApi.Models; using AeroORMFramework; using Newtonsoft.Json; using System.IO; namespace SpringHackApi.Controllers { public class AssesmentsController : ApiController { private string ConnectionString { get; } [HttpPost] public async Task<HttpResponseMessage> InsertAssesment() { return await Task.Run(async() => { try { string body; using (Stream stream = await Request.Content.ReadAsStreamAsync()) { stream.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(stream)) { body = await sr.ReadToEndAsync(); } } Connector connector = new Connector(ConnectionString); Assesment assesment = JsonConvert.DeserializeObject<Assesment>(body); Coupon coupon = connector.GetRecord<Coupon>("ID", assesment.CouponID); CouponCode couponCode = connector.GetRecord<CouponCode>("CouponID", coupon.ID); couponCode.CouponCodeStatus = CouponCodeStatus.Used; connector.UpdateRecord(couponCode); connector.Insert(assesment); return new HttpResponseMessage(HttpStatusCode.OK); } catch { return new HttpResponseMessage(HttpStatusCode.InternalServerError); } }); } [HttpGet] public async Task<HttpResponseMessage> GetOfficeAssesments(int officeID) { return await Task.Run(() => { try { Connector connector = new Connector(ConnectionString); List<Assesment> assesments = connector.GetRecords<Assesment>("OfficeID", officeID); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(assesments), System.Text.Encoding.UTF8, "application/json") }; } catch { return new HttpResponseMessage(HttpStatusCode.InternalServerError); } }); } [HttpGet] public async Task<HttpResponseMessage> GetAllAssesments() { return await Task.Run(() => { try { Connector connector = new Connector(ConnectionString); List<Assesment> assesments = connector.GetAllRecords<Assesment>(); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(assesments), System.Text.Encoding.UTF8, "application/json") }; } catch { return new HttpResponseMessage(HttpStatusCode.OK); } }); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using DG.Tweening; public class LevelUpEffect : MonoBehaviour { private static LevelUpEffect _instance; public static LevelUpEffect Instance { get { return _instance; } } private List<RectTransform> _tempList; private List<RectTransform> _levelupList; private List<RectTransform> _rankupList; private int[] _rankup_Positions; private List<Vector2> _rankup_Normal_Positions; private int times;//执行次数 private int _index;//子物体的下标 private Coroutine _coroutine;//携程对象 // Use this for initialization void Start() { //测试代码 //MyKeys.Gold_Value = 10000; //MyKeys.HeroOne_Level_Value = 0; _instance = this; _levelupList = new List<RectTransform>(); _rankupList = new List<RectTransform>(); _tempList = new List<RectTransform>(); _rankup_Normal_Positions = new List<Vector2>(); _rankup_Positions = new[] {38, -30, -100, -176, -247}; foreach (Transform child in transform.GetChild(0)) { _levelupList.Add(child.GetComponent<RectTransform>()); } foreach (Transform child in transform.GetChild(1)) { _rankupList.Add(child.GetComponent<RectTransform>()); _rankup_Normal_Positions.Add(child.GetComponent<RectTransform>().anchoredPosition); } } public void LevelUp() { initialize(); _tempList = _levelupList; transform.GetChild(0).gameObject.SetActive(true); Next(); } //初始化数据 void initialize() { times = 0; _index = 0; transform.GetChild(0).gameObject.SetActive(false); transform.GetChild(1).gameObject.SetActive(false); for (int i = 0; i < _rankupList.Count; i++) { _rankupList[i].anchoredPosition = _rankup_Normal_Positions[i]; } if (_coroutine != null) { StopCoroutine(_coroutine); } } //执行动画 void Next() { RectTransform rectTransform = _tempList[times]; Sequence mySequence = DOTween.Sequence(); mySequence.Append(rectTransform.DOLocalMoveY(rectTransform.anchoredPosition.y + (10f - 6 * _index), 0.05f).OnComplete(Next)); mySequence.Append(rectTransform.DOLocalMoveY(rectTransform.anchoredPosition.y - (10f - 6 * _index), 0.05f)); mySequence.Play(); times++; if (times == _tempList.Count) { _coroutine = StartCoroutine(Wait()); } } IEnumerator Wait() { yield return new WaitForSeconds(1); transform.GetChild(_index).gameObject.SetActive(false); _index++; if (_index == 1) { MyAudio.PlayAudio(StaticParameter.s_Rankup, false, StaticParameter.s_Rankup_Volume); transform.GetChild(1).gameObject.SetActive(true); _tempList = _rankupList; times = 0; Next(); int index = (MyKeys.GetHeroLevel(MyKeys.CurrentSelectedHero) - 1) % 5; transform.GetChild(1).localPosition = Vector3.right * transform.GetChild(1).localPosition.x + Vector3.up * _rankup_Positions[index]; } } }
using Alabo.App.Share.OpenTasks.Domain.Enum; namespace Alabo.App.Share.OpenTasks.Base { /// <summary> /// 封底规则 /// </summary> public class LimitRule { /// <summary> /// 封顶方式 /// </summary> public LimitType LimitType { get; set; } = LimitType.None; /// <summary> /// 封顶金额 /// </summary> public decimal LimitValue { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace aoc2016.day02 { public class Solution { public static void Run() { string[] input = System.IO.File.ReadAllLines("day02.txt"); // Part 1 Keypad keypad1 = new Keypad("5", @"1 2 3 4 5 6 7 8 9"); string part1 = keypad1.GetCode(input); Console.WriteLine("==== Part 1 ===="); Console.WriteLine($"Code: {part1}"); // Part 2 Keypad keypad2 = new Keypad("5", @"_ _ 1 _ _ _ 2 3 4 _ 5 6 7 8 9 _ A B C _ _ _ D _ _"); string part2 = keypad2.GetCode(input); Console.WriteLine("==== Part 2 ===="); Console.WriteLine($"Code: {part2}"); } private struct Pos { public int x, y; public Pos Up() { this.y--; return this; } public Pos Down() { this.y++; return this; } public Pos Right() { this.x++; return this; } public Pos Left() { this.x--; return this; } } private class Keypad { private int _nRows, _nCols; private string[,] _pad; public Pos start { get; } public Pos pos { get; private set; } public Keypad(string startButton, string pad) { string[] rows = pad.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); _nRows = rows.Length; _nCols = rows[0].Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Length; _pad = new string[_nCols, _nRows]; for (int row = 0; row < rows.Length; row++) { string[] cols = rows[row].Split((char[])null, StringSplitOptions.RemoveEmptyEntries); for (int col = 0; col < cols.Length; col++) { if (cols[col] == "_") continue; _pad[col, row] = cols[col]; if (cols[col] == startButton) start = new Pos { x = col, y = row }; } } } public string GetCode(string[] dirs) { pos = start; string code = ""; foreach (var line in dirs) { foreach (var dir in line) Move(dir); code += Current(); } return code; } public void Move(char dir) { switch (dir) { case 'U': if (pos.y > 0) { pos = pos.Up(); if (Current() == null) pos = pos.Down(); } break; case 'D': if (pos.y < _nRows - 1) { pos = pos.Down(); if (Current() == null) pos = pos.Up(); } break; case 'L': if (pos.x > 0) { pos = pos.Left(); if (Current() == null) pos = pos.Right(); } break; case 'R': if (pos.x < _nCols - 1) { pos = pos.Right(); if (Current() == null) pos = pos.Left(); } break; default: throw new NotImplementedException(); } } public string Current() { return _pad[pos.x, pos.y]; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(FieldOfView))] public class PlayerEntity : MonoBehaviour { private Rigidbody2D rb; private FieldOfView fov; private Vector2 moveVelocity; private float lastMirrorBufferCalculation; public float moveSpeed; public float turnSpeed; public float mirrorBufferMax; public float mirrorBufferDecay; public float mirrorBufferGain; public float mirrorBuffer; public delegate void PlayerDelegate(); public event PlayerDelegate mirrorBufferUpdated; public static event PlayerDelegate playerFailure; private void Awake() { rb = GetComponent<Rigidbody2D>(); fov = GetComponent<FieldOfView>(); fov.targetsFound += CalculateMirrorBufferTargets; } private void Start() { lastMirrorBufferCalculation = Time.time; } private float CalculateMirrorBufferAddition(Transform mirror) { Vector2 playerToMirror = (mirror.position - transform.position).normalized; float angle = Vector2.Angle(transform.up, playerToMirror); float anglePercent = 1f - (angle / (fov.viewAngle / 2)); return (Time.time - lastMirrorBufferCalculation) * anglePercent * mirrorBufferGain; } public void CalculateMoveVelocity(Vector3 input) { moveVelocity = input.normalized * moveSpeed; } public void CalculateMirrorBufferTargets() { float bufferSum = 0; foreach (Transform target in fov.visibleTargets) if (target.CompareTag("Mirror")) bufferSum += CalculateMirrorBufferAddition(target); mirrorBuffer += (bufferSum - (Time.time - lastMirrorBufferCalculation) * mirrorBufferDecay); if (mirrorBuffer < 0f) mirrorBuffer = 0f; else if (mirrorBuffer > mirrorBufferMax) if (playerFailure != null) playerFailure(); lastMirrorBufferCalculation = Time.time; if(mirrorBufferUpdated != null) mirrorBufferUpdated(); } public void Move() { rb.MovePosition (rb.position + moveVelocity * Time.fixedDeltaTime); } Quaternion CalculateLookRotation(Vector3 mousePositionInWorld) { float angleToMouse = Vector2.SignedAngle(transform.up, mousePositionInWorld - transform.position); Quaternion lookRotation = new Quaternion(); lookRotation.eulerAngles = new Vector3(0f, 0f, transform.rotation.eulerAngles.z + angleToMouse); return lookRotation; } public void TurnToward(Vector3 target) { Quaternion newRotation = new Quaternion(); newRotation.eulerAngles = new Vector3(0f, 0f, rb.rotation + Vector2.SignedAngle(transform.up, target - transform.position) * turnSpeed * Time.fixedDeltaTime); transform.rotation = newRotation; } }
public class MinStack { private Stack<int> st1; private Stack<int> st2; public MinStack() { st1 = new Stack<int>(); st2 = new Stack<int>(); } public void Push(int val) { st1.Push(val); if (st2.Count == 0 || st2.Peek() >= val) st2.Push(val); } public void Pop() { if (st2.Peek() == st1.Peek()) st2.Pop(); st1.Pop(); } public int Top() { return st1.Peek(); } public int GetMin() { return st2.Peek(); } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.Push(val); * obj.Pop(); * int param_3 = obj.Top(); * int param_4 = obj.GetMin(); */
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerStickyLook : MonoBehaviour { public Transform PlayerBody; public float MouseSensitivity; private void Update () { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; RotateCamera(); RotatePlayerBody(); } public void Reset() { transform.rotation = new Quaternion(); } private void RotateCamera() { float mouseY = Input.GetAxis("Mouse Y"); float rotateAmount = -mouseY * MouseSensitivity; float toUp = Vector3.Angle(PlayerBody.up, transform.forward); if (rotateAmount < 0) { rotateAmount = Mathf.Max(-toUp + 0.1f, rotateAmount); } else if (rotateAmount > 0) { rotateAmount = Mathf.Min(179.9f - toUp, rotateAmount); } transform.rotation = Quaternion.AngleAxis(rotateAmount, transform.right) * transform.rotation; } private void RotatePlayerBody() { float mouseX = Input.GetAxis("Mouse X"); float rotateAmount = mouseX * MouseSensitivity; PlayerBody.rotation = Quaternion.AngleAxis(rotateAmount, PlayerBody.up) * PlayerBody.rotation; } }
using gView.Framework.Data; using gView.Framework.Data.Cursors; using gView.Framework.Data.Filters; using gView.Framework.Geometry; using gView.Framework.Network.Algorthm; using gView.Framework.system; using gView.Framework.UI; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace gView.Framework.Network.Tracers { [RegisterPlugInAttribute("D102AFFA-1D37-4de0-9853-C28E2F3C5DC6")] public class TraceDistancePropagation : INetworkTracer, INetworkTracerProperties, IProgressReporterEvent { private Properties _properties = new Properties(); #region INetworkTracer Member public string Name { get { return "Trace Distance Propagation"; } } public bool CanTrace(NetworkTracerInputCollection input) { if (input == null) { return false; } return input.Collect(NetworkTracerInputType.SourceNode).Count == 1; } async public Task<NetworkTracerOutputCollection> Trace(INetworkFeatureClass network, NetworkTracerInputCollection input, gView.Framework.system.ICancelTracker cancelTraker) { if (network == null || !CanTrace(input)) { return null; } GraphTable gt = new GraphTable(network.GraphTableAdapter()); NetworkSourceInput source = input.Collect(NetworkTracerInputType.SourceNode)[0] as NetworkSourceInput; NetworkWeighInput weight = input.Contains(NetworkTracerInputType.Weight) ? input.Collect(NetworkTracerInputType.Weight)[0] as NetworkWeighInput : null; Dijkstra dijkstra = new Dijkstra(cancelTraker); dijkstra.reportProgress += this.ReportProgress; dijkstra.MaxDistance = _properties.Distance; if (weight != null) { dijkstra.GraphWeight = weight.Weight; dijkstra.WeightApplying = weight.WeightApplying; } dijkstra.ApplySwitchState = input.Contains(NetworkTracerInputType.IgnoreSwitches) == false && network.HasDisabledSwitches; Dijkstra.ApplyInputIds(dijkstra, input); dijkstra.Calculate(gt, source.NodeId); NetworkTracerOutputCollection output = new NetworkTracerOutputCollection(); #region Knoten/Kanten <= Distance Dijkstra.Nodes dijkstraNodes = dijkstra.DijkstraNodesWithMaxDistance(_properties.Distance); if (dijkstraNodes == null) { return null; } List<int> edgeIds = new List<int>(); foreach (Dijkstra.Node dijkstraNode in dijkstraNodes) { if (dijkstraNode.EId < 0) { continue; } int index = edgeIds.BinarySearch(dijkstraNode.EId); if (index < 0) { edgeIds.Insert(~index, dijkstraNode.EId); } if (Math.Abs(dijkstraNode.Dist - _properties.Distance) < double.Epsilon) { // ToDo: Flag einfügen!! } } output.Add(new NetworkEdgeCollectionOutput(edgeIds)); #endregion #region Knoten/Kanten > Distance Dijkstra.Nodes cnodes = dijkstra.DijkstraNodesDistanceGreaterThan(_properties.Distance); foreach (Dijkstra.Node cnode in cnodes) { Dijkstra.Node node = dijkstra.DijkstraNodes.ById(cnode.Pre); if (node == null) { continue; } IGraphEdge graphEdge = gt.QueryEdge(cnode.EId); if (graphEdge == null) { continue; } RowIDFilter filter = new RowIDFilter(String.Empty); filter.IDs.Add(graphEdge.Eid); IFeatureCursor cursor = await network.GetEdgeFeatures(filter); if (cursor == null) { continue; } IFeature feature = await cursor.NextFeature(); if (feature == null) { continue; } IPath path = null; if (cnode.Id != graphEdge.N2 && cnode.Id == graphEdge.N1) { ((Polyline)feature.Shape)[0].ChangeDirection(); } double trimDist = _properties.Distance - node.Dist; string label = _properties.Distance.ToString(); if (weight != null) { double w = gt.QueryEdgeWeight(weight.Weight.Guid, cnode.EId); switch (weight.WeightApplying) { case WeightApplying.Weight: trimDist *= w; break; case WeightApplying.ActualCosts: trimDist = ((IPolyline)feature.Shape)[0].Length * trimDist * w; // ??? Prüfen break; } label += "\n(" + Math.Round(node.GeoDist + trimDist, 2).ToString() + ")"; } path = ((IPolyline)feature.Shape)[0].Trim(trimDist); Polyline polyline = new Polyline(); polyline.AddPath(path); output.Add(new NetworkEdgePolylineOutput(cnode.EId, polyline)); output.Add(new NetworkFlagOutput( polyline[0][polyline[0].PointCount - 1], label)); } #endregion return output; } #endregion #region IProgressReporterEvent Member public event ProgressReporterEvent ReportProgress = null; #endregion #region INetworkTracerProperties Member public Task<object> NetworkTracerProperties(INetworkFeatureClass network, NetworkTracerInputCollection input) { return Task.FromResult<object>(_properties); } #endregion private class Properties { private double _distance = 1.0; public double Distance { get { return _distance; } set { _distance = value; } } } } }
using AzureAI.CallCenterTalksAnalysis.Core.Model; using System.Threading.Tasks; namespace AzureAI.CallCenterTalksAnalysis.Core.Services.Interfaces { public interface IFileProcessingService { Task<FileAnalysisResult> AnalyzeFileContentAsync(InputFileData inputFileData); } }