text
stringlengths
13
6.01M
using System; namespace Auth0.OidcClient { [Obsolete("It is recommended you leave Browser unassigned to accept the library default of AutoSelectBrowser.")] public class PlatformWebView : AutoSelectBrowser { } }
using System; using System.Collections.Generic; using System.Linq; namespace _05._Fashion_Boutique { class FashionBoutique { static void Main(string[] args) { int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray(); Stack<int> clothes = new Stack<int>(input); int rackCapacity = int.Parse(Console.ReadLine()); int usedRacks = 1; int currentSum = 0; if (clothes.Count == 0 || rackCapacity == 0) { Console.WriteLine(0); return; } while (clothes.Count > 0) { int currentValue = clothes.Peek(); if (currentValue + currentSum == rackCapacity) { clothes.Pop(); usedRacks++; currentSum = 0; if (clothes.Count == 0) { usedRacks--; } } else if (currentValue + currentSum < rackCapacity) { currentSum += clothes.Pop(); } else { usedRacks++; currentSum = clothes.Pop(); } } Console.WriteLine(usedRacks); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Hotel.Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Mvc.Rendering; using Hotel.Web.Areas.ModulAdministracija.ViewModels; using Hotel.Web.Helper; namespace Hotel.Web.Areas.ModulAdministracija.Controllers { [Area("ModulAdministracija")] public class PogodnostController : Controller { MojContext db = new MojContext(); public IActionResult Index() { return View(); } public IActionResult Prikazi() { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } List<Pogodnost> pogodnosti = new List<Pogodnost>(); pogodnosti = db.Pogodnost.ToList(); ViewData["pogodnosti"] = pogodnosti; return View(); } public IActionResult Dodaj() { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } NovaPogodnostVM Model = new NovaPogodnostVM(); return View(Model); } public IActionResult Snimi(NovaPogodnostVM temp) { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } if (!ModelState.IsValid) { //return View("Uredi", temp.Id); return View("Dodaj", temp); } Pogodnost p; if (temp.Id == 0) { p = new Pogodnost(); db.Pogodnost.Add(p); } else { p = db.Pogodnost.Find(temp.Id); } p.Opis = temp.Opis; db.SaveChanges(); return RedirectToAction("Prikazi"); } public IActionResult Obrisi(int id) { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } Pogodnost p = db.Pogodnost.Find(id); db.Pogodnost.Remove(p); db.SaveChanges(); return RedirectToAction("Prikazi"); } public IActionResult Uredi(int id) { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } NovaPogodnostVM Model = new NovaPogodnostVM(); Pogodnost p = new Pogodnost(); p = db.Pogodnost.Find(id); Model.Id = p.Id; Model.Opis = p.Opis; return View(Model); } public IActionResult ProvjeriDuplikate(string Opis, int Id) { if (db.Pogodnost.Any(x => x.Opis == Opis && x.Id != Id)) return Json("Pogodnost je već dodana!"); return Json(true); } //tabela "PogodnostiSmjestaja" public IActionResult PrikaziPogodnostiZaSmjestaj(int id) { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } ViewData["smjestajID"] = id; List<PogodnostiSmjestaja> p = new List<PogodnostiSmjestaja>(); p = db.PogodnostiSmjestaja.Include(x => x.Smjestaj).Include(x => x.Pogodnost). Where(x => x.SmjestajId == id).ToList(); ViewData["p"] = p; return View(); } public IActionResult ObrisiPogodnostZaSmjestaj(int id) { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } PogodnostiSmjestaja p = new PogodnostiSmjestaja(); p = db.PogodnostiSmjestaja.Find(id); int smjestajID = new int(); smjestajID = p.SmjestajId; db.PogodnostiSmjestaja.Remove(p); db.SaveChanges(); return RedirectToAction("PrikaziPogodnostiZaSmjestaj",new {id= smjestajID }); } public IActionResult DodajPogodnostZaSmjestaj(int smjestajID) { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } NovaPogodnostZaSmjestajVM Model = new NovaPogodnostZaSmjestajVM(); Model.smjestajID = smjestajID; NapuniCmb(Model); return View(Model); } void NapuniCmb(NovaPogodnostZaSmjestajVM p) { List<SelectListItem> _stavke = new List<SelectListItem>(); _stavke.Add(new SelectListItem() { Value = null, Text = "Odaberite pogodnost" }); _stavke.AddRange(db.Pogodnost.Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Opis })); p._stavke = _stavke; } public IActionResult ProvjeriStavkuPogodnosti(int? StavkaPogodnosti, int smjestajID) { if (StavkaPogodnosti == null) return Json("Odaberite pogodnost!"); if(db.PogodnostiSmjestaja.Any(x=>x.SmjestajId==smjestajID && x.PogodnostId==StavkaPogodnosti)) return Json("Pogodnost je već odabrana!"); return Json(true); } public IActionResult SnimiPogodnostZaSmjestaj(NovaPogodnostZaSmjestajVM p) { Zaposlenik k = HttpContext.GetLogiraniKorisnik(); if (k == null || k.isAdministrator == false) { TempData["error_poruka"] = "Nemate pravo pristupa."; return RedirectToAction("Index", "Autentifikacija", new { area = " " }); } if (!ModelState.IsValid) { NapuniCmb(p); return View("DodajPogodnostZaSmjestaj", p); } PogodnostiSmjestaja ps = new PogodnostiSmjestaja(); ps.PogodnostId = p.StavkaPogodnosti; ps.SmjestajId = p.smjestajID; db.PogodnostiSmjestaja.Add(ps); db.SaveChanges(); return RedirectToAction("PrikaziPogodnostiZaSmjestaj",new {id=p.smjestajID }); } } // }
namespace FileDownloader { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; public class RemoteFiles { private static RemoteFiles _instance; private static WebClient _webClient; public static RemoteFiles Instance => _instance ??= new RemoteFiles(); public void Download(DownloadArgs downloadArgs) { ValidateDownloadArgs(downloadArgs); var files = GetSourceAndDestination(downloadArgs); var postFetchContentOverride = downloadArgs.PostFetchContentOverride; foreach (var file in files) { var (source, destination) = (file.source, file.destination); if (downloadArgs.PostFetchContentOverride is null) DownloadFile(source, destination); else { var contents = ReadFileAsText(source.ToString()); ApplyTextOverrideAndSaveFile(destination, contents, postFetchContentOverride); } if (downloadArgs.ProgressTracker != null) downloadArgs.ProgressTracker((source.ToString(), destination)); } List<(Uri source, string destination)> GetSourceAndDestination(DownloadArgs _args) { List<(Uri _source, string _destination)> result = _args.MaintainSameDirectoryStructure switch { true => _args.Files.Select(x => (x.Source, GetDestinationFilename(x.Source, _args.RootFolderForDownload))).ToList(), false => _args.Files }; return result; string GetDestinationFilename(Uri _source, string _rootFoldername) { var fullPathExcludingHostname = _source.PathAndQuery; var result = $@"{_rootFoldername}\{fullPathExcludingHostname}"; return result; } } void DownloadFile(Uri _source, string _destination) { var dir = Path.GetDirectoryName(_destination); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); _webClientInstance.DownloadFile(_source, _destination); } void ApplyTextOverrideAndSaveFile(string _destination, string _contents, Func<string, string> func) { var overrideContents = func(_contents); var dir = Path.GetDirectoryName(_destination); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); File.WriteAllText(_destination, overrideContents); } } private void ValidateDownloadArgs(DownloadArgs downloadArgs) { Contracts.NullCheck(downloadArgs.Files); if (downloadArgs.MaintainSameDirectoryStructure) { Contracts.NullCheck(downloadArgs.RootFolderForDownload); } else { foreach (var file in downloadArgs.Files) { Contracts.NullCheck(file.Source); Contracts.NullCheck(file.Destination); } } } public string ReadFileAsText(string address) { var contents = _webClientInstance.DownloadString(address); return contents; } private static WebClient _webClientInstance => _webClient ??= new WebClient(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Inventory/Item")] public class Item : ScriptableObject { public string itemName = "New Item"; public string itemDescription = "New Description"; public string itemType = "Object"; public Sprite inventoryImage; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Windows.Forms; using System.Data.SqlClient; using ENTITY; using Openmiracle.BLL; using Openmiracle.DAL; namespace Openmiracle.BLL { public class DesignationBll { DesignationSP spDesignation = new DesignationSP(); public List<DataTable> DesignationViewAll() { try { return spDesignation.DesignationViewAll(); } catch (Exception) { throw; } } public bool DesignationDelete(decimal DesignationId) { bool isResult = false; try { isResult = spDesignation.DesignationDelete(DesignationId); } catch (Exception) { throw; } return isResult; } public List<DataTable> DesignationViewForGridFill() { try { return spDesignation.DesignationViewForGridFill(); } catch (Exception) { throw; } } public DataTable DesignationSearch(string strDesignation) { try { return spDesignation.DesignationSearch(strDesignation); } catch (Exception) { throw; } } public DesignationInfo DesignationView(decimal designationId) { try { return spDesignation.DesignationView(designationId); } catch (Exception) { throw; } } public bool DesignationCheckExistanceOfName(string strDesignation, decimal decDesignationId) { bool isResult = false; try { isResult = spDesignation.DesignationCheckExistanceOfName(strDesignation, decDesignationId); } catch (Exception) { throw; } return isResult; } public decimal DesignationAddWithReturnIdentity(DesignationInfo designationinfo) { decimal decId = 0; try { decId = spDesignation.DesignationAddWithReturnIdentity(designationinfo); } catch (Exception ex) { MessageBox.Show("BR1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public bool DesignationEdit(DesignationInfo designationinfo) { bool isStatus = false; try { isStatus = spDesignation.DesignationEdit(designationinfo); } catch (Exception) { } return isStatus; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Odbc; namespace SistemaPreguntas { public class ConexionBD { //Aqui van los atributos de la clase public OdbcConnection con { get; set; } public ConexionBD() { //Abrir el web config para sacar el string de conexion System.Configuration.Configuration webConfig; webConfig = System.Web.Configuration .WebConfigurationManager .OpenWebConfiguration("/SistemaPreguntas"); //<-- hay que decirle donde se encuentra el web.config //Sacar el string de conexion del web config System.Configuration.ConnectionStringSettings connectionString; connectionString = webConfig .ConnectionStrings .ConnectionStrings["BDPreguntas"]; con = new OdbcConnection(connectionString.ToString()); con.Open(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using QTHT.BusinesLogic; using CGCN.DataAccess; using CGCN.Configure.Interface; namespace QLBH { public partial class frmDangNhap : Form { private logBL _ctrlog = new logBL(); private InputValidation.Validation _validation = new InputValidation.Validation(); #region Method private void DangNhap() { if (txtAccount.Text.Trim().Equals("") == true) { MessageBox.Show("Tài khoản không được để trắng.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtAccount.Focus(); return; } if (txtPass.Text.Trim().Equals("") == true) { MessageBox.Show("Mật khẩu không được để trắng.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtPass.Focus(); return; } string shashPass = ""; shashPass = _validation.EncryptPassword(txtAccount.Text.Trim(), txtPass.Text.Trim()); nhanvienBL ctr = new nhanvienBL(); if (ctr.DangNhap(txtAccount.Text.Trim(), shashPass) == true) { try { Data.iduse = ctr.GetIDNhanVienByAccount(txtAccount.Text.Trim()); Data.use = txtAccount.Text.Trim(); this.Hide(); _ctrlog.Append(Data.use, "Đăng nhập hệ thống."); frmMain frm = new frmMain(); frm.ShowDialog(); if (frm.isActiveclose == false) { this.Show(); } else { this.Dispose(); } } catch (Exception e) { this.Dispose(); } } else { MessageBox.Show("Đăng nhập không thành công.\nVui lòng kiểm tra lại tài khoản và mật khẩu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtAccount.Focus(); return; } } #endregion public frmDangNhap() { InitializeComponent(); } private void btnDangNhap_Click(object sender, EventArgs e) { DangNhap(); } private void btnExit_Click(object sender, EventArgs e) { this.Dispose(); } private void btnConfig_Click(object sender, EventArgs e) { frmConfigure frm = new frmConfigure(); frm.ShowDialog(); } private void frmDangNhap_Load(object sender, EventArgs e) { txtAccount.Focus(); } private void txtPass_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { btnDangNhap_Click(sender, e); } } } }
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Tizen.NUI; using Tizen.NUI.BaseComponents; using Tizen.NUI.Components; namespace NUIGridLayout { class Program : NUIApplication { /// <summary> /// View representing the root for all other views /// </summary> private View RootView; /// <summary> /// View covering upper part of the screen /// </summary> private View TopView; /// <summary> /// View covering bottom part of the screen /// </summary> private View ButtonView; /// <summary> /// Buttons to change number of columns placed at the bottom of the screen /// </summary> private Button Button1, Button2; /// <summary> /// Items in view count /// </summary> private static int ItemsCnt = 55; /// <summary> /// Items in one column count /// </summary> private static int ColumnCnt = 6; /// <summary> /// Width/Height of the single item /// </summary> private static int ItemSide = 55; /// <summary> /// Right/Left/Top/Bottom single item margin /// </summary> private static ushort ItemMargin = 10; /// <summary> /// Custom style for a button /// <summary> ButtonStyle Style = new ButtonStyle { Size = new Size(300, 100), CornerRadius = 28.0f, BackgroundColor = new Selector<Color>() { Other = new Color(0.25f, 0.25f, 0.25f, 1.0f), Disabled = new Color(0.8f, 0.8f, 0.8f, 1.0f), }, }; /// <summary> /// Overridden method that is called after app launch /// <summary> protected override void OnCreate() { base.OnCreate(); Initialize(); } /// <summary> /// Initialize all views, layout and buttons /// </summary> void Initialize() { InitViews(); InitGrid(); InitButtons(); } /// <summary> /// Initialize all views /// </summary> private void InitViews() { RootView = new View() { Layout = new LinearLayout() { LinearOrientation = LinearLayout.Orientation.Vertical, }, WidthSpecification = LayoutParamPolicies.MatchParent, HeightSpecification = LayoutParamPolicies.MatchParent, }; TopView = new View() { Layout = new GridLayout() { Columns = ColumnCnt, }, WidthSpecification = LayoutParamPolicies.MatchParent, HeightSpecification = LayoutParamPolicies.MatchParent, Padding = new Extents(20, 20, 20, 20), }; ButtonView = new View() { WidthSpecification = LayoutParamPolicies.MatchParent, HeightSpecification = LayoutParamPolicies.WrapContent, Padding = new Extents(20, 20, 20, 20), }; RootView.Add(TopView); RootView.Add(ButtonView); Window.Instance.Add(RootView); Window.Instance.KeyEvent += OnKeyEvent; } /// <summary> /// Initialize Grid Layout with text labels /// </summary> private void InitGrid() { for (int i = 0; i < ItemsCnt; i++) { TextLabel t = new TextLabel(); t.Margin = new Extents(ItemMargin, ItemMargin, ItemMargin, ItemMargin); t.Text = "X"; t.HorizontalAlignment = HorizontalAlignment.Center; t.VerticalAlignment = VerticalAlignment.Center; t.Size2D = new Size2D(ItemSide, ItemSide); t.BackgroundColor = new Color(0.8f, 0.2f, 0.2f, 1.0f); TopView.Add(t); } } /// <summary> /// Initialize Buttons used in the application /// </summary> private void InitButtons() { LinearLayout ButtonLayout = new LinearLayout(); ButtonLayout.LinearOrientation = LinearLayout.Orientation.Horizontal; ButtonView.Layout = ButtonLayout; Button1 = new Button(Style) { WidthSpecification = LayoutParamPolicies.MatchParent, HeightSpecification = LayoutParamPolicies.WrapContent, Text = "Remove", TextColor = Color.White, TextAlignment = HorizontalAlignment.Center, Margin = new Extents(10, 10, 10, 10), }; Button2 = new Button(Style) { WidthSpecification = LayoutParamPolicies.MatchParent, HeightSpecification = LayoutParamPolicies.WrapContent, Text = "Add", TextColor = Color.White, TextAlignment = HorizontalAlignment.Center, Margin = new Extents(10, 10, 10, 10), }; ButtonView.Add(Button1); ButtonView.Add(Button2); Button1.Clicked += Button1Clicked; Button2.Clicked += Button2Clicked; } /// <summary> /// The method called when the left button is clicked /// It dos not allow to go outside the window boundaries - disables the left button /// </summary> /// <param name="sender">Button instance</param> /// <param name="e">Event arguments</param> private void Button1Clicked(object sender, ClickedEventArgs e) { ColumnCnt = ColumnCnt - 1 > 0 ? ColumnCnt - 1 : 1; var MyGridLayout = TopView.Layout as GridLayout; MyGridLayout.Columns = ColumnCnt; if (!Button2.IsEnabled) { Button2.IsEnabled = true; } var RowCnt = Math.Ceiling((double)(ItemsCnt) / (MyGridLayout.Columns - 1)); int NextItemsHeight = (int)((ItemSide + 2 * ItemMargin) * RowCnt + TopView.Padding.Top + TopView.Padding.Bottom); if (NextItemsHeight > TopView.SizeHeight) { Button1.IsEnabled = false; } } /// <summary> /// The method called when the right button is clicked. /// It dos not allow to go outside the window boundaries - disables the right button /// </summary> /// <param name="sender">Button instance</param> /// <param name="e">Event arguments</param> private void Button2Clicked(object sender, ClickedEventArgs e) { ++ColumnCnt; var MyGridLayout = TopView.Layout as GridLayout; MyGridLayout.Columns = ColumnCnt; if (!Button1.IsEnabled) { Button1.IsEnabled = true; } int NextItemsWidth = (int)((ItemSide + 2 * ItemMargin) * (ColumnCnt + 1) + TopView.Padding.Start + TopView.Padding.End); if (NextItemsWidth > TopView.SizeWidth) { Button2.IsEnabled = false; } } /// <summary> /// Method which is called when key event happens /// </summary> /// <param name="sender">Window instance</param> /// <param name="e">Event arguments</param> public void OnKeyEvent(object sender, Window.KeyEventArgs e) { if (e.Key.State == Key.StateType.Down && (e.Key.KeyPressedName == "XF86Back" || e.Key.KeyPressedName == "Escape")) { Exit(); } } static void Main(string[] args) { var app = new Program(); app.Run(args); app.Dispose(); } } }
using CustomerManagement.Domain.Interfaces; using CustomerManagement.Domain.Entities; using CustomerManagement.Infrastructure.Data.Context; using System.Collections.Generic; using System; using System.Linq; namespace CustomerManagement.Infrastructure.Data.Repositories { public class EnderecoRepository : GenericRepository<Endereco>, IEnderecoRepository { public EnderecoRepository(CMContext context) : base(context) { } public ICollection<Endereco> GetAllByClienteId(Guid id) { return Context.Enderecos.Where(x => x.ClienteId.Equals(id)).ToList(); } } }
using LojaYgor3.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; namespace LojaYgor3.Controllers { public class ClienteController : Controller { LojaContext contexto = new LojaContext(); // GET: Cliente public ActionResult Index() { return View(contexto.Clientes.ToList()); } // GET: Cliente/Details/5 public ActionResult Detalha(int id) { return GetCliente(id); } // GET: Cliente/Create public ActionResult Adiciona() { return View(); } // POST: Cliente/Create [HttpPost] public ActionResult Adiciona(Cliente cliente) { try { // TODO: Add insert logic here if (ModelState.IsValid) { contexto.Clientes.Add(cliente); contexto.SaveChanges(); return RedirectToAction("Index"); } return View(); } catch { return View(); } } // GET: Cliente/Edit/5 public ActionResult Atualiza(int id) { return GetCliente(id); } // POST: Cliente/Edit/5 [HttpPost] public ActionResult Atualiza(int id, Cliente cliente) { try { // TODO: Add update logic here if (ModelState.IsValid) { contexto.Entry(cliente).State = EntityState.Modified; contexto.SaveChanges(); return RedirectToAction("Index"); } return View(); } catch { return View(); } } // GET: Cliente/Delete/5 public ActionResult Remove(int id) { return GetCliente(id); } // POST: Cliente/Delete/5 [HttpPost] public ActionResult Remove(int id, Cliente cliente) { try { // TODO: Add delete logic here cliente = contexto.Clientes.Find(id); contexto.Clientes.Remove(cliente); contexto.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } private ActionResult GetCliente(int id) { var cliente = (from c in contexto.Clientes where c.Id == id select c).First(); return View(cliente); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PayRoll.BLL { public class ChangeNameTransaction:ChangeEmployeeTransaction { private readonly string name; public ChangeNameTransaction(int empId, string name, PayrollDatabase database):base(empId, database) { this.name = name; } protected override void Change(Employee emp) { emp.Name = name; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Payroll.Models { public class Project: Basic { [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "Company")] public Guid CompanyId { get; set; } [ForeignKey("CompanyId")] public virtual Company Company { get; set; } [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] [Display(ResourceType = typeof(Resource), Name = "Department")] public Guid DepartmentId { get; set; } [ForeignKey("DepartmentId")] public virtual Department Department { get; set; } [Display(ResourceType = typeof(Resource), Name = "Workplace")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public Guid WorkplaceId { get; set; } [ForeignKey("WorkplaceId")] public virtual Workplace Workplace { get; set; } [Display(ResourceType =typeof(Resource), Name ="Responsible")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public Guid ResponsibleId { get; set;} [ForeignKey("ResponsibleId")] public virtual Employee Responsible { get; set; } [Display(ResourceType =typeof(Resource), Name ="Description")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public string Description { get; set; } [Display(ResourceType = typeof(Resource), Name = "StartDate")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public DateTime Start { get; set; } [Display(ResourceType = typeof(Resource), Name = "EndDate")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public DateTime End { get; set; } public virtual IEnumerable<ProjectEmployee> Employees { get; set; } } }
using GameStore.Domain.Infrastructure; using GameStore.Domain.Model; using GameStore.WebUI.Helper; using GameStore.WebUI.Models; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace GameStore.WebUI.Controllers { [Authorize] public class ShoppingCartController : Controller { // GET: ShoppingCart public ActionResult Index() { ShoppingCart cart = (ShoppingCart)Session["ShoppingCart"]; if (cart == null) { cart = new ShoppingCart(); Session["ShoppingCart"] = cart; } return View(cart); } public ActionResult CreateOrUpdate(CartViewModel value) { ShoppingCart cart = (ShoppingCart)Session["ShoppingCart"]; if (cart == null) { cart = new ShoppingCart(); Session["ShoppingCart"] = cart; } using (GameStoreDBContext context = new GameStoreDBContext()) { Product product = context.Products.Find(value.Id); if (product != null) { if (value.Quantity == 0) { cart.AddItem(value.Id, product); } else { cart.SetItemQuantity(value.Id, value.Quantity, product); } } } Session["CartCount"] = cart.GetItems().Count(); return View("Index", cart); } public ActionResult Checkout() { CheckoutViewModel checkout = new CheckoutViewModel(); checkout.FullName = "Rong Zhuang"; checkout.Address = "1st Jackson Ave,Chicago,IL"; checkout.City = "Chicago"; checkout.State = "IL"; checkout.Zip = "60606"; ViewBag.States = State.List(); return View(checkout); } public ActionResult PlaceOrder(CheckoutViewModel value) { ShoppingCart cart = (ShoppingCart)Session["ShoppingCart"]; if (cart == null) { ViewBag.Message = "Your cart is empty!"; return View("Index", "ShoppingCart"); } if (!ModelState.IsValid) { ViewBag.Message = "Please provide valid shipping address!"; return View("Checkout", "ShoppingCart"); } Session["Checkout"] = value; //Assign the values for the properties we need to pass to the service String AppId = ConfigurationHelper.GetAppId2(); String SharedKey = ConfigurationHelper.GetSharedKey2(); String AppTransId = "20"; String AppTransAmount = cart.GetTotalValue().ToString(); // Hash the values so the server can verify the values are original String hash = HttpUtility.UrlEncode(CreditAuthorizationClient.GenerateClientRequestHash(SharedKey, AppId, AppTransId, AppTransAmount)); //Create the URL and concatenate the Query String values String url = "http://ectweb2.cs.depaul.edu/ECTCreditGateway/Authorize.aspx"; url = url + "?AppId=" + AppId; url = url + "&TransId=" + AppTransId; url = url + "&AppTransAmount=" + AppTransAmount; url = url + "&AppHash=" + hash; return Redirect(url); } public ActionResult ProcessCreditResponse(String TransId, String TransAmount, String StatusCode, String AppHash) { String AppId = ConfigurationHelper.GetAppId2(); String SharedKey = ConfigurationHelper.GetSharedKey2(); if (CreditAuthorizationClient.VerifyServerResponseHash(AppHash, SharedKey, AppId, TransId, TransAmount, StatusCode)) { switch (StatusCode) { case ("A"): ViewBag.TransactionStatus = "Transaction Approved! Your order has been created!"; break; case ("D"): ViewBag.TransactionStatus = "Transaction Denied!"; break; case ("C"): ViewBag.TransactionStatus = "Transaction Cancelled!"; break; } } else { ViewBag.TransactionStatus = "Hash Verification failed... something went wrong."; } OrderViewModel model = new OrderViewModel(); if (StatusCode.Equals("A")) { ShoppingCart cart = (ShoppingCart)Session["ShoppingCart"]; CheckoutViewModel value = (CheckoutViewModel)Session["Checkout"]; if (value != null) { try { using (GameStoreDBContext context = new GameStoreDBContext()) { Order newOrder = context.Orders.Create(); newOrder.FullName = value.FullName; newOrder.Address = value.Address; newOrder.City = value.City; newOrder.State = value.State; newOrder.Zip = value.Zip; newOrder.DeliveryDate = DateTime.Now.AddDays(14); newOrder.ConfirmationNumber = DateTime.Now.ToString("yyyyMMddHHmmss"); newOrder.UserId = User.Identity.GetUserId(); context.Orders.Add(newOrder); cart.GetItems().ForEach(c => context.OrderItems.Add(new OrderItem { OrderId = newOrder.OrderId, ProductId = c.GetItemId(), Quantity = c.Quantity })); context.SaveChanges(); System.Web.HttpContext.Current.Cache.Remove("OrderList"); Session["ShoppingCart"] = null; Session["CartCount"] = 0; Session["OrderCount"] = (int)Session["OrderCount"] + 1; var order = from o in context.Orders join u in context.Users on o.UserId equals u.Id where o.OrderId == newOrder.OrderId select new { o.OrderId, o.UserId, u.UserName, o.FullName, o.Address, o.City, o.State, o.Zip, o.ConfirmationNumber, o.DeliveryDate }; var ord = order.FirstOrDefault(); model = new OrderViewModel { OrderId = ord.OrderId, UserId = ord.UserId, UserName = ord.UserName, FullName = ord.FullName, Address = ord.Address, City = ord.City, State = ord.State, Zip = ord.Zip, ConfirmationNumber = ord.ConfirmationNumber, DeliveryDate = ord.DeliveryDate }; var orderitems = from i in context.OrderItems join p in context.Products on i.ProductId equals p.ProductId join c in context.Categories on p.CategoryId equals c.CategoryId where i.OrderId == newOrder.OrderId select new { i.OrderItemId, i.OrderId, i.ProductId, p.ProductName, p.CategoryId, c.CategoryName, p.Price, p.Image, p.Condition, p.Discount, i.Quantity }; model.Items = orderitems.Select(o => new OrderItemViewModel { OrderItemId = o.OrderItemId, OrderId = o.OrderId, ProductId = o.ProductId, ProductName = o.ProductName, CategoryId = o.CategoryId, CategoryName = o.CategoryName, Price = o.Price, Image = o.Image, Condition = o.Condition, Discount = o.Discount, Quantity = o.Quantity }).ToList(); } } catch (Exception ex) { ViewBag.Message = "Error Occurs:" + ex.Message; } } } return View("PlaceOrder", model); } } }
using UnityEngine; namespace LevelGenerator { public class mbLevelGenerator : MonoBehaviour { public Texture2D mapInput; public GameObject groundPrefab; public ColorToPrefab[] colorMappings; void Start() { Debug.Log(string.Format("Das Level hat eine Dimension von x:{0} und y:{1}", mapInput.width, mapInput.height)); GenerateLevel(); } #region Methods // Loop that goes through the width and height of the mapInput and uses the GenerateTile method with the looped x and y values. void GenerateLevel() { GenerateGround(mapInput.width, mapInput.height, groundPrefab); for (int x = 0; x < mapInput.width; x++) { for (int y = 0; y < mapInput.height; y++) { GenerateTile(x, y); } } } void GenerateGround(int width, int height, GameObject ground) { GameObject groundplane = Instantiate(ground, Vector3.zero, Quaternion.identity, transform); groundplane.transform.localScale = new Vector3(width, 1, height); } // Gets the Color information of each pixel void GenerateTile(int x, int y) { Color pixelColor = mapInput.GetPixel(x, y); if (pixelColor.a == 0) return; Debug.Log(pixelColor); foreach (ColorToPrefab colorMapping in colorMappings) { Debug.Log("For Each funktioniert"); if (colorMapping.color.Equals(pixelColor)) { Debug.Log("Instantiate"); Vector3 position = new Vector3(x, 1, y); Instantiate(colorMapping.prefab, position, Quaternion.identity, transform); } } } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Team3ADProject.Code; using Team3ADProject.Model; namespace Team3ADProject.Protected { public partial class PendingPODetails : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int id = Convert.ToInt32(Request.QueryString["id"]); Session["po"] = id; Label14.Visible = false; if (!IsPostBack) { GenerateGrid(); Label14.Visible = false; } } protected void GenerateGrid() { int id = (int)Session["po"]; GridView1.DataSource = BusinessLogic.getpurchaseorderdetail(id); GridView1.DataBind(); purchase_order p = BusinessLogic.getpurchaseorder(id); supplier s = BusinessLogic.getSupplierNameforPurchaseorder(id); employee d = BusinessLogic.GetEmployee(p.employee_id); Label5.Text = id.ToString(); Label4.Text = s.supplier_name; Label7.Text = s.supplier_id; Label9.Text = p.purchase_order_date.ToString("dd-MM-yyyy"); Label11.Text = p.purchase_order_status; Label13.Text = d.employee_name; } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { int r = GridView1.Rows.Count; for (int i = 0; i < r; i++) { System.Web.UI.WebControls.Button b = (System.Web.UI.WebControls.Button)GridView1.Rows[i].FindControl("AcceptItem"); System.Web.UI.WebControls.TextBox t1 = (System.Web.UI.WebControls.TextBox)GridView1.Rows[i].FindControl("TextBox1"); System.Web.UI.WebControls.TextBox t2 = (System.Web.UI.WebControls.TextBox)GridView1.Rows[i].FindControl("TextBox2"); HiddenField hd2 = (HiddenField)GridView1.Rows[i].FindControl("HiddenField2"); string s = hd2.Value; if(s == "Accepted") { b.Enabled = false; b.CssClass = "btn btn-success disabled"; b.Text = "Accepted"; t1.ReadOnly = true; t1.BackColor = Color.Silver; t2.ReadOnly = true; t2.BackColor = Color.Silver; } else { b.Enabled = true; b.CssClass = "btn btn-success"; b.Text = "Accept Item"; t1.ReadOnly = false; t1.BackColor = Color.White; t2.ReadOnly = false; t2.BackColor = Color.White; } } } protected void AcceptItem_Click(object sender, EventArgs e) { //if(!(Page.IsValid)) //{ int po_id = (int)Session["po"]; System.Web.UI.WebControls.Button b = (System.Web.UI.WebControls.Button)sender; System.Web.UI.WebControls.TextBox t1 = (System.Web.UI.WebControls.TextBox)b.FindControl("TextBox1"); System.Web.UI.WebControls.TextBox t2 = (System.Web.UI.WebControls.TextBox)b.FindControl("TextBox2"); HiddenField hd1 = (HiddenField)b.FindControl("HiddenField1"); HiddenField hd2 = (HiddenField)b.FindControl("HiddenField3"); int order_quantity = Convert.ToInt32(hd2.Value); string item = hd1.Value; int accept_quantity = Convert.ToInt32(t1.Text); string remark = t2.Text; if (accept_quantity == 0) { Label14.Visible = true; Label14.Text = "Received quantity should be greater than 0"; } else { Label14.Visible = false; BusinessLogic.acceptitemfromsupplier(po_id, item, accept_quantity, remark); GenerateGrid(); } //} } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("~/Protected/ViewPOHistory.aspx"); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using RestaurantApp.Core; using System.Data.Entity; using Moq; using AutoFixture; namespace RestaurantApp.Test.InfrastructureTest { [TestClass] public class UserRepositoryTest { [TestMethod] public void CreateItem_SaveItem_ViaContext() { var mockSet = new Mock<DbSet<User>>(); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.User).Returns(mockSet.Object); var repo = new RestaurantApp.Infrastructure.Repositories.UserRepository(mockContext.Object); var fixture = new Fixture(); var testObject = fixture.Build<User>().Without(c => c.Id).Create(); repo.Update(testObject); //Assert mockSet.Verify(m => m.Add(It.Is<User>(c => c.Name == testObject.Name)), Times.Once); mockContext.Verify(m => m.SaveChanges(), Times.Once); } [TestMethod] public void Update() { var fixture = new Fixture(); var testObject = fixture.Build<User>().With(c => c.Id, 1).Create<User>(); var mockSet = new Mock<DbSet<User>>(); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.User).Returns(mockSet.Object); mockContext.Setup(m => m.SetModified(It.IsAny<User>())); var repo = new RestaurantApp.Infrastructure.Repositories.UserRepository(mockContext.Object); //Act repo.Update(testObject); //Assert mockContext.Verify(m => m.SetModified(It.IsAny<User>()), Times.Once); mockContext.Verify(m => m.SaveChanges(), Times.Once); } [TestMethod] public void RemoveItemByIdWithValidData() { var fixture = new Fixture(); var testObject = fixture.Build<User>().Create<User>(); var mockSet = new Mock<DbSet<User>>(); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.Set<User>()).Returns(mockSet.Object); ; mockSet.Setup(m => m.Find(It.IsAny<int>())).Returns(testObject); mockSet.Setup(m => m.Remove(It.IsAny<User>())).Returns(testObject); var repo = new RestaurantApp.Infrastructure.Repositories.UserRepository(mockContext.Object); //act var result = repo.Remove(1); //Assert Assert.AreEqual(true, result); mockContext.Verify(m => m.Set<User>()); mockSet.Verify(m => m.Find(It.IsAny<int>())); mockSet.Verify(m => m.Remove(It.IsAny<User>()), Times.Once); mockContext.Verify(m => m.SaveChanges(), Times.Once); } [TestMethod] public void GetUsers_WithPaging_OrderByName() { var fixture = new Fixture(); var data = new List<User>() { fixture.Build<User>().With(c=>c.Name,"Miley").Create(), fixture.Build<User>().With(c=>c.Name,"Isabella").Create() }.AsQueryable(); var mockDbSet = Helper.CreateDbSetMock(data); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.User).Returns(mockDbSet.Object); var repo = new RestaurantApp.Infrastructure.Repositories.UserRepository(mockContext.Object); List<User> result = repo.GetUsers(0, 2).ToList(); //assert Assert.AreEqual(2, result.Count()); Assert.AreEqual("Isabella", result[0].Name); Assert.AreEqual("Miley", result[1].Name); } [TestMethod] public void GetById() { var fixture = new Fixture(); var data = new List<User>() { fixture.Build<User>().With(c=>c.Id,1).With(c=>c.Name,"seafood").Create(), fixture.Build<User>().With(c=>c.Id,2).With(c=>c.Name,"cheese cake").Create() }.AsQueryable(); var mockSet = Helper.CreateDbSetMock<User>(data); var mockContext = new Mock<RestaurantApp.Infrastructure.VitualRestaurantContext>(); mockContext.Setup(m => m.User).Returns(mockSet.Object); var repo = new RestaurantApp.Infrastructure.Repositories.UserRepository(mockContext.Object); var food = repo.GetById(2); Assert.AreEqual("cheese cake", food.Name); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Text; namespace Contoso.Domain.Attributes { class RangeAttributeRewriter : ValidationAttributeRewriter { public RangeAttributeRewriter(RangeAttribute rangeAttribute) { this.attribute = rangeAttribute; } #region Variables private RangeAttribute attribute; #endregion Variables #region Properties protected override ValidationAttribute Attribute => this.attribute; public override string AttributeString { get { return attribute.OperandType == typeof(double) || attribute.OperandType == typeof(int) ? string.Format ( CultureInfo.CurrentCulture, "[Range({0}, {1}{2})]", ((IConvertible)attribute.Minimum).ToString(CultureInfo.CurrentCulture), ((IConvertible)attribute.Maximum).ToString(CultureInfo.CurrentCulture), NamedParameters ) : string.Format ( CultureInfo.CurrentCulture, "[Range(typeof({0}), \"{1}\", \"{2}\"{3})]", attribute.OperandType.FullName, attribute.Minimum.ToString(), attribute.Maximum.ToString(), NamedParameters ); } } public string NamedParameters { get { StringBuilder sb = new StringBuilder(); string errorMessage = GetErrorMessage(); if (!string.IsNullOrEmpty(errorMessage)) sb.Append(string.Format(CultureInfo.CurrentCulture, ", ErrorMessage = \"{0}\"", errorMessage)); return sb.ToString(); } } #endregion Properties } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; using Terraria.ModLoader; namespace TheMinepack.NPCs.Piramyd { public class Piramyd : ModNPC { public override void SetDefaults() { npc.name = "Piramyd"; npc.displayName = "Piramyd"; npc.damage = 10; npc.aiStyle = 3; npc.width = 25; npc.height = 20; npc.defense = 10; npc.lifeMax = 60; npc.knockBackResist = 0.5f; Main.npcFrameCount[npc.type] = 5; animationType = 257; aiType = NPCID.AnomuraFungus; npc.value = Item.buyPrice(0, 0, 3, 0); npc.HitSound = SoundID.NPCHit7; npc.DeathSound = SoundID.NPCDeath15; } public override float CanSpawn(NPCSpawnInfo spawnInfo) { Tile tile = Main.tile[spawnInfo.spawnTileX, spawnInfo.spawnTileY]; return spawnInfo.player.ZoneDesert && !Main.snowMoon && !Main.pumpkinMoon ? 0.1f : 0f; } public override void ScaleExpertStats(int numPlayers, float bossLifeScale) { npc.lifeMax = (int)(npc.lifeMax * 0.6f * bossLifeScale); npc.damage = (int)(npc.damage * 0.5f); } public override void NPCLoot() { if (Main.rand.Next(25) == 0) // 4% Drop chance { Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, mod.ItemType("PharaohsAncientSword")); } } } }
using Microsoft.Practices.Unity; using Prism.Unity; using Prism.Modularity; using LogUrFace.Views; using System.Windows; using LogUrFace.Domain.Repositories; using LogUrFace.Infrastructure.Repositories; using LogUrFace.Services; using LogUrFace.Infrastructure.Persistence; using System.Data.Entity; using Prism.Events; using LogUrFace.Hardware; using LogUrFace.Infrastructure.Security; using System; using LogUrFace.ReportingModule.Services; using LogUrFace.ReportingModule.Views; using LogUrFace.Shared; namespace LogUrFace { class Bootstrapper : UnityBootstrapper { protected override void ConfigureModuleCatalog() { base.ConfigureModuleCatalog(); Type moduleReporting = typeof(ReportingModule.ReportingModule); ModuleCatalog.AddModule(new ModuleInfo { ModuleName = moduleReporting.Name, ModuleType = moduleReporting.AssemblyQualifiedName, }); Type moduleFaceRec = typeof(FaceRec.FaceRecModule); ModuleCatalog.AddModule(new ModuleInfo { ModuleName = moduleFaceRec.Name, ModuleType = moduleFaceRec.AssemblyQualifiedName }); } protected override void ConfigureContainer() { base.ConfigureContainer(); Container.RegisterType<IFolderBrowserService, MyFolderBrowserService>(); Container.RegisterType<IHashingService, PasswordHasher>(); Container.RegisterType<IDTRRepository, DTRRepository>(); Container.RegisterType<IAuthenticationService, AuthenticationService>(); if (Properties.Settings.Default.USE_FAKES) Container.RegisterType<IFaceCamera, FakeCamera>(); else Container.RegisterType<IFaceCamera, LuxandCamera>(new ContainerControlledLifetimeManager()); Container.RegisterType<IEmployeeRepository, EmployeeRepository>(); Container.RegisterType<IApplicationService, ApplicationService>(); Container.RegisterTypeForNavigation<Views.EmployeeList>(Shared.ViewNames.EmployeeListView); Container.RegisterTypeForNavigation<Views.LogSheet>(Shared.ViewNames.LogSheetView); Container.RegisterTypeForNavigation<Views.AddEditEmployee>(Shared.ViewNames.AddEditEmployeeView); //From reporting module Container.RegisterType<IDTRBuilder, DTRBuilder>(); Container.RegisterTypeForNavigation<DTRReport>(Shared.ViewNames.DTRReport); Container.RegisterTypeForNavigation<DTRPreview>(Shared.ViewNames.DTRPreview); //From facerec module Container.RegisterTypeForNavigation<FaceRec.Views.FaceRecView>(Shared.ViewNames.FaceRecView); } protected override DependencyObject CreateShell() { return Container.Resolve<MainWindow>(); } protected override void InitializeShell() { Application.Current.MainWindow.Show(); } } }
using System; using System.Collections.Generic; using UnityEngine; namespace Parabox.CSG { public class CSG { public const float EPSILON = 1E-05f; public static Mesh Union(GameObject lhs, GameObject rhs) { CSG_Model cSG_Model = new CSG_Model(lhs); CSG_Model cSG_Model2 = new CSG_Model(rhs); CSG_Node a = new CSG_Node(cSG_Model.ToPolygons()); CSG_Node b = new CSG_Node(cSG_Model2.ToPolygons()); List<CSG_Polygon> list = CSG_Node.Union(a, b).AllPolygons(); CSG_Model cSG_Model3 = new CSG_Model(list); return cSG_Model3.ToMesh(); } public static Mesh Subtract(GameObject lhs, GameObject rhs) { CSG_Model cSG_Model = new CSG_Model(lhs); CSG_Model cSG_Model2 = new CSG_Model(rhs); CSG_Node a = new CSG_Node(cSG_Model.ToPolygons()); CSG_Node b = new CSG_Node(cSG_Model2.ToPolygons()); List<CSG_Polygon> list = CSG_Node.Subtract(a, b).AllPolygons(); CSG_Model cSG_Model3 = new CSG_Model(list); return cSG_Model3.ToMesh(); } public static Mesh Intersect(GameObject lhs, GameObject rhs) { CSG_Model cSG_Model = new CSG_Model(lhs); CSG_Model cSG_Model2 = new CSG_Model(rhs); CSG_Node a = new CSG_Node(cSG_Model.ToPolygons()); CSG_Node b = new CSG_Node(cSG_Model2.ToPolygons()); List<CSG_Polygon> list = CSG_Node.Intersect(a, b).AllPolygons(); CSG_Model cSG_Model3 = new CSG_Model(list); return cSG_Model3.ToMesh(); } } }
/** *┌──────────────────────────────────────────────────────────────┐ *│ 描 述: *│ 作 者:zhujun *│ 版 本:1.0 模板代码自动生成 *│ 创建时间:2019-06-05 12:20:06 *└──────────────────────────────────────────────────────────────┘ *┌──────────────────────────────────────────────────────────────┐ *│ 命名空间: EWF.IServices *│ 接口名称: ISTATIONINFO_SHOWIMGService *└──────────────────────────────────────────────────────────────┘ */ using EWF.Entity; using EWF.Util; using EWF.Util.Page; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace EWF.IServices { public interface ISTATIONINFO_SHOWIMGService : IDependency { int Insert(STATIONINFO_SHOWIMG entity); /// <summary> /// 根据站码获取实体列表 /// </summary> /// <param name="STCD"></param> /// <returns></returns> IEnumerable<STATIONINFO_SHOWIMG> GetModelById(int Show_Id); bool Delete(int ID); bool DeleteList(object whereConditions); } }
using System.Collections.Generic; using IronPython.Compiler.Ast; namespace Py2Cs.CodeGraphs { public class PythonClass : IPythonNode { private PythonClass(string name, ClassDefinition pythonDefinition) { this.Name = name; this.PythonDefinition = pythonDefinition; this.Children = new Dictionary<string, IPythonNode>(); } public string Name { get; } public ClassDefinition PythonDefinition { get; } public Dictionary<string, IPythonNode> Children { get; } public static PythonClass Create(string name) { return new PythonClass(name, null); } public static PythonClass Create(ClassDefinition pythonDefinition) { var node = new PythonClass(pythonDefinition.Name, pythonDefinition); var nodeType = new PythonType(node); node.ExtractChildren(pythonDefinition.Body); foreach (var child in node.Children.Values) { if (child is PythonFunction pythonFunction) { pythonFunction.Parameters[0].Type = nodeType; } } return node; } public override string ToString() { return Name; } } }
/* * ProWritingAid API V2 * * Official ProWritingAid API Version 2 * * OpenAPI spec version: v2 * Contact: hello@prowritingaid.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = ProWritingAid.SDK.Client.SwaggerDateConverter; namespace ProWritingAid.SDK.Model { /** * <summary>AnalysisSummaryGraphItem</summary> */ [DataContract] public partial class AnalysisSummaryGraphItem : IEquatable<AnalysisSummaryGraphItem>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="AnalysisSummaryGraphItem" /> class. /// </summary> /// <param name="Label">Label.</param> /// <param name="Color">Color.</param> /// <param name="Length">Length.</param> /// <param name="SubCategory">SubCategory.</param> /// <param name="Index">Index.</param> /// <param name="Id">Id.</param> public AnalysisSummaryGraphItem(string Label = default(string), string Color = default(string), int? Length = default(int?), string SubCategory = default(string), int? Index = default(int?), string Id = default(string)) { this.Label = Label; this.Color = Color; this.Length = Length; this.SubCategory = SubCategory; this.Index = Index; this.Id = Id; } /// <summary> /// Gets or Sets Label /// </summary> [DataMember(Name="Label", EmitDefaultValue=false)] public string Label { get; set; } /// <summary> /// Gets or Sets Color /// </summary> [DataMember(Name="Color", EmitDefaultValue=false)] public string Color { get; set; } /// <summary> /// Gets or Sets Length /// </summary> [DataMember(Name="Length", EmitDefaultValue=false)] public int? Length { get; set; } /// <summary> /// Gets or Sets SubCategory /// </summary> [DataMember(Name="SubCategory", EmitDefaultValue=false)] public string SubCategory { get; set; } /// <summary> /// Gets or Sets Index /// </summary> [DataMember(Name="Index", EmitDefaultValue=false)] public int? Index { get; set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="Id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AnalysisSummaryGraphItem {\n"); sb.Append(" Label: ").Append(Label).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); sb.Append(" Length: ").Append(Length).Append("\n"); sb.Append(" SubCategory: ").Append(SubCategory).Append("\n"); sb.Append(" Index: ").Append(Index).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as AnalysisSummaryGraphItem); } /// <summary> /// Returns true if AnalysisSummaryGraphItem instances are equal /// </summary> /// <param name="other">Instance of AnalysisSummaryGraphItem to be compared</param> /// <returns>Boolean</returns> public bool Equals(AnalysisSummaryGraphItem other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Label == other.Label || this.Label != null && this.Label.Equals(other.Label) ) && ( this.Color == other.Color || this.Color != null && this.Color.Equals(other.Color) ) && ( this.Length == other.Length || this.Length != null && this.Length.Equals(other.Length) ) && ( this.SubCategory == other.SubCategory || this.SubCategory != null && this.SubCategory.Equals(other.SubCategory) ) && ( this.Index == other.Index || this.Index != null && this.Index.Equals(other.Index) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Label != null) hash = hash * 59 + this.Label.GetHashCode(); if (this.Color != null) hash = hash * 59 + this.Color.GetHashCode(); if (this.Length != null) hash = hash * 59 + this.Length.GetHashCode(); if (this.SubCategory != null) hash = hash * 59 + this.SubCategory.GetHashCode(); if (this.Index != null) hash = hash * 59 + this.Index.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
/* * Copyright (c) The Game Learner * https://connect.unity.com/u/rishabh-jain-1-1-1 * https://www.linkedin.com/in/rishabh-jain-266081b7/ * * created on - #CREATIONDATE# */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletHandler : MonoBehaviour { TrailRenderer tRenderer; Rigidbody rigidbody; [SerializeField] int muzzleFlashVfxIndex; [SerializeField] int HitVfxIndex; const float faddeOutTime = 0.1f; /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> void Awake() { tRenderer = transform.GetComponent<TrailRenderer>(); rigidbody = GetComponent<Rigidbody>(); } private void Start() { if (tRenderer != null) { tRenderer.Clear(); tRenderer.time = faddeOutTime; } } private void OnEnable() { if(rigidbody.velocity!=Vector3.zero){ GameObject muzzleFlashGo = ObjectPool.instance.GetPooledObject(muzzleFlashVfxIndex); muzzleFlashGo.transform.position = transform.position; muzzleFlashGo.SetActive(true); } if (tRenderer != null) { tRenderer.Clear(); } } private void OnDisable() { if(rigidbody.velocity!=Vector3.zero){ GameObject muzzleFlashGo = ObjectPool.instance.GetPooledObject(muzzleFlashVfxIndex); muzzleFlashGo.transform.position = transform.position; muzzleFlashGo.SetActive(true); } if (tRenderer != null) { tRenderer.Clear(); } } private void OnCollisionEnter(Collision collision) { //Debug.Log("bullet collided with " + collision.transform.name); GameObject hitVfxGo = ObjectPool.instance.GetPooledObject(HitVfxIndex); hitVfxGo.transform.position = transform.position; hitVfxGo.transform.SetParent(null,true); hitVfxGo.SetActive(true); AudioManager.instance.PlaybulletHitClip(); //if(collision.transform != GameSettings.instance.playerTransform) //{ // Debug.Log("bullet hits : " + collision.transform.name, collision.transform); //} ReturnList.instance.ReturnIfExisting(gameObject); } }
using BuilderDesignPattern.Product; namespace BuilderDesignPattern.Builders { public interface IPizzaBuilder { IPizzaBuilder SetName(); IPizzaBuilder SetPrice(); IPizzaBuilder SetDescription(); IPizzaBuilder SetToppings(); Pizza GetPizza(); } }
using NUnit.Framework; using Airfield_Simulator.Core.Simulation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Airfield_Simulator.Core.Simulation.Tests { [TestFixture()] public class AirplaneSpawnerTests { [Test()] public void AirplaneSpawnerTest() { Assert.Fail(); } [Test()] public void StartTest() { Assert.Fail(); } [Test()] public void StopTest() { Assert.Fail(); } } }
using BLL; using Entidades; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProyectoFinal.UI.Registros { public partial class rAgricultor : Form { private int IdUsuario; public rAgricultor(int IdUsuario) { InitializeComponent(); this.IdUsuario = IdUsuario; } private void Nuevobutton_Click(object sender, EventArgs e) { Limpiar(); } private void Limpiar() { IdnumericUpDown.Value = 0; NombretextBox.Text = string.Empty; CedulatextBox.Text = string.Empty; DirecciontextBox.Text = string.Empty; TelefonotextBox.Text = string.Empty; CelulartextBox.Text = string.Empty; FechaRegistrodateTimePicker.Value = DateTime.Now; FechaNacimientodateTimePicker.Value = DateTime.Now; BalancetextBox.Text = "0.0"; } private void Guardarbutton_Click(object sender, EventArgs e) { if (!Validar()) return; Agricultores agricultor = LlenarClase(); RepositorioBase<Agricultores> db = new RepositorioBase<Agricultores>(); try { if (IdnumericUpDown.Value == 0) { if (db.Guardar(agricultor)) { MessageBox.Show("Guardado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information); Limpiar(); } else { MessageBox.Show("No se pudo guardar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { if (db.Modificar(agricultor)) { MessageBox.Show("Modificado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information); Limpiar(); } else { MessageBox.Show("No se pudo Modificar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } catch (Exception) { MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private Agricultores LlenarClase() { Agricultores agricultor = new Agricultores(); agricultor.IdAgricultor = (int)IdnumericUpDown.Value; agricultor.Nombre = NombretextBox.Text; agricultor.Cedula = CedulatextBox.Text; agricultor.Direccion = DirecciontextBox.Text; agricultor.Telefono = TelefonotextBox.Text; agricultor.Celular = CelulartextBox.Text; agricultor.FechaCreacion = FechaRegistrodateTimePicker.Value; agricultor.FechaNacimiento = FechaNacimientodateTimePicker.Value; agricultor.IdUsuario = IdUsuario; try { agricultor.Balance = decimal.Parse(BalancetextBox.Text); } catch (Exception){ } return agricultor; } private bool Validar() { bool paso = true; errorProvider.Clear(); if (string.IsNullOrWhiteSpace(NombretextBox.Text)) { paso = false; errorProvider.SetError(NombretextBox, "Este campo no puede estar vacio"); } if (string.IsNullOrWhiteSpace(CedulatextBox.Text)) { paso = false; errorProvider.SetError(CedulatextBox, "Este campo no puede estar vacio"); } if (string.IsNullOrWhiteSpace(DirecciontextBox.Text)) { paso = false; errorProvider.SetError(DirecciontextBox, "Este campo no puede estar vacio"); } if (string.IsNullOrWhiteSpace(TelefonotextBox.Text)) { paso = false; errorProvider.SetError(TelefonotextBox, "Este campo no puede estar vacio"); } if (string.IsNullOrWhiteSpace(CelulartextBox.Text)) { paso = false; errorProvider.SetError(CelulartextBox, "Este campo no puede estar vacio"); } if (FechaRegistrodateTimePicker.Value > DateTime.Now) { paso = false; errorProvider.SetError(FechaRegistrodateTimePicker, "La fecha no puede ser mayor que la de hoy"); } if (FechaNacimientodateTimePicker.Value > DateTime.Now) { paso = false; errorProvider.SetError(FechaNacimientodateTimePicker, "La fecha no puede ser mayor que la de hoy"); } if (!Personas.ValidarCedula(CedulatextBox.Text.Trim())) { paso = false; errorProvider.SetError(CedulatextBox, "Esta cedula no es valida"); } return paso; } private void Eliminarbutton_Click(object sender, EventArgs e) { RepositorioBase<Agricultores> db = new RepositorioBase<Agricultores>(); errorProvider.Clear(); try { if (IdnumericUpDown.Value == 0) { errorProvider.SetError(IdnumericUpDown, "Este campo no puede ser cero al eliminar"); } else { if (db.Elimimar((int)IdnumericUpDown.Value)) { MessageBox.Show("Eliminado Existosamente", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Information); Limpiar(); } else { MessageBox.Show("No se pudo guardar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } catch (Exception) { MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Buscarbutton_Click(object sender, EventArgs e) { RepositorioBase<Agricultores> db = new RepositorioBase<Agricultores>(); Agricultores agricultores; try { if ((agricultores = db.Buscar((int)IdnumericUpDown.Value)) is null) { MessageBox.Show("No se pudo encontrar", "Atencion!!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { LlenarCampos(agricultores); } } catch (Exception) { MessageBox.Show("Hubo un error!!", "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void LlenarCampos(Agricultores agricultor) { Limpiar(); IdnumericUpDown.Value = agricultor.IdAgricultor; NombretextBox.Text = agricultor.Nombre; CedulatextBox.Text = agricultor.Cedula; DirecciontextBox.Text = agricultor.Direccion; TelefonotextBox.Text = agricultor.Telefono; CelulartextBox.Text = agricultor.Celular; FechaRegistrodateTimePicker.Value = agricultor.FechaCreacion; FechaNacimientodateTimePicker.Value = agricultor.FechaNacimiento; BalancetextBox.Text = agricultor.Balance.ToString(); } } }
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_SceneInnerTeleportData : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { SceneInnerTeleportData o = new SceneInnerTeleportData(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int CloneSelf(IntPtr l) { int result; try { SceneInnerTeleportData sceneInnerTeleportData = (SceneInnerTeleportData)LuaObject.checkSelf(l); SceneInnerTeleportData o = sceneInnerTeleportData.CloneSelf(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_pve(IntPtr l) { int result; try { SceneInnerTeleportData sceneInnerTeleportData = (SceneInnerTeleportData)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, sceneInnerTeleportData.pve); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_pve(IntPtr l) { int result; try { SceneInnerTeleportData sceneInnerTeleportData = (SceneInnerTeleportData)LuaObject.checkSelf(l); SceneInnerPlayModeTeleportData pve; LuaObject.checkType<SceneInnerPlayModeTeleportData>(l, 2, out pve); sceneInnerTeleportData.pve = pve; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_pvp(IntPtr l) { int result; try { SceneInnerTeleportData sceneInnerTeleportData = (SceneInnerTeleportData)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, sceneInnerTeleportData.pvp); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_pvp(IntPtr l) { int result; try { SceneInnerTeleportData sceneInnerTeleportData = (SceneInnerTeleportData)LuaObject.checkSelf(l); SceneInnerPlayModeTeleportData pvp; LuaObject.checkType<SceneInnerPlayModeTeleportData>(l, 2, out pvp); sceneInnerTeleportData.pvp = pvp; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_raids(IntPtr l) { int result; try { SceneInnerTeleportData sceneInnerTeleportData = (SceneInnerTeleportData)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, sceneInnerTeleportData.raids); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_raids(IntPtr l) { int result; try { SceneInnerTeleportData sceneInnerTeleportData = (SceneInnerTeleportData)LuaObject.checkSelf(l); SceneInnerPlayModeTeleportData[] raids; LuaObject.checkArray<SceneInnerPlayModeTeleportData>(l, 2, out raids); sceneInnerTeleportData.raids = raids; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.SceneInnerTeleportData"); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_SceneInnerTeleportData.CloneSelf)); LuaObject.addMember(l, "pve", new LuaCSFunction(Lua_RO_SceneInnerTeleportData.get_pve), new LuaCSFunction(Lua_RO_SceneInnerTeleportData.set_pve), true); LuaObject.addMember(l, "pvp", new LuaCSFunction(Lua_RO_SceneInnerTeleportData.get_pvp), new LuaCSFunction(Lua_RO_SceneInnerTeleportData.set_pvp), true); LuaObject.addMember(l, "raids", new LuaCSFunction(Lua_RO_SceneInnerTeleportData.get_raids), new LuaCSFunction(Lua_RO_SceneInnerTeleportData.set_raids), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_SceneInnerTeleportData.constructor), typeof(SceneInnerTeleportData), typeof(ScriptableObject)); } }
using UnityEngine; public class CameraController : MonoBehaviour { [Header("Camera Movement Attributes")] public float speed; public float scrollSpeed; public float borderThickness; [Header("Camera movement limit")] public float minY; public float maxY; public float minX; public float maxX; public float minZ; public float maxZ; private bool movementAvaiable = true; private void Start() { //Set start position of camera to look at the center of the map transform.position = new Vector3(0.5f * GameManager._Instance.mapSize, transform.position.y, transform.position.z); } private void Update() { //Lock Camera if (Input.GetKeyDown(KeyCode.Escape)) { movementAvaiable = !movementAvaiable; } if (!movementAvaiable) { return; } if (Input.GetKey("w") || Input.mousePosition.y >= Screen.height - borderThickness) { if (transform.position.z < maxZ) { //Move in the direction with rotation ignore transform.Translate(Vector3.forward * speed * Time.deltaTime, Space.World); } } if (Input.GetKey("s") || Input.mousePosition.y <= borderThickness) { if (transform.position.z > minZ) { transform.Translate(Vector3.back * speed * Time.deltaTime, Space.World); } } if (Input.GetKey("d") || Input.mousePosition.x >= Screen.width - borderThickness) { if (transform.position.x < maxX) { transform.Translate(Vector3.right * speed * Time.deltaTime, Space.World); } } if (Input.GetKey("a") || Input.mousePosition.x <= borderThickness) { if (transform.position.x > minX) { transform.Translate(Vector3.left * speed * Time.deltaTime, Space.World); } } //Scroll input is to change camera Height in comfortable way float scroll = Input.GetAxis("Mouse ScrollWheel"); if (scroll != 0) { Vector3 tempPosition = transform.position; tempPosition.y -= scroll * scrollSpeed * Time.deltaTime; tempPosition.y = Mathf.Clamp(tempPosition.y, minY, maxY); transform.position = tempPosition; } } }
using System; namespace CSharp.DessignPatterns.Adapter { class Program { static void Main(string[] args) { //Adapter Design Pattern bir Structural'dir. //Structural nesneler arasındaki yapıları ifade eden bir pattern'dir. //Birbiriyle uyumusuz/çalışmayan sınıfları çalışabilir hale getirmek istiyorsak. //Adapter Desing Pattern Instance var manager = new ProductManager(new EdLogger()); manager.Save(); var manager2 = new ProductManager(new Log4NetAdapter()); manager2.Save(); Console.ReadLine(); } internal interface ILogger { void Log(string message); } internal class EdLogger : ILogger { public void Log(string message) { Console.WriteLine($"EdLogger : {message}"); } } internal class ProductManager : IProductService { private ILogger _logger; public ProductManager(ILogger logger) { _logger = logger; } public void Save() { _logger.Log(nameof(ProductManager)); Console.WriteLine($"{nameof(ProductManager)} Save Method Worked"); } } internal interface IProductService { void Save(); } //Suppose that we have Log4Net from Nuget and can't change this library internal interface ILog4Net { void Log(string message); } internal class Log4Net : ILog4Net { public void Log(string message) { Console.WriteLine($"{nameof(Log4Net)} : {message}"); } } //How can we User Log4Net in our implementation //Create Adapter for this! internal class Log4NetAdapter : ILogger { private readonly ILog4Net _log4Net; public Log4NetAdapter() { _log4Net = new Log4Net(); } public void Log(string message) { _log4Net.Log(message); } } } }
using Harmony; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Terraria; namespace MechScope.Patches { [HarmonyPatch(typeof(Wiring), "LogicGatePass")] [HarmonyPriority(Priority.Normal)] internal class LogicGatePassPatch { [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(ILGenerator generator, IEnumerable<CodeInstruction> original) { bool inject = false; bool injectedPostBranch = false; bool injectedPreClearGatesDone = false; int GatesDoneCount = 0; Stack<Label> prevJumps = new Stack<Label>(); foreach (var item in original) { if (inject) { inject = false; CodeInstruction[] inst = SuspendableWireManager.MakeSuspendSnippet(generator, SuspendableWireManager.SuspendMode.perStage); foreach (var item2 in inst) { //ErrorLogger.Log(item2); yield return item2; } } //We want to inject after the end of the first loop at IL_0045 if (!injectedPostBranch && (item.opcode == OpCodes.Bgt || item.opcode == OpCodes.Bgt_S)) { injectedPostBranch = true; inject = true; } //We also need to put one on the end before IL_00D7 if (!injectedPreClearGatesDone && item.opcode == OpCodes.Ldsfld) { FieldInfo SetField = item.operand as FieldInfo; if (SetField != null && SetField.Name == "_GatesDone") { if (++GatesDoneCount == 4) { injectedPreClearGatesDone = true; inject = true; } } } if (item.opcode == OpCodes.Brfalse || item.opcode == OpCodes.Brfalse_S) { prevJumps.Push((Label)item.operand); } //ErrorLogger.Log(item); yield return item; } } } }
using System; using System.Text; using System.Windows; namespace OmniGui.Wpf { public static class XamlMixin { public static string ReadFromContent(this Uri uriContent) { if (uriContent == null) { throw new ArgumentNullException(nameof(uriContent)); } var contentStream = Application.GetContentStream(uriContent); if (contentStream == null) { throw new ArgumentNullException(nameof(contentStream)); } using (var stream = contentStream.Stream) { var l = stream.Length; var bytes = new byte[l]; stream.Read(bytes, 0, (int)l); return Encoding.UTF8.GetString(bytes); } } } }
 using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Stock_Management.Model; namespace StockManagementTest { [TestClass] public class UnitTest1 { [TestMethod] public void TestFillProductOrderList() { Product p = new Product() { Id = 999 }; // Create List of Orders and create an Order // Add order to List List<Order> lo = new List<Order>(); Order o = new Order(p.Id, 999, "På vej", 10, DateTime.Now, DateTime.Now); lo.Add(o); // Run method to fill the Product collection of orders p.FillOrderList(lo); // Test if order exists in the collection CollectionAssert.Contains(p.OrderList, o); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Sound { public AudioClip clip; public AudioSource audioSource; } public class SoundManager : MonoBehaviour { [SerializeField] private AudioSource audioSource; [SerializeField] Sound[] sound; [SerializeField] public static SoundManager inst; // Start is called before the first frame update void Start() { if (inst == null) { inst = this; } else if (inst != this) { Destroy(gameObject); } } private void Awake() { audioSource = GetComponent<AudioSource>(); } public void PlayAudio(int idx) { sound[idx].audioSource.clip = sound[idx].clip; sound[idx].audioSource.Play(); } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using TK_Recorder.Model; using Windows.Storage; namespace TK_Recorder.Services { public class BackendService { private readonly string apiEndpoint = "https://localhost:5001"; public async Task<Semester> GetCurrentSemesterAsync() { return await Get<Semester>(new Uri(apiEndpoint + "/api/semester/current")); } public async Task<List<Lecture>> GetCurrentLecturesAsync() { var semester = await GetCurrentSemesterAsync(); if (semester == null) { return new List<Lecture>(); } return await Get<List<Lecture>>(new Uri(apiEndpoint + "/api/lecture/semester/" + semester.Id)); } public async Task UploadRecordingAsync(Lecture lecture) { using (var httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; using (var client = new HttpClient(httpClientHandler)) { var slidesFile = await StorageFile.GetFileFromPathAsync(@"D:\Videos\Captures\2020-07-19-14-58-42_slides.mp4"); var talkingheadFile = await StorageFile.GetFileFromPathAsync(@"D:\Videos\Captures\2020-07-19-14-58-42_talkinghead.mp4"); var metadataFile = await StorageFile.GetFileFromPathAsync(@"D:\Videos\Captures\2020-07-19-14-58-42_meta.json"); var slidesStream = await slidesFile.OpenStreamForReadAsync(); var talkingheadStream = await talkingheadFile.OpenStreamForReadAsync(); var metadataStream = await metadataFile.OpenStreamForReadAsync(); var content = new MultipartFormDataContent(); content.Add(new StreamContent(slidesStream), "files", "2020-07-19-14-58-42_slides.mp4"); content.Add(new StreamContent(talkingheadStream), "files", "2020-07-19-14-58-42_talkinghead.mp4"); content.Add(new StreamContent(metadataStream), "files", "2020-07-19-14-58-42_meta.json"); content.Add(new StringContent("false"), "progess"); var response = await client.PostAsync(apiEndpoint + "/api/recording/upload/" + lecture.Id, content); response.EnsureSuccessStatusCode(); slidesStream.Close(); talkingheadStream.Close(); metadataStream.Close(); } } } private StreamContent CreateFileContent(Stream stream, string fileName, string contentType) { var fileContent = new StreamContent(stream); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("files") { FileName = fileName }; fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); return fileContent; } private async Task<T> Get<T>(Uri queryUri) { using (var httpClientHandler = new HttpClientHandler()) { httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; using (var client = new HttpClient(httpClientHandler)) { var response = await client.GetAsync(queryUri); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(responseBody); } } } } }
namespace ScriptCs.CompileOnlyOption { using System; using ScriptCs.Contracts; [Module("compile-only-option", Extensions = "csx")] public class CompileOnlyOptionModule : IModule { public void Initialize(IModuleConfiguration config) { if (config == null) { throw new ArgumentNullException(nameof(config)); } config.FilePreProcessor<CompileOnlyOptionFilePreProcessor>(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; public enum Targetable {LeftTargetable,RightTargetable }; public class Player : MonoBehaviour { private float maxY = 60f; private float maxZ = 39f; //In z Rotation Opening arm reverse transform private float minZ = -20f; private float yOffset; private float fireTimer = 0f; private PoolType currentBulletType; Animator animator; GameManager gameManager; BulletPool pool; [SerializeField] GameObject enemiesLeftText=default; public float speed; public bool isScaling = false; public VariableJoystick variableJoystick; public Rigidbody rb; public float rotationSpeed; public GameObject leftArm; public GameObject rightArm; public GameObject leftForeArm; public GameObject rightForeArm; public GameObject upperRightArm; public GameObject upperLeftArm; public GameObject leftWrist; public GameObject rightWrist; public GameObject leftEnemySearcher; public GameObject rightEnemySearcher; public GameObject leftGun; public GameObject rightGun; public GameObject fireStarterLeft; public GameObject fireStarterRigth; public GameObject forceShield; public GameObject enemyKillEffect; public List<Enemy> enemyList; void Awake() { enemyList = new List<Enemy>(); currentBulletType = PoolType.regulerBullet; } void Start() { animator = gameObject.GetComponent<Animator>(); gameManager = GameManager.Instance; pool = BulletPool.instance; } void Update() { if (Input.GetMouseButtonUp(0)) { TriggerShield(); } } void LateUpdate() { Vector3 direction = Vector3.forward * variableJoystick.Vertical + Vector3.right * variableJoystick.Horizontal; rb.AddForce(direction * speed * Time.fixedDeltaTime, ForceMode.VelocityChange); animator.SetFloat("speed", rb.velocity.magnitude); if (enemyList.Count > 0) { //Find left and right cloesest enemies Enemy leftClosestEnemy = GetClosestEnemy(enemyList, leftEnemySearcher); Enemy rightClosestEnemy = GetClosestEnemy(enemyList, rightEnemySearcher); float distanceLeft = (leftClosestEnemy.transform.position - leftWrist.transform.position).magnitude; float distanceRight = (rightClosestEnemy.transform.position - rightWrist.transform.position).magnitude; ////Override Arm Animation leftForeArm.transform.localRotation = Quaternion.Euler(new Vector3(0f, 15f, -55f)); rightForeArm.transform.localRotation = Quaternion.Euler(new Vector3(110f, -35f, -50f)); upperLeftArm.transform.localRotation = Quaternion.Euler(new Vector3(10f, 7f, 49f)); upperRightArm.transform.localRotation = Quaternion.Euler(new Vector3(-2f, -7f, 49f)); leftWrist.transform.localRotation = Quaternion.Euler(new Vector3(0f, 0f, 55f)); rightWrist.transform.localRotation = Quaternion.Euler(new Vector3(-90f, -90f, 85f)); if ((distanceLeft <= gameManager.PlayerAttackRange || distanceRight <= gameManager.PlayerAttackRange) && !animator.GetBool("isForceShield")) { //Rotate towards to enemy Vector3 leftEnemyDirection = (leftClosestEnemy.transform.position - transform.position).normalized; //Enemy to Player Quaternion lookLeftRotationEnemy = Quaternion.LookRotation(leftEnemyDirection, Vector3.up); float playerYLeftTransform = Quaternion.RotateTowards(lookLeftRotationEnemy, transform.rotation, rotationSpeed * Time.deltaTime).eulerAngles.y; //Player Y transform value needded to look towards enemy bool isLeftTargetable = CheckTargetable(playerYLeftTransform, Targetable.LeftTargetable); Vector3 rightEnemyDirection = (rightClosestEnemy.transform.position - transform.position).normalized; //Enemy to Player Quaternion lookRightRotationEnemy = Quaternion.LookRotation(rightEnemyDirection, Vector3.up); float playerYRightTransform = Quaternion.RotateTowards(lookRightRotationEnemy, transform.rotation, rotationSpeed * Time.deltaTime).eulerAngles.y; //Player Y transform value needded to look towards enemy bool isRightTargetable = CheckTargetable(playerYRightTransform, Targetable.RightTargetable); if (isLeftTargetable && isRightTargetable ) // both arms can shoot different enemies { float leftArmZRotation = YZRotationMapper(playerYLeftTransform); float rightArmZRotation = YZRotationMapper(playerYRightTransform); leftArm.transform.localRotation = Quaternion.Euler(new Vector3(-165f, 90f, leftArmZRotation)); rightArm.transform.localRotation = Quaternion.Euler(new Vector3(15f, 90f, rightArmZRotation)); } else // only enemy from left or right can be shoot bcs robot can open arms up to some degree, shoot closest { Enemy closestEnemy; if (distanceLeft < distanceRight) closestEnemy = leftClosestEnemy; else closestEnemy = rightClosestEnemy; Vector3 enemyDirection = (closestEnemy.transform.position - transform.position).normalized; Quaternion lookRotationEnemy = Quaternion.LookRotation(enemyDirection, Vector3.up); transform.rotation = Quaternion.Euler(new Vector3(0f, Quaternion.RotateTowards(lookRotationEnemy, transform.rotation, rotationSpeed * Time.fixedDeltaTime).eulerAngles.y)); leftArm.transform.localRotation = Quaternion.Euler(new Vector3(-165f, 90f, 39f)); rightArm.transform.localRotation = Quaternion.Euler(new Vector3(15f, 90f, 39f)); } fireTimer += Time.fixedDeltaTime; //Start fire if (fireTimer >= gameManager.FireRate) { fireTimer = 0; GameObject leftBullet = pool.Fire(currentBulletType, fireStarterLeft.transform.position, leftGun.transform.rotation); GameObject rightBullet = pool.Fire(currentBulletType, fireStarterRigth.transform.position, rightGun.transform.rotation); } } else //normal movement { //Rotate with joystick Vector3 directionJoystick = Vector3.forward * variableJoystick.Vertical + Vector3.right * variableJoystick.Horizontal; if (directionJoystick != Vector3.zero) { Vector3 lookDirection = new Vector3(variableJoystick.Horizontal, 0, variableJoystick.Vertical); Quaternion lookRotation = Quaternion.LookRotation(lookDirection, Vector3.up); float step = rotationSpeed * Time.deltaTime; transform.rotation = Quaternion.RotateTowards(lookRotation, transform.rotation, step); } } } } void OnTriggerEnter(Collider collider) { if(collider.tag == "Enemy") { gameManager.PlayerDied(); } } private bool CheckTargetable(float yTransform,Targetable targetable) { float playerYAbs = transform.rotation.eulerAngles.y; //Get player's current rotation bool isCloserDegreeExist = Mathf.Abs(playerYAbs - yTransform) > 180; //find closest degree between player's current and targeted enemy if (playerYAbs > 180 && isCloserDegreeExist) playerYAbs = playerYAbs - 360; if (yTransform > 180 && isCloserDegreeExist) yTransform = yTransform - 360; yOffset = Math.Abs (yTransform - playerYAbs); //How much rotation needed to hit the enemy if(targetable == Targetable.LeftTargetable) { if (yOffset < 65 && yTransform<= playerYAbs ) //robot's arm can rotate maximum 65 degrees check if it can hit that object return true; else return false; } else { if (yOffset < 65 && yTransform > playerYAbs) // for right arm return true; else return false; } } private Enemy GetClosestEnemy(List<Enemy> enemies, GameObject player) { Enemy bestTarget = null; float closestDistanceSqr = Mathf.Infinity; Vector3 currentPosition = player.transform.position; foreach (Enemy potentialTarget in enemies) { Vector3 directionToTarget = potentialTarget.transform.position - currentPosition; float dSqrToTarget = directionToTarget.sqrMagnitude; if (dSqrToTarget < closestDistanceSqr) { closestDistanceSqr = dSqrToTarget; bestTarget = potentialTarget; } } return bestTarget; } private float YZRotationMapper(float yTransform) { float playerYAbs = transform.rotation.eulerAngles.y; //Get player's current rotation bool isCloserDegreeExist = Mathf.Abs(playerYAbs - yTransform) > 180; //find closest degree between player's current and targeted enemy if (playerYAbs > 180 && isCloserDegreeExist) playerYAbs = playerYAbs - 360; if (yTransform > 180 && isCloserDegreeExist) yTransform = yTransform - 360; yOffset = Math.Abs(yTransform - playerYAbs); //How much rotation needed to hit the enemy //We know enemy hittable so calculate the rotation degree of arm float yDifference = maxY - yOffset; //Calculate in y axis float correspondingZ = yDifference + minZ; //Map to Z axis correspondingZ = Mathf.Clamp(correspondingZ, minZ, maxZ); // We dont want to arms broke :) return correspondingZ; } private void TriggerShield() { rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; var enemiesInsideShield = Physics.OverlapSphere(forceShield.transform.position, forceShield.GetComponent<Renderer>().bounds.extents.magnitude); StartCoroutine(ForceShieldTrigger(forceShield.transform.localScale.y, forceShield.transform.localScale.x, 0.7f)); foreach(var gameObj in enemiesInsideShield) { if (gameObj.tag == "Enemy") { RemoveEnemy(gameObj.GetComponent<Enemy>(),0.5f); } } } IEnumerator ForceShieldTrigger(float fromVal, float toVal, float duration) { float counter = 0f; animator.SetBool("isForceShield", true); while (counter < duration) { counter += Time.unscaledDeltaTime; float val = Mathf.Lerp(fromVal, toVal, counter / duration); forceShield.transform.localScale = new Vector3(val, val, val); yield return null; } forceShield.transform.localScale = new Vector3(3f, 0.1f, 3f); } IEnumerator ForceShieldAreaIncrease(float duration) { if (isScaling) { yield break; ///exit if this is still running } isScaling = true; float counter = 0; //Get the current scale of the object to be moved Vector3 startScaleSize = forceShield.transform.localScale; Vector3 toScale = new Vector3(startScaleSize.x + 0.5f, startScaleSize.y, startScaleSize.z + 0.5f); while (counter < duration) { counter += Time.fixedDeltaTime; forceShield.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration); yield return null; } isScaling = false; } public void AddEnemy(Enemy enemy) { enemyList.Add(enemy); enemiesLeftText.GetComponent<TextMeshProUGUI>().text = "Enemies left: " + enemyList.Count; } public void RemoveEnemy(Enemy enemy,float inTime=0) { if (enemyList.Count > 0) { if (Input.GetMouseButton(0) && forceShield.GetComponent<Renderer>().bounds.extents.magnitude<10) { StartCoroutine(ForceShieldAreaIncrease(0.5f)); } enemyList.Remove(enemy); Instantiate(enemyKillEffect, enemy.transform.position,enemy.transform.rotation); Destroy(enemy.gameObject,inTime); if (enemyList.Count == 0) { speed += 0.5f; gameManager.EndLevel(); } } enemiesLeftText.GetComponent<TextMeshProUGUI>().text = "Enemies left: " + enemyList.Count; } public void ForceShieldAnimationHandler() { animator.SetBool("isForceShield", false); } public void KillAllEnemies() { foreach(Enemy enemy in enemyList.ToList()) { enemyList.Remove(enemy); Destroy(enemy.gameObject, 0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; public class CreateField : EditorWindow { internal static ConfigEditorUI ceui; internal static string[] idArr; internal static string targetId; private string s = ""; void OnGUI() { if (ceui == null || idArr == null) return; GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUI.color = Color.white; GUILayout.Label("配置表名:", EditorStyles.largeLabel, GUILayout.Width(60)); GUI.color = Color.cyan; GUILayout.Label(ceui.typePool.Name, EditorStyles.largeLabel, GUILayout.Width(200)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(10); GUILayout.BeginHorizontal(); GUI.color = Color.white; GUILayout.Label("新配置id:", EditorStyles.largeLabel, GUILayout.Width(60)); GUI.color = Color.yellow; s = EditorGUILayout.TextField("", s, "LargeTextField", GUILayout.Width(s.Length * 8 + 100)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(10); GUILayout.BeginHorizontal(); GUI.color = Color.white; if (GUILayout.Button("确认创建", "LargeButton")) { bool flag = true; for (int i = 0; i < idArr.Length; i++) { if (idArr[i] == s) { flag = false; break; } } if (!flag) { EditorUtility.DisplayDialog("创建失败", "该id已存在!", "返回"); } else { long n; if (long.TryParse(s, out n)) { string[] newStrs = new string[ceui.currentCfgFileInfo[0].Count]; newStrs[0] = s; if (targetId == null) { for (int i = 1; i < newStrs.Length; i++) { newStrs[i] = ""; } } else { for (int i = 1; i < newStrs.Length; i++) { newStrs[i] = ceui.currentCfgFileInfo[int.Parse(targetId)][i]; } } ceui.currentCfgFileInfo.Add(newStrs.ToList()); ceui.StateInit(); int maxPage = (ceui.currentCfgFileInfo.Count - 3)%10 == 0 ? (ceui.currentCfgFileInfo.Count - 3)/10 : (ceui.currentCfgFileInfo.Count - 3)/10 + 1; ceui.Paging(10, maxPage); } else { EditorUtility.DisplayDialog("创建失败", "id格式不正确!", "返回"); } } ceui = null; idArr = null; targetId = null; Close(); } if (GUILayout.Button("返回", "LargeButton")) { ceui = null; idArr = null; targetId = null; Close(); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } }
namespace Newtonsoft.Json { using Newtonsoft.Json.Converters; using ns20; using System; using System.Globalization; using System.IO; using System.Numerics; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; public static class JsonConvert { public static readonly string False = "false"; [CompilerGenerated] private static Func<JsonSerializerSettings> func_0; public static readonly string NaN = "NaN"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string Null = "null"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string True = "true"; public static readonly string Undefined = "undefined"; public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } public static object DeserializeObject(string value) { return DeserializeObject(value, null, (JsonSerializerSettings) null); } public static T DeserializeObject<T>(string value) { return DeserializeObject<T>(value, (JsonSerializerSettings) null); } public static object DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } public static T DeserializeObject<T>(string value, JsonSerializerSettings settings) { return (T) DeserializeObject(value, typeof(T), settings); } public static object DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings) null); } public static T DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T) DeserializeObject(value, typeof(T), converters); } public static object DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters == null) || (converters.Length <= 0)) ? null : new JsonSerializerSettings(); return DeserializeObject(value, type, settings); } public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings) { Class203.smethod_2(value, "value"); StringReader reader = new StringReader(value); JsonSerializer serializer = JsonSerializer.CreateDefault(settings); if (!serializer.method_0()) { serializer.Boolean_0 = true; } return serializer.Deserialize(new JsonTextReader(reader), type); } public static Task<object> DeserializeObjectAsync(string value) { return DeserializeObjectAsync(value, null, null); } public static Task<T> DeserializeObjectAsync<T>(string value) { return DeserializeObjectAsync<T>(value, null); } public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings) { Class109<T> class2 = new Class109<T> { string_0 = value, jsonSerializerSettings_0 = settings }; return Task.Factory.StartNew<T>(new Func<T>(class2.method_0)); } public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings) { Class110 class2 = new Class110 { string_0 = value, type_0 = type, jsonSerializerSettings_0 = settings }; return Task.Factory.StartNew<object>(new Func<object>(class2.method_0)); } public static XmlDocument DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, false); } public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute) { XmlNodeConverter converter = new XmlNodeConverter { DeserializeRootElementName = deserializeRootElementName, WriteArrayAttribute = writeArrayAttribute }; return (XmlDocument) DeserializeObject(value, typeof(XmlDocument), new JsonConverter[] { converter }); } public static XDocument DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument DeserializeXNode(string value, string deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, false); } public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute) { XmlNodeConverter converter = new XmlNodeConverter { DeserializeRootElementName = deserializeRootElementName, WriteArrayAttribute = writeArrayAttribute }; return (XDocument) DeserializeObject(value, typeof(XDocument), new JsonConverter[] { converter }); } public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings settings) { StringReader reader = new StringReader(value); JsonSerializer serializer = JsonSerializer.CreateDefault(settings); using (JsonReader reader2 = new JsonTextReader(reader)) { serializer.Populate(reader2, target); if (reader2.Read() && (reader2.JsonToken_0 != JsonToken.Comment)) { throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); } } } public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings) { Class111 class2 = new Class111 { string_0 = value, object_0 = target, jsonSerializerSettings_0 = settings }; return Task.Factory.StartNew(new Action(class2.method_0)); } public static string SerializeObject(object value) { return SerializeObject(value, Newtonsoft.Json.Formatting.None, (JsonSerializerSettings) null); } public static string SerializeObject(object value, Newtonsoft.Json.Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings) null); } public static string SerializeObject(object value, params JsonConverter[] converters) { return SerializeObject(value, Newtonsoft.Json.Formatting.None, converters); } public static string SerializeObject(object value, JsonSerializerSettings settings) { return SerializeObject(value, Newtonsoft.Json.Formatting.None, settings); } public static string SerializeObject(object value, Newtonsoft.Json.Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters == null) || (converters.Length <= 0)) ? null : new JsonSerializerSettings(); return SerializeObject(value, formatting, settings); } public static string SerializeObject(object value, Newtonsoft.Json.Formatting formatting, JsonSerializerSettings settings) { return SerializeObject(value, null, formatting, settings); } public static string SerializeObject(object value, Type type, Newtonsoft.Json.Formatting formatting, JsonSerializerSettings settings) { JsonSerializer serializer = JsonSerializer.CreateDefault(settings); StringBuilder sb = new StringBuilder(0x100); StringWriter textWriter = new StringWriter(sb, CultureInfo.InvariantCulture); using (JsonTextWriter writer2 = new JsonTextWriter(textWriter)) { writer2.Formatting = formatting; serializer.Serialize(writer2, value, type); } return textWriter.ToString(); } public static Task<string> SerializeObjectAsync(object value) { return SerializeObjectAsync(value, Newtonsoft.Json.Formatting.None, null); } public static Task<string> SerializeObjectAsync(object value, Newtonsoft.Json.Formatting formatting) { return SerializeObjectAsync(value, formatting, null); } public static Task<string> SerializeObjectAsync(object value, Newtonsoft.Json.Formatting formatting, JsonSerializerSettings settings) { Class108 class2 = new Class108 { object_0 = value, formatting_0 = formatting, jsonSerializerSettings_0 = settings }; return Task.Factory.StartNew<string>(new Func<string>(class2.method_0)); } public static string SerializeXmlNode(System.Xml.XmlNode node) { return SerializeXmlNode(node, Newtonsoft.Json.Formatting.None); } public static string SerializeXmlNode(System.Xml.XmlNode node, Newtonsoft.Json.Formatting formatting) { XmlNodeConverter converter = new XmlNodeConverter(); return SerializeObject(node, formatting, new JsonConverter[] { converter }); } public static string SerializeXmlNode(System.Xml.XmlNode node, Newtonsoft.Json.Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, new JsonConverter[] { converter }); } public static string SerializeXNode(XObject node) { return SerializeXNode(node, Newtonsoft.Json.Formatting.None); } public static string SerializeXNode(XObject node, Newtonsoft.Json.Formatting formatting) { return SerializeXNode(node, formatting, false); } public static string SerializeXNode(XObject node, Newtonsoft.Json.Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, new JsonConverter[] { converter }); } private static string smethod_0(BigInteger bigInteger_0) { return bigInteger_0.ToString(null, CultureInfo.InvariantCulture); } internal static string smethod_1(float float_0, FloatFormatHandling floatFormatHandling_0, char char_0, bool bool_0) { return smethod_2((double) float_0, smethod_4((double) float_0, float_0.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling_0, char_0, bool_0); } private static string smethod_2(double double_0, string string_0, FloatFormatHandling floatFormatHandling_0, char char_0, bool bool_0) { if ((floatFormatHandling_0 == FloatFormatHandling.Symbol) || (!double.IsInfinity(double_0) && !double.IsNaN(double_0))) { return string_0; } if (floatFormatHandling_0 != FloatFormatHandling.DefaultValue) { return (char_0 + string_0 + char_0); } if (bool_0) { return Null; } return "0.0"; } internal static string smethod_3(double double_0, FloatFormatHandling floatFormatHandling_0, char char_0, bool bool_0) { return smethod_2(double_0, smethod_4(double_0, double_0.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling_0, char_0, bool_0); } private static string smethod_4(double double_0, string string_0) { if (((!double.IsNaN(double_0) && !double.IsInfinity(double_0)) && ((string_0.IndexOf('.') == -1) && (string_0.IndexOf('E') == -1))) && (string_0.IndexOf('e') == -1)) { return (string_0 + ".0"); } return string_0; } private static string smethod_5(string string_0) { if (string_0.IndexOf('.') != -1) { return string_0; } return (string_0 + ".0"); } internal static string smethod_6(Guid guid_0, char char_0) { string str = null; str = guid_0.ToString("D", CultureInfo.InvariantCulture); return (char_0 + str + char_0); } internal static string smethod_7(TimeSpan timeSpan_0, char char_0) { return ToString(timeSpan_0.ToString(), char_0); } internal static string smethod_8(Uri uri_0, char char_0) { return ToString(uri_0.ToString(), char_0); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(decimal value) { return smethod_5(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(double value) { return smethod_4(value, value.ToString("R", CultureInfo.InvariantCulture)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(Guid value) { return smethod_6(value, '"'); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(object value) { if (value == null) { return Null; } switch (Class181.smethod_1(value)) { case Enum17.Char: return ToString((char) value); case Enum17.Boolean: return ToString((bool) value); case Enum17.SByte: return ToString((sbyte) value); case Enum17.Int16: return ToString((short) value); case Enum17.UInt16: return ToString((ushort) value); case Enum17.Int32: return ToString((int) value); case Enum17.Byte: return ToString((byte) value); case Enum17.UInt32: return ToString((uint) value); case Enum17.Int64: return ToString((long) value); case Enum17.UInt64: return ToString((ulong) value); case Enum17.Single: return ToString((float) value); case Enum17.Double: return ToString((double) value); case Enum17.DateTime: return ToString((DateTime) value); case Enum17.DateTimeOffset: return ToString((DateTimeOffset) value); case Enum17.Decimal: return ToString((decimal) value); case Enum17.Guid: return ToString((Guid) value); case Enum17.TimeSpan: return ToString((TimeSpan) value); case Enum17.BigInteger: return smethod_0((BigInteger) value); case Enum17.Uri: return ToString((Uri) value); case Enum17.String: return ToString((string) value); case Enum17.DBNull: return Null; } throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".smethod_0(CultureInfo.InvariantCulture, value.GetType())); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return smethod_4((double) value, value.ToString("R", CultureInfo.InvariantCulture)); } public static string ToString(string value) { return ToString(value, '"'); } public static string ToString(TimeSpan value) { return smethod_7(value, '"'); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(Uri value) { if (value == null) { return Null; } return smethod_8(value, '"'); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using (StringWriter writer = Class198.smethod_6(0x40)) { writer.Write('"'); Class184.smethod_21(writer, value, format, null, CultureInfo.InvariantCulture); writer.Write('"'); return writer.ToString(); } } public static string ToString(string value, char delimiter) { if ((delimiter != '"') && (delimiter != '\'')) { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return Class189.smethod_1(value, delimiter, true); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime time = Class184.smethod_2(value, timeZoneHandling); using (StringWriter writer = Class198.smethod_6(0x40)) { writer.Write('"'); Class184.smethod_16(writer, time, format, null, CultureInfo.InvariantCulture); writer.Write('"'); return writer.ToString(); } } public static Func<JsonSerializerSettings> DefaultSettings { [CompilerGenerated] get { return func_0; } [CompilerGenerated] set { func_0 = value; } } [CompilerGenerated] private sealed class Class108 { public Newtonsoft.Json.Formatting formatting_0; public JsonSerializerSettings jsonSerializerSettings_0; public object object_0; public string method_0() { return JsonConvert.SerializeObject(this.object_0, this.formatting_0, this.jsonSerializerSettings_0); } } [CompilerGenerated] private sealed class Class109<T> { public JsonSerializerSettings jsonSerializerSettings_0; public string string_0; public T method_0() { return JsonConvert.DeserializeObject<T>(this.string_0, this.jsonSerializerSettings_0); } } [CompilerGenerated] private sealed class Class110 { public JsonSerializerSettings jsonSerializerSettings_0; public string string_0; public Type type_0; public object method_0() { return JsonConvert.DeserializeObject(this.string_0, this.type_0, this.jsonSerializerSettings_0); } } [CompilerGenerated] private sealed class Class111 { public JsonSerializerSettings jsonSerializerSettings_0; public object object_0; public string string_0; public void method_0() { JsonConvert.PopulateObject(this.string_0, this.object_0, this.jsonSerializerSettings_0); } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Retail.Tests { [TestClass] public class ReaderFactoryTests { [TestMethod] public void TestSerialize() { var readerFactory = new Retail.TextReaderFactory("Transform.Tests.deps.json"); var reader = readerFactory.Create(); reader = readerFactory.Create(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Xml.Linq; using System.Linq; using System.Runtime.CompilerServices; using Yasl.Internal; namespace Yasl { public class XmlSerializationWriter : ISerializationWriter { readonly ObjectIDGenerator _objectIdGenerator = new ObjectIDGenerator(); readonly Stack<XElement> _groups = new Stack<XElement>(); readonly SortedList<long, object> _references = new SortedList<long, object>(); readonly SortedList<long, XElement> _lookup = new SortedList<long, XElement>(); readonly Queue<long> _pending = new Queue<long>(); bool _hasWritten; XElement CurrentGroup { get { return _groups.Peek(); } } public void IncludeReference(object value) { if (value == null) { return; } Type type = value.GetType(); bool firstTime; long id = _objectIdGenerator.GetId(value, out firstTime); if (!_lookup.ContainsKey(id)) { XElement rootElement = new XElement("Reference"); rootElement.Add(new XAttribute("id", id)); rootElement.Add(new XAttribute("type", SerializerRegistry.GetSerializedTypeName(type))); _lookup.Add(id, rootElement); _references.Add(id, value); _pending.Enqueue(id); } } public void WriteSet(Type knownType, string itemName, IEnumerable set) { Assert.IsNotNull(itemName); Assert.IsNotNull(set, "Sets cannot be null because we assume empty tag value = empty collection during read"); foreach (var item in set) { Write(knownType, itemName, item); } } public void Write(Type knownType, string groupName, object value) { Assert.IsNotNull(groupName); var element = new XElement(groupName); CurrentGroup.Add(element); _groups.Push(element); if (SerializerRegistry.IsPrimitive(knownType)) { WriteValueContents(knownType, value); } else { WriteReferenceContents(knownType, value); } _groups.Pop(); } void WriteReferenceContents(Type knownType, object value) { if (value == null) { CurrentGroup.Add(new XAttribute("ref", "0")); } else { IncludeReference(value); bool firstTime; long id = _objectIdGenerator.GetId(value, out firstTime); Assert.That(_lookup.ContainsKey(id), "referenced object not included"); CurrentGroup.Add(new XAttribute("ref", id)); } } void WriteValueContents(Type knownType, object value) { if (value == null) { CurrentGroup.Add(new XAttribute("type", "null")); } else { Type type = value.GetType(); if (type.DerivesFrom<Type>()) { // Treat RuntimeType as if it's Type type = typeof(Type); } var serializer = SerializerRegistry.GetSerializer(type); serializer.SerializeConstructor(ref value, this); serializer.SerializeContents(ref value, this); serializer.SerializeBacklinks(ref value, this); if (type != knownType) { CurrentGroup.Add(new XAttribute("type", SerializerRegistry.GetSerializedTypeName(type))); } } } public void WritePrimitive(Type knownType, object value) { Assert.IsNotNull(knownType); Assert.IsNotNull(value); if (knownType == typeof(bool)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(byte)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(short)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(ushort)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(int)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(uint)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(long)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(ulong)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(float)) { CurrentGroup.Value = ((float)value).ToString("R", CultureInfo.InvariantCulture); } else if (knownType == typeof(double)) { CurrentGroup.Value = ((double)value).ToString("R"); } else if (knownType == typeof(decimal)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(char)) { CurrentGroup.Value = value.ToString(); } else if (knownType == typeof(string)) { CurrentGroup.Value = (string)value; } else if (knownType == typeof(byte[])) { CurrentGroup.Value = Convert.ToBase64String((byte[])value); } else if (knownType == typeof(Type)) { CurrentGroup.Value = SerializerRegistry.GetSerializedTypeName((Type)value); } else if (knownType.IsEnum()) { CurrentGroup.Value = value.ToString(); } else { throw Assert.CreateException( "unhandled primative type '{0}'", knownType.Name()); } } public XElement WriteXml(string rootName, object rootReference) { Assert.That(!_hasWritten); _hasWritten = true; IncludeReference(rootReference); Assert.That(_groups.Count == 0); bool firstTime; long rootId = _objectIdGenerator.GetId(rootReference, out firstTime); Assert.That(_references.ContainsKey(rootId), "root object not included"); while(_pending.Count > 0) { long id = _pending.Dequeue(); object value = _references[id]; Type type = value.GetType(); var serializer = SerializerRegistry.GetSerializer(type); try { _groups.Push(_lookup[id]); serializer.SerializeConstructor(ref value, this); serializer.SerializeContents(ref value, this); serializer.SerializeBacklinks(ref value, this); _groups.Pop(); } catch (Exception e) { throw new SerializationException( "Error occurred while serializing value of type '" + type.Name() + "'", e); } } Assert.That(_groups.Count == 0); XElement rootElement = new XElement(rootName); rootElement.Add(new XAttribute("id", rootId)); rootElement.Add(new XAttribute("version", SerializationVersion.Value)); foreach (var cur in _lookup.Values) { rootElement.Add(cur); } return rootElement; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ProjectileLauncher : MonoBehaviour { [Tooltip("Check if script is on the Player")] [SerializeField] private bool _onPlayer; [Space] [SerializeField] private Transform target; [SerializeField] private Rigidbody projectile; [SerializeField] private float airTime = 2.0f; [Tooltip("The time in-between Shots for Non-Player Objects")] [SerializeField] private float _instantiationTimer = 2.0f; private Vector3 _displacement = new Vector3(); private Vector3 _acceleration = new Vector3(); private float _time = 0.0f; private Vector3 _initialVelocity = new Vector3(); private Vector3 _finalVelocity = new Vector3(); private float _ogTimerTime; private void Start() { _ogTimerTime = _instantiationTimer; } private void Update() { if (_onPlayer) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { target = hit.transform; } } if (Input.GetMouseButtonDown(0) && _onPlayer) { LaunchProjectile(); } else if (!_onPlayer) { ShootPlayer(); } } public void LaunchProjectile() { _displacement = target.position - transform.position; _acceleration = Physics.gravity; _time = airTime; _initialVelocity = FindInitialVelocity(_displacement, _acceleration, _time); _finalVelocity = FindFinalVelocity(_initialVelocity, _acceleration, _time); Rigidbody projectileInstance = Instantiate(projectile, transform.position, transform.rotation); projectileInstance.velocity = _initialVelocity; } //Same as LaunchProjectile, but with a timer on shooting public void ShootPlayer() { _instantiationTimer -= Time.deltaTime; _displacement = target.position - transform.position; _acceleration = Physics.gravity; _time = airTime; _initialVelocity = FindInitialVelocity(_displacement, _acceleration, _time); _finalVelocity = FindFinalVelocity(_initialVelocity, _acceleration, _time); if (_instantiationTimer <= 0) { Rigidbody projectileInstance = Instantiate(projectile, transform.position, transform.rotation); projectileInstance.velocity = _initialVelocity; _instantiationTimer = _ogTimerTime; } } // FIND FUNCTIONS private Vector3 FindFinalVelocity(Vector3 initialVelocity, Vector3 acceleration, float time) { // v = v0 + at Vector3 finalVelocity = initialVelocity + acceleration * time; return finalVelocity; } private Vector3 FindDisplacement(Vector3 initialVelocity, Vector3 acceleration, float time) { // deltaX = v0*t + (1/2)*a*t^2 Vector3 displacement = initialVelocity * time + 0.5f * acceleration * time * time; return displacement; } private Vector3 FindInitialVelocity(Vector3 displacement, Vector3 acceleration, float time) { // deltaX = v0*t + (1/2)*a*t^2 // deltaX - (1/2)*a*t^2 = v0*t // deltaX/t - (1/2)*a*t = v0 // v0 = deltaX - (1/2)*a*t Vector3 initialVelocity = displacement / time - 0.5f * acceleration * time; return initialVelocity; } }
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Threading; using OpenQA.Selenium; namespace SpecflowBDD.TAF.NUFramework { public class StitchedScreenshot { /// <summary> /// Workaround for creating a screenshot of the whole browser screen in Chromedriver. /// </summary> /// <param name="driver"></param> /// <param name="filename"></param> /// <param name="imageFormat"></param> public void Save(IWebDriver driver, string filename, ImageFormat imageFormat) { Bitmap stitchedImage = null; var js = (IJavaScriptExecutor)driver; { js.ExecuteScript("return window.scrollTo(0,0)"); // Get the Total Size of the Document var totalWidth = (int)((long)js.ExecuteScript("return document.body.clientWidth")); var totalHeight = (int)((long)js.ExecuteScript("return document.body.clientHeight")); // Get the Size of the Viewport var viewportWidth = (int)((long)js.ExecuteScript("return document.documentElement.clientWidth")); var viewportHeight = (int)((long)js.ExecuteScript("return document.documentElement.clientHeight")); // Split the Screen in multiple Rectangles var rectangles = new List<Rectangle>(); // Loop until the Total Height is reached for (var i = 0; i < totalHeight; i += viewportHeight) { var newHeight = viewportHeight; // Fix if the Height of the Element is too big if (i + viewportHeight > totalHeight) { newHeight = totalHeight - i; } // Loop until the Total Width is reached for (var ii = 0; ii < totalWidth; ii += viewportWidth) { var newWidth = viewportWidth; // Fix if the Width of the Element is too big if (ii + viewportWidth > totalWidth) { newWidth = totalWidth - ii; } // Create and add the Rectangle var currRect = new Rectangle(ii, i, newWidth, newHeight); rectangles.Add(currRect); } } // Build the Image stitchedImage = new Bitmap(totalWidth, totalHeight); // Get all Screenshots and stitch them together var previous = Rectangle.Empty; foreach (var rectangle in rectangles) { // Calculate the Scrolling (if needed) if (previous != Rectangle.Empty) { var xDiff = rectangle.Right - previous.Right; var yDiff = rectangle.Bottom - previous.Bottom; // Scroll //selenium.RunScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff)); ((IJavaScriptExecutor)driver).ExecuteScript(String.Format("window.scrollBy({0}, {1})", xDiff, yDiff)); Thread.Sleep(100); } // Take Screenshot var screenshot = ((ITakesScreenshot)driver).GetScreenshot(); // Build an Image out of the Screenshot Image screenshotImage; using (var memStream = new MemoryStream(screenshot.AsByteArray)) { screenshotImage = Image.FromStream(memStream); } // Calculate the Source Rectangle var sourceRectangle = new Rectangle(viewportWidth - rectangle.Width, viewportHeight - rectangle.Height, rectangle.Width, rectangle.Height); // Copy the Image using (var g = Graphics.FromImage(stitchedImage)) { g.DrawImage(screenshotImage, rectangle, sourceRectangle, GraphicsUnit.Pixel); } // Set the Previous Rectangle previous = rectangle; } stitchedImage.Save(filename, imageFormat); } } } }
using Android.App; using Android.Content; using Android.OS; using Android.Provider; using Android.Support.V7.Widget; using Android.Views; using JKMAndroidApp.adapter; using JKMAndroidApp.Common; using JKMPCL; using JKMPCL.Model; using JKMPCL.Services; using System; using System.Collections.Generic; using static Android.Provider.CalendarContract; using static JKMAndroidApp.adapter.AdapterAlerts; namespace JKMAndroidApp.fragment { /// <summary> /// Method Name : FragmentAlerts /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Fragement for Alert layout /// Revision : /// </summary> public class FragmentAlerts : Android.Support.V4.App.Fragment, IAdapterTextViewClickListener { ProgressDialog progressDialog; private RecyclerView recyclerViewAlerts; List<AlertModel> alertList; CustomerModel customerModel; public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.Inflate(Resource.Layout.LayoutFragmentAlerts, container, false); recyclerViewAlerts = view.FindViewById<RecyclerView>(Resource.Id.recyclerViewAlerts); SetAdapterAsync(); return view; } /// <summary> /// Method Name : SetAdapterAsync /// Author : Sanket Prajapati /// Creation Date : 9 jan 2018 /// Purpose : Bind Data alert data /// Revision : /// </summary> private async void SetAdapterAsync() { alertList = new List<AlertModel>(); Alert alert; alert = new Alert(); string errorMessage = string.Empty; try { progressDialog = UIHelper.SetProgressDailoge(Activity); customerModel = new CustomerModel(); customerModel.CustomerId = UtilityPCL.LoginCustomerData.CustomerId; customerModel.LastLoginDate = UtilityPCL.LoginCustomerData.LastLoginDate; APIResponse<List<AlertModel>> serviceResponse; serviceResponse = await alert.GetAlertList(customerModel); if (serviceResponse.STATUS) { SetAlertDataBinding(serviceResponse); } else { errorMessage = serviceResponse.Message; } } catch (Exception error) { errorMessage = error.Message; } finally { progressDialog.Dismiss(); if (!string.IsNullOrEmpty(errorMessage)) { AlertMessage(errorMessage); } } } /// <summary> /// Method Name : SetAlertDataBinding /// Author : Sanket Prajapati /// Creation Date : 24 jan 2018 /// Purpose : Use alert data bind in adapter /// Revision : /// </summary> private void SetAlertDataBinding(APIResponse<List<AlertModel>> serviceResponse) { if (serviceResponse.DATA != null) { alertList = serviceResponse.DATA; if (alertList.Count > 0) { AdapterAlerts adapterAlerts = new AdapterAlerts(alertList, this); recyclerViewAlerts.SetLayoutManager(new LinearLayoutManager(Activity)); recyclerViewAlerts.SetItemAnimator(new DefaultItemAnimator()); recyclerViewAlerts.SetAdapter(adapterAlerts); } } } /// <summary> /// Method Name : AlertMessage /// Author : Sanket Prajapati /// Creation Date : 24 jan 2018 /// Purpose : Show alert message /// Revision : /// </summary> public void AlertMessage(String StrErrorMessage) { AlertDialog.Builder dialog; AlertDialog alertdialog; dialog = new AlertDialog.Builder(new ContextThemeWrapper(Activity, Resource.Style.AlertDialogCustom)); alertdialog = dialog.Create(); alertdialog.SetMessage(StrErrorMessage); alertdialog.SetButton(StringResource.msgOK, (c, ev) => { alertdialog.Dispose(); }); alertdialog.Show(); } /// <summary> /// Event Name : OnTextviewActionClick /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : Set event In Calender /// Revision : /// </summary> public void OnTextviewActionClick(int position) { if (alertList.Count > 0) { AlertModel alertModel = alertList[position]; Intent intent = new Intent(Intent.ActionInsert) .SetData(Events.ContentUri) .PutExtra(CalendarContract.ExtraEventBeginTime, alertModel.StartDate.ToString()) .PutExtra(CalendarContract.ExtraEventEndTime, alertModel.EndDate.ToString()) .PutExtra(CalendarContract.Events.InterfaceConsts.Title, alertModel.AlertTitle); StartActivityForResult(intent, 101); } } } }
using BSEWalletClient.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BSEWalletClient.BAL.BSEWalletService; namespace BSEWalletClient.BAL { public class CardRepository : ICardRepository { public BSEWalletServiceClient client = null; public CardRepository() { client = new BSEWalletServiceClient(); } #region ICardRepository Members public List<Cards> Get() { try { List<Cards> cards = new List<Cards>(); if (client.Get() != null) { foreach (var card in client.Get()) { cards.Add(new Cards() { CardId = card.CardId, CardNumber = card.CardNumber, Expiry = card.Expiry, Amount = card.Amount, //IsValid = card.IsValid }); } } return cards; } catch (Exception ex) { throw ex; } return null; } #endregion public List<Cards> GetCards() { try { List<Cards> cards = new List<Cards>(); if (client.GetCards(false) != null) { foreach (var card in client.GetCards(false)) { cards.Add(new Cards() { CardId = card.CardId, CardNumber = card.CardNumber, Expiry = card.Expiry, Amount = card.Amount, //IsValid = card.IsValid }); } } return cards; } catch (Exception ex) { throw ex; } return null; } #region ICardRepository Members public void Add(Cards card, int NumofCards) { try { CardData cd = new CardData(); cd.Amount = card.Amount; cd.Expiry = card.Expiry; for (int i = 0; i < NumofCards; i++) { client.AddCards(cd); } } catch (Exception ex) { throw ex; } } #endregion } }
using BAL; using DAL; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VetOnTrack.Controllers { public class ClienteController : Controller { public IActionResult DeleteClient(int id_cliente) { Response res = ClienteBAL.DeleteClient(id_cliente); if (res.Executed) { //Retorna para a página de cadastro concluído return RedirectToAction("ClienteDeletado", "Extra"); } else { //Retorna para a página de cadastro não concluído ViewData["ErrorLog"] = res.ErrorMessage; return RedirectToAction("ClienteNaoDeletado", "Extra"); } } } }
using System; using System.Collections; using System.Collections.Generic; namespace DoubleLinkedList { class Program { static void Main(string[] args) { LinkedList list = new LinkedList(10); list.append(11); list.append(12); list.append(13); list.remove(2); for (int i = 0; i < list.printList().Count; i++) { Console.WriteLine(list.printList()[i]); } } } public class Node { public int Value { get; set; } public Node Next { get; set; } public Node Previous { get; set; } public Node(int value) { this.Value = value; this.Next = null; this.Previous = null; } } public class LinkedList { private Node head; private Node tail; private int length; public LinkedList(int value) { this.head = new Node(value); this.tail = head; // tail points to the same Node so when you change tail-Next, Head-Next will also change. this.length = 1; } public void append(int value) { Node newNode = new Node(value); newNode.Previous = this.tail; this.tail.Next = newNode; this.tail = newNode; this.length++; } public void prepend(int value) { Node newNode = new Node(value); this.head.Previous = newNode; // Node temp = this.head; newNode.Next = this.head; this.head = newNode; //this.head.Next = temp; this.length++; } public ArrayList printList() { ArrayList myAL = new ArrayList(); Node currentNode = this.head; while (currentNode != null) { myAL.Add(currentNode.Value); currentNode = currentNode.Next; } return myAL; } public Node traverse(int index) { Node currentNode = this.head; for (int count = index - 1; count > 0; count--) { currentNode = currentNode.Next; } return currentNode; } public void insert(int index, int value) { if (index > this.length) { this.append(value); return; } if (index == 0) { this.prepend(value); return; } Node pointNode = this.traverse(index); Node newNode = new Node(value); Node follower = pointNode.Next; pointNode.Next = newNode; newNode.Next = follower; newNode.Previous = pointNode; follower.Previous = newNode; this.length++; } public void remove(int index) { Node pointNode = this.traverse(index); Node unwantedNode = pointNode.Next; Node temp = unwantedNode.Next; pointNode.Next = unwantedNode.Next; temp.Previous = pointNode; this.length--; } } }
using akka_microservices_proj.Domain; namespace akka_microservices_proj.Requests { public class AddProductToBasketRequest { public long CustomerId { get; set; } public BasketProduct Product { get; set; } } }
using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; using UnityEngine.UI; using UPersian.Components; public class GameManager : MonoBehaviour { public RtlText QCount; public RtlText QnText; public RtlText Option1Text; public RtlText Option2Text; public RtlText Option3Text; public RtlText Option4Text; public GameObject Option1; public GameObject Option2; public GameObject Option3; public GameObject Option4; private ScoreManger _scoreManager; public RtlText score; private ApiDtos.Question CurrentQuestion = new ApiDtos.Question(); private List<ApiDtos.Question> Questions = new List<ApiDtos.Question>(); //private List<ApiDtos.Question> Questions = new List<ApiDtos.Question>() //{ // new ApiDtos.Question() // { // QId = 1, // Qn = "لغت ((کتاب)) به انگلیسی چه میشود ؟ ", // Option1 = "notebook", // Option2 = "book", // Option3 = "خودکار", // Option4 = "blackBorad", // Ans = 2 , // }, // new ApiDtos.Question() // { // QId = 2, // Qn = "لغت ((دفتر)) به انگلیسی چه میشود ؟ ", // Option1 = "pen", // Option2 = "blackBorad", // Option3 = "book", // Option4 = "notebook", // Ans = 4 // } // , new ApiDtos.Question() // { // QId = 3, // Qn = "لغت ((خودکار)) به انگلیسی چه میشود ؟ ", // Option1 = "book", // Option2 = "notebook", // Option3 = "pen", // Option4 = "blackboard", // Ans = 3 // } //}; private Button CurrentOptionBtn; [Header("Fonts")] public Font EnFont; public Font PeFont; [Header("Dialog")] public GameObject DialogBox; public GameObject EmptyPanel; [Header("Animations")] public Animation QAnimation; public Animation OAnimation; private void RandomQn() { var rnd = Random.Range(0, Questions.Count); CurrentQuestion = Questions[rnd]; Questions.Remove(CurrentQuestion); QCount.text = " تعداد سوالات : " + (Questions.Count + 1); } private void ShowCurrentQn() { QnText.text = CurrentQuestion.Qn; Option1Text.text = CurrentQuestion.Option1; Option2Text.text = CurrentQuestion.Option2; Option3Text.text = CurrentQuestion.Option3; Option4Text.text = CurrentQuestion.Option4; SetFont(QnText); SetFont(Option1Text); SetFont(Option2Text); SetFont(Option3Text); SetFont(Option4Text); QAnimation.Play(); OAnimation.Play(); } public void SetFont(RtlText Content) { Content.font = Regex.IsMatch(Content.text, "^[a-zA-Z]*$") ? EnFont : PeFont; } public void CheckQn(Button btn) { CurrentOptionBtn = btn; if (btn.CompareTag(CurrentQuestion.Ans.ToString())) { btn.GetComponent<Image>().color = Color.green; _scoreManager.SubmitNewScore(10); score.text = " امتیاز شما : " + _scoreManager.GetHighScore(); } else { btn.GetComponent<Image>().color = Color.red; } if (Questions.Count > 0) { Invoke("NextQn", 1); } else { DialogBox.gameObject.SetActive(true); EmptyPanel.gameObject.SetActive(true); Option1.gameObject.SetActive(false); Option2.gameObject.SetActive(false); Option3.gameObject.SetActive(false); Option4.gameObject.SetActive(false); QnText.gameObject.SetActive(false); QCount.text = " تعداد سوالات : " + 0; } } private void NextQn() { RandomQn(); ShowCurrentQn(); CurrentOptionBtn.GetComponent<Image>().color = Color.white; } // Use this for initialization void Start() { _scoreManager = FindObjectOfType<ScoreManger>(); DialogBox.gameObject.SetActive(false); EmptyPanel.gameObject.SetActive(false); StartCoroutine(GetQn()); score.text = " امتیاز شما : " + _scoreManager.GetHighScore(); } private bool temp = true; // Update is called once per frame void Update() { if (www.isDone && temp) { RandomQn(); ShowCurrentQn(); QAnimation.Play(); OAnimation.Play(); temp = false; } } private WWW www = null; public IEnumerator GetQn() { www = new WWW(ApiDtos.BASE_URL); yield return www; if (www.isDone) { Questions = JsonConvert.DeserializeObject<List<ApiDtos.Question>>(www.text); } } }
using DAL.EF; using DAL.Entities; using DAL.Interfaces; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace DAL.Repositories { public class CategoriesRepository : IRepository<Category> { private readonly ApplicationDbContext _context; public CategoriesRepository(ApplicationDbContext context) { _context = context; } public IEnumerable<Category> GetAll() { return _context.Categories.ToList(); } public Category Get(int id) { return _context.Categories.SingleOrDefault(c => c.Id == id); } public Category FindSingle(Func<Category, bool> predicate) { return _context.Categories.SingleOrDefault(predicate); } public IEnumerable<Category> FindAll(Func<Category, bool> predicate) { return _context.Categories.Where(predicate).ToList(); } public void Create(Category item) { _context.Categories.Add(item); } public void Update(Category item) { _context.Entry(item).State = EntityState.Modified; } public void Delete(int id) { var category = _context.Categories.SingleOrDefault(c => c.Id == id); if (category != null) _context.Categories.Remove(category); } } }
using System; using System.Collections.Generic; using System.Net.Mail; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data.OracleClient; namespace utilities { public class webServiceExHandling { public webServiceExHandling() { // TODO: Add constructor logic here } private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(typeof(webServiceExHandling)); public static void ExceptionLog(Exception Ex) { logger.Fatal("An Exception occured at Method Name : {0}" + Ex.TargetSite.ToString()); logger.Debug("Exception Description : {0}" + Ex.Message.ToString()); } public static void ExceptionLog(SqlException sqlEx) { logger.Fatal("An Exception occured at Method Name : {0}" + sqlEx.TargetSite.ToString()); logger.Debug("Exception Description : {0}" + sqlEx.Message.ToString()); } public static void ExceptionLog(OracleException oracleEx) { logger.Fatal("An Oracle Exception occured at Method Name : {0}" + oracleEx.TargetSite.ToString()); logger.Debug("Exception Description : {0}" + oracleEx.Message.ToString()); } public static void Send_Email(Dictionary<string,string> Mail, string strBody = "") { try { logger.Info("Method Send_Email on Exception : Start"); MailMessage mail = new MailMessage(); SmtpClient smtp = new SmtpClient(); smtp.Host = Mail["SMTPID"]; smtp.Port = Convert.ToInt32(Mail["PORT"]); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //smtp.EnableSsl = true; mail.To.Add(Mail["TO"]); mail.From = new MailAddress(Mail["FROM"]); mail.Subject = Mail["SUBJECT"]; mail.Body = strBody; smtp.Send(mail); logger.Info("Method Send_Email on Exception : Stop"); } catch (Exception mailEx) { logger.Fatal("Exception At Method : Send_Email" + mailEx.Message.ToString()); logger.Error("Method Send_Email Exception : Stop"); } } } }
/////////////////////////////////////////////////////////// // Rectangle.cs // Implementation of the Class Rectangle // Generated by Enterprise Architect // Created on: 05-???-2018 19:15:49 // Original author: Nikita Butsko /////////////////////////////////////////////////////////// public class Rectangle : Parallelogram { public Rectangle(){ } ~Rectangle(){ } public override void Dispose(){ } public abstract override void draw(); public override vector<Point> location(){ return null; } /// /// <param name="destination"></param> public abstract override void move(Point destination); }//end Rectangle
using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; /* Utility to send close-command (ctrl-c) to a child console application from another (main) console application * The actual kill signal needs to be sent from a second child console app (which is this one). * Main application starts this utility program to send the kill-signal to its child application * * Based on the solution described here: * https://stackoverflow.com/a/29274238/2373715 */ namespace ProcCtrlC { internal class Program { internal const int CTRL_C_EVENT = 0; [DllImport("kernel32.dll")] internal static extern bool GenerateConsoleCtrlEvent(uint dwCtrlEvent, uint dwProcessGroupId); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool AttachConsole(uint dwProcessId); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] internal static extern bool FreeConsole(); [DllImport("kernel32.dll")] static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add); // Delegate type to be used as the Handler Routine for SCCH delegate Boolean ConsoleCtrlDelegate(uint CtrlType); static int Main(string[] args) { //Argument is process id of the (console) application we want to kill try { CtrlC(uint.Parse(args[0])); } finally { } return 0; } internal static bool CtrlC(uint pid) { //System.Diagnostics.Debugger.Launch(); //Needs to free current console, or else Attach will not work FreeConsole(); //Attaching to target applications console (which we will send killsignal to) by process id if (AttachConsole((uint)pid)) { SetConsoleCtrlHandler(null, true); try { //Send Ctrl-C if (!GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)) return false; FreeConsole(); Thread.Sleep(2000); } finally { SetConsoleCtrlHandler(null, false); } return true; } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace xCarpaccio.client { class GrilleTaxe { Dictionary<String, decimal> grilleTaxe = new Dictionary<string, decimal>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MGL_API.Model.Saida.Game { public class RetornoListaObterGame : Retorno { public int CodigoGame { get; set; } public string NomeGame { get; set; } } }
using System; namespace CSLab02 { class My_Vector { public string Name; public int X; public int Y; public My_Vector(string name, int x, int y) { this.Name = name; this.X = x; this.Y = y; } public My_Vector() { } public static My_Vector operator +(My_Vector Name1, My_Vector Name2) { My_Vector Vec3 = new My_Vector(); string NM = Name1.Name + "+" + Name2.Name; Vec3.Name = NM; Vec3.X = Name1.X + Name2.X; Vec3.Y = Name1.Y + Name2.Y; return Vec3; } public static My_Vector operator -(My_Vector Name1, My_Vector Name2) { My_Vector Vec4 = new My_Vector(); string NM = Name1.Name + "-" + Name2.Name; Vec4.Name = NM; Vec4.X = Name1.X - Name2.X; Vec4.Y = Name1.Y - Name2.Y; return Vec4; } public static My_Vector operator *(My_Vector Name, int Num) { My_Vector Vec5 = new My_Vector(); string NM = Name.Name + "*" + Num; Vec5.Name = NM; Vec5.X = Name.X * Num; Vec5.Y = Name.Y * Num; return Vec5; } } class CSLab02 { static void Main(string[] args) { Console.WriteLine("Первый вектор.\nВведите название вектора:"); string name; while (true) { name = Console.ReadLine(); if (name.Length < 1) { Console.WriteLine("Введено пустое значение!"); Console.WriteLine("Введите название вектора:"); continue; } break; } Console.WriteLine("Введите координату X:"); int x = Convert.ToInt32(int.Parse(Console.ReadLine())); Console.WriteLine("Введите координату Y:"); int y = Convert.ToInt32(int.Parse(Console.ReadLine())); My_Vector Vec1 = new My_Vector(name, x, y); Console.WriteLine("-----------------------------------------------------------------------------------\nВторой вектор.\nВведите название вектора:"); string name1; while (true) { name1 = Console.ReadLine(); if ((String.Equals(name, name1)) || (name1.Length < 1)) { Console.WriteLine("Введённое название уже существует или введено пустое значение!"); Console.WriteLine("Введите название вектора:"); continue; } break; } Console.WriteLine("Введите координату X:"); x = Convert.ToInt32(int.Parse(Console.ReadLine())); Console.WriteLine("Введите координату Y:"); y = Convert.ToInt32(int.Parse(Console.ReadLine())); My_Vector Vec2 = new My_Vector(name1, x, y); bool menu = true; while (true) { if (menu == true) { Console.WriteLine("===================================================================================\n1. Сложить векторы."); Console.WriteLine("2. Вычесть вектор из вектора."); Console.WriteLine("3. Умножить вектор на скалярную величину."); Console.WriteLine("4. Вычислить длину вектора."); Console.WriteLine("0. Перестать биться в агонии.\n"); menu = false; } int Action = Convert.ToInt32(int.Parse(Console.ReadLine())); switch (Action) { case 1: { My_Vector Vec3 = Vec1 + Vec2; Console.WriteLine($"-----------------------------------------------------------------------------------\n Сумма векторов {name} + {name1} = Вектор " + Vec3.Name + " = " + Vec3.X + " " + Vec3.Y); menu = true; Console.WriteLine("\nНажмите любую кнопку, чтобы продолжить..."); Console.ReadKey(true); continue; } case 2: { Console.WriteLine("-----------------------------------------------------------------------------------\nВыберите вариант нахождения разности:"); Console.WriteLine($"1. {name} - {name1}"); Console.WriteLine($"2. {name1} - {name}"); while (true) { Action = Convert.ToInt32(int.Parse(Console.ReadLine())); if (Action == 1) { My_Vector Vec4 = Vec1 - Vec2; Console.WriteLine($"\nРазность векторов {name} - {name1} = Вектор " + Vec4.Name + " = " + Vec4.X + " " + Vec4.Y); break; } else if (Action == 2) { My_Vector Vec4 = Vec2 - Vec1; Console.WriteLine($"\nРазность векторов {name1} - {name} = Вектор " + Vec4.Name + " = " + Vec4.X + " " + Vec4.Y); break; } } menu = true; Console.WriteLine("\nНажмите любую кнопку, чтобы продолжить..."); Console.ReadKey(true); continue; } case 3: { Console.WriteLine("-----------------------------------------------------------------------------------\nВыберите вектор:"); Console.WriteLine($"1. {name}"); Console.WriteLine($"2. {name1}"); while (true) { Action = Convert.ToInt32(int.Parse(Console.ReadLine())); if (Action != null) { Console.WriteLine("Введите число:"); int num = Convert.ToInt32(int.Parse(Console.ReadLine())); if (Action == 1) { My_Vector Vec5 = Vec1 * num; Console.WriteLine($"Произведение вектора на скаляр \n{name} * {num} = Вектор " + Vec5.Name + " = " + Vec5.X + " " + Vec5.Y); break; } else if (Action == 2) { My_Vector Vec5 = Vec2 * num; Console.WriteLine($"Произведение вектора на скаляр \n{name1} * {num} = Вектор " + Vec5.Name + " = " + Vec5.X + " " + Vec5.Y); break; } } } menu = true; Console.WriteLine("\nНажмите любую кнопку, чтобы продолжить..."); Console.ReadKey(true); continue; } case 4: { Console.WriteLine("-----------------------------------------------------------------------------------\nВыберите вектор:"); Console.WriteLine($"1. {name}"); Console.WriteLine($"2. {name1}"); while (true) { Action = Convert.ToInt32(int.Parse(Console.ReadLine())); if (Action == 1) { double Length = Math.Sqrt(Math.Pow(Vec1.X, 2) + Math.Pow(Vec1.Y, 2)); Console.WriteLine($"\nДлина вектора {name} = " + Math.Round(Length, 2) + " ед."); break; } else if (Action == 2) { double Length = Math.Sqrt(Math.Pow(Vec2.X, 2) + Math.Pow(Vec2.Y, 2)); Console.WriteLine($"\nДлина вектора {name} = " + Math.Round(Length, 2) + " ед."); break; } } menu = true; Console.WriteLine("\nНажмите любую кнопку, чтобы продолжить..."); Console.ReadKey(true); continue; } case 0: { break; } default: { continue; } } break; } Console.WriteLine("\nНажмите любую кнопку, чтобы продолжить..."); Console.ReadKey(true); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SongManager : MonoBehaviour { public static SongManager instance; public float BPM; public float previousBeatTime = 0; public float nextBeatTime = 0; public float deltaDSPTime = 0; public AudioSource explore; public AudioSource fight; [HideInInspector]public float secondsPerBeat; float lastDSPTime = 0; public float currentDSPTime = 0; // Use this for initialization void Start () { if (instance == null) instance = this; secondsPerBeat = 60f / BPM; Debug.Log(secondsPerBeat); lastDSPTime = (float)AudioSettings.dspTime; currentDSPTime = lastDSPTime; previousBeatTime = lastDSPTime; nextBeatTime = previousBeatTime + secondsPerBeat; explore.volume = 0.3f; fight.volume = 0.0f; } // Update is called once per frame void Update () { currentDSPTime = (float)AudioSettings.dspTime; //Calculate dspDeltaTime deltaDSPTime = currentDSPTime - lastDSPTime; //Calculate next beat if (currentDSPTime >= nextBeatTime) { previousBeatTime = nextBeatTime; nextBeatTime += secondsPerBeat; } lastDSPTime = currentDSPTime; if (PlayerCombat.instance.combat) { if (explore.volume > 0f) explore.volume -= deltaDSPTime; else explore.volume = 0f; if (fight.volume < 0.3f) fight.volume += deltaDSPTime; else fight.volume = 0.3f; } else { if (explore.volume < 0.3f) explore.volume += deltaDSPTime; else explore.volume = 0.3f; if (fight.volume > 0f) fight.volume -= deltaDSPTime; else fight.volume = 0f; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Pes.Core.Impl; using Pes.Core; using StructureMap; namespace PESWeb.UserControls { public class CommentsPresenter { private IComments _view; private IWebContext _webContext; private int moreComments = -1; public int MoreComments { get { if (moreComments == -1) moreComments = Comment.CountMore(_view.SystemObjectID, _view.SystemObjectRecordID); return moreComments; } } public CommentsPresenter() { _webContext = ObjectFactory.GetInstance<IWebContext>(); } internal void Init(IComments view, bool IsPostBack) { _view = view; //if (_webContext.CurrentUser != null) // _view.ShowViewComment(true); //else // _view.ShowViewComment(false); } internal bool IsOwner(int CommentByAccountID) { return _webContext.CurrentUser.AccountID == CommentByAccountID; } internal void LoadComments() { List<Comment> list = Comment.GetTopCommentsBySystemObject(_view.SystemObjectID, _view.SystemObjectRecordID, MoreComments); if (list.Count > 0) { // _view.LoadComments(Comment.GetCommentsBySystemObject(_view.SystemObjectID, _view.SystemObjectRecordID, 3)); _view.LoadComments(list); _view.ShowViewComment(MoreComments > 0); _view.ShowCommentInput(true); } else { _view.ShowViewComment(false); _view.ShowCommentInput(false); } } internal void AddComment(string comment) { Comment c = new Comment(); c.Body = comment; c.CommentByAccountID = _webContext.CurrentUser.AccountID; c.CommentByUsername = _webContext.CurrentUser.Username; c.CreateDate = DateTime.Now; c.SystemObjectID = _view.SystemObjectID; c.SystemObjectRecordID = _view.SystemObjectRecordID; Comment.SaveComment(c); // _view.ClearComments(); // LoadComments(); } } }
namespace AIMA.Core.Logic.Propositional.Parsing { using System; using System.Collections.Generic; using AIMA.Core.Logic.Propositional.Parsing.Ast; /** * @author Ravi Mohan * */ public class AbstractPLVisitor : PLVisitor { private PEParser parser = new PEParser(); public Object visitSymbol(Symbol s, Object arg) { return new Symbol(s.getValue()); } public Object visitTrueSentence(TrueSentence ts, Object arg) { return new TrueSentence(); } public Object visitFalseSentence(FalseSentence fs, Object arg) { return new FalseSentence(); } public virtual Object visitNotSentence(UnarySentence fs, Object arg) { return new UnarySentence((Sentence)fs.getNegated().accept(this, arg)); } public virtual Object visitBinarySentence(BinarySentence fs, Object arg) { return new BinarySentence(fs.getOperator(), (Sentence)fs.getFirst() .accept(this, arg), (Sentence)fs.getSecond().accept(this, arg)); } public Object visitMultiSentence(MultiSentence fs, Object arg) { List<Sentence> terms = fs.getSentences(); List<Sentence> newTerms = new List<Sentence>(); for (int i = 0; i < terms.Count; i++) { Sentence s = (Sentence)terms[i]; Sentence subsTerm = (Sentence)s.accept(this, arg); newTerms.Add(subsTerm); } return new MultiSentence(fs.getOperator(), newTerms); } protected Sentence recreate(Object ast) { return (Sentence)parser.parse(((Sentence)ast).ToString()); } } }
using System; using System.IO; using UnityEngine; namespace RO { public class BundleLoaderStrategy { private BundleCacher _cacher = new BundleCacher(); private static string[] m_Variants = new string[0]; private static AssetBundleManifest assetBundleManifest = null; private static SDictionary<string, Object> _cacheAsset = new SDictionary<string, Object>(); private static SDictionary<string, string> _mapBundleName = new SDictionary<string, string>(); private static SDictionary<string, string[]> m_Dependencies = new SDictionary<string, string[]>(); private static SDictionary<string, string> fullAssetBundleFileName = new SDictionary<string, string>(); private static SDictionary<string, string> sceneNameMapFull = new SDictionary<string, string>(); public static string EditorRoot = "AssetBundles/"; public static string AssetsURL { get { return Application.get_persistentDataPath() + "/" + ApplicationHelper.platformFolder + "/"; } } public BundleLoaderStrategy() { this.InitManifest(); this.InitResourceIDPath(); } private void InitManifest() { this.LoadAssetBundle(ApplicationHelper.platformFolder, true); if (BundleLoaderStrategy.assetBundleManifest != null) { string[] allAssetBundles = BundleLoaderStrategy.assetBundleManifest.GetAllAssetBundles(); string text = string.Empty; for (int i = 0; i < allAssetBundles.Length; i++) { text = allAssetBundles[i]; if (!string.IsNullOrEmpty(text)) { text = Path.GetDirectoryName(text) + "/" + Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(text)); BundleLoaderStrategy.fullAssetBundleFileName[text] = allAssetBundles[i]; if (text.StartsWith("scene")) { BundleLoaderStrategy.sceneNameMapFull[Path.GetFileName(text)] = allAssetBundles[i]; } } } } } private void InitResourceIDPath() { } public void UnLoad(ResourceID ID, bool unloadAllLoadedObjects) { string empty = string.Empty; if (this.GetMappedAssetBundleName(ID, out empty, "resouces/")) { this.UnloadAssetBundle(empty, false, 999); } } public void UnLoadScene(ResourceID ID, bool unloadAllLoadedObjects = false) { string empty = string.Empty; if (this.GetMappedAssetBundleName(ID, out empty, "scene/")) { this.UnloadAssetBundle(empty, false, 999); } } public void UnLoadAll(bool unloadAllLoadedObjects) { this._cacher.UnLoadAll(unloadAllLoadedObjects, 1); Resources.UnloadUnusedAssets(); } protected void JustUnloadBundle(ResourceID ID) { string empty = string.Empty; if (this.GetMappedAssetBundleName(ID, out empty, "resouces/")) { this.UnloadAssetBundle(empty, true, 999); } } protected void UnloadAssetBundle(string assetBundleName, bool justBundle = false, int priority = 999) { this.UnloadAssetBundleInternal(assetBundleName, justBundle, priority); this.UnloadDependencies(assetBundleName, justBundle, priority); } protected void UnloadDependencies(string assetBundleName, bool justBundle = false, int priority = 999) { string[] array = null; if (!BundleLoaderStrategy.m_Dependencies.TryGetValue(assetBundleName, ref array)) { return; } string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string assetBundleName2 = array2[i]; this.UnloadAssetBundleInternal(assetBundleName2, justBundle, priority); } if (!justBundle) { BundleLoaderStrategy.m_Dependencies.Remove(assetBundleName); } } protected void UnloadAssetBundleInternal(string assetBundleName, bool justBundle = false, int priority = 999) { LoadedAssetBundle loadedAssetBundle = null; this._cacher.GetLoaded(assetBundleName, out loadedAssetBundle); if (loadedAssetBundle == null) { return; } if (!justBundle) { if (loadedAssetBundle.UnCount() <= 0) { this._cacher.UnLoad(assetBundleName, false, priority); } } else { loadedAssetBundle.TryUnloadBundle(false, priority); } } public void AsyncLoad(ResourceID ID, Action<Object> loadedHandler) { throw new NotImplementedException(); } public void AsyncLoad(ResourceID ID, Type resType, Action<Object> loadedHandler) { throw new NotImplementedException(); } public void AsyncLoad<T>(ResourceID ID, Action<Object> loadedHandler) where T : Object { throw new NotImplementedException(); } private Object TryGetLoadedAsset(ResourceID ID, string prefix = "resources/") { string key = null; if (this.GetMappedAssetBundleName(ID, out key, prefix)) { return BundleLoaderStrategy._cacheAsset[key]; } return null; } private void AddLoadedAsset(string name, Object asset) { BundleLoaderStrategy._cacheAsset[name] = asset; } public Object Load(ResourceID ID) { return this.Load(ID, string.Empty); } public Object Load(ResourceID ID, string assetName) { Object @object = null; if (string.IsNullOrEmpty(assetName)) { @object = this.TryGetLoadedAsset(ID, "resources/"); } if (@object == null) { LoadedAssetBundle loadedAssetBundle = this.InternalDynamicLoad(ID, "resources/"); if (loadedAssetBundle != null) { if (loadedAssetBundle.assetBundle != null) { AssetBundle assetBundle = loadedAssetBundle.assetBundle; if (string.IsNullOrEmpty(assetName)) { @object = ((!(assetBundle.get_mainAsset() != null)) ? assetBundle.LoadAsset(assetBundle.GetAllAssetNames()[0]) : assetBundle.get_mainAsset()); this.AddLoadedAsset(loadedAssetBundle.name, @object); this._cacher.UnLoad(loadedAssetBundle.name, false, 1); } else { loadedAssetBundle.MapAssets(); @object = loadedAssetBundle.Load(assetName); loadedAssetBundle.TryUnloadBundle(false, 1); } } else { @object = loadedAssetBundle.Load(assetName); } } } return @object; } public Object LoadScene(ResourceID ID) { LoadedAssetBundle loadedAssetBundle = this.InternalDynamicLoad(ID, "scene/"); if (loadedAssetBundle != null && loadedAssetBundle.assetBundle != null) { return loadedAssetBundle.assetBundle; } return null; } public Object Load(ResourceID ID, Type resType) { return this.Load(ID, resType, string.Empty); } public Object Load(ResourceID ID, Type resType, string assetName = null) { LoadedAssetBundle loadedAssetBundle = this.InternalDynamicLoad(ID, "resources/"); if (loadedAssetBundle == null || !(loadedAssetBundle.assetBundle != null)) { return null; } AssetBundle assetBundle = loadedAssetBundle.assetBundle; if (string.IsNullOrEmpty(assetName)) { return (!(assetBundle.get_mainAsset() != null)) ? assetBundle.LoadAsset(assetBundle.GetAllAssetNames()[0]) : assetBundle.get_mainAsset(); } return assetBundle.LoadAsset(assetName); } public T Load<T>(ResourceID ID, string assetName = null) where T : Object { Object @object = this.Load(ID, assetName); if (@object != null && @object is GameObject && typeof(T).IsSubclassOf(typeof(MonoBehaviour))) { return ((GameObject)@object).GetComponent<T>(); } return (!(@object != null)) ? ((T)((object)null)) : ((T)((object)@object)); } public TextAsset LoadScript(ResourceID ID) { return null; } public SharedLoadedAB GetSharedLoaded(string bundleName) { return null; } public void LateUpdate() { } public void Dispose() { this._cacher.UnLoadAll(true, 9999); Resources.UnloadUnusedAssets(); this._cacher = null; BundleLoaderStrategy.assetBundleManifest = null; } private LoadedAssetBundle InternalDynamicLoad(ResourceID ID, string prefix = "") { string empty = string.Empty; if (this.GetMappedAssetBundleName(ID, out empty, prefix)) { LoadedAssetBundle result; if (!this._cacher.GetLoaded(ID, out result)) { this.LoadAssetBundle(empty, false); this._cacher.GetLoaded(empty, out result); } return result; } return null; } private bool GetMappedAssetBundleName(ResourceID ID, out string path, string prefix = "resources-") { path = string.Empty; return false; } protected void LoadAssetBundle(string assetBundleName, bool isLoadingAssetBundleManifest = false) { if (!isLoadingAssetBundleManifest) { assetBundleName = this.RemapVariantName(assetBundleName); } if (!this._cacher.IsLoaded(assetBundleName) && !this._cacher.IsLoading(assetBundleName) && !isLoadingAssetBundleManifest) { this.LoadDependencies(assetBundleName); } this.LoadAssetBundleInternal(assetBundleName, isLoadingAssetBundleManifest); } protected string RemapVariantName(string assetBundleName) { string[] allAssetBundlesWithVariant = BundleLoaderStrategy.assetBundleManifest.GetAllAssetBundlesWithVariant(); if (Array.IndexOf<string>(allAssetBundlesWithVariant, assetBundleName) < 0) { return assetBundleName; } string[] array = assetBundleName.Split(new char[] { '.' }); int num = 2147483647; int num2 = -1; for (int i = 0; i < allAssetBundlesWithVariant.Length; i++) { string[] array2 = allAssetBundlesWithVariant[i].Split(new char[] { '.' }); if (!(array2[0] != array[0])) { int num3 = Array.IndexOf<string>(BundleLoaderStrategy.m_Variants, array2[1]); if (num3 != -1 && num3 < num) { num = num3; num2 = i; } } } if (num2 != -1) { return allAssetBundlesWithVariant[num2]; } return assetBundleName; } protected bool LoadAssetBundleInternal(string assetBundleName, bool isLoadingAssetBundleManifest) { if (string.IsNullOrEmpty(assetBundleName)) { return false; } LoadedAssetBundle loadedAssetBundle = null; this._cacher.GetLoaded(assetBundleName, out loadedAssetBundle); if (loadedAssetBundle != null) { loadedAssetBundle.Count(); return true; } if (this._cacher.IsLoading(assetBundleName)) { return true; } string text = BundleLoaderStrategy.AssetsURL + assetBundleName; if (File.Exists(text)) { AssetBundle assetBundle = AssetBundle.LoadFromFile(text); if (isLoadingAssetBundleManifest) { BundleLoaderStrategy.assetBundleManifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest"); } else { loadedAssetBundle = this._cacher.AddLoaded(assetBundleName, assetBundle); } } else { LoggerUnused.LogError("未找到bundle.." + text); } return false; } protected void LoadDependencies(string assetBundleName) { if (BundleLoaderStrategy.assetBundleManifest == null) { LoggerUnused.LogError("Please initialize AssetBundleManifest by calling AssetBundleManager.Initialize()"); return; } string[] allDependencies = BundleLoaderStrategy.assetBundleManifest.GetAllDependencies(assetBundleName); if (allDependencies.Length == 0) { return; } for (int i = 0; i < allDependencies.Length; i++) { allDependencies[i] = this.RemapVariantName(allDependencies[i]); } BundleLoaderStrategy.m_Dependencies[assetBundleName] = allDependencies; for (int j = 0; j < allDependencies.Length; j++) { this.LoadAssetBundleInternal(allDependencies[j], false); } } } }
using System; using UnityEngine; namespace RO { [CustomLuaClass] public class UpdateDelegate : MonoBehaviour { public Action<GameObject> listener; private void Update() { if (this.listener != null) { this.listener.Invoke(base.get_gameObject()); } } } }
using UnityEngine; using System.Collections; public class PlayerCamera : MonoBehaviour { private string updateID = "DoUpdate"; void Start () { } void LateUpdate () { gameObject.SendMessage( updateID, SendMessageOptions.DontRequireReceiver); } }
using System; using System.Linq; namespace SortStringArrayByLength { class Program { static void Main(string[] args) { string[] unsortedArray = {"Telescopes", "Glasses", "Eyes", "Monocles", "Hagass"}; string[] sortedArray = SortByLength(unsortedArray); foreach (string s in sortedArray) { Console.WriteLine(s + " "); } } /* Solution with Linq (thx Stackoverflow) * TODO: Learn LINQ which is much easier for this type of exercise */ public static string[] SortByLength(string[] array) { array = array.OrderBy(a => a.Length).ToArray(); return array; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BalayPasilungan { public partial class success : Form { public eventorg reftoevorg { get; set; } public success() { InitializeComponent(); } private void btnBack_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; } private void lblSuccess_SelectionChanged(object sender, EventArgs e) { lblSuccess.SelectionAlignment = HorizontalAlignment.Center; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RandomBackground : MonoBehaviour { [SerializeField] private Sprite[] backgroundSprites; // Start is called before the first frame update void Start() { //Randomly select a background from our list of preselected backgrounds GetComponent<SpriteRenderer>().sprite = backgroundSprites[Random.Range(0, backgroundSprites.Length)]; } }
using Discovery.Client.About.Views; using Prism.Ioc; using Prism.Modularity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Discovery.Client.About { public class AboutModule : IModule { public void OnInitialized(IContainerProvider containerProvider) { } public void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<Views.About>(); containerRegistry.RegisterForNavigation<MoreFeature>(); } } }
using System; using System.Web.Mvc; using siva.api.Filters; using System.Collections; using System.Collections.Generic; using System.Linq; using siva.api.Models; namespace siva.api.Controllers { public class GimController : BaseController { private readonly BLL.BLLGim bpGim; public GimController() { bpGim = new BLL.BLLGim(); } [SessionExpire] public ActionResult Index() { return View(); } [SessionExpire] public JsonResult PreencherReferencia(string ie) { try { var referenciasList = bpGim.RetornarReferenciaPorInscricao(ie); var lista = new ArrayList(); foreach (var item in referenciasList) { lista.Add(new { id = item.NU_REFERENCIA, text = item.NU_REFERENCIA }); } return Json(new { result = "ok", referenciasList = lista }); } catch (Exception ex) { return Json(new { ex = ex.Message }); } } [SessionExpire] public ActionResult Consultar(string ie, decimal? referencia) { try { var gimList = bpGim.RetornaGIMPorInscricaoReferencia(ie, referencia); var lista = new List<GIMReferenciaViewModel>(); foreach (var item in gimList) { lista.Add(new GIMReferenciaViewModel() { Gim = item }); } return View(lista); } catch { throw; } } [SessionExpire] public ActionResult Emitir(string ie, decimal referencia) { try { var gim = bpGim.RetornaConsultaGuiaMensal(ie, referencia); var detalhe = bpGim.RetornaConsultaGuiaMensalDetalhe(ie, referencia).ToList(); var gimviewModel = new GIMViewModel() { Gim = gim, GimDetalhe = detalhe }; return View(gimviewModel); } catch { throw; } } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace W3ChampionsStatisticService.Admin { public class Queue { public int gameMode { get; set; } public List<QueuedPlayer> snapshot { get; set; } } public class QueuedPlayer { public float mmr { get; set; } public float rd { get; set; } public QueueQuantiles quantiles { get; set; } public int queueTime { get; set; } public bool isFloConnected { get; set; } public List<PlayerQueueData> playerData { get; set; } } public class QueueQuantiles { public float quantile { get; set; } public float activityQuantile { get; set; } } public class PlayerQueueData { public string battleTag { get; set; } public FloPingData floInfo { get; set; } public string location { get; set; } public string serverOption { get; set; } } public class FloPingData { public List<FloServerPingData> floPings { get; set; } public FloClosestServerData closestNode { get; set; } } public class FloServerPingData { public int nodeId { get; set; } public int currentPing { get; set; } public int avgPing { get; set; } public int lossRate { get; set; } public int pingFilter { get; set; } } public class FloClosestServerData { public string country_id { get; set; } public int id { get; set; } public string location { get; set; } public string name { get; set; } public bool isDisabled { get; set; } public bool isCnOptimized { get; set; } } }
namespace Phonebook { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Phonebook.Command; public class CommandFactoryWithLazyLoading : ICommandFactory { private IPhonebookRepository data; private IPrinter printer; private IPhonebookSanitizer sanitizer; private IPhonebookCommand addCommand; private IPhonebookCommand changeCommand; private IPhonebookCommand listCommand; public CommandFactoryWithLazyLoading(IPhonebookRepository data, IPrinter printer, IPhonebookSanitizer sanitizer) { this.data = data; this.printer = printer; this.sanitizer = sanitizer; } public IPhonebookCommand CreateCommand(string commandName, int argumentsCount) { IPhonebookCommand command; if (commandName.StartsWith("AddPhone") && (argumentsCount >= 2)) { if (this.addCommand == null) { this.addCommand = new AddPhoneCommand(this.printer, this.data, this.sanitizer); } command = this.addCommand; } else if ((commandName == "ChangePhone") && (argumentsCount == 2)) { if (this.changeCommand == null) { this.changeCommand = new ChangePhoneCommand(this.printer, this.data, this.sanitizer); } command = this.changeCommand; } else if ((commandName == "List") && (argumentsCount == 2)) { if (this.listCommand == null) { this.listCommand = new ListPhonesCommand(this.printer, this.data); } command = this.listCommand; } else { throw new ArgumentException("Invalid command!"); } return command; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GoalScr : MonoBehaviour { [SerializeField] GameManager gm; private void Awake() { gm = GameObject.Find("GameManager").GetComponent<GameManager>(); } void Start() { } void Update() { } private void OnTriggerEnter(Collider other) { //골 오브젝트에 닿이면 골 텍스트가 나오며 게임이 정지 된다 if (other.gameObject.tag == "Player") { Player player = other.gameObject.GetComponent<Player>(); gm.GoalFunc(); Destroy(this.gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CoreComponents { public interface IReadonlyHaveName { string Name { get; } } }
using System; [CustomLuaClass] public enum DUErrorType { System, IO, Web, Response, TimeOut, MD5Error, Unknown }
using UnityEngine; using System.Collections; public enum eButtonType {Exit, NewGame, Back, Settings, Shop, Secret, Mute}; public class OnButton : MonoBehaviour { public eButtonType type; public GameObject OnClickPage; public GameObject CurrentPage; public Sprite OnMouseEnterSprite; public Sprite OnMouseExitSprite; private SpriteRenderer spriteRenderer; void Awake() { if(OnMouseExitSprite && OnMouseEnterSprite) spriteRenderer = gameObject.GetComponent<SpriteRenderer> (); if(!CurrentPage) CurrentPage = transform.parent.gameObject; } void OnDisable(){ if(spriteRenderer) spriteRenderer.sprite = OnMouseExitSprite; } void OnMouseDown(){ if (type == eButtonType.Exit) { Application.Quit (); return; } else if (type == eButtonType.Mute) { MuteMusic.Mute(); return; } pageChanger.ChangePage (CurrentPage, OnClickPage); } void OnMouseEnter() { if(spriteRenderer) spriteRenderer.sprite = OnMouseEnterSprite; } void OnMouseOver() { } void OnMouseExit() { if(spriteRenderer) spriteRenderer.sprite = OnMouseExitSprite; } }
using System; namespace CallCenter.Client.ViewModel.Helpers { public class SimpleCommand : Command<object> { public SimpleCommand(Action<object> action, Func<bool> canExecuteFunc = null) : base(action, canExecuteFunc) { } } }
using Espades.Api.Models.Base; using System; using System.ComponentModel.DataAnnotations.Schema; namespace Espades.Api.Models { public class ReservaModel : BaseModel { public int Id_Cliente { get; set; } public int Id_Produto { get; set; } public DateTime? Data_Final_Reserva { get; set; } public decimal Quantidade { get; set; } [NotMapped] public ProdutoModel Produto { get; set; } [NotMapped] public ClienteModel Cliente { get; set; } } }
using RBIScoreboard.ViewModels; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RBIScoreboard.Controls.Team { /// <summary> /// Interaction logic for LineupListView.xaml /// </summary> public partial class LineupListView : UserControl { private MainViewModel mainViewModel = new MainViewModel(); public ObservableCollection<Models.Player> Lineup { get { return (ObservableCollection<Models.Player>)GetValue(LineupProperty); } set { SetValue(LineupProperty, value); } } // Using a DependencyProperty as the backing store for Lineup. This enables animation, styling, binding, etc... public static readonly DependencyProperty LineupProperty = DependencyProperty.Register("Lineup", typeof(ObservableCollection<Models.Player>), typeof(LineupListView), new PropertyMetadata(new ObservableCollection<Models.Player>())); public LineupListView() { InitializeComponent(); this.Loaded += LineupListView_Loaded; } private void LineupListView_Loaded(object sender, RoutedEventArgs e) { mainViewModel = (MainViewModel)this.DataContext; } private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListView listView = (ListView)sender; foreach(Models.Player item in listView.Items) { item.IsSelected = false; } Models.Player player = (Models.Player) listView.SelectedItem; this.mainViewModel.CurrentAtBat.CurrentPlayerNumber = player.Number; this.mainViewModel.OutputWindow.Event.Text = String.Format("{0} {1}", player.Number, player.Name); player.IsSelected = true; } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Dependency = Fornax.Net.Lib.Dependency; namespace Fornax.Net.Util.IO { /// <summary> /// /// </summary> /// <seealso cref="System.Reflection.Assembly" /> /// <seealso cref="System.IDisposable" /> [Progress("FornaxAssembly", false, Documented = false, Tested = false)] public sealed class FornaxAssembly : Assembly, IDisposable { private static IDictionary<string, Assembly> resolvedAssemblies; private Assembly assembly; private IList<Assembly> assemblies; private static Assembly hiddenAssembly; private static string name; /// <summary> /// Gets the display name of the assembly. /// </summary> public override string FullName => assembly.FullName; /// <summary> /// Gets the name of the Assembly. /// </summary> /// <value> /// The name. /// </value> public string Name => name; /// <summary> /// Initializes a new instance of the <see cref="FornaxAssembly"/> class. /// </summary> /// <param name="_assembly">The assembly.</param> /// <exception cref="FornaxAssemblyException">_assembly</exception> public FornaxAssembly(Assembly _assembly) { Contract.Requires(_assembly != null); this.assembly = _assembly ?? throw new FornaxAssemblyException(nameof(_assembly)); name = _assembly.GetName().FullName; hiddenAssembly = this.assembly; } /// <summary> /// Initializes a new instance of the <see cref="FornaxAssembly"/> class. /// </summary> /// <param name="_assemblies">The assemblies.</param> /// <exception cref="FornaxAssemblyException">_assemblies</exception> public FornaxAssembly(IEnumerable<Assembly> _assemblies) { Contract.Requires(assemblies != null); if (_assemblies == null) throw new FornaxAssemblyException(nameof(_assemblies)); this.assemblies = _assemblies.ToList(); } /// <summary> /// Initializes a new instance of the <see cref="FornaxAssembly"/> class. /// </summary> /// <param name="assemblyBuffer">The assembly buffer.</param> public FornaxAssembly(byte[] assemblyBuffer) : this(Assembly.Load(assemblyBuffer)) { } /// <summary> /// Initializes a new instance of the <see cref="FornaxAssembly"/> class. /// </summary> /// <param name="file">The file.</param> /// <exception cref="FornaxAssemblyException"></exception> public FornaxAssembly(FileInfo file) { Contract.Requires(file != null); if (!file.Exists || file == null) throw new FornaxAssemblyException(); name = file.Name; new FornaxAssembly(LoadFrom(file.FullName)); } /// <summary> /// Initializes a new instance of the <see cref="FornaxAssembly"/> class. /// </summary> /// <param name="filename">The filename.</param> public FornaxAssembly(AssemblyName filename) : this(File.ReadAllBytes(filename.FullName)) { name = filename.FullName; } private static bool Resolve() { try { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; return true; } catch (Exception) { return false; } } private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { return LoadAssembly(name); } /// <summary> /// Tries the resolve all. /// </summary> /// <param name="_assemblies">The assemblies.</param> /// <returns></returns> public static bool TryResolveAll(Assembly[] _assemblies) { try { foreach (var item in _assemblies) { if (!TryResolve(item)) return false; } return true; } catch (Exception) { return false; } } /// <summary> /// Tries the resolve. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns></returns> public static bool TryResolve(Assembly assembly) { hiddenAssembly = assembly; return Resolve(); } /// <summary> /// Gets the assembly. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <exception cref="FornaxAssemblyException">name</exception> public static Assembly LoadAssembly(AssemblyName name) { Contract.Requires(name != null); if (name == null) throw new FornaxAssemblyException(nameof(name)); return LoadAssembly(name.FullName); } /// <summary> /// Gets the assembly. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public static Assembly LoadAssembly(string name) { if (!resolvedAssemblies.ContainsKey(name)) { using (var stream = GetExecutingAssembly().GetManifestResourceStream(name)) { byte[] temp = new byte[stream.Length]; stream.Read(temp, 0, temp.Length); var ass = Load(temp); resolvedAssemblies.Add(name, ass); return ass; } } else return resolvedAssemblies[name]; } /// <summary> /// Loads the specified temporary. /// </summary> /// <param name="temp">The temporary.</param> /// <returns></returns> public new static Assembly Load(byte[] temp) { try { return Assembly.Load(temp); } catch { return null; } } /// <summary> /// Loads all. /// </summary> /// <param name="temp">The temporary.</param> /// <returns></returns> /// <exception cref="FornaxAssemblyException"></exception> public static Assembly[] LoadAll(IEnumerable<byte[]> temp) { if (temp == null) throw new FornaxAssemblyException(); byte[][] barr = temp.ToArray(); Assembly[] assemblies = new Assembly[barr.Length]; for (int i = 0; i < assemblies.Length; i++) { assemblies[i] = Load(barr[i]); } return assemblies; } /// <summary> /// Gets the names. /// </summary> /// <param name="assemblies">The assemblies.</param> /// <returns></returns> public static IEnumerable<AssemblyName> GetNames(string[] assemblies) { var assembly_names = from dll in assemblies where (!string.IsNullOrEmpty(dll)) let dll_name = new AssemblyName(dll) select dll_name; foreach (var item in assembly_names) { yield return item; } } public static bool TryResolveAllDependencies() { return Dependency.ResolveAllDefaults(); } #region override /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } /// <summary> /// Tries the resolve. /// </summary> /// <returns></returns> public bool TryResolve() { return TryResolve(this.assembly); } /// <summary> /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. /// </summary> /// <param name="o">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object o) { return assembly.Equals(o); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { return assembly.GetHashCode(); } /// <summary> /// Gets an <see cref="T:System.Reflection.AssemblyName" /> for this assembly. /// </summary> /// <returns> /// An object that contains the fully parsed display name for this assembly. /// </returns> public override AssemblyName GetName() { return assembly.GetName(); } /// <summary> /// Gets the names. /// </summary> /// <returns></returns> public AssemblyName[] GetNames() { var assembly_names = from dll in this.assemblies where (!string.IsNullOrEmpty(dll.FullName)) select dll.GetName(); return assembly_names.ToArray(); } /// <summary> /// Gets the types defined in this assembly. /// </summary> /// <returns> /// An array that contains all the types that are defined in this assembly. /// </returns> public override Type[] GetTypes() { return assembly.GetTypes(); } #endregion /// <summary> /// Initializes the <see cref="FornaxAssembly"/> class. /// </summary> static FornaxAssembly() { resolvedAssemblies = new Dictionary<string, Assembly>(); } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_Rigidbody : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { Rigidbody o = new Rigidbody(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SetDensity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float density; LuaObject.checkType(l, 2, out density); rigidbody.SetDensity(density); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddForce(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); rigidbody.AddForce(vector); LuaObject.pushValue(l, true); result = 1; } else if (num == 3) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector2; LuaObject.checkType(l, 2, out vector2); ForceMode forceMode; LuaObject.checkEnum<ForceMode>(l, 3, out forceMode); rigidbody2.AddForce(vector2, forceMode); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Rigidbody rigidbody3 = (Rigidbody)LuaObject.checkSelf(l); float num2; LuaObject.checkType(l, 2, out num2); float num3; LuaObject.checkType(l, 3, out num3); float num4; LuaObject.checkType(l, 4, out num4); rigidbody3.AddForce(num2, num3, num4); LuaObject.pushValue(l, true); result = 1; } else if (num == 5) { Rigidbody rigidbody4 = (Rigidbody)LuaObject.checkSelf(l); float num5; LuaObject.checkType(l, 2, out num5); float num6; LuaObject.checkType(l, 3, out num6); float num7; LuaObject.checkType(l, 4, out num7); ForceMode forceMode2; LuaObject.checkEnum<ForceMode>(l, 5, out forceMode2); rigidbody4.AddForce(num5, num6, num7, forceMode2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddRelativeForce(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); rigidbody.AddRelativeForce(vector); LuaObject.pushValue(l, true); result = 1; } else if (num == 3) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector2; LuaObject.checkType(l, 2, out vector2); ForceMode forceMode; LuaObject.checkEnum<ForceMode>(l, 3, out forceMode); rigidbody2.AddRelativeForce(vector2, forceMode); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Rigidbody rigidbody3 = (Rigidbody)LuaObject.checkSelf(l); float num2; LuaObject.checkType(l, 2, out num2); float num3; LuaObject.checkType(l, 3, out num3); float num4; LuaObject.checkType(l, 4, out num4); rigidbody3.AddRelativeForce(num2, num3, num4); LuaObject.pushValue(l, true); result = 1; } else if (num == 5) { Rigidbody rigidbody4 = (Rigidbody)LuaObject.checkSelf(l); float num5; LuaObject.checkType(l, 2, out num5); float num6; LuaObject.checkType(l, 3, out num6); float num7; LuaObject.checkType(l, 4, out num7); ForceMode forceMode2; LuaObject.checkEnum<ForceMode>(l, 5, out forceMode2); rigidbody4.AddRelativeForce(num5, num6, num7, forceMode2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddTorque(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); rigidbody.AddTorque(vector); LuaObject.pushValue(l, true); result = 1; } else if (num == 3) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector2; LuaObject.checkType(l, 2, out vector2); ForceMode forceMode; LuaObject.checkEnum<ForceMode>(l, 3, out forceMode); rigidbody2.AddTorque(vector2, forceMode); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Rigidbody rigidbody3 = (Rigidbody)LuaObject.checkSelf(l); float num2; LuaObject.checkType(l, 2, out num2); float num3; LuaObject.checkType(l, 3, out num3); float num4; LuaObject.checkType(l, 4, out num4); rigidbody3.AddTorque(num2, num3, num4); LuaObject.pushValue(l, true); result = 1; } else if (num == 5) { Rigidbody rigidbody4 = (Rigidbody)LuaObject.checkSelf(l); float num5; LuaObject.checkType(l, 2, out num5); float num6; LuaObject.checkType(l, 3, out num6); float num7; LuaObject.checkType(l, 4, out num7); ForceMode forceMode2; LuaObject.checkEnum<ForceMode>(l, 5, out forceMode2); rigidbody4.AddTorque(num5, num6, num7, forceMode2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddRelativeTorque(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); rigidbody.AddRelativeTorque(vector); LuaObject.pushValue(l, true); result = 1; } else if (num == 3) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector2; LuaObject.checkType(l, 2, out vector2); ForceMode forceMode; LuaObject.checkEnum<ForceMode>(l, 3, out forceMode); rigidbody2.AddRelativeTorque(vector2, forceMode); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Rigidbody rigidbody3 = (Rigidbody)LuaObject.checkSelf(l); float num2; LuaObject.checkType(l, 2, out num2); float num3; LuaObject.checkType(l, 3, out num3); float num4; LuaObject.checkType(l, 4, out num4); rigidbody3.AddRelativeTorque(num2, num3, num4); LuaObject.pushValue(l, true); result = 1; } else if (num == 5) { Rigidbody rigidbody4 = (Rigidbody)LuaObject.checkSelf(l); float num5; LuaObject.checkType(l, 2, out num5); float num6; LuaObject.checkType(l, 3, out num6); float num7; LuaObject.checkType(l, 4, out num7); ForceMode forceMode2; LuaObject.checkEnum<ForceMode>(l, 5, out forceMode2); rigidbody4.AddRelativeTorque(num5, num6, num7, forceMode2); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddForceAtPosition(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 3) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); Vector3 vector2; LuaObject.checkType(l, 3, out vector2); rigidbody.AddForceAtPosition(vector, vector2); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector3; LuaObject.checkType(l, 2, out vector3); Vector3 vector4; LuaObject.checkType(l, 3, out vector4); ForceMode forceMode; LuaObject.checkEnum<ForceMode>(l, 4, out forceMode); rigidbody2.AddForceAtPosition(vector3, vector4, forceMode); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddExplosionForce(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 4) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float num2; LuaObject.checkType(l, 2, out num2); Vector3 vector; LuaObject.checkType(l, 3, out vector); float num3; LuaObject.checkType(l, 4, out num3); rigidbody.AddExplosionForce(num2, vector, num3); LuaObject.pushValue(l, true); result = 1; } else if (num == 5) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); float num4; LuaObject.checkType(l, 2, out num4); Vector3 vector2; LuaObject.checkType(l, 3, out vector2); float num5; LuaObject.checkType(l, 4, out num5); float num6; LuaObject.checkType(l, 5, out num6); rigidbody2.AddExplosionForce(num4, vector2, num5, num6); LuaObject.pushValue(l, true); result = 1; } else if (num == 6) { Rigidbody rigidbody3 = (Rigidbody)LuaObject.checkSelf(l); float num7; LuaObject.checkType(l, 2, out num7); Vector3 vector3; LuaObject.checkType(l, 3, out vector3); float num8; LuaObject.checkType(l, 4, out num8); float num9; LuaObject.checkType(l, 5, out num9); ForceMode forceMode; LuaObject.checkEnum<ForceMode>(l, 6, out forceMode); rigidbody3.AddExplosionForce(num7, vector3, num8, num9, forceMode); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ClosestPointOnBounds(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); Vector3 o = rigidbody.ClosestPointOnBounds(vector); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetRelativePointVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); Vector3 relativePointVelocity = rigidbody.GetRelativePointVelocity(vector); LuaObject.pushValue(l, true); LuaObject.pushValue(l, relativePointVelocity); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetPointVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); Vector3 pointVelocity = rigidbody.GetPointVelocity(vector); LuaObject.pushValue(l, true); LuaObject.pushValue(l, pointVelocity); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int MovePosition(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); rigidbody.MovePosition(vector); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int MoveRotation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Quaternion quaternion; LuaObject.checkType(l, 2, out quaternion); rigidbody.MoveRotation(quaternion); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Sleep(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); rigidbody.Sleep(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int IsSleeping(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); bool b = rigidbody.IsSleeping(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int WakeUp(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); rigidbody.WakeUp(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SweepTest(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 3) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); RaycastHit r; bool b = rigidbody.SweepTest(vector, ref r); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); LuaObject.pushValue(l, r); result = 3; } else if (num == 4) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector2; LuaObject.checkType(l, 2, out vector2); float num2; LuaObject.checkType(l, 4, out num2); RaycastHit r2; bool b2 = rigidbody2.SweepTest(vector2, ref r2, num2); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b2); LuaObject.pushValue(l, r2); result = 3; } else if (num == 5) { Rigidbody rigidbody3 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector3; LuaObject.checkType(l, 2, out vector3); float num3; LuaObject.checkType(l, 4, out num3); QueryTriggerInteraction queryTriggerInteraction; LuaObject.checkEnum<QueryTriggerInteraction>(l, 5, out queryTriggerInteraction); RaycastHit r3; bool b3 = rigidbody3.SweepTest(vector3, ref r3, num3, queryTriggerInteraction); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b3); LuaObject.pushValue(l, r3); result = 3; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SweepTestAll(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 2) { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector; LuaObject.checkType(l, 2, out vector); RaycastHit[] o = rigidbody.SweepTestAll(vector); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (num == 3) { Rigidbody rigidbody2 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector2; LuaObject.checkType(l, 2, out vector2); float num2; LuaObject.checkType(l, 3, out num2); RaycastHit[] o2 = rigidbody2.SweepTestAll(vector2, num2); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o2); result = 2; } else if (num == 4) { Rigidbody rigidbody3 = (Rigidbody)LuaObject.checkSelf(l); Vector3 vector3; LuaObject.checkType(l, 2, out vector3); float num3; LuaObject.checkType(l, 3, out num3); QueryTriggerInteraction queryTriggerInteraction; LuaObject.checkEnum<QueryTriggerInteraction>(l, 4, out queryTriggerInteraction); RaycastHit[] o3 = rigidbody3.SweepTestAll(vector3, num3, queryTriggerInteraction); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o3); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_velocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_velocity()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_velocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 velocity; LuaObject.checkType(l, 2, out velocity); rigidbody.set_velocity(velocity); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_angularVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_angularVelocity()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_angularVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 angularVelocity; LuaObject.checkType(l, 2, out angularVelocity); rigidbody.set_angularVelocity(angularVelocity); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_drag(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_drag()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_drag(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float drag; LuaObject.checkType(l, 2, out drag); rigidbody.set_drag(drag); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_angularDrag(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_angularDrag()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_angularDrag(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float angularDrag; LuaObject.checkType(l, 2, out angularDrag); rigidbody.set_angularDrag(angularDrag); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_mass(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_mass()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_mass(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float mass; LuaObject.checkType(l, 2, out mass); rigidbody.set_mass(mass); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_useGravity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_useGravity()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_useGravity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); bool useGravity; LuaObject.checkType(l, 2, out useGravity); rigidbody.set_useGravity(useGravity); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_maxDepenetrationVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_maxDepenetrationVelocity()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_maxDepenetrationVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float maxDepenetrationVelocity; LuaObject.checkType(l, 2, out maxDepenetrationVelocity); rigidbody.set_maxDepenetrationVelocity(maxDepenetrationVelocity); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_isKinematic(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_isKinematic()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_isKinematic(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); bool isKinematic; LuaObject.checkType(l, 2, out isKinematic); rigidbody.set_isKinematic(isKinematic); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_freezeRotation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_freezeRotation()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_freezeRotation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); bool freezeRotation; LuaObject.checkType(l, 2, out freezeRotation); rigidbody.set_freezeRotation(freezeRotation); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_constraints(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushEnum(l, rigidbody.get_constraints()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_constraints(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); RigidbodyConstraints constraints; LuaObject.checkEnum<RigidbodyConstraints>(l, 2, out constraints); rigidbody.set_constraints(constraints); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_collisionDetectionMode(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushEnum(l, rigidbody.get_collisionDetectionMode()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_collisionDetectionMode(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); CollisionDetectionMode collisionDetectionMode; LuaObject.checkEnum<CollisionDetectionMode>(l, 2, out collisionDetectionMode); rigidbody.set_collisionDetectionMode(collisionDetectionMode); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_centerOfMass(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_centerOfMass()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_centerOfMass(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 centerOfMass; LuaObject.checkType(l, 2, out centerOfMass); rigidbody.set_centerOfMass(centerOfMass); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_worldCenterOfMass(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_worldCenterOfMass()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_inertiaTensorRotation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_inertiaTensorRotation()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_inertiaTensorRotation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Quaternion inertiaTensorRotation; LuaObject.checkType(l, 2, out inertiaTensorRotation); rigidbody.set_inertiaTensorRotation(inertiaTensorRotation); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_inertiaTensor(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_inertiaTensor()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_inertiaTensor(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 inertiaTensor; LuaObject.checkType(l, 2, out inertiaTensor); rigidbody.set_inertiaTensor(inertiaTensor); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_detectCollisions(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_detectCollisions()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_detectCollisions(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); bool detectCollisions; LuaObject.checkType(l, 2, out detectCollisions); rigidbody.set_detectCollisions(detectCollisions); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_useConeFriction(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_useConeFriction()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_useConeFriction(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); bool useConeFriction; LuaObject.checkType(l, 2, out useConeFriction); rigidbody.set_useConeFriction(useConeFriction); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_position(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_position()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_position(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Vector3 position; LuaObject.checkType(l, 2, out position); rigidbody.set_position(position); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_rotation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_rotation()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_rotation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); Quaternion rotation; LuaObject.checkType(l, 2, out rotation); rigidbody.set_rotation(rotation); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_interpolation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushEnum(l, rigidbody.get_interpolation()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_interpolation(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); RigidbodyInterpolation interpolation; LuaObject.checkEnum<RigidbodyInterpolation>(l, 2, out interpolation); rigidbody.set_interpolation(interpolation); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_solverIterationCount(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_solverIterationCount()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_solverIterationCount(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); int solverIterationCount; LuaObject.checkType(l, 2, out solverIterationCount); rigidbody.set_solverIterationCount(solverIterationCount); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_sleepThreshold(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_sleepThreshold()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_sleepThreshold(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float sleepThreshold; LuaObject.checkType(l, 2, out sleepThreshold); rigidbody.set_sleepThreshold(sleepThreshold); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_maxAngularVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rigidbody.get_maxAngularVelocity()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_maxAngularVelocity(IntPtr l) { int result; try { Rigidbody rigidbody = (Rigidbody)LuaObject.checkSelf(l); float maxAngularVelocity; LuaObject.checkType(l, 2, out maxAngularVelocity); rigidbody.set_maxAngularVelocity(maxAngularVelocity); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.Rigidbody"); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.SetDensity)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.AddForce)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.AddRelativeForce)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.AddTorque)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.AddRelativeTorque)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.AddForceAtPosition)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.AddExplosionForce)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.ClosestPointOnBounds)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.GetRelativePointVelocity)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.GetPointVelocity)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.MovePosition)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.MoveRotation)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.Sleep)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.IsSleeping)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.WakeUp)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.SweepTest)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.SweepTestAll)); LuaObject.addMember(l, "velocity", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_velocity), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_velocity), true); LuaObject.addMember(l, "angularVelocity", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_angularVelocity), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_angularVelocity), true); LuaObject.addMember(l, "drag", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_drag), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_drag), true); LuaObject.addMember(l, "angularDrag", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_angularDrag), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_angularDrag), true); LuaObject.addMember(l, "mass", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_mass), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_mass), true); LuaObject.addMember(l, "useGravity", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_useGravity), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_useGravity), true); LuaObject.addMember(l, "maxDepenetrationVelocity", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_maxDepenetrationVelocity), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_maxDepenetrationVelocity), true); LuaObject.addMember(l, "isKinematic", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_isKinematic), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_isKinematic), true); LuaObject.addMember(l, "freezeRotation", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_freezeRotation), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_freezeRotation), true); LuaObject.addMember(l, "constraints", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_constraints), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_constraints), true); LuaObject.addMember(l, "collisionDetectionMode", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_collisionDetectionMode), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_collisionDetectionMode), true); LuaObject.addMember(l, "centerOfMass", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_centerOfMass), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_centerOfMass), true); LuaObject.addMember(l, "worldCenterOfMass", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_worldCenterOfMass), null, true); LuaObject.addMember(l, "inertiaTensorRotation", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_inertiaTensorRotation), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_inertiaTensorRotation), true); LuaObject.addMember(l, "inertiaTensor", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_inertiaTensor), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_inertiaTensor), true); LuaObject.addMember(l, "detectCollisions", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_detectCollisions), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_detectCollisions), true); LuaObject.addMember(l, "useConeFriction", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_useConeFriction), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_useConeFriction), true); LuaObject.addMember(l, "position", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_position), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_position), true); LuaObject.addMember(l, "rotation", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_rotation), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_rotation), true); LuaObject.addMember(l, "interpolation", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_interpolation), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_interpolation), true); LuaObject.addMember(l, "solverIterationCount", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_solverIterationCount), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_solverIterationCount), true); LuaObject.addMember(l, "sleepThreshold", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_sleepThreshold), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_sleepThreshold), true); LuaObject.addMember(l, "maxAngularVelocity", new LuaCSFunction(Lua_UnityEngine_Rigidbody.get_maxAngularVelocity), new LuaCSFunction(Lua_UnityEngine_Rigidbody.set_maxAngularVelocity), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Rigidbody.constructor), typeof(Rigidbody), typeof(Component)); } }
using System; namespace Decorator { class AudioDecorador : IComponente { IComponente decoramosA; public AudioDecorador(IComponente componente) { decoramosA = componente; } public override string ToString() { return $"Phone Equipo Alpine Ilx-107 Apple Carplay Exclusivo\r\n {decoramosA}"; } public double CalcularCosto() { return decoramosA.CalcularCosto() + 70500; } public string HacerFuncionar() { return decoramosA.HacerFuncionar() + " Audio encendido."; } } }
using System; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.WorkDone { public interface IWorkDoneObserver : IObserver<WorkDoneProgress>, IDisposable { ProgressToken WorkDoneToken { get; } void OnNext(string message, int? percentage, bool? cancellable); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace лаба_7 { class Flower : Plant { public struct flowerProperties { public Color color; public int price; public flowerProperties(Color color, int price) { this.color = color; this.price = price; } } flowerProperties flow = new flowerProperties(); public Color Color { get { return flow.color; } set { flow.color = value; } } public int Price { get { return flow.price; } set { flow.price = value; } } public override string GetInfo() { string str; str = $"вид: {Vid}\nвысота: {Hidth}\nЦвет: {Color}\nвозраст: {Age}\n"; return str; } public override string ToString() { return GetInfo(); } } class Flow : Flower { public string pole; public Flow() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Mogre; using MogreNewt; namespace Tachycardia { sealed class Core { public Root m_Root; public RenderWindow m_RenderWindow; public SceneManager m_SceneManager; public Camera m_Camera; public Viewport m_Viewport; public MOIS.Keyboard m_Keyboard; public MOIS.Mouse m_Mouse; public MOIS.InputManager m_InputManager; public World m_NewtonWorld; public Debugger m_NewtonDebugger; public Map m_CurrentMap; public GameCamera m_GameCamera; public ObjectManager m_ObjectManager; int m_BodyId; public const float m_FixedFPS = 60; public const float m_FixedTimeStep = 1.0f / m_FixedFPS; public float m_TimeStep; float m_TimeAccumulator; long m_LastTime; public void Initialise() { m_Root = new Root(); ConfigFile cf = new ConfigFile(); cf.Load("Resources.cfg", "\t:=", true); ConfigFile.SectionIterator seci = cf.GetSectionIterator(); while (seci.MoveNext()) { ConfigFile.SettingsMultiMap settings = seci.Current; foreach (KeyValuePair<string, string> pair in settings) ResourceGroupManager.Singleton.AddResourceLocation(pair.Value, pair.Key, seci.CurrentKey); } if (!m_Root.RestoreConfig()) if (!m_Root.ShowConfigDialog()) return; m_RenderWindow = m_Root.Initialise(true); ResourceGroupManager.Singleton.InitialiseAllResourceGroups(); m_SceneManager = m_Root.CreateSceneManager(SceneType.ST_GENERIC); m_Camera = m_SceneManager.CreateCamera("MainCamera"); m_Viewport = m_RenderWindow.AddViewport(m_Camera); m_Camera.NearClipDistance = 0.1f; m_Camera.FarClipDistance = 1000.0f; MOIS.ParamList pl = new MOIS.ParamList(); IntPtr windowHnd; m_RenderWindow.GetCustomAttribute("WINDOW", out windowHnd); pl.Insert("WINDOW", windowHnd.ToString()); m_InputManager = MOIS.InputManager.CreateInputSystem(pl); m_Keyboard = (MOIS.Keyboard)m_InputManager.CreateInputObject(MOIS.Type.OISKeyboard, false); m_Mouse = (MOIS.Mouse)m_InputManager.CreateInputObject(MOIS.Type.OISMouse, false); m_NewtonWorld = new World(); m_NewtonDebugger = new Debugger(m_NewtonWorld); m_NewtonDebugger.Init(m_SceneManager); m_GameCamera = new GameCamera(); m_ObjectManager = new ObjectManager(); } public void Update() { long currentTime = m_Root.Timer.Milliseconds; m_TimeStep = (currentTime - m_LastTime) / 1000.0f; m_LastTime = currentTime; m_TimeAccumulator += m_TimeStep; m_TimeAccumulator = System.Math.Min(m_TimeAccumulator, m_FixedTimeStep * (m_FixedFPS / 15)); m_Keyboard.Capture(); m_Mouse.Capture(); m_Root.RenderOneFrame(); while (m_TimeAccumulator >= m_FixedTimeStep) { m_TimeAccumulator -= m_FixedTimeStep; m_NewtonWorld.Update(m_FixedTimeStep); m_GameCamera.Update(); m_ObjectManager.Update(); } WindowEventUtilities.MessagePump(); } public int GetUniqueBodyId() { return m_BodyId++; } static Core instance; public void Method() { } Core() { } static Core() { instance = new Core(); } public static Core Singleton { get { return instance; } } } } //using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //namespace Tachycardia //{ // class Core // { // protected static Core Instance = null; // public static Core Singleton() // { // if (Instance == null) // Instance = new Core(); // return Instance; // } // protected Core() // { // //m_Config = null; // //!config // m_StateManager = null; // m_Root = null; // m_RenderWnd = null; // m_Viewport = null; // m_Log = null; // m_Timer = null; // m_InputMgr = null; // m_Keyboard = null; // m_Mouse = null; // m_Update = 1.0f / 120; // m_Elapsed = 0.0f; // /* // for (int i = 0; i < 256; ++i) // m_keyStates[i] = false; // */ // } // public Boolean Start() // { // //GameState.create(m_stateManager, "GameState"); // //MenuState.create(m_stateManager, "MenuState"); // //PauseState.create(m_stateManager, "PauseState"); // m_StateManager.PushState("MenuState"); // m_StateManager.Start(); // return true; // } // public Boolean Init(String wndTitle/*, skoro to static to po co przekazywac? MOIS.KeyListener.KeyPressedHandler keyListener/* = null, MOIS.MouseListener.MouseMovedHandler mouseListener = null*/) // { //#if DEBUG // m_ResourcesCfg = "../../res/resources_d.cfg"; // m_PluginsCfg = "../../res/plugins_d.cfg"; //#else // m_ResourcesCfg = "../../res/resources.cfg"; // m_PluginsCfg = "../../res/plugins.cfg"; //#endif // //m_ResourcesCfg = "../../res/resources.cfg"; // //m_luginsCfg = "../../res/plugins.cfg"; // SetupLog(); // GetLog().LogMessage("Initialize SECred Framework..."); // m_Root = new Mogre.Root(m_PluginsCfg); // if (!m_Root.ShowConfigDialog()) // { // return false; // } // m_RenderWnd = m_Root.Initialise(true, wndTitle); // //?????GetRoot().AddFrameListener(this); // SetupViewport(); // GetLog().LogMessage("ViewPort ready."); // SetupInputSystem(/*keyListener, mouseListener*/); // GetLog().LogMessage("InputSystem ready."); // SetupResources(); // GetLog().LogMessage("Resources ready."); // Mogre.TextureManager.Singleton.DefaultNumMipmaps = 5; // Mogre.ResourceGroupManager.Singleton.InitialiseAllResourceGroups(); // GetLog().LogMessage("TrayManager ready."); // m_Timer = new Mogre.Timer(); // m_Timer.Reset(); // GetLog().LogMessage("Timer ready."); // //config // //m_config = new Config( "../../res/game_config.xml" ); // GetLog().LogMessage("ConfigManager ready."); // //!config // m_StateManager = new StateManager(); // GetLog().LogMessage("StateManager ready."); // /* // //CEgui initialization // mainRenderer = &CEGUI.OgreRenderer.bootstrapSystem(); // // set the default resource groups to be used // CEGUI.Imageset.setDefaultResourceGroup((CEGUI.utf8*)"Imagesets"); // CEGUI.Font.setDefaultResourceGroup((CEGUI.utf8*)"Fonts"); // CEGUI.Scheme.setDefaultResourceGroup((CEGUI.utf8*)"Schemes"); // CEGUI.WidgetLookManager.setDefaultResourceGroup((CEGUI.utf8*)"LookNFeel"); // CEGUI.WindowManager.setDefaultResourceGroup((CEGUI.utf8*)"Layouts"); // //setup default group for validation schemas // CEGUI.XMLParser* parser = CEGUI.System.getSingleton().getXMLParser(); // if (parser->isPropertyPresent((CEGUI.utf8*)"SchemaDefaultResourceGroup")) // parser->setProperty((CEGUI.utf8*)"SchemaDefaultResourceGroup", (CEGUI.utf8*)"schemas"); // //wybranie stylu CEgui // CEGUI.SchemeManager.getSingleton().create((CEGUI.utf8*)"SECred.scheme"); // //kursor // CEGUI.System.getSingleton().setDefaultMouseCursor((CEGUI.utf8*)"SECred", (CEGUI.utf8*)"MouseArrow"); // //Tooltips - jeszcze nie wiem czy bedziemy tego uzywac // CEGUI.System.getSingleton().setDefaultTooltip((CEGUI.utf8*)"SECred/Tooltip"); // GetLog().LogMessage("CEgui has been initiliazed!"); // */ // m_RenderWnd.IsActive = true; // //MissionsCreator missions; // GetLog().LogMessage("SECred Framework initialized!"); // return true; // } // public Boolean FrameRenderingQueued(Mogre.FrameEvent evt) // { // if (m_StateManager.GetActiveState() != null) // m_StateManager.GetActiveState().UpdateFrameEvent(evt); // double time = evt.timeSinceLastFrame; // ///// Bullet time tymczasowo wyci?ty // //if( m_keyStates[OIS.KC_B] ) // // time = 0.3 * evt.timeSinceLastFrame; // //else // // time = 1.0 * evt.timeSinceLastFrame; // double tElapsed = m_Elapsed += time; // double tUpdate = m_Update; // // loop through and update as many times as necessary (up to 10 times maximum). // if ((tElapsed > tUpdate) && (tElapsed < (tUpdate * 10))) // { // while (tElapsed > tUpdate) // { // //for( std.list<TimeObserver *>.iterator it = m_TimeObservers.begin(); it != m_TimeObservers.end(); it++ ) // // (*it)->update( tUpdate ); // m_StateManager.Update(tUpdate); // tElapsed -= tUpdate; // } // } // else // { // if (tElapsed < tUpdate) // { // // not enough time has passed this loop, so ignore for now. // } // else // { // // too much time has passed (would require more than 10 updates!), so just update once and reset. // // this often happens on the first frame of a game, where assets and other things were loading, then // // the elapsed time since the last drawn frame is very long. // //for( std.list<TimeObserver *>.iterator it = m_TimeObservers.begin(); it != m_TimeObservers.end(); it++ ) // // (*it)->update( tUpdate ); // m_StateManager.Update(tUpdate); // tElapsed = 0.0f; // reset the elapsed time so we don't become "eternally behind". // } // } // Core.Singleton().m_Elapsed = tElapsed; // Core.Singleton().m_Update = tUpdate; // //wstrzykiwanie uplywu czasu do CEgui // //CEGUI.System.getSingleton().injectTimePulse(evt.timeSinceLastFrame); // return true; // } // public Boolean KeyPressed(MOIS.KeyEvent keyEventRef) // { // m_StateManager.KeyPressed(keyEventRef); // m_KeyStates[keyEventRef.key] = true; // return true; // } // public Boolean KeyReleased(MOIS.KeyEvent keyEventRef) // { // if (keyEventRef.key == MOIS.KeyCode.KC_KANJI || keyEventRef.key == MOIS.KeyCode.KC_GRAVE || keyEventRef.key == MOIS.KeyCode.KC_TAB) // /*{ // if (Console.getSingleton().isVisible()) // Console.getSingleton().hide(); // else // Console.getSingleton().show(); // }*/ // m_StateManager.KeyReleased(keyEventRef); // m_KeyStates[keyEventRef.key] = false; // return true; // } // public Boolean MouseMoved(MOIS.MouseEvent evt) // { // m_StateManager.MouseMoved(evt); // return true; // } // public Boolean MousePressed(MOIS.MouseEvent evt, MOIS.MouseButtonID id) // { // m_StateManager.MousePressed(evt, id); // return true; // } // public Boolean MouseReleased(MOIS.MouseEvent evt, MOIS.MouseButtonID id) // { // m_StateManager.MouseReleased(evt, id); // return true; // } // /*public Config GetConfig() // { // return m_Config; // }*/ // public StateManager GetStateManager() // { // return m_StateManager; // } // public Mogre.Root GetRoot() // { // return m_Root; // } // public Mogre.RenderWindow GetRenderWindow() // { // return m_RenderWnd; // } // public Mogre.Viewport GetViewport() // { // return m_Viewport; // } // public Mogre.Log GetLog() // { // return m_Log; // } // public Mogre.Timer GetTimer() // { // return m_Timer; // } // public MOIS.InputManager GetInputMgr() // { // return m_InputMgr; // } // public MOIS.Keyboard GetKeyboard() // { // return m_Keyboard; // } // public MOIS.Mouse GetMouse() // { // return m_Mouse; // } // //public CEGUI.MogreRenderer getMogreRenderer(); // public Boolean GetKeyState(MOIS.KeyCode keyCode) // { // return m_KeyStates[keyCode]; // } // private void SetupLog() // { // Mogre.LogManager logMgr = new Mogre.LogManager(); // m_Log = Mogre.LogManager.Singleton.CreateLog("OgreLogfile.log", true, true, false); // m_Log.SetDebugOutputEnabled(true); // } // private void SetupViewport() // { // m_Viewport = m_RenderWnd.AddViewport(null); // m_Viewport.BackgroundColour = new Mogre.ColourValue(0.5f, 0.5f, 0.5f, 1.0f); // } // private void SetupInputSystem(/*MOIS.KeyListener pKeyListener, MOIS.MouseListener pMouseListener//jak wczesniej static przekzywac?*/) // { // ulong hWnd = 0; // MOIS.ParamList paramList = new MOIS.ParamList(); // paramList.Insert( "WINDOW", Mogre.StringConverter.ToString(hWnd)); // m_InputMgr = MOIS.InputManager.CreateInputSystem(paramList); // m_Keyboard = (MOIS.Keyboard) m_InputMgr.CreateInputObject( MOIS.Type.OISKeyboard, true); // m_Mouse = (MOIS.Mouse)m_InputMgr.CreateInputObject(MOIS.Type.OISMouse, true); // //m_mouse.MouseState.height = m_renderWnd.height; // //m_mouse.MouseState.width = m_renderWnd.width; // //if(pKeyListener == 0) // // m_Keyboard->setEventCallback(this); // //else // // m_Keyboard->setEventCallback(pKeyListener); // //if(pMouseListener == 0) // // m_Mouse->setEventCallback(this); // //else // // m_Mouse->setEventCallback(pMouseListener); // } // private void SetupResources() // { // // Load resource paths from config file // var cf = new Mogre.ConfigFile(); // cf.Load(m_ResourcesCfg, "\t:=", true); // // Go through all sections & settings in the file // var seci = cf.GetSectionIterator(); // while (seci.MoveNext()) // { // foreach (var pair in seci.Current) // { // Mogre.ResourceGroupManager.Singleton.AddResourceLocation( // pair.Value, pair.Key, seci.CurrentKey); // } // } // /* // String secName, typeName, archName; // Mogre.ConfigFile cf; // cf.Load(m_ResourcesCfg, "", false); // Mogre.ConfigFile.SectionIterator seci = cf.GetSectionIterator(); // while (seci.HasMoreElements()) // { // secName = seci.PeekNextKey(); // Mogre.ConfigFile.SettingsMultiMap settings = seci.GetNext(); // Mogre.ConfigFile.SettingsMultiMap.Iterator i; // for (i = settings.Begin(); i != settings.End(); ++i) // { // typeName = i.Key; // archName = i.Value; // Mogre.ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName); // } // }*/ // /* // new SoundDict(); // SoundDict.Singleton().SetDirectory( "../../res/sfx/" ); // SoundDict.Singleton().LoadAndInsert( "button.wav" ); // SoundDict.Singleton().LoadAndInsert( "player/die_01.wav" ); // SoundDict.Singleton().LoadAndInsert( "impact/box_01.wav" ); // SoundDict.Singleton().LoadAndInsert( "player/jump_01.wav" ); // SoundDict.Singleton().LoadAndInsert( "player/step_concrete_01.wav" ); // SoundDict.Singleton().LoadAndInsert( "player/step_concrete_02.wav" ); // SoundDict.Singleton().LoadAndInsert( "player/step_concrete_03.wav" ); // SoundDict.Singleton().LoadAndInsert( "player/step_concrete_04.wav" ); // SoundDict.Singleton().LoadAndInsert( "player/step_concrete_05.wav" ); // SoundDict.Singleton().LoadAndInsert( "ambient/siren_01.wav" ); // SoundDict.Singleton().Init(); // */ // } // //private Config m_Config; // private StateManager m_StateManager; // private Mogre.Root m_Root; // private Mogre.RenderWindow m_RenderWnd; // private Mogre.Viewport m_Viewport; // private Mogre.Log m_Log; // private Mogre.Timer m_Timer; // private MOIS.InputManager m_InputMgr; // private MOIS.Keyboard m_Keyboard; // private MOIS.Mouse m_Mouse; // //CEgui - renderer dla CEgui // //private CEGUI.MogreRenderer mainRenderer; // private String m_ResourcesCfg; // private String m_PluginsCfg; // private Double m_Update; // private Double m_Elapsed; // private Dictionary<MOIS.KeyCode, Boolean> m_KeyStates; // } //}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.AppServices.DataContracts.TPos { /// <summary> /// /// </summary> public class TradeStatDataObject { /// <summary> /// 日期 /// </summary> public DateTime Date { get; set; } /// <summary> /// Gets the date format string. /// </summary> /// <value> /// The date format string. /// </value> public string DateFormatString { get { return Date.ToString("MM-dd"); } } /// <summary> /// 交易金额 /// </summary> public decimal TradeMoney { get; set; } /// <summary> /// 交易笔数 /// </summary> public int TradeTimes { get; set; } /// <summary> /// 交易收益 /// </summary> public decimal TradeGain { get; set; } /// <summary> /// 交易笔数 (单位:千) /// </summary> /// <value> public decimal TradeMoneyK { get { return TradeMoney / 1000; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; //NOV 17 add using statement for dependancy injection using codeRed_Capstone.Models; //Dec 5 added service for cookies using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; //Dec 5 added service for cookies using Microsoft.AspNetCore.Identity; //NOV17 IMPORTED FOR USESQLSERVER using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace codeRed_Capstone { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddRazorPages(); // cookie policy to deal with temporary browser incompatibilities //services.AddSameSiteCookiePolicy(); //services.AddDefaultAllowAllCors(); services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme, option => { option.Cookie.Name = "codeRedCookie"; // change cookie name option.ExpireTimeSpan = TimeSpan.FromDays(1); // change cookie expire time span }); //NOV17 inject dependancy services.AddDbContext<CompanyContext>(); // (options => //options.UseMySql(Configuration.GetConnectionString("XAMPPConnection"))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Employee}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; ///<summary> /// Script Manager: Denver /// Description: Handles instantiating a health bar for enemy, /// moving that health bar with enemy and moving /// it up in the hierarchy /// Date Modified: 25/10/2018 ///</summary> public class UIHealthBar : MonoBehaviour { [Tooltip("Health Bar prefab.")] [SerializeField] private GameObject m_healthBarPrefab; [Tooltip("Y axis offset of health bar.")] [SerializeField] private float m_fOffset; private EnemyActor m_enemyActor; private Image m_healthBar; private Image m_healthBarFilled; private bool m_bIsActive; void Awake() { this.enabled = false; } void Start() { // get EnemyActor m_enemyActor = GetComponent<EnemyActor>(); } // Use this for initialization void StartHealthBar () { // instantiate health bar m_healthBar = Instantiate(m_healthBarPrefab, FindObjectOfType<Canvas>().transform).GetComponent<Image>(); m_healthBarFilled = new List<Image>(m_healthBar.GetComponentsInChildren<Image>()).Find(img => img != m_healthBar); // make sure health bar is higher than other ui elements in hierarchy m_healthBar.transform.SetSiblingIndex(0); m_bIsActive = true; } void FixedUpdate () { if (m_enemyActor.m_bIsShooting && !m_bIsActive) { StartHealthBar(); } if (m_bIsActive) { // move the health bar to be slightly above gameObject on canvas m_healthBar.transform.position = Camera.main.WorldToScreenPoint(transform.position + Vector3.forward * m_fOffset); // fill bar according to enemies health m_healthBarFilled.fillAmount = (float)m_enemyActor.m_nCurrentHealth / (float)m_enemyActor.m_nHealth; } } public void DestroyHealthBar() { // destroy background Destroy(m_healthBar.gameObject); // destroy fill bar Destroy(m_healthBarFilled.gameObject); } }
using System.Collections.Generic; namespace Battleships { public class Ship { public Ship(IEnumerable<Position> positions) { Positions = positions; this.Sunk = false; } public IEnumerable<Position> Positions { get; private set; } public bool Sunk { get; set; } } }
using LogUrFace.Domain.Entities; using LogUrFace.Domain.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LogUrFace.Infrastructure.Repositories { public class DTRRepository : IDTRRepository { public DTR GetDTRFor(string employeeNumber, DateTime logDate) { using (var db = new Persistence.FaceLogContext()) { try { var dtr = db.DTRs.Include("Logs") .Where(d => d.LogDate.Equals(logDate) && d.EmployeeNumber == employeeNumber) .Single(); return dtr; } catch (Exception) { return new DTR { EmployeeNumber = employeeNumber, LogDate = logDate.Date, }; } } } public IEnumerable<DTR> GetDTRForDay(DateTime logDate) { using (var db = new Persistence.FaceLogContext()) { return db.DTRs.Include("Logs").Where(d => d.LogDate.Equals(logDate)).ToList(); } } public void Save(DTR item) { using (var db = new Persistence.FaceLogContext()) { var dtr = db.DTRs.Find(item.DTRID); if (dtr != null) { db.DTRs.Remove(dtr); db.SaveChanges(); } db.DTRs.Add(item); db.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Text; using ServiceDesk.Core.Interfaces.Common; namespace ServiceDesk.Core.Interfaces.Factories { public interface IFactoryManager<in TEntity, out TData> where TEntity : class, IEntity where TData : IFactoryData { public TFactory GetFactory<TFactory>() where TFactory : class, IGenericFactory<TEntity, TData>; } }
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.Diagnostics; namespace BackPropagation { public partial class Form1 : Form { private Network network; private TrainerIO io = new PolarToCartesianIO(); private Trainer trainer; private int totalIterations = 0; private BackgroundWorker trainingWorker = new BackgroundWorker(); public Form1() { InitializeComponent(); numNeurons.Value = io.MedialNeurons; numLayers.Value = io.Layers; numRate.Value = (decimal)io.LearningRate; ResetNetwork(); lblTrainingProgress.Text = ""; RunTest(); MinimumSize = Size; trainingWorker.WorkerReportsProgress = true; trainingWorker.WorkerSupportsCancellation = true; trainingWorker.DoWork += trainingWorker_DoWork; trainingWorker.ProgressChanged += trainingWorker_ProgressChanged; trainingWorker.RunWorkerCompleted += trainingWorker_RunWorkerCompleted; } private void trainingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { lblTrainingProgress.Text = "Training: " + (totalIterations + e.ProgressPercentage).ToString(); } private void trainingWorker_DoWork(object sender, DoWorkEventArgs e) { int iterations = (int)numTrainingSize.Value; lineGraph.SetData(trainer.Train(iterations, trainingWorker, chPrintData.Checked)); totalIterations += iterations; } private void trainingWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { RunTest(); } private void btnTrain_Click(object sender, EventArgs e) { if (!trainingWorker.IsBusy) { trainingWorker.RunWorkerAsync(); } } private void btnReset_Click(object sender, EventArgs e) { ResetNetwork(); } private void numR_ValueChanged(object sender, EventArgs e) { RunTest(); } private void numTheta_ValueChanged(object sender, EventArgs e) { numTheta.Value = Math.Min(numTheta.Value, (decimal)(Math.PI * 0.25)); RunTest(); } private void RunTest() { double[] inputs = new double[] { (double)numR.Value, (double)numTheta.Value }; double[] outputs = network.GetOutput(inputs); double[] expected = io.GetExpectedOutput(inputs); lblResult.Text = String.Format("x = {0:0.00000} y = {1:0.00000}", outputs[0], outputs[1]); lblActual.Text = String.Format("x = {0:0.00000} y = {1:0.00000}", expected[0], expected[1]); double errorX = (outputs[0] - expected[0]) / expected[0]; double errorY = (outputs[1] - expected[1]) / expected[1]; lblErrors.Text = String.Format("E(x) = {0:P1}, E(y) = {1:P1}, ET = {2:P1}", errorX, errorY, Math.Sqrt(Math.Pow(errorX, 2) + Math.Pow(errorY, 2))); } private void ResetNetwork() { network = new Network(io.Inputs, io.Outputs, (int)numNeurons.Value, (int)numLayers.Value); trainer = new Trainer(network, io); trainer.LearningRate = (double)numRate.Value; totalIterations = 0; lblTrainingProgress.Text = ""; lineGraph.SetData(null); lineGraph.Refresh(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IMoveState { void OperateEnter(Rigidbody2D _rb2d, Transform _transform, float _speed); void OperateUpdate(Rigidbody2D _rb2d, Transform _transform, float _speed); void OperateExit(Rigidbody2D _rb2d, Transform _transform, float _speed); } class IMoveState_Static : IMoveState { public void OperateEnter(Rigidbody2D _rb2d = null, Transform _transform = null, float _speed = 0) { Debug.Log($"Start: Static State"); } public void OperateExit(Rigidbody2D _rb2d = null, Transform _transform = null, float _speed = 0) { Debug.Log($"Stop: Static State"); } public void OperateUpdate(Rigidbody2D _rb2d = null, Transform _transform = null, float _speed = 0) { } } class IMoveState_MoveToDestination : IMoveState { public void OperateEnter(Rigidbody2D _rb2d, Transform _destination, float _speed) { } public void OperateExit(Rigidbody2D _rb2d, Transform _destination, float _speed) { } public void OperateUpdate(Rigidbody2D _rb2d, Transform _destination, float _speed) { Vector2 destination = (_destination.position - _rb2d.transform.position); _rb2d.MovePosition(_rb2d.position + (destination * _speed * Time.deltaTime)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Door : MonoBehaviour { private void Teleport() { if (!StageManager.PlayerInStage) StageManager.Instance.PlayerTeleportToStage(); else { StageManager.Instance.PlayerTeleportToBonusRoom(transform.position); gameObject.SetActive(false); } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.CompareTag(TagManager.PlayerTag)) GameManager.Instance.input.activeCallback += Teleport; } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.CompareTag(TagManager.PlayerTag)) GameManager.Instance.input.activeCallback -= Teleport; } }
using UnityEngine; using System.Collections; public class FinalScoreController : MonoBehaviour { private int _finalScore; //public GameController gameController; public int FinalScore { get { return this._finalScore; } set { this._finalScore = value; } } // Use this for initialization void Start () { //this._finalScore = this.gameController.FinalScore; } // Update is called once per frame void Update () { } }
namespace MonoGame.Extended.Particles.Modifiers { public interface IModifier { void Update(float elapsedSeconds, ParticleBuffer.ParticleIterator iterator); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AugmentedReality.Models { class GeoPath : GeoPoint { public List<GeoPoint> Path { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading.Tasks; namespace GlobalModels { /// <summary> /// Facillitates passing of notifications. /// </summary> /// <value></value> public class DiscussionNotification { public string Imdbid { get; set; } public string Usernameid { get; set; } public string Discussionid { get; set; } public DiscussionNotification(string movieid, string userid, string discussionid) { Imdbid = movieid; Usernameid = userid; Discussionid = discussionid; } public DiscussionNotification() { } } }
using System; using ReadyGamerOne.Common; using UnityEngine; namespace ReadyGamerOne.Script { public class KeyToMessage : UnityEngine.MonoBehaviour { public KeyCode key; public string message; private void Update() { if (Input.GetKeyDown(key)) CEventCenter.BroadMessage(message); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoursIngesup.Class2 { class StreamWriters { public void Write(string s) { string[] lines = { "Coucou1", "Coucou2", "Coucou3" }; string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //Crée un fichier using (StreamWriter outputFile = new StreamWriter(mydocpath + @"\WriteLines.txt")) { foreach (string line in lines) outputFile.WriteLine(line); } //Ajoute à un fichier using (StreamWriter outputFile = new StreamWriter(mydocpath + @"\WriteLines.txt", true)) { foreach (string line in lines) outputFile.WriteLine(line); } } } }
#region Header /* This file is part of NDoctor. NDoctor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NDoctor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with NDoctor. If not, see <http://www.gnu.org/licenses/>. */ #endregion Header namespace Probel.NDoctor.View.Toolbox.Logging { using System; using System.Collections.Generic; using System.Linq; using System.Text; using log4net; using log4net.Appender; using log4net.Core; using Probel.Helpers.Events; using Probel.Mvvm.DataBinding; /// <summary> /// This appender insert all log events into a WPF UI item /// </summary> public sealed class WpfAppender : AppenderSkeleton { #region Fields /// <summary> /// Gets a read-only snapshot of the recorded events /// currently stored in the buffer. /// The returned collection contains the events /// in the same order as they have been appended. /// </summary> private readonly List<LogEvent> RecordedEvents = new List<LogEvent>(); #endregion Fields #region Methods /// <summary> /// Registers the specified displayer. /// </summary> /// <param name="displayer">The displayer.</param> /// <param name="log">The log.</param> public static IEnumerable<LogEvent> GetLogs(ILog log) { WpfAppender recorder = log.Logger.Repository.GetAppenders().OfType<WpfAppender>().Single(); return recorder.RecordedEvents; } /// <summary> /// Append the logging event into the configured Log Displayer. /// If no log displayer is configured, it does nothing /// </summary> /// <param name="loggingEvent">The event to append.</param> protected override void Append(LoggingEvent loggingEvent) { var @event = new LogEvent() { LoggerName = loggingEvent.LoggerName, TimeStamp = loggingEvent.TimeStamp, ThreadName = loggingEvent.ThreadName, LevelName = loggingEvent.Level.Name, Message = loggingEvent.RenderedMessage, ExeptionMessage = (loggingEvent.ExceptionObject != null) ? loggingEvent.ExceptionObject.ToString() : string.Empty }; this.RecordedEvents.Add(@event); } #endregion Methods } }
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class StartScript : MonoBehaviour { // Use this for initialization void Start () { SceneManager.LoadScene("GameScene"); } void Update () { if (SceneManager.GetSceneByName ("GameScene").isLoaded && SceneManager.GetSceneByName("StartScene").isLoaded) { SceneManager.UnloadScene ("StartScene"); Destroy (gameObject); } } }