text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace APP_Biblioteca { public partial class AddLibro : Form { SqlConnection cn = new SqlConnection("Data Source = "); public AddLibro() { InitializeComponent(); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void button3_Click(object sender, EventArgs e) { } private void btnGuardar_Click(object sender, EventArgs e) { Libro libro = new Libro(); libro.Titulo = txtTitulo.Text; libro.Edicion = cmbEdicion.SelectedText; libro.Idioma = cmbIdioma.SelectedText; libro.Genero = cmbGenero.SelectedText; libro.ISBN = txtISBN.Text; libro.No_Pags = txtPags.Text; libro.Tomo = txtTomo.Text; libro.Ubicacion = txtUbicacion.Text; libro.Formato = cmbFormato.SelectedText; libro.Costo = txtCosto.Text; Autor Autor = new Autor(); Autor.Nombre = txtAutor.Text; Autor.Nacionalidad = cmbNacionalidad.SelectedText; Editora Editora = new Editora(); Editora.Nombre = txtEditora.Text; Editora.Pais = cmbPais.SelectedText; int respuesta = DataBaseRegister.Agregarlibro(libro); int respuesta1 = DataBaseRegister.AgregarAutor(Autor); int respuesta2 = DataBaseRegister.AgregarEditora(Editora); if (respuesta > 0 && respuesta1 > 0 && respuesta2 > 0) { MessageBox.Show("Libro Guardado Exitosamente", "Guardando ...", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Hubo problemas, Verifique nuevamente", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void btnCerrar_Click(object sender, EventArgs e) { this.Hide(); Master mlibro = new Master(); mlibro.Show(); } private void AddLibro_Load(object sender, EventArgs e) { /*cmbPais.DataSource = DataBaseRegister.ObtenerPaises(); cmbPais.DisplayMember = "Name"; cmbPais.ValueMember = "ID"; cmbNacionalidad.DataSource = DataBaseRegister.ObtenerPaises(); cmbNacionalidad.DisplayMember = "Name"; cmbNacionalidad.ValueMember = "ID";*/ //esto no esta cargando } private void txtTitulo_TextChanged(object sender, EventArgs e) { } } }
using EasyHarmonica.DAL.Entities; using Microsoft.AspNet.Identity; namespace EasyHarmonica.DAL.Identity { public class EasyHarmonicaUserManager:UserManager<User> { public EasyHarmonicaUserManager(IUserStore<User> store):base(store) { } } }
namespace Project.Base { public abstract class Service { // The handle of this service public abstract string GetHandle(); // Called after loading the app public virtual void Load() { } // Called before unloading the app public virtual void Unload() { } } }
using System; using System.Text; namespace gView.Framework.IO { public class ExceptionConverter { public static string ToString(Exception ex) { StringBuilder sb = new StringBuilder(); sb.Append("Details:\r\n"); while (ex != null) { sb.Append("Message:" + ex.Message + "\r\n"); sb.Append("Source:" + ex.Source + "\r\n"); sb.Append("Stacktrace:" + ex.StackTrace + "\r\n"); ex = ex.InnerException; if (ex != null) { sb.Append("Inner Exception:\r\n"); } } return sb.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Lava : MonoBehaviour { public PlayerManager character; private void OnCollisionEnter2D(Collision2D col) { if(col.gameObject.tag == "Player" && !character.isBlinking) { character.BlinkHurt(); character.isBlinking = true; } } private void OnCollisionStay2D(Collision2D col) { if(col.gameObject.tag == "Player" && !character.isBlinking) { character.BlinkHurt(); character.isBlinking = true; } } }
using System; using System.Linq; using MassEffect.Exceptions; namespace MassEffect.Engine.Commands { using MassEffect.Interfaces; public class PlotJumpCommand : Command { public PlotJumpCommand(IGameEngine gameEngine) : base(gameEngine) { } public override void Execute(string[] commandArgs) { string shipName = commandArgs[1]; string starSystemName = commandArgs[2]; var ship = this.GetShipByName(shipName); this.ValidateAlive(ship); var oldStarSystem = ship.Location.Name; var starSystem=this.GameEngine.Galaxy.GetStarSystemByName(starSystemName); if (ship.Location == starSystem) { throw new ShipException(String.Format(Messages.ShipAlreadyInStarSystem,starSystemName)); } this.GameEngine.Galaxy.TravelTo(ship,starSystem); Console.WriteLine(Messages.ShipTraveled,shipName,oldStarSystem,ship.Location.Name); } } }
namespace MeterReader.Models.ViewModels { using System; public class StatisticByMonth { public Indication ColdWater { get; set; } public Indication HotWater { get; set; } public Indication Electric { get; set; } public Indication Gas { get; set; } public string MonthName { get; set; } } }
namespace Model.EF { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Student")] public partial class Student { [Key] public int MaHS { get; set; } [Display(Name ="Tên Học Sinh")] [StringLength(100)] public string HoTenHS { get; set; } [Display(Name ="Tên Phụ Huynh")] [StringLength(100)] public string HoTenPH { get; set; } [Display(Name ="Môn Học")] public int? MonHoc { get; set; } [Display(Name ="Lớp")] public int? Lop { get; set; } [Display(Name ="Học Phí")] public int? HocPhi { get; set; } [Display(Name = "Ngày Đăng Kí")] [Column(TypeName = "date")] public DateTime? NgayDangKi { get; set; } [Display(Name ="Ngày Bắt Đầu Học")] [Column(TypeName = "date")] public DateTime? NgayBatDauHoc { get; set; } [Display(Name ="Tình Trạng Học Tập")] public int? TinhTrangHT { get; set; } [Display(Name ="Tình Trạng Học Phí")] public int? TinhTrangHP { get; set; } [Display(Name ="Lời Nhắc")] public string LoiNhac { get; set; } [Display(Name ="Ngày Đóng Học Phí")] [Column(TypeName = "date")] public DateTime? NgayDongHocPhi { get; set; } [Display(Name ="Trạng Thái")] public bool? Status { get; set; } public virtual HocPhi HocPhi1 { get; set; } public virtual MonHoc MonHoc1 { get; set; } public virtual TinhTrangHocTap TinhTrangHocTap { get; set; } public virtual TinhTrangHocPhi TinhTrangHocPhi { get; set; } } }
using System.Collections.Generic; using System.Web.Mvc; namespace DevExpress.Web.Demos { public partial class ReportController : DemoController { public ActionResult FormattingRulesReport([ModelBinder(typeof(ParameterDictionaryBinder))] Dictionary<string, string> parameter) { var model = ReportDemoHelper.CreateModel("FormattingRules", parameter); ViewData["parameterConditionIndexParameter"] = SelectListItemHelper.GetFormattingRuleConditionItems((int)model.Report.Parameters["ConditionIndexParameter"].Value); ViewData["parameterStyleIndexParameter"] = SelectListItemHelper.GetFormattingRuleStyleItems((int)model.Report.Parameters["StyleIndexParameter"].Value); return DemoView("FormattingRulesReport", "SampleViewer", model); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Bogus; using Domain.Data.DataModels; using Domain.Ef; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace SimpleWebApi { public static class DbInitializeExpression { public static void DbInitialize(this IServiceCollection services) { var serviceProvider = services.BuildServiceProvider(); var context = serviceProvider.GetService<MyAppContext>(); if (File.Exists("trips.db")) { return; } else { context.Database.Migrate(); } TestData(context); } private static void TestData(MyAppContext context) { #region Locations var fakeLocations = new Faker<Locations>("ru") .RuleFor(x => x.LocationName, f => f.Address.City()); context.Locations.AddRange(fakeLocations.Generate(100)); context.SaveChanges(); #endregion #region Users var fakeUsers = new Faker<Users>("ru") .RuleFor(x => x.FirstName, f => f.Name.FirstName()) .RuleFor(x => x.LastName, f => f.Name.LastName()) .RuleFor(x => x.Patronimic, f => f.Name.Suffix()) .RuleFor(x => x.IsDriver, f => f.PickRandom(new List<bool> {false, false, true, false, false, false, false})) .RuleFor(x => x.YearOfBirth, f => f.Date.Between(DateTime.Now.AddYears(-70), DateTime.Now.AddYears(-20))); context.Users.AddRange(fakeUsers.Generate(10000)); context.SaveChanges(); #endregion #region Routes var locations = context.Locations.ToList(); var fakeRoutes = new Faker<Routes>("ru") .RuleFor(x => x.DestinationLocationId, f => f.PickRandom(locations.Select(s => s.Id))) .RuleFor(x => x.StartLocationId, f => f.PickRandom(locations.Select(s => s.Id))); context.Routes.AddRange(fakeRoutes.Generate(2000)); context.SaveChanges(); #endregion #region Trips var drivers = context.Users.Where(x => x.IsDriver == true).ToList(); var routes = context.Routes.ToList(); var fakeTrips = new Faker<Trips>("ru") .RuleFor(x => x.DriverId, f => f.PickRandom(drivers.Select(s => s.Id))) .RuleFor(x => x.RouteId, f => f.PickRandom(routes.Select(s => s.Id))) .RuleFor(x => x.StartTime, f => f.Date.Between(DateTime.Now.AddDays(1), DateTime.Now.AddDays(60))); context.Trips.AddRange(fakeTrips.Generate(1000)); context.SaveChanges(); #endregion #region Passangers var trips = context.Trips.ToList(); var passangerUsers = context.Users.Where(x => x.IsDriver != true).ToList(); var ran = new Random(); foreach (var trip in trips) { var inDbUsers = new List<Passangers>(); var pasUsers = passangerUsers.Take(ran.Next(15, 25)).ToList(); foreach (var pasUser in pasUsers) { passangerUsers.Remove(pasUser); var passanger = new Passangers { TripId = trip.Id, PassangerId = pasUser.Id }; inDbUsers.Add(passanger); } context.Passangers.AddRange(inDbUsers); } context.SaveChanges(); #endregion } } }
namespace MatchingBrackets { using System; using System.Collections.Generic; using System.Text; public class Startup { public static void Main(string[] args) { var input = Console.ReadLine(); Console.WriteLine(Execute(input)); } private static string Execute(string input) { var res = new StringBuilder(); var stack = new Stack<int>(); for (int i = 0; i < input.Length; i++) { if (input[i] == '(') { stack.Push(i); } else if (input[i] == ')') { var opening = stack.Pop(); var expression = input.Substring(opening, i - opening + 1); res.AppendLine(expression); } } return res.ToString().Trim(); } } }
using System; namespace STUFV { public class LifeSaversViewModel { public LifeSaversViewModel () { } } }
using Claudia.SoundCloud.EndPoints; using Claudia.SoundCloud.EndPoints.Tracks; using System; using System.Windows.Forms; namespace Claudia.Utility { /// <summary> /// 再生時に表示されるトースト/バルーン通知を管理します。 /// </summary> /// <typeparam name="T"> SCFavoriteObjects or Track </typeparam> public class NotifyMessage<T> { #region Constructor /// <summary> /// コンストラクタ /// </summary> /// <param name="track"></param> public NotifyMessage(T track) { using (var notifyIcon = new NotifyIcon { Visible = true, Icon = Properties.Resources.icon }) { var os = Environment.OSVersion; if (track is SCFavoriteObjects fav) { if (os.Version.Major >= 6 && os.Version.Minor >= 2) { notifyIcon.BalloonTipTitle = $"Claudia NowPlaying\r\n"; notifyIcon.BalloonTipText = $"{fav.Title}\r\n{fav.User.UserName}"; } else { notifyIcon.BalloonTipTitle = $"Claudia NowPlaying"; notifyIcon.BalloonTipText = $"{fav.Title} - {fav.User.UserName}\r\n"; } } else if (track is Track t) { if (os.Version.Major >= 6 && os.Version.Minor >= 2) { notifyIcon.BalloonTipTitle = $"Claudia NowPlaying\r\n"; notifyIcon.BalloonTipText = $"{t.Title}\r\n{t.User.UserName}"; } else { notifyIcon.BalloonTipTitle = $"Claudia NowPlaying"; notifyIcon.BalloonTipText = $"{t.Title} - {t.User.UserName}\r\n"; } } notifyIcon.ShowBalloonTip(3000); } } #endregion Constructor } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HNDunit20 { public partial class frmPractice : Form { ArrayList al = new ArrayList(); public frmPractice() { InitializeComponent(); } private void btnCreate_Click(object sender, EventArgs e) { Student temp = new Student(txtName.Text); al.Add(temp); txtName.Text=""; } private void btnCount_Click(object sender, EventArgs e) { lblOutput.Text = ""; //Student.getCount(); foreach(object obj in al) { if(obj != null) { Student temp = (Student)obj; lblOutput.Text += temp.Name + "\n"; } else { lblOutput.Text += "null\n"; } } lblOutput.Text += "Student objects:" + Student.getCount() + "\n"; lblOutput.Text += "ArrayList objects:" + al.Count.ToString() + "\n"; } private void btnRemove_Click(object sender, EventArgs e) { int index = Convert.ToInt32(nudIndex.Value); al[index] = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oop.BranchingOverBoolean { class Closed : IAccountState { public IAccountState Close() => this; public IAccountState Deposit(Action addToBalance) => this; public IAccountState Freeeze() => this; public IAccountState HolderVerified() => this; public IAccountState Withdraw(Action substractFromBalance) => this; } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using RabbitMQ.Services; namespace RabbitMQ { public static class ApplicationBuilderExtentions { public static Consumer Listener { get; set; } public static IApplicationBuilder UseRabbitListener(this IApplicationBuilder app) { Listener = app.ApplicationServices.GetService<Consumer>(); var life = app.ApplicationServices.GetService<IApplicationLifetime>(); life.ApplicationStarted.Register(OnStarted); //press Ctrl+C to reproduce if your app runs in Kestrel as a console app //life.ApplicationStopping.Register(OnStopping); return app; } private static void OnStarted() { Listener.ReceiveMessageFromQ(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SuperMarket.DAO { class NhapHangDAO { private static NhapHangDAO instance; public static NhapHangDAO Instance { get { if (instance == null) instance = new NhapHangDAO(); return NhapHangDAO.instance; } private set { NhapHangDAO.instance = value; } } private NhapHangDAO() { } public bool NhapHang(int Ma , string TenSP, string MaNCC, string TenNCC, int GiaNhap, int SoLuong ,string DonVi) { string query = "INSERT INTO dbo.NhapSP(Ma,TenSP ,MaNCC,TenNCC , GiaNhap,SoLuong,GhiChu )VALUES ( "+Ma+", N'" + TenSP + "' , '" + MaNCC + "' , '" + TenNCC + "' ," + GiaNhap + ", " + SoLuong + " , '"+DonVi+"' )"; int result = DataProvider.Instance.ExecuteNonQuery(query); return result > 0; } public bool NhapSpBaoQuat(int MaPhieu , string NgayNhap , int ThanhTien) { string query = "INSERT INTO dbo.NhapSpBaoQuat( MaPhieu , NgayNhap , ThanhTien )VALUES ( " + MaPhieu + " , '" + NgayNhap + "' , "+ThanhTien+")"; int result = DataProvider.Instance.ExecuteNonQuery(query); return result > 0; } public bool Insert(string Ma, string Ten, string MaNCC, int SoLuong, string DonVi) { string query = "INSERT INTO dbo.SanPham ( Ma, Ten, MaNCC, SoLuong, DonVi ) VALUES ( '" + Ma + "', N'" + Ten + "', '" + MaNCC + "', " + SoLuong + ", N'" + DonVi + "' )"; int result = DataProvider.Instance.ExecuteNonQuery(query); return result > 0; } public bool Update(int SoLuong,string Ma) { string query = "UPDATE dbo.SanPham SET SoLuong = '" + SoLuong + "' WHERE Ma= N'" + Ma + "'"; int results = DataProvider.Instance.ExecuteNonQuery(query); return results > 0; } public bool Search(string Ten) { string query = "select * from NhapSP where TenSP like '%" + Ten + "%'"; DataTable results = DataProvider.Instance.ExecuteQuery(query); return results.Rows.Count > 0; } } }
using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; /// <summary> /// Class responsible to manage login. /// </summary> public class UserManager: GameBase { private Info info; private string accountsPath; private const string MasterPassword = "LabDinRehab"; public List<string> Managers { get { return info.managers; } } public List<string> Players { get { return info.players; } } public List<string> Description { get { return info.description; } } public int AmountManagers { get { return info.managers.Count; } } public int AmountPlayers { get { return info.players.Count; } } // Use this for initialization void Awake () { info = new Info(); accountsPath = Application.dataPath + "\\Users\\"; if (!Directory.Exists(accountsPath)) Directory.CreateDirectory(accountsPath); accountsPath = accountsPath + "Accounts.dat"; if (!File.Exists(accountsPath)) File.Create(accountsPath); Load(); } /* /// <summary> /// Reads the specified file. /// </summary> /// <param name="file">File path.</param> private string[,] Read(string file) { string[,] result; string[] lines, line; int length = 2; line = new string[length]; if (!File.Exists(file)) { return null; } lines = File.ReadAllLines(file); result = new string[lines.Length, length]; for (int iUser = 0; iUser < lines.Length; iUser++) { line = lines[iUser].Split('\x09'); for (int iInfo = 0; iInfo < line.Length; iInfo++) { result[iUser, iInfo] = line[iInfo]; } } return result; }*/ /// <summary> /// Load current managers and passwords. /// </summary> void Load() { FileStream accounts = File.Open(accountsPath, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); if (accounts.Length > 0) info = (Info)bf.Deserialize(accounts); accounts.Close(); } /// <summary> /// Saves current managers and passwords. /// </summary> private void Save() { FileStream accounts = File.Open(accountsPath, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(accounts, info); accounts.Close(); } /// <summary> /// Checks the password. /// </summary> /// <returns><c>true</c>, if password was checked, <c>false</c> otherwise.</returns> /// <param name="UserNumber">User number.</param> /// <param name="password">Password.</param> public bool CheckPassword(int userNumber, string password) { return ((info.passwords[userNumber] == password) || (MasterPassword == password)); } /// <summary> /// Adds a new manager. /// </summary> /// <param name="name">Name.</param> /// <param name="password">Password.</param> public void AddManager(string name, string password) { if ((name != "") && (password != "")) { info.managers.Add(name); info.passwords.Add(password); Save(); } } /// <summary> /// Removes a manager. /// </summary> /// <param name="userNumber">User number.</param> /// <param name="password">Password.</param> public void RemoveManager(int userNumber, string password) { if (userNumber < AmountManagers) if (CheckPassword(userNumber, password)) { info.managers.RemoveAt(userNumber); info.passwords.RemoveAt(userNumber); Save(); } } /// <summary> /// Changes a manager. /// </summary> /// <param name="userNumber">User number.</param> /// <param name="name">Name.</param> /// <param name="password">Password.</param> public void ChangeManager(int userNumber, string name, string password) { if ((name != "") && (password != "") && (userNumber < AmountManagers)) { info.managers[userNumber] = name; info.passwords[userNumber] = password; Save(); } } /// <summary> /// Adds a player. /// </summary> /// <param name="name">Name.</param> /// <param name="information">Information.</param> public void AddPlayer(string name, string information) { if (name != "") { info.players.Add(name); if (information == "") info.description.Add("No description"); else info.description.Add(information); Save(); } } /// <summary> /// Removes a player. /// </summary> /// <param name="userNumber">User number.</param> /// <param name="password">Password.</param> public void RemovePlayer(int userNumber) { if (userNumber < AmountPlayers) { info.players.RemoveAt(userNumber); info.description.RemoveAt(userNumber); Save(); } } /// <summary> /// Changes a player. /// </summary> /// <param name="userNumber">User number.</param> /// <param name="name">Name.</param> /// <param name="password">Password.</param> public void ChangePlayer(int userNumber, string name, string information) { if ((name != "") && (userNumber < AmountManagers)) { info.players[userNumber] = name; if (information == "") info.description[userNumber] = "No description"; else info.description[userNumber] = information; Save(); } }} [Serializable] class Info { public List<string> managers, passwords, players, description; public Info() { managers = new List<string>(); passwords = new List<string>(); players = new List<string>(); description = new List<string>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace St.Eg.M2.Ex2.Generics.After { internal class Program { private static void Main(string[] args) { // TODO: create a dog with Age of type double // TODO: create a cat with Age of type int var dog = new Dog<int>(5); var cat = new Cat<double>(10.0); // TODO: output the age of each Console.WriteLine(dog.Age); Console.WriteLine(cat.Age); // TODO: print the types of Age for cat and dog Console.WriteLine(dog.Age.GetType().Name); Console.WriteLine(cat.Age.GetType().Name); } } public delegate void AgeUpdatedHandler(object sender, EventArgs args); // TODO: Make this a generic interface public interface IAnimal<T> { T Age { get; set; } void MakeSound(); event AgeUpdatedHandler AgeUpdated; } // TODO: make this generic too public abstract class Animal<T> { // TODO: change the type to the generic type private T _age; // TODO: change the type to the generic type public T Age { get { return _age; } set { _age = value; if (AgeUpdated != null) AgeUpdated(this, null); // TODO: modify to fire PropertyChanged } } public event AgeUpdatedHandler AgeUpdated; // TODO: Add an event for PropertyChanged public abstract void MakeSound(); } // TODO: Derive from generic public class Dog<T> : Animal<T> { public Dog() { } public Dog(T age) { Age = age; } public override void MakeSound() { Console.WriteLine("Woof!"); } } // TODO: Derive from generic public class Cat<T> : Animal<T> { public Cat() { } public Cat(T age) { Age = age; } public override void MakeSound() { Console.WriteLine("Meow!"); } } }
using System; using System.Linq; using System.Xml.Linq; using Cogito.Web.Configuration; namespace Cogito.IIS.Configuration { public class WebSystemWebServerGlobalModuleConfigurator : IWebElementConfigurator { readonly XElement element; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="element"></param> public WebSystemWebServerGlobalModuleConfigurator(XElement element) { this.element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Returns the configuration. /// </summary> /// <returns></returns> public XElement Element => element; public WebSystemWebServerGlobalModuleConfigurator Clear() { Element.RemoveNodes(); return this; } public WebSystemWebServerGlobalModuleConfigurator Remove(string moduleName) { Element.Elements().Where(i => (string)i.Attribute("name") == moduleName).Remove(); return this; } public WebSystemWebServerGlobalModuleConfigurator Add(string moduleName, string image) { Element.Add( new XElement("add", new XAttribute("name", image), new XAttribute("image", image))); return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Dorisol1019.MemorialArchiver.Domain.User; namespace Dorisol1019.MemorialArchiver.Infrastracture.User { public class InMemoryUserRepository : IUserRepository { private readonly Dictionary<long, UserEntity> dic = new Dictionary<long, UserEntity>(); public void Delete(UserEntity user) { dic.Remove(user.Id); } public UserEntity? FindById(long id) { dic.TryGetValue(id, out UserEntity? user); return user; } public UserEntity? FindByName(string name) { return dic.Select(e => e.Value).FirstOrDefault(e => e.Name == name); } public void Save(UserEntity user) { dic.Add(user.Id, user); } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; namespace Phenix.Test.使用指南._21._5 { class Program { [STAThread] static void Main(string[] args) { Console.WriteLine("请启动Bin.Top目录下的Phenix.Services.Host.x86/x64.exe程序"); Console.WriteLine("如需观察日志(被保存在TempDirectory子目录里)可将Host的Debugging功能菜单点亮"); Console.Write("准备好后请点回车继续:"); Console.ReadLine(); Phenix.Web.Client.Security.UserIdentity userIdentity = new Phenix.Web.Client.Security.UserIdentity("ADMIN", "ADMIN"); using (Phenix.Web.Client.HttpClient client = new Phenix.Web.Client.HttpClient("127.0.0.1", 8080, userIdentity)) { while (true) { using (HttpResponseMessage message = client.SecurityProxy.TryLogOnAsync().Result) { if (message.StatusCode == HttpStatusCode.OK) { Console.WriteLine("登录成功"); break; } Console.WriteLine("登录未成功:" + message.Content.ReadAsStringAsync().Result); Console.Write("请重新登录,输入ADMIN的口令:"); } userIdentity.Password = Console.ReadLine(); } Console.WriteLine(); Console.WriteLine("****************************"); Console.WriteLine("**** 开始测试拉取消息功能 ****"); Console.WriteLine(); try { client.MessageProxy.Send("ADMIN", "Hello pull!"); Console.WriteLine("发送消息成功!"); try { IDictionary<long, string> messages = client.MessageProxy.Receive(); foreach (KeyValuePair<long, string> kvp in messages) { Console.WriteLine("收取消息成功! id: " + kvp.Key + ", content:" + kvp.Value); try { client.MessageProxy.AffirmReceived(kvp.Key); Console.WriteLine("确认收到成功! id: " + kvp.Key); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine("调用AffirmReceived失败! error: " + Phenix.Core.AppUtilities.GetErrorMessage(ex)); Console.ReadLine(); } } } catch (Exception ex) { Console.WriteLine("调用Receive失败! error: " + Phenix.Core.AppUtilities.GetErrorMessage(ex)); Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine("调用Send失败! error: " + Phenix.Core.AppUtilities.GetErrorMessage(ex)); Console.ReadLine(); } Console.WriteLine("****************************"); Console.WriteLine("**** 开始测试推送消息功能 ****"); Console.WriteLine(); try { client.MessageProxy.Subscribe((proxy, messages) => { foreach (KeyValuePair<long, string> kvp in messages) { Console.WriteLine("收取消息成功! id: " + kvp.Key + ", content:" + kvp.Value); try { proxy.AffirmReceived(kvp.Key); Console.WriteLine("确认收到成功! id: " + kvp.Key); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine("调用AffirmReceived失败! error: " + Phenix.Core.AppUtilities.GetErrorMessage(ex)); Console.ReadLine(); } } }, (proxy, text) => { Console.WriteLine(text); Console.ReadLine(); }); } catch (Exception ex) { Console.WriteLine("调用Subscribe失败! error: " + Phenix.Core.AppUtilities.GetErrorMessage(ex)); Console.ReadLine(); } try { client.MessageProxy.Send("ADMIN", "Hello push!"); Console.WriteLine("发送消息成功!"); } catch (Exception ex) { Console.WriteLine("调用Send失败! error: " + Phenix.Core.AppUtilities.GetErrorMessage(ex)); Console.ReadLine(); } Console.WriteLine(); } Console.WriteLine("结束, 与数据库交互细节见日志"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.IO; using GLTF.Schema; using UnityEngine; namespace Egret3DExportTools { public static class GLTFExtension { public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, int[] arr, bool isIndices = false, BinaryWriter writer = null) { var count = arr.Length; if (count == 0) { MyLog.LogError("Accessors can not have a count of 0."); } var accessor = new Accessor(); accessor.Count = count; accessor.Type = GLTFAccessorAttributeType.SCALAR; int min = arr[0]; int max = arr[0]; for (var i = 1; i < count; i++) { var cur = arr[i]; if (cur < min) { min = cur; } if (cur > max) { max = cur; } } var byteOffset = writer.BaseStream.Position; if (max <= byte.MaxValue && min >= byte.MinValue && !isIndices) { accessor.ComponentType = GLTFComponentType.UnsignedByte; foreach (var v in arr) { writer.Write((byte)v); } } else if (max <= sbyte.MaxValue && min >= sbyte.MinValue && !isIndices) { accessor.ComponentType = GLTFComponentType.Byte; foreach (var v in arr) { writer.Write((sbyte)v); } } else if (max <= short.MaxValue && min >= short.MinValue && !isIndices) { accessor.ComponentType = GLTFComponentType.Short; foreach (var v in arr) { writer.Write((short)v); } } else if (max <= ushort.MaxValue && min >= ushort.MinValue) { accessor.ComponentType = GLTFComponentType.UnsignedShort; foreach (var v in arr) { writer.Write((ushort)v); } } else if (min >= uint.MinValue) { accessor.ComponentType = GLTFComponentType.UnsignedInt; foreach (var v in arr) { writer.Write((uint)v); } } else { accessor.ComponentType = GLTFComponentType.Float; foreach (var v in arr) { writer.Write((float)v); } } accessor.Min = new List<double> { min }; accessor.Max = new List<double> { max }; var byteLength = writer.BaseStream.Position - byteOffset; accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength); var id = new AccessorId { Id = root.Accessors.Count, Root = root }; root.Accessors.Add(accessor); return id; } public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Vector2[] arr, BufferViewId bufferViewId = null, BinaryWriter writer = null) { var count = arr.Length; if (count == 0) { MyLog.LogError("Accessors can not have a count of 0."); } var accessor = new Accessor(); accessor.ComponentType = GLTFComponentType.Float; accessor.Count = count; accessor.Type = GLTFAccessorAttributeType.VEC2; float minX = arr[0].x; float minY = arr[0].y; float maxX = arr[0].x; float maxY = arr[0].y; for (var i = 1; i < count; i++) { var cur = arr[i]; if (cur.x < minX) { minX = cur.x; } if (cur.y < minY) { minY = cur.y; } if (cur.x > maxX) { maxX = cur.x; } if (cur.y > maxY) { maxY = cur.y; } } accessor.Min = new List<double> { minX, minY }; accessor.Max = new List<double> { maxX, maxY }; var byteOffset = writer.BaseStream.Position; foreach (var vec in arr) { writer.Write(vec.x); writer.Write(vec.y); } var byteLength = writer.BaseStream.Position - byteOffset; if (bufferViewId != null) { accessor.BufferView = bufferViewId; accessor.ByteOffset = (int)byteOffset; } else { accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength); } var id = new AccessorId { Id = root.Accessors.Count, Root = root }; root.Accessors.Add(accessor); return id; } public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Vector3[] arr, BufferViewId bufferViewId = null, bool normalized = false, Transform rootNode = null, BinaryWriter writer = null) { var count = arr.Length; if (count == 0) { MyLog.LogError("Accessors can not have a count of 0."); } var accessor = new Accessor(); accessor.ComponentType = GLTFComponentType.Float; accessor.Count = count; accessor.Type = GLTFAccessorAttributeType.VEC3; /*float minX = arr[0].x; float minY = arr[0].y; float minZ = arr[0].z; float maxX = arr[0].x; float maxY = arr[0].y; float maxZ = arr[0].z; for (var i = 1; i < count; i++) { var cur = arr[i]; if (cur.x < minX) { minX = cur.x; } if (cur.y < minY) { minY = cur.y; } if (cur.z < minZ) { minZ = cur.z; } if (cur.x > maxX) { maxX = cur.x; } if (cur.y > maxY) { maxY = cur.y; } if (cur.z > maxZ) { maxZ = cur.z; } }*/ accessor.Normalized = normalized; //accessor.Min = new List<double> { minX, minY, minZ }; //accessor.Max = new List<double> { maxX, maxY, maxZ }; var byteOffset = writer.BaseStream.Position; Matrix4x4 mA = rootNode != null ? rootNode.localToWorldMatrix : new Matrix4x4(); Matrix4x4 mB = rootNode != null ? rootNode.parent.worldToLocalMatrix : new Matrix4x4(); foreach (var vec in arr) { writer.Write(vec.x); writer.Write(vec.y); writer.Write(vec.z); } var byteLength = writer.BaseStream.Position - byteOffset; if (bufferViewId != null) { accessor.BufferView = bufferViewId; accessor.ByteOffset = (int)byteOffset; } else { accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength); } var id = new AccessorId { Id = root.Accessors.Count, Root = root }; root.Accessors.Add(accessor); return id; } public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Vector4[] arr, BufferViewId bufferViewId = null, bool normalized = false, BinaryWriter writer = null) { var count = arr.Length; if (count == 0) { MyLog.LogError("Accessors can not have a count of 0."); } var accessor = new Accessor(); accessor.ComponentType = GLTFComponentType.Float; accessor.Count = count; accessor.Type = GLTFAccessorAttributeType.VEC4; float minX = arr[0].x; float minY = arr[0].y; float minZ = arr[0].z; float minW = arr[0].w; float maxX = arr[0].x; float maxY = arr[0].y; float maxZ = arr[0].z; float maxW = arr[0].w; for (var i = 1; i < count; i++) { var cur = arr[i]; if (cur.x < minX) { minX = cur.x; } if (cur.y < minY) { minY = cur.y; } if (cur.z < minZ) { minZ = cur.z; } if (cur.w < minW) { minW = cur.w; } if (cur.x > maxX) { maxX = cur.x; } if (cur.y > maxY) { maxY = cur.y; } if (cur.z > maxZ) { maxZ = cur.z; } if (cur.w > maxW) { maxW = cur.w; } } accessor.Normalized = normalized; accessor.Min = new List<double> { minX, minY, minZ, minW }; accessor.Max = new List<double> { maxX, maxY, maxZ, maxW }; var byteOffset = writer.BaseStream.Position; foreach (var vec in arr) { writer.Write(vec.x); writer.Write(vec.y); writer.Write(vec.z); writer.Write(vec.w); } var byteLength = writer.BaseStream.Position - byteOffset; if (bufferViewId != null) { accessor.BufferView = bufferViewId; accessor.ByteOffset = (int)byteOffset; } else { accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength); } var id = new AccessorId { Id = root.Accessors.Count, Root = root }; root.Accessors.Add(accessor); return id; } public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, Matrix4x4[] arr, BufferViewId bufferViewId = null, BinaryWriter writer = null) { var count = arr.Length; if (count == 0) { MyLog.LogError("Accessors can not have a count of 0."); } var accessor = new Accessor(); accessor.ComponentType = GLTFComponentType.Float; accessor.Count = count; accessor.Type = GLTFAccessorAttributeType.MAT4; var byteOffset = writer.BaseStream.Position; foreach (var vec in arr) { writer.Write(vec.m00); writer.Write(vec.m10); writer.Write(vec.m20); writer.Write(vec.m30); writer.Write(vec.m01); writer.Write(vec.m11); writer.Write(vec.m21); writer.Write(vec.m31); writer.Write(vec.m02); writer.Write(vec.m12); writer.Write(vec.m22); writer.Write(vec.m32); writer.Write(vec.m03); writer.Write(vec.m13); writer.Write(vec.m23); writer.Write(vec.m33); } var byteLength = writer.BaseStream.Position - byteOffset; if (bufferViewId != null) { accessor.BufferView = bufferViewId; accessor.ByteOffset = (int)byteOffset; } else { accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength); } var id = new AccessorId { Id = root.Accessors.Count, Root = root }; root.Accessors.Add(accessor); return id; } public static AccessorId WriteAccessor(this GLTFRoot root, BufferId bufferId, UnityEngine.Color[] arr, BufferViewId bufferViewId = null, BinaryWriter writer = null) { var count = arr.Length; if (count == 0) { MyLog.LogError("Accessors can not have a count of 0."); } var accessor = new Accessor(); accessor.ComponentType = GLTFComponentType.Float; accessor.Count = count; accessor.Type = GLTFAccessorAttributeType.VEC4; float minR = arr[0].r; float minG = arr[0].g; float minB = arr[0].b; float minA = arr[0].a; float maxR = arr[0].r; float maxG = arr[0].g; float maxB = arr[0].b; float maxA = arr[0].a; for (var i = 1; i < count; i++) { var cur = arr[i]; if (cur.r < minR) { minR = cur.r; } if (cur.g < minG) { minG = cur.g; } if (cur.b < minB) { minB = cur.b; } if (cur.a < minA) { minA = cur.a; } if (cur.r > maxR) { maxR = cur.r; } if (cur.g > maxG) { maxG = cur.g; } if (cur.b > maxB) { maxB = cur.b; } if (cur.a > maxA) { maxA = cur.a; } } accessor.Normalized = true; accessor.Min = new List<double> { minR, minG, minB, minA }; accessor.Max = new List<double> { maxR, maxG, maxB, maxA }; var byteOffset = writer.BaseStream.Position; foreach (var color in arr) { writer.Write(color.r); writer.Write(color.g); writer.Write(color.b); writer.Write(color.a); } var byteLength = writer.BaseStream.Position - byteOffset; if (bufferViewId != null) { accessor.BufferView = bufferViewId; accessor.ByteOffset = (int)byteOffset; } else { accessor.BufferView = root.WriteBufferView(bufferId, (int)byteOffset, (int)byteLength); } var id = new AccessorId { Id = root.Accessors.Count, Root = root }; root.Accessors.Add(accessor); return id; } public static BufferViewId WriteBufferView(this GLTFRoot root, BufferId bufferId, int byteOffset, int byteLength) { var bufferView = new BufferView { Buffer = bufferId, ByteOffset = byteOffset, ByteLength = byteLength, }; var id = new BufferViewId { Id = root.BufferViews.Count, Root = root }; root.BufferViews.Add(bufferView); return id; } public static byte[] WriteBinary(byte[] json, byte[] bin, BinaryWriter writer) { var resize = new List<byte>(json); while (resize.Count % 4 != 0) { resize.Add(0); } json = resize.ToArray(); resize = new List<byte>(bin); while (resize.Count % 4 != 0) { resize.Add(0); } bin = resize.ToArray(); // writer.Write(0x46546c67); writer.Write(2); writer.Write(0); //JSON CHUNK writer.Write(json.Length); writer.Write(0x4e4f534a); writer.Write(json); //BIN CHUNK writer.Write(bin.Length); writer.Write(0x004e4942); writer.Write(bin); //全部写完,长度重写 var ms = writer.BaseStream as MemoryStream; var length = (uint)ms.Length; ms.Position = 8; ms.Write(BitConverter.GetBytes((UInt32)length), 0, 4); writer.Close(); var res = ms.ToArray(); ms.Dispose(); return res; } } }
using AutoFixture; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Web.Controllers; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using SFA.DAS.ProviderUrlHelper; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Controllers.ApprenticesControllerTests { [TestFixture] public class WhenGettingSentTests { private string _newEmployerName; private ApprenticeController _sut; [SetUp] public void Arrange() { var fixture = new Fixture(); _newEmployerName = fixture.Create<string>(); _sut = new ApprenticeController(Mock.Of<IModelMapper>(), Mock.Of<ICookieStorageService<IndexRequest>>(), Mock.Of<ICommitmentsApiClient>()); var tempData = new TempDataDictionary(new DefaultHttpContext(), Mock.Of<ITempDataProvider>()); tempData[nameof(ConfirmViewModel.NewEmployerName)] = _newEmployerName; _sut.TempData = tempData; } [Test] public void ThenNewEmployerNameIsPopulatedFromTempData() { var result = _sut.Sent() as ViewResult; Assert.NotNull(result); Assert.AreEqual(_newEmployerName, result.Model as string); } } }
using System; namespace libairvidproto.types { public class BigIntValue : KeyValueBase { public BigIntValue(string key, long value) : base(key) { Value = value; } public long Value { get; private set; } public override void Encode(Encoder encoder) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using Tweetinvi.Core.Controllers; using Tweetinvi.Core.Factories; using Tweetinvi.Models; using Tweetinvi.Models.DTO; using Tweetinvi.Parameters; namespace Tweetinvi.Controllers.Messages { public class MessageController : IMessageController { private readonly IMessageQueryExecutor _messageQueryExecutor; private readonly IMessageFactory _messageFactory; public MessageController( IMessageQueryExecutor messageQueryExecutor, IMessageFactory messageFactory) { _messageQueryExecutor = messageQueryExecutor; _messageFactory = messageFactory; } public IEnumerable<IMessage> GetLatestMessagesReceived(int maximumMessages = TweetinviConsts.MESSAGE_GET_COUNT) { var parameter = new MessagesReceivedParameters { MaximumNumberOfMessagesToRetrieve = maximumMessages }; var messagesDTO = _messageQueryExecutor.GetLatestMessagesReceived(parameter); return _messageFactory.GenerateMessagesFromMessagesDTO(messagesDTO); } public IEnumerable<IMessage> GetLatestMessagesReceived(IMessagesReceivedParameters messagesReceivedParameters) { var messagesDTO = _messageQueryExecutor.GetLatestMessagesReceived(messagesReceivedParameters); return _messageFactory.GenerateMessagesFromMessagesDTO(messagesDTO); } public IEnumerable<IMessage> GetLatestMessagesSent(int maximumMessages = TweetinviConsts.MESSAGE_GET_COUNT) { var parameter = new MessagesSentParameters { MaximumNumberOfMessagesToRetrieve = maximumMessages }; var messagesDTO = _messageQueryExecutor.GetLatestMessagesSent(parameter); return _messageFactory.GenerateMessagesFromMessagesDTO(messagesDTO); } public IEnumerable<IMessage> GetLatestMessagesSent(IMessagesSentParameters messagesSentParameters) { var messagesDTO = _messageQueryExecutor.GetLatestMessagesSent(messagesSentParameters); return _messageFactory.GenerateMessagesFromMessagesDTO(messagesDTO); } // Publish Message public IMessage PublishMessage(string text, long recipientId) { return PublishMessage(text, new UserIdentifier(recipientId)); } public IMessage PublishMessage(string text, string recipientUserName) { return PublishMessage(text, new UserIdentifier(recipientUserName)); } public IMessage PublishMessage(string text, IUserIdentifier recipient) { return PublishMessage(new PublishMessageParameters(text, recipient)); } public IMessage PublishMessage(IPublishMessageParameters parameter) { if (parameter == null) { throw new ArgumentNullException("Parameter cannot be null."); } var publishedMessageDTO = _messageQueryExecutor.PublishMessage(parameter); return _messageFactory.GenerateMessageFromMessageDTO(publishedMessageDTO); } // Destroy Message public bool DestroyMessage(IMessage message) { if (message == null) { throw new ArgumentException("Message cannot be null"); } return DestroyMessage(message.MessageDTO); } public bool DestroyMessage(IMessageDTO messageDTO) { if (messageDTO == null) { throw new ArgumentException("Message cannot be null"); } messageDTO.IsMessageDestroyed = _messageQueryExecutor.DestroyMessage(messageDTO); return messageDTO.IsMessageDestroyed; } public bool DestroyMessage(long messageId) { return _messageQueryExecutor.DestroyMessage(messageId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; namespace AxisEq { /// <summary> /// Базовый класс эквайринга /// </summary> public class AbstractAcquiring { /// <summary> /// Последний считаный баланс /// </summary> public decimal Balance; /// <summary> /// Мнемоника эквайринга /// </summary> public virtual string Mnemonic { get { return ""; } } /// <summary> /// Оплаты по картам /// </summary> public List<CardPayment> CardPayments; /// <summary> /// Инициализация /// </summary> public virtual void Init(string currentDir) { } /// <summary> /// Сумма транзакции /// </summary> public decimal Amount { get; set; } /// <summary> /// Код авторизации /// </summary> public string AuthCode { get; set; } /// <summary> /// Номер карты /// </summary> public string CardNo { get; set; } /// <summary> /// Срок действия /// </summary> public string ExpireDate { get; set; } /// <summary> /// Код ошибки /// </summary> public int ErrorCode { get; set; } /// <summary> /// Номер чека /// </summary> public int NumCheck { get; set; } /// <summary> /// Описание ошибки /// </summary> public string ErrorDesc { get; set; } /// <summary> /// Время транзакции /// </summary> public DateTime DateTime { get; set; } /// <summary> /// Номер транзакции /// </summary> public string TransNum { get; set; } /// <summary> /// Номер терминала /// </summary> public string TermNo { get; set; } /// <summary> /// Данные второго трека /// </summary> protected string Track2Data { get; set; } /// <summary> /// Номер ссылочной транзакции /// </summary> public string RRN { get; set; } /// <summary> /// Сверка итогов с банком /// </summary> public virtual bool ZBankReport() { return true; } /// <summary> /// Сверка при х отчете /// </summary> public virtual bool XBankReport() { return true; } /// <summary> /// Транзакция Возврата(отмены) /// </summary> public virtual bool PurchaseReturn(string RetRRN,bool returnCurrSift) { return true; } /// <summary> /// Транзакция продажи /// </summary> public virtual bool PurchaseSale() { return true; } /// <summary> /// Отмена транзакции /// </summary> public virtual bool EmergencyCancel() { return true; } //Слип оплаты public string BankSlip { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CreatingAfarm { class duck { public void DuckSpeak() { Console.WriteLine("This is the Duck randy "); Console.WriteLine(" the Duck goes quakkk"); } public void Duckfood() { Console.WriteLine("The Duck eats hay and seeds"); } public void DuckWeight() { Console.WriteLine("The horse ways 14lb"); } public void DuckSpeed() { Console.WriteLine("The Duck runs 4 miles per hour"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SCANINOUTBL; using System.IO; namespace ScanIn_Out { public partial class frmRestor : Form { public Form1 f1; public DataLog logdata; DataTable dt; DataTable dto; public frmRestor() { InitializeComponent(); } private void frmRestor_Load(object sender, EventArgs e) { dt = logdata.GetLogs(); dto = logdata.GetLogsOrderID(); lbOrderID.DataSource = dto; lbOrderID.ValueMember = "OrderID"; lbOrderID.DisplayMember = "OrderID"; dgvOrders.DataSource = dt; updategrid(); lbOrderID.SelectedIndex = -1; label1.Text = ""; } void updategrid() { if (dgvOrders.Columns.Count == 12) { dgvOrders.Columns[0].Width = 100; dgvOrders.Columns[1].Width = 100; dgvOrders.Columns[2].Width = 150; dgvOrders.Columns[3].Visible = false; dgvOrders.Columns[4].Visible = false; dgvOrders.Columns[5].Width = 60; dgvOrders.Columns[6].Width = 60; dgvOrders.Columns[7].Width = 60; dgvOrders.Columns[8].Width = 80; dgvOrders.Columns[9].Width = 105; dgvOrders.Columns[10].Width = 60; dgvOrders.Columns[11].Width = 60; } } private void lbOrderID_SelectedIndexChanged(object sender, EventArgs e) { if (lbOrderID.SelectedIndex >= 0) { dgvOrders.DataSource = logdata.GetLogsbyOrderID(lbOrderID.Text); updategrid(); try { label1.Text = "Transaction Date: " + new DateTime(int.Parse(lbOrderID.Text.Substring(0, 4)), int.Parse(lbOrderID.Text.Substring(4, 2)), int.Parse(lbOrderID.Text.Substring(6, 2)), int.Parse(lbOrderID.Text.Substring(8, 2)), int.Parse(lbOrderID.Text.Substring(10, 2)), int.Parse(lbOrderID.Text.Substring(12, 2))).ToString(@"dddd, MMMM dd, yyyy Tran\sac\tion Ti\me: hh:mm:ss tt"); } catch (Exception ex) { label1.Text = ""; } } } private void btnRestor_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; if (lbOrderID.SelectedIndex == -1) { MessageBox.Show("Please Select Item to restore!", "Scan IN&OUT"); return; } if (dgvOrders.Rows[0].Cells[10].Value.ToString() == "true") { MessageBox.Show("You have aleready Restored this transaction!", "Scan IN&OUT"); return; } if (dgvOrders.Rows[0].Cells[11].Value.ToString() == "IN") { logdata.LogKeyIN = lbOrderID.Text; f1.ScanIN(); } else { logdata.LogKeyOUT = lbOrderID.Text; f1.ScanOUT(); } foreach (DataGridViewRow item in dgvOrders.Rows) { for (int i = 1; i <= (int)item.Cells[5].Value; i++) { if (item.Cells[11].Value.ToString() == "IN") { f1.txtINSKU.Text = item.Cells[0].Value.ToString(); } else { f1.txtOUTSKU.Text = item.Cells[0].Value.ToString(); } } } this.Cursor = Cursors.Default; this.Close(); } private void btnDelete_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { logdata.RemoveFromLog(lbOrderID.Text); dto.Rows.Remove(dto.Select("OrderID = '" + lbOrderID.Text + "'")[0]); lbOrderID.SelectedIndex = 0; } } private void btnExport_Click(object sender, EventArgs e) { if (lbOrderID.SelectedIndex == -1) { MessageBox.Show("Please Select Item to Export!", "Scan IN&OUT"); return; } SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "CSV files (*.csv)|*.csv|XML Files (*.xml)|*.xml"; sfd.ShowDialog(); if (sfd.FileName != "") { if (Path.GetExtension(sfd.FileName).ToLower().Contains("xml")) { DataSet ds = new DataSet(); ds.Tables.Add((DataTable)dgvOrders.DataSource); ds.WriteXml(sfd.FileName); } else { DataTable dt = (DataTable)dgvOrders.DataSource; StreamWriter sw = new StreamWriter(sfd.FileName, false); for (int i = 0; i < dt.Columns.Count; i++) { if (i != dt.Columns.Count - 1) { sw.Write(@"""" + dt.Columns[i].ColumnName + @""","); } else { sw.WriteLine(@"""" + dt.Columns[i].ColumnName + @""""); } } foreach (DataRow item in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { if (i != dt.Columns.Count - 1) { sw.Write(@"""" + item[i].ToString() + @""","); } else { sw.WriteLine(@"""" + item[i].ToString() + @""""); } } } sw.Close(); MessageBox.Show("Exported!"); } } } private void btnExportAll_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "CSV files (*.csv)|*.csv|XML Files (*.xml)|*.xml"; sfd.ShowDialog(); if (sfd.FileName != "") { if (Path.GetExtension(sfd.FileName).ToLower().Contains("xml")) { DataSet ds = new DataSet(); ds.Tables.Add(dt); ds.WriteXml(sfd.FileName); } else { StreamWriter sw = new StreamWriter(sfd.FileName, false); for (int i = 0; i < dt.Columns.Count; i++) { if (i != dt.Columns.Count - 1) { sw.Write(@"""" + dt.Columns[i].ColumnName + @""","); } else { sw.WriteLine(@"""" + dt.Columns[i].ColumnName + @""""); } } foreach (DataRow item in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { if (i != dt.Columns.Count - 1) { sw.Write(@"""" + item[i].ToString() + @""","); } else { sw.WriteLine(@"""" + item[i].ToString() + @""""); } } } sw.Close(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Window { class Program { static void Main(string[] args) { int[] a = { 4,5,6,1,2,3 }; int index = SearchRotated.search(a,0,a.Length-1,6); Console.WriteLine(index); Console.WriteLine(SearchRotated.binary_search(a,0,a.Length-1,6)); Console.ReadKey(); } public static void mywindow(int [] a , int windowSize) { if (a.Length < windowSize) { return; } LinkedList<int> window = new LinkedList<int>(); for (int i = 0; i < windowSize; i++) { while (window.Count != 0 && a[i] > a[window.Last()]) { window.RemoveLast(); } window.AddLast(i); } // Console.WriteLine("{0}",a[window.First()]); for (int i = windowSize; i < a.Length; i++) { while (window.Count != 0 && a[i] > a[window.Last()]) { window.RemoveLast(); } if (window.Count > 0 && window.First() <= i -windowSize) { window.RemoveFirst(); } window.AddLast(i); Console.WriteLine("{0}", a[window.First()]); } } } }
using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using static System.Net.Mime.MediaTypeNames; namespace FocusStart_TeskTask_Java_.Net_ { class Program { static void Main(string[] args) { new MergeFileProgram().Run(args); Console.ReadKey(); } } }
using System; class SpiralMatrix { private static void Main() { Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!"); while (true) { int iN; do { Console.Write(@"Enter positive integer number N (1 <= N <= 20). : "); } while (!int.TryParse(Console.ReadLine(), out iN) && iN <= 20 && iN >= 1); int[,] aiNum = new int[iN,iN]; string sDir = "R"; int iCol = -1, iMaxNum = iN*iN, iRow = 0, iMoreToLeft = 0; for (int i = 1; i <= iMaxNum; i++) { if (sDir == "R") { iCol++; aiNum[iRow, iCol] = i; if (iCol == (iN - 1) - iRow && iRow <= iN / 2) { sDir = "D"; } } else if (sDir == "D") { iRow++; aiNum[iRow, iCol] = i; if (iRow == iCol) { sDir = "L"; } } else if (sDir == "L") { iCol--; aiNum[iRow, iCol] = i; if (iCol == iMoreToLeft) { sDir = "U"; iMoreToLeft++; } } else if (sDir == "U") { iRow--; aiNum[iRow, iCol] = i; if (iCol == iRow - 1) { sDir = "R"; } } } for (int i = 0; i < iN; i++) { for (int j = 0; j < iN; j++) { Console.Write("{0,4}",aiNum[i,j]); } Console.WriteLine(); } } } }
using UnityEngine; [RequireComponent(typeof(EntityBase))] [DisallowMultipleComponent] public class PathfindingAgent : MonoBehaviour { [SerializeField, Min(0)] [Tooltip("How many units the Entity moves per second.")] public float walkSpeed = 1f; [SerializeField, Min(0)] [Tooltip("How long it takes to climb a ladder in seconds.")] public float ladderClimbSpeed = 0.1f; [SerializeField] public float speedMultiplyer = 1f; private EntityBase entity; private float layerChangeProgress; public NavPath path { get; private set; } private void Awake() { this.entity = this.GetComponent<EntityBase>(); } public void update() { if(this.hasPath()) { PathPoint currentWaypoint = this.path.targetPoint; Vector2 workerPos = this.entity.worldPos; bool posMatch = workerPos == currentWaypoint.worldPos; bool depthMatch = entity.depth == currentWaypoint.depth; if(posMatch) { if(depthMatch) { this.path.nextPoint(); if(this.path.targetIndex >= path.pointCount) { // Reached the end of the path. if(this.path.endingLookDirection != null) { this.entity.rotation = this.path.endingLookDirection; } this.stop(); return; } currentWaypoint = this.path.targetPoint; } else { if(this.layerChangeProgress == 0) { // First frame climbing, start an animation if(this.entity.depth > currentWaypoint.depth) { //this.worker.animator.playClip("ClimbLadderUp"); } else { //this.worker.animator.playClip("ClimbLadderDown"); } } this.layerChangeProgress += Time.deltaTime; if(this.layerChangeProgress > this.ladderClimbSpeed) { this.layerChangeProgress = 0; this.entity.depth = currentWaypoint.depth; } } } Vector3 posBeforeMove = this.transform.position; // Move the Worker towards the next point on the X and Y axis. this.transform.position = Vector2.MoveTowards( transform.position, currentWaypoint.worldPos, this.walkSpeed * this.speedMultiplyer * Time.deltaTime); // Update the direction the Worker is looking. Vector2 direction = this.transform.position - posBeforeMove; this.entity.rotation = Rotation.directionToRotation(direction); } } private void OnDrawGizmos() { if(this.hasPath()) { for(int i = this.path.targetIndex; i < this.path.pointCount; i++) { Gizmos.color = Color.yellow; if(i == this.path.targetIndex) { Gizmos.DrawLine( this.transform.position, this.path.getPoint(i).worldPos); } else { Gizmos.DrawLine( this.path.getPoint(i - 1).worldPos, this.path.getPoint(i).worldPos); } } for(int i = 0; i < this.path.pointCount; i++) { Gizmos.DrawSphere(this.path.getPoint(i).worldPos, 0.1f); } } } /// <summary> /// Stops the Worker. This will delete the path. /// </summary> public void stop() { this.path = null; } /// <summary> /// Returns true if the Worker has a path that they are following. /// </summary> public bool hasPath() { return this.path != null; } public void setPath(NavPath path) { this.path = path; } /* /// <summary> /// Returns the distance from the Worker to the end of the path in a straight line. /// -1 is returned if the Worker has no path. /// </summary> public float getDirectDistanceToEnd() { if(!this.hasPath()) { return -1f; } float dis = Vector2.Distance(this.entity.getCellPos(), this.path.endPoint.worldPos); // Add the total number of levels that will be crossed dis += Mathf.Abs(this.path.endPoint.depth - this.entity.depth) * Position.LAYER_DISTANCE_COST; return dis; } /// <summary> /// Returns the distance the worker has left on their path. /// -1 is returned if the Worker has no path. /// </summary> public float getDistanceToEnd() { if(!this.hasPath()) { return -1f; } // Start off with the distance from the Worker to the next node. float dis = Vector2.Distance(this.entity.getCellPos(), this.path.targetPoint.worldPos); dis += Mathf.Abs(this.entity.depth - this.path.targetPoint.depth) * Position.LAYER_DISTANCE_COST; // Total the distances between the nodes. for(int i = this.path.targetIndex; i < this.path.pointCount - 1; i++) { PathPoint p1 = this.path.getPoint(i); PathPoint p2 = this.path.getPoint(i + 1); // X and Y distance. dis += Vector2.Distance(p1.worldPos, p2.worldPos); // Depth change distance dis += Mathf.Abs(p1.depth - p2.depth) * Position.LAYER_DISTANCE_COST; } // Add the total number of levels that will be crossed dis += Mathf.Abs(this.path.getPoint(this.path.pointCount - 1).depth - this.entity.depth) * Position.LAYER_DISTANCE_COST; return dis; } */ /// <summary> /// Attempts to calculate a path to the passed destination. /// </summary> public NavPath calculatePath(Position destination, bool stopAdjacentToFinish = false, Rotation endingRotation = null) { if(this.entity.position == destination) { if(stopAdjacentToFinish) { //dest = free position adjacent to entity World w = this.entity.world; foreach(Rotation r in Rotation.ALL) { Position p = destination + r; if(!w.isOutOfBounds(p) && w.getCellState(p).data.isWalkable) { destination = p; stopAdjacentToFinish = false; // TODO looking rot? } } } else { return new NavPath( new PathPoint[] { new PathPoint(destination) }, endingRotation); } } else if(Vector2Int.Distance(this.entity.position.vec2Int, destination.vec2Int) == 1) { // Next to destination if(stopAdjacentToFinish) { return new NavPath( new PathPoint[] { new PathPoint(this.entity.position) }, // Go to their own spot Rotation.directionToRotation(destination.vec2Int - this.entity.getCellPos())); } } // Return if either the start of the end is out of the world if(this.entity.world.isOutOfBounds(this.entity.position) || this.entity.world.isOutOfBounds(destination)) { return null; } // Try and find a path. PathPoint[] pathPoints = this.entity.world.navManager.findPath( this.entity.position, destination, stopAdjacentToFinish); if(pathPoints == null) { // Unable to find a path, return null. //Debug.Log(this.entity.name + " could not find a path to " + destination); return null; } Rotation endRot; if(endingRotation != null) { endRot = endingRotation; } else { endRot = stopAdjacentToFinish ? Rotation.directionToRotation(destination.vec2Int - pathPoints[pathPoints.Length - 1].cellPos) : null; } return new NavPath(pathPoints, endRot); } }
using System; using System.Net; using IMessage = ResumeEditor.Messages.IMessage; namespace ResumeEditor.Messages { public abstract class Message : IMessage { public abstract int ByteLength { get; } protected int CheckWritten(int written) { if (written != ByteLength) throw new MessageException("Message encoded incorrectly. Incorrect number of bytes written"); return written; } public abstract void Decode(byte[] buffer, int offset, int length); public byte[] Encode() { byte[] buffer = new byte[ByteLength]; Encode(buffer, 0); return buffer; } public abstract int Encode(byte[] buffer, int offset); static public byte ReadByte(byte[] buffer, int offset) { return buffer[offset]; } static public byte ReadByte(byte[] buffer, ref int offset) { byte b = buffer[offset]; offset++; return b; } static public byte[] ReadBytes(byte[] buffer, int offset, int count) { return ReadBytes(buffer, ref offset, count); } static public byte[] ReadBytes(byte[] buffer, ref int offset, int count) { byte[] result = new byte[count]; Buffer.BlockCopy(buffer, offset, result, 0, count); offset += count; return result; } static public short ReadShort(byte[] buffer, int offset) { return ReadShort(buffer, ref offset); } static public short ReadShort(byte[] buffer, ref int offset) { short ret = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, offset)); offset += 2; return ret; } static public string ReadString(byte[] buffer, int offset, int count) { return ReadString(buffer, ref offset, count); } static public string ReadString(byte[] buffer, ref int offset, int count) { string s = System.Text.Encoding.ASCII.GetString(buffer, offset, count); offset += count; return s; } static public int ReadInt(byte[] buffer, int offset) { return ReadInt(buffer, ref offset); } static public int ReadInt(byte[] buffer, ref int offset) { int ret = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, offset)); offset += 4; return ret; } static public long ReadLong(byte[] buffer, int offset) { return ReadLong(buffer, ref offset); } static public long ReadLong(byte[] buffer, ref int offset) { long ret = IPAddress.NetworkToHostOrder(BitConverter.ToInt64(buffer, offset)); offset += 8; return ret; } static public int Write(byte[] buffer, int offset, byte value) { buffer[offset] = value; return 1; } static public int Write(byte[] dest, int destOffset, byte[] src, int srcOffset, int count) { Buffer.BlockCopy(src, srcOffset, dest, destOffset, count); return count; } static public int Write(byte[] buffer, int offset, ushort value) { return Write(buffer, offset, (short)value); } static public int Write(byte[] buffer, int offset, short value) { offset += Write(buffer, offset, (byte)(value >> 8)); offset += Write(buffer, offset, (byte)value); return 2; } static public int Write(byte[] buffer, int offset, int value) { offset += Write(buffer, offset, (byte)(value >> 24)); offset += Write(buffer, offset, (byte)(value >> 16)); offset += Write(buffer, offset, (byte)(value >> 8)); offset += Write(buffer, offset, (byte)(value)); return 4; } static public int Write(byte[] buffer, int offset, uint value) { return Write(buffer, offset, (int)value); } static public int Write(byte[] buffer, int offset, long value) { offset += Write(buffer, offset, (int)(value >> 32)); offset += Write(buffer, offset, (int)value); return 8; } static public int Write(byte[] buffer, int offset, ulong value) { return Write(buffer, offset, (long)value); } static public int Write(byte[] buffer, int offset, byte[] value) { return Write(buffer, offset, value, 0, value.Length); } static public int WriteAscii(byte[] buffer, int offset, string text) { for (int i = 0; i < text.Length; i++) Write(buffer, offset + i, (byte)text[i]); return text.Length; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Objects; namespace birdepobenzin.dataaccess.Helper { public class QueryExecuter { public void QueryExecute() { } } }
using Crystal.Plot2D.Common; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Crystal.Plot2D.Charts { public class ViewportHostPanel : ViewportPanel, IPlotterElement { static ViewportHostPanel() { EventManager.RegisterClassHandler(typeof(ViewportHostPanel), PlotterBase.PlotterChangedEvent, new PlotterChangedEventHandler(OnPlotterChanged)); } public ViewportHostPanel() { RenderTransform = translateTransform; #if false // for debug purposes Width = 100; Height = 100; Background = Brushes.PaleGreen.MakeTransparent(0.2); #endif } private static void OnPlotterChanged(object sender, PlotterChangedEventArgs e) { ViewportHostPanel owner = (ViewportHostPanel)sender; if (owner.plotter != null && e.PreviousPlotter != null) { owner.viewport.PropertyChanged -= owner.Viewport_PropertyChanged; owner.viewport = null; owner.plotter = null; } if (owner.plotter == null && e.CurrentPlotter != null) { owner.plotter = (PlotterBase)e.CurrentPlotter; owner.viewport = owner.plotter.Viewport; owner.viewport.PropertyChanged += owner.Viewport_PropertyChanged; } } readonly TranslateTransform translateTransform = new(); private readonly Canvas hostingCanvas = new(); internal Canvas HostingCanvas { get { return hostingCanvas; } } #region IPlotterElement Members private PlotterBase plotter; protected PlotterBase Plotter => plotter; Viewport2D viewport; public virtual void OnPlotterAttached(PlotterBase plotter) { this.plotter = (PlotterBase)plotter; viewport = this.plotter.Viewport; if (!IsMarkersHost) { plotter.CentralGrid.Children.Add(hostingCanvas); } if (Parent == null) { hostingCanvas.Children.Add(this); } this.plotter.Viewport.PropertyChanged += Viewport_PropertyChanged; } public virtual void OnPlotterDetaching(PlotterBase _plotter) { plotter.Viewport.PropertyChanged -= Viewport_PropertyChanged; if (!IsMarkersHost) { _plotter.CentralGrid.Children.Remove(hostingCanvas); } hostingCanvas.Children.Remove(this); plotter = null; } PlotterBase IPlotterElement.Plotter => plotter; protected override void OnChildDesiredSizeChanged(UIElement child) { InvalidatePosition((FrameworkElement)child); } Vector prevVisualOffset; bool sizeChanged = true; DataRect visibleWhileCreation; protected virtual void Viewport_PropertyChanged(object sender, ExtendedPropertyChangedEventArgs e) { if (e.PropertyName == "Visible") { DataRect visible = (DataRect)e.NewValue; DataRect prevVisible = (DataRect)e.OldValue; if (prevVisible.Size.EqualsApproximately(visible.Size) && !sizeChanged) { var transform = viewport.Transform; Point prevLocation = prevVisible.Location.ViewportToScreen(transform); Point location = visible.Location.ViewportToScreen(transform); Vector offset = prevLocation - location; translateTransform.X += offset.X; translateTransform.Y += offset.Y; } else { visibleWhileCreation = visible; translateTransform.X = 0; translateTransform.Y = 0; InvalidateMeasure(); } sizeChanged = false; } else if (e.PropertyName == "Output") { sizeChanged = true; translateTransform.X = 0; translateTransform.Y = 0; InvalidateMeasure(); } prevVisualOffset = VisualOffset; } #endregion protected internal override void OnChildAdded(FrameworkElement child) { if (plotter == null) { return; } InvalidatePosition(child); //Dispatcher.BeginInvoke(((Action)(()=> InvalidatePosition(child))), DispatcherPriority.ApplicationIdle); } private DataRect overallViewportBounds = DataRect.Empty; internal DataRect OverallViewportBounds { get { return overallViewportBounds; } set { overallViewportBounds = value; } } private BoundsUnionMode boundsUnionMode; internal BoundsUnionMode BoundsUnionMode { get { return boundsUnionMode; } set { boundsUnionMode = value; } } protected override void InvalidatePosition(FrameworkElement child) { invalidatePositionCalls++; if (viewport == null) { return; } if (child.Visibility != Visibility.Visible) { return; } var transform = viewport.Transform.WithScreenOffset(-translateTransform.X, -translateTransform.Y); Size elementSize = GetElementSize(child, AvailableSize, transform); child.Measure(elementSize); Rect bounds = GetElementScreenBounds(transform, child); child.Arrange(bounds); var viewportBounds = Viewport2D.GetContentBounds(this); if (!viewportBounds.IsEmpty) { overallViewportBounds = viewportBounds; } UniteWithBounds(transform, bounds); if (!InBatchAdd) { Viewport2D.SetContentBounds(this, overallViewportBounds); ContentBoundsChanged.Raise(this); } } private void UniteWithBounds(CoordinateTransform transform, Rect bounds) { var childViewportBounds = bounds.ScreenToViewport(transform); if (boundsUnionMode == BoundsUnionMode.Bounds) { overallViewportBounds.Union(childViewportBounds); } else { overallViewportBounds.Union(childViewportBounds.GetCenter()); } } int invalidatePositionCalls = 0; internal override void BeginBatchAdd() { base.BeginBatchAdd(); invalidatePositionCalls = 0; } internal override void EndBatchAdd() { base.EndBatchAdd(); if (plotter == null) { return; } UpdateContentBounds(Children.Count > 0 && invalidatePositionCalls == 0); } public void UpdateContentBounds() { UpdateContentBounds(true); } private void UpdateContentBounds(bool recalculate) { if (recalculate) { var transform = plotter.Viewport.Transform.WithScreenOffset(-translateTransform.X, -translateTransform.Y); overallViewportBounds = DataRect.Empty; foreach (FrameworkElement child in Children) { if (child != null) { if (child.Visibility != Visibility.Visible) { continue; } Rect bounds = GetElementScreenBounds(transform, child); UniteWithBounds(transform, bounds); } } } Viewport2D.SetContentBounds(this, overallViewportBounds); ContentBoundsChanged.Raise(this); } protected override Size ArrangeOverride(Size finalSize) { if (plotter == null) { return finalSize; } var transform = plotter.Viewport.Transform.WithScreenOffset(-translateTransform.X, -translateTransform.Y); overallViewportBounds = DataRect.Empty; foreach (UIElement child in InternalChildren) { if (child != null) { if (child.Visibility != Visibility.Visible) { continue; } Rect bounds = GetElementScreenBounds(transform, child); child.Arrange(bounds); UniteWithBounds(transform, bounds); } } if (!InBatchAdd) { Viewport2D.SetContentBounds(this, overallViewportBounds); ContentBoundsChanged.Raise(this); } return finalSize; } public event EventHandler ContentBoundsChanged; protected override Size MeasureOverride(Size availableSize) { AvailableSize = availableSize; if (plotter == null) { if (availableSize.Width.IsInfinite() || availableSize.Height.IsInfinite()) { return new Size(); } return availableSize; } var transform = plotter.Viewport.Transform; foreach (FrameworkElement child in InternalChildren) { if (child != null) { Size elementSize = GetElementSize(child, availableSize, transform); child.Measure(elementSize); } } if (availableSize.Width.IsInfinite()) { availableSize.Width = 0; } if (availableSize.Height.IsInfinite()) { availableSize.Height = 0; } return availableSize; } } public enum BoundsUnionMode { Center, Bounds } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonInheritance { class Child : Person { public Child(string name, int age) : base(name, age) { } public override int Age { get { return base.Age; } set { base.Age = value; } } } }
using System; using System.Collections.Generic; using Hl7.Fhir.Support; using System.Xml.Linq; /* Copyright (c) 2011-2012, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // // Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08 // namespace Hl7.Fhir.Model { /// <summary> /// A measured or measurable amount /// </summary> [FhirComposite("Quantity")] public partial class Quantity : Element { /// <summary> /// how the Quantity should be understood and represented /// </summary> public enum QuantityCompararator { LessThan, // The actual value is less than the given value LessOrEqual, // The actual value is less than or equal to the given value GreaterOrEqual, // The actual value is greater than or equal to the given value GreaterThan, // The actual value is greater than the given value } /// <summary> /// Conversion of QuantityCompararatorfrom and into string /// <summary> public static class QuantityCompararatorHandling { public static bool TryParse(string value, out QuantityCompararator result) { result = default(QuantityCompararator); if( value=="<") result = QuantityCompararator.LessThan; else if( value=="<=") result = QuantityCompararator.LessOrEqual; else if( value==">=") result = QuantityCompararator.GreaterOrEqual; else if( value==">") result = QuantityCompararator.GreaterThan; else return false; return true; } public static string ToString(QuantityCompararator value) { if( value==QuantityCompararator.LessThan ) return "<"; else if( value==QuantityCompararator.LessOrEqual ) return "<="; else if( value==QuantityCompararator.GreaterOrEqual ) return ">="; else if( value==QuantityCompararator.GreaterThan ) return ">"; else throw new ArgumentException("Unrecognized QuantityCompararator value: " + value.ToString()); } } /// <summary> /// Numerical value (with implicit precision) /// </summary> public FhirDecimal Value { get; set; } /// <summary> /// Relationship of stated value to actual value /// </summary> public Code<Quantity.QuantityCompararator> Comparator { get; set; } /// <summary> /// Unit representation /// </summary> public FhirString Units { get; set; } /// <summary> /// System that defines coded unit form /// </summary> public FhirUri System { get; set; } /// <summary> /// Coded form of the unit /// </summary> public Code Code { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp33 { class Futbolcu { public string AdSoyad { get; set; } public int FormaNo { get; set; } public int Hiz { get; set; } public int Dayaniklik { get; set; } public int Pas { get; set; } public int Sut { get; set; } public int Yetenek { get; set; } public int Kararlilik { get; set; } public int DogalForm { get; set; } public int Sans { get; set; } public Futbolcu(string AdSoyad,int FormaNo) { this.AdSoyad = AdSoyad; this.FormaNo = FormaNo; Hiz = RastgeleSayiUret.Uret(50, 100); Dayaniklik = RastgeleSayiUret.Uret(50, 100); Pas = RastgeleSayiUret.Uret(50, 100); Sut = RastgeleSayiUret.Uret(50, 100); Yetenek = RastgeleSayiUret.Uret(50, 100); Kararlilik = RastgeleSayiUret.Uret(50, 100); DogalForm = RastgeleSayiUret.Uret(50, 100); Sans = RastgeleSayiUret.Uret(50, 100); } public virtual bool PasVer() { double PasSkor; PasSkor = Pas * 0.3 + Yetenek * 0.3 + Dayaniklik * 0.1 + DogalForm * 0.1 + Sans * 0.2; if (PasSkor > 60) return true; else return false; } public virtual bool GolVurusu() { double GolSkor; GolSkor = Yetenek * 0.3 + Sut * 0.2 + Kararlilik * 0.1 + DogalForm * 0.1 +Hiz * 0.1 + Sans * 0.2; if (GolSkor > 70) return true; else return false; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DRL_2021 { class PrimitiveBatch<T> : IDisposable where T : struct, IVertexType { BlendState BlendState; SamplerState SamplerState; DepthStencilState DepthStencilState; RasterizerState RasterizerState; Effect Effect; GraphicsDevice GraphicsDevice; Texture Texture; BasicEffect BasicEffect; EffectPass BasicPass; T[] Vertices; int PositionInBuffer; PrimitiveType PrimitiveType; int VerticesPerPrimitive; int MinVertices; bool HasBegun = false; bool IsDisposed = false; public PrimitiveBatch(GraphicsDevice graphicsDevice, int size = 500) { if (graphicsDevice == null) { throw new ArgumentNullException("graphicsDevice"); } GraphicsDevice = graphicsDevice; Vertices = new T[size]; BasicEffect = new BasicEffect(graphicsDevice); BasicEffect.VertexColorEnabled = true; BasicEffect.Projection = Matrix.CreateOrthographicOffCenter (0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1); BasicEffect.World = Matrix.Identity; BasicEffect.View = Matrix.CreateLookAt(Vector3.Zero, Vector3.Forward, Vector3.Up); BasicPass = BasicEffect.CurrentTechnique.Passes[0]; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing && !IsDisposed) { if (BasicEffect != null) BasicEffect.Dispose(); IsDisposed = true; } } private void Setup() { var gd = GraphicsDevice; gd.BlendState = BlendState; gd.DepthStencilState = DepthStencilState; gd.RasterizerState = RasterizerState; gd.SamplerStates[0] = SamplerState; //BasicPass.Apply(); } public void Begin(PrimitiveType primitiveType, Texture texture = null, BlendState blendState = null, SamplerState samplerState = null, DepthStencilState depthStencilState = null, RasterizerState rasterizerState = null, Effect effect = null, Matrix? transform = null, Matrix? projection = null) { if (HasBegun) { throw new InvalidOperationException ("End must be called before Begin can be called again."); } this.PrimitiveType = primitiveType; PositionInBuffer = 0; VerticesPerPrimitive = NumVertsPerPrimitive(primitiveType); MinVertices = MinVerts(primitiveType); BlendState = blendState ?? BlendState.AlphaBlend; SamplerState = samplerState ?? SamplerState.LinearClamp; DepthStencilState = depthStencilState ?? DepthStencilState.None; RasterizerState = rasterizerState ?? RasterizerState.CullCounterClockwise; Effect = effect; Texture = texture; BasicEffect.World = transform ?? Matrix.Identity; BasicEffect.Projection = projection ?? Matrix.Identity; BasicEffect.View = Matrix.Identity; HasBegun = true; } public void End() { if (!HasBegun) { throw new InvalidOperationException ("Begin must be called before End can be called."); } Flush(); HasBegun = false; } private void Flush() { if (!HasBegun) { throw new InvalidOperationException ("Begin must be called before Flush can be called."); } if (PositionInBuffer == 0) { return; } Setup(); Draw(Effect, Texture); T v1 = Vertices[PositionInBuffer - 2]; T v2 = Vertices[PositionInBuffer - 1]; if (Vertices.Length % 2 == 1) { T h = v1; v1 = v2; v2 = h; } // now that we've drawn, it's ok to reset positionInBuffer back to zero, // and write over any vertices that may have been set previously. PositionInBuffer = 0; switch (PrimitiveType) { case (PrimitiveType.LineStrip): AddVertex(v2); break; case (PrimitiveType.TriangleStrip): AddVertex(v1); AddVertex(v2); break; } } public void Draw(Effect effect, Texture texture) { int primitiveCount = (PositionInBuffer - MinVertices) / VerticesPerPrimitive; GraphicsDevice.Textures[0] = texture; if (effect != null) { var passes = effect.CurrentTechnique.Passes; foreach (var pass in passes) { pass.Apply(); GraphicsDevice.Textures[0] = texture; GraphicsDevice.DrawUserPrimitives<T>(PrimitiveType, Vertices, 0, primitiveCount); } } else { GraphicsDevice.DrawUserPrimitives<T>(PrimitiveType, Vertices, 0, primitiveCount); } } public void AddVertex(T vertex) { if (!HasBegun) { throw new InvalidOperationException ("Begin must be called before AddVertex can be called."); } bool newPrimitive = ((PositionInBuffer % VerticesPerPrimitive) == 0); if (newPrimitive && (PositionInBuffer + VerticesPerPrimitive) >= Vertices.Length) { Flush(); } Vertices[PositionInBuffer] = vertex; PositionInBuffer++; } static private int NumVertsPerPrimitive(PrimitiveType primitive) { switch (primitive) { case PrimitiveType.LineList: return 2; case PrimitiveType.TriangleList: return 3; case PrimitiveType.LineStrip: case PrimitiveType.TriangleStrip: return 1; default: throw new InvalidOperationException("primitive is not valid"); } } static private int MinVerts(PrimitiveType primitive) { switch (primitive) { case PrimitiveType.LineList: case PrimitiveType.TriangleList: return 0; case PrimitiveType.LineStrip: return 1; case PrimitiveType.TriangleStrip: return 2; default: throw new InvalidOperationException("primitive is not valid"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain.Enums { public enum ImageFilters { BLUR, MONO, SEPIA, NEGATIVE, PAINT, PIXEL } }
using NUnit.Framework; using NASTYADANYA; namespace NASTYADANYATest { [TestFixture] public class AcosTests { [TestCase(0, 1.5708)] [TestCase(1, 0.0000)] [TestCase(-1, 3.1416)] public void CalculateTest(double firstValue, double expected) { var calculator = new Acos(); double actualResult = calculator.Calculate(-1); Assert.AreEqual(3.1416, actualResult, 0.0001); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using CityGenerator; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CityGenerator.Tests { [TestClass()] public class TensorFieldTests { [TestMethod()] public void TensorFieldTest() { List<List<float>> polylinesX = new List<List<float>>(); List<List<float>> polylinesY = new List<List<float>>(); List<float> x = new List<float>() { 0.0f, 1.0f }; List<float> y = new List<float>() { 0.0f, 0.0f }; polylinesX.Add(x); polylinesY.Add(y); TensorField tf = new TensorField(null, null, polylinesX, polylinesY); Assert.AreEqual(tf.GetMajorEigenVectorX()[0,0], 1.0f); Assert.AreEqual(tf.GetMajorEigenVectorY()[0, 0], 0.0f); } [TestMethod()] public void GetMajorEigenVectorXTest() { Assert.Fail(); } [TestMethod()] public void GetMajorEigenVectorYTest() { Assert.Fail(); } [TestMethod()] public void GetMinorEigenVectorXTest() { Assert.Fail(); } [TestMethod()] public void GetMinorEigenVectorYTest() { Assert.Fail(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace PayRentAndUse_V3.Models { public class VendorClass { public int Id { get; set; } [Required(ErrorMessage = "Please Enter Name")] [Display(Name = "Enter Name :")] [StringLength(maximumLength: 50, MinimumLength = 2, ErrorMessage = "Name must be Max 50 and Min 2")] public string Name { get; set; } [Required(ErrorMessage = "Please Email Address")] [Display(Name = "Email Id :")] public string Email { get; set; } [Required(ErrorMessage = "Please Enter Password")] [Display(Name = "Password :")] [DataType(DataType.Password)] public string VendorPassword { get; set; } [Required(ErrorMessage = "Confirm Password cannot be blank")] [Display(Name = "Confirm Password :")] [DataType(DataType.Password)] [Compare("VendorPassword")] public string VendorRePassword { get; set; } public DateTime DateAdded { get; set; } public VehicleClass VehicleClass { get; set; } [Display(Name = "Vehicle Name")] public int VehicleClassId { get; set; } [Required(ErrorMessage = "Please Enter Total Vehicle Count")] [Display(Name = "Vehicle Count")] public int VehicleCount { get; set; } public int BookedVehicle { get; set; } public int AvailableVehicle { get; set; } } }
using Spring.Context; using Spring.Context.Support; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ZY.OA.Common; using ZY.OA.IBLL; using ZY.OA.Model; using ZY.OA.Model.Enum; namespace ZY.OA.UI.PortalNew.Controllers { public class BaseController : Controller { public UserInfo userInfo { get; set; } private bool isExp = false; protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); //Action执行之前判断memcache是否有值(用户是否已经登录) if (Request.Cookies["usersLoginId"] != null) { string usersLoginId = Request.Cookies["usersLoginId"].Value; object obj = memcachedHelper.Get(usersLoginId); if (obj != null) { userInfo = SerializerHelper.DeSerializerToObject<UserInfo>(obj.ToString());//反序列化 //模拟Session的滑动过期时间 memcachedHelper.Update(usersLoginId, obj, DateTime.Now.AddMinutes(20)); isExp = true; //zhengyu可越狱 if (userInfo.UName=="zhengyu") { return; } //获取请求的绝对路径和请求方式 string requestUrl = Request.Url.AbsolutePath.ToLower(); string httpMethod = Request.HttpMethod; //通过容器对象来创建对象,因基类注入不了 IApplicationContext ctx = ContextRegistry.GetContext(); IActionInfoService actionInfoService = ctx.GetObject("ActionInfoService") as IActionInfoService; IUserInfoService UserInfoService = ctx.GetObject("UserInfoService") as IUserInfoService; ActionInfo actionInfo = actionInfoService.GetEntities(a => a.Url == requestUrl && a.HttpMethd == httpMethod&&a.DelFlag==(short)DelFlagEnum.Normal).FirstOrDefault(); if (actionInfo == null) { filterContext.Result = new RedirectResult("/Error.html"); //Response.Redirect("/Error.html"); return; } //第1条线.用户---权限 //登录用户 UserInfo loginUser = UserInfoService.GetEntities(u => u.ID == userInfo.ID).FirstOrDefault(); //判断登录用户请求的地址是否有权限 ActionInfo userActionOne = (from r in loginUser.R_UserInfo_ActionInfo where r.ActionInfoID == actionInfo.ID && r.HasPermission == true select r.ActionInfo).FirstOrDefault(); if (userActionOne == null) { //第2条线.用户---角色---权限 //判断登录用户请求的地址是否有权限 ActionInfo userActionTwo = (from r in loginUser.RoleInfo from a in r.ActionInfo where a.ID == actionInfo.ID select a).FirstOrDefault(); if (userActionTwo == null) { //filterContext.Result = new RedirectResult("/ActionError.html"); //Response.Redirect("/ActionError.html"); filterContext.Result = new ContentResult() {Content="您没有此权限!请联系管理员" }; return; } } } } if (!isExp) { RedirectToAct.RedirectTo(); //filterContext.HttpContext.Response.Redirect("/UserLogin/Index?return="+Request.Url); return; } } } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityEngine.UIElements; using UnityAtoms.Editor; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Event property drawer of type `BoolPair`. Inherits from `AtomEventEditor&lt;BoolPair, BoolPairEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomEditor(typeof(BoolPairEvent))] public sealed class BoolPairEventEditor : AtomEventEditor<BoolPair, BoolPairEvent> { } } #endif
/**************************************************************************** * Copyright (c) 2017 liangxie * * http://liangxiegame.com * https://github.com/liangxiegame/QFramework * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ****************************************************************************/ using System; using UnityEngine; using System.Collections; using System.Collections.Generic; namespace QFramework { public class AbstractRes : RefCounter, IRes, ICacheAble { protected string m_Name; private short m_ResState = eResState.kWaiting; private bool m_CacheFlag = false; protected UnityEngine.Object m_Asset; private event Action<bool, IRes> m_ResListener; public string name { get { return m_Name; } set { m_Name = value; } } public short resState { get { return m_ResState; } set { m_ResState = value; if (m_ResState == eResState.kReady) { NotifyResEvent(true); } } } public float progress { get { if (m_ResState == eResState.kLoading) { return CalculateProgress(); } if (m_ResState == eResState.kReady) { return 1; } return 0; } } protected virtual float CalculateProgress() { return 0; } public UnityEngine.Object asset { get { return m_Asset; } set { m_Asset = value; } } public virtual object rawAsset { get { return null; } } public bool CacheFlag { get { return m_CacheFlag; } set { m_CacheFlag = value; } } public virtual void AcceptLoaderStrategySync(IResLoader loader, IResLoaderStrategy strategy) { strategy.OnSyncLoadFinish(loader, this); } public virtual void AcceptLoaderStrategyAsync(IResLoader loader, IResLoaderStrategy strategy) { strategy.OnAsyncLoadFinish(loader, this); } public void RegisteResListener(Action<bool, IRes> listener) { if (listener == null) { return; } if (m_ResState == eResState.kReady) { listener(true, this); return; } m_ResListener += listener; } public void UnRegisteResListener(Action<bool, IRes> listener) { if (listener == null) { return; } if (m_ResListener == null) { return; } m_ResListener -= listener; } protected void OnResLoadFaild() { m_ResState = eResState.kWaiting; NotifyResEvent(false); } private void NotifyResEvent(bool result) { if (m_ResListener != null) { m_ResListener(result, this); m_ResListener = null; } } protected AbstractRes(string name) { m_Name = name; } public AbstractRes() { } protected bool CheckLoadAble() { if (m_ResState == eResState.kWaiting) { return true; } return false; } protected void HoldDependRes() { string[] depends = GetDependResList(); if (depends == null || depends.Length == 0) { return; } for (int i = depends.Length - 1; i >= 0; --i) { var res = ResMgr.Instance.GetRes(depends[i], false); if (res != null) { res.AddRef(); } } } protected void UnHoldDependRes() { string[] depends = GetDependResList(); if (depends == null || depends.Length == 0) { return; } for (int i = depends.Length - 1; i >= 0; --i) { var res = ResMgr.Instance.GetRes(depends[i], false); if (res != null) { res.SubRef(); } } } #region 子类实现 public virtual bool LoadSync() { return false; } public virtual void LoadAsync() { } public virtual string[] GetDependResList() { return null; } public bool IsDependResLoadFinish() { string[] depends = GetDependResList(); if (depends == null || depends.Length == 0) { return true; } for (int i = depends.Length - 1; i >= 0; --i) { var res = ResMgr.Instance.GetRes(depends[i], false); if (res == null || res.resState != eResState.kReady) { return false; } } return true; } public virtual bool UnloadImage(bool flag) { return false; } public bool ReleaseRes() { if (m_ResState == eResState.kLoading) { return false; } if (m_ResState != eResState.kReady) { return true; } //Log.i("Release Res:" + m_Name); OnReleaseRes(); m_ResState = eResState.kWaiting; m_ResListener = null; return true; } protected virtual void OnReleaseRes() { } protected override void OnZeroRef() { if (m_ResState == eResState.kLoading) { return; } ReleaseRes(); } public virtual void Recycle2Cache() { } public virtual void OnCacheReset() { m_Name = null; m_ResListener = null; } public virtual IEnumerator StartIEnumeratorTask(Action finishCallback) { finishCallback(); yield break; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Euler_Logic.Problems.AdventOfCode.Y2021 { public class Problem18 : AdventOfCodeBase { public override string ProblemName { get { return "Advent of Code 2021: 18"; } } public override string GetAnswer() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { var pair = GetSinglePair(input[0]); for (int index = 1; index < input.Count; index++) { var next = GetSinglePair(input[index]); var parent = GetNewPair(); parent.NumberLeft = pair; parent.NumberRight = next; pair.Parent = parent; next.Parent = parent; pair = parent; var left = GetLowestLeft(pair.NumberRight); var right = GetLowestRight(pair.NumberLeft); left.ClosestNumberLeft = right; right.ClosestNumberRight = left; ReduceAddition(pair); } return GetMagnitude(pair); } private int Answer2(List<string> input) { int best = 0; for (int index1 = 0; index1 < input.Count; index1++) { for (int index2 = 0; index2 < input.Count; index2++) { if (index1 != index2) { var pair = GetSinglePair(input[index1]); var next = GetSinglePair(input[index2]); var parent = GetNewPair(); parent.NumberLeft = pair; parent.NumberRight = next; pair.Parent = parent; next.Parent = parent; pair = parent; var left = GetLowestLeft(pair.NumberRight); var right = GetLowestRight(pair.NumberLeft); left.ClosestNumberLeft = right; right.ClosestNumberRight = left; ReduceAddition(pair); int magnitude = GetMagnitude(pair); if (magnitude > best) { best = magnitude; } } } } return best; } private int GetMagnitude(Pair pair) { int sum = 0; if (pair.IsNumber) { return pair.NumberSingle; } return GetMagnitude(pair.NumberLeft) * 3 + GetMagnitude(pair.NumberRight) * 2; } private Pair GetLowestRight(Pair pair) { do { if (pair.NumberRight == null && pair.NumberLeft == null) { return pair; } if (pair.NumberRight != null) { pair = pair.NumberRight; } else { pair = pair.NumberLeft; } } while (true); } private Pair GetLowestLeft(Pair pair) { do { if (pair.NumberRight == null && pair.NumberLeft == null) { return pair; } if (pair.NumberLeft != null) { pair = pair.NumberLeft; } else { pair = pair.NumberRight; } } while (true); } private int _actionId; private void ReduceAddition(Pair pair) { var action = GetFirstAction(pair, 0, true); if (action == null) { action = GetFirstAction(pair, 0, false); } while (action != null) { _actionId++; PerformAction(action); action = GetFirstAction(pair, 0, true); if (action == null) { action = GetFirstAction(pair, 0, false); } } } private Pair GetFirstAction(Pair pair, int level, bool explosionFirst) { if (level >= 4 && pair.NumberLeft != null && pair.NumberLeft.IsNumber && pair.NumberRight != null && pair.NumberRight.IsNumber) { pair.DoesExplode = true; return pair; } if (!explosionFirst && pair.IsNumber && pair.NumberSingle > 9) { pair.DoesExplode = false; return pair; } if (pair.NumberLeft != null) { var result = GetFirstAction(pair.NumberLeft, level + 1, explosionFirst); if (result != null) { return result; } } if (pair.NumberRight != null) { var result = GetFirstAction(pair.NumberRight, level + 1, explosionFirst); if (result != null) { return result; } } return null; } private void PerformAction(Pair pair) { if (pair.DoesExplode) { Explode(pair); } else { Split(pair); } } private void Explode(Pair pair) { var zeroPair = GetNewPair(); zeroPair.IsNumber = true; zeroPair.Parent = pair.Parent; int leftNum = pair.NumberLeft.NumberSingle; int rightNum = pair.NumberRight.NumberSingle; var closestLeftNum = pair.NumberLeft.ClosestNumberLeft; var closestRightNum = pair.NumberRight.ClosestNumberRight; if (closestLeftNum != null) { closestLeftNum.NumberSingle += leftNum; closestLeftNum.ClosestNumberRight = zeroPair; zeroPair.ClosestNumberLeft = closestLeftNum; } if (closestRightNum != null) { closestRightNum.NumberSingle += rightNum; closestRightNum.ClosestNumberLeft = zeroPair; zeroPair.ClosestNumberRight = closestRightNum; } if (zeroPair.Parent != null) { if (zeroPair.Parent.NumberLeft.Id == pair.Id) { zeroPair.Parent.NumberLeft = zeroPair; } else if (zeroPair.Parent.NumberRight.Id == pair.Id) { zeroPair.Parent.NumberRight = zeroPair; } else { throw new Exception(); } } } private void Split(Pair pair) { var left = GetNewPair(); left.ClosestNumberLeft = pair.ClosestNumberLeft; left.IsNumber = true; left.NumberSingle = pair.NumberSingle / 2; left.Parent = pair; var right = GetNewPair(); right.ClosestNumberRight = pair.ClosestNumberRight; right.IsNumber = true; right.NumberSingle = pair.NumberSingle / 2 + (pair.NumberSingle % 2); right.Parent = pair; left.ClosestNumberRight = right; right.ClosestNumberLeft = left; pair.IsNumber = false; pair.NumberLeft = left; pair.NumberRight = right; if (left.ClosestNumberLeft != null) { left.ClosestNumberLeft.ClosestNumberRight = left; } if (right.ClosestNumberRight != null) { right.ClosestNumberRight.ClosestNumberLeft = right; } } private Pair GetSinglePair(string line) { Pair current = GetNewPair(); Pair left = null; for (int index = 1; index < line.Length - 1; index++) { var digit = line[index]; if (digit == '[') { var next = GetNewPair(); next.Parent = current; AddChildPair(current, next); current = next; } else if (digit == ']') { current = current.Parent; } else if (digit == ',') { } else { var number = Convert.ToInt32(new string(new char[1] { digit })); var next = GetNewPair(); next.IsNumber = true; next.NumberSingle = number; next.Parent = current; AddChildPair(current, next); next.ClosestNumberLeft = left; if (left != null) { left.ClosestNumberRight = next; } left = next; } } return current; } private void AddChildPair(Pair parent, Pair child) { if (parent.NumberLeft == null) { parent.NumberLeft = child; } else { parent.NumberRight = child; } } private string Output(Pair pair) { if (pair.IsNumber) { return pair.NumberSingle.ToString(); } if (pair.NumberRight == null) { return Output(pair.NumberLeft); } return "[" + Output(pair.NumberLeft) + "," + Output(pair.NumberRight) + "]"; } private string OutputClosest(Pair pair) { var text = new StringBuilder(); var left = GetLowestLeft(pair); while (left != null) { text.Append(left.NumberSingle.ToString() + ","); left = left.ClosestNumberRight; if (left != null && !left.IsNumber) { throw new Exception(); } } return text.ToString(); } private bool Validate(Pair pair) { var full = Output(pair).Split(',').ToList(); var closest = OutputClosest(pair).Split(',').ToList(); closest.RemoveAt(closest.Count - 1); int index = 0; foreach (var digit in full) { var format = digit.Replace("[", "").Replace("]", ""); if (format != closest[index]) { return false; } index++; } return true; } private List<Pair> _pairs = new List<Pair>(); private Pair GetNewPair() { var pair = new Pair(); pair.Id = _pairs.Count; _pairs.Add(pair); return pair; } private class Pair { public bool IsAddition { get; set; } public bool IsNumber { get; set; } public Pair NumberLeft { get; set; } public Pair NumberRight { get; set; } public Pair Parent { get; set; } public int NumberSingle { get; set; } public bool DoesExplode { get; set; } public Pair ClosestNumberRight { get; set; } public Pair ClosestNumberLeft { get; set; } public int Id { get; set; } } } }
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("AutoTests.Framework.Models")] [assembly: AssemblyProduct("AutoTests.Framework")] [assembly: ComVisible(false)] [assembly: Guid("05ba50f8-ec90-406d-af94-aee1bebf0998")]
using Thrift.Protocol; using Thrift.Transport; using VersionExample; namespace v2server { public class ServiceHttpHandler : THttpHandler { public ServiceHttpHandler() : base(CreateProcessor(), CreateJsonFactory()) { } private static ServerService.Processor CreateProcessor() { return new ServerService.Processor(new ServiceImplementation()); } private static TJSONProtocol.Factory CreateJsonFactory() { return new TJSONProtocol.Factory(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DSharpPlus; using DSharpPlus.Entities; using DSharpPlus.Exceptions; using Humanizer; using NodaTime; using PluralKit.Core; namespace PluralKit.Bot { public class EmbedService { private readonly IDatabase _db; private readonly ModelRepository _repo; private readonly DiscordShardedClient _client; public EmbedService(DiscordShardedClient client, IDatabase db, ModelRepository repo) { _client = client; _db = db; _repo = repo; } public async Task<DiscordEmbed> CreateSystemEmbed(Context cctx, PKSystem system, LookupContext ctx) { await using var conn = await _db.Obtain(); // Fetch/render info for all accounts simultaneously var accounts = await _repo.GetSystemAccounts(conn, system.Id); var users = await Task.WhenAll(accounts.Select(async uid => (await cctx.Shard.GetUser(uid))?.NameAndMention() ?? $"(deleted account {uid})")); var memberCount = cctx.MatchPrivateFlag(ctx) ? await _repo.GetSystemMemberCount(conn, system.Id, PrivacyLevel.Public) : await _repo.GetSystemMemberCount(conn, system.Id); var eb = new DiscordEmbedBuilder() .WithColor(DiscordUtils.Gray) .WithTitle(system.Name ?? null) .WithThumbnail(system.AvatarUrl) .WithFooter($"System ID: {system.Hid} | Created on {system.Created.FormatZoned(system)}"); var latestSwitch = await _repo.GetLatestSwitch(conn, system.Id); if (latestSwitch != null && system.FrontPrivacy.CanAccess(ctx)) { var switchMembers = await _repo.GetSwitchMembers(conn, latestSwitch.Id).ToListAsync(); if (switchMembers.Count > 0) eb.AddField("Fronter".ToQuantity(switchMembers.Count(), ShowQuantityAs.None), string.Join(", ", switchMembers.Select(m => m.NameFor(ctx)))); } if (system.Tag != null) eb.AddField("Tag", system.Tag.EscapeMarkdown()); eb.AddField("Linked accounts", string.Join(", ", users).Truncate(1000), true); if (system.MemberListPrivacy.CanAccess(ctx)) { if (memberCount > 0) eb.AddField($"Members ({memberCount})", $"(see `pk;system {system.Hid} list` or `pk;system {system.Hid} list full`)", true); else eb.AddField($"Members ({memberCount})", "Add one with `pk;member new`!", true); } if (system.DescriptionFor(ctx) is { } desc) eb.AddField("Description", desc.NormalizeLineEndSpacing().Truncate(1024), false); return eb.Build(); } public DiscordEmbed CreateLoggedMessageEmbed(PKSystem system, PKMember member, ulong messageId, ulong originalMsgId, DiscordUser sender, string content, DiscordChannel channel) { // TODO: pronouns in ?-reacted response using this card var timestamp = DiscordUtils.SnowflakeToInstant(messageId); var name = member.NameFor(LookupContext.ByNonOwner); return new DiscordEmbedBuilder() .WithAuthor($"#{channel.Name}: {name}", iconUrl: DiscordUtils.WorkaroundForUrlBug(member.AvatarFor(LookupContext.ByNonOwner))) .WithThumbnail(member.AvatarFor(LookupContext.ByNonOwner)) .WithDescription(content?.NormalizeLineEndSpacing()) .WithFooter($"System ID: {system.Hid} | Member ID: {member.Hid} | Sender: {sender.Username}#{sender.Discriminator} ({sender.Id}) | Message ID: {messageId} | Original Message ID: {originalMsgId}") .WithTimestamp(timestamp.ToDateTimeOffset()) .Build(); } public async Task<DiscordEmbed> CreateMemberEmbed(PKSystem system, PKMember member, DiscordGuild guild, LookupContext ctx) { // string FormatTimestamp(Instant timestamp) => DateTimeFormats.ZonedDateTimeFormat.Format(timestamp.InZone(system.Zone)); var name = member.NameFor(ctx); if (system.Name != null) name = $"{name} ({system.Name})"; DiscordColor color; try { color = member.Color?.ToDiscordColor() ?? DiscordUtils.Gray; } catch (ArgumentException) { // Bad API use can cause an invalid color string // TODO: fix that in the API // for now we just default to a blank color, yolo color = DiscordUtils.Gray; } await using var conn = await _db.Obtain(); var guildSettings = guild != null ? await _repo.GetMemberGuild(conn, guild.Id, member.Id) : null; var guildDisplayName = guildSettings?.DisplayName; var avatar = guildSettings?.AvatarUrl ?? member.AvatarFor(ctx); var groups = await _repo.GetMemberGroups(conn, member.Id) .Where(g => g.Visibility.CanAccess(ctx)) .OrderBy(g => g.Name, StringComparer.InvariantCultureIgnoreCase) .ToListAsync(); var eb = new DiscordEmbedBuilder() // TODO: add URL of website when that's up .WithAuthor(name, iconUrl: DiscordUtils.WorkaroundForUrlBug(avatar)) // .WithColor(member.ColorPrivacy.CanAccess(ctx) ? color : DiscordUtils.Gray) .WithColor(color) .WithFooter($"System ID: {system.Hid} | Member ID: {member.Hid} {(member.MetadataPrivacy.CanAccess(ctx) ? $"| Created on {member.Created.FormatZoned(system)}":"")}"); var description = ""; if (member.MemberVisibility == PrivacyLevel.Private) description += "*(this member is hidden)*\n"; if (guildSettings?.AvatarUrl != null) if (member.AvatarFor(ctx) != null) description += $"*(this member has a server-specific avatar set; [click here]({member.AvatarUrl}) to see the global avatar)*\n"; else description += "*(this member has a server-specific avatar set)*\n"; if (description != "") eb.WithDescription(description); if (avatar != null) eb.WithThumbnail(avatar); if (!member.DisplayName.EmptyOrNull() && member.NamePrivacy.CanAccess(ctx)) eb.AddField("Display Name", member.DisplayName.Truncate(1024), true); if (guild != null && guildDisplayName != null) eb.AddField($"Server Nickname (for {guild.Name})", guildDisplayName.Truncate(1024), true); if (member.BirthdayFor(ctx) != null) eb.AddField("Birthdate", member.BirthdayString, true); if (member.PronounsFor(ctx) is {} pronouns && !string.IsNullOrWhiteSpace(pronouns)) eb.AddField("Pronouns", pronouns.Truncate(1024), true); if (member.MessageCountFor(ctx) is {} count && count > 0) eb.AddField("Message Count", member.MessageCount.ToString(), true); if (member.HasProxyTags) eb.AddField("Proxy Tags", member.ProxyTagsString("\n").Truncate(1024), true); // --- For when this gets added to the member object itself or however they get added // if (member.LastMessage != null && member.MetadataPrivacy.CanAccess(ctx)) eb.AddField("Last message:" FormatTimestamp(DiscordUtils.SnowflakeToInstant(m.LastMessage.Value))); // if (member.LastSwitchTime != null && m.MetadataPrivacy.CanAccess(ctx)) eb.AddField("Last switched in:", FormatTimestamp(member.LastSwitchTime.Value)); // if (!member.Color.EmptyOrNull() && member.ColorPrivacy.CanAccess(ctx)) eb.AddField("Color", $"#{member.Color}", true); if (!member.Color.EmptyOrNull()) eb.AddField("Color", $"#{member.Color}", true); if (groups.Count > 0) { // More than 5 groups show in "compact" format without ID var content = groups.Count > 5 ? string.Join(", ", groups.Select(g => g.DisplayName ?? g.Name)) : string.Join("\n", groups.Select(g => $"[`{g.Hid}`] **{g.DisplayName ?? g.Name}**")); eb.AddField($"Groups ({groups.Count})", content.Truncate(1000)); } if (member.DescriptionFor(ctx) is {} desc) eb.AddField("Description", member.Description.NormalizeLineEndSpacing(), false); return eb.Build(); } public async Task<DiscordEmbed> CreateFronterEmbed(PKSwitch sw, DateTimeZone zone, LookupContext ctx) { var members = await _db.Execute(c => _repo.GetSwitchMembers(c, sw.Id).ToListAsync().AsTask()); var timeSinceSwitch = SystemClock.Instance.GetCurrentInstant() - sw.Timestamp; return new DiscordEmbedBuilder() .WithColor(members.FirstOrDefault()?.Color?.ToDiscordColor() ?? DiscordUtils.Gray) .AddField($"Current {"fronter".ToQuantity(members.Count, ShowQuantityAs.None)}", members.Count > 0 ? string.Join(", ", members.Select(m => m.NameFor(ctx))) : "*(no fronter)*") .AddField("Since", $"{sw.Timestamp.FormatZoned(zone)} ({timeSinceSwitch.FormatDuration()} ago)") .Build(); } public async Task<DiscordEmbed> CreateMessageInfoEmbed(DiscordClient client, FullMessage msg) { var ctx = LookupContext.ByNonOwner; var channel = await _client.GetChannel(msg.Message.Channel); var serverMsg = channel != null ? await channel.GetMessage(msg.Message.Mid) : null; // Need this whole dance to handle cases where: // - the user is deleted (userInfo == null) // - the bot's no longer in the server we're querying (channel == null) // - the member is no longer in the server we're querying (memberInfo == null) DiscordMember memberInfo = null; DiscordUser userInfo = null; if (channel != null) memberInfo = await channel.Guild.GetMember(msg.Message.Sender); if (memberInfo != null) userInfo = memberInfo; // Don't do an extra request if we already have this info from the member lookup else userInfo = await client.GetUser(msg.Message.Sender); // Calculate string displayed under "Sent by" string userStr; if (memberInfo != null && memberInfo.Nickname != null) userStr = $"**Username:** {memberInfo.NameAndMention()}\n**Nickname:** {memberInfo.Nickname}"; else if (userInfo != null) userStr = userInfo.NameAndMention(); else userStr = $"*(deleted user {msg.Message.Sender})*"; // Put it all together var eb = new DiscordEmbedBuilder() .WithAuthor(msg.Member.NameFor(ctx), iconUrl: DiscordUtils.WorkaroundForUrlBug(msg.Member.AvatarFor(ctx))) .WithDescription(serverMsg?.Content?.NormalizeLineEndSpacing() ?? "*(message contents deleted or inaccessible)*") .WithImageUrl(serverMsg?.Attachments?.FirstOrDefault()?.Url) .AddField("System", msg.System.Name != null ? $"{msg.System.Name} (`{msg.System.Hid}`)" : $"`{msg.System.Hid}`", true) .AddField("Member", $"{msg.Member.NameFor(ctx)} (`{msg.Member.Hid}`)", true) .AddField("Sent by", userStr, inline: true) .WithTimestamp(DiscordUtils.SnowflakeToInstant(msg.Message.Mid).ToDateTimeOffset()); var roles = memberInfo?.Roles?.ToList(); if (roles != null && roles.Count > 0) { var rolesString = string.Join(", ", roles.Select(role => role.Name)); eb.AddField($"Account roles ({roles.Count})", rolesString.Truncate(1024)); } return eb.Build(); } public Task<DiscordEmbed> CreateFrontPercentEmbed(FrontBreakdown breakdown, DateTimeZone tz, LookupContext ctx) { var actualPeriod = breakdown.RangeEnd - breakdown.RangeStart; var eb = new DiscordEmbedBuilder() .WithColor(DiscordUtils.Gray) .WithFooter($"Since {breakdown.RangeStart.FormatZoned(tz)} ({actualPeriod.FormatDuration()} ago)"); var maxEntriesToDisplay = 24; // max 25 fields allowed in embed - reserve 1 for "others" // We convert to a list of pairs so we can add the no-fronter value // Dictionary doesn't allow for null keys so we instead have a pair with a null key ;) var pairs = breakdown.MemberSwitchDurations.ToList(); if (breakdown.NoFronterDuration != Duration.Zero) pairs.Add(new KeyValuePair<PKMember, Duration>(null, breakdown.NoFronterDuration)); var membersOrdered = pairs.OrderByDescending(pair => pair.Value).Take(maxEntriesToDisplay).ToList(); foreach (var pair in membersOrdered) { var frac = pair.Value / actualPeriod; eb.AddField(pair.Key?.NameFor(ctx) ?? "*(no fronter)*", $"{frac*100:F0}% ({pair.Value.FormatDuration()})"); } if (membersOrdered.Count > maxEntriesToDisplay) { eb.AddField("(others)", membersOrdered.Skip(maxEntriesToDisplay) .Aggregate(Duration.Zero, (prod, next) => prod + next.Value) .FormatDuration(), true); } return Task.FromResult(eb.Build()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using KartLib; namespace KartSystem { interface IRegistryReportView : IAxiTradeView { /// <summary> /// Документы /// </summary> IList<RegistryReportRecord> RegistryReportRecords { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FitApp.Services; using Xamarin.Forms; namespace FitApp.ViewModels { public class RecipeViewModel : ContentPage { public MealsService mealsService; public RecipeViewModel() { mealsService = App.ms; setValues(); } // I1 --> Image1 // T1 --> Title1 // R1 --> Recipe1 // S1 --> Step1 - 6 //Image public string _i1; public string I1 { get { return _i1; } set { _i1 = value; OnPropertyChanged(); } } //title public string _t1; public string T1 { get { return _t1; } set { _t1 = value; OnPropertyChanged(); } } //ingredients public string _ing1; public string Ing1 { get { return _ing1; } set { _ing1 = value; OnPropertyChanged(); } } //STEPS, RECIPE public string s1; public string S1 { get { return s1; } set { s1 = value; OnPropertyChanged(); } } public string s2; public string S2 { get { return s2; } set { s2 = value; OnPropertyChanged(); } } public string s3; public string S3 { get { return s3; } set { s3 = value; OnPropertyChanged(); } } public string s4; public string S4 { get { return s4; } set { s4 = value; OnPropertyChanged(); } } public string s5; public string S5 { get { return s5; } set { s5 = value; OnPropertyChanged(); } } public string s6; public string S6 { get { return s6; } set { s6 = value; OnPropertyChanged(); } } // private void setValues() { I1 = mealsService.Image; T1 = mealsService.Titile; Ing1 = mealsService.Ingredients; S1 = mealsService.Step1; S2 = mealsService.Step2; S3 = mealsService.Step3; S4 = mealsService.Step4; S5 = mealsService.Step5; S6 = mealsService.Step6; } } }
using System; using System.Collections.Generic; using System.Linq; namespace TrafficNavigation { public class OrbitGenerator { /// <summary> /// Generates correct orbit for both similar as well as non similar destination /// </summary> /// <param name="orbits"></param> /// <param name="climate"></param> /// <param name="isSameDestination"></param> /// <returns></returns> public static List<CorrectOrbit> GenerateCorrectRoute(Orbit[] orbits, Climate climate,bool isSameDestination) { if (!isSameDestination) { double overallCarTime = Double.MaxValue; KeyValuePair<Orbit, double> carShortestPathToD2; orbits[2].IsBreakJourney = true; orbits[3].IsBreakJourney = true; GetShortestPathToD1(orbits, climate, out KeyValuePair<Orbit, double> carShortestPathToD1, out KeyValuePair<Orbit, double> bikeShortestPathToD1, out KeyValuePair<Orbit, double> ttShortestPathToD1); orbits[2].IsBreakJourney = false; if (carShortestPathToD1.Key.IsBreakJourney) { carShortestPathToD2 = ShortestPathGenerator.GenerateShortestPathForVehicle(new Orbit[] { orbits[2] }, climate, new Car()); overallCarTime = carShortestPathToD1.Value; } else { carShortestPathToD1.Key.IsBreakJourney = true; carShortestPathToD2 = ShortestPathGenerator.GenerateShortestPathForVehicle(new Orbit[] { carShortestPathToD1.Key, orbits[3] }, climate, new Car()); carShortestPathToD1.Key.IsBreakJourney = false; overallCarTime = carShortestPathToD2.Value; } double overallBikeTime = Double.MaxValue; KeyValuePair<Orbit, double> bikeShortestPathToD2; if (bikeShortestPathToD1.Key.IsBreakJourney) { bikeShortestPathToD2 = ShortestPathGenerator.GenerateShortestPathForVehicle(new Orbit[] { orbits[2] }, climate, new Bike()); overallBikeTime = bikeShortestPathToD1.Value; } else { bikeShortestPathToD1.Key.IsBreakJourney = true; bikeShortestPathToD2 = ShortestPathGenerator.GenerateShortestPathForVehicle(new Orbit[] { bikeShortestPathToD1.Key, orbits[3] }, climate, new Bike()); bikeShortestPathToD1.Key.IsBreakJourney = false; overallBikeTime = bikeShortestPathToD2.Value; } KeyValuePair<Orbit, double> ttShortestPathToD2; double ttOverAllTime = Double.MaxValue; if (ttShortestPathToD1.Key.IsBreakJourney) { ttShortestPathToD2 = ShortestPathGenerator.GenerateShortestPathForVehicle(new Orbit[] { orbits[2] }, climate, new TukTuk()); ttOverAllTime = ttShortestPathToD1.Value; } else { ttShortestPathToD1.Key.IsBreakJourney = true; ttShortestPathToD2 = ShortestPathGenerator.GenerateShortestPathForVehicle(new Orbit[] { ttShortestPathToD1.Key, orbits[3] }, climate, new TukTuk()); ttOverAllTime = ttShortestPathToD2.Value; } var shortestPath = new List<CorrectOrbit>(); shortestPath = overallCarTime < overallBikeTime && overallCarTime < ttOverAllTime ? GenerateCorrectOrbit(new List<KeyValuePair<Orbit, double>>() { carShortestPathToD1, carShortestPathToD2 }, Vehicle.Car) : ttOverAllTime < overallBikeTime ? GenerateCorrectOrbit(new List<KeyValuePair<Orbit, double>>() { ttShortestPathToD1, ttShortestPathToD2 }, Vehicle.TukTuk) : GenerateCorrectOrbit(new List<KeyValuePair<Orbit, double>>() { bikeShortestPathToD1 , bikeShortestPathToD2 }, Vehicle.Bike); return shortestPath; } else return GetSameDestinationCorrectOrbit(orbits, climate); } private static List<CorrectOrbit> GetSameDestinationCorrectOrbit(Orbit[] orbits, Climate climate) { GetShortestPathToD1(orbits, climate, out KeyValuePair<Orbit, double> carShortestPathToD1, out KeyValuePair<Orbit, double> bikeShortestPathToD1, out KeyValuePair<Orbit, double> ttShortestPathToD1); var shortestPath = carShortestPathToD1.Value < bikeShortestPathToD1.Value && carShortestPathToD1.Value < ttShortestPathToD1.Value ? GenerateCorrectOrbit(new List<KeyValuePair<Orbit, double>>() { carShortestPathToD1 }, Vehicle.Car) : ttShortestPathToD1.Value < bikeShortestPathToD1.Value ? GenerateCorrectOrbit(new List<KeyValuePair<Orbit, double>>() { ttShortestPathToD1 }, Vehicle.TukTuk) : GenerateCorrectOrbit(new List<KeyValuePair<Orbit, double>>() { bikeShortestPathToD1 }, Vehicle.Bike); return shortestPath; } private static void GetShortestPathToD1(Orbit[] orbits, Climate climate, out KeyValuePair<Orbit, double> carShortestPathToD1, out KeyValuePair<Orbit, double> bikeShortestPathToD1, out KeyValuePair<Orbit, double> ttShortestPathToD1) { carShortestPathToD1 = ShortestPathGenerator.GenerateShortestPathForVehicle(orbits, climate, new Car()); bikeShortestPathToD1 = ShortestPathGenerator.GenerateShortestPathForVehicle(orbits, climate, new Bike()); ttShortestPathToD1 = ShortestPathGenerator.GenerateShortestPathForVehicle(orbits, climate, new TukTuk()); } private static List<CorrectOrbit> GenerateCorrectOrbit(List<KeyValuePair<Orbit, double>> currentOrbit, Vehicle car) { return currentOrbit.Select(c=> new CorrectOrbit() { TypeofVehicle = car, Destination = c.Key.Destination, Orbit = c.Key.OrbitName, TimeTaken = c.Value }).ToList(); } } }
using Data.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Data.Contracts { public interface IDepartmentRepository : IGenericRepository<Department> { } }
using System; using System.Collections.Generic; using System.Net; using System.Web.Mvc; using Modelos; using Servicos; namespace WEBTeste.Controllers { [Authorize] public class ProdutoController : Controller { ProdutoServico serv = new ProdutoServico(); UsuarioServico servUsu = new UsuarioServico(); CategoriaServico servCat = new CategoriaServico(); UnidadeServico servUni = new UnidadeServico(); // GET: Produto public ActionResult Index(int? pagina) { int linhas = 5; int qtProd = serv.ObterQuantidadeProdutos(); if (qtProd <= linhas) ViewBag.Pages = 1; else ViewBag.Pages = Convert.ToInt32(qtProd / linhas) + 1; ViewBag.Page = pagina.GetValueOrDefault(1); return View(serv.ObterProdutos(pagina.GetValueOrDefault(1), linhas)); } // GET: Produto/Details/5 public ActionResult Details(int? Pid) { if (Pid == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Produto produto = serv.ObterProduto(Pid.Value); if (produto == null) { return HttpNotFound(); } return View(produto); } // GET: Produto/Create public ActionResult Create() { var produto = serv.InstanciarProduto(); var usuario = servUsu.ObterUsuario(User.Identity.Name); CriarViewBag(produto); return View(); } // POST: Produto/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([Bind(Include = "ID,nmProduto,dsProduto,vlPreco,qtEstoque,IdUserCreate,CategoriaId")] Produto produto, FormCollection Pform) { if (ModelState.IsValid) { Usuario usuario = servUsu.ObterUsuario(User.Identity.Name); produto.IdUserCreate = usuario.ID; produto.SgUnidade = Pform.GetValue("sgUnidade").AttemptedValue; serv.IncluirProduto(produto); return RedirectToAction("Index"); } CriarViewBag(produto); return View(produto); } // GET: Produto/Edit/5 public ActionResult Edit(int? Pid) { if (Pid == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var produto = serv.InstanciarProduto(); produto = serv.ObterProduto(Pid.Value); if (produto == null) { return HttpNotFound(); } CriarViewBag(produto); return View(produto); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,nmProduto,dsProduto,vlPreco,qtEstoque,CategoriaId,IdUserCreate")] Produto produto, FormCollection Pform) { if (ModelState.IsValid) { //Usuario usuario = servositorio.ObterUsuario(User.Identity.Name); Usuario usuario = servUsu.ObterUsuario(Convert.ToInt16(Pform.GetValue("IdUserCreate").AttemptedValue)); produto.IdUserCreate = usuario.ID; Categoria categoria = servCat.ObterCategoria(Convert.ToInt16(Pform.GetValue("CategoriaId").AttemptedValue)); produto.CategoriaId = categoria.ID; produto.SgUnidade = Pform.GetValue("SgUnidade").AttemptedValue; serv.AtualizarProduto(produto); return RedirectToAction("Index"); } CriarViewBag(produto); return View(produto); } // GET: Produto/Delete/5 public ActionResult Delete(int? Pid) { if (Pid == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Produto produto = serv.ObterProduto(Pid.Value); if (produto == null) { return HttpNotFound(); } return View(produto); } // POST: Produto/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int Pid) { Produto produto = serv.ObterProduto(Pid); serv.ExcluirProduto(produto); return RedirectToAction("Index"); } [AllowAnonymous] public PartialViewResult List() { return PartialView("_Lista", serv.ObterProdutos()); } private void CriarViewBag(Produto produto) { if (produto.ID == 0) { ViewBag.IdUserCreate = new SelectList(servUsu.ObterUsuarios(), "ID", "nmUsuario"); ViewBag.CategoriaId = new SelectList(servCat.ObterCategoriasT(), "ID", "NmCategoria"); ViewBag.SgUnidade = new SelectList(servUni.ObterUnidadesT(), "SgUnidade", "DsUnidade"); } else { ViewBag.IdUserCreate = new SelectList(servUsu.ObterUsuarios(), "ID", "nmUsuario", produto.IdUserCreate); ViewBag.CategoriaId = new SelectList(servCat.ObterCategoriasT(), "ID", "NmCategoria", produto.CategoriaId); ViewBag.SgUnidade = new SelectList(servUni.ObterUnidadesT(), "SgUnidade", "DsUnidade", produto.SgUnidade); } } public List<Produto> ObterProdutosNome(string pnmProduto) { return serv.ObterPNome(pnmProduto); } public string ObterNome(int? Pid) { if (Pid == null) { return ""; } return serv.ObterNomeProduto(Pid.Value); } public Produto ObterProduto(int? Pid) { var produto = serv.InstanciarProduto(); if (Pid == null) { return produto; } produto = serv.ObterProduto(Pid.Value); return produto; } } }
using System; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Activation; using Phenix.Core.Dictionary; using Phenix.Core.Log; using Phenix.Core.Mapping; using Phenix.Services.Host.Core; namespace Phenix.Services.Host.Service.Wcf { [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public sealed class DataDictionary : Phenix.Services.Contract.Wcf.IDataDictionary { [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetEnterprise() { try { ServiceManager.CheckActive(); return DataDictionaryHub.Enterprise; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetDepartmentInfos() { try { ServiceManager.CheckActive(); return DataDictionaryHub.DepartmentInfos; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetPositionInfos() { try { ServiceManager.CheckActive(); return DataDictionaryHub.PositionInfos; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetTableFilterInfos() { try { ServiceManager.CheckActive(); return DataDictionaryHub.TableFilterInfos; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetRoleInfos() { try { ServiceManager.CheckActive(); return DataDictionaryHub.RoleInfos; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetSectionInfos() { try { ServiceManager.CheckActive(); return DataDictionaryHub.SectionInfos; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void DepartmentInfoHasChanged() { try { DataDictionaryHub.DepartmentInfoHasChanged(); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex); } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void PositionInfoHasChanged() { try { DataDictionaryHub.PositionInfoHasChanged(); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex); } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void AssemblyInfoHasChanged() { try { DataDictionaryHub.AssemblyInfoHasChanged(); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex); } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetAssemblyInfos() { try { ServiceManager.CheckActive(); return DataDictionaryHub.GetAssemblyInfos(); } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetAssemblyInfo(string assemblyName) { try { ServiceManager.CheckActive(); return DataDictionaryHub.GetAssemblyInfo(assemblyName); } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void TableFilterInfoHasChanged() { try { DataDictionaryHub.TableFilterInfoHasChanged(); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex); } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void RoleInfoHasChanged() { try { DataDictionaryHub.RoleInfoHasChanged(); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex); } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void SectionInfoHasChanged() { try { DataDictionaryHub.SectionInfoHasChanged(); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex); } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void TableInfoHasChanged() { try { DataDictionaryHub.TableInfoHasChanged(); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex); } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object AddAssemblyClassInfo(string assemblyName, string assemblyCaption, string className, string classCaption, ExecuteAction? permanentExecuteAction, string[] groupNames, AssemblyClassType classType) { try { ServiceManager.CheckActive(); DataDictionaryHub.AddAssemblyClassInfo(assemblyName, assemblyCaption, className, classCaption, permanentExecuteAction, groupNames, classType); return null; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object AddAssemblyClassPropertyInfos(string assemblyName, string className, string[] names, string[] captions, string[] tableNames, string[] columnNames, string[] aliases, ExecuteModify[] permanentExecuteModifies) { try { ServiceManager.CheckActive(); DataDictionaryHub.AddAssemblyClassPropertyInfos(assemblyName, className, names, captions, tableNames, columnNames, aliases, permanentExecuteModifies); return null; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object AddAssemblyClassPropertyConfigInfos(string assemblyName, string className, string[] names, string[] captions, bool[] configurables, string[] configKeys, string[] configValues, AssemblyClassType classType) { try { ServiceManager.CheckActive(); DataDictionaryHub.AddAssemblyClassPropertyInfos(assemblyName, className, names, captions, configurables, configKeys, configValues, classType); return null; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object AddAssemblyClassMethodInfos(string assemblyName, string className, string[] names, string[] captions, string[] tags, bool[] allowVisibles) { try { ServiceManager.CheckActive(); DataDictionaryHub.AddAssemblyClassMethodInfos(assemblyName, className, names, captions, tags, allowVisibles); return null; } catch (Exception ex) { return ex; } } #region BusinessCode [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetBusinessCodeFormats() { try { ServiceManager.CheckActive(); return DataDictionaryHub.BusinessCodeFormats; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object GetBusinessCodeFormat(string businessCodeName) { try { ServiceManager.CheckActive(); return DataDictionaryHub.GetBusinessCodeFormat(businessCodeName); } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object SetBusinessCodeFormat(BusinessCodeFormat format) { try { ServiceManager.CheckActive(); DataDictionaryHub.SetBusinessCodeFormat(format); return null; } catch (Exception ex) { return ex; } } [OperationBehavior(Impersonation = ImpersonationOption.Allowed)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public object RemoveBusinessCodeFormat(string businessCodeName) { try { ServiceManager.CheckActive(); DataDictionaryHub.RemoveBusinessCodeFormat(businessCodeName); return null; } catch (Exception ex) { return ex; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.MESRMM { /// <summary> /// 技能熟练程度 /// </summary> public class SkillLevel { /// <summary> /// 技能熟练等级 /// </summary> public int Level { get; set; } /// <summary> /// 技能熟练等级描述 /// </summary> public string SkillLevelString { get; set; } public SkillLevel Clone() { return MemberwiseClone() as SkillLevel; } } }
using System; namespace Docller.Core.Models { public class BlobBase : BaseFederatedModel { public string UniqueIdentifier { get; set; } public long FileId { get; set; } public Guid FileInternalName { get; set; } public string ContentType { get; set; } public string FileName { get; set; } public string FileExtension { get; set; } public decimal FileSize { get; set; } public Folder Folder { get; set; } public Project Project { get; set; } public User CreatedBy { get; set; } public User ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } #region Overrides of BaseModel internal override string InsertProc { get { throw new NotImplementedException(); } } internal override string UpdateProc { get { throw new NotImplementedException(); } } internal override string DeleteProc { get { throw new NotImplementedException(); } } internal override string GetProc { get { throw new NotImplementedException(); } } #endregion } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using BugTracker.Models.TicketAddonsModels; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace BugTracker.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public ApplicationUser() { ProjectsCreated = new HashSet<Project>(); ProjectsManage = new HashSet<Project>(); } public string DisplayName { get; set; } public string LastName { get; set; } public string FirstName { get; set; } [InverseProperty("Author")] public virtual ICollection<Project> ProjectsCreated { get; set; } [InverseProperty("AssignedDevelopers")] public virtual ICollection<Project> ProjectsManage { get; set; } [InverseProperty("Assignee")] public virtual ICollection<Ticket> AssignedTickets { get; set; } [InverseProperty("Author")] public virtual ICollection<Ticket> CreatedTickets { get; set; } public virtual ICollection<TicketHistory> Histories { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here userIdentity.AddClaim(new Claim("DisplayName", this.DisplayName)); return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public DbSet<Project> Projects { get; set; } public DbSet<ProjectType> ProjectTypes { get; set; } public System.Data.Entity.DbSet<BugTracker.Models.Ticket> Tickets { get; set; } public System.Data.Entity.DbSet<BugTracker.Models.TicketComment> TicketComments { get; set; } public DbSet<TicketAttachment> TicketAttachments { get; set; } public DbSet<TicketHistory> TicketHistory { get; set; } public DbSet<TicketStatus> TicketStatus { get; set; } public DbSet<TicketPriority> TicketPriority { get; set; } public DbSet<TicketType> TicketType { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Query; using EBS.Query.DTO; using EBS.Domain.Entity; using EBS.Domain.ValueObject; using Dapper.DBContext; using System.Dynamic; using EBS.Infrastructure.Extension; namespace EBS.Query.Service { public class AdjustContractPriceQueryService:IAdjustContractPriceQuery { IQuery _query; public AdjustContractPriceQueryService(IQuery query) { this._query = query; } public IEnumerable<AdjustContractPriceDto> GetPageList(Pager page, SearchAdjustContractPrice condition) { dynamic param = new ExpandoObject(); string where = ""; if (!string.IsNullOrEmpty(condition.ProductCodeOrBarCode)) { where += @"and a.Id in( select i.AdjustContractPriceId from adjustcontractpriceitem i left join product p on p.id = i.ProductId where (p.`Code`=@ProductCodeOrBarCode or p.BarCode=@ProductCodeOrBarCode) )"; param.ProductCodeOrBarCode = condition.ProductCodeOrBarCode; } if (!string.IsNullOrEmpty(condition.Code)) { where += "and a.Code=@Code "; param.Code = condition.Code; } if (condition.SupplierId > 0) { where += "and a.SupplierId=@SupplierId "; param.SupplierId = condition.SupplierId; } if (condition.StoreId > 0) { where += "and a.StoreId=@StoreId "; param.StoreId = condition.StoreId; } if (condition.Status !=0) { where += "and a.Status=@Status "; param.Status = condition.Status; } string sql = @"select a.*,c.NickName,r.`Name` as StoreName ,s.`Name` as SupplierName,s.`Code` as SupplierCode from adjustcontractprice a left join account c on c.Id = a.CreatedBy left join Supplier s on s.Id = a.SupplierId left join store r on r.Id = a.StoreId where 1=1 {0} ORDER BY a.Id desc LIMIT {1},{2}"; string sqlCount = @"select count(*) from adjustcontractprice a left join account c on c.Id = a.CreatedBy left join Supplier s on s.Id = a.SupplierId left join store r on r.Id = a.StoreId where 1=1 {0} "; sql = string.Format(sql, where, (page.PageIndex - 1) * page.PageSize, page.PageSize); sqlCount = string.Format(sqlCount, where); var rows = this._query.FindAll<AdjustContractPriceDto>(sql, param); page.Total = this._query.Context.ExecuteScalar<int>(sqlCount, param); return rows; } public IEnumerable<AdjustContractPriceItemDto> GetAdjustContractPriceItems(int AdjustContractPriceId) { string sql = @"select pc.ProductId,p.Code as ProductCode,p.`Name` as ProductName,p.BarCode,p.Specification,p.Unit,pc.AdjustPrice,pc.ContractPrice from AdjustContractPriceItem pc left join Product p on pc.ProductId=p.Id where pc.AdjustContractPriceId = @AdjustContractPriceId"; var productItems = _query.FindAll<AdjustContractPriceItemDto>(sql, new { AdjustContractPriceId = AdjustContractPriceId }); return productItems; } public IEnumerable<AdjustContractPriceItemDto> GetItems(int AdjustContractPriceId, int supplierId, int storeId) { string sql = @"select p.id as ProductId,p.`Name` as ProductName,p.Specification,p.`Code` as ProductCode,p.BarCode,p.Unit,p.Specification ,t.ContractPrice from (select c.Id,i.ProductId,i.ContractPrice,i.AdjustPrice from purchasecontract c inner join purchasecontractitem i on c.Id = i.PurchaseContractId left join supplier s on s.Id = c.SupplierId where c.`Status` = 3 and c.EndDate>= CURDATE() and s.Id=@SupplierId and FIND_IN_SET(@StoreId,c.StoreIds) and i.AdjustContractPriceId = @AdjustContractPriceId ) t left join product p on p.Id = t.ProductId "; var result = _query.FindAll<AdjustContractPriceItemDto>(sql, new { AdjustContractPriceId = AdjustContractPriceId, SupplierId = supplierId, StoreId = storeId, Today = DateTime.Now }); return result; } public AdjustContractPriceItemDto GetAdjustContractPriceItem(string productCodeOrBarCode, int supplierId, int storeId) { if (string.IsNullOrEmpty(productCodeOrBarCode)) { throw new Exception("请输入商品编码或条码"); } string sql = @"select p.id as ProductId,p.`Name` as ProductName,p.Specification,p.`Code` as ProductCode,p.BarCode,p.Unit,p.Specification ,t.ContractPrice from product p left join (select c.Id,i.ProductId,i.ContractPrice from purchasecontract c inner join purchasecontractitem i on c.Id = i.PurchaseContractId left join supplier s on s.Id = c.SupplierId where c.`Status` = 3 and c.EndDate>= CURDATE() and s.Id=@SupplierId and FIND_IN_SET(@StoreId,c.StoreIds) ) t on p.Id = t.ProductId where (p.BarCode=@ProductCodeOrBarCode or p.`Code`=@ProductCodeOrBarCode ) order by t.Id desc LIMIT 1"; var item = _query.Find<AdjustContractPriceItemDto>(sql, new { ProductCodeOrBarCode = productCodeOrBarCode, StoreId = storeId, SupplierId = supplierId }); return item; } public IEnumerable<AdjustContractPriceItemDto> GetAdjustContractPriceList(string inputProducts, int supplierId, int storeId) { if (string.IsNullOrEmpty(inputProducts)) throw new Exception("商品明细为空"); var dic = inputProducts.ToDecimalDic(); string sql = @"select p.id as ProductId,p.`Name` as ProductName,p.Specification,p.`Code` as ProductCode,p.BarCode,p.Unit,p.Specification ,t.ContractPrice from product p left join (select c.Id,i.ProductId,i.ContractPrice from purchasecontract c inner join purchasecontractitem i on c.Id = i.PurchaseContractId left join supplier s on s.Id = c.SupplierId where c.`Status` = 3 and c.EndDate>= CURDATE() and s.Id=@SupplierId and FIND_IN_SET(@StoreId,c.StoreIds) ) t on p.Id = t.ProductId where p.BarCode in @BarCodes order by t.Id desc"; var productItems = _query.FindAll<AdjustContractPriceItemDto>(sql, new { BarCodes = dic.Keys.ToArray(), SupplierId = supplierId, StoreId = storeId, Today = DateTime.Now }); foreach (var product in productItems) { if (dic.ContainsKey(product.BarCode)) { product.AdjustPrice = dic[product.BarCode]; } } return productItems; } public IEnumerable<SupplierDto> QuerySupplier(string productCodeOrBarCode, int storeId) { string sql = @"select s.Id,s.Code,s.Name,s.Type,t.Id as PurchaseContractId,t.code as PurchaseContractCode from supplier s left join ( select c.Id,c.code, c.SupplierId,c.StoreIds , i.ProductId from purchasecontract c inner join purchasecontractitem i on c.Id = i.PurchaseContractId where c.`Status` = 3 and c.EndDate > NOW() ) t on s.Id = t.SupplierId left join product p on p.Id = t.ProductId where (p.BarCode=@ProductCodeOrBarCode or p.`Code`=@ProductCodeOrBarCode ) and FIND_IN_SET(@StoreId,t.StoreIds) order by t.Id desc "; var result = _query.FindAll<SupplierDto>(sql, new { ProductCodeOrBarCode = productCodeOrBarCode, StoreId = storeId }); return result; } } }
using System; using System.Collections.Generic; using Laan.Sql.Parser.Expressions; namespace Laan.Sql.Parser.Entities { public class Top { public Top( Expression value, bool brackets ) { Brackets = brackets; Expression = value; } public override string ToString() { string format = Brackets ? " TOP ({0}){1}" : " TOP {0}{1}"; return String.Format( format, Expression.Value, Percent ? " PERCENT " : "" ); } public bool Brackets { get; private set; } public Expression Expression { get; set; } public bool Percent { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Content.PM; namespace CN.Jpush.Android.UI { [Activity(Name = "cn.jpush.android.ui.PushActivity", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.KeyboardHidden, Exported = false)] [IntentFilter(new string[] { "cn.jpush.android.ui.PushActivity" }, Categories = new string[]{ "android.intent.category.DEFAULT", Defines.PackageName })] public partial class PushActivity { } }
using System.Web.UI; namespace mssngrrr { public partial class MsgForm : UserControl { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LandmineADC : MonoBehaviour { public string type = "LandMine"; public bool randomizeCount = true; public int count; public List<GameObject> icon; private void Start() { if (randomizeCount) { count = Random.Range(1, 4); } } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Player")) { Player player = collision.gameObject.GetComponent<Player>(); player.GiveAirdrop(type, this.gameObject); Destroy(this.gameObject); } } }
using System; using System.Collections.Generic; namespace Podemski.Musicorum.Interfaces.Repositories { public interface IRepository<T> { void Save(T item); void Delete(int id); T Get(int id); bool Exists(int id); IEnumerable<T> Find(Func<T, bool> searchCriteria); } }
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; [Serializable] public class FireBallSkill : AbstractSkillUse { public override void StartUse(SkillProperties properties, Vector3 target, Vector3 start,int playerId) { base.StartUse(properties, target, start, playerId); target.y = transform.position.y; this.target = transform.position + (target - transform.position).normalized * properties.ragne; this.move = (target - transform.position).normalized * properties.speed; } public override void Use() { isUse = true; } void Update () { if (isServer) { if (isUse) { List<GameObject> hitPlayers = GetPlayers(); if(hitPlayers.Count>0) { foreach(GameObject go in hitPlayers) { go.GetComponent<Player>().doSkillUse(this); } Destroy(); } transform.position += move * Time.deltaTime; if (Vector3.Distance(transform.position, target) < 1f) Destroy(); } } } }
using UnityEngine; using System.Collections; /** * @author Chris Foulston */ namespace Malee.Hive.Util { public static class PhysicsUtil { public static void ClampVelocity(Rigidbody rigidbody, float threshold) { Vector3 velocity = rigidbody.velocity; float speed = velocity.magnitude; if (speed > threshold) { rigidbody.velocity = velocity.normalized * threshold; } } /* * TODO - Convert into spring public static void ClampVelocityForce(Rigidbody rigidbody, float threshold, ForceMode forceMode) { float speed = rigidbody.velocity.magnitude; if (speed > threshold) { float diff = speed - threshold; Debug.Log("OK" + diff); rigidbody.AddForce(-rigidbody.velocity / diff, forceMode); } } */ public static void AddForceWithLimit(Rigidbody rigidbody, Vector3 targetVelocity, float maxSpeed, float maxForce, ForceMode forceMode) { AddForceWithLimit(rigidbody, targetVelocity, maxSpeed, maxForce, forceMode, Vector3.one); } public static void AddForceWithLimit(Rigidbody rigidbody, Vector3 targetVelocity, float maxSpeed, float maxForce, ForceMode forceMode, Vector3 axis) { targetVelocity = Vector3.ClampMagnitude(targetVelocity, maxSpeed); Vector3 velocity = Vector3.Scale(rigidbody.velocity, axis); Vector3 velocityChange = Vector3.ClampMagnitude(targetVelocity - velocity, maxForce); rigidbody.AddForce(velocityChange, forceMode); } public static void ClearVelocity(Transform transform, Vector3 velocity, Vector3 angularVelocity, bool recursive) { if (recursive) { ClearVelocityRecursive(transform, velocity, angularVelocity); } else if (transform.rigidbody) { transform.rigidbody.velocity = velocity; transform.rigidbody.angularVelocity = angularVelocity; } } private static void ClearVelocityRecursive(Transform transform, Vector3 velocity, Vector3 angularVelocity) { if (transform.rigidbody) { transform.rigidbody.velocity = velocity; transform.rigidbody.angularVelocity = angularVelocity; } foreach (Transform child in transform) { ClearVelocityRecursive(child, velocity, angularVelocity); } } } }
using System; namespace ServiceDesk.Infrastructure { public class DomainEvent : Message { public DateTime Timestamp { get; private set; } public DomainEvent() { Timestamp = DateTime.UtcNow; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BugTracker.Entities { class Categoria { public int IdCategoria { get; set; } public string Nombre { get; set; } public Categoria() { } public Categoria(int idCategoria, string nombre) { this.IdCategoria = idCategoria; this.Nombre = nombre; } public int getIdCategoria() { return IdCategoria; } public string getNombre() { return Nombre; } public void setNombre(string nom) { Nombre = nom; } } }
using System; using System.Text; using System.Collections.Generic; using System.Web; using System.IO; using System.Xml; using System.Linq; using System.Net; using System.Xml.Serialization; using ASCOM; using ASCOM.Controls; using ASCOM.Utilities.Video; using ASCOM.DeviceInterface; using ASCOM.DriverAccess; using ASCOM.Interface; using ASCOM.Helper; using ComputerBeacon.Json; using CodeScales.Http; using CodeScales.Http.Methods; using CodeScales.Http.Entity; using CodeScales.Http.Entity.Mime; using CodeScales.Http.Common; using Occultationis; namespace Occultationis { class JANClient { static string url = "http://nova.astrometry.net"; static string apikey = "amblhcpsjipelcuu"; static string sesin = ""; static string fileName = ""; static string[] jobids = { "" }; static string[] jobstaties = { "" }; static string[] user_images = { "" }; static string userid = ""; static string delimiter = ";"; static int waitingTime = 10000; static int howManyTimes = 10; static string outString = "./"; static bool ascom = false; static double racenter; static double deccenter; static bool debug = true; private void setConfig() { } public string replaceSuffix(string filename, string suffix) { int lastPointPosition = filename.LastIndexOf("."); if (lastPointPosition < 0) { Console.WriteLine("The nameof image file is NOT correct: " + filename); // Exit } StringBuilder sb = new StringBuilder(); sb.Append(filename.Substring(0, lastPointPosition + 1)); sb.Append(suffix); return sb.ToString(); } public static JsonObject getLoginJSON(string s) { JsonObject obj = new JsonObject(); obj.Add("apikey", s); return obj; } public WebRequest makePost(string url, string data, string contentType) { WebRequest request = WebRequest.Create(url); request.Credentials = CredentialCache.DefaultCredentials; request.Method = "POST"; request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded"; Stream dataStream = request.GetRequestStream(); dataStream.Write(Encoding.ASCII.GetBytes(data), 0, Encoding.ASCII.GetByteCount(data)); Console.WriteLine(data); dataStream.Close(); return request; } public string loginPost() { // WebRequest request = WebRequest.Create( url + "/api/login" ); JsonObject jsonObject = getLoginJSON(apikey); String input = "&request-json=" + jsonObject.ToString(); WebRequest request = makePost(url + "/api/login", input, "application/x-www-form-urlencoded"); WebResponse response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusCode); Console.WriteLine(((HttpWebResponse)response).StatusDescription); Stream dataStream = ((HttpWebResponse)response).GetResponseStream(); StreamReader reader = new StreamReader(dataStream); String serverResponse = reader.ReadToEnd(); Console.WriteLine(serverResponse); reader.Close(); dataStream.Close(); response.Close(); return jsonGetValue(serverResponse, "session"); } public string jsonGetValue(string sjson, string key) { string value; object init; JsonObject jsonObj = new JsonObject(sjson); jsonObj.TryGetValue(key, out init); return init.ToString(); } public static JsonObject getUploadJSON(string session) { JsonObject obj = new JsonObject(); obj.Add("publicity_visible", "y"); obj.Add("allow_modifications", "d"); obj.Add("session", session); obj.Add("allow_commercial_use", "d"); return obj; } public string postFile(string session, string fileName) { int GOOD_RETURN_CODE = 200; string subIdLocal = ""; FileStream imageFile = File.OpenRead(fileName); CodeScales.Http.HttpClient httpClient = new CodeScales.Http.HttpClient(); HttpPost httpPost = new HttpPost(new Uri(url + "/api/upload/")); JsonObject jsonObject = getUploadJSON(session); MultipartEntity reqEntity = new MultipartEntity(); StringBody stringBody = new StringBody(Encoding.UTF8, "request-json", jsonObject.ToString()); reqEntity.AddBody(stringBody); FileInfo fileInfo = new FileInfo(fileName); FileBody fileBody = new FileBody("file", fileName, fileInfo); reqEntity.AddBody(fileBody); httpPost.Entity = reqEntity; HttpResponse response = httpClient.Execute(httpPost); String result = ""; int respCode = response.ResponseCode; if (respCode == GOOD_RETURN_CODE) { HttpEntity entity = response.Entity; String content = EntityUtils.ToString(entity); string success = jsonGetValue(content, "status"); subIdLocal = jsonGetValue(content, "subid"); string hash = jsonGetValue(content, "hash"); } return subIdLocal; } public string[] getJobids(String subID) { StringBuilder builder = new StringBuilder(); String results = ""; CodeScales.Http.HttpClient httpClient = new CodeScales.Http.HttpClient(); HttpGet httpget = new HttpGet(new Uri(url + "/api/submissions/" + subID)); HttpResponse response = httpClient.Execute(httpget); HttpEntity entity = response.Entity; results = EntityUtils.ToString(entity); if (debug) { Console.WriteLine("getJobsID gets:" + response.ResponseCode); Console.WriteLine("getJobsID :" + results); } String jobs = jsonGetValue(results, "jobs"); jobs = jobs.Replace("[", ""); jobs = jobs.Replace("]", ""); if (debug) { Console.WriteLine("Jobs: " + jobs); } char[] separator = { ',' }; string[] jobidsLocal = jobs.Split(separator); if (debug) { if (jobidsLocal.Length >= 1) { Console.WriteLine("Job IDs:"); for (int i = 0; i < jobidsLocal.Length; i++) { Console.WriteLine(jobidsLocal[i]); } } } userid = jsonGetValue(results, "user"); if (debug) { Console.WriteLine("\nUserID: " + userid); } String user_imageslocal = jsonGetValue(results, "user_images"); user_imageslocal = user_imageslocal.Replace("[", ""); user_imageslocal = user_imageslocal.Replace("]", ""); if (debug) { Console.WriteLine("User_images line: " + user_imageslocal); } user_images = user_imageslocal.Split(separator); if (debug) { if (user_images.Length >= 1) { Console.WriteLine("User images:"); for (int i = 0; i < user_images.Length; i++) { Console.WriteLine(user_images[i]); } } } return jobidsLocal; } public CalibrationData getCalibration(string jobid) { StringBuilder builder = new StringBuilder(); String result = ""; CodeScales.Http.HttpClient httpClient = new CodeScales.Http.HttpClient(); HttpGet httpGet = new HttpGet(new Uri(url + "/api/jobs/" + jobid + "/calibration")); HttpResponse response = httpClient.Execute(httpGet); HttpEntity entity = response.Entity; String content = EntityUtils.ToString(entity); if (debug) { Console.WriteLine("getCalibration gets: " + content); } String parity = jsonGetValue(content, "parity"); String orientation = jsonGetValue(content, "orientation"); String pixscale = jsonGetValue(content, "pixscale"); String radius = jsonGetValue(content, "radius"); String radecimal = jsonGetValue(content, "ra"); String decdecimal = jsonGetValue(content, "dec"); CalibrationData res = new CalibrationData(); res.parity = Double.Parse(parity); res.orientation = Double.Parse(orientation); res.pixscale = Double.Parse(pixscale); res.radius = Double.Parse(radius); res.ra = Double.Parse(radecimal); res.dec = Double.Parse(decdecimal); return res; } public string[] getJobStaties() { String[] staties = new String[jobids.Length]; for (int i = 0; i < jobids.Length; i++) { CodeScales.Http.HttpClient httpClient = new CodeScales.Http.HttpClient(); HttpGet httpGet = new HttpGet(new Uri(url + "/api/jobs/" + jobids[i])); HttpResponse response = httpClient.Execute(httpGet); HttpEntity entity = response.Entity; String results = EntityUtils.ToString(entity); if (debug) { Console.WriteLine("getJobStaties gets:" + response.ResponseCode); Console.WriteLine("getJobStaties :" + results); } String status = jsonGetValue(results, "status"); if (debug) { if (jobids[i] != "") { Console.WriteLine(jobids[i] + " " + status); } } staties[i] = status; } return staties; } public bool testResult() { bool b = false; for (int i = 0; i < jobids.Length; i++) { if ((jobids[i] != "") && (jobstaties[i].Equals("success"))) { b = true; } } return b; } public CalibrationData waitResult(string subID) { CalibrationData cal = new CalibrationData(); for (int i = 0; i < howManyTimes; i++) { System.Threading.Thread.Sleep(waitingTime); jobids = getJobids(subID); jobstaties = getJobStaties(); Console.Write("."); Boolean b = testResult(); if (b) { break; } } for (int i = 0; i < jobids.Length; i++) { cal = getCalibration(jobids[i]); } return cal; } public CalibrationData imageCalibration(string nameFile) { String sessionID = loginPost(); String sidl = postFile(sessionID, nameFile); CalibrationData calibrationData = waitResult(sidl); return calibrationData; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.IO; namespace demo1 { public partial class myleaves : System.Web.UI.Page { string Connection = ConfigurationManager.ConnectionStrings["mydb"].ConnectionString; string user; protected void Page_Load(object sender, EventArgs e) { string userName = Convert.ToString(Session["username"]); user = userName.ToString(); if (userName != null) { Label1.Text = "WELCOME-->" + userName.ToString(); } else { Response.Redirect("login.aspx"); } if (!IsPostBack) { PopulateGridview(); } } void PopulateGridview() { DataTable dtbl = new DataTable(); using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString)) { sqlCon.Open(); SqlDataAdapter sqlo = new SqlDataAdapter("SELECT Srno, EmployeeName, Date, Day, ActualTimeIn,ActualTimeOut,LateBy,ReasonOfLeave, ApprovalStatus, ApprovalRemarks FROM excel WHERE EmployeeName='" + user + "'", sqlCon); sqlo.Fill(dtbl); } if (dtbl.Rows.Count > 0) { GridView1.DataSource = dtbl; GridView1.DataBind(); } else { dtbl.Rows.Add(dtbl.NewRow()); GridView1.DataSource = dtbl; GridView1.DataBind(); GridView1.Rows[0].Cells.Clear(); GridView1.Rows[0].Cells.Add(new TableCell()); GridView1.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count; GridView1.Rows[0].Cells[0].Text = "NO DATA FOUND "; GridView1.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center; } } protected void LinkButton1_Click(object sender, EventArgs e) { } protected void LinkButton3_Click(object sender, EventArgs e) { Session.Clear(); Response.Redirect("logout.aspx"); } protected void LinkButton2_Click(object sender, EventArgs e) { Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "ProductDetail.xls")); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF"); for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++) { GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1"); } int j = 1; foreach (GridViewRow gvrow in GridView1.Rows) { gvrow.BackColor = System.Drawing.Color.White; if (j <= GridView1.Rows.Count) { if (j % 2 != 0) { for (int k = 0; k < gvrow.Cells.Count; k++) { gvrow.Cells[k].Style.Add("background-color", "#EFF3FB"); } } } j++; } GridView1.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { /* Verifies that the control is rendered */ } protected void Button1_Click(object sender, EventArgs e) { using (SqlConnection sqlCon = new SqlConnection(Connection)) { string find = "Select * from excel where(Date like '%' +@name) AND EmployeeName='" + user + "' "; SqlCommand com = new SqlCommand(find, sqlCon); com.Parameters.Add("@name", SqlDbType.NVarChar).Value = TextBox1.Text; sqlCon.Open(); com.ExecuteNonQuery(); SqlDataAdapter ad = new SqlDataAdapter(); ad.SelectCommand = com; DataSet ds = new DataSet(); ad.Fill(ds, "YEAR(Date)"); GridView1.DataSource = ds; GridView1.DataBind(); sqlCon.Close(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WhiteQuestions : AllQuestions { public WhiteQuestions() { this.allPossibleQuestions = new List<QuestionObject>(); Effect decreaseGold = new Effect(0, -10, 0); Effect hiredFriend = new Effect(0, 20, 15); Effect startedPayingMore = new Effect(0, 0, 10); Effect nothingNew = new Effect(0, 0, 0); Effect kickedOutNatives = new Effect(10, 20, 0); Effect joinedSmallCompany = new Effect(10, -5, -3); Effect gotSickForAWhile = new Effect(0, -20, 5); Effect claimBoughtOut = new Effect(30, -30, 5); Effect failedCompany = new Effect(0, -5, 50); Effect gotMoreGold = new Effect(0, 5, 0); Effect builtHouseWing = new Effect(0, 0, 50); Effect smallGoldDecrease = new Effect(0, -5, 0); Effect quickFailedCompany = new Effect(0, 5, 30); Effect cheapSupplies = new Effect(0, 0, -10); Effect backedSmallBusiness = new Effect(50, 0, 20); Effect wifeIsDisgusted = new Effect(0, 0, 30); Effect wifeSupported = new Effect(0, 0, 15); Effect nativeSudoSlave = new Effect(0, 20, 5); QuestionObject q1 = new QuestionObject(failedCompany, gotMoreGold, "One of your friends offers to let you buy into his company and work there for the next couple of months. Alternatively you could continue to work at prospecting.", "Sign on to your Friend's company", "Prospect in the nearby river", "Your group's attempts to divert water and mine a riverbed failed due to the heavy riverbed rocks and you make no money.", "The River had too much water and you have difficulty finding gold."); QuestionObject q2 = new QuestionObject(startedPayingMore, decreaseGold, "Your cradle breaks. You need a cradle to seperate dirt and gold, so you decide to replace it.", "You buy a new one", "You attempt to fixes yourself", "It costs you some money but you get back to work", "It doesn't work very well for some time and eventually you get one from someone going back east"); QuestionObject q3 = new QuestionObject(nothingNew, builtHouseWing, "You are forced to pay for an expensive fix to your house.", "Write home to try to try to get money", "Pay with your money in the West", "Your wife is able to call in debts and get you the money", "It really costs you, but your family at least was not put through financial hardship"); QuestionObject q4 = new QuestionObject(smallGoldDecrease, decreaseGold, "You are not eating right and feel your teeth loosening from scurvy", "Eat grass, it might help", "Try to find better food", "It does help...", "You are unable to find a fruit vendor and you loose some teeth."); QuestionObject q5 = new QuestionObject(gotSickForAWhile, decreaseGold, "The wet season creates sickness throughout the camp and you become very sick.", "Rest to try to recover", "Keep working", "You recover, but find little gold", "You don't recover soon. You collect little and end up never fully recovering"); QuestionObject q6 = new QuestionObject(quickFailedCompany, nothingNew, "A few people you know offer you a chance to block up a river to mine out the gold.", "Pay in to the company", "move on to find another opportunity", "Your group tries to dam the river but more rain than usual slows and eventually stops you", "You end up just panning for gold in the river"); QuestionObject q7 = new QuestionObject(cheapSupplies, nothingNew, "A steam boat comes down the river", "Try to trade with it", "ignore it and stick with your current supplies", "The boat has cheap supplies that it is selling!", "Life goes on unchanged"); QuestionObject q8 = new QuestionObject(smallGoldDecrease, smallGoldDecrease, "A friend from home writes you to ask if he should come out to mine in the west", "Discourage him", "Tell stories about the gold", "While your friend does not come, your warnings are drowned out by stories of gold and many more people come west", "Your friend along with thousands more people come out west to try to get a gold claim"); QuestionObject q9 = new QuestionObject(nothingNew, decreaseGold, "Your claim seems like it has no gold", "Stick with it and hope you eventually find gold", "try a new claim", "Your claim stays about the same", "Your new claim is worse than your original"); QuestionObject q10 = new QuestionObject(nothingNew, gotMoreGold, "Your claim seems like it has no gold", "Stick with it and hope you eventually find gold", "try a new claim", "Your claim stays about the same", "Your new claim is better than the last"); QuestionObject q11 = new QuestionObject(backedSmallBusiness, nothingNew, "Your friend asks for some money to start a mining equipment shop", "Give him the money", "Don't give him the money", "He strikes it rich selling supplies to new miners and rewards you for your investment", "Nothing really happens"); QuestionObject q12 = new QuestionObject(wifeIsDisgusted, wifeSupported, "Your wife writes to say that she is having troubles back home", "Tell her to come out west with you", "Send her home some money", "Upon arriving your wife realizes the kind of behavior that you engage in at the camps and leaves disgusted with you and with a lot of money", "The money you send her is put to good use"); QuestionObject q13 = new QuestionObject(nothingNew, nothingNew, "You are called to a camp trial over a supposed crime by a Mexican citizen", "Vote guilty", "Vote not guilty", "The Mexican is found guilty", "The Mexican is still found guilty"); QuestionObject q14 = new QuestionObject(kickedOutNatives, nothingNew, "You hear rumours of gold on native lands", "Join a vigilanty group", "stay with your current claim", "The state government does nothing to punish you and eventually the army comes in to deal with the natives you fought. You get the valuable land", "You hear that the others made a lot of money from the land they were able to take, but your decendents get to say that you didn't participate in that genocide"); QuestionObject q15 = new QuestionObject(nativeSudoSlave, hiredFriend, "You find that you want some help around your land", "Lease a native prisoner", "Offer someone full pay to work for you", "You are able to boost your productivity while also paying very little income", "You end up paying a lot"); this.allPossibleQuestions.Add(q1); this.allPossibleQuestions.Add(q2); this.allPossibleQuestions.Add(q3); this.allPossibleQuestions.Add(q4); this.allPossibleQuestions.Add(q5); this.allPossibleQuestions.Add(q6); this.allPossibleQuestions.Add(q7); this.allPossibleQuestions.Add(q8); this.allPossibleQuestions.Add(q9); this.allPossibleQuestions.Add(q10); this.allPossibleQuestions.Add(q11); this.allPossibleQuestions.Add(q12); this.allPossibleQuestions.Add(q13); this.allPossibleQuestions.Add(q14); this.allPossibleQuestions.Add(q15); this.lastQuestion = new QuestionObject(null, null, "", "", "", "", ""); } protected override QuestionObject GetQuestionObject(int year) { QuestionObject potential = this.allPossibleQuestions[Random.Range(0, allPossibleQuestions.Count)]; while (potential.question == this.lastQuestion.question) { potential = this.allPossibleQuestions[Random.Range(0, this.allPossibleQuestions.Count)]; } this.lastQuestion = potential; return potential; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FluentValidation; using TableroComando.Dominio; namespace Dominio.Validations { public class IndicadorValidator : ModelValidator<Indicador> { public IndicadorValidator() { RuleFor(i => i.Nombre) .NotNull(); RuleFor(i => i.Responsable) .NotNull(); RuleFor(i => i.Frecuencia) .NotNull(); RuleFor(i => i.Objetivo) .NotNull(); RuleFor(i => i.Restricciones) .NotNull(); RuleFor(i => i.Codigo) .NotNull() .Must((indicador, codigo) => IndicadorRepository.Instance.ValidateCodigoUnico(indicador)) .WithMessage("El código '{0}' ya existe", i => i.Codigo); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using DFrame; using PM=DAV.ProgramMonitor; using DPYM; namespace DPYM_DEBUG { /// <summary> /// 场景中程序记录器的操作对象 /// </summary> public class PMLogger : MonoBehaviour { public bool isOpen = false; private readonly string _openMessage = "logging"; private readonly string _closedMessage = "open logger"; [SerializeField] private Text _text; private void Start() { if (PM.isOpen) { isOpen = true; SetString(_openMessage); } } private void Update() { if (isOpen != PM.isOpen) { isOpen = PM.isOpen; if (isOpen) { DLogger.MD("[INFO] PMLogger.OnClick : Opened by others."); SetString(_openMessage); } else { DLogger.KMD("[INFO] PMLogger.OnClick : Closed by others."); SetString(_closedMessage); } } } public void OnClick() { isOpen = !isOpen; if (isOpen) { DLogger.MD("[INFO] PMLogger.OnClick : Opened by user."); SetString(_openMessage); } else { DLogger.KMD("[INFO] PMLogger.OnClick : Closed by user."); SetString(_closedMessage); } } private void SetString(string messagw) { _text.text = messagw; } } }
using System; using System.Runtime.InteropServices; 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.IO; using System.Reflection; using System.Windows.Forms; using System.Threading; using System.Diagnostics; //using Excel = Microsoft.Office.Interop.Excel; namespace Validator { public partial class Form1 : Form { /* public class Excel_validator { [DllImport("Validator_dll.dll")] public static extern void correlation_check(string file_name); [DllImport("Validator_dll.dll")] public static extern void variable_type_check(string file_path); [DllImport("Validator_dll.dll")] public static extern void vaildate_all(); }*/ public static TextBox box; public static TextBox box_file_name; public static Validator_dll.Validator validator; public Form1() { InitializeComponent(); box = (TextBox)this.Controls["textBox1"]; box_file_name = (TextBox)this.Controls["textBox2"]; Validator_dll.Validator.Instance.init(); Trace.WriteLine("init end!!"); } private void close_dlg(object sender, EventArgs e) { Util.trace_msg("quit call!!"); } //연관성 체크 private void correlation_check_btn(object sender, EventArgs e) { string file_path = box_file_name.Text; if (file_path == "") { MessageBox.Show(Validator.Properties.Resources.ERROR_FILE_PATH); return; } Validator_dll.Validator.Instance.correlation_check(file_path); Util.print_log(Validator_dll.Validator.Instance.output); Util.print_log(Validator.Properties.Resources.COMPLETE_CORRELATION); } private void variable_type_check_btn(object sender, EventArgs e) { string file_path = box_file_name.Text; if (file_path == "") { MessageBox.Show(Validator.Properties.Resources.ERROR_FILE_PATH); return; } Validator_dll.Validator.Instance.variable_type_check(file_path); Util.print_log(Validator_dll.Validator.Instance.output); Util.print_log("Type validate 완료"); } //모두 검증 private void vaildate_all_btn(object sender, EventArgs e) { if (MessageBox.Show(Validator.Properties.Resources.CHECK_REALY , "주의!!", MessageBoxButtons.YesNo) == DialogResult.Yes) { Validator_dll.Validator.Instance.vaildate_all(); Util.print_log(Validator_dll.Validator.Instance.output); Util.print_log("vaildate_all 완료", true); } } private void folder_select(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "EXCEL FILE|*.xlsx"; openFileDialog.Title = "Select a Excel File"; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { box_file_name.Text = openFileDialog.FileName; } } } }
using ClinicManagement.Core.Aggregates; using ClinicManagement.Core.ValueObjects; namespace UnitTests.Builders { public class PatientBuilder { private Patient _patient; public PatientBuilder() { WithDefaultValues(); } public PatientBuilder Id(int id) { _patient.Id = id; return this; } public PatientBuilder SetPatient(Patient patient) { _patient = patient; return this; } public PatientBuilder WithDefaultValues() { _patient = new Patient(1, "Test Patient", "MALE", new AnimalType("Cat", "Mixed")); return this; } public Patient Build() => _patient; } }
namespace SpeckleBot.Data { public class Links { public static string PLEADING_BRICK = "https://user-images.githubusercontent.com/7717434/101414600-49facb00-38de-11eb-95c5-771c5baba15d.png"; } }
using System; namespace useSOLIDin { class Swap : ISwap { public void SwapElementOnPosition(Int32 cpl, Int32 cpt, GameBoard gb) { int pos = cpl + cpt * (int)Math.Sqrt(gb.CodedLevelData.Length); char charInPos = gb.CodedLevelData[pos]; char[] temp = gb.CodedLevelData.ToCharArray(); charInPos = charInPos == 'x' ? 'o' : 'x'; temp[pos] = charInPos; gb.CodedLevelData = new string(temp); } } }
/****************************************************************************** * File : pLab_KJPOCMainMenu.cs * Lisence : BSD 3-Clause License * Copyright : Lapland University of Applied Sciences * Authors : Toni Westerlund (toni.westerlund@lapinamk.fi) Arto Söderström (arto.soderstrom@lapinamk.fi) * BSD 3-Clause License * * Copyright (c) 2019, Lapland University of Applied Sciences * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; /// <summary> /// MainMenu-script /// </summary> public class pLab_KJPOCMainMenu : MonoBehaviour { #region Variables [SerializeField] private Button continueButton; [SerializeField] private GameObject areUSureDialog; [SerializeField] private GameObject nameDialog; [SerializeField] private InputField playerNameInputField; [SerializeField] private string mainSceneName = "Level_001 AR Kemijarvi"; #endregion #region Inherited Methods private void Start(){ continueButton.interactable = pLab_KJPOCSaveGame.Instance.IsThereSave(); } private void Update(){ if (Application.platform == RuntimePlatform.Android){ if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } } } #endregion #region Private Methods private void LoadMainScene() { SceneManager.LoadScene(mainSceneName); } #endregion #region Public Methods /// <summary> /// Starts a new fresh game /// </summary> public void StartNewGame(){ string name = playerNameInputField.text.ToString(); if(name.Length < 1){ name = "Pelaaja"; } pLab_KJPOCSaveGame.Instance.CreateNewGame(name); LoadMainScene(); } /// <summary> /// Set player name query element active /// </summary> public void PlayerNameQuery(){ areUSureDialog.SetActive(false); nameDialog.SetActive(true); } /// <summary> /// Sets "are you sure" dialog active if there is a save. Otherwise starts a new game /// </summary> public void PrepareToStartNewGame(){ if (pLab_KJPOCSaveGame.Instance.IsThereSave()) { areUSureDialog.SetActive(true); } else { StartNewGame(); } } /// <summary> /// Loads gamesave and loads the main scene /// </summary> public void LoadGame() { pLab_KJPOCSaveGame.Instance.LoadGame(); LoadMainScene(); } #endregion }
using Common.Data; using Common.Exceptions; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using Common.Extensions; namespace Entity { public partial class MovieGenre { public List<string> GetMovieGenres(string connectionString, int id) { List<string> result = new List<string>(); string sql = "select genre from movie_genre where id = " + id.ToString(); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectStringList(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public List<string> GetMovieGenresByRank(string connectionString, int id) { List<string> result = new List<string>(); string sql = "select genre from movie_genre where id = " + id.ToString() + " order by rank"; using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectStringList(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public List<Tuple<int, string>> GetRankAndGenre(string connectionString, int id) { List<Tuple<int, string>> result = new List<Tuple<int, string>>(); string sql = "select rank, genre from movie_genre where id = " + id.ToString() + " "+ "and genre is not null and genre <> ''"; using (Database database = new Database(connectionString)) { try { using (DataTable dt = database.ExecuteSelect(sql)) { if (dt.HasRows()) { foreach (DataRow dr in dt.Rows) { result.Add(new Tuple<int, string>(Convert.ToInt32(dr["rank"]), dr["genre"].ToString())); } } } } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public bool HasTranny(string connectionString, int id) { bool result = false; //select count(*) from movie_genre where id = @ID and genre = 'tranny' string sql = "P_Search_Exclude_Tranny"; SqlParameter parameter = new SqlParameter("@ID", id); using(Database database = new Database(connectionString)) { try { result = database.ExecuteSelectInt(sql, parameters: new SqlParameter[] { parameter }).GetValueOrDefault() > 0; } catch(Exception e) { throw new EntityException(sql, e); } finally { parameter = null; } } return result; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Ejercicios_LibroCSharp.Cap._9.Entidades; using Ejercicios_LibroCSharp.Cap._9.UI.Registro; using Ejercicios_LibroCSharp.Cap._9; using System.Collections; namespace Ejercicios_LibroCSharp.Cap._9.UI.Registro { public partial class rDueñoMascota : Form { public rDueñoMascota() { InitializeComponent(); } ArrayList arrayList = new ArrayList(); public DueñoMascota DueñoMascota = new DueñoMascota(); private bool Validar() { bool paso = true; MyErrorProvider.Clear(); if (NombreDTextBox.Text == string.Empty) { MyErrorProvider.SetError(NombreDTextBox, "Este campo no puede estar vacio"); NombreDTextBox.Focus(); paso = false; } if (EdadTextBox.Text == string.Empty) { MyErrorProvider.SetError(EdadTextBox, "Este campo no puede estar vacio"); EdadTextBox.Focus(); paso = false; } if (SexoDTextBox.Text == string.Empty) { MyErrorProvider.SetError(SexoDTextBox, "Este campo no puede estar vacio"); SexoDTextBox.Focus(); paso = false; } if (NombreMTextBox.Text == string.Empty) { MyErrorProvider.SetError(NombreMTextBox, "No puede dejar este campo vacio"); NombreMTextBox.Focus(); paso = false; } if (DuenoTextBox.Text == string.Empty) { MyErrorProvider.SetError(DuenoTextBox, "No puede dejar este campo vacio"); DuenoTextBox.Focus(); paso = false; } if (SexoTextBox.Text == string.Empty) { MyErrorProvider.SetError(SexoTextBox, "No puede dejar este campo vacio"); SexoTextBox.Focus(); paso = false; } return paso; } public void Limpiar() { NombreDTextBox.Text = string.Empty; EdadTextBox.Text = string.Empty; SexoDTextBox.Text = string.Empty; NombreMTextBox.Text = string.Empty; DuenoTextBox.Text = string.Empty; SexoTextBox.Text = string.Empty; } public void Agregar() { DueñoMascota dueño = new DueñoMascota(); dueño.NombreD = NombreDTextBox.Text; dueño.edadD = EdadTextBox.Text; dueño.sexoD = SexoDTextBox.Text; dueño.NombreMascota = NombreMTextBox.Text; dueño.DueñoMascot = DuenoTextBox.Text; dueño.sexoMascota = SexoTextBox.Text; arrayList.Add(dueño); MessageBox.Show("!!Informacion Guardadas!!"); } public void Mostrar() { DataGridView.DataSource = null; DataGridView.DataSource = arrayList; } private void NuevoButton_Click(object sender, EventArgs e) { Limpiar(); } private void GuardarButton_Click(object sender, EventArgs e) { if(Validar()) Agregar(); Limpiar(); } private void MostrarButton_Click(object sender, EventArgs e) { Mostrar(); Limpiar(); } } }
using UnityEngine; using System.Collections; using System; public class BulletOracleBehaviour : Bullet { public Transform render; Vector3 myScale = Vector3.zero; void OnEnable() { if (myScale == Vector3.zero) myScale = transform.localScale; transform.localScale = myScale; StartCoroutine(bulletCoroutine()); } void OnDisable() { StopAllCoroutines(); } void Update() { //Movimenta o objeto move(); //verifica onde o objeto está para desliga-lo checkEnds(); } /// <summary> /// verifica se a posição da bala está fora do quadro da tela /// </summary> public override void checkEnds() { if (transform.position.y < CameraManager.instance.bottomDown || transform.position.y > CameraManager.instance.bottomUp || transform.position.x > CameraManager.instance.bottomRight || transform.position.x < CameraManager.instance.bottomLeft) { //desliga o objeto se ele estive fora da Screen do Usuario gameObject.SetActive(false); } } /// <summary> /// Movimenta da Bala /// </summary> public override void move() { //Movimenta o objeto sempre em Y positivo transform.Translate(new Vector3(velocity.x, velocity.y * Time.deltaTime)); render.Rotate(new Vector3(0,0,180) * Time.deltaTime); } /// <summary> /// Metodo que contem implementação unica /// </summary> public override void bulletSpecial() { throw new NotImplementedException(); } /// <summary> /// Metodo de uma coroutine se for necessario para usar /// </summary> /// <returns></returns> public override IEnumerator bulletCoroutine() { yield return new WaitForSeconds(0.3f); gameObject.transform.localScale += gameObject.transform.localScale*0.15f; StartCoroutine(bulletCoroutine()); } }
using System.Collections; using System.Collections.Generic; using BP12.Events; using DChild.Gameplay.Combat; using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { public class Goblin : Minion { [SerializeField] [MinValue(1f)] [TabGroup("Movement")] private float m_retreatSpeed; [SerializeField] [MinValue(1f)] [TabGroup("Movement")] private float m_moveSpeed; [SerializeField] [MinValue(0f)] [TabGroup("Attack")] private float m_attackFinishRest; [SerializeField] private DamageFXType m_damageType; [SerializeField] private AttackDamage m_damage; private GoblinAnimation m_animation; private PhysicsMovementHandler2D m_movement; private EnemyBehaviourHandler m_behaviourHandler; private ITurnHandler m_turn; private ICharacterTime m_characterTime; protected override CharacterAnimation animation => m_animation; public bool isAttacking => m_animation.isAttackingAnimationPlaying; public void LookAt(Vector2 target) => m_turn.LookAt(target); public void Retreat(Vector2 destination) { m_movement.MoveTo(destination, m_retreatSpeed); m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(RetreatRoutine(destination))); } public void TossCoin() { m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(TossCoinRoutine())); } public void HeadButt() { m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(HeadButtRoutine())); } public void Stay() { m_movement.Stop(); //IdleAnim } private void Flinch() { m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(WaitRoutine())); } private IEnumerator WaitRoutine() { m_waitForBehaviourEnd = true; yield return new WaitForSeconds(1f); m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } private IEnumerator RetreatRoutine(Vector2 destination) { yield return new WaitForSeconds(1f); m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_waitForBehaviourEnd = true; yield return null; } private IEnumerator TossCoinRoutine() { //HeadBUtt yield return null; } private IEnumerator HeadButtRoutine() { //HeadButt Animation yield return null; } private IEnumerator DeathRoutine() { m_waitForBehaviourEnd = true; m_movement.Stop(); //Do animation death yield return null; m_behaviourHandler.SetActiveBehaviour(null); m_waitForBehaviourEnd = false; } protected override void OnTakeExternalDamage(DamageSource source) { Flinch(); base.OnTakeExternalDamage(source); } protected override EventActionArgs OnDeath(object sender, EventActionArgs eventArgs) { base.OnDeath(sender, eventArgs); m_behaviourHandler.StopActiveBehaviour(ref m_waitForBehaviourEnd); m_behaviourHandler.SetActiveBehaviour(StartCoroutine(DeathRoutine())); return eventArgs; } protected override void GetAttackInfo(out AttackInfo attackInfo, out DamageFXType fxType) { fxType = m_damageType; attackInfo = new AttackInfo(m_damage, 0, null, null); } protected override void InitializeMinion() { m_health.InitializeHealth(); } protected override void Awake() { base.Awake(); m_movement = new PhysicsMovementHandler2D(GetComponent<ObjectPhysics2D>(), transform); m_behaviourHandler = new EnemyBehaviourHandler(this); m_turn = new SimpleTurnHandler(this); m_characterTime = GetComponent<ICharacterTime>(); m_animation = GetComponent<GoblinAnimation>(); } } }
using Entities; using System.Collections.Generic; namespace DataAccess { public interface INoteHandler { Note GetNoteById(int id); List<Note> GetNotes(); void AddNote(Note note); bool UpdateNote(int id,Note note); bool DeleteNote(int id); void AddLabel(int noteId, Label label); void UpdateLabel(int noteId, Label label); ICollection<Label> GetLabels(int noteId); void DeleteLabelByNoteIdAndLabelId(int noteId, int labelId); Label GetLabelById(int noteId, int labelId); } }
using Microsoft.SharePoint.Client; namespace DistCWebSite.SharePoint.Utility { public static class ListItemExtension { public static string GetValue(this ListItem item, string fieldName) { if (item == null || string.IsNullOrEmpty(fieldName)) { return ""; } else if (item[fieldName] == null) { return ""; } else { return item[fieldName].ToString(); } } public static string GetUrlValue(this ListItem item, string fieldName) { string value = ""; if (item == null || string.IsNullOrEmpty(fieldName)) { return ""; } var url = item[fieldName] as FieldUrlValue; if (url != null) { value = url.Url; } return value; } public static string GetUrlDescription(this ListItem item, string fieldName) { string value = ""; if (item == null || string.IsNullOrEmpty(fieldName)) { return ""; } var url = item[fieldName] as FieldUrlValue; if (url != null) { value = url.Description; } return value; } public static string GetUserValue(this ListItem item, string fieldName) { string value = ""; if (item == null || string.IsNullOrEmpty(fieldName)) { return ""; } var url = item[fieldName] as FieldUserValue; if (url != null) { value = url.LookupValue; } return value; } } }
namespace WinAppDriver.SystemWrapper.Windows.Input { using System.Windows.Input; internal class KeyInteropWrap : IKeyInteropWrap { public Key KeyFromVirtualKey(int virtualKey) { return KeyInterop.KeyFromVirtualKey(virtualKey); } public int VirtualKeyFromKey(Key key) { return KeyInterop.VirtualKeyFromKey(key); } } }
using UnityEditor; using UnityAtoms.Editor; using UnityEngine; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Variable Inspector of type `Collision2D`. Inherits from `AtomVariableEditor` /// </summary> [CustomEditor(typeof(Collision2DVariable))] public sealed class Collision2DVariableEditor : AtomVariableEditor<Collision2D, Collision2DPair> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TreehouseDefense { abstract class Invader : IInvader //This is not saying that the Invader inherits from the IInvader but that Invader implements the IInvader interface//Interfaces are similar to types. They can be used in place of classes.Interfaces can be used to replace the base type //abstract base class - defines what it means to be an invader but isn't a type of invader that can be created. abstract base class means no longer a concrete implementation of an invader. provides an abstract definition of what an invader is. can no longer instatiate can only subclass it - create basic invader { private readonly Path _path; private int _pathStep = 0; protected virtual int StepSize {get; } = 1; //only has a getter and returns constant value this is a read only property since it doesn't have a setter it can't be changed to anything else//protected access modifies only allows access from class and its subclasses public MapLocation Location => _path.GetLocationAt(_pathStep); public bool HasScored { get { return _pathStep >= _path.Length; } } //invader has scored if the path to the is equal to the path's length public abstract int Health { get; protected set; }//allows different types of invaders to have different levels of initial health //making health property abstract means that healthproperty must be overriden in subclasses. abstract properties canthave implementation //Properties in an interface don't have implementation public bool IsNeutralized => Health <= 0; public bool IsActive => !(IsNeutralized || HasScored); public Invader(Path path) ///constructor is still here in invader class. when copying public members to IInvader, removed constructor since interfaces don't have constructors { _path = path; } public void Move() => _pathStep += 1; //methods in an interface don't have implemementation. Deleting implementation from move and decrease health methods in IInvader public virtual void DecreaseHealth(int factor) //virtual is polymorphic. tell c# that this is just one possible implementation of the decreased health method { Health -= factor; Console.WriteLine("Shot at and hit an invader!"); } } }
using Revisao.LogConfing; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace ExceptionControl.LogConfing { public class SendEmailWay { public void SendEmailWAy(Email email, string error) { try { MailMessage mail = new MailMessage(); mail.Body = "<p style='font-size: 12px;color: red;'>Erros</p>"; mail.IsBodyHtml = true; mail.Subject = email.Subject; mail.Body = error; foreach (string item in email.EmailDestinatarios) { mail.To.Add(item); } mail.From = new MailAddress("TRABALHOENTRA21@GMAIL.COM"); SmtpClient servidor = new SmtpClient("smtp.gmail.com", 587); servidor.EnableSsl = true; servidor.UseDefaultCredentials = false; servidor.Credentials = new NetworkCredential("trabalhoentra21@gmail.com", "csharp>java"); servidor.Send(mail); } catch (Exception ex) { } } } }
using MySql.Data.MySqlClient; using PROYECTOFINAL.Models; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Mvc; using Libreria; namespace PROYECTOFINAL.Controllers { public class CajaController : Controller { // GET: Caja public ActionResult Index() { return View(); } public ActionResult Inicio(FormCollection formulario) { bool existe = false; int registros = -1; var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { int cajaI = Convert.ToInt16(Request.Form["cajaInicial"]); using (MySqlConnection con = producto.AbrirConexion()) { MySqlCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "ObtenerCajaExistente"; cmd.Parameters.AddWithValue("fech", DateTime.Today); cmd.Parameters.AddWithValue("idLocal", Convert.ToInt16(idLocal)); MySqlDataReader lector = cmd.ExecuteReader(); while (lector.Read()) { existe = true; } con.Close(); } if (existe == false) { using (MySqlConnection con2 = producto.AbrirConexion()) { MySqlCommand cmd2 = con2.CreateCommand(); cmd2.CommandType = CommandType.StoredProcedure; cmd2.CommandText = "InsertarCajaInicial"; cmd2.Parameters.AddWithValue("fecha", DateTime.Today); cmd2.Parameters.AddWithValue("montoCaja", cajaI); cmd2.Parameters.AddWithValue("idLocal", idLocal); registros = cmd2.ExecuteNonQuery(); con2.Close(); } } return View(registros); } } public ActionResult CerrarCaja() { //averigua si la caja del dia de la fecha esta cerrada y sino la cierra int idLocal = Convert.ToInt16(Session["idLocal"]); if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { int cajafinal = caja.ObtenerCajaFinal(idLocal); if (cajafinal == -1) { using (MySqlConnection con2 = producto.AbrirConexion()) { MySqlCommand cmd2 = con2.CreateCommand(); cmd2.CommandType = CommandType.StoredProcedure; cmd2.CommandText = "CerrarCaja"; cmd2.Parameters.AddWithValue("idLocal", idLocal); int registros = cmd2.ExecuteNonQuery(); con2.Close(); } cajafinal = caja.ObtenerCajaFinal(idLocal); } return View(cajafinal); } } public ActionResult ListarMovimientosCaja() { var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { return View(); } } public ActionResult MostrarMovDia(DateTime fecha) { //seleccionar los movimientos de la caja de un dia var idLocal = Session["idLocal"]; if (Session["idLocal"] == null) { return RedirectToAction("Index", "Usuarios"); } else { ViewBag.Fecha = fecha; List<movimientosmodel> lmov = caja.ListarMovimientosCajaXDia(fecha); return View(lmov); } } } }
using System.Collections.Generic; using System.Linq; using Giusti.Chat.Model.Results; using Giusti.Chat.Business.Library; using Giusti.Chat.Data; using Giusti.Chat.Model; using System; using Giusti.Chat.Model.Dominio; using System.Web.Security; namespace Giusti.Chat.Business { public class EmpresaBusiness : BusinessBase { public Empresa RetornaEmpresa_Id(int id) { LimpaValidacao(); Empresa RetornoAcao = null; if (IsValid()) { using (EmpresaData data = new EmpresaData()) { RetornoAcao = data.RetornaEmpresa_Id(id); } } return RetornoAcao; } public Empresa RetornaEmpresa_Id(int id, int? empresaId) { LimpaValidacao(); Empresa RetornoAcao = null; if (IsValid()) { using (EmpresaData data = new EmpresaData()) { RetornoAcao = data.RetornaEmpresa_Id(id, empresaId); } } return RetornoAcao; } public bool ExisteUsuario_EmpresaId(int empresaId) { LimpaValidacao(); bool RetornoAcao = false; if (IsValid()) { using (EmpresaData data = new EmpresaData()) { RetornoAcao = data.ExisteUsuario_EmpresaId(empresaId); } } return RetornoAcao; } public bool ExisteArea_EmpresaId(int empresaId) { LimpaValidacao(); bool RetornoAcao = false; if (IsValid()) { using (EmpresaData data = new EmpresaData()) { RetornoAcao = data.ExisteArea_EmpresaId(empresaId); } } return RetornoAcao; } public IList<Empresa> RetornaEmpresas() { LimpaValidacao(); IList<Empresa> RetornoAcao = new List<Empresa>(); if (IsValid()) { using (EmpresaData data = new EmpresaData()) { RetornoAcao = data.RetornaEmpresas(); } } return RetornoAcao; } public IList<Empresa> RetornaEmpresas(int? empresaId) { LimpaValidacao(); IList<Empresa> RetornoAcao = new List<Empresa>(); if (IsValid()) { using (EmpresaData data = new EmpresaData()) { RetornoAcao = data.RetornaEmpresas(empresaId); } } return RetornoAcao; } public void SalvaEmpresa(Empresa itemGravar) { LimpaValidacao(); ValidateService(itemGravar); ValidaRegrasSalvar(itemGravar); if (IsValid()) { using (EmpresaData data = new EmpresaData()) { data.SalvaEmpresa(itemGravar); IncluiSucessoBusiness("Empresa_SalvaEmpresaOK"); } } } public void ExcluiEmpresa(Empresa itemGravar) { LimpaValidacao(); ValidateService(itemGravar); ValidaRegrasExcluir(itemGravar); if (IsValid()) { using (EmpresaData data = new EmpresaData()) { data.ExcluiEmpresa(itemGravar); IncluiSucessoBusiness("Empresa_ExcluiEmpresaOK"); } } } public void ValidaRegrasSalvar(Empresa itemGravar) { if (IsValid() && string.IsNullOrWhiteSpace(itemGravar.Nome)) IncluiErroBusiness("Empresa_Nome"); if (IsValid()) { if (itemGravar.Id.HasValue) { Empresa itemBase = RetornaEmpresa_Id((int)itemGravar.Id); ValidaExistencia(itemBase); if (IsValid()) { itemGravar.Chave = itemBase.Chave; itemGravar.DataInclusao = itemBase.DataInclusao; itemGravar.DataAlteracao = DateTime.Now; } } else { itemGravar.Chave = Guid.NewGuid().ToString(); itemGravar.DataInclusao = DateTime.Now; itemGravar.Ativo = true; } } if (IsValid() && itemGravar.Id == (int)Constantes.EmpresaMasterId) IncluiErroBusiness("Empresa_SemPermissaoEdicaoExclusao"); } public void ValidaRegrasExcluir(Empresa itemGravar) { if (IsValid()) { Empresa itemBase = RetornaEmpresa_Id((int)itemGravar.Id); ValidaExistencia(itemBase); } if (IsValid() && itemGravar.Id == (int)Constantes.EmpresaMasterId) IncluiErroBusiness("Empresa_SemPermissaoEdicaoExclusao"); if (IsValid() && ExisteUsuario_EmpresaId((int)itemGravar.Id)) IncluiErroBusiness("Empresa_CadastroUtilizado"); if (IsValid() && ExisteArea_EmpresaId((int)itemGravar.Id)) IncluiErroBusiness("Empresa_CadastroUtilizado"); } public void ValidaExistencia(Empresa itemGravar) { if (itemGravar == null) IncluiErroBusiness("Empresa_NaoEncontrada"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Data.SqlClient; using System.Net; using System.Net.Sockets; using System.IO; namespace HealthApp.FileSystem { [Serializable] class Settings { private const string fileName = "settings.bin"; // database server private string dbServer; public string DbServer { get { return this.dbServer; } set { this.dbServer = value; } } private string dbObject; public string DbObject { get { return this.dbObject; } set { this.dbObject = value; } } private string dbName; public string DbName { get { return this.dbName; } set { this.dbName = value; } } private bool isWondowsAuth; public bool IsWindowAuth { get { return this.isWondowsAuth; } set { this.isWondowsAuth = value; } } private string dbLogin; public string DbLogin { get { return this.dbLogin; } set { this.dbLogin = value; } } private string dbPassword; public string DbPassword { get { return this.dbPassword; } set { this.dbPassword = value; } } // network server private string netServer; public string NetServer { get { return this.netServer; } set { this.netServer = value; } } private uint netPort; public uint NetPort { get { return this.netPort; } set { this.netPort = value; } } public bool TestDbConnection() { SqlConnection connection; if (IsWindowAuth) { connection = new SqlConnection(GetConnectionString()); } else connection = new SqlConnection(GetConnectionString()); try { connection.Open(); connection.Close(); return true; } catch (Exception) { return false; } } public bool TestNetConnection() { try { IPAddress ipAddr = IPAddress.Parse(NetServer); IPEndPoint point = new IPEndPoint(ipAddr, (int)NetPort); TcpClient client = new TcpClient(); try { client.Connect(point); client.Close(); return true; } catch (Exception) { return false; } } catch (Exception) { TcpClient client = new TcpClient(NetServer, (int)NetPort); IPAddress ipAddr = Dns.GetHostAddresses(NetServer)[0]; try { client.Connect(ipAddr, (int)NetPort); client.Close(); return true; } catch (Exception) { return false; } } } public string GetConnectionString() { if (IsWindowAuth) { return "Data Source=" + DbServer + @"\" + DbObject + ";Initial Catalog=" + DbName + ";Integrated Security=True"; } else return "Data Source=" + DbServer + @"\" + DbObject + ";Initial Catalog=" + DbName + ";Persist Security Info=True;User ID=" + DbLogin + ";Password=" + DbPassword; } public bool Read() { try { if (!File.Exists(fileName)) return false; FileStream fStream = new FileStream(fileName, FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); object objSettings = (Settings)formatter.Deserialize(fStream); fStream.Close(); if (!(objSettings is Settings)) { File.Delete(fileName); return false; } Storage.Settings = (Settings)objSettings; return true; } catch (Exception) { if (File.Exists(fileName)) File.Delete(fileName); return false; } } public bool Write() { //if (!File.Exists(fileName)) File.Create(fileName); FileStream fStream = new FileStream(fileName, FileMode.OpenOrCreate); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fStream, this); fStream.Close(); Storage.Settings = this; return true; } } }
using System; using System.ComponentModel.DataAnnotations; using com.Sconit.Entity.VIEW; using com.Sconit.Entity.SYS; //TODO: Add other using statements here namespace com.Sconit.Entity.INV { public partial class ProductBarCode { #region Non O/R Mapping Properties #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace DataStrcture.LinkedList { // TODO impelment generic LinkedList<T> /// <summary> /// Linear Linked List /// </summary> public class LinkedList { public LinkedList() { // 成員初始化 Count = 0; First = default; Last = default; } /// <summary> /// 第一個Node /// </summary> public Node First { internal set; get; } /// <summary> /// 最後一個Node /// </summary> public Node Last { internal set; get; } /// <summary> /// LinkedList總數 /// </summary> public int Count { internal set; get; } /// <summary> /// 新增資料到LinkedList最末端 /// </summary> /// <param name="value">要新增的資料</param> public virtual Node Append(int value) { Node result = new Node() { Value = value }; // 效率比較 // iterative 40175ms // two pointer 9ms // Iterative O(n) //var current = First; //if (First == default) //{ // First = result; //} //else //{ // while (current.Next != default) // { // // 找到最後一個 最後一個node一定沒指東西 // current = current.Next; // } // // 最後一個node指向新增的node // current.Next = result; //} // NOTE 2個指標版本 比較不好懂 要下逐步去看 這個效率是O(1) // NOTE 關鍵點:觀察每個Node有誰Ref if (First == default) { First = result; } else { Last.Next = result; } Last = result; Count++; return result; } /// <summary> /// 將值插入指定node前 /// </summary> /// <param name="target">要插入的目標</param> /// <param name="value">值</param> public virtual Node InsertBefore(Node target, int value) { if (target == default) { return default; } // 存下previous的原因是 // 1 -> 3的linkedlist 如果要在1後面插入2 // 1 -> [toInsert] -> 3 // 原本1指向3要改為指向result // 而result則指向3 var previous = new Node(); var current = First; var result = new Node() { Value = value }; // 如果插在最前面 if (target == First) { First = result; } while (current != target) { previous = current; current = current.Next; } previous.Next = result; result.Next = current; Count++; return result; } /// <summary> /// 將值插入現有node後 /// </summary> /// <param name="target">要插入的目標</param> /// <param name="value">值</param> public virtual Node InsertAfter(Node target, int value) { if (target == default) { return default; } var current = First; var nextNode = new Node(); var result = new Node() { Value = value }; // 如果target跟Last相同 if (target == Last) { Last = result; } while (target != current) { current = current.Next; } // 在2後面插入 // 1 -> 2 -> 3 // 1 -> 2 -> result -> 3 // 所以存下current.Next (3) // 然後result的下一個就會是Next(3) // 再把current(2).Next 指向 result nextNode = current.Next; result.Next = nextNode; current.Next = result; Count++; return result; } /// <summary> /// 刪除指定Node /// </summary> /// <param name="target">指定要刪除的目標</param> public virtual void RemoveAt(Node target) { if (target == default) { return; } // 刪除第一個 if (target == First) { First = First.Next; } var current = First; var previous = new Node(); while (target != current) { previous = current; current = current.Next; } if (target == Last) { Last = previous; } // 1 > 2 > 3 > 4, removeAt (3) // current = 3 // 1 > 2 > 4, so 2 point to 4 previous.Next = current.Next; Count--; } /// <summary> /// 串接兩個LinkedList /// </summary> /// <param name="linkedList">要進行串接的LinkedList</param> public virtual void Concat(LinkedList linkedList) { if (linkedList == default) { return; } Last.Next = linkedList.First; Last = linkedList.Last; Count += linkedList.Count; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GravitacioJavito : MonoBehaviour { // Ha a játékos a platform oldalán van, nem tud mozogni private void OnTriggerEnter2D(Collider2D collision) { if(collision.gameObject.tag == "Player") { collision.gameObject.GetComponent<JatekosIranyitas>().enabled = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MyHotel.Business.Entity; using Obout.Ajax.UI.TreeView; using MyHotel.Business.Entity.Incomes; using MyHotel.Business.Entity.Booking; using MyHotel.Utils; namespace MyHotel.Business.WebControls.Incomes { public partial class IncomesControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } public void Refresh(DateTime startDate, DateTime endDate) { var allIncomes = IncomesController.GetPlanedIncomesData(startDate, endDate); this.TablePlanned.Rows.Clear(); this.TablePlanned.Rows.AddRange(getHeaderRow().ToArray()); int totalDays = (int)(endDate - startDate).TotalDays; totalDays = totalDays == 0 ? 1 : totalDays; List<string> cssStyleList = new List<string>() { "White", "Silver" }; int cssIdx = 0; foreach (var room in allIncomes) { this.TablePlanned.Rows.AddRange(getDataRow(room, totalDays, cssStyleList[cssIdx]).ToArray()); cssIdx = cssIdx == 0 ? 1 : 0; } this.TablePlanned.Rows.AddRange(getTotalRow(allIncomes, totalDays).ToArray()); } private List<TableRow> getHeaderRow() { List<TableRow> result = new List<TableRow>(); TableRow header = new TableRow(); header.Cells.Add(new TableCell() { Text = "Номер", RowSpan = 2, ColumnSpan = 2, CssClass = "incomesRoomHeaderColl" }); var statuses = Enum.GetValues(typeof(EBookingStatus)); header.Cells.Add(new TableCell() { Text = "Статус", ColumnSpan = statuses.Length, CssClass = "incomesStatusHeaderCell" }); TableRow subHeader = new TableRow(); foreach (var statusValue in statuses) { subHeader.Cells.Add(new TableCell() { Text = statusValue.ToString(), CssClass = "incomesSubHeaderColl" }); } header.Cells.Add(new TableCell() { Text = "Сума", RowSpan = 2, CssClass = "incomesTotalHeaderColl" }); result.Add(header); result.Add(subHeader); return result; } private List<TableRow> getDataRow(IncomeByRoomEntity incomeByRoomEntity, int daysInSelectedRange, string cssIdx) { List<TableRow> result = new List<TableRow>(); TableRow roomName = new TableRow(); roomName.Cells.Add(new TableCell() { Text = incomeByRoomEntity.RoomEntity.Name, RowSpan = 4, CssClass = "incomesRoomNameDataRow" + cssIdx }); result.Add(roomName); TableRow tableRowSum = new TableRow(); tableRowSum.Cells.Add(new TableCell() { Text = "∑", CssClass = "incomesRoomSumDataRow" + cssIdx }); TableRow tableRowDays = new TableRow(); tableRowDays.Cells.Add(new TableCell() { Text = "днів", CssClass = "incomesRoomDaysDataRow" + cssIdx }); TableRow tableRowPercent = new TableRow(); tableRowPercent.Cells.Add(new TableCell() { Text = "%", CssClass = "incomesRoomPercentDataRow" + cssIdx }); List<double> allSumByRow = new List<double>(); List<double> allDaysByRow = new List<double>(); List<double> allPercentByRow = new List<double>(); foreach (var valueByStatus in incomeByRoomEntity.IncomesByStatus) { allSumByRow.Add(valueByStatus.TotalSum); tableRowSum.Cells.Add(new TableCell() { Text = allSumByRow.Last().ToString(HelperCommon.DoubleFormat), CssClass = "incomesDataRow" + cssIdx }); allDaysByRow.Add(valueByStatus.TotalDays); tableRowDays.Cells.Add(new TableCell() { Text = allDaysByRow.Last().ToString(), CssClass = "incomesDataRow" + cssIdx }); allPercentByRow.Add(((double)(valueByStatus.TotalDays == 0 ? 0 : (valueByStatus.TotalDays * 100.00 / daysInSelectedRange)))); tableRowPercent.Cells.Add(new TableCell() { Text = allPercentByRow.Last().ToString(HelperCommon.DoubleFormat), CssClass = "incomesDataRow" + cssIdx }); } tableRowSum.Cells.Add(new TableCell() { Text = allSumByRow.Where(s => s > 0).Sum().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalDataRow" + cssIdx }); tableRowDays.Cells.Add(new TableCell() { Text = allDaysByRow.Where(s => s > 0).Sum().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalDataRow" + cssIdx }); tableRowPercent.Cells.Add(new TableCell() { Text = allPercentByRow.Where(s => s > 0).Sum().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalDataRow" + cssIdx }); result.Add(tableRowSum); result.Add(tableRowDays); result.Add(tableRowPercent); return result; } private List<TableRow> getTotalRow(List<IncomeByRoomEntity> allIncomes, int daysInSelectedRange) { List<TableRow> result = new List<TableRow>(); TableRow tableTotalRow = new TableRow(); tableTotalRow.Cells.Add(new TableCell() { Text = "Сума", RowSpan = 4, CssClass = "incomesTotalHeaderRow" }); result.Add(tableTotalRow); TableRow tableRowSum = new TableRow(); tableRowSum.Cells.Add(new TableCell() { Text = "∑", CssClass = "incomesTotalHeaderSubRow" }); TableRow tableRowDays = new TableRow(); tableRowDays.Cells.Add(new TableCell() { Text = "днів", CssClass = "incomesTotalHeaderSubRow" }); TableRow tableRowPercent = new TableRow(); tableRowPercent.Cells.Add(new TableCell() { Text = "%", CssClass = "incomesTotalHeaderSubRow" }); result.Add(tableRowSum); result.Add(tableRowDays); result.Add(tableRowPercent); List<double> allSumByRow = new List<double>(); List<double> allDaysByRow = new List<double>(); List<double> allPercentByRow = new List<double>(); foreach (var valueByStatus in allIncomes.SelectMany(s => s.IncomesByStatus).GroupBy(s => s.BookingStatus)) { allSumByRow.Add(valueByStatus.Sum(s=>s.TotalSum)); tableRowSum.Cells.Add(new TableCell() { Text = allSumByRow.Last().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalHeaderSubRow" }); allDaysByRow.Add(valueByStatus.Sum(s=>s.TotalDays)); tableRowDays.Cells.Add(new TableCell() { Text = allDaysByRow.Last().ToString(), CssClass = "incomesTotalHeaderSubRow" }); allPercentByRow.Add(valueByStatus.Average(s => (double)(s.TotalDays * 100.00 / daysInSelectedRange))); tableRowPercent.Cells.Add(new TableCell() { Text = allPercentByRow.Last().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalHeaderSubRow" }); } tableRowSum.Cells.Add(new TableCell() { Text = allSumByRow.Where(s => s > 0).Sum().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalHeaderSubRow" }); tableRowDays.Cells.Add(new TableCell() { Text = allDaysByRow.Where(s => s > 0).Sum().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalHeaderSubRow" }); tableRowPercent.Cells.Add(new TableCell() { Text = allPercentByRow.Where(s => s > 0).Sum().ToString(HelperCommon.DoubleFormat), CssClass = "incomesTotalHeaderSubRow" }); return result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class InventoryTextObject : MonoBehaviour { public List<string> textList; int currentEntry; Text inventoryText; // Use this for initialization public void AddTextList (List<string> list) { inventoryText = gameObject.transform.Find ("TextCanvas").Find ("Text").GetComponent<Text> (); this.textList = list; inventoryText.text = textList [0]; } // Update is called once per frame void Update () { if (Input.anyKeyDown) { NextEntry (); } } // Show next entry, and if you ran out of entries, destroy public void NextEntry() { currentEntry++; if (currentEntry < textList.Count) { inventoryText.text = textList [currentEntry]; } else { Destroy (gameObject); } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; public class SCSetEditor : EditorWindow { #region UI properties private Vector2 windowScrollPos; #endregion #region builder model private SCSet scSet; #endregion #region EditorWindow Lifecycle [MenuItem("Window/UniTunes/SoundCloud Set Editor")] private static void ShowWindow() { SCSetEditor win = EditorWindow.GetWindow<SCSetEditor>("SCSetEditor"); if(win != null) { win.title = "SoundCloud Set"; win.minSize = new Vector2(UniTunesConsts.MIN_WINDOW_WIDTH, UniTunesConsts.MIN_WINDOW_HEIGHT); } } /// <summary> /// Validates the Menu Item based on if the Editor is Playing. /// </summary> /// <returns><c>true</c>, if RT was validated, <c>false</c> otherwise.</returns> [MenuItem("Window/UniTunes/SoundCloud Set Editor", true)] private static bool ValidateRTD () { return !EditorApplication.isPlaying; } void OnDestroy() { EditorUtility.SetDirty(scSet); UniTunesTextureFactory.ClearTextures(); } private void OnGUI() { if(scSet == null) { LoadSetConfig(); } EditorGUILayout.BeginVertical(GUILayout.ExpandHeight(true), GUILayout.MaxHeight(2048)); { //render the default ui items SCUIAction uiAction = RenderSCAddTrack.RenderUI(scSet); switch(uiAction.Action) { case SCUIAction.ControlAction.Add: SoundCloudService.Instance.Resolve((string) uiAction.Data, OnResolveCallback, null); break; default: break; } //render the tracks windowScrollPos = EditorGUILayout.BeginScrollView(windowScrollPos); { SCUIAction trackUiAction = RenderSCTracks.RenderUI(scSet); switch(trackUiAction.Action) { case SCUIAction.ControlAction.Play: SoundCloudService.Instance.StreamTrack(((SCTrack) trackUiAction.Data)); break; case SCUIAction.ControlAction.Stop: SoundCloudService.Instance.StopPlayback(); break; case SCUIAction.ControlAction.Remove: Undo.RecordObject(scSet, "Remove track"); scSet.RemoveTrack((SCTrack) trackUiAction.Data); break; case SCUIAction.ControlAction.MoveUp: Undo.RecordObject(scSet, "Track order up"); scSet.Move((SCTrack) trackUiAction.Data, -1); break; case SCUIAction.ControlAction.MoveDown: Undo.RecordObject(scSet, "Track order down"); scSet.Move((SCTrack) trackUiAction.Data, 1); break; default: Repaint(); break; } } EditorGUILayout.EndScrollView(); GUILayout.FlexibleSpace(); //render save json, load json & loop playlist controls EditorGUILayout.BeginHorizontal(GUI.skin.box, GUILayout.ExpandWidth(true), GUILayout.MaxWidth(2048)); { //loop checkbox if(scSet != null) { bool loop = scSet.loopPlaylist; scSet.loopPlaylist = EditorGUILayout.Toggle(scSet.loopPlaylist, GUILayout.Width(20)); if(loop != scSet.loopPlaylist) { EditorUtility.SetDirty(scSet); } GUILayout.Label(UniTunesConsts.EN_LOOP_CHECKBOX, GUILayout.Width(80)); } //load json btn GUI.color = Color.yellow; if(GUILayout.Button(UniTunesConsts.EN_LOAD_EXISTING_JSON, GUILayout.Width(160), GUILayout.ExpandHeight(true))) { string selectedFile = string.Empty; if(scSet.tracks == null || scSet.tracks.Count == 0) { //skip confirmation and go right to selecting a json file selectedFile = EditorUtility.OpenFilePanel(UniTunesConsts.EN_JSON_FILE_SELECT_TITLE, Application.dataPath, "json"); } else { if(EditorUtility.DisplayDialog(UniTunesConsts.EN_JSON_LOAD_TITLE, UniTunesConsts.EN_JSON_LOAD_MSG, "Continue", "Cancel")) { selectedFile = EditorUtility.OpenFilePanel(UniTunesConsts.EN_JSON_FILE_SELECT_TITLE, Application.dataPath, "json"); } } if(!string.IsNullOrEmpty(selectedFile)) { Debug.Log("SCSetEditor - Loading .json file at: " + selectedFile); SCSetJsonModel loadedSet = UniTunesUtils.GetSetConfigFromJsonFile<SCSetJsonModel>(selectedFile); if(loadedSet.tracks == null || loadedSet.tracks.Count == 0) { //no track info, so we're not doing anything further EditorUtility.DisplayDialog(UniTunesConsts.EN_JSON_INVALID_TITLE, UniTunesConsts.EN_JSON_INVALID_MSG, "Ok"); } else { //tracks found, copy to a new SCSet instance SCSet set = ScriptableObject.CreateInstance<SCSet>(); set.tracks = loadedSet.tracks; set.loopPlaylist = loadedSet.loopPlaylist; ConfigHardSave(set); } } } GUI.color = Color.white; //save json btn GUI.color = Color.green; if(GUILayout.Button(UniTunesConsts.EN_BTN_SAVE_JSON, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true))) { if(EditorUtility.DisplayDialog(UniTunesConsts.EN_JSON_SAVED_TITLE, string.Format(UniTunesConsts.EN_JSON_SAVED_MSG, UniTunesUtils.GetSetJsonConfigPath()), "Ok", "Cancel")) { string fileContents = JsonFx.Json.JsonWriter.Serialize(new SCSetJsonModel(scSet)); UniTunesUtils.WriteStringToFile(UniTunesUtils.GetSetJsonConfigPath(), fileContents); } } GUI.color = Color.white; } EditorGUILayout.EndHorizontal(); } } #endregion private void OnResolveCallback(SCServiceResponse response) { if(response.isSuccess) { /* Debug.Log(string.Format("SCSetEditor DebugGUI.OnResolveCallback() - SUCCESS! {0}, streamable:{1}, from url:{2}", response.trackInfo.title, response.trackInfo.streamable, response.trackInfo.stream_url) ); */ Undo.RecordObject(scSet, "Track added"); if(!scSet.AddTrack(response.trackInfo)) { EditorUtility.DisplayDialog(UniTunesConsts.EN_TRACK_ALREADY_ADDED_TITLE, UniTunesConsts.EN_TRACK_ALREADY_ADDED_MSG, "Ok"); } } else { Debug.Log("SCSetEditor, resolve Error : " + response.errorMsg); EditorUtility.DisplayDialog(UniTunesConsts.EN_RESOLVE_FAIL_TITLE, UniTunesConsts.EN_RESOLVE_FAIL_MSG + "\n\n" + response.errorMsg, "Ok"); } } private void LoadSetConfig() { if(scSet == null) { scSet = (SCSet) Resources.LoadAssetAtPath(UniTunesConsts.SC_CONFIG_FILE, typeof(SCSet)); if(scSet == null) { scSet = ScriptableObject.CreateInstance<SCSet>(); AssetDatabase.CreateAsset(scSet, UniTunesConsts.SC_CONFIG_FILE); } } } private void ConfigHardSave(SCSet set) { AssetDatabase.DeleteAsset(UniTunesConsts.SC_CONFIG_FILE); AssetDatabase.CreateAsset(set, UniTunesConsts.SC_CONFIG_FILE); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DamageCalculatorFinal { class SwordDamage : WeaponDamage { private const int BASE_DAMAGE = 3; // Since these constants aren't going to be used by any other class it makes sense to keep them private. private const int FLAME_DAMAGE = 2; /// <summary> /// The constructor calculates damage based on default Magic and Flaming values and a starting 3d6 roll. /// </summary> /// <param name="startingRoll"></param> public SwordDamage(int startingRoll) : base(startingRoll) { // All the constructor needs to do is use the base keyword to call the superclass's constructor, using its startingRoll parameter as the argument. } /// <summary> /// Calculates the damage based on the current properties. /// </summary> protected override void CalculateDamage() { // All of the calculation is encapsulated inside the CalculateDamage method. It only depends on the get accessors for the Roll, Magic, and Flaming properties. decimal magicMultiplier = 1M; if (Magic) { magicMultiplier = 1.75M; } Damage = BASE_DAMAGE; Damage = (int)(Roll * magicMultiplier) + BASE_DAMAGE; if (Flaming) { Damage += FLAME_DAMAGE; } } } }