text
stringlengths
13
6.01M
using Microsoft.AspNet.Identity.EntityFramework; using RimLiqourProject.Models; using System.ComponentModel.DataAnnotations; using System.Data.Entity; namespace NewRimLiqourProject.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { } public DbSet<Customer> Customers { get; set; } public System.Data.Entity.DbSet<RimLiqourProject.Models.Products> Products { get; set; } // public System.Data.Entity.DbSet<RimLiqourProject.Models.Order> Orders { get; set; } // public System.Data.Entity.DbSet<NewRimLiqourProject.Models.RegisterViewModel> RegisterViewModels { get; set; } public System.Data.Entity.DbSet<Cart2> Cart { get; set; } public System.Data.Entity.DbSet<OrderDetails> OrderDetails { get; set; } //public System.Data.Entity.DbSet<SFD.Model.CartItemViewModel> CartItemViewModels { get; set; } // public System.Data.Entity.DbSet<SFD.Model.CartItemViewModel> CartItemViewModels { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EX_6C_Inheritance_Weapons { class Program { static void Main(string[] args) { Console.WriteLine("Firing Small weapon: "); SmallCaliberWeapon myHandgun = new SmallCaliberWeapon(); myHandgun.Handgunload(); myHandgun.StartFiring("Fire in the hole"); Console.WriteLine("\nFiring Artillery"); InDirectFireMethod myArtillery = new InDirectFireMethod(); myArtillery.Howitzerload(); myArtillery.StartFiring("Take Cover"); Console.WriteLine("\nFiring Missiles"); DirectFireMethod myHellfire = new DirectFireMethod(); myHellfire.Hellfireload(); myHellfire.StartFiring("Warheads on Foreheads"); Console.WriteLine("\nTesting polymorphism"); Weapon w = myHandgun; w.Fire(); w = myArtillery; w.Fire(); w = myHellfire; w.Fire(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TransferData.DataAccess; using TransferData.DataAccess.Entity.Mapping; namespace TransferData.Business.MappingMasterData { public class MappingCarModelLogic { private static IList<MappingCarModel> dataCache; public IList<MappingCarModel> DataCache { get { if (dataCache != null) { return dataCache; } dataCache = GetInternal(); return dataCache; } } //Get all data from Nodes table private IList<MappingCarModel> GetInternal() { //_logger.Debug("GetNodesInternal"); try { var req = new Repository<MappingCarModel>(_context); return req.GetQuery().ToList(); } catch (Exception e) { //_logger.Error("GetUsableInterfaceTypesInternal exception:{0}", e.ToString()); return new List<MappingCarModel>(); } } private string _insurerID = ""; MyContext _context = null; public MappingCarModelLogic(string insurerID) { _insurerID = insurerID; _context = new MyContext(Configurator.CrmSqlConnection); } public MappingCarModelLogic(string insurerID, MyContext context) { _insurerID = insurerID; _context = context; } public string GetByClaimDiKey(string key) { MappingCarModel result = (from data in DataCache where data.ClaimDiID == key select data).FirstOrDefault(); if (result == null) return ""; if (_insurerID.Equals(Service.ClaimDiBikeAPI.InsurerID.SEIC, StringComparison.OrdinalIgnoreCase)) { return result.SEICID; } return ""; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class SwordItem : Collectable { public int itemID = 5; override protected void OnCollect(GameObject target) { var equipBehavior = target.GetComponent<Equip>(); if (equipBehavior != null) { equipBehavior.currentItem = itemID; } var attackBehavior = target.GetComponent<Attack>(); if (attackBehavior != null) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CEMAPI.Models { public class FailInfo { public int listcount { get; set; } public int errorcode { get; set; } public string errormessage { get; set; } public string exceptionMessage { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControls : MonoBehaviour { private MovingEntity m_movingEntity; private AttackingEntity m_attackingEntity; private SynchronizedActor m_actor; private LevelBuilder m_levelBuilder; private bool m_myTurn; private GameObject m_crosshair; private Texture2D cursor; public Texture2D AimCursor { get { if (cursor == null) cursor = Resources.Load<Texture2D>("Graphics/aim"); return cursor; } } // Use this for initialization void Start() { m_movingEntity = GetComponent<MovingEntity>(); m_attackingEntity = GetComponent<AttackingEntity>(); m_actor = GetComponent<SynchronizedActor>(); m_levelBuilder = FindObjectOfType<LevelBuilder>(); m_actor.OnTurnStatusChange += actor_OnTurnStatusChange; } public event Action OnPlayerMovedToEndEvent = null; public event Action OnPlayerMovedToObjectiveEvent = null; private void actor_OnTurnStatusChange(bool hasTurn) { if (hasTurn) Debug.Log("Player gained turn"); else { Debug.Log("Player Turn End"); } m_myTurn = hasTurn; } // Update is called once per frame void Update() { if (m_myTurn) { World.Cell mouseOverCell = GetMouseOverCell(); if (mouseOverCell != null && mouseOverCell.ContainsEntity) { ApplyLOS(); int x, y; Entity ent = mouseOverCell.GetEntity(); ent.GetPosition(out x, out y); if (!"Player".Equals(ent.GetType().ToString()) && ent.GetCell().IsVisible()) SetCrosshair(x, y); else HideCrosshair(); if (Input.GetMouseButtonDown(0)) { AttackingEntity.AttackResult res = CombatSolver.Fight(m_actor, mouseOverCell.GetEntity().Actor); if (res != null && res.Weapon != null) { Synchronizer.Continue(m_actor, res.Weapon.TimeCost); return; } else if (res.Result == AttackingEntity.AttackResult.ResultValue.NoEnergy) Debug.Log(res.Weapon.Name+" Out of energy"); } } else { HideCrosshair(); } Vector2 move = Vector2.zero; if (Input.GetButtonDown("Horizontal")) { float h = Input.GetAxis("Horizontal"); move.x = Mathf.Sign(h); } if (Input.GetButtonDown("Vertical")) { float h = Input.GetAxis("Vertical"); move.y = Mathf.Sign(h); } if (move != Vector2.zero) { //Debug.Log("Move: " + move); MovingEntity.MoveResult result = m_movingEntity.Move(move); switch (result.Result) { case MovingEntity.MoveResult.ResultValue.Ok: Synchronizer.Continue(m_actor, m_movingEntity.moveActionCost); if (m_levelBuilder.LevelType != LevelType.Ambush) { if (m_levelBuilder.EndPoint.X == result.Cell.X && m_levelBuilder.EndPoint.Y == result.Cell.Y) { if (OnPlayerMovedToEndEvent != null) { OnPlayerMovedToEndEvent(); } } if(m_levelBuilder.ObjectivePoint.X == result.Cell.X && m_levelBuilder.ObjectivePoint.Y == result.Cell.Y) { if(OnPlayerMovedToObjectiveEvent != null) { OnPlayerMovedToObjectiveEvent(); } } } break; case MovingEntity.MoveResult.ResultValue.TileBlocked: //Debug.Log("Tile blocked!"); break; case MovingEntity.MoveResult.ResultValue.TileOccupied: AttackingEntity.AttackResult res = CombatSolver.Fight(m_actor, result.Cell.GetEntity().Actor); Synchronizer.Continue(m_actor, res.Weapon.TimeCost); break; } } } } private World.Cell GetMouseOverCell() { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { int x = (int)(hit.point.x + 0.5); int y = (int)(hit.point.y + 0.5); int z = (int)(hit.point.z + 0.5); Vector3 loc = new Vector3(x, y, z); //Debug.Log(loc); World.Cell cell = World.Instance.GetGrid().GetCell((int)loc.x, (int)loc.z); return cell; } return null; } private void SetCrosshair(int x, int y) { Cursor.SetCursor(AimCursor, new Vector2(64, 64), CursorMode.Auto); //if (m_crosshair == null) // m_crosshair = GameObject.CreatePrimitive(PrimitiveType.Sphere); //m_crosshair.transform.position = new Vector3(x, 2, y); //m_crosshair.SetActive(true); //return m_crosshair; } private void HideCrosshair() { //if (m_crosshair != null) // m_crosshair.SetActive(false); Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto); } private void ApplyLOS() { World.Cell[,] grid = World.Instance.GetGrid().GetCells(); int x, y; Synchronizer.Instance.Player.Entity.GetPosition(out x, out y); List<SynchronizedActor> actors = Synchronizer.Instance.GetActors(); bool skipfirst = true; foreach (SynchronizedActor a in actors) { if (skipfirst) { skipfirst = false; } else { int xe, ye; a.Entity.GetPosition(out xe, out ye); float xd = xe - x; float yd = ye - y; bool visible = true; if (Math.Abs(xd) < Math.Abs(yd)) { float d = 0.0f; for (int i = 0; i < Math.Abs(yd); i++) { int xc = (xd < 0 ? -i : i) + x; d += xd / yd; int yc = (int)d + y; World.Cell c = grid[xc, yc]; if (c.IsBlocked) { visible = false; break; } } } else { float d = 0.0f; for (int i = 0; i < Math.Abs(xd); i++) { int yc = (yd < 0 ? -i : i) + y; d += yd / xd; int xc = (int)d + x; World.Cell c = grid[xc, yc]; if (c.IsBlocked) { visible = false; break; } } } grid[xe, ye].SetVisible(visible); } } } }
using ContentPatcher.Framework.Conditions; using ContentPatcher.Framework.ConfigModels; using ContentPatcher.Framework.Tokens; using ContentPatcher.Framework.Tokens.Json; using StardewModdingAPI; namespace ContentPatcher.Framework.Migrations { /// <summary>Migrates patches to a given format version.</summary> internal interface IMigration { /********* ** Accessors *********/ /// <summary>The format version to which this migration applies.</summary> ISemanticVersion Version { get; } /********* ** Public methods *********/ /// <summary>Migrate a content pack.</summary> /// <param name="content">The content pack data to migrate.</param> /// <param name="error">An error message which indicates why migration failed.</param> /// <returns>Returns whether migration succeeded.</returns> bool TryMigrate(ContentConfig content, out string error); /// <summary>Migrate a token name.</summary> /// <param name="name">The token name to migrate.</param> /// <param name="error">An error message which indicates why migration failed (if any).</param> /// <returns>Returns whether migration succeeded.</returns> bool TryMigrate(ref TokenName name, out string error); /// <summary>Migrate a tokenised string.</summary> /// <param name="tokenStr">The tokenised string to migrate.</param> /// <param name="error">An error message which indicates why migration failed (if any).</param> /// <returns>Returns whether migration succeeded.</returns> bool TryMigrate(TokenString tokenStr, out string error); /// <summary>Migrate a tokenised JSON structure.</summary> /// <param name="tokenStructure">The tokenised JSON structure to migrate.</param> /// <param name="error">An error message which indicates why migration failed (if any).</param> /// <returns>Returns whether migration succeeded.</returns> bool TryMigrate(TokenisableJToken tokenStructure, out string error); } }
using System; using System.Collections.Generic; using System.Text; namespace Shuffle_Deck { class Deck_Manipulation: Random { static List<string> shuffled_Deck = new List<string>(); static List<string> deck = new List<string>(); static StringBuilder sb = new StringBuilder(); static Random rand = new Random(); static string card; static int number; static int random; public static List<string> create_Starting_Deck(List<string> faces, List<string> suits) { foreach (string s in suits) { foreach(string s_1 in faces) { sb.Clear(); sb.Append(s_1); sb.Append(" of "); sb.Append(s); card = sb.ToString(); deck.Add(card); } } return deck; } public static List<string> shuffle_Deck(List<string> unshuffled_Deck) { number = unshuffled_Deck.Count; while(shuffled_Deck.Count < 52) { random = rand.Next(number); if (shuffled_Deck.Contains(unshuffled_Deck[random])) { goto cont; } else { shuffled_Deck.Add(unshuffled_Deck[random]); } cont:; } return shuffled_Deck; } } }
namespace qbq.EPCIS.Repository.Custom.Entities { class EpcisEventSourceDestination { //----------------------------------------------------------------- //-- Tabelle zum Zwischenspeichern der SourceDestination //----------------------------------------------------------------- //create table #EPCISEvent_SourceDestination //( //EPCISEventID bigint not null, //IsSource bit not null, //SourceDestinationURN nvarchar(512) not null, //SourceDestinationTypeURN nvarchar(512) not null, //SourceDestinationID bigint null, //SourceDestinationTypeID bigint null, //); public long EpcisEventId { get; set; } public bool IsSource { get; set; } public string SourceDestinationUrn { get; set; } public string SourceDestinationTypeUrn { get; set; } public long SourceDestinationId { get; set; } public long SourceDestinationTypeId { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace slashGame { public partial class setupUI : Form { public Form1 f1Parent = null; IPAddress myIp = null; // TcpClient myClient = null; TcpListener tcpListener = null; //IPAddress slaveIp; TcpClient myClient = null; int defport = 32767; public setupUI() { InitializeComponent(); try { var myHost = Dns.GetHostEntry(Dns.GetHostName()); var host = Dns.GetHostEntry(Dns.GetHostName()); foreach(var ip in host.AddressList) { if(ip.AddressFamily == AddressFamily.InterNetwork) { myIp = ip; } } } catch(System.Exception err) { System.Diagnostics.Debug.Print(err.Message); myIp = null; }; } private void setupUI_Load(object sender, EventArgs e) { this.toolStripStatusLabel1.Text = myIp.ToString() + ":" + defport; this.textBox1.Text = myIp.ToString() + ":" + defport.ToString(); } private void button3_Click(object sender, EventArgs e) { Clipboard.SetText(this.toolStripStatusLabel1.Text); } private void button2_Click(object sender, EventArgs e) { if(int.TryParse(this.tbListenPort.Text, out SelectedListenPort)) { Thread t = new Thread(new ThreadStart(ListenThread)); t.Start(); } } public int SelectedListenPort; public void ListenThread() { // Create an instance of the TcpListener class. if(tcpListener != null) return; try { // Set the listener on the local IP address // and specify the port. tcpListener = new TcpListener(myIp, SelectedListenPort); tcpListener.Start(); // this.textBox2.Invoke( // new MethodInvoker(delegate // { // // Show the current time in the form's title bar. // this.textBox2.Text += (DateTime.Now.ToLongTimeString() + "\r\n"); // })); } catch(Exception e) { System.Diagnostics.Debug.Print(e.Message); // this.textBox2.Invoke( // new MethodInvoker(delegate // { // // Show the current time in the form's title bar. // this.textBox2.Text += e.Message + "\r\n"; // })); } while(true) { if(this.IsDisposed) break; Thread.Sleep(10); // Create a TCP socket. // If you ran this server on the desktop, you could use // Socket socket = tcpListener.AcceptSocket() // for greater flexibility. var c = tcpListener.AcceptTcpClient(); var rs = c.GetStream(); int trycount = 0; while(!rs.DataAvailable && trycount++ < 10) System.Threading.Thread.Sleep(100); System.IO.StreamReader sr = new System.IO.StreamReader(rs); var s = sr.ReadLine(); for(int i = 0; i < s.Length; i++) { KeyEventArgs MyKey = new KeyEventArgs(Keys.D); if(f1Parent != null) { f1Parent.keyDownListener(null, MyKey); System.Threading.Thread.Sleep(50); f1Parent.keyUpListener(null, MyKey); } } } } int SelectedPort; IPAddress SelectedIP; private void buttonConnect_Click(object sender, EventArgs e) { var parse = this.textBox1.Text.Split(':'); if(parse.Length != 2 || !int.TryParse(parse[1], out SelectedPort) || !IPAddress.TryParse(parse[0], out SelectedIP)) return; myClient = new System.Net.Sockets.TcpClient(); try { myClient.Connect(SelectedIP, SelectedPort); if(myClient.Connected) { this.Text = "Conected to " + SelectedIP.ToString() + ":" + SelectedPort.ToString(); var sw = new System.IO.StreamWriter(myClient.GetStream()); sw.WriteLine("Message from ..." + System.Diagnostics.Process.GetCurrentProcess().Id); sw.Flush(); //myClient.Close(); } } catch(System.Exception err) { // this.textBox1.Text = err.Message + "\r\n"; System.Diagnostics.Debug.Print(err.Message); } } } }
using ShopApp.Entities; using System; using System.Collections.Generic; using System.Text; namespace ShopApp.Business.Abstract { public interface IAddressService { Address GetById(int id); IEnumerable<Address> GetByUserId(string id); void Create(Address entity); void Update(Address entity); void Delete(Address entity); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovementBob : MonoBehaviour { public float walkingBobbingSpeed = 14f; public float bobbingAmount = 0.05f; public float timeOffset = 0f; public CharacterController controller; protected float startYPos = 0f; protected float timer = 0f; private void Start() { startYPos = transform.localPosition.y; } private void Update() { if (Mathf.Abs(controller.velocity.x) > 0.1f || Mathf.Abs(controller.velocity.z) > 0.1f) { // Player is moving timer += Time.deltaTime * walkingBobbingSpeed; transform.localPosition = new Vector3(transform.localPosition.x, startYPos + Mathf.Sin(timer) * bobbingAmount, transform.localPosition.z); } else { // Player is idle timer = 0 + timeOffset; transform.localPosition = new Vector3(transform.localPosition.x, Mathf.Lerp(transform.localPosition.y, startYPos, Time.deltaTime * walkingBobbingSpeed), transform.localPosition.z); } } }
using Alabo.Domains.Dtos; using Alabo.Domains.Entities; using Alabo.Domains.UnitOfWork; using Alabo.Validations.Aspects; using System.Threading.Tasks; namespace Alabo.Domains.Services.Add { /// <summary> /// 创建操作 /// </summary> public interface IAddAsync<TEntity, in TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> { /// <summary> /// 创建 /// </summary> /// <param name="request">创建参数</param> [UnitOfWork] Task<string> AddAsync<TRequest>([Valid] TRequest request) where TRequest : IRequest, new(); /// <summary> /// 添加实体,异步 /// </summary> /// <param name="entity">实体</param> Task AddAsync([Valid] TEntity entity); } }
using System; using System.IO; using System.Threading.Tasks; using XamarinConfig.Configuration; namespace XamarinConfig.iOS.Configuration { public class IOSConfigurationStreamProvider : IConfigurationStreamProvider { private const string ConfigurationFilePath = "Assets/config.json"; private Stream _readingStream; public Task<Stream> GetStreamAsync() { ReleaseUnmanagedResources(); _readingStream = new FileStream(ConfigurationFilePath, FileMode.Open, FileAccess.Read); return Task.FromResult(_readingStream); } private void ReleaseUnmanagedResources() { _readingStream?.Dispose(); _readingStream = null; } public void Dispose() { ReleaseUnmanagedResources(); GC.SuppressFinalize(this); } ~IOSConfigurationStreamProvider() { ReleaseUnmanagedResources(); } } }
// // TorrentException.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2006 Alan McGovern using System; namespace ResumeEditor.Torrents { [Serializable] public class TorrentException : Exception { public TorrentException() : base() { } public TorrentException(string message) : base(message) { } public TorrentException(string message, Exception innerException) : base(message, innerException) { } public TorrentException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Validation; using System.Linq; using System.Security.Claims; using System.Web.Mvc; using BradescoPGP.Common; using BradescoPGP.Common.Logging; using BradescoPGP.Repositorio; using BradescoPGP.Web.Models; namespace BradescoPGP.Web.Controllers { [Authorize] public class UsuarioController : AbstractController { private readonly PGPEntities _context; public UsuarioController(DbContext context) : base(context) { _context = context as PGPEntities; } public ActionResult Index() { if (!User.IsInRole(NivelAcesso.Master.ToString())) { return View("Error", new ErrorViewModel { Endereco = Url.Action("Index", "Usuario", null, Request.Url.Scheme), Mensagem = "Você não tem permissão para acessar esta página!", Status = "401 - Não autorizado" }); } ViewBag.Titulo = "Perfil"; return View(_context.Usuario.ToList()); } public ActionResult Perfil(string matricula) { ViewBag.Titulo = "Perfil"; var claimsIdentity = ((ClaimsIdentity)User.Identity); var matriculaUsuarioLogado = claimsIdentity.FindFirst("matricula").Value; var usuario = default(Usuario); var usuarioAdmin = User.IsInRole(NivelAcesso.Master.ToString()); var usuarios = _context.Usuario.Select(u => new UsuarioViewModel { UsuarioId = u.UsuarioId, Matricula = u.Matricula, Equipe = u.Equipe, Perfil = u.Perfil, NomeUsuario = u.NomeUsuario, Nome = u.Nome, }).ToList(); if (string.IsNullOrWhiteSpace(matricula)) { usuario = _context.Usuario.FirstOrDefault(u => u.Matricula.ToLower() == matriculaUsuarioLogado.ToLower()); if (usuarioAdmin) { ViewBag.usuarios = usuarios; ViewBag.equipes = usuarios.Select(u => u.Equipe).Distinct(); } } else if (usuarioAdmin) { usuario = _context.Usuario.FirstOrDefault(u => u.Matricula == matricula); ViewBag.equipes = usuarios.Select(u => u.Equipe).Distinct(); ViewBag.usuarios = usuarios; } if (usuario != null) { var viewModel = new UsuarioViewModel { UsuarioId = usuario.UsuarioId, Matricula = usuario.Matricula, Equipe = usuario.Equipe, MatriculaSupervisor = usuario.MatriculaSupervisor, //TipoUsuario = usuario.TipoUsuario, Perfil = usuario.Perfil, NomeUsuario = usuario.NomeUsuario, Nome = usuario.Nome, NomeSupervisor = usuario.NomeSupervisor, ReceberNotificacaoEvento = usuario.NotificacaoEvento, ReceberNotificacaoPipeline = usuario.NotificacaoPipeline }; return View(viewModel); } //var linksCapInv = GetLinksCapInvest(); //ViewBag.LinksCap = linksCapInv.FirstOrDefault(l => l.Titulo == "CapLiq").Url; //ViewBag.LinksInvest = linksCapInv.FirstOrDefault(l => l.Titulo == "Invest").Url; return RedirectToAction("Index", "Home"); } public ActionResult Detalhes(string matricula) { if (!User.IsInRole(NivelAcesso.Master.ToString())) { return View("Error", new ErrorViewModel { Endereco = Url.Action("Detalhes", "Usuario", null, Request.Url.Scheme), Mensagem = "Você não tem permissão para acessar esta página!", Status = "401 - Não autorizado" }); } if (matricula == null) { ViewBag.error = "Desculpe, não foi possível executar esta ação!"; return View("Perfil"); } var usuario = _context.Usuario.FirstOrDefault(u => u.Matricula == matricula); if (usuario == null) { ViewBag.error = "Desculpe, não foi possível executar esta ação!"; Log.Error($"Usuário não encontrado, matrícula: {matricula}!"); return View("Perfil"); } var viewModel = new UsuarioViewModel { UsuarioId = usuario.UsuarioId, Matricula = usuario.Matricula, Equipe = usuario.Equipe, MatriculaSupervisor = usuario.MatriculaSupervisor, ReceberNotificacaoEvento = usuario.NotificacaoEvento, ReceberNotificacaoPipeline = usuario.NotificacaoPipeline, Perfil = usuario.Perfil, NomeUsuario = usuario.NomeUsuario, Nome = usuario.Nome, NomeSupervisor = usuario.NomeSupervisor }; //var linksCapInv = GetLinksCapInvest(); //ViewBag.LinksCap = linksCapInv.FirstOrDefault(l => l.Titulo == "CapLiq")?.Url; //ViewBag.LinksInvest = linksCapInv.FirstOrDefault(l => l.Titulo == "Invest")?.Url; ViewBag.Titulo = "Detalhe"; return View("Detalhes", viewModel); } public ActionResult Novo() { if (!User.IsInRole(NivelAcesso.Master.ToString())) { return View("Error", new ErrorViewModel { Endereco = Url.Action("Novo", "Usuario", null, Request.Url.Scheme), Mensagem = "Você não tem permissão para acessar esta página!", Status = "401 - Não autorizado" }); } var dadosUsuarios = _context.Usuario.ToList(); var supervisores = dadosUsuarios .Where(u => u.NomeSupervisor.ToLower() != "bradesco" && (u.PerfilId == 1 || u.PerfilId == 2)) .Distinct() .OrderBy(u => u.Nome) .ToDictionary(k => k.Nome, v => v.Matricula); //var supervisores = dadosUsuariosSupervisores; ViewData["Perfil"] = new SelectList(_context.Perfil.ToList().OrderBy(p => p.Descricao), "PerfilId", "Descricao"); ViewBag.Equipes = dadosUsuarios.Select(u => u.Equipe).Distinct().ToList().ConvertAll(e => new SelectListItem { Text = e.ToUpper(), Value = e }); ViewData["Supervisores"] = new SelectList(supervisores.Keys.ToList()); ViewData["Matriculas"] = supervisores; //var linksCapInv = GetLinksCapInvest(); //ViewBag.LinksCap = linksCapInv.FirstOrDefault(l => l.Titulo == "CapLiq")?.Url; //ViewBag.LinksInvest = linksCapInv.FirstOrDefault(l => l.Titulo == "Invest")?.Url; ViewBag.Titulo = "Perfil - Novo usuario"; return View(); } // POST: Usuario/Novo // Para se proteger de mais ataques, ative as propriedades específicas a que você quer se conectar. Para // obter mais detalhes, consulte https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] public ActionResult Novo([Bind(Include = "Nome,Matricula,NomeSupervisor,MatriculaSupervisor,Equipe,NomeUsuario,PerfilId,TipoUsuario")] UsuarioViewModel model) { if (!User.IsInRole(NivelAcesso.Master.ToString())) { return View("Error", new ErrorViewModel { Endereco = null, Mensagem = "Você não tem permissão para acessar esta página!", Status = "401 - Não autorizado" }); } if (ModelState.IsValid) { try { var usuario = new Usuario { NomeUsuario = model.NomeUsuario, Equipe = model.Equipe, Matricula = model.Matricula, MatriculaSupervisor = model.MatriculaSupervisor, Nome = model.Nome, NomeSupervisor = model.NomeSupervisor, PerfilId = model.PerfilId, NotificacaoEvento = true, NotificacaoPipeline = true //,TipoUsuario = model.TipoUsuario }; _context.Usuario.Add(usuario); _context.SaveChanges(); return RedirectToAction("Perfil"); } catch (Exception ex) { ViewBag.error = "Desculpe, não foi possível executar esta ação!"; Log.Error($"Erro ao cadastrar novo usuário, matrícula: {model.Matricula}!", ex); ViewData["Perfil"] = new SelectList(_context.Perfil.ToList(), "PerfilId", "Descricao"); return View(model); } } ViewData["Perfil"] = new SelectList(_context.Perfil.ToList(), "PerfilId", "Descricao"); return View(model); } public ActionResult ExportarExcel() { var excel = default(byte[]); var usuarios = _context.Usuario.ToList(); excel = GerarExcel(usuarios.ConvertAll(u => UsuariosExportExcel.Mapear(u)), "Hierarquias"); var nomeArquivo = "Hierarquias.xlsx"; return File(excel, System.Net.Mime.MediaTypeNames.Application.Octet, nomeArquivo); } public ActionResult Editar(string matricula) { if (!User.IsInRole(NivelAcesso.Master.ToString())) { return View("Error", new ErrorViewModel { Endereco = Url.Action("Editar", "Usuario", null, Request.Url.Scheme), Mensagem = "Você não tem permissão para acessar esta página!", Status = "401 - Não autorizado" }); } if (matricula == null) { ViewBag.error = "Desculpe, não foi possível carregar os dados!"; return View(); } var dadosUsuarios = _context.Usuario.ToList(); var supervisoresMatricula = dadosUsuarios.Where(s => s.NomeSupervisor != "Bradesco" && (s.PerfilId == 1 || s.PerfilId == 2)) .Distinct() .OrderBy(u => u.Nome) .ToDictionary(k => k.Nome, v => v.Matricula); var usuario = dadosUsuarios.FirstOrDefault(u => u.Matricula == matricula); if (usuario == null) { ViewBag.error = "Desculpe, não foi possível executar esta ação!"; Log.Error($"Usuário não encontrado, matrícula: {matricula}!"); return View("Perfil"); } var viewModel = new UsuarioViewModel { UsuarioId = usuario.UsuarioId, Matricula = usuario.Matricula, Equipe = usuario.Equipe, MatriculaSupervisor = usuario.MatriculaSupervisor, //TipoUsuario = usuario.TipoUsuario, Perfil = usuario.Perfil, PerfilId = usuario.PerfilId, NomeUsuario = usuario.NomeUsuario, Nome = usuario.Nome, NomeSupervisor = usuario.NomeSupervisor }; ViewData["Perfis"] = _context.Perfil.OrderBy(p => p.Descricao).ToList(); ViewData["Equipes"] = dadosUsuarios.Select(s => s.Equipe).Distinct().ToList(); ViewData["Supervisores"] = supervisoresMatricula.Keys.ToList(); /*dadosUsuarios.Select(s => s.NomeSupervisor).Distinct().Where(s => s != "Bradesco").ToList();*/ ViewData["Matriculas"] = supervisoresMatricula; ViewBag.Titulo = "Perfil - Editar Usuario"; //var linksCapInv = GetLinksCapInvest(); //ViewBag.LinksCap = linksCapInv.FirstOrDefault(l => l.Titulo == "CapLiq")?.Url; //ViewBag.LinksInvest = linksCapInv.FirstOrDefault(l => l.Titulo == "Invest")?.Url; return View(viewModel); } [HttpPost] public ActionResult Editar([Bind(Include = "UsuarioId,Matricula,NomeUsuario,Nome,NomeSupervisor,MatriculaSupervisor,Equipe,TipoAcesso,PerfilId")] Usuario usuario) { if (!User.IsInRole(NivelAcesso.Master.ToString())) { return View("Error", new ErrorViewModel { Endereco = null, Mensagem = "Você não tem permissão para acessar esta página!", Status = "401 - Não autorizado" }); } if (ModelState.IsValid) { try { var local = _context.Usuario.Local.FirstOrDefault(u => u.UsuarioId == usuario.UsuarioId); if (local != null) { _context.Entry(local).State = EntityState.Detached; } var entry = _context.Entry(usuario); entry.State = EntityState.Modified; entry.Property(u => u.Matricula).IsModified = false; entry.Property(u => u.NomeUsuario).IsModified = false; _context.SaveChanges(); if (MatriculaUsuario == usuario.Matricula) return RedirectToAction("Logoff", "Conta"); else return RedirectToAction("Perfil"); } catch (DbEntityValidationException ex) { var errosmessage = ObterValidationErros(ex); Log.Error($"ValidationErros: {string.Join(Environment.NewLine, errosmessage)}"); Log.Error($"Erro ao editar usuário, matrícula: {usuario.Matricula}!", ex); return View("Error", new ErrorViewModel { Endereco = null, Mensagem = "Houve um erro inesperado ao editar este usuario, contate o administrador.", Status = "500 - Erro interno" }); } catch(Exception ex) { Log.Error($"Erro ao editar usuário, matrícula: {usuario.Matricula}!", ex); return View("Error", new ErrorViewModel { Endereco = null, Mensagem = "Houve um erro inesperado ao editar este usuario, contate o administrador.", Status = "500 - Erro interno" }); } } return View(usuario); } private List<string> ObterValidationErros(DbEntityValidationException e) { var errosList = new List<string>(); var errosmessage = ""; foreach (var eve in e.EntityValidationErrors) { errosmessage += $"Entidade do tipo \"{eve.Entry.Entity.GetType().Name}\" no estado \"{eve.Entry.State}\" tem os seguintes erros de validação:\n"; foreach (var ve in eve.ValidationErrors) { errosmessage += $"Property: \"{ve.PropertyName}\", Erro: \"{ve.ErrorMessage}\""; } errosList.Add(errosmessage); } return errosList; } public ActionResult Deletar(string matricula) { if (!User.IsInRole(NivelAcesso.Master.ToString())) { return View("Error", new ErrorViewModel { Endereco = null, Mensagem = "Você não tem permissão para executar esta ação!", Status = "401 - Não autorizado" }); } if (matricula == null) { ViewBag.error = "Desculpe, não foi possível executar esta ação!"; return RedirectToAction("Perfil"); } var usuario = _context.Usuario.FirstOrDefault(u => u.Matricula == matricula); if (usuario == null) { ViewBag.error = "Desculpe, não foi possível executar esta ação!"; Log.Error($"Usuário não encontrado, matrícula: {matricula}!"); return RedirectToAction("Perfil"); } try { _context.Usuario.Remove(usuario); _context.SaveChanges(); return RedirectToAction("Perfil"); } catch (Exception ex) { Log.Error($"Erro ao deletar o usuário, matrícula: {matricula}!", ex); ViewBag.error = "Desculpe, não foi possível executar esta ação!"; return View("Perfil"); } } [HttpPost] public ActionResult Pesquisa(string nome, string equipe) { var usuarios = default(List<Usuario>); if (!string.IsNullOrWhiteSpace(nome) && !string.IsNullOrWhiteSpace(equipe)) { usuarios = _context.Usuario.Where(u => u.Nome.ToLower().Contains(nome) && u.Equipe.ToLower().Contains(equipe)).ToList(); } else if (!string.IsNullOrWhiteSpace(nome)) { usuarios = _context.Usuario.Where(u => u.Nome.ToLower().Contains(nome)).ToList(); } else if (!string.IsNullOrWhiteSpace(equipe)) { usuarios = _context.Usuario.Where(u => u.Equipe.ToLower().Contains(equipe)).ToList(); } if (string.IsNullOrWhiteSpace(nome) && string.IsNullOrWhiteSpace(equipe)) { usuarios = _context.Usuario.ToList(); } ViewBag.usuarios = usuarios.Select(u => new UsuarioViewModel { UsuarioId = u.UsuarioId, Matricula = u.Matricula, Equipe = u.Equipe, //MatriculaSupervisor = u.MatriculaSupervisor, //TipoUsuario = usuario.TipoUsuario, Perfil = u.Perfil, NomeUsuario = u.NomeUsuario, Nome = u.Nome, //NomeSupervisor = u.NomeSupervisor }).ToList(); ViewBag.equipes = _context.Usuario.Select(u => u.Equipe).Distinct().ToList(); var claimsIdentity = ((ClaimsIdentity)User.Identity); var matriculaUsuarioLogado = claimsIdentity.FindFirst("matricula").Value; var usuario = _context.Usuario.FirstOrDefault(u => u.Matricula == matriculaUsuarioLogado); var viewModel = new UsuarioViewModel { UsuarioId = usuario.UsuarioId, Matricula = usuario.Matricula, Equipe = usuario.Equipe, MatriculaSupervisor = usuario.MatriculaSupervisor, //TipoUsuario = usuario.TipoUsuario, Perfil = usuario.Perfil, NomeUsuario = usuario.NomeUsuario, Nome = usuario.Nome, NomeSupervisor = usuario.NomeSupervisor }; ViewData["filtro"] = new FiltroUsuario { //Nome = nome, Equipe = equipe }; return View("Perfil", viewModel); } [HttpPost] public ActionResult ReceberNotificacao(bool valor, string notificacao) { var usuario = _context.Usuario.FirstOrDefault(u => u.Matricula == MatriculaUsuario); if (notificacao == Noticacoes.Evento.ToString()) usuario.NotificacaoEvento = valor; else if (notificacao == Noticacoes.Pipeline.ToString()) usuario.NotificacaoPipeline = valor; try { _context.SaveChanges(); } catch (Exception) { return Json(new { success = false, error = true, message = "Erro ao salvar alterações." }); } return Json(new { success = true, error = false, message = "Cadatramento feito com sucesso" }); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using WebAPI.Helpers; using WebAPI.Services.Base; namespace WebAPI.Controllers { public class BaseController : ControllerBase { protected ActionResult<APIResponseWrapper<T>> APIResponse<T>(T result, ValidationResult validationResult, int failureStatusCode = StatusCodes.Status500InternalServerError) { return InternalAPIResponse<T>(result, validationResult, failureStatusCode); } private ActionResult<APIResponseWrapper<T>> InternalAPIResponse<T>(object result, ValidationResult validationResult, int failureStatusCode = StatusCodes.Status500InternalServerError) { var apiResponse = new APIResponseWrapper<T>(); if (!validationResult.IsValid) { apiResponse.Errors = validationResult.Errors; HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; } else if (result == null) { HttpContext.Response.StatusCode = StatusCodes.Status404NotFound; } else { HttpContext.Response.StatusCode = StatusCodes.Status200OK; if (result is T data) { apiResponse.Data = data; } } return apiResponse; } } }
using System; using System.Collections.Generic; using DelftTools.Functions.Generic; using NUnit.Framework; namespace DelftTools.Functions.Tests.Conversion { [TestFixture] public class ConvertedArrayTest { [Test] public void TestConvertedArray() { IMultiDimensionalArray<int> intArray = new MultiDimensionalArray<int>(new List<int> { 1, 2, 3, 4, 5 }, new[] { 5 }); IMultiDimensionalArray<string> stringArray = new ConvertedArray<string, int>(intArray, Convert.ToInt32, Convert.ToString); Assert.AreEqual(intArray.Shape, stringArray.Shape); Assert.AreEqual("1", stringArray[0]); //assignment on the converted array are passed to the source stringArray.Add("30"); Assert.AreEqual(30, intArray[5]); intArray.Add(31); Assert.AreEqual("31", stringArray[6]); } [Test] public void ToString() { var source = new MultiDimensionalArray<int>(new List<int> { 1, 2, 3, 4, 5, 6 }, new[] { 2, 3 }); var target = new ConvertedArray<string, int>(source, Convert.ToInt32, Convert.ToString); Assert.AreEqual("{{1, 2, 3}, {4, 5, 6}}", target.ToString()); } } }
using System.CodeDom.Compiler; namespace Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution { [GeneratedCode("wsdl", "2.0.50727.42")] public delegate void GetExecutionInfo3CompletedEventHandler(object sender, GetExecutionInfo3CompletedEventArgs e); }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Xlns.BusBook.Core.Model; namespace Xlns.BusBook.UI.Web.Models { public class ListFlyerView { public Agenzia agenzia; public IList<Flyer> flyers; } }
using BS; using System; using UnityEngine; namespace BlinkSpell { public class Spell_Blink : Spell { SpellCasterHand spellCasterHand; public override void Load(SpellData.Instance spellDataInstance, SpellCasterHand handCaster) { spellCasterHand = handCaster; base.Load(spellDataInstance, handCaster); } public override void Fire(bool active) { // Just experimenting if (!spellCasterHand.caster.currentMidSpell) DoSpell(); else AimSpell(); //base.Fire(active); } public override void Unload() { base.Unload(); } public void Teleport() { //spellCasterHand.bodyHand.body.player } public void AimSpell() { } public void DoSpell() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShowMeDateClient { class Program { static void Main(string[] args) { ShowMeDateBusiness.ShowMeDateBusiness date = new ShowMeDateBusiness.ShowMeDateBusiness(); Console.WriteLine(date.GetDate()); Console.ReadLine(); } } }
using System.Data.Entity.ModelConfiguration; using ODL.DomainModel.Common; namespace ODL.DataAccess.Mappningar { public class MetadataMappning : ComplexTypeConfiguration<Metadata> { public MetadataMappning() { Property(m => m.UppdateradDatum).HasColumnName("UppdateradDatum"); Property(m => m.UppdateradAv).HasMaxLength(10).HasColumnName("UppdateradAv").IsUnicode(false); Property(m => m.SkapadDatum).IsRequired().HasColumnName("SkapadDatum"); Property(m => m.SkapadAv).IsRequired().HasMaxLength(10).HasColumnName("SkapadAv").IsUnicode(false); } } }
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 PegususDemo.View { public partial class Reports : Form { public Reports() { InitializeComponent(); } private void BunifuFormFadeTransition1_TransitionEnd(object sender, EventArgs e) { } private void BunifuThinButton21_Click(object sender, EventArgs e) { } private void Reports_Load(object sender, EventArgs e) { } private void BunifuThinButton21_Click_1(object sender, EventArgs e) { } private void ComboBox2_SelectedIndexChanged(object sender, EventArgs e) { } private void Label6_Click(object sender, EventArgs e) { } private void BunifuGradientPanel1_Paint(object sender, PaintEventArgs e) { } private void TextBox1_OnValueChanged(object sender, EventArgs e) { } private void Label4_Click(object sender, EventArgs e) { } } }
using System.Collections.Generic; using System.Linq; using System.Threading; namespace com.Sconit.Entity { public class MessageHolder { private static ThreadLocal<IList<Message>> messages = new ThreadLocal<IList<Message>>(); public static IList<Message> GetAll() { return messages.Value; } public static void CleanMessage() { messages.Value = new List<Message>(); } public static void AddMessage(Message message) { DoAddMessage(message); } public static void AddErrorMessage(string messageKey) { Message message = new Message(CodeMaster.MessageType.Error, messageKey, null); DoAddMessage(message); } public static void AddErrorMessage(string messageKey, params string[] messageParams) { Message message = new Message(CodeMaster.MessageType.Error, messageKey, messageParams); DoAddMessage(message); } public static void AddInfoMessage(string messageKey) { Message message = new Message(CodeMaster.MessageType.Info, messageKey, null); DoAddMessage(message); } public static void AddInfoMessage(string messageKey, params string[] messageParams) { Message message = new Message(CodeMaster.MessageType.Info, messageKey, messageParams); DoAddMessage(message); } public static void AddWarningMessage(string messageKey) { Message message = new Message(CodeMaster.MessageType.Warning, messageKey, null); DoAddMessage(message); } public static void AddWarningMessage(string messageKey, params string[] messageParams) { Message message = new Message(CodeMaster.MessageType.Warning, messageKey, messageParams); DoAddMessage(message); } public static bool HasInfoMessages() { if (messages.Value != null) { return GetInfoMessages().Count > 0; } else { return false; } } public static bool HasWarningMessages() { if (messages.Value != null) { return GetWarningMessages().Count > 0; } else { return false; } } public static bool HasErrorMessages() { if (messages.Value != null) { return GetErrorMessages().Count > 0; } else { return false; } } public static IList<Message> GetInfoMessages() { if (messages.Value != null) { return messages.Value.Where(m => m.MessageType == CodeMaster.MessageType.Info).ToList(); } else { return null; } } public static IList<Message> GetWarningMessages() { if (messages.Value != null) { return messages.Value.Where(m => m.MessageType == CodeMaster.MessageType.Warning).ToList(); } else { return null; } } public static IList<Message> GetErrorMessages() { if (messages.Value != null) { return messages.Value.Where(m => m.MessageType == CodeMaster.MessageType.Error).ToList(); } else { return null; } } private static void DoAddMessage(Message message) { if (messages.Value == null) { messages.Value = new List<Message>(); } messages.Value.Add(message); } } }
using SalaryCalculator; using SalaryCalculator.TaxPlans; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SalaryCalculatorTests { /// <summary> /// Summary description for IrelandTests /// </summary> [TestClass] public class CaymanIslandsTests { [TestMethod] public void CaymanIslandsTaxPlanGetGrossSalaryTest() { Assert.AreEqual(25000, Calculator.GetGrossSalary(250, 100)); Assert.AreEqual(2840.48m, Calculator.GetGrossSalary(17.753m, 160)); } [TestMethod] public void CaymanIslandsTaxPlanGetNetSalaryTests() { CaymanIslandsTaxPlan citp = new CaymanIslandsTaxPlan(); Assert.AreEqual(25000, Calculator.GetNetSalary(100, 250, citp)); Assert.AreEqual(2840.48m, Calculator.GetNetSalary(17.753m, 160, citp)); } } }
using System; using System.Collections.Generic; using System.Text; namespace Hayaa.SecurityController.Model { public class UserAuthReponse { /// <summary> /// 会话标识 /// </summary> public String SessionToken { set; get; } } }
using UnityEngine; public interface IOption { string name { get; set; } GameObject controlObj { get; set; } void setupControlObj(GameObject obj); /// <summary> /// Applies the option's value to game. This makes the option /// take effect. /// </summary> void applyValue(); /// <summary> /// Writes the option's value to disk. /// </summary> void write(); /// <summary> /// Reads the option's value from disk. /// </summary> void read(); }
using System; using System.Data.SqlClient; using System.Management; using System.Net.NetworkInformation; using System.Windows.Forms; namespace POS.Classes { class Authorize { static public bool AuthorizeComputer() { return AuthorizeCridentials(GetUniqueKey()); } static private bool AuthorizeCridentials(string IDMBADMAKIDCP) { try { Connection cn = new Connection(); return (cn.chekIfAlreadyExist("SELECT *FROM AUTHORIZE WHERE IDMBADMAKIDCP='" + IDMBADMAKIDCP + "'")); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return false; } static public bool chekIfAlreadyExist(string query) { try { SqlConnection cn = new SqlConnection("Server=tcp:licensekeys.database.windows.net,1433;Initial Catalog=LICENSE;Persist Security Info=False;User ID=infinitydevs;Password=03027203844Qf@;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"); cn.Open(); SqlCommand cmd = new SqlCommand(query, cn); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) if (dr.HasRows == true) { dr.Close(); return true; } dr.Close(); cn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return false; } static public bool AddLicenseKey(string key) { try { SqlConnection cn = new SqlConnection("Server=tcp:licensekeys.database.windows.net,1433;Initial Catalog=LICENSE;Persist Security Info=False;User ID=infinitydevs;Password=03027203844Qf@;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"); cn.Open(); Connection mycon = new Connection(); if(chekIfAlreadyExist("SELECT *FROM LICENSEKEY WHERE STATUS='YES' AND KEYS='" + key + "'")) { MessageBox.Show("This License Key Already Has Been Used. Contact Infinity Devs To Buy A License Key.", "License Key Expired", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if(chekIfAlreadyExist("SELECT *FROM LICENSEKEY WHERE STATUS='NOT' AND KEYS='" + key + "'")) { mycon.ExecuteQuery("INSERT INTO AUTHORIZE VALUES('" + key + "','" + GetUniqueKey() + "')"); new SqlCommand("UPDATE LICENSEKEY SET STATUS='YES' , USEROF='" + Environment.UserName + "' WHERE KEYS='"+key+"'",cn).ExecuteNonQuery(); MessageBox.Show("You've registred infinity devs POS successfully!\nUse username : emp and password : 123 for first use", "Registered Successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information); return true; } else { MessageBox.Show("You've entered a worng license key! Contact Infinity Devs To Buy A License Key.", "Wrong License Key", MessageBoxButtons.OK, MessageBoxIcon.Stop); } cn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return false; } static private string GetMotherBoardID() { try { ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard"); ManagementObjectCollection moc = mos.Get(); string motherBoard = ""; foreach (ManagementObject mo in moc) { motherBoard = (string)mo["SerialNumber"]; } return motherBoard; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return null; } static private string GetProcessorID() { try { var mbs = new ManagementObjectSearcher("Select ProcessorID From Win32_processor"); var mbsList = mbs.Get(); string cpuid=null; foreach (ManagementObject mo in mbsList) { cpuid = mo["ProcessorID"].ToString(); } return cpuid; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return null; } static private string GetMacAddress() { string macAddresses = string.Empty; try { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus == OperationalStatus.Up) { macAddresses += nic.GetPhysicalAddress().ToString(); break; } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return macAddresses; } static private string GetUniqueKey() { return GetMotherBoardID() + GetMacAddress() + GetProcessorID(); } } }
using System; using System.Collections.Generic; namespace PizzeriaApi.Models { public partial class Ciasto { public int IdCiasta { get; set; } public string Nazwa { get; set; } public int CenaCiasta { get; set; } } }
using CQRS.MediatR.Event; namespace Scheduler.MailService.Events { public class MailHasBeenSent: IEvent { public string From { get; } public string Recipient { get; } public string Title { get; } public MailHasBeenSent(string from, string recipient, string title) { From = @from; Recipient = recipient; Title = title; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IBLLService { public partial interface IBLLSession { IWeChat_MANAGER IWeChat_MANAGER { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UseFul.Uteis { public static class UltimoDiaMes { public static DateTime RetornaDia(DateTime dt) { return new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InfoSign : MonoBehaviour { private void OnEnable() { transform.Find("Canvas").gameObject.SetActive(false); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { transform.Find("Canvas").gameObject.SetActive(true); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.CompareTag("Player")) { transform.Find("Canvas").gameObject.SetActive(false); } } }
using System; using Tomelt.ContentManagement; using Tomelt.Events; namespace Tomelt.Autoroute.Services { public interface IRouteEvents : IEventHandler { void Routed(IContent content, String path); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace KartLib { /// <summary> /// Класс, расширяющий работу с сообщениями /// </summary> public static class ExtMessageBox { /// <summary> /// Выводит сообщение об ошибке /// </summary> /// <param name="errorText"></param> /// <returns></returns> public static DialogResult ShowError(string errorText) { return ShowError(errorText, null); } /// <summary> /// Выводит собщение об ошибке /// </summary> /// <param name="errorText"></param> /// <param name="caption"></param> /// <returns></returns> public static DialogResult ShowError(string errorText, string caption) { return MessageBox.Show(errorText, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } /// <summary> /// Выводит сообщение об ошибке удаления /// </summary> /// <param name="errorText"></param> /// <returns></returns> public static DialogResult ShowDeleteError(string errorText) { return ShowError(errorText, "Ошибка удаления"); } /// <summary> /// Выводит вопрос пользователю /// </summary> /// <param name="question"></param> /// <returns></returns> public static DialogResult ShowQuestion(string question) { return ShowQuestion(question, string.Empty); } /// <summary> /// Выводит вопрос пользователю /// </summary> /// <param name="question">Текст вопроса</param> /// <param name="caption">Заголовок окна</param> /// <returns></returns> public static DialogResult ShowQuestion(string question, string caption) { return MessageBox.Show(question, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question); } /// <summary> /// Показать предупреждение /// </summary> /// <param name="message"></param> public static void ShowWarning(string message) { MessageBox.Show(message, "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } /// <summary> /// Показать предупреждение /// </summary> /// <param name="message"></param> public static void ShowWarning(string message,IWin32Window owner) { MessageBox.Show(owner,message, "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning); } public static void ShowRequiredWarning(string fieldname) { ShowWarning(string.Format("Поле '{0}' обязательно для заполнения", fieldname)); } /// <summary> /// Показать запрос на подтверждение удаления объекта /// </summary> /// <param name="entityName">Название объекта в винительном падеже</param> /// <returns></returns> public static DialogResult ShowDeleteQuestion(string entityName) { return ShowDeleteQuestion(entityName, "Подтверждение удаления"); } /// <summary> /// Показать запрос на подтверждение удаления объекта /// </summary> /// <param name="entityName">Название объекта в винительном падеже</param> /// <param name="caption">Заголовок окна сообщения</param> /// <returns></returns> public static DialogResult ShowDeleteQuestion(string entityName, string caption) { return ShowQuestion( string.Format("Вы действительно хотите удалить {0}?", entityName), caption); } /// <summary> /// Показывает сообщение с вопросом и тремя вариантами ответа: Прервать, Повторить, Игнорировать /// </summary> /// <param name="message">Сообщение с вопросом</param> /// <param name="caption">Заголовок окна сообщения</param> /// <returns></returns> public static DialogResult ShowAbortRetryIgnore(string message, string caption) { return ShowAbortRetryIgnore(message, caption, MessageBoxDefaultButton.Button3); } /// <summary> /// Показывает сообщение с вопросом и тремя вариантами ответа: Прервать, Повторить, Игнорировать /// </summary> /// <param name="message">Сообщение с вопросом</param> /// <param name="caption">Заголовок окна сообщения</param> /// <param name="defaultButton">Выбранная кнопка по умолчанию</param> /// <returns></returns> public static DialogResult ShowAbortRetryIgnore(string message, string caption, MessageBoxDefaultButton defaultButton) { return MessageBox.Show(message, caption, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation, defaultButton); } /// <summary> /// Показывает информационное сообщение /// </summary> /// <param name="message">Текст сообщения</param> /// <param name="caption">Заголовок сообщения</param> /// <returns></returns> public static DialogResult ShowInfo(string message, string caption) { return MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// Показывает инфомационное сообщение с заголовком "Сообщение" /// </summary> /// <param name="message">Заголовок сообщения</param> /// <returns></returns> public static DialogResult ShowInfo(string message) { return ShowInfo(message, "Сообщение"); } } }
using System.Data.Entity.Migrations; using System.Linq; namespace GymWorkout.Data.Migrations { internal sealed class Configuration : DbMigrationsConfiguration<GymWorkout.Data.GymContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(GymWorkout.Data.GymContext context) { // This method will be called after migrating to the latest version. if (!context.FoodMeals.Any()) context.FoodMeals.AddRange(Seeds.FoodMeals); if (!context.FoodUnits.Any()) context.FoodUnits.AddRange(Seeds.FoodUnits); if (!context.Genders.Any()) context.Genders.AddRange(Seeds.Genders); } } }
using UnityEngine; using System.Collections; public class AssetPoolItem : MonoBehaviour { private string _assetName; public void SetAssetName(string name) { _assetName = name; } public string GetAssetName() { return _assetName; } public void Drop() { this.gameObject.SetActive(false); AssetManager. Instance().PutEnityToPool(this); } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Inventory.Data { public class Street : BaseEntity { [Required] public string Name { get; set; } public int StreetTypeId { get; set; } [ForeignKey(nameof(StreetTypeId))] public virtual StreetType StreetType { get; set; } public int CityId { get; set; } [ForeignKey(nameof(CityId))] public virtual City City { get; set; } public virtual ICollection<Address> Addresses { get; set; } public virtual ICollection<Order> Orders { get; set; } } }
using UnityEngine; using System.Collections; public class SetPanelJiaoZhunDianCtrl : MonoBehaviour { public Transform JiaoZhunDianTr; GameObject JiaoZhunDianObj; int IndexJiaoZhun; int StartX = -3; int StartY = 3; static SetPanelJiaoZhunDianCtrl _Instance; public static SetPanelJiaoZhunDianCtrl GetInstance() { return _Instance; } // Use this for initialization void Start() { _Instance = this; UITexture TexturePoint = JiaoZhunDianTr.GetComponent<UITexture>(); if (pcvr.bIsHardWare && pcvr.IsGetValByKey) { TexturePoint.color = Color.black; } else { TexturePoint.color = Color.red; } JiaoZhunDianObj = JiaoZhunDianTr.gameObject; JiaoZhunDianObj.SetActive(false); InputEventCtrl.GetInstance().ClickFireBtEvent += ClickFireBtEvent; } public void OpenJiaoZhunDian() { Vector3 pos = Vector3.zero; if (pcvr.IsUseZhunXingJZ_36) { StartX = -3; StartY = 3; pos.x = pcvr.ScreenW * StartX; pos.y = pcvr.ScreenH * StartY; } if (pcvr.IsUseLineHitCross) { StartX = 0; StartY = 0; pos.x = -3f * pcvr.ScreenW; pos.y = 3 * pcvr.ScreenH; } JiaoZhunDianTr.localPosition = pos; JiaoZhunDianObj.SetActive(true); } void CloseJiaoZhunDian() { JiaoZhunDianObj.SetActive(false); StartX = -3; StartY = 3; Vector3 pos = Vector3.zero; pos.x = pcvr.ScreenW * StartX; pos.y = pcvr.ScreenH * StartY; JiaoZhunDianTr.localPosition = pos; } void ClickFireBtEvent(ButtonState val) { if (val == ButtonState.DOWN) { return; } switch (pcvr.JZPoint) { case PcvrJZCrossPoint.Num49: StartX++; if (StartX > 3) { StartX = -3; StartY--; if (StartY < -3) { CloseJiaoZhunDian(); return; } } break; case PcvrJZCrossPoint.Num7: StartX++; StartY--; if (StartX > 3) { CloseJiaoZhunDian(); return; } break; case PcvrJZCrossPoint.Num4: StartX++; StartY++; if (StartX > 3) { CloseJiaoZhunDian(); return; } break; } Vector3 pos = Vector3.zero; if (pcvr.IsUseZhunXingJZ_36) { pos.x = pcvr.ScreenW * StartX; pos.y = pcvr.ScreenH * StartY; } if (pcvr.IsUseLineHitCross) { if (StartX == 0 || StartX == 3) { pos.x = -3f * pcvr.ScreenW; } if (StartX == 1 || StartX == 2) { pos.x = 3f * pcvr.ScreenW; } if (StartY == 0 || StartY == 1) { pos.y = 3f * pcvr.ScreenH; } if (StartY == 2 || StartY == 3) { pos.y = -3f * pcvr.ScreenH; } } JiaoZhunDianTr.localPosition = pos; } }
using Newtonsoft.Json; namespace gView.Interoperability.GeoServices.Rest.Json.Legend { public class LegendResponse : JsonStopWatch { [JsonProperty("layers")] public Layer[] Layers { get; set; } } }
public enum RoomCode { Test1, Test2, Test3, Test4, Room, //Ground Story StartingRoom, Library, DiningRoom, Kitchen, MasterBedroom, GameRoom, Lounge, //Basement BasementLanding, Catacomb, Cellar, BoilerRoom, PanicRoom, //Upper Story UpperStoryLanding, GuestBedroom, ServantBedroom, Study, //Shared Bathroom }
using Newtonsoft.Json; namespace Titan.MatchID.Sharecode { public class ShareCodeInfo { [JsonProperty("matchid")] public ulong MatchID { get; set; } [JsonProperty("outcomeid")] public ulong OutcomeID { get; set; } [JsonProperty("tokens")] public uint Tokens { get; set; } } }
using System; using System.Threading; namespace Amf.Ultima.Api.Services { public class TimerUltima { private Timer _timer; private AutoResetEvent _autoResetEvent; private Action _action; public DateTime TimerStarted { get; set; } public TimerUltima(Action action) { _action = action; _autoResetEvent = new AutoResetEvent(false); _timer = new Timer(Executer, _autoResetEvent, 1000, 2000); } public void Executer(object stateInfo) { _action(); // Arrêter après 60 sec if((DateTime.Now -TimerStarted).Seconds > 60) { _timer.Dispose(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class PlayerMotor { [Header("References")] public Transform cam; public CapsuleCollider col; [Header("Player")] public float playerSpeed; [Header("Physics")] public float gravity; public LayerMask discludePlayer; public int solverIterations; public float collisionRadius; [Header("Velocity Clamp")] public Vector2 maxVelocity; public Vector3 returnMovementDirection (float horizontalValue, float verticalValue) { Vector3 p = cam.transform.TransformDirection ( new Vector3(horizontalValue, 0, verticalValue) * playerSpeed * Time.deltaTime ); p.x = Mathf.Clamp(p.x, -maxVelocity.x, maxVelocity.x); p.z = Mathf.Clamp(p.z, -maxVelocity.y, maxVelocity.y); p.y = 0; return p; } public Vector3 finalDirection (Vector3 movementDirection) { return movementDirection + (new Vector3(0,gravity,0)) * Time.deltaTime; } public void AdjustTransformForCollision (Transform transform, Vector3 expectedDir) { //Check all nearby colliders (except self) Collider[] c = Physics.OverlapSphere(transform.position, collisionRadius, discludePlayer); transform.position += expectedDir; //Custom Collision Implementation foreach (Collider col in c) { Vector3 penDir = new Vector3(); float penDist = 0f; for (int i = 0; i < solverIterations; i++) { bool d = Physics.ComputePenetration(col, col.transform.position, col.transform.rotation, col, transform.position + expectedDir, transform.rotation, out penDir, out penDist); if (d == false) continue; transform.position += -penDir.normalized * penDist; } } } public void FixedUpdate(Transform transform) { //Target velocity from WASD keys Vector3 targetVelocity = cam.transform.TransformDirection ( new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * playerSpeed * Time.deltaTime ); //Clamping Velocity var velocityChange = targetVelocity; velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocity.x, maxVelocity.x); velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocity.y, maxVelocity.y); velocityChange.y = 0; //Check all nearby colliders (except self) Collider[] c = Physics.OverlapSphere(transform.position, collisionRadius, discludePlayer); //Custom Collision Implementation foreach (Collider col in c) { Vector3 penDir = new Vector3(); float penDist = 0f; Vector3 newDir = velocityChange; for (int i = 0; i < solverIterations; i++) { bool d = Physics.ComputePenetration(col, col.transform.position, col.transform.rotation, col, transform.position + newDir, transform.rotation, out penDir, out penDist); if (d == false) continue; transform.position += -penDir.normalized * penDist; newDir = -penDir.normalized * penDist; } } //Moves the player towards the desired velocity with the added gravity transform.position += (velocityChange + Physics.gravity * Time.deltaTime);//Target velocity from WASD keys } }
// // --------------------------------------------------------- // // <copyright file="IPagedList.cs" > // // Co., Ltd // // Author: Hua Dai Phong // // Created date: 22/07/2014 // // </copyright> // // --------------------------------------------------------- using System.Collections.Generic; namespace Ricky.Infrastructure.Core { public interface IPagedList<T> : IList<T> { int PageIndex { get; } int PageSize { get; } int TotalCount { get; } int TotalPages { get; } bool HasPreviousPage { get; } bool HasNextPage { get; } Paging Paging { get; } } }
using System.Collections.Generic; using System.Text; using System.Xml; namespace pjank.BossaAPI.Fixml { public class MarketDataIncRefreshMsg : FixmlMsg { public const string MsgName = "MktDataInc"; public int RequestId { get; private set; } public MDEntry[] Entries { get; private set; } public MarketDataIncRefreshMsg(FixmlMsg m) : base(m) { } protected override void ParseXmlMessage(string name) { base.ParseXmlMessage(MsgName); RequestId = FixmlUtil.ReadInt(xml, "MDReqID"); List<MDEntry> list = new List<MDEntry>(); foreach (XmlElement inc in xml.GetElementsByTagName("Inc")) list.Add(new MDEntry(inc)); Entries = list.ToArray(); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(string.Format("[{0}:{1}]", Xml.Name, RequestId)); foreach (MDEntry entry in Entries) sb.Append("\n " + entry.ToString()); return sb.ToString(); } } }
using System; using System.Collections.Generic; using TechnicalRadiation.Models; using TechnicalRadiation.Models.Dtos; using TechnicalRadiation.Models.Entities; using TechnicalRadiation.Models.InputModels; using TechnicalRadiation.Repositories; namespace TechnicalRadiation.Services { public class AuthorService { private readonly AuthorRepository _authorRepository = new AuthorRepository(); public IEnumerable<AuthorDto> GetAllAuthors(string urlStr) { return _authorRepository.GetAllAuthors(urlStr); } public AuthorDetailDto GetAuthorDetailById(int id, string urlStr) { return _authorRepository.GetAuthorDetailById(id, urlStr); } public IEnumerable<NewsItemDto> GetAuthorNewsByAuthorId(int id, string urlStr) { return _authorRepository.GetAuthorNewsByAuthorId(id, urlStr); } public int CreateAuthor(AuthorInputModel author) { return _authorRepository.CreateAuthor(author); } public Boolean UpdateAuthorById(int id, AuthorInputModel category, string urlStr) { if (_authorRepository.GetAuthorDetailById(id, urlStr) == null) { return false; } _authorRepository.UpdateAuthorById(id, category); return true; } public Boolean DeleteAuthorById(int id, string urlStr) { if (_authorRepository.GetAuthorDetailById(id, urlStr) == null) { return false; } _authorRepository.DeleteAuthorById(id); return true; } public Boolean LinkNewsItemToAuthorByIds(int authorId, int newsItemId) { // We have to go one level deeper to validate as here we do not have access // to NewsItemRepository. return _authorRepository.LinkNewsItemToAuthorByIds(authorId, newsItemId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CQRS.Abstraction; using Model; namespace Client.Command { public class DocumentCreateCommandHandler : ICommandHandler<DocumentCreateCommand> { private FakeContext context; public DocumentCreateCommandHandler(FakeContext context) { this.context = context; } public void Execute(DocumentCreateCommand command) { context.Documents.Add(new Document() { DateTime = command.Date, Status = DocumentStatus.Draft, Id = context.Documents.Max(x=>x.Id)+1, Name = command.Name }); context.SaveChanges(); } } }
namespace FeriaVirtual.Infrastructure.Persistence.OracleContext.Configuration { public interface IDBConfig { string GetConnectionString { get; } string GetDatabaseName { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abhs.Model.ViewModel { public class StudentHeartCondition { /// <summary> /// 学生ID /// </summary> public int student_id { get; set; } /// <summary> /// 大模块分类 ( 1 智能学习,2 智能提升, 3智能作业, 4错题巩固,5 思维训练,6计算训练 7 其它) /// </summary> public int module_type { get; set; } = 0; /// <summary> /// 课时模块类别 (1.错题巩固 2 基础检测 3 课时介绍 4视频学习 5 典例训练 6 查漏补缺) /// </summary> public int lesson_module_type { get; set; } = 0; /// <summary> /// 课时ID /// </summary> public int lesson_id { get; set; } = 0; /// <summary> /// 学生位置 /// </summary> public string student_position { get; set; } = ""; /// <summary> /// 学生动作 /// </summary> public string student_action { get; set; } = ""; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hoofdstuk_7_Facade { public class PopcornPopper { public void On() { Console.WriteLine("Popcorn machine turned on"); } public void Pop() { Console.WriteLine("Popcorn has been popped"); } public void Off() { Console.WriteLine("Popcorn machien turned off"); } } }
/* ******************************************************************************** * COPYRIGHT(c) ЗАО «ЧИП и ДИП», 2018 * * Программное обеспечение предоставляется на условиях «как есть» (as is). * При распространении указание автора обязательно. ******************************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RDC2_0043 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private const Int32 USB_PACKET_SIZE = 64; private const byte USB_REPORT_ID = 1; private const byte USB_CMD_POS = 1; private const byte USB_DATA_POS = 3; private const byte USB_CMD_EEPROM_WRITE = 0; private const byte USB_CMD_EEPROM_READ = 1; private const byte MODE_SIZE = 1; private const byte ACTIVE_LEVEL_SIZE = 1; private const byte THERMISTOR_R_NOMINAL_SIZE = 4; private const byte THERMISTOR_B_CONSTANT_SIZE = 2; private const byte TEMP_DELTA_LOW_SIZE = 2; private const byte TEMP_DELTA_HIGH_SIZE = TEMP_DELTA_LOW_SIZE; private const byte TEMP_NOMINAL_SIZE = 2; private const byte PROTECTION_ACTIVE_SIZE = 1; private const byte MAXIMUM_ON_TIME_SIZE = 2; private const byte MODE_OFFSET = 0; private const byte ACTIVE_LEVEL_OFFSET = (MODE_OFFSET + MODE_SIZE); private const byte THERMISTOR_R_NOMINAL_OFFSET = (ACTIVE_LEVEL_OFFSET + ACTIVE_LEVEL_SIZE); private const byte THERMISTOR_B_CONSTANT_OFFSET = (THERMISTOR_R_NOMINAL_OFFSET + THERMISTOR_R_NOMINAL_SIZE); private const byte TEMP_DELTA_LOW_OFFSET = (THERMISTOR_B_CONSTANT_OFFSET + THERMISTOR_B_CONSTANT_SIZE); private const byte TEMP_DELTA_HIGH_OFFSET = (TEMP_DELTA_LOW_OFFSET + TEMP_DELTA_LOW_SIZE); private const byte TEMP_NOMINAL_OFFSET = (TEMP_DELTA_HIGH_OFFSET + TEMP_DELTA_HIGH_SIZE); private const byte PROTECTION_ACTIVE_OFFSET = (TEMP_NOMINAL_OFFSET + TEMP_NOMINAL_SIZE); private const byte MAXIMUM_ON_TIME_OFFSET = (PROTECTION_ACTIVE_OFFSET + PROTECTION_ACTIVE_SIZE); private const byte PROTECTION_DISABLED = 0; private const byte PROTECTION_ENABLED = 1; private const UInt16 PROTECTION_MINUTE_MAX = 1500; private const UInt16 PROTECTION_MINUTE_MIN = 1; private static readonly string DeviceConnectedString = "Термостат RDC2-0043 подключен."; private static readonly string DeviceNotConnectedString = "Термостат RDC2-0043 не подключен. Подключите устройство и перезапустите программу."; public static readonly string[] OutLevelsStrings = { "0", "1", }; private static readonly string UserInputErrorHeader = "Ошибка ввода данных"; private static readonly string UserInputErrorCommonPhrase = "Неверно указан параметр: "; private static readonly string UserInputErrorTnom = "температура"; private static readonly string UserInputErrordTH = "верхнее отклонение"; private static readonly string UserInputErrordTL = "нижнее отклонение"; private static readonly string UserInputErrorRnom = "номинальное сопротивление терморезистора"; private static readonly string UserInputErrorBconst = "постоянная B терморезистора"; private static readonly string UserInputErrorProtectTime = "время (от 1 до 1500 минут)"; private static readonly string DownloadCommandHeader = "Загрузка конфигурации"; private static readonly string DownloadCommandSuccess = "Загрузка выполнена"; private static readonly string DownloadCommandError = "При загрузке возникла ошибка"; private static readonly string OldFirmwareVersionHeader = "Доступна новая версия ПО устройства"; private static readonly string OldFirmwareVersionMessage = "Настоятельно рекомендуется обновить ПО устройства."; private static readonly string FirmwareVersionPhrase = "Версия ПО устройства "; private const byte MODE_HEAT = 0; private const byte MODE_COOL = 1; private const float TEMP_FLOAT_TO_INT_VALUE = 10.0f; private const byte MINIMUM_FIRMWARE_VER = 0x20; public MainWindow() { InitializeComponent(); OutLevelComboBox.ItemsSource = OutLevelsStrings; ModeImage.Source = new BitmapImage(new Uri("images/Mode_Heat.jpg", UriKind.Relative)); Boolean USBDevDetected = USB_device.Open(); ShowConnectionState(USBDevDetected); if (USBDevDetected) { byte[] USBPacket = new byte[USB_PACKET_SIZE]; USBPacket[0] = USB_REPORT_ID; USBPacket[USB_CMD_POS] = USB_CMD_EEPROM_READ; Boolean USBSuccess = USB_device.Write(USBPacket); USBSuccess = USB_device.Read(USBPacket); byte FirmwareVersion = USBPacket[USB_DATA_POS + MAXIMUM_ON_TIME_OFFSET + MAXIMUM_ON_TIME_SIZE]; if (USBPacket[USB_DATA_POS + MODE_OFFSET] <= MODE_COOL) { if (USBPacket[USB_DATA_POS + MODE_OFFSET] == MODE_HEAT) { HeatMode.IsChecked = true; ModeImage.Source = new BitmapImage(new Uri("images/Mode_Heat.jpg", UriKind.Relative)); } else { CoolMode.IsChecked = true; ModeImage.Source = new BitmapImage(new Uri("images/Cool_Heat.jpg", UriKind.Relative)); } Tnorm.Text = ((float)((USBPacket[USB_DATA_POS + TEMP_NOMINAL_OFFSET] | (USBPacket[USB_DATA_POS + TEMP_NOMINAL_OFFSET + 1] << 8)) / TEMP_FLOAT_TO_INT_VALUE)).ToString("f2"); dTH.Text = ((float)((USBPacket[USB_DATA_POS + TEMP_DELTA_HIGH_OFFSET] | (USBPacket[USB_DATA_POS + TEMP_DELTA_HIGH_OFFSET + 1] << 8)) / TEMP_FLOAT_TO_INT_VALUE)).ToString("f2"); dTL.Text = ((float)((USBPacket[USB_DATA_POS + TEMP_DELTA_LOW_OFFSET] | (USBPacket[USB_DATA_POS + TEMP_DELTA_LOW_OFFSET + 1] << 8)) / TEMP_FLOAT_TO_INT_VALUE)).ToString("f2"); OutLevelComboBox.SelectedIndex = USBPacket[USB_DATA_POS + ACTIVE_LEVEL_OFFSET]; RnomTextBox.Text = (USBPacket[USB_DATA_POS + THERMISTOR_R_NOMINAL_OFFSET] | (USBPacket[USB_DATA_POS + THERMISTOR_R_NOMINAL_OFFSET + 1] << 8) | (USBPacket[USB_DATA_POS + THERMISTOR_R_NOMINAL_OFFSET + 2] << 16) | (USBPacket[USB_DATA_POS + THERMISTOR_R_NOMINAL_OFFSET + 3] << 24)).ToString(); BconstTextBox.Text = (USBPacket[USB_DATA_POS + THERMISTOR_B_CONSTANT_OFFSET] | (USBPacket[USB_DATA_POS + THERMISTOR_B_CONSTANT_OFFSET + 1] << 8)).ToString(); if (FirmwareVersion >= MINIMUM_FIRMWARE_VER) { if (USBPacket[USB_DATA_POS + PROTECTION_ACTIVE_OFFSET] == PROTECTION_ENABLED) ProtectionCheck.IsChecked = true; ProtectionTimeTextBox.Text = (USBPacket[USB_DATA_POS + MAXIMUM_ON_TIME_OFFSET] | (USBPacket[USB_DATA_POS + MAXIMUM_ON_TIME_OFFSET + 1] << 8)).ToString(); } else ProtectionBorder.IsEnabled = false; } if (FirmwareVersion < MINIMUM_FIRMWARE_VER) MessageBox.Show(OldFirmwareVersionMessage, OldFirmwareVersionHeader, MessageBoxButton.OK, MessageBoxImage.Exclamation); else FirmwareTextBlock.Text = FirmwareVersionPhrase + (FirmwareVersion >> 4).ToString() + "." + (FirmwareVersion & 0x0F).ToString(); } } private void ShowConnectionState(bool State) { if (State) { StateImage.Source = new BitmapImage(new Uri("images/apply_32x32.png", UriKind.Relative)); StateTextBlock.Text = DeviceConnectedString; } else { StateImage.Source = new BitmapImage(new Uri("images/warning_32x32.png", UriKind.Relative)); StateTextBlock.Text = DeviceNotConnectedString; } } private void DownloadButton_Click(object sender, RoutedEventArgs e) { byte[] USBPacket = new byte[USB_PACKET_SIZE]; USBPacket[0] = USB_REPORT_ID; USBPacket[USB_CMD_POS] = USB_CMD_EEPROM_WRITE; if (HeatMode.IsChecked == true) USBPacket[USB_DATA_POS + MODE_OFFSET] = MODE_HEAT; else USBPacket[USB_DATA_POS + MODE_OFFSET] = MODE_COOL; Int16 IntSetValue = 0; if (TryParseStringToInt(Tnorm.Text, out IntSetValue)) { USBPacket[USB_DATA_POS + TEMP_NOMINAL_OFFSET] = (byte)IntSetValue; USBPacket[USB_DATA_POS + TEMP_NOMINAL_OFFSET + 1] = (byte)(IntSetValue >> 8); } else { UserInputErrorMessage(UserInputErrorTnom); return; } if (TryParseStringToInt(dTH.Text, out IntSetValue)) { USBPacket[USB_DATA_POS + TEMP_DELTA_HIGH_OFFSET] = (byte)IntSetValue; USBPacket[USB_DATA_POS + TEMP_DELTA_HIGH_OFFSET + 1] = (byte)(IntSetValue >> 8); } else { UserInputErrorMessage(UserInputErrordTH); return; } if (TryParseStringToInt(dTL.Text, out IntSetValue)) { USBPacket[USB_DATA_POS + TEMP_DELTA_LOW_OFFSET] = (byte)IntSetValue; USBPacket[USB_DATA_POS + TEMP_DELTA_LOW_OFFSET + 1] = (byte)(IntSetValue >> 8); } else { UserInputErrorMessage(UserInputErrordTL); return; } USBPacket[USB_DATA_POS + ACTIVE_LEVEL_OFFSET] = (byte)OutLevelComboBox.SelectedIndex; UInt32 Uint32Val = 0; if (UInt32.TryParse(RnomTextBox.Text, out Uint32Val)) { for (byte i = 0; i < THERMISTOR_R_NOMINAL_SIZE; i++) USBPacket[USB_DATA_POS + THERMISTOR_R_NOMINAL_OFFSET + i] = (byte)(Uint32Val >> (8 * i)); } else { UserInputErrorMessage(UserInputErrorRnom); return; } if (UInt32.TryParse(BconstTextBox.Text, out Uint32Val)) { USBPacket[USB_DATA_POS + THERMISTOR_B_CONSTANT_OFFSET] = (byte)Uint32Val; USBPacket[USB_DATA_POS + THERMISTOR_B_CONSTANT_OFFSET + 1] = (byte)(Uint32Val >> 8); } else { UserInputErrorMessage(UserInputErrorBconst); return; } if (ProtectionCheck.IsChecked == true) { USBPacket[USB_DATA_POS + PROTECTION_ACTIVE_OFFSET] = PROTECTION_ENABLED; } else USBPacket[USB_DATA_POS + PROTECTION_ACTIVE_OFFSET] = PROTECTION_DISABLED; if ((!UInt32.TryParse(ProtectionTimeTextBox.Text, out Uint32Val)) || (!((Uint32Val >= PROTECTION_MINUTE_MIN) && (Uint32Val <= PROTECTION_MINUTE_MAX)))) { UserInputErrorMessage(UserInputErrorProtectTime); return; } else { USBPacket[USB_DATA_POS + MAXIMUM_ON_TIME_OFFSET] = (byte)Uint32Val; USBPacket[USB_DATA_POS + MAXIMUM_ON_TIME_OFFSET + 1] = (byte)(Uint32Val >> 8); } Boolean USBSuccess = USB_device.Write(USBPacket); if (USBSuccess) MessageBox.Show(DownloadCommandSuccess, DownloadCommandHeader, MessageBoxButton.OK, MessageBoxImage.Information); else MessageBox.Show(DownloadCommandError, DownloadCommandHeader, MessageBoxButton.OK, MessageBoxImage.Error); ShowConnectionState(USBSuccess); } void UserInputErrorMessage(string WrongSetting) { MessageBox.Show(UserInputErrorCommonPhrase + WrongSetting, UserInputErrorHeader, MessageBoxButton.OK, MessageBoxImage.Warning); } private bool TryParseStringToInt(string Text, out Int16 IntValue) { bool Result = true; float FloatValue; if (float.TryParse(Text, out FloatValue)) { FloatValue *= 10; IntValue = (Int16)FloatValue; } else { IntValue = 0; Result = false; } return Result; } private void HeatMode_Clicked(object sender, RoutedEventArgs e) { ModeImage.Source = new BitmapImage(new Uri("images/Mode_Heat.jpg", UriKind.Relative)); } private void CoolMode_Clicked(object sender, RoutedEventArgs e) { ModeImage.Source = new BitmapImage(new Uri("images/Mode_Cool.jpg", UriKind.Relative)); } private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { USB_device.Close(); } } }
using Stack; using NUnit.Framework; namespace NUnitTestStack { [TestFixture] class ItemTests { [Test] public void Index_GetIndexOfSecondItem_1Returned() { //arrange Item<int> firstitem = new Item<int>(null); Item<int> secoditem = new Item<int>(firstitem); int expectedIndex; //act expectedIndex = 1; //assert Assert.AreEqual(expectedIndex, secoditem.Index); } [Test] public void Constructor_InitializeChain_ChainRefsAreCorrect() { //arrange Item<int> firstitem = new Item<int>(null); Item<int> secoditem = new Item<int>(firstitem); //act //assert Assert.AreEqual(firstitem, secoditem.Prev); } [Test] public void Constructor_InitializeItemsWithObj_ItemsKeepsObj() { //arrange Item<int> firstitem = new Item<int>(null, 1); Item<int> secoditem = new Item<int>(firstitem, 2); int expectedInt = 2; //act //assert Assert.AreEqual(expectedInt, secoditem.Object); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace transport.Models.ApplicationModels { public class Tankowanie { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int IdTankowania { get; set; } public int IdPracownik { get; set; } [ForeignKey("IdPracownik")] public virtual Pracownik Pracownik { get; set; } public int IdPojazd { get; set; } public virtual Pojazd Pojazd { get; set; } [Display(Name = "Przebieg podczas tankowania")] public int PrzebiegTankow { get; set; } [Display(Name = "Ilość paliwa zatankowanego")] public decimal IloscPaliwa { get; set; } [Display(Name = "Wartość zatankowanego paliwa")] public decimal WartoscPaliwa { get; set; } [DataType(DataType.Date)] [Display(Name = "Data tankowania")] public DateTime DataTank { get; set; } public bool Aktywny { get; set; } public int IdFirma { get; set; } [ForeignKey("IdFirma")] public virtual Firma Firma { get; set; } } }
using System; namespace OptionalTypes.JsonConverters.Tests.TestDtos { public class NullableDateTimeDto { public Optional<DateTime?> Value { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tenant2 { public readonly string Name; public readonly int MaxRent; public readonly int MinQuality; public Tenant2() { Name = Names.One(); MaxRent = 1800; MinQuality = 0; } }
using System; using System.Collections.ObjectModel; namespace TwojePrzedszkole.API.Models { public class Task { public int Id { get; set; } public Collection<TaskCategory> TaskCategories { get; set; } public string TaskName { get; set; } public int Quantity { get; set; } public DateTime TaskDate { get; set; } public Collection<User> AssignedUsers { get; set; } //classes leaders public Collection<Child> AssignedChilds { get; set; } public decimal TaskCost { get; set; } public DateTime Created { get; set; } } }
using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { RadialBlur RadialBlurScript; MotionBlur BlurScript; private Transform mCamTran; //Main Camera transform private float fCamShakeImpulse = 0.0f; //Camera Shake Impulse float minShakeVal = 0.05f; public static bool IsActiveCamOtherPoint; private Transform mCamPoint_forward = null; //forward private Transform mCamPoint_right = null; //right private Transform mCamPoint_free = null; Transform mCamPoint_first; Transform CamPointUp; CamDirPos CamDir; Transform CamPoint_back = null; //back Transform CamPointBackNear = null; public static float BlurStrengthPubu = 2.2f; public static float BlurStrengthHuanYingFu = 2f; bool IsActiveRadialBlur; float MinSp = 55f; float MaxSp = 90f; float MinBlur = 0.2f; float MaxBlur = 1.5f; float KeyBlur = 0f; GameObject PlayerObj; public static AudioSource AudioSoureFengXue; bool IsActiveHuanYingFu; static private CameraShake _Instance; public static CameraShake GetInstance() { return _Instance; } // Use this for initialization void Awake () { _Instance = this; IsActiveCamOtherPoint = false; mCamTran = camera.transform; RadialBlurScript = GetComponent<RadialBlur>(); RadialBlurScript.enabled = false; //CreateAudioSoureFengXue(); BlurScript = GetComponent<MotionBlur>(); BlurScript.enabled = false; InitSetPlayerSpeedRadialBlur(); //InvokeRepeating("TestCamShake", 3f, 3f); } void TestCamShake() { SetCameraShakeImpulseValue(); } void FixedUpdate() { if (!IsActiveCamOtherPoint) { //camera transitions CameraMain(); } } void Update() { if (IsActiveCamOtherPoint) { ActiveCameraOtherPoint(); } /*if (Input.GetKeyUp(KeyCode.P)) { SetActiveCamOtherPoint(true, CamDirPos.PLAYER_UP, null); }*/ /*if (Input.GetKeyUp(KeyCode.P)) { HeatDistort.GetInstance().InitPlayScreenWater(); }*/ /*if (Input.GetKeyUp(KeyCode.P)) { GameCtrlXK.GetInstance().CreateScreenWaterParticle(); }*/ } void CreateAudioSoureFengXue() { AudioSoureFengXue = gameObject.AddComponent<AudioSource>(); AudioSoureFengXue.clip = AudioListCtrl.GetInstance().AudioFengXue; AudioSoureFengXue.loop = true; AudioSoureFengXue.Stop(); } public void PlayAudioSoureFengXue() { if (AudioSoureFengXue == null) { CreateAudioSoureFengXue(); } if (AudioSoureFengXue.isPlaying) { return; } AudioSoureFengXue.volume = 0f; AudioSoureFengXue.Play(); StartCoroutine(AddAudioSoureFengXueVolume()); } IEnumerator AddAudioSoureFengXueVolume() { while (AudioSoureFengXue.volume < 1f) { AudioSoureFengXue.volume += 0.01f; yield return new WaitForSeconds(0.03f); } } public void StopAudioSoureFengXue() { StartCoroutine(SubAudioSoureFengXueVolume()); } IEnumerator SubAudioSoureFengXueVolume() { if (AudioSoureFengXue == null) { yield break; } while (AudioSoureFengXue.volume < 1f) { AudioSoureFengXue.volume -= 0.01f; yield return new WaitForSeconds(0.03f); } AudioSoureFengXue.Stop(); } public bool CheckCamForwardHit() { if (PlayerObj == null) { if (GameCtrlXK.PlayerTran != null) { PlayerObj = GameCtrlXK.PlayerTran.gameObject; } return false; } if (GameCtrlXK.PlayerTran.forward.y < 0f) { return false; } if (CamPoint_back == null) { if (GlobalData.GetInstance().gameMode == GameMode.SoloMode) { CamPointBackNear = WaterwheelCameraCtrl.CamPointBackNear; CamPoint_back = WaterwheelCameraCtrl.CamPoint_back; } else { CamPointBackNear = WaterwheelCameraNetCtrl.CamPointBackNear; CamPoint_back = WaterwheelCameraNetCtrl.CamPoint_back; } return false; } Vector3 startPos = CamPointBackNear.position; Vector3 endPos = CamPoint_back.position; float dis = Vector3.Distance(startPos, endPos); if (startPos.y > endPos.y) { startPos.y = endPos.y; } else { endPos.y = startPos.y; } RaycastHit hitInfo; Vector3 forwardVal = endPos - startPos; Physics.Raycast(startPos, forwardVal, out hitInfo, dis); if (hitInfo.collider != null) { GameObject objHit = hitInfo.collider.gameObject; Transform tranRootHit = objHit.transform.root; if (PlayerObj != tranRootHit.gameObject && tranRootHit.name != GameCtrlXK.MissionCleanup.name && tranRootHit.GetComponent<CamNotCheckHitObj>() == null && objHit.GetComponent<CamNotCheckHitObj>() == null) { forwardVal = forwardVal.normalized; mCamTran.position = hitInfo.point - forwardVal * 0.6f; return true; } } return false; } public void SetActiveCamOtherPoint(bool isActive, CamDirPos camDirPosVal, Transform camFreePoint) { IsActiveCamOtherPoint = isActive; if (isActive) { switch (camDirPosVal) { case CamDirPos.BACK: Debug.LogError("SetActiveCamOtherPoint -> camDirPosVal should not is BackCamPoint"); CamPointUp = null; CamPointUp.name = "null"; return; case CamDirPos.FREE: if (camFreePoint == null) { Debug.LogError("SetActiveCamOtherPoint -> camFreePoint should not is null"); CamPointUp = null; CamPointUp.name = "null"; return; } mCamPoint_free = camFreePoint; break; case CamDirPos.FIRST: GameCtrlXK.GetInstance().SetPlayerBoxColliderState(true); break; } } else { Time.timeScale = 1f; if (IntoPuBuCtrl.IsIntoPuBu) { IntoPuBuCtrl.PlayerMvSpeed += 20f; } GameCtrlXK.GetInstance().InitDelayClosePlayerBoxCollider(); } CamDir = camDirPosVal; } public void SetCameraPointInfo() { if (GlobalData.GetInstance().gameMode == GameMode.SoloMode) { WaterwheelPlayerCtrl aimObjScripte = WaterwheelPlayerCtrl.GetInstance(); if(aimObjScripte == null) { return; } mCamPoint_first = aimObjScripte.GetCamPointFirst(); mCamPoint_right = aimObjScripte.GetCamPointRight(); mCamPoint_forward = aimObjScripte.GetCamPointForward(); CamPointUp = aimObjScripte.GetCamPointUp(); } else { WaterwheelPlayerNetCtrl aimObjNetScripte = WaterwheelPlayerNetCtrl.GetInstance(); if(aimObjNetScripte == null) { return; } mCamPoint_first = aimObjNetScripte.GetCamPointFirst(); mCamPoint_right = aimObjNetScripte.GetCamPointRight(); mCamPoint_forward = aimObjNetScripte.GetCamPointForward(); CamPointUp = aimObjNetScripte.GetCamPointUp(); } } void ActiveCameraOtherPoint() { switch(CamDir) { case CamDirPos.FORWARD: mCamTran.position = mCamPoint_forward.position; mCamTran.eulerAngles = mCamPoint_forward.eulerAngles; break; case CamDirPos.RIGHT: mCamTran.position = mCamPoint_right.position; mCamTran.eulerAngles = mCamPoint_right.eulerAngles; break; case CamDirPos.FREE: mCamTran.position = mCamPoint_free.position; mCamTran.eulerAngles = mCamPoint_free.eulerAngles; break; case CamDirPos.FIRST: mCamTran.position = mCamPoint_first.position; mCamTran.eulerAngles = mCamPoint_first.eulerAngles; break; case CamDirPos.PLAYER_UP: mCamTran.position = CamPointUp.position; mCamTran.eulerAngles = CamPointUp.eulerAngles; break; } } /* * FUNCTION: Controls camera movements * CALLED BY: FixedUpdate() */ private void CameraMain() { //make the camera shake if the fCamShakeImpulse is not zero if(fCamShakeImpulse > 0.0f) { shakeCamera(); } } /* * FUNCTION: Make the camera vibrate. Used for visual effects */ void shakeCamera() { Vector3 pos = mCamTran.position; pos.x += Random.Range(0, 100) % 2 == 0 ? Random.Range(-fCamShakeImpulse, -minShakeVal) : Random.Range(minShakeVal, fCamShakeImpulse); pos.y += Random.Range(0, 100) % 2 == 0 ? Random.Range(-fCamShakeImpulse, -minShakeVal) : Random.Range(minShakeVal, fCamShakeImpulse); pos.z += Random.Range(0, 100) % 2 == 0 ? Random.Range(-fCamShakeImpulse, -minShakeVal) : Random.Range(minShakeVal, fCamShakeImpulse); mCamTran.position = pos; fCamShakeImpulse -= Time.deltaTime * fCamShakeImpulse * 4.0f; if(fCamShakeImpulse < minShakeVal) { fCamShakeImpulse = 0.0f; BlurScript.enabled = false; } } /* * FUNCTION: Set the intensity of camera vibration * PARAMETER 1: Intensity value of the vibration */ public void SetCameraShakeImpulseValue() { if(fCamShakeImpulse > 0.0f || IsActiveCamOtherPoint) { return; } fCamShakeImpulse = 0.5f; //BlurScript.enabled = true; AudioListCtrl.PlayAudio(AudioListCtrl.GetInstance().AudioShipHit_1); if (IntoPuBuCtrl.IsIntoPuBu) { HeatDistort.GetInstance().InitPlayScreenWater(); //GameCtrlXK.GetInstance().CreateScreenWaterParticle(); } } public void SetIsActiveHuanYingFu(bool isActive) { IsActiveHuanYingFu = isActive; } public bool GetIsActiveHuanYingFu() { return IsActiveHuanYingFu; } public void SetRadialBlurActive(bool isActive, float strengthVal) { if (IsActiveRadialBlur == isActive) { return; } RadialBlurScript.SampleStrength = strengthVal; RadialBlurScript.enabled = isActive; IsActiveRadialBlur = isActive; } void InitSetPlayerSpeedRadialBlur() { float DisSp = MaxSp - MinSp; if (DisSp == 0) { DisSp = 1f; } KeyBlur = (MaxBlur - MinBlur) / DisSp; } public void SetPlayerSpeedRadialBlur(float playerSpeed) { if (IsActiveRadialBlur) { return; } if (playerSpeed < MinSp) { if (RadialBlurScript.enabled) { RadialBlurScript.enabled = false; } return; } if (playerSpeed > MaxSp) { return; } float strengthVal = KeyBlur * (playerSpeed - MinSp) + MinBlur; if (strengthVal > MaxBlur) { strengthVal = MaxBlur; } RadialBlurScript.SampleStrength = strengthVal; if (!RadialBlurScript.enabled) { RadialBlurScript.enabled = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fahrzeugverwaltung { public enum Autotyp { Coupe, Combi, Roadster, Van, Pickup } class Auto : Landfahrzeug { public Autotyp Typ { get; set; } public Auto(uint leistung, string name, uint laenge, uint breite, uint hoehe, uint raeder, string hersteller, Autotyp typ) :base(leistung, name, laenge, breite, hoehe, hersteller, raeder) { Typ = typ; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PasswordCreator22 { public class NumLetter : Letter { public NumLetter(Random random) : base(random) //baseは親クラスのこと。親クラスに引数randomを送る { } public override string GetLetter() //親クラスで使われてるGetLetterメソッドを使う { return random.Next(10).ToString(); //10未満の数字を呼び出してstring型に変換 } } }
using MuggleTranslator.Common; using MuggleTranslator.Runtime; using MuggleTranslator.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace MuggleTranslator.View { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainView : Window { private MainViewModel _viewmodel; public MainView() { InitializeComponent(); _viewmodel = new MainViewModel(); DataContext = _viewmodel; } protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); Visibility = Visibility.Hidden; KeyboardMonitor.KeyDown += KeyboardMonitor_KeyDown; KeyboardMonitor.KeyUp += KeyboardMonitor_KeyUp; MouseMonitor.LeftButtonDown += MouseMonitor_LeftButtonDown; } private void MouseMonitor_LeftButtonDown(MouseHookEventArgs args) { if (!_viewmodel.Locked) { var clickPoint = PointFromScreen(new Point(args.MouseStruct.pt.x, args.MouseStruct.pt.y)); if (!(clickPoint.X > 0 && clickPoint.X < Width && clickPoint.Y > 0 && clickPoint.Y < Height)) Visibility = Visibility.Hidden; } } private DateTime _downTime; private KeyboardHook.VKeys _downKey; private void KeyboardMonitor_KeyDown(KeyboardHook.VKeys key) { // 忽略用户按住Ctrl+鼠标的操作 if (_downKey == KeyboardHook.VKeys.LCONTROL && key == KeyboardHook.VKeys.LCONTROL) return; _downTime = DateTime.Now; _downKey = key; } private async void KeyboardMonitor_KeyUp(KeyboardHook.VKeys key) { if (_downKey == KeyboardHook.VKeys.LCONTROL && key == KeyboardHook.VKeys.LCONTROL) { // 1、 var deltaTime = DateTime.Now - _downTime; if (deltaTime.TotalMilliseconds < 300) { var selectedText = string.Empty; try { selectedText = (await AutomationHelper.GetSelectedText())?.Trim(); if (string.IsNullOrEmpty(selectedText) && UserConfig.Current.EnableScreenshotTranlate) { using (var screenImage = ScreenShotHelper.CaptureScreen()) { var overlay = new Overlay(screenImage); overlay.ShowDialog(); if (overlay.CropImage != null) { using (var cropImage = overlay.CropImage) { var cropImageBase64 = ImageProcess.ImageToBase64String(cropImage); selectedText = new BaiduOCR(UserConfig.Current.ClientId, UserConfig.Current.ClientSecret).GeneralBasic(cropImageBase64); } } } } } catch { } // 2、 Visibility = Visibility.Visible; selectedText = selectedText?.Trim(); if (string.IsNullOrEmpty(selectedText)) return; textbox_origintext.Text = selectedText; Translate(selectedText); } } _downKey = KeyboardHook.VKeys.NONAME; } private void btn_close_window_MouseUp(object sender, MouseButtonEventArgs e) { Visibility = Visibility.Hidden; } private void Grid_MouseDown(object sender, MouseButtonEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) this.DragMove(); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); MouseMonitor.LeftButtonDown -= MouseMonitor_LeftButtonDown; KeyboardMonitor.KeyUp -= KeyboardMonitor_KeyUp; KeyboardMonitor.KeyDown -= KeyboardMonitor_KeyDown; } private void search_btn_MouseUp(object sender, MouseButtonEventArgs e) { var originText = textbox_origintext.Text?.Trim(); if (string.IsNullOrEmpty(originText)) return; Translate(originText); } private void textbox_origintext_KeyDown(object sender, KeyEventArgs e) { var originText = textbox_origintext.Text?.Trim(); if (string.IsNullOrEmpty(originText)) return; if (e.Key == Key.Enter) Translate(originText); } private void Translate(string originText) { bing_translator_control.Translate(originText); youdao_translator_control.Translate(originText); google_translator_control.Translate(originText); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace AxisEq { /// <summary> /// Эмуляция фискальной памяти /// </summary> /// [Serializable] public class FiscalMemory { /// <summary> /// Закрыта ли смена /// </summary> public bool IsShiftClosed { get; set; } public FiscalMemory() { //6 счетчиков максимум ShiftCounters = new List<ShiftCounter>(6); LastShiftNum = 1; for (int i = 0; i < 6; i++) { ShiftCounters.Add(new ShiftCounter()); } } /// <summary> /// Сквозной номер последнего документа /// </summary> public int DocNum { get; set; } /// <summary> /// Номер последнего закрытого чека /// </summary> public int LastReceiptNum { get; set; } /// <summary> /// Номер последней закрытой смены /// </summary> public int LastShiftNum { get; set; } /// <summary> /// Наличность в кассе /// </summary> public decimal TotalCash { get; set; } /// <summary> /// Сменные счетчики по типам оплат /// </summary> public List<ShiftCounter> ShiftCounters { get; set; } /// <summary> /// Последний КПК /// </summary> public int KPK { get; set; } /// <summary> /// Загрузка из файла экземпляра /// </summary> public bool Load(string label) { try { FileStream fs = File.Open(label , FileMode.Open, FileAccess.Read, FileShare.Read); BinaryFormatter bf = new BinaryFormatter(); FiscalMemory tmp = (FiscalMemory)bf.Deserialize(fs); this.DocNum = tmp.DocNum; this.KPK= tmp.KPK; this.LastReceiptNum = tmp.LastReceiptNum; this.ShiftCounters = tmp.ShiftCounters; this.LastShiftNum = tmp.LastShiftNum; this.TotalCash = tmp.TotalCash; this.IsShiftClosed = tmp.IsShiftClosed; this.TotalPurchase = tmp.TotalPurchase; this.TotalReturn = tmp.TotalReturn; fs.Flush(); fs.Close(); return true; } catch (Exception) { return false; } } /// <summary> /// Сохранение в файл экземпляра /// </summary> public bool Save(string label) { try { FileStream fs = File.Open(label, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, this); fs.Flush(); fs.Close(); return true; } catch (Exception) { return false; } } /// <summary> /// Нарастающий итог продаж /// </summary> public decimal TotalPurchase { get; set; } /// <summary> /// Нарастрающий итог возвратов /// </summary> public decimal TotalReturn { get; set; } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace fajlList { class Program { static void Main(string[] args) { string[] ip = (File.ReadAllLines( @"ip.txt")); List<int> host = new List<int>(); Console.WriteLine(Directory.GetCurrentDirectory()); Console.WriteLine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); Console.WriteLine(); kiir(ip); Console.WriteLine(); Console.WriteLine("Rendezett:"); for (int i = 0; i < ip.Length; i++) { if (ip[i].Contains('.')) { host.Add(int.Parse(ip[i].Split('.')[3])); } } host.Sort(); listkiir(host); Console.WriteLine(); Console.ReadKey(); } static void kiir(string[] tomb) { for (int i = 1; i < tomb.Length; i++) { Console.WriteLine(tomb[i]); } } static void listkiir(List<int>tomb) { foreach (int ip in tomb) { Console.Write(ip + ", "); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace cs_pp1 { class TreadQueue { private Queue<String> list; private object block = new object(); public TreadQueue() { list = new Queue<String>(); } public void push(String _e) { lock (block) { list.Enqueue(_e); Console.WriteLine(Thread.CurrentThread.Name + ", >> " + _e); } Thread.Sleep(1); } public bool pop() { String first = null; lock (block) { if (list.Count > 0) { first = list.Dequeue(); Console.WriteLine(Thread.CurrentThread.Name + ", << " + first); } } Thread.Sleep(1); if (first != null) { return true; } else { return false; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace CarRental.API.DAL.Entities { [Table("PriceModels")] public class PriceItem { [Key] public Guid Id { get; set; } public Guid CarId { get; set; } public int Price { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Blog.Core.AuthHelper { public class JwtHelper { } }
using ApiTemplate.Core.Entities.Base; using ApiTemplate.Core.Entities.Users; using ApiTemplate.Data.Extensions; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace ApiTemplate.Data.ApplicationDbContexts { public class AppDbContext :IdentityDbContext<AppUser,AppRole,long,AppUserClaim,AppUserRole,AppUserLogin,AppRoleClaim,AppUserToken> { public AppDbContext(DbContextOptions dbContextOptions):base(dbContextOptions) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); var assemblies = typeof(IEntity).Assembly; //register all entities builder.RegisterEntities<IEntity>(assemblies); //register all configurations builder.RegisterConfigurations(GetType().Assembly); //add restrict delete behavior convention builder.AddRestrictDeleteBehaviorConvention(); //pluralize all table names builder.PluralizingTableNameConvention(); } } }
using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201302200921)] public class AuditSources : Migration { public override void Down() { Delete.Table("PRF_Source_AUD"); } public override void Up() { Create.Table("PRF_Source_AUD") .WithColumn("SourceID").AsInt32().NotNullable() .WithColumn("REV").AsInt32() .WithColumn("REVTYPE").AsInt16() .WithColumn("Archive").AsBoolean().NotNullable(); Create.PrimaryKey().OnTable("PRF_Source_AUD").Columns(new string[] { "SourceID", "REV" }); } } }
using System; using System.Collections.Generic; using FTLibrary.EliteDevice; using UnityEngine; class EliteDeviceAccessJava : EliteDeviceAccess { private AndroidJavaObject jo = null; public EliteDeviceAccessJava() :base() { jo = new AndroidJavaObject("com.ss.game.MyElite5Access"); } public int AccessTest(int a,int b) { return jo.Call<int>("AccessTest", a, b); } public override void Device_SecurityInterfaceProc(byte[] input, uint inputLength, byte[] output, out uint outputLength) { outputLength = 0; byte[] data = jo.Call<byte[]>("AccessFromJni",input); if (data == null) return; outputLength = (uint)data.Length; Array.Copy(data, output, data.Length); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TopTrumpsHCML.Entities { public abstract class SharpEntity { } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using VEE.Models; using VEE.Models.BasedeDatos; namespace VEE.Controllers { public class ResultadoesController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Resultadoes public async Task<ActionResult> Index() { var resu = await db.Resultadoes.Include(c => c.Planilla).OrderByDescending(v => v.Votos).ToListAsync(); var model = new ResultadoViewModel(); model.Resultados = resu.Select(d => new Resultadomodel { Id = d.Id, Fecha = d.Fecha, Planilla = d.Planilla, puesto = "", Votos = d.Votos }).OrderByDescending(v => v.Votos); var mb = new List<Resultadomodel>(); int x = 0; foreach (var item in model.Resultados) { item.puesto = cargo(x); mb.Add(item); x = x + 1; } model.Resultados = mb.Select(d => new Resultadomodel { Id = d.Id, Fecha = d.Fecha, Planilla = d.Planilla, puesto = d.puesto, Votos = d.Votos }).OrderByDescending(v => v.Votos); return View(model); } public string cargo(int x) { if (x == 0) { return "Presidencia"; } if (x == 1) { return "Vice Presidencia"; } if (x == 2) { return "Secretaria"; } if (x == 3) { return "Pro Secretaria"; } if (x == 4) { return "Tesoreria"; } if (x == 5) { return "Fiscalia"; } if (x == 6) { return "Vocalia"; } if (x > 6) { return "No obtuvo un puesto"; } else { return "No obtuvo un puesto"; } } [HttpPost] public async Task<JsonResult> planillajson() { var resu = await db.Resultadoes.Include(c => c.Planilla).OrderByDescending(v => v.Votos).Take(7).ToListAsync(); var d = resu.Select(n => new { Nombre = n.Planilla.Nombre, Votos = n.Votos } ); return Json(d); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using HBPonto.Database.Entities; using HBPonto.Kernel.Enums; using HBPonto.Kernel.Interfaces.Entities; using System; using System.Collections.Generic; using System.Text; namespace HBPonto.Kernel.Interfaces.Authentication { public interface IUserService { List<User> GetAllUsers(); List<RoleEnum> GetRoles(); void UpdateUser(User user); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using IdentityS4.Data; using Microsoft.EntityFrameworkCore; namespace IdentityS4.Services { public class BaseService<T> where T : class, new() { public EFContext db; /// <summary> /// 增 /// </summary> /// <param name="entity"></param> /// <returns></returns> public async Task<bool> Add(T entity) { await db.Set<T>().AddAsync(entity); return db.SaveChanges() > 0; } /// <summary> /// 删 /// </summary> /// <param name="entity"></param> /// <returns></returns> public async Task<bool> Del(T entity) { db.Entry(entity).State = EntityState.Deleted; int i = await db.SaveChangesAsync(); return i > 0; } /// <summary> /// 改 /// </summary> /// <param name="entity"></param> /// <returns></returns> public async Task<bool> Edit(T entity) { db.Entry(entity).State = EntityState.Modified; int i = await db.SaveChangesAsync(); return i > 0; } /// <summary> /// 查-根据传进来的lambda表达式查询一条数据 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public async Task<T> Get(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda) { T t = await db.Set<T>().Where(whereLambda).SingleOrDefaultAsync(); return t; } /// <summary> /// 查询多条数据-根据传进来的lambda和排序的lambda查询 /// </summary> /// <typeparam name="s"></typeparam> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="whereLambda"></param> /// <param name="orderbyLambda"></param> /// <param name="isAsc"></param> /// <returns></returns> public async Task<List<T>> GetList<s>(int pageIndex, int pageSize, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, s>> orderbyLambda, bool isAsc) { var temp = db.Set<T>().Where(whereLambda); List<T> list = null; if (isAsc)//升序 { list = await temp.OrderBy(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); } else//降序 { list = await temp.OrderByDescending(orderbyLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); } return list; } /// <summary> /// 获取总条数 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public async Task<int> GetTotalCount(Expression<Func<T, bool>> whereLambda) { return await db.Set<T>().Where(whereLambda).CountAsync(); } } }
using System; using DFC.ServiceTaxonomy.ContentApproval.Drivers; using DFC.ServiceTaxonomy.ContentApproval.Handlers; using DFC.ServiceTaxonomy.ContentApproval.Indexes; using DFC.ServiceTaxonomy.ContentApproval.Models; using DFC.ServiceTaxonomy.ContentApproval.Permissions; using DFC.ServiceTaxonomy.ContentApproval.Services; using DFC.ServiceTaxonomy.ContentApproval.Shapes; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using OrchardCore.AuditTrail.Services; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.Contents.Services; using OrchardCore.Contents.ViewModels; using OrchardCore.Data.Migration; using OrchardCore.DisplayManagement.Descriptors; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.Modules; using OrchardCore.Security.Permissions; using YesSql.Indexes; namespace DFC.ServiceTaxonomy.ContentApproval { public class Startup : StartupBase { public override void ConfigureServices(IServiceCollection services) { services.AddContentPart<ContentApprovalPart>() .AddHandler<ContentApprovalContentHandler>() .UseDisplayDriver<ContentApprovalPartDisplayDriver>(); services.AddContentPart<ContentApprovalItemStatusDashboardPart>() .UseDisplayDriver<ContentApprovalItemStatusDashboardPartDisplayDriver>(); services.AddScoped<IDataMigration, Migrations>(); services.AddSingleton<IIndexProvider, ContentApprovalPartIndexProvider>(); services.AddScoped<IPermissionProvider, CanPerformReviewPermissions>(); services.AddScoped<IPermissionProvider, CanPerformApprovalPermissions>(); services.AddScoped<IPermissionProvider, RequestReviewPermissions>(); services.AddScoped<IPermissionProvider, ForcePublishPermissions>(); services.AddScoped<IShapeTableProvider, ContentEditShapes>(); services.AddScoped<IContentItemsApprovalService, ContentItemsApprovalService>(); // contents admin list filters services.AddTransient<IContentsAdminListFilterProvider, ContentApprovalPartContentsAdminListFilterProvider>(); services.AddScoped<IDisplayDriver<ContentOptionsViewModel>, ContentApprovalContentsAdminListFilterDisplayDriver>(); services.AddScoped<IAuditTrailEventHandler, ContentApprovalAuditTrailEventHandler>(); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { routes.MapAreaControllerRoute( name: "ContentApproval", areaName: "DFC.ServiceTaxonomy.ContentApproval", pattern: "ContentApproval/RequestApproval", defaults: new { controller = "ContentApproval", action = "RequestApproval" } ); } } }
using System; using System.Collections.Generic; using System.Linq; namespace DigiX.Web.Global.Objects { public class FreeOtherItemDeals : IDeals { public int DealsId { get; set; } public int DealsTypeId { get; set; } public int LeastItems { get; set; } public bool IsMultipliable { get; set; } public string Note { get; set; } public IEnumerable<FreeProduct> FreeProducts { get; set; } public bool IsAdjusted { get; private set; } public IEnumerable<FreeProduct> AdjustDeals(Order order, int totalEntitled) { FreeProducts.All(it => { it.total = it.total * totalEntitled; return true; }); IsAdjusted = true; return FreeProducts; } void IDeals.AdjustDeals(Order order, int totalEntitled) { throw new NotImplementedException(); } } public class FreeProduct { public int ProductId { get; set; } public int total { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Interfaz { public partial class MenuPrincipal : Form { private Boolean Arrastrar = false; private int MouseDownX; private int MouseDownY; public MenuPrincipal() { InitializeComponent(); this.Size = Screen.PrimaryScreen.WorkingArea.Size; this.Location = Screen.PrimaryScreen.WorkingArea.Location; } private void Salir_Click(object sender, EventArgs e) { this.Dispose(); } private void Barra_MouseDown(object sender, MouseEventArgs e) { Arrastrar = true; MouseDownX = e.X; MouseDownY = e.Y; } private void Barra_MouseUp(object sender, MouseEventArgs e) { Arrastrar = false; } private void Barra_MouseMove(object sender, MouseEventArgs e) { if (Arrastrar == true) { Point temp = new Point(); temp.X = this.Location.X + (e.X - MouseDownX); temp.Y = this.Location.Y + (e.Y - MouseDownY); this.Location = temp; } } private void MenuPrincipal_Load(object sender, EventArgs e) { tiempo_continuo.Start(); } private void tiempo_continuo_Tick(object sender, EventArgs e) { lblhora.Text = DateTime.Now.ToLongTimeString(); lblfecha.Text = DateTime.Now.ToShortDateString(); } private void panel3_Paint(object sender, PaintEventArgs e) { } private void btnregistrar_compra_Click(object sender, EventArgs e) { } private void btnarticulos_Click(object sender, EventArgs e) { Close(); } } }
// Copyright (c) Adrian Sims 2018 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using static System.Math; using System; namespace Gclusters { internal class GridLocation { class EEllipse { public double A { get; set; } public double B { get; set; } public double F { get; set; } }; // Helmert Transformation - see http://en.wikipedia.org/wiki/Helmert_transformation class Helmert { public double Tx { get; set; } public double Ty { get; set; } public double Tz { get; set; } public double Rx { get; set; } public double Ry { get; set; } public double Rz { get; set; } public double S { get; set; } }; private double _longitude; // longitude in WGS84 private double _latitude; // latitude in WGS84 private bool _cacheValid; // are calculated eastings and northings still valid? private int _cachedEastings; // cached eastings - we don't want to recalculate unnecesarily as calculation is LONG! private int _cachedNorthings; // cached northings - we don't want to recalculate unnecesarily as calculation is LONG! private const string squares = "SV.SW.SX.SY.SZ.TV.XX.SQ.SR.SS.ST.SU.TQ.TR.XX.SM.SN.SO.SP.TL.TM.XX.XX.SH.SJ.SK.TF.TG.XX.XX.SC.SD.SE.TA.XX.XX.NW.NX.NY.NZ.XX.XX.NQ.NR.NS.NT.NU.XX.XX.NL.NM.NN.NO.NP.XX.XX.NF.NG.NH.NJ.NK.XX.XX.NA.NB.NC.ND.NE.XX.XX.HV.HW.HX.HY.HZ.XX.XX.HQ.HR.HS.HT.HU.XX.XX.HL.HM.HN.HO.HP.XX.XX."; public (int eastings, int northings) OsGrid { get { if (!_cacheValid) { var (newLat, newLong) = ConvertWGS84ToOSGB36(_latitude, _longitude); LatLongToOsGrid(newLat, newLong); } return (_cachedEastings, _cachedNorthings); } } public int Eastings { get { if (!_cacheValid) { var (newLat, newLong) = ConvertWGS84ToOSGB36(_latitude, _longitude); LatLongToOsGrid(newLat, newLong); } return _cachedEastings; } } public int Northings { get { if (!_cacheValid) { var (newLat, newLong) = ConvertWGS84ToOSGB36(_latitude, _longitude); LatLongToOsGrid(newLat, newLong); } return _cachedNorthings; } } string GetSquare() { if (!_cacheValid) { var (newLat, newLong) = ConvertWGS84ToOSGB36(_latitude, _longitude); LatLongToOsGrid(newLat, newLong); } int hsquare = _cachedEastings / 100000; int vsquare = _cachedNorthings / 100000 - 1; int index = 3 * (vsquare * 7 + hsquare); return $"{squares[index]}{squares[index + 1]}"; } int GetEastingsInSquare() { return Eastings % 100000; } int GetNorthingsInSquare() { return Northings % 100000; } private (double latitude, double longitude) ConvertSystem(EEllipse eTo, EEllipse eFrom, Helmert h, double latitude, double longitude) { double a = eFrom.A, b = eFrom.B; double f = eFrom.F; double H = 0; // Height double eSq = 2 * f - f * f; double eSq1 = (a * a - b * b) / (a * a); double nu = a / Sqrt(1 - eSq * Sin(latitude) * Sin(latitude)); double x1 = (nu + H) * Cos(latitude) * Cos(longitude); double y1 = (nu + H) * Cos(latitude) * Sin(longitude); double z1 = ((1 - eSq) * nu + H) * Sin(latitude); // Console.WriteLine($"old cartesian {x1:N11}, {y1:N11}, {z1:N11}"); // Apply helmert transformation: double tx = h.Tx, ty = h.Ty, tz = h.Tz; double rx = h.Rx / 3600 * PI / 180; // convert seconds to radians double ry = h.Ry / 3600 * PI / 180; double rz = h.Rz / 3600 * PI / 180; double s1 = h.S / 1e6 + 1; // convert ppm to (s+1) // apply transform double x2 = tx + x1 * s1 - y1 * rz + z1 * ry; double y2 = ty + x1 * rz + y1 * s1 - z1 * rx; double z2 = tz - x1 * ry + y1 * rx + z1 * s1; // Console.WriteLine($"new cartesian {x2:N11}, {y2:N11}, {z2:N11}"); a = eTo.A; b = eTo.B; f = eTo.F; eSq = 2 * f - f * f; nu = a / Sqrt(1 - eSq * Sin(latitude) * Sin(latitude)); double p = Sqrt(x2 * x2 + y2 * y2); double phi = Atan2(z2, p * (1 - eSq)); double phiP = 2 * PI; double precision = 0.001 / a; // results accurate to around 4 metres var iterationCount = 0; while (Abs(phi - phiP) > precision) { nu = a / Sqrt(1 - eSq * Sin(phi) * Sin(phi)); phiP = phi; phi = Atan2(z2 + eSq * nu * Sin(phi), p); iterationCount++; } // Console.WriteLine($"Iterations: {iterationCount}"); double lambda = Atan2(y2, x2); H = p / Cos(phi) - nu; return (phi, lambda); } private (double latitude, double longitude) ConvertWGS84ToOSGB36(double latitude, double longitude) { var WGS84Ellipse = new EEllipse { A = 6378137, B = 6356752.314245, F = 1 / 298.257223563 }; var OSGB36Ellipse = new EEllipse { A = 6377563.396, B = 6356256.909, F = 1 / 299.3249646 }; Helmert h = new Helmert { Tx = -446.448, Ty = 125.157, Tz = -542.060, // tx, ty, tz in metres (translation parameters) Rx = -0.1502, Ry = -0.2470, Rz = -0.8421, // rx, ry, rz in seconds of a degree (rotational parameters) S = 20.4894 // scale; }; return ConvertSystem(OSGB36Ellipse, WGS84Ellipse, h, latitude, longitude); } /// <summary> /// Adjust the latitude and longitude of this instance from OSGB36 (the coordinates used for grid referenced) to /// the coordinates used by GBP (WGS84) /// </summary> private (double latitude, double longitude) ConvertOSGB36ToWgs84(double latitude, double longitude) { var WGS84Ellipse = new EEllipse { A = 6378137, B = 6356752.314245, F = 1 / 298.257223563 }; var OSGB36Ellipse = new EEllipse { A = 6377563.396, B = 6356256.909, F = 1 / 299.3249646 }; Helmert helmert = new Helmert { Tx = 446.448, Ty = -125.157, Tz = 542.060, // tx, ty, tz in metres (translation parameters) Rx = 0.1502, Ry = 0.2470, Rz = 0.8421, // rx, ry, rz in seconds of a degree (rotational parameters) S = -20.4894 // scale; }; return ConvertSystem(WGS84Ellipse, OSGB36Ellipse, helmert, latitude, longitude); } public static GridLocation CreateFromDegrees(double latitude, double longitude) { var result = new GridLocation(); result.SetLatLongDegrees(latitude, longitude); return result; } public static GridLocation CreateFromOsGrid(int eastings, int northings) { var result = new GridLocation(); result.SetFromOsGrid(eastings, northings); return result; } /// <summary> /// Set latitude and longitude from degrees. The values specified should be in WGS84 coordinates /// </summary> /// <param name="latitude"></param> /// <param name="longitude"></param> /// <returns></returns> public bool SetLatLongDegrees(double latitude, double longitude) { bool result; if (latitude < -90.0000000001 || latitude > 90.0000000001 || longitude < -360.0000000001 || longitude > 360.0000000001) { result = false; } else { _cacheValid = false; // we have changed so E/N cache is rubbish _latitude = latitude * Math.PI / 180.0; _longitude = longitude * Math.PI / 180.0; result = true; } return result; } public void SetFromOsGrid(double E, double N) { // const double n = 0.001673220250; // ellipsoidal constant - see textbooks const double a = 6375020.481; // ellipsoidal constant - see textbooks (scaled by f0) const double b = 6353722.490; // ellipsoidal constant - see textbooks (scaled by f0) const double phi0 = 49 * PI / 180; // True origin of latitude - 49 deg. north const double lambda0 = -2 * PI / 180; // True origin of longitude - 2 deg. west const double N0 = -100000; // Grid northings of true origin const double E0 = 400000; // Grid eastings of true origin double phidash, m, error, VII, VIII, IX, X, XI, XII, XIIA; double Et, t, t2, t4, t6; double ro, nu, phi; Et = E - E0; phidash = (N - N0) / a + phi0; int count = 0; do { m = fM(phi0, phidash); phidash = phidash + (N - N0 - m) / a; error = N - N0 - m; count++; } while (error > 0.000000001 && count < 40); //Console.WriteLine($"Count is {count} phidash = {phidash}"); // eccentricity squared: var e2 = (a * a - b * b) / (a * a); nu = a / Sqrt(1.0 - e2 * Sin(phidash) * Sin(phidash)); ro = nu * (1.0 - e2) / (1.0 - e2 * Sin(phidash) * Sin(phidash)); var eta2 = nu / ro - 1; t = Tan(phidash); t2 = t * t; t4 = t * t * t * t; t6 = t * t * t * t * t * t; VII = t / (2 * ro * nu); VIII = t * (5 + 3 * t2 + eta2 - 9 * t2 * eta2) / (24 * ro * nu * nu * nu); IX = t * (61 + 90 * t2 + 45 * t4) / (720 * ro * nu * nu * nu * nu * nu); phi = phidash - Et * Et * VII + Et * Et * Et * Et * VIII - Et * Et * Et * Et * Et * Et * IX; X = 1 / (Cos(phidash) * nu); XI = (nu / ro + 2 * t2) / (6 * nu * nu * nu * Cos(phidash)); XII = (5 + 28 * t2 + 24 * t4) / (120 * nu * nu * nu * nu * nu * Cos(phidash)); XIIA = (61 + 662 * t2 + 1320 * t4 + 720 * t6) / (5040 * nu * nu * nu * nu * nu * nu * nu * Cos(phidash)); //Console.WriteLine($"VII is {VII}"); //Console.WriteLine($"VIII is {VIII}"); //Console.WriteLine($"IX is {IX}"); //Console.WriteLine($"XII is {XII}"); //Console.WriteLine($"XIIA is {XIIA}"); double lambda = lambda0 + Et * X - Et * Et * Et * XI + Et * Et * Et * Et * Et * XII - Et * Et * Et * Et * Et * Et * Et * XIIA; //Console.WriteLine($"lamba is {lambda} phi is {phi}"); //Console.WriteLine($"pretransform: _longitude is {_longitude} latitude is {_latitude}"); //Console.WriteLine($"pretransform-degrees: _longitude is {_longitude * 180 / PI} latitude is {_latitude * 180 / PI}"); (_latitude, _longitude) = ConvertOSGB36ToWgs84(phi, lambda); //Console.WriteLine($"posttransform: _longitude is {_longitude} latitude is {_latitude}"); //Console.WriteLine($"posttransform-degrees: _longitude is {_longitude * 180 / PI} latitude is {_latitude * 180 / PI}"); } /// <summary> /// Convert latitude and longitude to OS Grid /// </summary> /// <param name="phi">Latitude in radians</param> /// <param name="lambda">Longitude in radians</param> private void LatLongToOsGrid(double phi, double lambda) { const double PI = 3.14159265358979310; // const double n = 0.001673220250; // ellipsoidal constant - see textbooks const double a = 6375020.481; // ellipsoidal constant - see textbooks (scaled by f0) const double b = 6353722.490; // ellipsoidal constant - see textbooks (scaled by f0) const double phi0 = 49 * PI / 180; // True origin of latitude - 49 deg. north const double lambda0 = -2 * PI / 180; // True origin of longitude - 2 deg. west const double N0 = -100000; // Grid northings of true origin // const double E0 = 400000; // Grid eastings of true origin // trigs and powers: var s = Sin(phi); var s2 = s * s; var c = Cos(phi); var c3 = c * c * c; var c5 = c * c * c * c * c; var t = Tan(phi); var t2 = t * t; var t4 = t2 * t2; var m = fM(phi0, phi); var e = Sqrt((a * a - b * b) / (a * a)); var nu = a / Sqrt(1.0 - e * e * s2); var ro = nu * (1.0 - e * e) / (1.0 - e * e * s2); var eta = Sqrt(nu / ro - 1); var P = lambda - lambda0; var term1 = 5.0 - t2 + 9.0 * eta * eta; var term2 = 61.0 - 58.0 * t2 + t4; var I = m + N0; var II = nu * s * c / 2.0; //OK var III = nu * s * c3 * term1 / 24.0; //OK var IIIA = nu * s * c5 * term2 / 720; var N = I + P * P * II + P * P * P * P * III + P * P * P * P * P * P * IIIA; var IV = nu * c; var V = nu * c3 * (nu / ro - t2) / 6; var VI = nu * c5 * (5 - 18 * t2 + t4 + 14 * eta * eta - 58 * t2 * eta * eta) / 120; var E = 400000 + P * IV + P * P * P * V + P * P * P * P * P * VI; // convert eastings an northings to integers in metres but remember to round up or down!: _cachedEastings = (int)(E + 0.5); _cachedNorthings = (int)(N + 0.5); // these values should be cached in case asked for again - setting a new value for latitude or longitude // will invalidate the cache: _cacheValid = true; } double fM(double phi1, double phi2) { const double b = 6353722.490; // ellipsoidal constant - see textbooks (scaled by f0) const double n = 0.001673220250; // ellipsoidal constant - see textbooks [n is actually (a-b)/(a+b)] double f1, f2, f3, f4; var n2 = n * n; var n3 = n * n * n; var delta = phi2 - phi1; var sum = phi2 + phi1; f1 = (1.0 + n + (5.0 * (n2 + n3) / 4.0)) * delta; f2 = (3.0 * (n + n2) + 21.0 * n3 / 8) * Sin(delta) * Cos(sum); f3 = (15.0 * (n2 + n3) / 8.0) * Sin(2 * delta) * Cos(2 * sum); f4 = (35.0 * n * n * n / 24.0) * Sin(3 * delta) * Cos(3 * sum); return b * (f1 - f2 + f3 - f4); } public double Latitude => _latitude; public double Longitude => _longitude; public (double latitude, double longitude) LatLong => (_latitude * 180.0 / PI, _longitude * 180.0 / PI); public static double operator -(GridLocation loc1, GridLocation loc2) { var R = 6371e3; // metres var φ1 = loc1._latitude; var φ2 = loc2._latitude; var Δφ = (φ2 - φ1); var Δλ = loc1._longitude - loc2._longitude; var a = Math.Sin(Δφ / 2) * Math.Sin(Δφ / 2) + Math.Cos(φ1) * Math.Cos(φ2) * Math.Sin(Δλ / 2) * Math.Sin(Δλ / 2); var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); var d = R * c; return d; } private GridLocation() { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using DT; namespace DTPrueba { public partial class Form1 : Form { public Form1() { InitializeComponent(); } String afiliado = "0801-1991-09122,CaRLOs,JAmILCAR,SáncHEz,RosA,1991-04-07,Soltero,Masculino,col.loarque sur blqW casa " + "1016;226-8169,226-7522;97604843,90785634;kouta_revenge3@hotmail.com,d6288b8ae441ed58142bb70133276b72;" + "UNITEC,225-1234,alla cerca de los pinos," + "2008-06-01,Docencia,Tegucigalpa;Estudiante;0801-1991-00000,Luis,Carlos,Baquero,,1991-11-01,Soltero," + "Masculino,Res.Plaza,Amigo;0801-1991-00001,Daniel,Eduardo,ACOSTA,carbajal,1991-12-05,Soltero,Masculino," + "Res.Plaza,Alumno,50,0;0801-1990-90234,Angela,Sarahi,Velasquez,Lopez,1990-05-17,Soltero,Femenino,col. " + "Primavera,Pareja,50,100", afiliado_mod = "0801-1991-09122,CaRLOs,AmILCAR,SáncHEz,RosA,1991-04-07,Divorciado,Masculino,col.loarque sur blqW casa " + "1016;226-8169,226-7522;97604843,90785634;carlos.sanchez@squadventure.com,d628142bb7013327688b8ae441ed5b72;" + "UNITEC,225-1234,alla cerca de los pinos," + "2008-06-01,Docencia,Tegucigalpa;Puta;0801-1991-00000,Luis,Carlos,Baquero,,1991-11-01,Soltero," + "Masculino,Res.Plaza,Amigo;0801-1991-00001,Daniel,Eduardo,ACOSTA,carbajal,1991-12-05,Soltero,Masculino," + "Res.Plaza,Alumno,50,0;0801-1990-90234,Angela,Sarahi,Velasquez,Lopez,1990-05-17,Soltero,Femenino,col. " + "Primavera,Pareja,50,100", empleado = "0901-2011-09212,Mauricio,JAVIER,Funez,PERALTA,2010-12-31,Viudo," + "Masculino,zamorano;2290-9090;9999-9999,3333-3333;pedro_jose@gmail.com,d6288b8ae441ed58142bb70133276b72,Jefe IT", empleado_mod = "0901-2011-09213,Mauricio,JAVIER,Funez,PERALTA,2010-12-31,Casado," + "Masculino,zamorano;2290-9090;9999-9999,3333-3333;pedro_jose3@gmail.com,d6288b8ae441ed58142bb70133276b72,Jefe IT", empleado2 = "1911-2011-09212,Federico,,Andares,,2010-12-31,Viudo," + "Masculino,alla en la requinta pija;2290-9090;9999-9999,3333-3333;federico@gmail.com,d6288b8ae441ed58142bb70133276b72,Prostituta", afiliado2 = "0801-0900-1231," + "dany,eduardo,acosta,carbajal,2001-12-14,casado,masc,ksa;2222-2222,2133-1233;99-9999,9913-1123;dany@sca.com,d6288b8ae441ed58142bb70133276b72;mi" + " kasa,8765-2313,esquina,2100-12-01,IT,ksa;Estudiante;0801-0920-1231,dany2,eduardo2,acosta2,carbajal2,2001-02-14," + "casado,masculino,llegando aki,padre;0801-0920-0931,dany3,eduardo3,acosta3,carbajal3,2001-05-14,casado,masculino,mi" + " ksa,primo,60,59"; private void button1_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.InsertarAfiliado(afiliado + '&' + textBox4.Text).ToString()); } private void button2_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.InsertarEmpleado(empleado + '&' + textBox4.Text).ToString()); } private void button3_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getTodasOcupaciones()); } private void button4_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.InsertarOcupacion(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button5_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.DeshabilitarOcupacion(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button6_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getTodosMotivos()); } private void button7_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.InsertarMotivo(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button8_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.DeshabilitarMotivo(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button9_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getTodosParentescos()); } private void button10_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.InsertarParentesco(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button11_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.DeshabilitarParentesco(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button12_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.InsertarNuevoMonto(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button13_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getMontoActual().ToString()); } private void button14_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.InsertarNuevoLimite(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button15_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getLimiteActual().ToString()); } private void button16_Click(object sender, EventArgs e) { String InteresDK = textBox1.Text + "," + textBox3.Text + "," + checkBox1.Checked.ToString() + "," + checkBox2.Checked.ToString() + "," + checkBox3.Checked.ToString() + "," + checkBox4.Checked.ToString() + "," + textBox2.Text + '&' + textBox4.Text; MessageBox.Show(DataTransaction.InsertarInteres(InteresDK).ToString()); } private void button17_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getTodosIntereses()); } private void button18_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.DeshabilitarInteres(textBox1.Text + '&' + textBox4.Text).ToString()); } private void button19_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getPerfilAfiliado(textBox1.Text).ToString()); } private void button20_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getPerfilEmpleado(textBox1.Text).ToString()); } private void button21_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getInteres(textBox1.Text)); } private void button24_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.SolicitarModificacionDePerfil(empleado_mod + "&" + textBox4.Text + "&0901-2011-09213").ToString()); } private void button26_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.ModificarPerfil("0901-2011-09213").ToString()); } private void button22_Click(object sender, EventArgs e) { MessageBox.Show(DataTransaction.getLogin("pedro_jose3@gmail.com,d6288b8ae441ed58142bb70133276b72").ToString()); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SnakeMultiplayer.Services; var builder = WebApplication.CreateBuilder(args); builder.Services.AddMvc(o => o.EnableEndpointRouting = false); builder.Services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); builder.Services.AddSingleton<IGameServerService, GameServerService>(); builder.Services.AddSingleton<ITimerService, TimerService>(); builder.Services.AddTransient<IServerHub, ServerHub>(); builder.Services.AddSignalR(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseWebSockets(); app.MapHub<LobbyHub>("/LobbyHub"); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.Run();
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using SocialMedia.Infrastructure.Core; using System; using System.Collections.Generic; using System.Text; namespace SocialMedia.Infrastructure.Data.Configurations { public class AspnetPersonalizationPerUserConfiguration : IEntityTypeConfiguration<AspnetPersonalizationPerUser> { public void Configure(EntityTypeBuilder<AspnetPersonalizationPerUser> entity) { entity.HasKey(e => e.Id) .HasName("PK__aspnet_P__3214EC063925661E") .IsClustered(false); entity.ToTable("aspnet_PersonalizationPerUser"); entity.HasIndex(e => new { e.PathId, e.UserId }) .HasName("aspnet_PersonalizationPerUser_index1") .IsUnique() .IsClustered(); entity.HasIndex(e => new { e.UserId, e.PathId }) .HasName("aspnet_PersonalizationPerUser_ncindex2") .IsUnique(); entity.Property(e => e.Id).HasDefaultValueSql("(newid())"); entity.Property(e => e.LastUpdatedDate).HasColumnType("datetime"); entity.Property(e => e.PageSettings) .IsRequired() .HasColumnType("image"); entity.HasOne(d => d.Path) .WithMany(p => p.AspnetPersonalizationPerUser) .HasForeignKey(d => d.PathId) .HasConstraintName("FK__aspnet_Pe__PathI__1BC821DD"); entity.HasOne(d => d.User) .WithMany(p => p.AspnetPersonalizationPerUser) .HasForeignKey(d => d.UserId) .HasConstraintName("FK__aspnet_Pe__UserI__1CBC4616"); } } }
using Atc.Resources; // ReSharper disable once CheckNamespace namespace Atc { /// <summary> /// Enumeration: ForwardReverseType. /// </summary> public enum ForwardReverseType { /// <summary> /// Default None. /// </summary> [LocalizedDescription(null, typeof(EnumResources))] None = 0, /// <summary> /// Forward. /// </summary> [LocalizedDescription("ForwardReverseTypeForward", typeof(EnumResources))] Forward = 1, /// <summary> /// Reverse. /// </summary> [LocalizedDescription("ForwardReverseTypeReverse", typeof(EnumResources))] Reverse = 2, } }
 using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Rendering; namespace DFC.ServiceTaxonomy.GraphSync.Settings { public class GraphSyncPartSettingsViewModel { public GraphSyncPartSettingsViewModel() { Settings = new List<SelectListItem>(); AllSettings = new List<GraphSyncPartSettings>(); } public List<SelectListItem> Settings { get; set; } public List<GraphSyncPartSettings> AllSettings { get; set; } public string? SelectedSetting { get; set; } public string? BagPartContentItemRelationshipType { get; set; } public bool PreexistingNode { get; set; } public string? NodeNameTransform { get; set; } public string? PropertyNameTransform { get; set; } public string? CreateRelationshipType { get; set; } //or RelationshipTypeTransform for consistency? public string? IdPropertyName { get; set; } public string? GenerateIdPropertyValue { get; set; } public int? VisualiserNodeDepth { get; set; } public int? VisualiserIncomingRelationshipsPathLength { get; set; } public bool DisplayId { get; set; } public bool ReadOnly { get; internal set; } public string? PreExistingNodeUriPrefix { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LapComplete : MonoBehaviour { public GameObject MiddleTrig; public GameObject LapCompleteTrig; public GameObject CANVAStoGO; public Text MinuteSet; public Text SecSet; public Text MilliSet; public Text LapNo; public static int lastmin; public static int lastsec; public static float lastmilli; public static int lap=0; public GameObject LapTimeBox; public GameObject GameDone; private void Start() { Debug.Log("Entered LapComplete.cs"); GameDone.SetActive(false); // lap = 0; // LapTime.Sec = 0; // LapTime.Min = 0; don't add or else timer restarts at halftrigger // LapTime.Milli = 0; } private void Update() { if (lap >= 3) CANVAStoGO.SetActive(false); } // Update is called once per frame void OnTriggerEnter() { Debug.Log("Entered OnTriggered of LapComplete and value of lap : "+lap); lap++; LapNo.text = "" + lap.ToString(); if ((LapTime.Min * 60 * 100 + LapTime.Sec * 100 + LapTime.Milli) < (lastmin * 6000 + lastsec * 100 + lastmilli) || lap==1) { if (LapTime.Min > 9) { lastmin = LapTime.Min; MinuteSet.text = LapTime.Min.ToString() + ": "; } else { lastmin = LapTime.Min; MinuteSet.text = "0" + LapTime.Min.ToString() + ": "; } if (LapTime.Sec > 9) { lastsec = LapTime.Sec; SecSet.text = LapTime.Sec.ToString() + "."; } else { lastsec = LapTime.Sec; SecSet.text = "0" + LapTime.Sec.ToString() + "."; } if (LapTime.Milli > 9) { MilliSet.text = LapTime.Milli.ToString(); lastmilli = LapTime.Milli; } else { lastmilli = LapTime.Milli; MilliSet.text = "0" + LapTime.Milli.ToString(); } } LapTime.bestlapgame =(lastmilli + lastsec * 100 + lastmin * 6000); if(LapTime.bestlapgame<PlayerPrefs.GetFloat("BestLap", 999999999999999999999999.0f)) { PlayerPrefs.SetFloat("BestLap", LapTime.bestlapgame); } LapTime.Sec = 0; LapTime.Min = 0; LapTime.Milli = 0; MiddleTrig.SetActive(true); LapCompleteTrig.SetActive(false); } }
 using System.Collections.Generic; namespace ObjectDumper { public enum QueueType { Unknown, QueueTypeOne, QueueTypeTwo }; class Queue { public int Id { get; set; } public string Name { get; set; } public QueueType QueueType { get; set; } public int? NullableInt { get; set; } public List<Owner> Owners { get; set; } public List<Owner> OtherOwners { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; using System.Web.Mvc; using SSISTeam9.Services; namespace SSISTeam9.Filters { public class PendingDeliveryOrderFilter : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext context) { string sessionId = HttpContext.Current.Request["sessionId"]; string orderNumber = HttpContext.Current.Request["orderNumber"]; long empId = EmployeeService.GetUserBySessionId(sessionId).EmpId; long empIdOfOrder = PurchaseOrderService.GetOrderDetails(orderNumber).EmployeeId; if (empId != empIdOfOrder) { context.Result = new RedirectToRouteResult( new RouteValueDictionary { { "controller", "Home" }, { "action", "NotAuthorised" } } ); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Nailhang.Display { public static class StringUtils { public static Guid ToMD5(this string content) { using (var md5 = MD5.Create()) return new Guid(md5.ComputeHash(Encoding.UTF8.GetBytes(content))); } public static string GetNamespace(string typeName) { var splited = typeName.Split('.'); return splited.Take(splited.Length - 1) .Aggregate((a, b) => a + "." + b); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using NeuralNetwork; using NeuralNetwork.Core; namespace NeuralNetworkTests { [TestClass] public class BackpropagationTest { [TestMethod] public void GetErrorsOutputSignal() { //Arrange float[][] outputSignal = new float[][] { new float[] { 1 }, new float[] { 0 }, new float[] { 0 }, new float[] { 1 } }; float[][] actualSignal = new float[][] { new float[] { 1 }, new float[] { 0 }, new float[] { 0 }, new float[] { 1 } }; float[][] expected = new float[][] { new float[] { 0 }, new float[] { 0 }, new float[] { 0 }, new float[] { 0 } }; //Act var actual = NeuralMath.GetTotalLoss(outputSignal, actualSignal, LossFunc.MSE); //Assert for (int i = 0; i < expected.Length; i++) { for (int j = 0; j < expected[i].Length; j++) { Assert.AreEqual(expected[i][j], actual); } } } [TestMethod] public void GetDeltasErrorsOutputLayer() { //Arrange float[] outputSignal = new float[] { 0.95F, 0.55F, 0.40F, 0.90F }; float[] actualSignal = new float[] { 1, 0, 0, 1 }; float[] expected = new float[] { 0.002375001F, -0.136125F, -0.096F, 0.009000004F }; //Act var actual = Backpropagation.GetDeltasOutputLayer(outputSignal, actualSignal, ActivationFunc.Sigmoid); //Assert for (int i = 0; i < expected.Length; i++) { Assert.AreEqual(expected[i], actual[i]); } } [TestMethod] public void GetDeltasErrorsHiddenLayer() { //Arrange float[] outputSignal = new float[] { 0.95F, 0.55F, 0.90F }; float[][] weightsNextLayer = new float[][] { new float[] { 1 }, new float[] { 1 }, new float[] { 1 }, }; float[] deltasErrorsNextLayer = new float[] { 0.15F }; float[] expected = new float[] { 0.007125002F, 0.0371250026F, 0.0135000031F }; //Act var actual = Backpropagation.GetDeltasHiddenLayer(outputSignal, weightsNextLayer, deltasErrorsNextLayer, ActivationFunc.Sigmoid); //Assert for (int i = 0; i < expected.Length; i++) { Assert.AreEqual(expected[i], actual[i]); } } [TestMethod] public void GetGradientsForWeights() { //Arrange float[] inputSignal = new float[] { 0.95F, 0.55F, 0.90F }; float[] deltasErrorThisLayer = new float[] { 0.77F }; float[][] expected = new float[][] { new float[] { 0.73149997F }, new float[] { 0.4235F }, new float[] { 0.692999959F } }; //Act var actual = Backpropagation.GetGradientsForWeights(inputSignal, deltasErrorThisLayer); //Assert for (int i = 0; i < expected.Length; i++) { for (int j = 0; j < expected[i].Length; j++) { Assert.AreEqual(expected[i][j], actual[i][j]); } } } [TestMethod] public void GetUpdatesForWeights() { //Arrange float[][] gradientsForWeights = new float[][] { new float[] { 0.73F }, new float[] { 0.42F }, new float[] { 0.70F } }; float[][] updatesForWeightsOld = new float[][] { new float[] { 0.14F }, new float[] { 0.17F }, new float[] { 0.19F } }; float[][] expected = new float[][] { new float[] { 0.87F }, new float[] { 0.59F }, new float[] { 0.89F } }; //Act var actual = Backpropagation.GetUpdatesForWeights(gradientsForWeights, updatesForWeightsOld, 1, 1, LearningOptimizing.NAG); //Assert for (int i = 0; i < expected.Length; i++) { for (int j = 0; j < expected[i].Length; j++) { Assert.AreEqual(expected[i][j], actual[i][j]); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using static ProgressQuest.GameStrings; using static ProgressQuest.GameManager; namespace ProgressQuest.Models { public static class EquipmentManager { public static void Equip(ArmorItem item) { var oldItem = State.Player.Equipment.First(i => i.Slot == item.Slot); var index = State.Player.Equipment.IndexOf(oldItem); var oldLoot = new LootItem { Name = oldItem.Name, Value = oldItem.Value }; State.Player.Equipment.Remove(oldItem); State.Player.Equipment.Insert(index, item); State.Player.LastEquipped = index; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace BSTree.Tests { [TestClass] public class TraversingTests { [TestMethod] public void TestInorderTraverse() { var treeHead = GetTree(40); List<int> sortedKeys = new List<int>(); treeHead.InorderTraverse((key, value) => sortedKeys.Add(key)); } protected StdNode<int, string> GetTree(int count) { var treeHead = new StdNode<int, string>(); var testData = TestDataGenerator.GetKeysAndValues(count); FillTreeByTestData(treeHead, testData); return treeHead; } protected void FillTreeByTestData(StdNode<int, string> head, Tuple<int[], string[]> data) { var keys = data.Item1; var values = data.Item2; for (int i = 0; i < keys.Length; i++) head.Insert(keys[i], values[i]); } [TestMethod] public void TestPreorderTraverse() { var treeHead = GetTree(40); var allKeys = new List<int>(); treeHead.PreorderTraverse((key, value) => allKeys.Add(key)); } [TestMethod] public void TestPostorderTraverse() { var treeHead = GetTree(40); var allKeys = new List<int>(); treeHead.PostorderTraverse((key, value) => allKeys.Add(key)); } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Bidar.WebAPI.Domain; using Bidar.WebAPI.Services; using TalebiAPI.Domain; namespace TalebiAPI.Controllers { [ApiController] [Route("[controller]")] public class EmployeeController : ControllerBase { private readonly DataService _dataService; public EmployeeController() { _dataService = new DataService(); } [HttpPost] public int CreateUser(User user) { return _dataService.CreateUser(user); } [HttpPut] public bool Update(User user) { return _dataService.Update(user); } [HttpGet("/all")] public List<User> GetAll() { return _dataService.GetUsers(); } [HttpDelete("/delete/{id}")] public bool Remove(long id) { return _dataService.Delete(id); } } }
using UnityEngine; using UnityEditor; [CustomEditor(typeof(Experiment_Ctrl))] public class Experiment_Ctrl_Editor : Editor { KeyCode key; SerializedProperty SMI_Prefab; private void OnEnable() { SMI_Prefab = serializedObject.FindProperty("SMI_Prefab"); } public override void OnInspectorGUI() { Experiment_Ctrl ctrl = (Experiment_Ctrl)target; serializedObject.Update(); ctrl.SMI_Prefab = (GameObject)EditorGUILayout.ObjectField("SMI_Prefab", ctrl.SMI_Prefab, typeof(GameObject), true); ctrl.sample_rate = EditorGUILayout.FloatField("sample rate", ctrl.sample_rate); ctrl.stimulus_interval = EditorGUILayout.FloatField("stimulus interval", ctrl.stimulus_interval); ctrl.user_name = EditorGUILayout.TextField("user name", ctrl.user_name); SerializedProperty usrTags = serializedObject.FindProperty("usrTags"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(usrTags,true); if (EditorGUI.EndChangeCheck()) serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties(); } }
using Swan.Net; namespace Swan.Ldap { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// The central class that encapsulates the connection /// to a directory server through the Ldap protocol. /// LdapConnection objects are used to perform common Ldap /// operations such as search, modify and add. /// In addition, LdapConnection objects allow you to bind to an /// Ldap server, set connection and search constraints, and perform /// several other tasks. /// An LdapConnection object is not connected on /// construction and can only be connected to one server at one /// port. /// /// Based on https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard. /// </summary> /// <example> /// The following code describes how to use the LdapConnection class: /// /// <code> /// class Example /// { /// using Swan; /// using Swan.Ldap; /// using System.Threading.Tasks; /// /// static async Task Main() /// { /// // create a LdapConnection object /// var connection = new LdapConnection(); /// /// // connect to a server /// await connection.Connect("ldap.forumsys.com", 389); /// /// // set up the credentials /// await connection.Bind("cn=read-only-admin,dc=example,dc=com", "password"); /// /// // retrieve all entries that have the specified email using ScopeSub /// // which searches all entries at all levels under /// // and including the specified base DN /// var searchResult = await connection /// .Search("dc=example,dc=com", LdapConnection.ScopeSub, "(cn=Isaac Newton)"); /// /// // if there are more entries remaining keep going /// while (searchResult.HasMore()) /// { /// // point to the next entry /// var entry = searchResult.Next(); /// /// // get all attributes /// var entryAttributes = entry.GetAttributeSet(); /// /// // select its name and print it out /// entryAttributes.GetAttribute("cn").StringValue.Info(); /// } /// /// // modify Tesla and sets its email as tesla@email.com /// connection.Modify("uid=tesla,dc=example,dc=com", /// new[] { /// new LdapModification(LdapModificationOp.Replace, /// "mail", "tesla@email.com") /// }); /// /// // delete the listed values from the given attribute /// connection.Modify("uid=tesla,dc=example,dc=com", /// new[] { /// new LdapModification(LdapModificationOp.Delete, /// "mail", "tesla@email.com") /// }); /// /// // add back the recently deleted property /// connection.Modify("uid=tesla,dc=example,dc=com", /// new[] { /// new LdapModification(LdapModificationOp.Add, /// "mail", "tesla@email.com") /// }); /// /// // disconnect from the LDAP server /// connection.Disconnect(); /// /// Terminal.Flush(); /// } /// } /// </code> /// </example> public class LdapConnection : IDisposable { private const int LdapV3 = 3; private readonly CancellationTokenSource _cts = new CancellationTokenSource(); private Connection _conn; private bool _isDisposing; /// <summary> /// Returns the protocol version uses to authenticate. /// 0 is returned if no authentication has been performed. /// </summary> /// <value> /// The protocol version. /// </value> public int ProtocolVersion => BindProperties?.ProtocolVersion ?? LdapV3; /// <summary> /// Returns the distinguished name (DN) used for as the bind name during /// the last successful bind operation. null is returned /// if no authentication has been performed or if the bind resulted in /// an anonymous connection. /// </summary> /// <value> /// The authentication dn. /// </value> public string AuthenticationDn => BindProperties == null ? null : (BindProperties.Anonymous ? null : BindProperties.AuthenticationDN); /// <summary> /// Returns the method used to authenticate the connection. The return /// value is one of the following:. /// <ul><li>"none" indicates the connection is not authenticated.</li><li> /// "simple" indicates simple authentication was used or that a null /// or empty authentication DN was specified. /// </li><li>"sasl" indicates that a SASL mechanism was used to authenticate</li></ul> /// </summary> /// <value> /// The authentication method. /// </value> public string AuthenticationMethod => BindProperties == null ? "simple" : BindProperties.AuthenticationMethod; /// <summary> /// Indicates whether the connection represented by this object is open /// at this time. /// </summary> /// <returns> /// True if connection is open; false if the connection is closed. /// </returns> public bool Connected => _conn?.IsConnected == true; internal BindProperties BindProperties { get; set; } internal List<RfcLdapMessage> Messages { get; } = new List<RfcLdapMessage>(); /// <inheritdoc /> public void Dispose() { if (_isDisposing) return; _isDisposing = true; Disconnect(); _cts?.Dispose(); } /// <summary> /// Synchronously authenticates to the Ldap server (that the object is /// currently connected to) using the specified name, password, Ldap version, /// and constraints. /// If the object has been disconnected from an Ldap server, /// this method attempts to reconnect to the server. If the object /// has already authenticated, the old authentication is discarded. /// </summary> /// <param name="dn">If non-null and non-empty, specifies that the /// connection and all operations through it should /// be authenticated with dn as the distinguished /// name.</param> /// <param name="password">If non-null and non-empty, specifies that the /// connection and all operations through it should /// be authenticated with dn as the distinguished /// name and password. /// Note: the application should use care in the use /// of String password objects. These are long lived /// objects, and may expose a security risk, especially /// in objects that are serialized. The LdapConnection /// keeps no long lived instances of these objects.</param> /// <returns> /// A <see cref="Task" /> representing the asynchronous operation. /// </returns> public Task Bind(string dn, string password) => Bind(LdapV3, dn, password); /// <summary> /// Synchronously authenticates to the Ldap server (that the object is /// currently connected to) using the specified name, password, Ldap version, /// and constraints. /// If the object has been disconnected from an Ldap server, /// this method attempts to reconnect to the server. If the object /// has already authenticated, the old authentication is discarded. /// </summary> /// <param name="version">The Ldap protocol version, use Ldap_V3. /// Ldap_V2 is not supported.</param> /// <param name="dn">If non-null and non-empty, specifies that the /// connection and all operations through it should /// be authenticated with dn as the distinguished /// name.</param> /// <param name="password">If non-null and non-empty, specifies that the /// connection and all operations through it should /// be authenticated with dn as the distinguished /// name and passwd as password. /// Note: the application should use care in the use /// of String password objects. These are long lived /// objects, and may expose a security risk, especially /// in objects that are serialized. The LdapConnection /// keeps no long lived instances of these objects.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public Task Bind(int version, string dn, string password) { dn = string.IsNullOrEmpty(dn) ? string.Empty : dn.Trim(); var passwordData = string.IsNullOrWhiteSpace(password) ? Array.Empty<sbyte>() : Encoding.UTF8.GetSBytes(password); var anonymous = false; if (passwordData.Length == 0) { anonymous = true; // anonymous, password length zero with simple bind dn = string.Empty; // set to null if anonymous } BindProperties = new BindProperties(version, dn, "simple", anonymous); return RequestLdapMessage(new LdapBindRequest(version, dn, passwordData)); } /// <summary> /// Connects to the specified host and port. /// If this LdapConnection object represents an open connection, the /// connection is closed first before the new connection is opened. /// At this point, there is no authentication, and any operations are /// conducted as an anonymous client. /// </summary> /// <param name="host">A host name or a dotted string representing the IP address /// of a host running an Ldap server.</param> /// <param name="port">The TCP or UDP port number to connect to or contact. /// The default Ldap port is 389.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task Connect(string host, int port) { var tcpClient = new TcpClient(); await tcpClient.ConnectAsync(host, port).ConfigureAwait(false); _conn = new Connection(tcpClient, Encoding.UTF8, "\r\n", true, 0); #pragma warning disable 4014 Task.Run(RetrieveMessages, _cts.Token); #pragma warning restore 4014 } /// <summary> /// Synchronously disconnects from the Ldap server. /// Before the object can perform Ldap operations again, it must /// reconnect to the server by calling connect. /// The disconnect method abandons any outstanding requests, issues an /// unbind request to the server, and then closes the socket. /// </summary> public void Disconnect() { // disconnect from API call _cts.Cancel(); _conn.Disconnect(); } /// <summary> /// Synchronously reads the entry for the specified distinguished name (DN), /// using the specified constraints, and retrieves only the specified /// attributes from the entry. /// </summary> /// <param name="dn">The distinguished name of the entry to retrieve.</param> /// <param name="attrs">The names of the attributes to retrieve.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// the LdapEntry read from the server. /// </returns> /// <exception cref="LdapException">Read response is ambiguous, multiple entries returned.</exception> public async Task<LdapEntry> Read(string dn, string[] attrs = null, CancellationToken cancellationToken = default) { var sr = await Search(dn, LdapScope.ScopeSub, null, attrs, false, cancellationToken).ConfigureAwait(false); LdapEntry ret = null; if (sr.HasMore()) { ret = sr.Next(); if (sr.HasMore()) { throw new LdapException("Read response is ambiguous, multiple entries returned", LdapStatusCode.AmbiguousResponse); } } return ret; } /// <summary> /// Performs the search specified by the parameters, /// also allowing specification of constraints for the search (such /// as the maximum number of entries to find or the maximum time to /// wait for search results). /// </summary> /// <param name="base">The base distinguished name to search from.</param> /// <param name="scope">The scope of the entries to search.</param> /// <param name="filter">The search filter specifying the search criteria.</param> /// <param name="attrs">The names of attributes to retrieve.</param> /// <param name="typesOnly">If true, returns the names but not the values of /// the attributes found. If false, returns the /// names and values for attributes found.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A <see cref="Task" /> representing the asynchronous operation. /// </returns> public async Task<LdapSearchResults> Search( string @base, LdapScope scope, string filter = "objectClass=*", string[] attrs = null, bool typesOnly = false, CancellationToken cancellationToken = default) { // TODO: Add Search options var msg = new LdapSearchRequest(@base, scope, filter, attrs, 0, 1000, 0, typesOnly, null); await RequestLdapMessage(msg, cancellationToken).ConfigureAwait(false); return new LdapSearchResults(Messages, msg.MessageId); } /// <summary> /// Modifies the specified dn. /// </summary> /// <param name="distinguishedName">Name of the distinguished.</param> /// <param name="mods">The mods.</param> /// <param name="ct">The cancellation token.</param> /// <returns> /// A <see cref="Task" /> representing the asynchronous operation. /// </returns> /// <exception cref="ArgumentNullException">distinguishedName.</exception> public Task Modify(string distinguishedName, LdapModification[] mods, CancellationToken ct = default) { if (distinguishedName == null) { throw new ArgumentNullException(nameof(distinguishedName)); } return RequestLdapMessage(new LdapModifyRequest(distinguishedName, mods, null), ct); } internal async Task RequestLdapMessage(LdapMessage msg, CancellationToken ct = default) { using (var stream = new MemoryStream()) { LberEncoder.Encode(msg.Asn1Object, stream); await _conn.WriteDataAsync(stream.ToArray(), true, ct).ConfigureAwait(false); try { while (new List<RfcLdapMessage>(Messages).Any(x => x.MessageId == msg.MessageId) == false) await Task.Delay(100, ct).ConfigureAwait(false); } catch (ArgumentException) { // expected } var first = new List<RfcLdapMessage>(Messages).FirstOrDefault(x => x.MessageId == msg.MessageId); if (first != null) { var response = new LdapResponse(first); response.ChkResultCode(); } } } internal void RetrieveMessages() { while (!_cts.IsCancellationRequested) { try { var asn1Id = new Asn1Identifier(_conn.ActiveStream); if (asn1Id.Tag != Asn1Sequence.Tag) { continue; // loop looking for an RfcLdapMessage identifier } // Turn the message into an RfcMessage class var asn1Len = new Asn1Length(_conn.ActiveStream); Messages.Add(new RfcLdapMessage(_conn.ActiveStream, asn1Len.Length)); } catch (IOException) { // ignore } } // ReSharper disable once FunctionNeverReturns } } }
using System; namespace _9_Abstract { abstract class Shape { public int numSides; public abstract double GetArea(); } class Square : Shape { int n; public Square(int n) { numSides = 4; this.n = n; } public override double GetArea() { return n * n; } } class Triangle : Shape { double width, height; public Triangle(double width, double height) { this.width = width; this.height = height; numSides = 3; } public override double GetArea() { return width * height / 2; } } class Program { static void Main(string[] args) { var square = new Square(12); Console.WriteLine($"Area of the square = {square.GetArea()}"); var triangle = new Triangle(5, 2); Console.WriteLine($"Area of the triangle = {triangle.GetArea()}"); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Ideal.Ipos.RealTime.Skat.Model { public class Spieltisch { private readonly List<Spieler> m_Spieler = new List<Spieler>(3); private const int SpielerProTisch = 3; public Spieltisch() { this.ID = Guid.NewGuid().ToString("N"); } [JsonProperty(PropertyName = "id")] public string ID { get; private set; } [JsonProperty(PropertyName = "spieler")] public IEnumerable<Spieler> Spieler { get { return m_Spieler; } } public bool SpielerHinzufuegen(Spieler spieler) { if (this.Spieler.Count() >= SpielerProTisch) { return false; } m_Spieler.Add(spieler); return true; } public bool BenoetigteSpieleranzahlErreicht() { return m_Spieler.Count >= SpielerProTisch; } public void SpielerBereitFuerNeueRunde(string spielerID) { m_SpielerBereitFuerNeueRunde++; } public bool AlleSpielerBereit() { return m_SpielerBereitFuerNeueRunde >= SpielerProTisch; } private int m_SpielerBereitFuerNeueRunde = 0; public void NeueRundeStarten() { m_SpielerBereitFuerNeueRunde++; } } }
using AutoFixture; using NUnit.Framework; using System.Threading.Tasks; using FluentAssertions; using SFA.DAS.ProviderCommitments.Web.Mappers; using SFA.DAS.ProviderCommitments.Web.Models; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers { [TestFixture] public class WhenIMapBaseDraftApprenticeshipRequestFromSelectDeliveryModelViewModel { private BaseDraftApprenticeshipRequestFromSelectDeliveryModelViewModelMapper _mapper; private SelectDeliveryModelViewModel _source; [SetUp] public void Arrange() { var fixture = new Fixture(); _source = fixture.Create<SelectDeliveryModelViewModel>(); _mapper = new BaseDraftApprenticeshipRequestFromSelectDeliveryModelViewModelMapper(); } [Test] public async Task ProviderIdIsMapped() { var result = await _mapper.Map(_source); result.ProviderId.Should().Be(_source.ProviderId); } [Test] public async Task CohortReferenceIsMapped() { var result = await _mapper.Map(_source); result.CohortReference.Should().Be(_source.CohortReference); } [Test] public async Task DraftApprenticeshipHashedIdIsMapped() { var result = await _mapper.Map(_source); result.DraftApprenticeshipHashedId.Should().Be(_source.DraftApprenticeshipHashedId); } } }
namespace DFC.ServiceTaxonomy.GraphVisualiser.Models.Owl { public partial class Description { public string? En { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace MIDIDotNet { public static class InvokeLayer { public static class Messages { public const uint MM_MOM_OPEN = 0x3C7; public const uint MM_MOM_CLOSE = 0x3C8; public const uint MM_MOM_DONE = 0x3C9; } public static class MidiOpenFlags { public const uint CALLBACK_NULL = 0x00000000; public const uint CALLBACK_WINDOW = 0x00010000; public const uint CALLBACK_THREAD = 0x00020000; public const uint CALLBACK_FUNCTION = 0x00030000; public const uint CALLBACK_EVENT = 0x00050000; } public static class ErrorCode { public const uint MMSYSERR_NOERROR = 0x00000000; public const uint MMSYSERR_BADDEVICEID = 0x00000002; public const uint MMSYSERR_ALLOCATED = 0x00000004; public const uint MMSYSERR_INVALHANDLE = 0x00000005; } public static class MidiOutputDeviceType { public const uint MOD_MIDIPORT = 1; public const uint MOD_SYNTH = 2; public const uint MOD_SQSYNTH = 3; public const uint MOD_FMSYNTH = 4; public const uint MOD_MAPPER = 5; public const uint MOD_WAVETABLE = 6; public const uint MOD_SWSYNTH = 7; public static string[] Description = { "", "Port", "Synth", "Square-wave synth", "FM synth", "MIDI Mapper", "Wavetable synth", "Software synth" }; } public static class MidiInMessages { public const uint MM_MIM_OPEN = 0x3C1; public const uint MM_MIM_CLOSE = 0x3C2; public const uint MM_MIM_DATA = 0x3C3; public const uint MM_MIM_LONGDATA = 0x3C4; public const uint MM_MIM_ERROR = 0x3C5; public const uint MM_MIM_LONGERROR = 0x3C6; } [DllImport("winmm.dll")] public static extern uint midiInGetNumDevs(); #region midiInGetDevCaps [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] public class MIDIINCAPS { public const int MAXPNAMELEN = 32; public static readonly uint CBMIDIINCAPS = (uint)Marshal.SizeOf(typeof(MIDIINCAPS)); public ushort wMid; public ushort wPid; public uint vDriverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAXPNAMELEN)] public string szPName; public uint dwSupport; }; [DllImport("winmm.dll", CharSet = CharSet.Auto)] public static extern uint midiInGetDevCaps( IntPtr uDeviceID, [Out] MIDIINCAPS lpMidiInCaps, uint cbMidiInCaps); #endregion [DllImport("winmm.dll")] public static extern uint midiOutGetNumDevs(); #region midiOutGetDevCaps [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public class MIDIOUTCAPS { public const int MAXPNAMELEN = 32; public static readonly uint CBMIDIOUTCAPS = (uint)Marshal.SizeOf(typeof(MIDIOUTCAPS)); public ushort wMid; // 2 public ushort wPid; // 4 public uint vDriverVersion; // 8 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAXPNAMELEN)] public String szPName; public ushort wTechnology; // 10 public ushort wVoices; // 12 public ushort wNotes; // 14 public ushort wChannelMask; //16 public uint dwSupport; // 20 } [DllImport("winmm.dll", CharSet=CharSet.Auto)] public static extern uint midiOutGetDevCaps( IntPtr uDeviceID, [Out] MIDIOUTCAPS lpMidiOutCaps, uint cbMidiOutCaps); #endregion #region midiOutOpen public delegate void MidiOutProc(IntPtr lphmo, uint uMsg, IntPtr dwInstance, IntPtr dwParam1, IntPtr dwParam2); [DllImport("winmm.dll")] public static extern uint midiOutOpen( ref IntPtr lphmo, uint uDeviceID, MidiOutProc dwCallback, IntPtr dwCallbackInstance, uint dwFlags); #endregion #region midiOutClose [DllImport("winmm.dll")] public static extern uint midiOutClose(IntPtr hmo); #endregion #region midiOutMessage [DllImport("winmm.dll")] public static extern uint midiOutMessage( IntPtr deviceID, uint msg, IntPtr dw1, IntPtr dw2); [DllImport("winmm.dll")] public static extern uint midiOutShortMsg( IntPtr deviceID, uint dwMsg); #endregion #region midiInOpen public delegate void MidiInProc(IntPtr hMidiIn, uint uMsg, IntPtr dwInstance, IntPtr dwParam1, IntPtr dwParam2); [DllImport("winmm.dll")] public static extern uint midiInOpen( ref IntPtr lphMidiIn, uint uDeviceID, MidiInProc dwCallback, IntPtr dwCallbackInstance, uint dwFlags); #endregion #region midiInClose [DllImport("winmm.dll")] public static extern uint midiInClose(IntPtr hMidiIn); #endregion #region midiInStart [DllImport("winmm.dll")] public static extern uint midiInStart(IntPtr hMidiIn); #endregion #region midiInStop [DllImport("winmm.dll")] public static extern uint midiInStop(IntPtr hMidiIn); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HTB.Database.Views { public class qryLookupUser : Record { #region Property Declaration private int _userID; private string _userVorname; private string _userNachname; private string _userUsername; private int _userStatus; private string _abteilungCaption; [MappingAttribute(FieldType = MappingAttribute.FIELD_TYPE_ID, FieldAutoNumber = true)] public int UserID { get { return _userID; } set { _userID = value; } } public string UserVorname { get { return _userVorname; } set { _userVorname = value; } } public string UserNachname { get { return _userNachname; } set { _userNachname = value; } } public string UserUsername { get { return _userUsername; } set { _userUsername = value; } } public int UserStatus { get { return _userStatus; } set { _userStatus = value; } } public string AbteilungCaption { get { return _abteilungCaption; } set { _abteilungCaption = value; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem48 : ProblemBase { public override string ProblemName { get { return "48: Self powers"; } } public override string GetAnswer() { return StripCharacters(CalcAllSelfPowers(1000)).ToString(); } public decimal CalcAllSelfPowers(decimal max) { decimal sum = 0; for (int index = 1; index <= max; index++) { sum += CalcSelfPower(index); } return sum; } private decimal CalcSelfPower(decimal max) { decimal num = max; for (decimal index = 2; index <= max; index++) { num *= max; num = StripCharacters(num); } return num; } private decimal Multiply(decimal a, decimal b) { decimal sum = a; for (int count = 1; count < b; count++) { sum += a; sum = StripCharacters(sum); } return sum; } private decimal StripCharacters(decimal num) { if (num < 10000000000) { return num; } else { string text = num.ToString(); decimal power = 0; for (int index = 1; index <= 10; index++) { power += Convert.ToDecimal(text.Substring(text.Length - index, 1)) * (decimal)Math.Pow(10, index - 1); } string powerAsString = power.ToString(); if (powerAsString.Length > 10) { return Convert.ToInt32(powerAsString.Substring(powerAsString.Length - 10, 10)); } else { return power; } } } } }