text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WFadeOut : MonoBehaviour
{
float time = 0;
float fades = 1;
Text text;
public bool isPush;
WFadeIn wfi;
private void Start()
{
isPush = false;
text = GetComponent<Text>();
wfi = GetComponent<WFadeIn>();
}
void Update()
{
time += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Q) || Input.GetKeyDown(KeyCode.W))
{
if (wfi.isEnd == true)
{
isPush = true;
wfi.enabled = false;
}
}
if (isPush == true)
{
if (fades > 0 && time >= 0.1f)
{
fades -= 0.1f;
text.color = new Color(255, 255, 255, fades);
time = 0;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Excel2Binary
{
class Global
{
public const string VERSION = "1.0.0";
// 기타 등록정보
}
}
|
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual
{
/// <summary>
/// Implementacion del adaptador de Flujo Aprobacion
/// </summary>
public sealed class ProcesoAuditoriaAdapter
{
/// <summary>
/// Realiza la adaptación de campos para registrar o actualizar
/// </summary>
/// <param name="data"></param>
/// <returns>Indicador con el resultado de la operación</returns>
public static ProcesoAuditoriaEntity RegistrarFlujoAuditoria(ProcesoAuditoriaRequest data)
{
ProcesoAuditoriaEntity procesoAuditoriaEntity = new ProcesoAuditoriaEntity();
if (data.CodigoAuditoria != null)
{
procesoAuditoriaEntity.CodigoAuditoria = new Guid(data.CodigoAuditoria);
}
else
{
Guid code;
code = Guid.NewGuid();
procesoAuditoriaEntity.CodigoAuditoria = code;
}
procesoAuditoriaEntity.CodigoUnidadOperativa = new Guid(data.CodigoUnidadOperativa);
if (!string.IsNullOrWhiteSpace(data.FechaPlanificadaString))
{
procesoAuditoriaEntity.FechaPlanificada = DateTime.ParseExact(data.FechaPlanificadaString, DatosConstantes.Formato.FormatoFecha, System.Globalization.CultureInfo.InvariantCulture);
}
if (!string.IsNullOrWhiteSpace(data.FechaEjecucionString))
{
procesoAuditoriaEntity.FechaEjecucion = DateTime.ParseExact(data.FechaEjecucionString, DatosConstantes.Formato.FormatoFecha, System.Globalization.CultureInfo.InvariantCulture);
}
else
{
procesoAuditoriaEntity.FechaEjecucion = null;
}
procesoAuditoriaEntity.CantidadAuditadas = data.CantidadAuditadas;
procesoAuditoriaEntity.CantidadObservadas = data.CantidadObservadas;
procesoAuditoriaEntity.ResultadoAuditoria = data.ResultadoAuditoria;
return procesoAuditoriaEntity;
}
/// <summary>
/// Obtiene Proceso de Auditoria
/// </summary>
/// <param name="procesoAuditoriaLogic">Proceso Auditoria Logic</param>
/// <param name="unidadOperativa">Unidad Operativa</param>
/// <returns>Proceso de Auditoria</returns>
public static ProcesoAuditoriaResponse ObtenerProcesoAuditoria(
ProcesoAuditoriaLogic procesoAuditoriaLogic,
List<UnidadOperativaResponse> unidadOperativa
)
{
string sUnidadOperativa = null;
if (unidadOperativa != null)
{
var uoperativa = unidadOperativa.Where(n => n.CodigoUnidadOperativa.ToString() == procesoAuditoriaLogic.CodigoUnidadOperativa.ToString()).FirstOrDefault();
sUnidadOperativa = (uoperativa == null ? null : uoperativa.Nombre.ToString());
}
var procesoAuditoriaResponse = new ProcesoAuditoriaResponse();
procesoAuditoriaResponse.CodigoAuditoria = procesoAuditoriaLogic.CodigoAuditoria.ToString();
procesoAuditoriaResponse.CodigoUnidadOperativa = procesoAuditoriaLogic.CodigoUnidadOperativa.ToString();
procesoAuditoriaResponse.DescripcionUnidadOperativa = sUnidadOperativa;
procesoAuditoriaResponse.FechaPlanificada = procesoAuditoriaLogic.FechaPlanificada;
procesoAuditoriaResponse.FechaPlanificadaString = procesoAuditoriaLogic.FechaPlanificada.ToString(DatosConstantes.Formato.FormatoFecha);
procesoAuditoriaResponse.FechaEjecucion = procesoAuditoriaLogic.FechaEjecucion;
procesoAuditoriaResponse.FechaEjecucionString = procesoAuditoriaLogic.FechaEjecucion.HasValue ? procesoAuditoriaLogic.FechaEjecucion.Value.ToString(DatosConstantes.Formato.FormatoFecha) : string.Empty;
procesoAuditoriaResponse.CantidadAuditadas = procesoAuditoriaLogic.CantidadAuditadas;
procesoAuditoriaResponse.CantidadObservadas = procesoAuditoriaLogic.CantidadObservadas;
procesoAuditoriaResponse.ResultadoAuditoria = procesoAuditoriaLogic.ResultadoAuditoria;
return procesoAuditoriaResponse;
}
}
}
|
using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Models.Mapping
{
public class TitelMap : ClassMap<Titel>
{
public TitelMap()
{
Id(x => x.TitelID).GeneratedBy.HiLo("10");
Map(x => x.Bezeichnung).Not.Nullable();
Map(x => x.Vorgestellt);
}
}
}
|
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 MineSweeper.forms
{
public partial class Options : Form
{
private int kolommen;
private int rijen;
private int bommen;
private int max_size = 30;
public Options()
{
InitializeComponent();
}
private void Options_Load(object sender, EventArgs e)
{
//KOLOMMEN OPTIE
//Create a new label and text box
Label kolommenLabel = new Label();
TextBox kolommenTextBox = new TextBox();
//Initialize label's property
kolommenLabel.Text = "Aantal kolommen: ";
kolommenLabel.Location = new Point(10, 10);
kolommenLabel.AutoSize = true;
//Initialize textBoxes Property
int afstand = kolommenLabel.Width + 100;
kolommenTextBox.Location = new Point(afstand, kolommenLabel.Top - 3);
kolommenTextBox.TextChanged += new EventHandler(this.kolommenTextBox_TextChanged);
kolommenTextBox.MaxLength = 2;
//Add the labels and text box to the form
this.Controls.Add(kolommenLabel);
this.Controls.Add(kolommenTextBox);
//RIJEN OPTIE
//Create a new label and text box
Label rijenLabel = new Label();
TextBox rijenTextBox = new TextBox();
//Initialize label's property
rijenLabel.Text = "Aantal rijen: ";
rijenLabel.Location = new Point(10, 30);
rijenLabel.AutoSize = true;
//Initialize textBoxes Property
rijenTextBox.Location = new Point(afstand, rijenLabel.Top - 3);
rijenTextBox.TextChanged += new EventHandler(this.rijenTextBox_TextChanged);
rijenTextBox.MaxLength = 2;
//Add the labels and text box to the form
this.Controls.Add(rijenLabel);
this.Controls.Add(rijenTextBox);
//BOMMEN OPTIE
//Create a new label and text box
Label bommenLabel = new Label();
TextBox bommenTextBox = new TextBox();
//Initialize label's property
bommenLabel.Text = "Aantal bommen: ";
bommenLabel.Location = new Point(10, 50);
bommenLabel.AutoSize = true;
//Initialize textBoxes Property
bommenTextBox.Location = new Point(afstand, bommenLabel.Top - 3);
bommenTextBox.TextChanged += new EventHandler(this.bommenTextBox_TextChanged);
bommenTextBox.MaxLength = 3;
//Add the labels and text box to the form
this.Controls.Add(bommenLabel);
this.Controls.Add(bommenTextBox);
Button startButton = new Button();
startButton.Location = new Point(afstand, 70);
startButton.Visible = true;
startButton.Text = "Start";
startButton.Size = new Size(100, 20);
this.Controls.Add(startButton);
startButton.Click += new EventHandler(this.startButtonClick);
}
void startButtonClick(object sender, EventArgs e)
{
Boolean kolom = false;
Boolean rij = false;
Boolean bom = false;
if (kolommen <= max_size && kolommen > 0)
{
kolom = true;
}
if (rijen <= max_size && rijen > 0)
{
rij = true;
}
if (bommen < (max_size * max_size - 1) && bommen > 0 && bommen < kolommen * rijen)
{
bom = true;
}
if (kolom == true && rij == true)
{
if (bommen >= kolommen * rijen)
{
MessageBox.Show("Er bevinden zich meer bommen dan velden in het spel!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
// verzend kolommen + rijen + bommen
// MessageBox.Show("verzend kolommen + rijen + bommen", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Client.sbombs = bommen;
Client.sx = kolommen;
Client.sy = rijen;
this.Close();
}
}
else
{
string melding = String.Format("Let erop dat de waarden van de kolommen en rijen zich tussen de 1 en {0} moeten bevinden en van de bommen tussen 1 en {1}.",max_size,max_size*max_size-1);
MessageBox.Show(melding, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void kolommenTextBox_TextChanged(object sender, EventArgs e)
{
TextBox t = (TextBox)sender;
if (String.IsNullOrEmpty(t.Text))
{
kolommen = 0;
}
else
{
try
{
kolommen = Convert.ToInt32(t.Text);
kolommen = int.Parse(t.Text);
if (kolommen <= max_size && kolommen > 0)
{
}
else
{
string melding = String.Format("De waarden van kolommen ligt tussen 1 en {0}",max_size);
MessageBox.Show(melding, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (FormatException)
{
MessageBox.Show("Alleen getallen!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void rijenTextBox_TextChanged(object sender, EventArgs e)
{
TextBox t = (TextBox)sender;
if (String.IsNullOrEmpty(t.Text))
{
rijen = 0;
}
else
{
try
{
rijen = Convert.ToInt32(t.Text);
rijen = int.Parse(t.Text);
if (rijen <= max_size && rijen > 0)
{
}
else
{
string melding = String.Format("De waarden van rijen ligt tussen 1 en {0}", max_size);
MessageBox.Show(melding, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (FormatException)
{
MessageBox.Show("Alleen getallen!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void bommenTextBox_TextChanged(object sender, EventArgs e)
{
TextBox t = (TextBox)sender;
if (String.IsNullOrEmpty(t.Text))
{
bommen = 0;
}
else
{
try
{
bommen = Convert.ToInt32(t.Text);
bommen = int.Parse(t.Text);
int aantalVelden = kolommen * rijen;
if (bommen < (max_size * max_size-1) && bommen > 0)
{
if (bommen >= aantalVelden)
{
MessageBox.Show("Er zijn meer bommen in het veld dan dat er velden zijn verlaag het aantal bommen!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
string melding = String.Format("De waarden van het aantal bommen ligt tussen 1 en {0}",max_size*max_size-1);
MessageBox.Show(melding, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (FormatException)
{
MessageBox.Show("Alleen getallen!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
|
namespace TomsToolbox.Wpf
{
using System.Diagnostics.Contracts;
using System.Windows.Input;
using JetBrains.Annotations;
/// <summary>
/// Routed commands for window management.
/// </summary>
public static class WindowCommands
{
[NotNull] private static readonly RoutedUICommand _minimize = new RoutedUICommand("Minimize", "Minimize", typeof (WindowCommands));
[NotNull] private static readonly RoutedUICommand _maximize = new RoutedUICommand("Maximize", "Maximize", typeof(WindowCommands));
[NotNull] private static readonly RoutedUICommand _restore = new RoutedUICommand("Restore", "Restore", typeof(WindowCommands));
[NotNull] private static readonly RoutedUICommand _close = new RoutedUICommand("Close", "Close", typeof(WindowCommands));
/// <summary>
/// Gets the minimize window command.
/// </summary>
[NotNull]
public static RoutedUICommand Minimize
{
get
{
Contract.Ensures(Contract.Result<RoutedUICommand>() != null);
return _minimize;
}
}
/// <summary>
/// Gets the maximize window command.
/// </summary>
[NotNull]
public static RoutedUICommand Maximize
{
get
{
Contract.Ensures(Contract.Result<RoutedUICommand>() != null);
return _maximize;
}
}
/// <summary>
/// Gets the close window command.
/// </summary>
[NotNull]
public static RoutedUICommand Close
{
get
{
Contract.Ensures(Contract.Result<RoutedUICommand>() != null);
return _close;
}
}
/// <summary>
/// Gets the restore window command.
/// </summary>
[NotNull]
public static RoutedUICommand Restore
{
get
{
Contract.Ensures(Contract.Result<RoutedUICommand>() != null);
return _restore;
}
}
}
}
|
namespace VehiclesInfoModels.NonMotorVihicle
{
public class PassengerCarriage : Carriage
{
public int StandingPassengersCapacity { get; set; }
}
} |
using System;
namespace FeriaVirtual.Domain.Models.Users.Exceptions
{
public class InvalidSignInException
: Exception
{
public InvalidSignInException(string message)
: base(message) { }
}
}
|
using System;
using System.IO;
using System.Linq;
namespace Day1
{
class Program
{
static void Main()
{
static int FuelRequired(int mass)
{
var fuel = mass / 3 - 2;
if (fuel <= 0)
return 0;
else
return fuel + FuelRequired(fuel);
}
var totalFuel = File.ReadAllLines("Day1.txt")
.Select(line => int.Parse(line))
.Select(line => FuelRequired(line))
.Sum();
Console.WriteLine(totalFuel); //4739374
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Trivia
{
public class Players
{
private IList<Player> players;
private IEnumerator<Player> playerEnumerator;
public int Count
{
get
{
return players.Count;
}
}
public Player CurrentPlayer
{
get { return playerEnumerator.Current; }
}
public Players()
{
players = new List<Player>();
playerEnumerator = PlayerEnumerator();
}
public void AddPlayer(Player player)
{
players.Add(player);
}
public void AdvanceCurrentPlayer()
{
playerEnumerator.MoveNext();
}
private IEnumerator<Player> PlayerEnumerator()
{
while (true)
{
foreach (var player in players)
{
yield return player;
}
}
}
}
}
|
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 MySql.Data.MySqlClient;
namespace ProjetoAutoEscola
{
public partial class Login : Form
{
Principal principal = new Principal();
public Login()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btnCancelar_Click(object sender, EventArgs e)
{
Dispose();
}
private void btnEntrar_Click(object sender, EventArgs e)
{
/*
principal.Show();
this.Hide();
string CONFIG = ("Persist Security Info=False;server=localhost;database=autoescola_db;uid=root;server=localhost;database=autoescola_db;uid=root;pwd='oracle'");
MySqlConnection conexao = new MySqlConnection(CONFIG);
MySqlCommand comando = new MySqlCommand();
comando.Connection = conexao;
conexao.Open();
if (conexao.State == ConnectionState.Open)
{
MessageBox.Show("Salvo com sucesso!");
comando = new MySqlCommand("INSERT INTO aluno (num_mat, nome) VALUE ('" + random + "', '" + txtNome.Text + "')", conexao);
}
else
{
MessageBox.Show("Erro");
}*/
}
private void btnLimpar_Click(object sender, EventArgs e)
{
mskTxtSenha.Clear();
txtLogin.Clear();
}
private void txtLogin_TextChanged(object sender, EventArgs e)
{
Focus();
}
}
}
|
using System.Xml.Serialization;
namespace Appnotics.PCBackupLib
{
public class BackupDirectory
{
public string path { get; set; }
[XmlIgnore]
public string name { get; set; }
}
}
|
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Mapping.Contractual
{
/// <summary>
/// Implementación del mapeo de la entidad Contrato Parrafo Variable
/// </summary>
/// <remarks>
/// Creación: GMD 20150527 <br />
/// Modificación: <br />
/// </remarks>
public class ContratoParrafoVariableCampoMapping: BaseEntityMapping<ContratoParrafoVariableCampoEntity>
{
public ContratoParrafoVariableCampoMapping()
:base()
{
HasKey(x => x.CodigoContratoParrafoVariableCampo).ToTable("CONTRATO_PARRAFO_VARIABLE_CAMPO","CTR");
Property(u => u.CodigoContratoParrafoVariable).HasColumnName("CODIGO_CONTRATO_PARRAFO_VARIABLE");
Property(u => u.CodigoVariableCampo).HasColumnName("CODIGO_VARIABLE_CAMPO");
Property(u => u.NumeroFila).HasColumnName("NUMERO_FILA");
Property(u => u.Valor).HasColumnName("VALOR");
Property(u => u.EstadoRegistro).HasColumnName("ESTADO_REGISTRO");
Property(u => u.UsuarioCreacion).HasColumnName("USUARIO_CREACION");
Property(u => u.FechaCreacion).HasColumnName("FECHA_CREACION");
Property(u => u.TerminalCreacion).HasColumnName("TERMINAL_CREACION");
Property(u => u.UsuarioModificacion).HasColumnName("USUARIO_MODIFICACION");
Property(u => u.FechaModificacion).HasColumnName("FECHA_MODIFICACION");
Property(u => u.TerminalModificacion).HasColumnName("TERMINAL_MODIFICACION");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.Kanban
{
/// <summary>
/// IRAP树视图节点信息
/// </summary>
public class IRAPTreeViewNode
{
public int NodeID { get; set; }
public int TreeViewType { get; set; }
public int NodeType { get; set; }
public string NodeCode { get; set; }
public string NodeName { get; set; }
public int Parent { get; set; }
public int NodeDepth { get; set; }
public int CSTRoot { get; set; }
public double UDFOrdinal { get; set; }
public int NodeStatus { get; set; }
public int Accessibility { get; set; }
public int SelectStatus { get; set; }
public string SearchCode1 { get; set; }
public string SearchCode2 { get; set; }
public string HelpMemoryCode { get; set; }
public string IconFile { get; set; }
public byte[] IconImage { get; set; }
public IRAPTreeViewNode Clone()
{
IRAPTreeViewNode rlt = MemberwiseClone() as IRAPTreeViewNode;
return rlt;
}
}
} |
using geographymaster.Models;
using geographymaster.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
namespace geographymaster.Controllers
{
public class AdminController : Controller
{
#region Properties
UserRepository userRepository = new UserRepository();
QuestionRepository questionRepository = new QuestionRepository();
CategoryRepository categoryRepository = new CategoryRepository();
SubcategoryRepository subcategoryRepository = new SubcategoryRepository();
AnswerRepository answerRepository = new AnswerRepository();
HintRepository hintRepository = new HintRepository();
InfoBoxRepository infoboxRepository = new InfoBoxRepository();
public IEnumerable<Category> activeCategories;
public IEnumerable<Subcategory> activeSubcategories;
#endregion
public IEnumerable<Category> GetActiveCategories()
{
return activeCategories = categoryRepository.GetAllCategories();
}
public IEnumerable<Subcategory> GetActiveSubcategories()
{
return activeSubcategories = subcategoryRepository.GetAllSubCategories();
}
#region User
[HttpGet]
[Authorize]
public ActionResult CreateUser()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult CreateUser(User user)
{
user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password, "SHA1");
userRepository.CreateNewUser(user);
userRepository.SaveChanges();
return View("ListQuestions", "Admin");
}
#endregion
#region Login
[HttpGet]
public ViewResult Login()
{
return View(new LoginViewModel());
}
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var activeUser = userRepository.GetUserByUsername(model.Username);
if (Membership.ValidateUser(model.Username, FormsAuthentication.HashPasswordForStoringInConfigFile(model.Password, "SHA1")))
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(model);
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(1,
activeUser.Username,
DateTime.Now,
DateTime.Now.AddMinutes(45),
model.RememberMe,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);
return RedirectToAction("ListQuestions", "Admin");
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
#endregion
#region Question
[HttpGet]
[Authorize]
public ViewResult ListQuestions()
{
IEnumerable<Question> questions = questionRepository.GetAllQuestions();
return View(questions);
}
[Authorize]
[HttpGet]
public ActionResult AddQuestion()
{
return View(new QuestionViewModel()
{
Categories = GetActiveCategories(),
Subcategories = GetActiveSubcategories()
});
}
[Authorize]
[HttpPost]
public ActionResult AddQuestion(QuestionViewModel question)
{
if (ModelState.IsValid)
{
Question newQuestion = new Question()
{
IdCategory = question.CategoryId,
IdSubcategory = question.SubcatetegoryId,
Question1 = question.QuestionDetails.Question1,
NoStars = question.QuestionDetails.NoStars
};
questionRepository.CreateNewQuestion(newQuestion);
questionRepository.SaveChanges();
return RedirectToAction("ListQuestions", "Admin");
}
else
{
return RedirectToAction("AddQuestion", "Admin");
}
}
[Authorize]
[HttpGet]
public ActionResult EditQuestion(long idQuestion)
{
Question activeQuestion = questionRepository.GetQuestionByID(idQuestion);
return View(new QuestionViewModel()
{
QuestionDetails = activeQuestion,
Categories = GetActiveCategories(),
Subcategories = GetActiveSubcategories(),
QuestionId = idQuestion,
SubcatetegoryId = activeQuestion.IdSubcategory,
CategoryId = activeQuestion.IdCategory
});
}
[Authorize]
[HttpPost]
public ActionResult EditQuestion(QuestionViewModel question)
{
Question activeQuestion = questionRepository.GetQuestionByID(question.QuestionId);
if (activeQuestion != null && question.QuestionDetails.Question1 != null)
{
activeQuestion.IdCategory = question.CategoryId;
activeQuestion.IdSubcategory = question.SubcatetegoryId;
activeQuestion.NoStars = question.QuestionDetails.NoStars;
activeQuestion.Question1 = question.QuestionDetails.Question1;
questionRepository.SaveChanges();
}
return RedirectToAction("ListQuestions", "Admin");
}
[Authorize]
[HttpGet]
public ActionResult DetailsQuestion(long idQuestion)
{
Question activeQuestion = questionRepository.GetQuestionByID(idQuestion);
return View(activeQuestion);
}
[Authorize]
[HttpGet]
public ActionResult DeleteQuestion(long idQuestion)
{
questionRepository.DeleteQuestion(idQuestion);
questionRepository.SaveChanges();
return RedirectToAction("ListQuestions", "Admin");
}
#endregion
#region Answer
[Authorize]
[HttpGet]
public ViewResult ListAnswers(long idQuestion)
{
IEnumerable<Answer> answers = answerRepository.GetAllAnswers().Where(x => x.IdQuestion == idQuestion);
return View(new AnswerViewModel() { Answers = answers, IdQuestion = idQuestion });
}
[Authorize]
[HttpGet]
public ViewResult AddAnswer(long idQuestion)
{
return View(new AnswerViewModel()
{
QuestionDescription = questionRepository.GetAllQuestions()
.Where(x => x.IdQuestion == idQuestion)
.SingleOrDefault().Question1,
IdQuestion = idQuestion
});
}
[Authorize]
[HttpPost]
public ActionResult AddAnswer(AnswerViewModel answer)
{
if (ModelState.IsValid)
{
Answer newAnswer = new Answer()
{
IdQuestion = answer.IdQuestion,
AnswerDescription = answer.AnswerDescription,
IsTrue = answer.IsTrue
};
answerRepository.CreateNewAnswer(newAnswer);
answerRepository.SaveChanges();
return RedirectToAction("ListAnswers", "Admin", new { idQuestion = answer.IdQuestion });
}
else
{
return RedirectToAction("AddAnswer", "Admin");
}
}
[Authorize]
[HttpGet]
public ActionResult EditAnswer(int idAnswer)
{
Answer activeAnswer = answerRepository.GetAnswerByID(idAnswer);
return View(new AnswerViewModel()
{
AnswerDescription = activeAnswer.AnswerDescription,
IsTrue = activeAnswer.IsTrue,
IdQuestion = activeAnswer.IdQuestion
});
}
[Authorize]
[HttpPost]
public ActionResult EditAnswer(AnswerViewModel answer)
{
Answer activeAnswer = answerRepository.GetAnswerByID(answer.IdAnswer);
if (activeAnswer != null && answer.AnswerDescription != null)
{
activeAnswer.AnswerDescription = answer.AnswerDescription;
activeAnswer.IsTrue = answer.IsTrue;
answerRepository.SaveChanges();
}
return RedirectToAction("ListAnswers", "Admin", new { idQuestion = answer.IdQuestion });
}
[Authorize]
[HttpGet]
public ActionResult DeleteAnswer(long idAnswer)
{
long id = answerRepository.GetAnswerByID(idAnswer).IdQuestion;
answerRepository.DeleteAnswer(idAnswer);
answerRepository.SaveChanges();
return RedirectToAction("ListAnswers", "Admin", new { idQuestion = id });
}
#endregion
#region Hints
[Authorize]
[HttpGet]
public ViewResult ListHints(long idQuestion)
{
IEnumerable<Hint> hints = hintRepository.GetAllHints().Where(x => x.IdQuestion == idQuestion);
return View(new HintViewModel() { Hints = hints, IdQuestion = idQuestion });
}
[Authorize]
[HttpGet]
public ViewResult AddHint(long idQuestion)
{
return View(new HintViewModel()
{
QuestionDescription = questionRepository.GetAllQuestions()
.Where(x => x.IdQuestion == idQuestion)
.SingleOrDefault().Question1,
IdQuestion = idQuestion
});
}
[Authorize]
[HttpPost]
public ActionResult AddHint(HintViewModel hint)
{
if (ModelState.IsValid)
{
Hint newHint = new Hint()
{
IdQuestion = hint.IdQuestion,
Hint1 = hint.HintDescription
};
hintRepository.CreateNewHint(newHint);
hintRepository.SaveChanges();
return RedirectToAction("ListHints", "Admin", new { idQuestion = hint.IdQuestion });
}
else
{
return RedirectToAction("AddHint", "Admin");
}
}
[Authorize]
[HttpGet]
public ActionResult EditHint(int idHint)
{
Hint activeHint = hintRepository.GetHintByID(idHint);
return View(new HintViewModel()
{
HintDescription = activeHint.Hint1,
IdQuestion = activeHint.IdQuestion
});
}
[Authorize]
[HttpPost]
public ActionResult EditHint(HintViewModel hint)
{
Hint activeHint = hintRepository.GetHintByID(hint.IdHint);
if (activeHint != null && activeHint.Hint1 != null)
{
activeHint.Hint1 = hint.HintDescription;
activeHint.IdQuestion = hint.IdQuestion;
hintRepository.SaveChanges();
}
return RedirectToAction("ListHints", "Admin", new { idQuestion = hint.IdQuestion });
}
[Authorize]
[HttpGet]
public ActionResult DeleteHint(long idHint)
{
long id = hintRepository.GetHintByID(idHint).IdQuestion;
hintRepository.DeleteHint(idHint);
hintRepository.SaveChanges();
return RedirectToAction("ListHints", "Admin", new { idQuestion = id });
}
#endregion
#region Infoboxes
[Authorize]
[HttpGet]
public ActionResult ListInfoboxes()
{
return View(infoboxRepository.GetAllInfoBoxes());
}
[Authorize]
[HttpGet]
public ActionResult AddInfobox()
{
return View(new InfoboxViewModel() { Categories = GetActiveCategories() });
}
[Authorize]
[HttpPost]
public ActionResult AddInfobox(InfoboxViewModel infobox)
{
if (ModelState.IsValid)
{
InfoBox newInfobox = new InfoBox()
{
IdCategory = infobox.IdCategory,
InfoBox1 = infobox.InfoBoxDescription
};
infoboxRepository.CreateNewInfoBox(newInfobox);
infoboxRepository.SaveChanges();
return RedirectToAction("ListInfoboxes", "Admin");
}
else
{
return RedirectToAction("AddInfobox", "Admin");
}
}
[Authorize]
[HttpGet]
public ActionResult EditInfobox(long idInfobox)
{
InfoBox activeInfobox = infoboxRepository.GetInfoBoxByID(idInfobox);
return View(new InfoboxViewModel()
{
InfoBoxDescription = activeInfobox.InfoBox1,
Categories = GetActiveCategories(),
IdInfoBox = idInfobox
});
}
[Authorize]
[HttpPost]
public ActionResult EditInfobox(InfoboxViewModel infobox)
{
InfoBox activeInfobox = infoboxRepository.GetInfoBoxByID(infobox.IdInfoBox);
if (activeInfobox != null && activeInfobox.InfoBox1 != null)
{
activeInfobox.IdCategory = infobox.IdCategory;
activeInfobox.InfoBox1 = infobox.InfoBoxDescription;
infoboxRepository.SaveChanges();
}
return RedirectToAction("ListInfoboxes", "Admin");
}
[Authorize]
[HttpGet]
public ActionResult DeleteInfobox(long idInfobox)
{
infoboxRepository.DeleteInfoBox(idInfobox);
infoboxRepository.SaveChanges();
return RedirectToAction("ListInfoboxes", "Admin");
}
#endregion
}
}
|
using System.Threading.Tasks;
using CustomServiceRegistration.Models;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace CustomServiceRegistration.Services.Users
{
public interface IUserService
{
Task<bool> CreateAsync(RegistrationModel model);
ModelStateDictionary ModelState { get; }
Task<bool> EditUserAsync(UserModel model);
Task<UserModel> GetUser(string userEmail);
Task<UserModel> GetUserById(string userId);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
public class sphereScript : MonoBehaviour {
[Range(0,2000)]
public float forcex;
[Range(0,2000)]
public float forcey;
public bool Shoot;
Rigidbody rb;
public float x=0f,y=0f;
public Vector3 direction;
bool setDirection;
// Use this for initialization
void Start ()
{
setDirection = true;
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update ()
{
//x = Input.GetAxis ("Horizontal");
// y = Input.GetAxis ("Vertical");
}
void FixedUpdate()
{
if (Shoot)
{
if (setDirection)
{
setDirection = false;
direction = transform.forward;
}
}
}
void OnCollisionStay(Collision col)
{
if (Shoot)
{
if (col.gameObject.tag == "Accelerate")
{
forcey += 0.05f;
AccelerateMe ();
}
else
if (col.gameObject.tag == "Rotate")
{
forcex += 1f;
x += 0.03f;
RotateMe ();
}
else
{
x -= 0.05f;
y -= 0.05f;
}
}
}
void AccelerateMe()
{
//rb.AddForce ();
rb.velocity = direction*Time.deltaTime*forcey;
}
void RotateMe()
{
rb.velocity=direction*Time.deltaTime*forcey;
rb.AddTorque (new Vector3(y,0f,x)*Time.deltaTime*forcex);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace System
{
/// <summary>
/// Object对象的扩展类。
/// </summary>
public static class ObjectExtension
{
/// <summary>
/// 类型转换。
/// </summary>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <returns>返回结果。</returns>
public static T AsType<T>(this object obj) where T : class
{
return obj as T;
}//end method
/// <summary>
/// 隐式转换。
/// </summary>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <returns>返回结果。</returns>
public static T ToType<T>(this object obj)
{
return (T)obj;
}//end method
/// <summary>
/// 显式转换。
/// </summary>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <returns>返回结果。</returns>
public static T ToChangeType<T>(this object obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}//end method
/// <summary>
/// 隐式转换,匿名对象转换专用。
/// </summary>
/// <url>http://www.cnblogs.com/tianxiang2046/p/3586537.html</url>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <param name="t">匿名对象的初始化结构,例如:new{ Name = string.Empty, Age = 0 }。</param>
/// <returns>返回结果。</returns>
public static T ToAnonymousType<T>(this object obj, T t)
{
return (T)obj;
}//end method
/// <summary>
/// 隐式转换,如果有异常则直接返回结果类型的默认值。
/// </summary>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <returns>返回结果。</returns>
public static T ToTypeOrDefault<T>(this object obj)
{
try
{
return ToType<T>(obj);
}
catch
{
return default(T);
}
}//end method
/// <summary>
/// 显式转换,如果有异常则直接返回结果类型的默认值。
/// </summary>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <returns>返回结果。</returns>
public static T ToChangeTypeOrDefault<T>(this object obj)
{
return ToChangeTypeOrDefault<T>(obj, default(T));
}//end method
/// <summary>
/// 显式转换,如果有异常则直接返回指定的默认值。
/// </summary>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <param name="def">指定的默认值。</param>
/// <returns>返回结果。</returns>
public static T ToChangeTypeOrDefault<T>(this object obj, T def)
{
try
{
return ToChangeType<T>(obj);
}
catch
{
return def;
}
}
/// <summary>
/// 隐式转换,如果有异常则直接返回结果类型的默认值,匿名对象转换专用。
/// </summary>
/// <url>http://www.cnblogs.com/tianxiang2046/p/3586537.html</url>
/// <typeparam name="T">结果类型。</typeparam>
/// <param name="obj">Object对象。</param>
/// <param name="t">匿名对象的初始化结构,例如:new{ Name = string.Empty, Age = 0 }。</param>
/// <returns>返回结果。</returns>
public static T ToAnonymousTypeOrDefault<T>(this object obj, T t)
{
try
{
return ToAnonymousTypeOrDefault<T>(obj, t);
}
catch
{
return default(T);
}
}//end method
/// <summary>
/// 对象深拷贝。
/// </summary>
/// <typeparam name="T">对象泛型定义。</typeparam>
/// <param name="obj">Object对象。</param>
/// <returns>返回深拷贝后的对象。</returns>
public static T DeepCopy<T>(this T obj)
{
//如果是字符串或值类型则直接返回
if (obj is string || obj.GetType().IsValueType) return obj;
object retval = Activator.CreateInstance(obj.GetType());
FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
try
{
field.SetValue(retval, DeepCopy(field.GetValue(obj)));
}
catch { }
}
return (T)retval;
}//end method
/// <summary>
/// 对象自适应。
/// </summary>
/// <typeparam name="T">对象泛型定义。</typeparam>
/// <param name="obj">Object对象。</param>
/// <param name="action">自适应的方法委托。</param>
/// <returns>返回结果。</returns>
public static T Adaptive<T>(this T obj, Action<T> action)
{
action?.Invoke(obj);
return obj;
}//end method
/// <summary>
/// 对象自适应。
/// </summary>
/// <typeparam name="TIn">输入对象泛型定义。</typeparam>
/// <typeparam name="TOut">输出对象泛型定义。</typeparam>
/// <param name="obj">Object对象。</param>
/// <param name="precidate">自适应的方法委托。</param>
/// <returns>返回结果。</returns>
public static TOut Adaptive<TIn, TOut>(this TIn obj, Func<TIn, TOut> precidate)
{
return precidate == null ? default(TOut) : precidate(obj);
}//end method
}//end class
}//end namespace
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class eventInformationitem : MonoBehaviour {
public Image Image;
public GameObject EventInformationGO;
public Text Title, Description;
public Button CompleteButton;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
/* 作者: 盛世海
* 创建时间: 2012/7/19 10:36:31
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using MODEL.ViewModel;
using Common;
using Common.Attributes;
using IBLLService;
using ShengUI.Helper;
using MODEL;
using Common.EfSearchModel.Model;
using MODEL.DataTableModel;
using MODEL.ViewPage;
namespace ShengUI.Logic.Admin
{
[AjaxRequestAttribute]
[Description("产品管理")]
public class ProductController : Controller
{
IMST_PRD_MANAGER prdB = OperateContext.Current.BLLSession.IMST_PRD_MANAGER;
IMST_CATEGORY_MANAGER categroyB = OperateContext.Current.BLLSession.IMST_CATEGORY_MANAGER;
[DefaultPage]
[ActionParent]
[ActionDesc("产品管理首页")]
[Description("[产品管理]产品管理首页列表信息")]
public ActionResult ProductIndex()
{
return View();
}
[ActionDesc("产品详细信息")]
[Description("[产品管理]产品详细信息(add,Update,Detail必备)")]
public ActionResult ProductDetail(string id)
{
ViewBag.TYPE = "Add";
ViewBag.CATE_IDS = DataSelect.ToListViewModel(VIEW_MST_CATEGORY.ToListViewModel(categroyB.GetListBy(m => m.ISSHOW == true && m.ACTIVE == true)));
var model = prdB.Get(m => m.PRD_CD == id);
if (model == null)
{
return View(new VIEW_MST_PRD() { PRD_CD = "PRD"+Common.Tools.Get8Digits() });
}
ViewBag.TYPE = "Update";
return View(VIEW_MST_PRD.ToViewModel(model));
}
[ActionDesc("产品管理获取产品信息列表")]
[Description("[产品管理]获取产品信息(主页必须)")]
public ActionResult GetProductForGrid(QueryModel model)
{
DataTableRequest request = new DataTableRequest(HttpContext,model);
return this.JsonFormat(prdB.GetProductsForGrid(request));
}
public ActionResult UploadProductImg()
{
bool status = false;
var fileurl = UploadRequestImg.OneImageSave(HttpContext);
status = true;
return this.JsonFormat(fileurl, status, "上传成功!");
}
[ValidateInput(false)]
[ActionDesc("添加", "Y")]
[Description("[产品管理]添加动作")]
public ActionResult Add(VIEW_MST_PRD model)
{
bool status = false;
if (!ModelState.IsValid)
return this.JsonFormat(ModelState, status, "ERROR");
var prd = VIEW_MST_PRD.ToEntity(model);
try
{
prd.ISCHECK = true;
prd.CREATE_BY = OperateContext.Current.UsrId;
prd.CREATE_DT = DateTime.Now;
prdB.Add(prd);
status = true;
}
catch (Exception e)
{
return this.JsonFormat(status, status, SysOperate.Add);
}
return this.JsonFormat("/Admin/Product/ProductIndex", status, SysOperate.Add.ToMessage(status), status);
}
[ValidateInput(false)]
[ActionDesc("修改", "Y")]
[Description("[产品管理]修改动作")]
public ActionResult Update(VIEW_MST_PRD model)
{
bool status = false;
if (!ModelState.IsValid)
return this.JsonFormat(ModelState, status, "ERROR");
var prd = VIEW_MST_PRD.ToEntity(model);
try
{
prd.MODIFY_DT = DateTime.Now;
prdB.Modify(prd, "PRD_NAME", "CATE_ID", "PRD_SHORT_DESC", "PRD_DESC", "ISHOT", "STATUS", "PRICE", "ARKETPRICE", "FRONTPRICE", "REMARK1", "SEQ_NO", "MODIFY_DT");
status = true;
}
catch (Exception ex)
{
return this.JsonFormat(status, !status, ex.Message + ex.StackTrace);
}
return this.JsonFormat("/Admin/Product/ProductIndex", status, SysOperate.Update.ToMessage(status), status);
}
[ActionDesc("删除", "Y")]
[Description("[产品管理]软删除动作")]
public ActionResult Delete()
{
var ids = HttpContext.Request["Ids"].Split(',').ToList();
var data = false;
try
{
MODEL.MST_PRD prd = new MODEL.MST_PRD() {ISCHECK=false, SYNCOPERATION = "D" };
if (prdB.ModifyBy(prd, p => ids.Contains(p.PRD_CD), "ISCHECK", "SYNCOPERATION") > 0)
{
data = true;
}
return this.JsonFormat(data, data, SysOperate.Delete);
}
catch (Exception)
{
return this.JsonFormat(data, data, SysOperate.Delete);
}
}
[ActionDesc("亮灯", "Y")]
[Description("[产品管理]设置热门")]
public ActionResult SetHot()
{
var ids = HttpContext.Request["Ids"].Split(',').ToList();
var data = false;
try
{
MODEL.MST_PRD prd = new MODEL.MST_PRD() { ISHOT = true, SYNCOPERATION = "U" };
if (prdB.ModifyBy(prd, p => ids.Contains(p.PRD_CD), "ISHOT", "SYNCOPERATION") > 0)
{
data = true;
}
return this.JsonFormat(data, data, SysOperate.Update);
}
catch (Exception)
{
return this.JsonFormat(data, data, SysOperate.Update);
}
}
[ActionDesc("取消亮灯", "Y")]
[Description("[产品管理]取消热门")]
public ActionResult CanceHot()
{
//var ids = HttpContext.Request["Ids"].Split(',').ToList();
var data = false;
try
{
MODEL.MST_PRD prd = new MODEL.MST_PRD() { ISHOT = false, SYNCOPERATION = "U" };
if (prdB.ExcuteSql("update MST_PRD set ishot=0") > 0)
{
data = true;
}
return this.JsonFormat(data, data, SysOperate.Update);
}
catch (Exception)
{
return this.JsonFormat(data, data, SysOperate.Update);
}
}
[ActionDesc("永久删除", "Y")]
[Description("[产品管理]永久删除动作")]
public ActionResult RealDelete()
{
bool status = false;
try
{
status = true;
}
catch (Exception e)
{
return this.JsonFormat(status, status, SysOperate.Delete);
}
return this.JsonFormat(status, status, SysOperate.Delete);
}
//[Description("[产品详细信息]获取产品分类信息(语言)")]
//public ActionResult GetProductCategoryByLanguage()
//{
// return this.JsonFormat("");
//}
[ActionDesc("永久删除图片")]
[Description("[产品管理]永久删除图片")]
public ActionResult DeleteImg()
{
string url = @" " + HttpContext.Request["ImageUrl"];
url = Server.MapPath("~");
try
{
FileOperate.FileDel(HttpContext.Server.MapPath(url));
FileOperate.FileDel(HttpContext.Server.MapPath(url + "_150x150.jpg"));
FileOperate.FileDel(HttpContext.Server.MapPath(url + "_359x359.jpg"));
FileOperate.FileDel(HttpContext.Server.MapPath(url + "_680x680.jpg"));
return Content("ok");
}
catch (Exception ex)
{
return Content("no" + ex.Message);
}
}
}
}
|
//Here is an example of how to controll your MySQL database from C# code. BE CAREFUL this is not secured.
//Every data, string etc. could be get from a form, from console or whatever, DO NOT HARDCODE THE QUERIES AND DATABASE DATAS
//I only wrote the CRUD operations and the Backup/Restore method, but every other query should work this way
//It's not the optimazed way, you can make prepared statements/functions in your database and just call them in the code.
//This script is based on:
//https://www.codeproject.com/Articles/43438/Connect-C-to-MySQL?fid=1551304&df=90&mpp=25&sort=Position&spc=Relaxed&prof=True&view=Normal&fr=1#_articleTop
//Prerequisite: - runnin MySQL server
// - MySql.Data library in your C# project's reference (you can download it through the NuGet package manager)
// - MySqlBackup.NET library in your C# project's reference
// - (optional) GUI to check your database (e.g.: MySQL Workbench)
/*------------------------------------------------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.IO;
namespace ExampleProject
{
class MySQLDatabaseController
{
//Fields
private MySqlConnection connection;
private string server;
private string database;
private string username;
private string password;
//Constructor
public MySQLDatabaseController()
{
Initialize();
}
private void Initialize()
{
server = "";
database = "";
username = "";
password = "";
string ConnectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + username + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//Open connection to database
//The exception's number are based on the MySQL Documentation
private bool OpenConnection()
{
try
{
connection.Open();
Console.WriteLine("Connection success!");
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
Console.WriteLine("Cannot connect to server. Contact administrator");
break;
case 1045:
Console.WriteLine("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
Console.WriteLine("Connection closed!");
return true;
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
//CREATE TABLE
public void CreateTable()
{
string query = "CREATE TABLE 'table_name' (column_name column_type) table_attributes;";
if(this.OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
Console.WriteLine("Table created successfully!");
}
catch(MySqlException ex)
{
Console.WriteLine("Table creation failed! ERROR MESSAGE: " + ex.Message);
}
}
}
//INSERT INTO table
public void Insert()
{
string query = "INSERT INTO table_name (column_1, column_2, column_n) VALUES(column_1_data, column_2_data, column_n_data);";
if (this.OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
Console.WriteLine("Insert into table success!");
}
catch(MySqlException ex)
{
Console.WriteLine("Data insert failed!. ERROR MESSAGE: " + ex.Message);
}
}
}
//SELECT statement
//Before you copy this, you should notice, that I saved the querie's result in a string List (or if you want, you can make a generic type List, Dictionary, etc),
//but this is optional. If you just want a true or false back, you should make your functions return type Boolen
public List<string> SelectStatement()
{
string query = "SELECT optional_column(s) FROM table(s)_name;";
List<string> selectResultList = new List<string>();
if(this.OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dr = cmd.ExecuteReader();
selectResultList.Add("column_1_name" + " " + "column_n_name");
while(dr.Read())
{
selectResultList.Add(dr["column_1"] + " " + ["column_n"]);
}
dr.Close();
this.CloseConnection();
return selectResultList;
}
catch(MySqlException ex)
{
Console.WriteLine("Select data failed!. ERROR MESSAGE: " + ex.Message);
}
}
else
{
return selectResultList;
}
}
//UPDATE statement
public void Update()
{
string query = "UPDATE table_name SET column_name='value';";
if (this.OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = connection;
cmd.ExecuteNonQuery();
this.CloseConnection();
}
catch(MySqlException ex)
{
Console.WriteLine("Select data failed!. ERROR MESSAGE: " + ex.Message);
}
}
}
//DELETE statement
public void Delete()
{
//Based on your goal, you can delete everything from a table or just with conditions
string query = "DELETE FROM table_name;";
string queryWithCondition = "DELETE FROM table_name WHERE condition;";
if (this.OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
catch(MySqlException ex)
{
Console.WriteLine("Select data failed!. ERROR MESSAGE: " + ex.Message);
}
}
}
//BACKUP
public void Backup()
{
try
{
DateTime time = DateTime.Now;
int year = time.Year;
int month = time.Month;
int day = time.Day;
int hour = time.Hour;
int minute = time.Minute;
int second = time.Second;
int millisecond = time.Millisecond;
string file;
file = @"full_path_to_the_file\MySqlBackup" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
if (this.OpenConnection() == true)
{
using (MySqlCommand command = new MySqlCommand())
{
using (MySqlBackup backup = new MySqlBackup(command))
{
command.Connection = connection;
backup.ExportToFile(file);
connection.Close();
}
}
}
Console.WriteLine("Backup success!");
}
catch (IOException ex)
{
Console.WriteLine("Error, unable to backup! " + ex.Message);
}
}
//RESTORE
public void Restore()
{
try
{
string file;
file = @"full_path_to_the_file\filename.sql";
if (this.OpenConnection() == true)
{
using (MySqlCommand command = new MySqlCommand())
{
using (MySqlBackup backup = new MySqlBackup(command))
{
command.Connection = connection;
//Be careful, package may be bigger than the supported size!
backup.ImportFromFile(file);
connection.Close();
}
}
}
Console.WriteLine("Restore completed!");
}
catch (IOException ex)
{
Console.WriteLine("Error, unable to backup! " + ex.Message);
}
}
}
}
|
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 lab_004
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
base.Text = "Введите пароль";
textBox1.Text = null;
textBox1.TabIndex = 0;
textBox1.PasswordChar = '☺';
textBox1.Font = new Font("Courier New", 12.0F);
label1.Text = string.Empty;
label1.Font = new Font("Courier New", 9.0F);
button1.Text = "Покажи паспорт";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="GraphicsCamera.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.KinectFusionExplorer
{
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Media3D;
using Microsoft.Kinect;
using Microsoft.Kinect.Fusion;
using Wpf3DTools;
/// <summary>
/// Basic Camera class
/// </summary>
public class GraphicsCamera : IDisposable
{
#region Fields
/// <summary>
/// Graphics camera horizontal field of view, approximately equivalent to default Kinect camera parameters
/// Note: In WPF the camera's horizontal rather the vertical field-of-view is specified when creating a perspective camera.
/// </summary>
public const float DefaultNominalHorizontalFov = 58.5f;
/// <summary>
/// Graphics camera vertical field of view (approximately 45degrees), equivalent to default Kinect camera parameters
/// </summary>
public const float DefaultNominalVerticalFov = 45.6f;
/// <summary>
/// Graphics camera near plane in m
/// </summary>
public const float DefaultCameraNear = 0.1f;
/// <summary>
/// Graphics camera far plane in m
/// </summary>
public const float DefaultCameraFar = 1000.0f;
/// <summary>
/// Frustum size in m
/// </summary>
public const float DefaultCameraFrustumSize = 1.0f;
/// <summary>
/// Camera Frustum 3D graphics line thickness in pixels
/// </summary>
public const int DefaultCameraFrustumLineThickness = 2;
/// <summary>
/// Translate mouse speed (to convert pixels to m)
/// </summary>
private const float TranslateMouse = 0.0002f;
/// <summary>
/// Translate mouse wheel speed (to convert wheel units to m)
/// </summary>
private const float TranslateWheel = 0.001f;
/// <summary>
/// Rotate mouse speed (to convert pixels to radians)
/// </summary>
private const float RotateMouse = 0.005f;
/// <summary>
/// Default normalized Kinect camera parameters
/// </summary>
private static CameraParameters camParams = CameraParameters.Defaults;
/// <summary>
/// Camera Frustum 3D graphics line color
/// </summary>
private static System.Windows.Media.Color defaultCameraFrustumLineColor = System.Windows.Media.Color.FromArgb(180, 240, 240, 0); // Yellow, partly transparent
/// <summary>
/// The perspective camera cumulative view transform for graphics rendering
/// </summary>
private Transform3DGroup cumulativeCameraViewTransform = new Transform3DGroup();
/// <summary>
/// The perspective camera partial transform for graphics rendering
/// </summary>
private AxisAngleRotation3D rotationTransform = new AxisAngleRotation3D();
/// <summary>
/// The perspective camera partial transform for graphics rendering
/// </summary>
private TranslateTransform3D translateTransform = new TranslateTransform3D();
/// <summary>
/// The perspective camera cumulative transform for graphics rendering (inverse of cumulativeCameraViewTransform)
/// </summary>
private MatrixTransform3D cumulativeCameraTransform = new MatrixTransform3D();
/// <summary>
/// The transform for frustum graphics rendering
/// </summary>
private MatrixTransform3D cameraFrustumTransform3D = new MatrixTransform3D();
/// <summary>
/// The cumulative transform for frustum graphics rendering, including a 180 degree rotation to view towards -Z
/// </summary>
private Transform3DGroup cumulativeCameraFrustumTransform = new Transform3DGroup();
/// <summary>
/// The Viewport3D that the CameraFrustum is added to
/// </summary>
private Viewport3D graphicsViewport = null;
/// <summary>
/// The UI element to attach to and receive mouse events from
/// </summary>
private UIElement attachedElement = null;
/// <summary>
/// True when mouse left button pressed
/// </summary>
private bool mousePressedLeft = false;
/// <summary>
/// True when mouse right button pressed
/// </summary>
private bool mousePressedRight = false;
/// <summary>
/// Last mouse button press position
/// </summary>
private Point buttonPressMousePosition = new Point(0, 0);
/// <summary>
/// The current position that the mouse is in when a button is clicked or held down inside the active area
/// </summary>
private Point currentMousePosition = new Point();
/// <summary>
/// Track whether Dispose has been called
/// </summary>
private bool disposed = false;
/// <summary>
/// Lock for updating pose
/// </summary>
private object transformUpdateLock = new object();
/// <summary>
/// Set true when the frustum 3D graphics are added to the viewport scene
/// </summary>
private bool haveAddedFrustumGraphics = false;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="GraphicsCamera"/> class.
/// </summary>
/// <param name="startTranslation">The start translation.</param>
/// <param name="startRotation">The start rotation.</param>
/// <param name="aspectRatio">The aspect ratio of the image or window.</param>
public GraphicsCamera(Point3D startTranslation, Quaternion startRotation, float aspectRatio)
: this(startTranslation, startRotation, DefaultNominalHorizontalFov, aspectRatio, DefaultCameraNear, DefaultCameraFar, DefaultCameraFrustumSize)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GraphicsCamera"/> class.
/// </summary>
/// <param name="startTranslation">The start translation.</param>
/// <param name="startRotation">The start rotation.</param>
/// <param name="fovDegrees">The field of view in degrees.</param>
/// <param name="aspectRatio">The aspect ratio of the image or window.</param>
/// <param name="near">The near plane distance.</param>
/// <param name="far">The far plane distance.</param>
public GraphicsCamera(Point3D startTranslation, Quaternion startRotation, float fovDegrees, float aspectRatio, float near, float far)
: this(startTranslation, startRotation, fovDegrees, aspectRatio, near, far, DefaultCameraFrustumSize)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GraphicsCamera"/> class.
/// Note: In WPF, the standard Right Hand coordinate system has the +X axis to the right, +Y axis up, and +Z axis out of the screen towards the viewer
/// ^ +Y
/// |
/// +----> +X
/// /
/// / +Z
/// </summary>
/// <param name="startTranslation">The start translation.</param>
/// <param name="startRotation">The start rotation.</param>
/// <param name="fovDegrees">The field of view in degrees.</param>
/// <param name="aspectRatio">The aspect ratio of the image or window.</param>
/// <param name="near">The near plane distance.</param>
/// <param name="far">The far plane distance.</param>
/// <param name="frustumSize">The length of the frustum sides to draw visually.</param>
public GraphicsCamera(Point3D startTranslation, Quaternion startRotation, float fovDegrees, float aspectRatio, float near, float far, float frustumSize)
{
this.FrustumSize = frustumSize;
this.NearPlane = near;
this.FarPlane = far;
this.StartTranslation = startTranslation;
this.StartRotation = startRotation;
this.AspectRatio = aspectRatio;
// Add the transform components into the cumulative transform
// Normally this would be SRT for world transform of objects, and the inverted form for the camera view (TRS),
// but here as we are controlling the camera view directly, to orbit around the origin, we can use TR (with scale always 1)
this.cumulativeCameraViewTransform.Children.Add(this.translateTransform);
this.cumulativeCameraViewTransform.Children.Add(new RotateTransform3D(this.rotationTransform));
// We set the initial translation to 0 here as we implement the transformation explicitly.
// By default the look direction puts a 180 degree transform on the look direction (i.e. we look back along -Z into the screen)
this.Camera = new PerspectiveCamera(new Point3D(0, 0, 0), new Vector3D(0, 0, -1), new Vector3D(0, 1, 0), fovDegrees); // look towards the origin
this.Camera.NearPlaneDistance = near;
this.Camera.FarPlaneDistance = far;
// Attach the camera transform to the Perspective camera
this.Camera.Transform = this.cumulativeCameraViewTransform;
this.attachedElement = null;
this.Reset();
}
/// <summary>
/// Finalizes an instance of the GraphicsCamera class.
/// This destructor will run only if the Dispose method does not get called.
/// </summary>
~GraphicsCamera()
{
this.Dispose(false);
}
#region properties
/// <summary>
/// Delegate for Event which signals camera transformation has changed
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
internal delegate void TransformationChangedEventHandler(object sender, EventArgs e);
/// <summary>
/// Event to signal camera transformation has changed
/// </summary>
internal event TransformationChangedEventHandler CameraTransformationChanged;
/// <summary>
/// Gets the perspective camera for graphics rendering
/// </summary>
public PerspectiveCamera Camera { get; private set; }
/// <summary>
/// Gets the perspective camera Projection matrix for graphics rendering
/// </summary>
public Matrix3D Projection
{
get
{
return MathUtils.GetProjectionMatrix(this.Camera, this.AspectRatio);
}
}
/// <summary>
/// Gets the camera start translation in world coordinates
/// </summary>
public Point3D StartTranslation { get; private set; }
/// <summary>
/// Gets the camera start rotation from identity
/// </summary>
public Quaternion StartRotation { get; private set; }
/// <summary>
/// Gets the camera transform matrix (i.e. CameraToWorld Transform, or SE3)
/// </summary>
public Matrix3D CameraToWorldMatrix3D
{
get
{
lock (this.transformUpdateLock)
{
return this.Camera.Transform.Value;
}
}
}
/// <summary>
/// Gets or sets the camera View matrix (i.e. WorldToCamera Transform) as Matrix3D
/// </summary>
public Matrix3D WorldToCameraMatrix3D
{
get
{
lock (this.transformUpdateLock)
{
return this.cumulativeCameraViewTransform.Value;
}
}
set
{
lock (this.transformUpdateLock)
{
Matrix3D transform = value;
this.UpdateTransform(KinectFusionHelper.Matrix3DToQuaternion(transform), new Vector3D(transform.OffsetX, transform.OffsetY, transform.OffsetZ));
}
}
}
/// <summary>
/// Gets or sets the camera View matrix (i.e. WorldToCamera Transform) as Matrix4
/// </summary>
public Matrix4 WorldToCameraMatrix4
{
get
{
lock (this.transformUpdateLock)
{
// Assumes T,R
Matrix3D trans = this.cumulativeCameraViewTransform.Children[0].Value;
Matrix3D rot = this.cumulativeCameraViewTransform.Children[1].Value;
Quaternion q = KinectFusionHelper.Matrix3DToQuaternion(rot);
double angle = q.Angle;
Vector3D axis = q.Axis;
axis.X = -axis.X; // negate x rotation
Matrix3D newMat = Matrix3D.Identity;
newMat.Rotate(new Quaternion(axis, angle));
newMat.OffsetX = -trans.OffsetX; // negate x translation
newMat.OffsetY = trans.OffsetY;
newMat.OffsetZ = trans.OffsetZ;
return KinectFusionHelper.ConvertMatrix3DToMatrix4(newMat);
}
}
set
{
Matrix3D transform = KinectFusionHelper.ConvertMatrix4ToMatrix3D(value);
Quaternion q = KinectFusionHelper.Matrix3DToQuaternion(transform);
double angle = q.Angle;
Vector3D axis = q.Axis;
axis.X = -axis.X; // negate x rotation
Quaternion newq = new Quaternion(axis, angle);
// negate x translation
this.UpdateTransform(newq, new Vector3D(-transform.OffsetX, transform.OffsetY, transform.OffsetZ));
}
}
/// <summary>
/// Gets the camera frustum 3D graphical representation
/// </summary>
public ScreenSpaceLines3D CameraFrustum { get; private set; }
/// <summary>
/// Gets the near plane
/// </summary>
public float NearPlane { get; private set; }
/// <summary>
/// Gets the far plane
/// </summary>
public float FarPlane { get; private set; }
/// <summary>
/// Gets the camera graphics frustum size in m
/// </summary>
public float FrustumSize { get; private set; }
/// <summary>
/// Gets the camera aspect ratio
/// </summary>
public float AspectRatio { get; private set; }
#endregion
/// <summary>
/// Dispose resources
/// </summary>
public void Dispose()
{
this.Dispose(true);
// This object will be cleaned up by the Dispose method.
GC.SuppressFinalize(this);
}
/// <summary>
/// Attach to a UI element to receive mouse events
/// </summary>
/// <param name="element">The framework element to attach to.</param>
public void Attach(UIElement element)
{
if (null == element)
{
return;
}
element.MouseMove += this.OnMouseMove;
element.MouseLeftButtonDown += this.OnMouseLeftDown;
element.MouseLeftButtonUp += this.OnMouseLeftUp;
element.MouseRightButtonDown += this.OnMouseRightDown;
element.MouseRightButtonUp += this.OnMouseRightUp;
element.MouseWheel += this.OnMouseWheel;
element.MouseLeave += this.OnMouseLeave;
this.attachedElement = element;
}
/// <summary>
/// Detach from a UI element to stop receiving mouse events
/// </summary>
/// <param name="element">The framework element to detach from.</param>
public void Detach(UIElement element)
{
if (null == element)
{
return;
}
element.MouseMove -= this.OnMouseMove;
element.MouseLeftButtonDown -= this.OnMouseLeftDown;
element.MouseLeftButtonUp -= this.OnMouseLeftUp;
element.MouseRightButtonDown -= this.OnMouseRightDown;
element.MouseRightButtonUp -= this.OnMouseRightUp;
element.MouseWheel -= this.OnMouseWheel;
element.MouseLeave -= this.OnMouseLeave;
this.attachedElement = null;
}
/// <summary>
/// Camera frustum 3D graphics
/// </summary>
/// <param name="viewport">The viewport.</param>
/// <param name="depthWidth">The width of the depth image.</param>
/// <param name="depthHeight">The height of the depth image.</param>
public void CreateFrustum3DGraphics(Viewport3D viewport, float depthWidth, float depthHeight)
{
if (null == viewport)
{
return;
}
this.CreateFrustum3DGraphics(viewport, DefaultCameraNear, DefaultCameraFrustumSize, depthWidth, depthHeight, defaultCameraFrustumLineColor, DefaultCameraFrustumLineThickness);
}
/// <summary>
/// Camera frustum 3D graphics
/// </summary>
/// <param name="viewport">The viewport.</param>
/// <param name="near">The near plane of the frustum.</param>
/// <param name="far">The far plane of the frustum.</param>
/// <param name="depthWidth">The width of the depth image.</param>
/// <param name="depthHeight">The height of the depth image.</param>
/// <param name="color">The color to draw the frustum.</param>
/// <param name="thickness">The line thickness to use when drawing the frustum.</param>
public void CreateFrustum3DGraphics(Viewport3D viewport, float near, float far, float depthWidth, float depthHeight, System.Windows.Media.Color color, int thickness)
{
if (null == viewport)
{
return;
}
this.graphicsViewport = viewport;
// De-normalize default camera params
float px = camParams.PrincipalPointX * depthWidth;
float py = camParams.PrincipalPointY * depthHeight;
float fx = camParams.FocalLengthX * depthWidth;
float fy = camParams.FocalLengthY * depthHeight;
float iflx = 1.0f / fx;
float ifly = 1.0f / fy;
this.CameraFrustum = new ScreenSpaceLines3D();
this.CameraFrustum.Points = new Point3DCollection();
Point3DCollection pts = this.CameraFrustum.Points;
// Near plane rectangle
pts.Add(KinectFusionHelper.BackProject(0, 0, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, 0, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, 0, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, depthHeight, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, depthHeight, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, depthHeight, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, depthHeight, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, 0, near, px, py, iflx, ifly));
// Far plane rectangle
pts.Add(KinectFusionHelper.BackProject(0, 0, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, 0, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, 0, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, depthHeight, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, depthHeight, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, depthHeight, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, depthHeight, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, 0, far, px, py, iflx, ifly));
// Connecting lines
pts.Add(KinectFusionHelper.BackProject(0, 0, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, 0, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, 0, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, 0, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, depthHeight, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(depthWidth, depthHeight, far, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, depthHeight, near, px, py, iflx, ifly));
pts.Add(KinectFusionHelper.BackProject(0, depthHeight, far, px, py, iflx, ifly));
this.CameraFrustum.Thickness = thickness;
this.CameraFrustum.Color = color;
// Add a fixed rotation around the Y axis to look back down +Z towards origin
Matrix3D fixedRotY180 = new Matrix3D();
fixedRotY180.Rotate(new Quaternion(new Vector3D(0, 1, 0), 180));
this.cumulativeCameraFrustumTransform.Children.Add(new MatrixTransform3D(fixedRotY180));
this.cumulativeCameraFrustumTransform.Children.Add(this.cameraFrustumTransform3D);
this.CameraFrustum.Transform = this.cumulativeCameraFrustumTransform;
}
/// <summary>
/// Add the frustum graphics to the visual tree
/// </summary>
public void AddFrustum3DGraphics()
{
if (!this.haveAddedFrustumGraphics && null != this.graphicsViewport && null != this.CameraFrustum)
{
this.graphicsViewport.Children.Add(this.CameraFrustum);
this.haveAddedFrustumGraphics = true;
}
}
/// <summary>
/// Remove the frustum graphics from the visual tree
/// </summary>
public void RemoveFrustum3DGraphics()
{
if (this.haveAddedFrustumGraphics && null != this.graphicsViewport && null != this.CameraFrustum)
{
this.graphicsViewport.Children.Remove(this.CameraFrustum);
this.haveAddedFrustumGraphics = false;
}
}
/// <summary>
/// Dispose the frustum graphics
/// </summary>
public void DisposeFrustum3DGraphics()
{
if (this.haveAddedFrustumGraphics)
{
this.RemoveFrustum3DGraphics();
}
if (null != this.CameraFrustum)
{
this.CameraFrustum.Dispose();
this.CameraFrustum = null;
}
}
/// <summary>
/// Reset the camera to starting translation and rotation
/// </summary>
public void Reset()
{
this.UpdateTransform(this.StartRotation, new Vector3D(this.StartTranslation.X, this.StartTranslation.Y, this.StartTranslation.Z));
}
/// <summary>
/// Update virtual camera transform
/// Note: To update the frustum graphics transform, call the UpdateFrustumTransform functions separately
/// </summary>
/// <param name="rotationQuaternion">The rotation.</param>
/// <param name="translation">The translation.</param>
public void UpdateTransform(Quaternion rotationQuaternion, Vector3D translation)
{
if (null == this.Camera)
{
return;
}
this.rotationTransform.Axis = rotationQuaternion.Axis;
this.rotationTransform.Angle = rotationQuaternion.Angle;
this.translateTransform.OffsetX = translation.X;
this.translateTransform.OffsetY = translation.Y;
this.translateTransform.OffsetZ = translation.Z;
// Update the combined transforms
Matrix3D view = this.cumulativeCameraViewTransform.Value; // Invert the camera view transform to get camera matrix
view.Invert();
this.cumulativeCameraTransform.Matrix = view;
// Raise Transformation Changed Event
if (null != this.CameraTransformationChanged)
{
this.CameraTransformationChanged(this, null);
}
}
/// <summary>
/// Update frustum graphics transform
/// </summary>
/// <param name="worldToCameraMatrix3D">The transformation.</param>
public void UpdateFrustumTransformMatrix3D(Matrix3D worldToCameraMatrix3D)
{
// Update the frustum graphics if we have created them
if (null != this.CameraFrustum)
{
this.cameraFrustumTransform3D.Matrix = worldToCameraMatrix3D; // Set the camera transform to the frustum graphics
}
}
/// <summary>
/// Update frustum graphics transform
/// </summary>
/// <param name="worldToCameraMatrix4">The transformation.</param>
public void UpdateFrustumTransformMatrix4(Matrix4 worldToCameraMatrix4)
{
// Update the frustum graphics if we have created them
if (null != this.CameraFrustum)
{
Matrix3D transform = KinectFusionHelper.ConvertMatrix4ToMatrix3D(worldToCameraMatrix4);
Quaternion q = KinectFusionHelper.Matrix3DToQuaternion(transform);
double angle = q.Angle;
Vector3D axis = q.Axis;
axis.X = -axis.X; // negate x rotation
Quaternion newq = new Quaternion(axis, angle);
Transform3DGroup cumulativeFrustumViewTransform = new Transform3DGroup();
cumulativeFrustumViewTransform.Children.Add(new TranslateTransform3D(new Vector3D(-transform.OffsetX, transform.OffsetY, transform.OffsetZ)));
cumulativeFrustumViewTransform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(axis, angle)));
this.cameraFrustumTransform3D.Matrix = cumulativeFrustumViewTransform.Value; // Set the camera transform to the frustum graphics
}
}
/// <summary>
/// Update the transform from the mouse deltas
/// </summary>
/// <param name="deltaX">The delta in X.</param>
/// <param name="deltaY">The delta in Y.</param>
/// <param name="deltaZ">The delta in Z.</param>
/// <param name="rotate">Whether to rotate.</param>
/// <param name="translate">Whether to translate in X,Y.</param>
public void UpdateTransformFromMouseDeltas(int deltaX, int deltaY, int deltaZ, bool rotate, bool translate)
{
if (rotate)
{
this.RotateCamera(deltaX, deltaY);
}
else if (translate)
{
this.TranslateCamera(deltaX, deltaY);
}
// Mouse wheel
if (deltaZ != 0)
{
this.TranslateCameraMouseWheel(deltaZ);
}
}
/// <summary>
/// Frees associated memory and tidies up
/// </summary>
/// <param name="disposing">Whether the function was called from Dispose.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (null != this.attachedElement)
{
this.Detach(this.attachedElement); // stop getting mouse events
}
this.RemoveFrustum3DGraphics();
this.DisposeFrustum3DGraphics();
}
}
this.disposed = true;
}
////////////////////////////////////////////////////////////////
// Mouse Handling
/// <summary>
/// Called when mouse left button pressed inside the reconstruction image
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
private void OnMouseLeftDown(object sender, MouseButtonEventArgs e)
{
if (!this.mousePressedRight)
{
this.mousePressedLeft = true;
Point pos = e.GetPosition(this.attachedElement);
this.buttonPressMousePosition = new Point(pos.X, pos.Y);
}
}
/// <summary>
/// Called when mouse right button pressed inside the reconstruction image
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
private void OnMouseRightDown(object sender, MouseButtonEventArgs e)
{
if (!this.mousePressedLeft)
{
this.mousePressedRight = true;
Point pos = e.GetPosition(this.attachedElement);
this.buttonPressMousePosition = new Point(pos.X, pos.Y);
}
}
/// <summary>
/// Called when mouse left button released
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
private void OnMouseLeftUp(object sender, MouseButtonEventArgs e)
{
if (this.mousePressedLeft)
{
float dx, dy;
if (this.CalculateMouseDeltas(e, out dx, out dy))
{
this.UpdateTransformFromMouseDeltas((int)dx, (int)dy, 0, this.mousePressedLeft, this.mousePressedRight);
}
this.mousePressedLeft = false;
}
}
/// <summary>
/// Called when mouse right button released
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
private void OnMouseRightUp(object sender, MouseButtonEventArgs e)
{
if (this.mousePressedRight)
{
float dx, dy;
if (this.CalculateMouseDeltas(e, out dx, out dy))
{
this.UpdateTransformFromMouseDeltas((int)dx, (int)dy, 0, this.mousePressedLeft, this.mousePressedRight);
}
this.mousePressedRight = false;
}
}
/// <summary>
/// Called when mouse moves when pointer inside image
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (this.mousePressedLeft || this.mousePressedRight)
{
float dx, dy;
if (this.CalculateMouseDeltas(e, out dx, out dy))
{
this.UpdateTransformFromMouseDeltas((int)dx, (int)dy, 0, this.mousePressedLeft, this.mousePressedRight);
}
}
}
/// <summary>
/// Called when mouse wheel moves when pointer inside image
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
private void OnMouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Delta != 0)
{
this.UpdateTransformFromMouseDeltas(0, 0, (int)e.Delta, this.mousePressedLeft, this.mousePressedRight);
}
}
/// <summary>
/// Called when the mouse leaves the interactive area
/// </summary>
/// <param name="sender">Event generator</param>
/// <param name="e">Event parameter</param>
private void OnMouseLeave(object sender, MouseEventArgs e)
{
if (this.mousePressedLeft || this.mousePressedRight)
{
float dx, dy;
if (this.CalculateMouseDeltas(e, out dx, out dy))
{
this.UpdateTransformFromMouseDeltas((int)dx, (int)dy, 0, this.mousePressedLeft, this.mousePressedRight);
}
this.mousePressedLeft = false;
this.mousePressedRight = false;
}
}
/// <summary>
/// Calculate the difference between mouse positions
/// </summary>
/// <param name="e">The event args.</param>
/// <param name="deltaX">The delta in the x axis.</param>
/// <param name="deltaY">The delta in the y axis.</param>
/// <returns>Returns true if deltaX or deltaY are non-0.</returns>
private bool CalculateMouseDeltas(MouseEventArgs e, out float deltaX, out float deltaY)
{
this.currentMousePosition = e.GetPosition(this.attachedElement);
deltaX = (float)this.currentMousePosition.X - (float)this.buttonPressMousePosition.X;
deltaY = (float)this.currentMousePosition.Y - (float)this.buttonPressMousePosition.Y;
if (!(deltaX == 0 && deltaY == 0))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Rotate and update the camera
/// </summary>
/// <param name="deltaX">The delta in X.</param>
/// <param name="deltaY">The delta in Y.</param>
private void RotateCamera(float deltaX, float deltaY)
{
if (null == this.attachedElement)
{
return;
}
Quaternion qx = new Quaternion(new Vector3D(1, 0, 0), -deltaY * RotateMouse);
Quaternion qy = new Quaternion(new Vector3D(0, 1, 0), -deltaX * RotateMouse);
var delta = qx * qy;
// Compose the delta with the previous orientation
var q = new Quaternion(this.rotationTransform.Axis, this.rotationTransform.Angle);
q *= delta;
this.UpdateTransform(q, new Vector3D(this.translateTransform.OffsetX, this.translateTransform.OffsetY, this.translateTransform.OffsetZ));
}
/// <summary>
/// Translate and update the camera
/// </summary>
/// <param name="deltaX">The delta in X.</param>
/// <param name="deltaY">The delta in Y.</param>
private void TranslateCamera(float deltaX, float deltaY)
{
// Get the current orientation from the RotateTransform3D
var q = new Quaternion(this.rotationTransform.Axis, this.rotationTransform.Angle);
// Update translation
double x = this.translateTransform.OffsetX + (-deltaX * TranslateMouse);
double y = this.translateTransform.OffsetY + (deltaY * TranslateMouse);
double z = this.translateTransform.OffsetZ;
this.UpdateTransform(q, new Vector3D(x, y, z));
}
/// <summary>
/// Translate and update the camera (zoom)
/// </summary>
/// <param name="deltaZ">The delta in Z.</param>
private void TranslateCameraMouseWheel(float deltaZ)
{
// Get the current orientation from the RotateTransform3D
var q = new Quaternion(this.rotationTransform.Axis, this.rotationTransform.Angle);
// We are orbiting, so we just need to adjust the Z
double x = this.translateTransform.OffsetX;
double y = this.translateTransform.OffsetY;
double z = this.translateTransform.OffsetZ + (deltaZ * TranslateWheel);
this.UpdateTransform(q, new Vector3D(x, y, z));
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Stock_Exchange_Analyzer;
using Stock_Exchange_Analyzer.Exceptions;
using System.Management;
namespace SEATest
{
[TestClass]
public class DataRetrieverTests
{
[TestMethod]
public void RequestDataCorrectly()
{
Exception ex = null;
try
{
string result = DataRetriever.RetrieveData(DataProviders.YahooFinance, DateTime.Now.AddMonths(-1), "GOOG");
}
catch (Exception e)
{
ex = e;
}
Assert.IsNull(ex, "An exception occured on good query, if the internet is working, this test FAILED.");
}
[TestMethod]
public void RequestDataFromANonExistentProvider()
{
Exception ex = null;
try
{
string result = DataRetriever.RetrieveData(((DataProviders)50), DateTime.Now.AddMonths(-1), "GOOG");
}
catch (Exception e)
{
ex = e;
}
Assert.IsInstanceOfType(ex, typeof(DataProviderNotValidException), "A non existent Data Provider did not throw the appropriate exception. FAILED.");
}
[TestMethod]
public void RequestDataFromANonExistentCompany()
{
Exception ex = null;
try
{
string result = DataRetriever.RetrieveData(DataProviders.YahooFinance, DateTime.Now.AddMonths(-1), "GOOGLE");
}
catch (Exception e)
{
ex = e;
}
Assert.IsInstanceOfType(ex, typeof(CompanyNotFoundException), "A non existent company did not throw the appropriate exception. FAILED.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Data;
using System.Threading.Tasks;
namespace Logic
{
public static class CompanyDataHandler
{
static public List<ProducedCompanyPower> GetTotalProducedPower(string företag = null)
{
return CompanyDataAccesser.GetTotalProducedPower(företag);
}
static public List<ProducedCompanyPower> GetProducedPowerOfDay(string date, string företag = null)
{
return CompanyDataAccesser.GetProducedPowerOfDay(ConvertDate(date), företag);
}
static public List<ProducedCompanyPower> GetProducedPowerOfMonth(string date, string företag = null)
{
return CompanyDataAccesser.GetProducedPowerOfMonth(ConvertDate(date), företag);
}
static public List<ProducedCompanyPower> GetProducedPowerOfYear(string date, string företag = null)
{
return CompanyDataAccesser.GetProducedPowerOfYear(ConvertDate(date), företag);
}
static private Date ConvertDate(string date)
{
Date formattedDate = new Date();
var year = date.Split()[0];
var month = date.Split()[1];
var day = date.Split()[2];
var hour = date.Split()[3];
if (Int32.Parse(month) < 10)
{
month = "0" + month;
}
if (Int32.Parse(day) < 10)
{
day = "0" + day;
}
if (Int32.Parse(hour) < 10)
{
hour = "0" + hour;
}
formattedDate.year = year;
formattedDate.month = month;
formattedDate.day = day;
formattedDate.hour = hour;
formattedDate.date = String.Format("{0} {1} {2} {3}", year, month, day, hour);
return formattedDate;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cards;
namespace Blackjack
{
public class BlackjackPlayer : Player
{
public BlackjackDecisionPolicy DecisionPolicy { get; set; }
public BlackjackEarlySurrenderPolicy EarlySurrenderPolicy { get; set; }
public BlackjackBettingPolicy BettingPolicy { get; set; }
public BlackjackInsurancePolicy InsurancePolicy { get; set; }
public BlackjackPlayer(string name) : base(name) { }
protected BlackjackPlayer(string name, Bank bank) : base(name, bank) { }
}
public class BlackjackDealer : BlackjackPlayer
{
public const string DealerName = "Dealer";
public BlackjackDealer(IBlackjackConfig config) : base(DealerName, new Bank())
{
DecisionPolicy = new DealerDecisionPolicy(config);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Islands
{
public class IslandDetector
{
public int GetIslandCount(char[,] sea)
{
var countedCoordinates = new List<Coordinate>();
int result = 0;
List<Coordinate> allCoordinates = Coordinate.GetAllCoordinates(sea.GetLength(0), sea.GetLength(1));
// We only need to analyze coordinates that are already land
foreach (Coordinate coordinate in allCoordinates.Where(x => sea[x.X, x.Y] == 'X'))
{
if (countedCoordinates.Contains(coordinate)) continue;
result++;
//Any coordinates belonging to this island no longer need to be counted
var connectedCoordinates = new List<Coordinate>();
GetIsland(coordinate, sea, connectedCoordinates);
countedCoordinates.AddRange(connectedCoordinates);
}
return result;
}
/// <summary>
/// Returns the coordinates for the entire island that the given coordinate is a part of
/// </summary>
/// <param name="coordinate"></param>
/// <param name="sea"></param>
/// <param name="islandCoordinates"></param>
private void GetIsland(Coordinate coordinate, char[,] sea, List<Coordinate> islandCoordinates)
{
if (islandCoordinates.Contains(coordinate)) return;
islandCoordinates.Add(coordinate);
List<Coordinate> siblings = GetConnectedCoordinates(coordinate, sea);
foreach (Coordinate sibling in siblings)
{
if (sea[sibling.X,sibling.Y] == 'X')
{
GetIsland(sibling, sea, islandCoordinates);
}
}
}
/// <summary>
/// Returns the immediately connected coordinates to the provided coordinate (N, S, E, W, NE, NW, SE, SW)
/// </summary>
/// <param name="coordinate"></param>
/// <param name="sea"></param>
/// <returns></returns>
private List<Coordinate> GetConnectedCoordinates(Coordinate coordinate, char[,] sea)
{
var list = new List<Coordinate>
{
new Coordinate(coordinate.X - 1, coordinate.Y - 1),
new Coordinate(coordinate.X, coordinate.Y - 1),
new Coordinate(coordinate.X + 1, coordinate.Y - 1),
new Coordinate(coordinate.X - 1, coordinate.Y),
new Coordinate(coordinate.X + 1, coordinate.Y),
new Coordinate(coordinate.X - 1, coordinate.Y + 1),
new Coordinate(coordinate.X, coordinate.Y + 1),
new Coordinate(coordinate.X + 1, coordinate.Y + 1)
};
list = list.Where(x => x.X != -1 && x.X < sea.GetLength(0))
.Where(x => x.Y != -1 && x.Y < sea.GetLength(1))
.ToList();
return list;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace Docller.Core.Repository.Mappers
{
public class GenericResultSetMapper<T>:IResultSetMapper<T>
{
private readonly IRowMapper<T> _rowMapper;
public GenericResultSetMapper(IRowMapper<T> rowMapper)
{
_rowMapper = rowMapper;
}
public IEnumerable<T> MapSet(IDataReader reader)
{
List<T> list = new List<T>();
using(reader)
{
while (reader.Read())
{
list.Add(this._rowMapper.MapRow(reader));
}
}
return list;
}
}
}
|
using System.Linq;
namespace PasswordDll
{
public static class Encrypter
{
public static string Encrypt(string str, int key = 1) => new string(str.Select(c => (char)(c + key)).ToArray());
public static string Deencrypt(string str, int key = 1) => new string(str.Select(c => (char)(c - key)).ToArray());
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IncreaseCanvas : MonoBehaviour {
void Start () {
transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Models.DbModels
{
public class Task
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Column(TypeName = "nvarchar(100)")]
public string Name { get; set; }
[Column(TypeName = "nvarchar(1000)")]
public string Description { get; set; }
public int Priority { get; set; }
[Column(TypeName = "datetime")]
public DateTime FinishTime { get; set; }
[Required]
public int StatusId { get; set; }
public Status Status { get; set; }
[Required]
public int ListId { get; set; }
public List List { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Report_ClassLibrary
{
public class UserPermission
{
public int PerPK { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int UserPK { get; set; }
public string PageName { get; set; }
public string PageDesc { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace LoanSystem
{
class Program
{
public static List<string> ProductName = new List<string> { "IPHONE === ₱45,000","SMARTWATCH === ₱15,000","GOPRO === ₱20,000",
"TOYOTA WIGO === ₱650,000 ","HONDA CIVIC === ₱700,000","FORD FIESTA === ₱500,000"
,"SMART TV === ₱20,000","AIRCON === ₱10,000","DINING TABLE === ₱5,000"};
static void Main(string[] args)
{
Console.Title = "LoanSystem";
Console.WriteLine("===============================");
Console.WriteLine("\n Welcome to Loan System \n");
Console.WriteLine("===============================");
Console.WriteLine("Press [0] to enter your information");
Console.WriteLine("LOAN MENU");
Console.WriteLine("===============================");
Console.WriteLine("\n [1]Gadget Loan \n");
Console.WriteLine("\n [2]Car Loan \n");
Console.WriteLine("\n [3]Appliances Loan \n");
Console.WriteLine("===============================");
string UserInput = Console.ReadLine();
if (UserInput == "1")
{
gadgetloan();
}
else if (UserInput == "2")
{
carloan();
}
else if (UserInput == "3")
{
appliancesloan();
}
else if (UserInput == "0")
{
UserInfo();
}
static void UserInfo()
{
Console.Clear();
Console.WriteLine("Enter your FullName:");
var name = Console.ReadLine();
Console.WriteLine("Enter your Age:");
var age = Console.ReadLine();
Console.WriteLine("Enter your Occupation:");
var occupation = Console.ReadLine();
Console.WriteLine("\n Here are your details \n");
Console.WriteLine($"Name: {name} ");
Console.WriteLine($"Age: {age} ");
Console.WriteLine($"Occupation: {occupation} ");
}
}
static void gadgetloan()
{
Console.Clear();
Console.WriteLine("\n You choose gadget loan \n");
Console.WriteLine();
Console.WriteLine("Available Gadgets:");
Console.WriteLine("===============================");
Console.WriteLine(ProductName[0]);
Console.WriteLine(ProductName[1]);
Console.WriteLine(ProductName[2]);
Console.WriteLine("===============================");
Console.WriteLine();
Console.WriteLine("To Calculate your interest for your loan press ENTER");
Console.ReadLine();
Console.Write("Enter the total amount:");
double amount = double.Parse(Console.ReadLine());
Console.Write("Enter the interest rate (per year):");
double intrate = double.Parse(Console.ReadLine());
Console.Write("Enter the duration(in months):");
int months = int.Parse(Console.ReadLine());
double totalInt = ((amount / 12)) * ((intrate / 100)) * months;
Console.WriteLine("-------------------------------");
Console.WriteLine("Total Interest for {0} Months is {1}", months, totalInt);
Console.WriteLine("-------------------------------");
Console.Read();
}
public static void carloan()
{
Console.Clear();
Console.WriteLine("You choose car loan");
Console.WriteLine();
Console.WriteLine("Available Vehicles:");
Console.WriteLine("===============================");
Console.WriteLine(ProductName[3]);
Console.WriteLine(ProductName[4]);
Console.WriteLine(ProductName[5]);
Console.WriteLine("===============================");
Console.WriteLine("To Calculate your interest for your loan press ENTER:");
Console.ReadLine();
Console.Write("Enter the total amount:");
double amount = double.Parse(Console.ReadLine());
Console.Write("Enter the interest rate (per year):");
double intrate = double.Parse(Console.ReadLine());
Console.Write("Enter the duration(in months):");
int months = int.Parse(Console.ReadLine());
double totalInt = ((amount / 12)) * ((intrate / 100)) * months;
Console.WriteLine("-------------------------------");
Console.WriteLine("Total Interest for {0} Months is {1}", months, totalInt);
Console.WriteLine("-------------------------------");
Console.Read();
}
public static void appliancesloan()
{
Console.Clear();
Console.WriteLine("You choose appliances loan");
Console.WriteLine("Available Appliances:");
Console.WriteLine("===============================");
Console.WriteLine(ProductName[6]);
Console.WriteLine(ProductName[7]);
Console.WriteLine(ProductName[8]);
Console.WriteLine("===============================");
Console.WriteLine("To Calculate your interest for your loan press ENTER:");
Console.ReadLine();
Console.Write("Enter the total amount:");
double amount = double.Parse(Console.ReadLine());
Console.Write("Enter the interest rate (per year):");
double intrate = double.Parse(Console.ReadLine());
Console.Write("Enter the duration(in months):");
int months = int.Parse(Console.ReadLine());
double totalInt = ((amount / 12)) * ((intrate / 100)) * months;
Console.WriteLine("-------------------------------");
Console.WriteLine("Total Interest for {0} Months is {1}", months, totalInt);
Console.WriteLine("-------------------------------");
Console.Read();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace HBPonto.Kernel.DTO
{
public class JiraWorklogSummaryWithSecondsDTO
{
public int timeSpentSeconds { get; private set; }
public string comment { get; private set; }
public string started { get; private set; }
public JiraWorklogSummaryWithSecondsDTO(int timeSpentSeconds, string comment, string started)
{
this.timeSpentSeconds = timeSpentSeconds;
this.comment = comment;
this.started = started;
}
public static JiraWorklogSummaryWithSecondsDTO Create(int timeSpentSeconds, string comment, string started)
{
return new JiraWorklogSummaryWithSecondsDTO(timeSpentSeconds, comment, started);
}
}
}
|
using Microsoft.Xna.Framework.Graphics;
namespace Entoarox.Framework
{
interface IProfession
{
/// <summary>
/// The skill level required before this profession can be unlocked
/// </summary>
int SkillLevel { get; }
/// <summary>
/// The internal name of the parent profession needed to unlock this one (or `null` for no parent)
/// </summary>
string Parent { get; }
/// <summary>
/// The internal name used for this profession by the code
/// </summary>
string Name { get; }
/// <summary>
/// The name that is visually displayed for this profession
/// </summary>
string DisplayName { get; }
/// <summary>
/// A short description of the benefits this profession gives
/// </summary>
string Description { get; }
/// <summary>
/// The icon for this profession
/// </summary>
Texture2D Icon { get; }
}
}
|
using System;
namespace UnityAtoms
{
/// <summary>
/// Attribute that makes an Atom searchable.
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class AtomsSearchable : Attribute { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//..
using ETS.data;
using ETS.logic;
using ETS.logic.Domain;
namespace ETS.service
{
public class LoginService
{
public static void ConnectionString()
{
// Encoded connection string
string conString = "Data Source=.;Initial Catalog=EmployeeInformation;User ID=sa;Password=********";
// Decode
conString = Hasher.Decode(conString);
// Set it in both DB classes
LoginDao.SetCon(conString);
EmployeeDao.SetCon(conString);
}
public static int NewLogin(LoginUser user)
{
try
{
// Get salt
user.Salt = Hasher.SetSalt();
// Encode
user.PasswordHash = Hasher.EncodeFull(user.Salt, user.Password);
// Check that there is no duplicate username in the DB
if (LoginDao.SearchUserName(user.UserName) == (int)SuccessEnum.Success)
{
// Add new Login to the DB
return LoginDao.NewLogin(user);
}
else
{
// Return Search fail message
return LoginDao.SearchUserName(user.UserName);
}
}
catch (Exception)
{
return (int)SuccessEnum.Fail;
}
}
public static int HashLogin(LoginUser user)
{
try
{
// Get salt
user.Salt = GetSalt(user.UserName);
// Hash
user.PasswordHash = Hasher.EncodeFull(user.Salt, user.Password);
// Log in
if (LoginDao.Login(user) == (int)SuccessEnum.Success)
{
return (int)SuccessEnum.Success;
}
else
{
return (int)SuccessEnum.Fail;
}
}
catch (Exception)
{
return (int)SuccessEnum.Fail;
}
}
public static int UpdatePassword(LoginUser user)
{
string result = "";
// Check log in with old password
if (HashLogin(user) == (int)SuccessEnum.Success)
{
result = "Pass";
}
//Send PasswordHash && SaltHash to DataBase for saving
if (result == "Pass")
{
try
{
// Get salt hash
user.Salt = Hasher.SetSalt();
// Encode password + salt
user.PasswordHash = Hasher.EncodeFull(user.Salt, user.NewPassword);
return LoginDao.UpdatePassword(user);
}
catch (Exception)
{
return (int)SuccessEnum.Fail;
}
}
else
{
return (int)SuccessEnum.Fail;
}
}
private static string GetSalt(string userName)
{
// Retrieve salt hash from database
string salt = LoginDao.GetSalt(userName);
return salt;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeyDrop : MonoBehaviour
{
public Key key;
private SpriteRenderer sprite;
void Start()
{
sprite = GetComponent<SpriteRenderer>();
sprite.sprite = key.image;
}
private void OnTriggerEnter2D(Collider2D other)
{
PlayerMovement player = other.GetComponent<PlayerMovement>();
if (player != null)
{
Iventario.inventario.addKey(key);
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Uintra.Core.Feed.Models;
using Uintra.Core.Feed.Settings;
namespace Uintra.Core.Feed.Services
{
public interface IFeedItemService
{
Enum Type { get; }
FeedSettings GetFeedSettings();
IEnumerable<IFeedItem> GetItems();
IEnumerable<IFeedItem> GetGroupItems(Guid groupId);
Task<IEnumerable<IFeedItem>> GetItemsAsync();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManageProducts.Domain.Entities
{
public class Product
{
//prop + double tab : light version
public int ProductId { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
public DateTime DateProd { get; set; }
public string Description { get; set; }
public string Name { get; set; }
/* propfull+ double tab : full version (if we need to override the var)
private int ProductId;
public int MyProperty
{
get { return ProductId; }
set { ProductId = value; }
}*/
//navigation prop
/*List:
public List<Provider> Providers { get; set;}
*/
// ICollection
public virtual ICollection<Provider> Providers { get; set; }
public virtual Category Category { get; set; }
// ctor + double tab : construct
public Product()
{
}
public Product(int productId, int quantity, double price, DateTime dateProd, string description, string name)
{
ProductId = productId;
Quantity = quantity;
Price = price;
DateProd = dateProd;
Description = description;
Name = name;
}
public override string ToString()
{
return "Id: " + ProductId
+ " Quantity: " + Quantity
+ " Price: " + Price
+ " Date: " + DateProd
+ " Description: " + Description
+ " Name: " + Name;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Personagens;
namespace TerraMediaTests
{
[TestClass]
public class OrcTest
{
[TestMethod]
public void TestMethod1()
{
var orc = new Orc();
Assert.AreEqual(12, orc.Ataque);
}
}
}
|
public class Solution {
public int HammingWeight(uint n) {
int res = 0;
for (int i = 0; i < 32; i ++) {
res += (int) (n & 1);
n >>= 1;
}
return res;
}
} |
using BehaviourTree;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class GuardAI : MonoBehaviour {
public float TimeSinceLastStun = 0;
public SwapSightConeColor swapSightConeColor;
public int VisionAngle;
public int VisionRange;
public INavNode InitialNavNode;
public float SupriseDuration;
public Vector3 lastSeenPlayerPosition;
public Vector3 lastHeardPlayerPosition;
public float AlertLevel2Coefficient = 1.25f;
public float AlertLevel3Coefficient = 1.5f;
public float RedAlertCoefficient = 1.75f;
private float initialSpeed;
private int initialVisionAngle;
private int initialVisionRange;
private GuardState guardState;
private GuardState previousGuardState;
private Task behaviourTree;
public INavNode currentNavNode
{
get;
set;
}
public INavNode previousNavNode
{
get;
set;
}
public NavMeshAgent navMeshAgent
{
get;
set;
}
public AudioSource EffectAudioSource
{
get;
set;
}
public AudioSource MouvementAudioSource
{
get;
set;
}
public AudioSource WalkingAudioSource = new AudioSource();
public AudioClip Level1WalkingClip;
public AudioClip Level2WalkingClip;
public AudioClip RunningClip;
public AudioClip CurrentWalkingClip;
public FieldOfView GraphicalConeOfView;
// Use this for initialization
void Start () {
var aSources = GetComponents<AudioSource>();
EffectAudioSource = aSources[0];
MouvementAudioSource = aSources[1];
previousGuardState = new GuardPatrolState(this);
guardState = new GuardPatrolState(this);
navMeshAgent = GetComponent<NavMeshAgent>();
currentNavNode = InitialNavNode;
GameManager.Instance.AlertManager.alertStatusChanged += alertChanged;
initialSpeed = navMeshAgent.speed;
initialVisionAngle = VisionAngle;
initialVisionRange = VisionRange;
}
private void alertChanged(AlertStatus alertStatus)
{
if (alertStatus == AlertStatus.level2)
{
CurrentWalkingClip = Level2WalkingClip;
SupriseDuration = 0.75f;
navMeshAgent.speed = AlertLevel2Coefficient * initialSpeed;
VisionRange = (int)(AlertLevel2Coefficient * initialVisionRange);
VisionAngle = (int)(AlertLevel2Coefficient * initialVisionAngle);
//scale the guard
}
else if (alertStatus == AlertStatus.level3)
{
SupriseDuration = 0.5f;
navMeshAgent.speed = AlertLevel3Coefficient * initialSpeed;
VisionRange = (int)(AlertLevel3Coefficient * initialVisionRange);
VisionAngle = (int)(AlertLevel3Coefficient * initialVisionAngle);
//scale the guard
}
else if (alertStatus == AlertStatus.RedAlert)
{
navMeshAgent.speed = RedAlertCoefficient * initialSpeed;
VisionRange = (int)(RedAlertCoefficient * initialVisionRange);
VisionAngle = (int)(RedAlertCoefficient * initialVisionAngle);
SupriseDuration = 0;
//scale the guard
}
GraphicalConeOfView.viewAngle = VisionAngle;
GraphicalConeOfView.viewRadius = VisionRange;
}
// Update is called once per frame
void Update () {
GuardState temp = guardState;
guardState = guardState.DoAction(previousGuardState);
previousGuardState = temp;
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "PedestalCheck" && guardState.GetType() == typeof(GuardPatrolState))
{
GameObject artefact1 = null;
GameObject artefact2 = null;
if (other.GetComponent<PedestalNavNode>().PedestalTransform != null)
{
artefact1 = other.GetComponent<PedestalNavNode>().PedestalTransform.gameObject;
}
if (other.GetComponent<PedestalNavNode>().PedestalTransform2 != null)
{
artefact2 = other.GetComponent<PedestalNavNode>().PedestalTransform2.gameObject;
}
guardState = new GuardPedestalCheckState(this, artefact1, artefact2);
// do some logic to check the artefact if not in the alert level
}
if (other.gameObject.tag == "Player")
{
GameManager.Instance.KillPlayer();
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
GameManager.Instance.KillPlayer();
}
}
public void SetFlashLightAlertMode()
{
swapSightConeColor.SetAlarmMaterial();
}
public void SetFlashLightPatrolMode()
{
swapSightConeColor.SetPatrolMaterial();
}
public void SetFlashLightSearchingMode()
{
swapSightConeColor.SetSearchingMaterial();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LMS.App_Code
{
public class ReturnData
{
public int status { get; set; }
public string message { get; set; }
public string para1 { get; set; }
public string para2 { get; set; }
public double dblPara1 { get; set; }
public double dblPara2 { get; set; }
public double dblPara3 { get; set; }
public double dblPara4 { get; set; }
}
} |
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class VersionText : MonoBehaviour {
private void Awake() {
this.GetComponent<Text>().text = "version: " + Application.version;
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using System;
using System.Linq;
namespace DuckingAround.NPCs
{
public class DuckingAroundGlobalNPC : GlobalNPC
{
public override bool InstancePerEntity => true;
public static int[] enemySpawnList =
{
NPCID.ChaosElemental, NPCID.ArmoredSkeleton, NPCID.Corruptor, NPCID.CursedSkull,
NPCID.FloatyGross, NPCID.GiantBat, NPCID.Hornet, NPCID.Nymph, NPCID.Pixie,
NPCID.Skeleton, NPCID.Unicorn, NPCID.Werewolf, NPCID.Zombie
};
public static int[] zombieGroup = { -26, -27, -28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -44, -45, 3, 187, 188, 189, 200, 132, 590 };
public override void EditSpawnRate(Player player, ref int spawnRate, ref int maxSpawns)
{
maxSpawns = 40;
}
public override bool CheckDead(NPC npc)
{
Towns.EnemySpawnerNPC.EnemySpawnerNPC.enemyCount -= 1;
return true;
}
public override bool PreNPCLoot(NPC npc)
{
//remove drops from vanilla enemies with NPCLoader.blockloot
int randGenNum = Main.rand.Next(2);
bool randGen;
if (randGenNum == 1)
{
randGen = true;
}
else
{
randGen = false;
}
if (npc.type == NPCID.LostGirl || npc.type == NPCID.Nymph)
{
if (randGen == true)
{
Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.MetalDetector);
}
if (randGen == false && !Main.LocalPlayer.HasItem(ModContent.ItemType<Items.EnemyEggs.NymphEgg>()))
{
Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ModContent.ItemType<Items.EnemyEggs.NymphEgg>());
}
NPCLoader.blockLoot.Add(ItemID.MetalDetector);
}
if (npc.type == NPCID.VoodooDemon)
{
int item = Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ItemID.GuideVoodooDoll);
ItemID.Sets.ItemNoGravity[Main.item[item].type] = true;
}
NPCLoader.blockLoot.Add(ItemID.GuideVoodooDoll);
return true;
}
public override void NPCLoot(NPC npc)
{
if (npc.type == ModContent.NPCType<Bosses.EyeDestruction>())
{
if (Main.netMode != NetmodeID.MultiplayerClient)
{
int centerX = (int)(npc.position.X + (float)(npc.width / 4)) / 16;
int centerY = (int)(npc.position.Y + (float)(npc.height / 4)) / 16;
int halfLength = npc.width / 2 / 16 + 1;
for (int x = centerX - halfLength; x <= centerX + halfLength; x++)
{
for (int y = centerY - halfLength; y <= centerY + halfLength; y++)
{
if ((x == centerX - halfLength || x == centerX + halfLength || y == centerY - halfLength || y == centerY + halfLength) && !Main.tile[x, y].active())
{
Main.tile[x, y].type = TileID.AdamantiteBeam;
Main.tile[x, y].active(true);
}
Main.tile[x, y].lava(false);
Main.tile[x, y].liquid = 0;
if (Main.netMode == NetmodeID.Server)
{
NetMessage.SendTileSquare(-1, x, y, 1);
}
else
{
WorldGen.SquareTileFrame(x, y, true);
}
}
}
}
if (Main.expertMode)
{
npc.DropBossBags();
}
else
{
if (!NPC.downedMoonlord && Main.hardMode && Main.expertMode)
{
Item.NewItem(npc.getRect(), ModContent.ItemType<Items.Placeable.PlatyrhynchiumOre>(), Main.rand.Next(72, 94));
}
else if (!NPC.downedMoonlord && Main.hardMode && !Main.expertMode)
{
Item.NewItem(npc.getRect(), ModContent.ItemType<Items.Placeable.PlatyrhynchiumOre>(), Main.rand.Next(62, 75));
}
Item.NewItem(npc.getRect(), ModContent.ItemType<Items.Mounts.DuckEgg>());
}
WorldGenMethods.SpawnOre(ModContent.TileType<Tiles.PlatyrhynchiumOre>(), 0.000035, 0.45f, 0.65f);
DuckingNetcode.SyncWorld();
}
//vastium slime ore drops
if (NPC.downedMoonlord == true && npc.type == ModContent.NPCType<Enemies.PlatyrhynchiumSlime>())
{
Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ModContent.ItemType<Items.Placeable.PlatyrhynchiumOre>(), Main.rand.Next(26) + 7);
}
//acid drops
if (npc.type == ModContent.NPCType<Enemies.AcidicSlime>())
{
Item.NewItem(npc.getRect(), ModContent.ItemType<Items.Materials.Acid>());
}
//machine part drops
if (npc.type == ModContent.NPCType<Enemies.RobotFlier>())
{
Item.NewItem(npc.getRect(), ModContent.ItemType<Items.Materials.MachineParts>());
}
//enemy egg drops
if (zombieGroup.Contains(npc.type) && !Main.LocalPlayer.HasItem(ModContent.ItemType<Items.EnemyEggs.ZombieEgg>()))
{
if (Main.rand.Next(0, 10) == 4)
{
Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, ModContent.ItemType<Items.EnemyEggs.ZombieEgg>(), 1);
}
}
if (enemySpawnList.Contains(npc.type) && Main.rand.Next(0, 10) == 4)
{
string name = npc.FullName;
string trimmed = string.Concat(name.Where(c => !Char.IsWhiteSpace(c))) + "Egg";
Item.NewItem((int)npc.position.X, (int)npc.position.Y, npc.width, npc.height, mod.ItemType(trimmed), 1);
}
}
}
} |
using UnityEngine;
using System.Collections;
public class TransitionPointScript : MonoBehaviour
{
public int goToScene;
public bool goingBack;
GameObject freccia;
bool playerExited = true;
bool inside;
public bool shouldShowFrecccia = true;
public bool shouldPickUp = true;
LevelScript level;
GameObject orfeo;
void Start()
{
level = GetComponentInParent<LevelScript>();
}
void Update()
{
if (shouldShowFrecccia)
{
if (GetComponent<Collider2D>().enabled && freccia == null)
{
freccia = Instantiate(Resources.Load("freccia"), transform.position, Quaternion.identity) as GameObject;
if (transform.localPosition.x > 0)
freccia.transform.localScale = new Vector3(-.5f, .5f, transform.localScale.z);
freccia.transform.parent = transform;
}
if (GetComponent<Collider2D>() == null && freccia != null)
Destroy(freccia);
}
if (orfeo != null && inside)
{
if (shouldPickUp)
{
if (orfeo.GetComponent<Movement>().pickedUp && playerExited)
{
//scnManager.SceneChange (goToScene,goingBack);
SceneManager.ChangeScene(goToScene, goingBack);
}
if (!orfeo.GetComponent<Movement>().pickedUp && playerExited)
{
Debug.Log("Prendi Euridice coglione!");
}
}
else
SceneManager.ChangeScene(goToScene, goingBack);
}
}
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.name == "orfeo")
{
orfeo = coll.gameObject;
inside = true;
}
}
void OnTriggerExit2D(Collider2D coll)
{
if (coll.name == "orfeo")
inside = false;
if (!playerExited)
{
playerExited = true;
Debug.Log("Trigger Reactived");
}
}
public void DeactivateUntilExit()
{
//disattivo il trigger finchè il player non si sposta
playerExited = false;
}
}
|
using Backend.Model;
using Backend.Model.Enums;
using Backend.Model.Exceptions;
using Backend.Model.Users;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Backend.Repository
{
public class MySqlActivePatientRepository : IActivePatientRepository
{
private readonly MyDbContext _context;
public MySqlActivePatientRepository(MyDbContext context)
{
_context = context;
}
public void AddPatient(Patient patient)
{
try
{
_context.Patients.Add(patient);
_context.SaveChanges();
}
catch (DbUpdateException)
{
throw new BadRequestException("Username or jmbg already exists.");
}
catch (Exception)
{
throw new DatabaseException("The database connection is down.");
}
}
public Patient CheckUsernameAndPassword(string username, string password)
{
Patient _patient = _context.Patients.Find(username);
if (_patient == null || !_patient.Password.Equals(password))
{
return null;
}
return _patient;
}
public void DeletePatient(string jmbg)
{
Patient patient = GetPatientByJmbg(jmbg);
_context.Remove(patient);
_context.SaveChanges();
}
public List<Patient> GetAllPatients()
{
return _context.Patients.ToList();
}
public Patient GetPatientByJmbg(string jmbg)
{
Patient patient;
try
{
patient = _context.Patients.Find(jmbg);
}
catch (Exception)
{
throw new DatabaseException("The database connection is down.");
}
if (patient == null)
throw new NotFoundException("Patient doesn't exist in database.");
return patient;
}
public void UpdatePatient(Patient patient)
{
try
{
_context.Patients.Update(patient);
_context.SaveChanges();
}
catch (Exception)
{
throw new DatabaseException("The database connection is down.");
}
}
public int GetNumberOfCanceledExaminations(string jmbg)
{
try
{
return _context.Examinations.Count(e => e.PatientCard.PatientJmbg == jmbg &&
e.ExaminationStatus == ExaminationStatus.CANCELED && e.DateAndTime >= DateTime.Now.AddMonths(-1));
}
catch (Exception)
{
throw new DatabaseException("The database connection is down.");
}
}
public Patient GetPatientByUsernameAndPassword(string username, string password)
{
Patient patient;
try
{
patient = _context.Patients.Where(p => p.Username == username && p.Password == password).FirstOrDefault();
}
catch (Exception)
{
throw new DatabaseException("The database connection is down.");
}
if (patient == null)
throw new NotFoundException("Patient doesn't exist in database.");
if (patient.IsBlocked)
throw new BadRequestException("Patient is blocked.");
if (!patient.IsActive)
throw new BadRequestException("Patient didn't activate account.");
return patient;
}
public Patient GetPatientByPatientCardId(int patientCardId)
{
Patient patient;
try
{
patient = _context.Patients.Where(p => p.PatientCard.Id == patientCardId).FirstOrDefault();
}
catch (Exception)
{
throw new DatabaseException("The database connection is down.");
}
if (patient == null)
throw new NotFoundException("Patient doesn't exist in database.");
if (patient.IsBlocked)
throw new BadRequestException("Patient is blocked.");
return patient;
}
}
}
|
using System;
using System.Collections.Generic;
using iSukces.Code.Interfaces;
using JetBrains.Annotations;
namespace iSukces.Code.Typescript
{
public sealed class TsReference : ITsCodeProvider, IEquatable<TsReference>
{
static TsReference()
{
#warning Only WINDOWS
PathComparer = StringComparer.OrdinalIgnoreCase;
}
public TsReference([NotNull] string path)
{
Path = path ?? throw new ArgumentNullException(nameof(path));
}
public static bool operator ==(TsReference left, TsReference right)
{
return Equals(left, right);
}
public static bool operator !=(TsReference left, TsReference right)
{
return !Equals(left, right);
}
public bool Equals(TsReference other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return PathComparer.Equals(Path, other.Path);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TsReference)obj);
}
public override int GetHashCode()
{
return PathComparer.GetHashCode(Path);
}
public override string ToString()
{
return "TsReference: " + Path;
}
public void WriteCodeTo(ITsCodeWriter writer)
{
writer.WriteLine($"/// <reference path=\"{Path}\"/>");
}
public static StringComparer PathComparer { get; }
[NotNull]
public string Path { get; }
private static EqualityComparer<string> _pathComparer;
}
} |
using Common.Contracts;
using Common.Enums;
using Common.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.DbTools
{
public class DbLocalController : IDbLocalController
{
public DbLocalController()
{
}
public void Connect(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
if (!context.LocalControllers.Any(lc => lc.Code == code))
{
Create(code);
}
else
{
LocalController localController = context.LocalControllers.First(lc => lc.Code == code);
localController.IsOnline = true;
context.SaveChanges();
}
}
}
public void Create(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
LocalController localController = new LocalController(code);
localController.IsOnline = true;
SystemController sc = context.SystemControllers.Include("LocalControllers").FirstOrDefault();
if (sc != null)
{
sc.LocalControllers.Add(localController);
context.SaveChanges();
}
}
}
public LocalController GetLocalController(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
return context.LocalControllers.Include("Groups").Include("Generators").FirstOrDefault(lc => lc.Code == code);
}
}
public void TurnOnLCGenerators(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
foreach (Generator generator in context.Generators.Where(g => g.LCCode == code))
{
generator.State = EState.ONLINE;
context.SaveChanges();
}
}
}
public void ShutDownGenerators(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
foreach (Generator generator in context.Generators.Where(g => g.LCCode == code))
{
generator.State = EState.OFFLINE;
}
context.SaveChanges();
}
}
public List<LocalController> ReadAll()
{
using(ApplicationDbContext context = new ApplicationDbContext())
{
return context.LocalControllers.Include("Generators").Where(lc => lc.IsOnline).ToList();
}
}
public bool IsCodeFree(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
if (context.LocalControllers.Any(lc => lc.Code.Equals(code)))
{
return false;
}
return true;
}
}
public bool IsOnline(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
LocalController lc = context.LocalControllers.FirstOrDefault(l => l.Code.Equals(code));
return lc != null && lc.IsOnline;
}
}
public void ShutDown(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
LocalController lc = context.LocalControllers.FirstOrDefault(l => l.Code.Equals(code));
if (lc != null)
{
lc.IsOnline = false;
context.SaveChanges();
}
}
}
public void SaveChanges(Generator generator)
{
using(ApplicationDbContext context = new ApplicationDbContext())
{
Generator genFromDb = context.Generators.FirstOrDefault(g => g.Id == generator.Id);
if (genFromDb != null)
{
genFromDb.CurrentPower = generator.CurrentPower;
genFromDb.State = generator.State;
context.SaveChanges();
}
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class OrderlyBehavoiur : MonoBehaviour {
public Transform[] eventPositions;
public Transform[] resolutionWaypoints;
public Vector3 _Target = Vector3.zero;
public GameObject _Player = null;
public GameObject patient = null;
public bool triggerEvent = false;
public float dist = 0.0f;
public int currentWaypoint = 0;
public bool faceWaypoint = false;
public bool resolveEvent = false;
public DATACORE dataCore = null;
// Use this for initialization
void Start () {
if (dataCore == null) {
dataCore = GameObject.FindGameObjectWithTag("GameLogic").GetComponent<DATACORE>();
}
}
// Update is called once per frame
void Update () {
if (resolveEvent == true) {
if(currentWaypoint >= resolutionWaypoints.Length) {
// Do nothing
this.gameObject.SetActive(false);
}
else {
if(faceWaypoint == false) {
transform.LookAt(resolutionWaypoints[currentWaypoint]);
faceWaypoint = true;
}
float distToCurrentPosition = (resolutionWaypoints[currentWaypoint].position - transform.position).magnitude;
if(distToCurrentPosition < 1.5f) {
++currentWaypoint;
faceWaypoint = false;
Debug.Log ("Changing Way Point " + currentWaypoint);
}
if(currentWaypoint < resolutionWaypoints.Length) {
//this.transform.LookAt(waypoints[currentWaypoint].position);
transform.position = Vector3.MoveTowards (transform.position, resolutionWaypoints[currentWaypoint].position, 2.0f * Time.deltaTime);
}
}
}
else if (triggerEvent == true) {
if (currentWaypoint >= eventPositions.Length) {
transform.LookAt(patient.transform.position);
}
else
{
if (faceWaypoint == false)
{
transform.LookAt(eventPositions[currentWaypoint]);
faceWaypoint = true;
}
float distToCurrentPosition = (eventPositions[currentWaypoint].position - transform.position).magnitude;
if (distToCurrentPosition < 1.0f)
{
++currentWaypoint;
faceWaypoint = false;
Debug.Log("Changing Way Point " + currentWaypoint);
}
if (currentWaypoint < eventPositions.Length)
{
transform.position = Vector3.MoveTowards(transform.position, eventPositions[currentWaypoint].position, 4.0f * Time.deltaTime);
}
}
//dist = (transform.position - eventPosition.position).magnitude;
//if (triggerEvent && dist > 1.0f)
//transform.position = Vector3.MoveTowards (transform.position, eventPosition.position, 2.0f * Time.deltaTime);
//if (dist < 1.0f) {
//Transform temp = patient.transform;
//temp.position.y = transform.position.y;
//transform.LookAt (temp.position);
//transform.LookAt (patient.transform.position);
//Quaternion newRotation = Quaternion.LookRotation (Patient.transform.position - transform.position, Vector3.up);
//newRotation.y = 0.0f;
//transform.rotation = Quaternion.Slerp (transform.rotation, newRotation, 0.5f * Time.deltaTime);
//}
}
/*
if (_Target != Vector3.zero) {
this.transform.LookAt (_Target);
_Target = _Player.transform.position;
}
*/
}
void OnTriggerEnter(Collider theCollider) {
if (theCollider.gameObject.layer == 9 && triggerEvent == false) {
if(audio != null){
if(audio.isPlaying == false) audio.Play ();
}
_Player = theCollider.gameObject;
_Target = theCollider.gameObject.transform.position;
}
}
void OnTriggerStay(Collider theCollider) {
if (theCollider.gameObject.layer == 9 && triggerEvent == false) this.transform.LookAt (_Player.transform.position);
//if (_Target != Vector3.zero) {
// this.transform.LookAt (_Target);
// _Target = _Player.transform.position;
//}
}
/**/
void OnTriggerExit(Collider theCollider) {
_Target = Vector3.zero;
}
public void TriggerFreakOut() {
triggerEvent = true;
currentWaypoint = 0;
Debug.Log ("ORDERLY TRIGGERED");
this.gameObject.GetComponent<RemoveColliderBehaviour>().ToggleCollider ();
}
void ResolveFreakOut() {
resolveEvent = true;
currentWaypoint = 0;
Debug.Log ("ORDERLY RESOLVING FREAKOUT");
}
}
|
using ClassLibrary1.Fundamentals;
using NUnit.Framework;
namespace ClassLibrary1.UnitTests
{
[TestFixture]
public class CustomerControllerTests
{
[Test]
public void GetCustomer_IdIsZero_ReturnNotFound()
{
var controller = new CustomerController();
var result = controller.GetCustomer(0);
// exactly the object
Assert.That(result, Is.TypeOf<NotFound>());
// the object or its derivatives
Assert.That(result, Is.InstanceOf<NotFound>());
}
[Test]
public void GetCustomer_IdIsNotZero_ReturnOk()
{
var controller = new CustomerController();
var result = controller.GetCustomer(1);
Assert.That(result, Is.TypeOf<Ok>());
}
}
} |
using System;
using System.Linq;
using System.Reflection;
namespace Aquamonix.Mobile.Lib.Utilities
{
/// <summary>
/// Weak references are to be used mainly for storing references to function wrappers; a weak reference will ensure
/// that those objects do not interfere with garbage collection.
/// </summary>
public static class WeakReferenceUtility
{
public static Action MakeWeakAction(Action action)
{
if (action != null)
{
var reference = new WeakReference(action.Target);
var method = action.GetInvocationList().FirstOrDefault().GetMethodInfo();
return () =>
{
var target = reference.Target;
if (target != null)
{
method.Invoke(target, null);
}
};
}
else
return null;
}
public static Action<T> MakeWeakAction<T>(Action<T> action)
{
if (action != null)
{
var reference = new WeakReference(action.Target);
var method = action.GetInvocationList().FirstOrDefault().GetMethodInfo();
return t =>
{
var target = reference.Target;
if (target != null)
{
method.Invoke(target, new object[] { t });
}
};
}
else
return null;
}
public static Action<T1, T2> MakeWeakAction<T1, T2>(Action<T1, T2> action)
{
if (action != null)
{
var reference = new WeakReference(action.Target);
var method = action.GetInvocationList().FirstOrDefault().GetMethodInfo();
return (t1, t2) =>
{
var target = reference.Target;
if (target != null)
{
method.Invoke(target, new object[] { t1, t2 });
}
};
}
else
return null;
}
public static Action<T1, T2, T3> MakeWeakAction<T1, T2, T3>(Action<T1, T2, T3> action)
{
if (action != null)
{
var reference = new WeakReference(action.Target);
var method = action.GetInvocationList().FirstOrDefault().GetMethodInfo();
return (t1, t2, t3) =>
{
var target = reference.Target;
if (target != null)
{
method.Invoke(target, new object[] { t1, t2, t3 });
}
};
}
else
return null;
}
public static Action<T1, T2, T3, T4> MakeWeakAction<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action)
{
if (action != null)
{
var reference = new WeakReference(action.Target);
var method = action.GetInvocationList().FirstOrDefault().GetMethodInfo();
return (t1, t2, t3, t4) =>
{
var target = reference.Target;
if (target != null)
{
method.Invoke(target, new object[] { t1, t2, t3, t4});
}
};
}
else
return null;
}
public static Func<K, V> MakeWeakAction<K, V>(Func<K, V> action)
{
if (action != null)
{
var reference = new WeakReference(action.Target);
var method = action.GetInvocationList().FirstOrDefault().GetMethodInfo();
return (k) =>
{
var target = reference.Target;
if (target != null)
{
return (V)method.Invoke(target, new object[] { k });
}
return default(V);
};
}
else
return null;
}
public static EventHandler MakeWeakHandler(Action action)
{
if (action != null)
{
var reference = new WeakReference(action.Target);
var method = action.GetInvocationList().FirstOrDefault().GetMethodInfo();
return (sender, e) =>
{
var target = reference.Target;
if (target != null)
{
method.Invoke(target, null);
}
};
}
else
return null;
}
public static EventHandler MakeWeakHandler(EventHandler handler)
{
if (handler != null)
{
var reference = new WeakReference(handler.Target);
var method = handler.GetInvocationList().FirstOrDefault().GetMethodInfo();
return (sender, e) =>
{
var target = reference.Target;
if (target != null)
{
method.Invoke(target, new object[] { sender, e });
}
};
}
else
return null;
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace Vlc.DotNet.Core.Interops.Signatures
{
/// <summary>
/// Get the current subtitle delay.
/// </summary>
[LibVlcFunction("libvlc_video_get_spu_delay")]
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate long GetVideoSpuDelay(IntPtr mediaPlayerInstance);
}
|
using AbstractFactoryPattern.Abstractions;
namespace AbstractFactoryPattern.Ingredients
{
public class MarinaraSauce: ISauce
{
public string Name { get; } = "Marinara Sauce";
}
}
|
namespace Nan.Configuration.Notification
{
using System;
/// <summary>
/// 提供 <seealso cref="INotifyFieldOperated.FieldOperated"/> 事件的資料
/// </summary>
public class FieldOperatedEventArgs : EventArgs
{
/// <summary>
/// 初始化 <see cref="FieldOperatedEventArgs"/> 類別的新執行個體
/// </summary>
/// <param name="operation">操作方式</param>
/// <param name="fieldName">欄位名稱</param>
public FieldOperatedEventArgs(Operation operation, string fieldName)
{
this.FieldName = fieldName ?? throw new ArgumentNullException(nameof(fieldName));
Operation = operation;
}
/// <summary>
/// 欄位名稱
/// </summary>
public string FieldName { get; private set; }
/// <summary>
/// 操作方式
/// </summary>
public Operation Operation { get; private set; }
}
} |
namespace PhonebookHost
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class PhonebookContacts : IComparable<PhonebookContacts>
{
private string contactName;
//private string contactNameToLower;
public string ContactName
{
get
{
return this.contactName;
}
set
{
this.contactName = value;
}
}
//public string ContactNameToLower
//{
// get
// {
// return this.contactNameToLower;
// }
// set
// {
// this.contactNameToLower = this.ContactName.ToLowerInvariant();
// }
//}
public SortedSet<string> PhonebookContactsData;
public override string ToString()
{
StringBuilder sb = new StringBuilder(); sb.Clear(); sb.Append('[');
sb.Append(this.ContactName);
//probably isPhoneNumber
bool isPhoneNumber = true;
foreach (var phone in this.PhonebookContactsData)
{
if (isPhoneNumber)
{
sb.Append(", ");
}
else
{
sb.Append(": ");
isPhoneNumber = false;
}
sb.Append(phone);
}
sb.Append(']');
return sb.ToString();
}
public int CompareTo(PhonebookContacts other)
{
return this.contactName.ToLowerInvariant().CompareTo(other.contactName.ToLowerInvariant());
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace DataAccess.Migrations
{
public partial class Initial002 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_PurchaseOrders_ApplicationUserId",
schema: "devDb",
table: "PurchaseOrders");
migrationBuilder.DropIndex(
name: "IX_PurchaseOrders_Code",
schema: "devDb",
table: "PurchaseOrders");
migrationBuilder.CreateIndex(
name: "IX_UniquePO",
schema: "devDb",
table: "PurchaseOrders",
columns: new[] { "ApplicationUserId", "Code" },
unique: true,
filter: "[Code] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_UniquePO",
schema: "devDb",
table: "PurchaseOrders");
migrationBuilder.CreateIndex(
name: "IX_PurchaseOrders_ApplicationUserId",
schema: "devDb",
table: "PurchaseOrders",
column: "ApplicationUserId");
migrationBuilder.CreateIndex(
name: "IX_PurchaseOrders_Code",
schema: "devDb",
table: "PurchaseOrders",
column: "Code",
unique: true,
filter: "[Code] IS NOT NULL");
}
}
}
|
using System.Security.Cryptography;
namespace NStandard.Security
{
public class AesProvider : SymmetricProvider<AesCipher>
{
public override byte[] EmptyIV => new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/// <summary>
/// Create an AesProvider.
/// </summary>
/// <param name="cipher"></param>
/// <param name="padding"></param>
public AesProvider(CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(cipher, padding)
{
}
/// <summary>
/// Create an AesProvider.
/// </summary>
/// <param name="key">The length of Key must be 16, 24 or 32.</param>
/// <param name="cipher"></param>
/// <param name="padding"></param>
public AesProvider(byte[] key, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) : base(key, cipher, padding)
{
}
protected override SymmetricAlgorithm CreateAlgorithm() => Aes.Create();
}
}
|
using Abp.Authorization;
using Abp.NHibernate.EntityMappings;
namespace Abp.Zero.NHibernate.EntityMappings
{
public class PermissionMap : EntityMap<PermissionSetting, long>
{
public PermissionMap()
: base("AbpPermissions")
{
Map(x => x.RoleId);
Map(x => x.UserId);
Map(x => x.Name);
Map(x => x.IsGranted);
this.MapCreationAudited();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CMSWebsite
{
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
// set up navigation
//navigation.InnerHtml = "<li><a href=\"Manage\">Manage</a></li>";
// clean navigation
navigation.InnerHtml = "";
// query for page titles
string query = "SELECT * FROM pages WHERE isPublished = true";
// get page titles from db
List<HTMLPAGE> Pages = new WEBSITEDB().List_Query(query);
foreach (HTMLPAGE page in Pages)
{
string pagetitle = page.PageTitle;
string pageid = page.PageId;
navigation.InnerHtml += "<li> <a href=\"DetailPage.aspx?pageid=" + pageid + "\">" + pagetitle + "</a></li>";
}
}
}
} |
using System;
using JetBrains.Annotations;
using SpeedSlidingTrainer.Core.Model;
namespace SpeedSlidingTrainer.Application.Events
{
public sealed class SolveCompleted
{
public SolveCompleted([NotNull] SolveStatistics statistics)
{
if (statistics == null)
{
throw new ArgumentNullException(nameof(statistics));
}
this.Statistics = statistics;
}
[NotNull]
public SolveStatistics Statistics { get; }
}
}
|
using Alabo.Framework.Core.Enums.Enum;
using System.Collections.Generic;
namespace Alabo.App.Asset.Pays.Dtos
{
/// <summary>
/// 支付结果返回
/// </summary>
public class PayOutput
{
/// <summary>
/// 账单处理状态
/// </summary>
public PayStatus Status { get; set; } = PayStatus.WaiPay;
/// <summary>
/// 返回信息,不同的支付方式,返回的结果不同
/// 保存对象的json数据:比如支付宝支付保存 AlipayResponse.ToJson()
/// 微信支付返回:WeChatPayResponse.ToJson()
/// </summary>
public string Message { get; set; }
/// <summary>
/// 支付Id
/// </summary>
public long PayId { get; set; }
/// <summary>
/// 签名
/// </summary>
public string Sign { get; set; }
/// <summary>
/// 支付实体的Id
/// </summary>
public IList<object> EntityIds { get; set; }
/// <summary>
/// 订单Id
/// </summary>
public object OrderId { get; set; }
/// <summary>
/// 支付成功以后前端跳转的Url
/// </summary>
public string Url { get; set; }
}
} |
namespace EAN.GPD.Infrastructure.Database.SqlClient
{
public enum TypePersistence
{
Update,
Insert,
Delete
}
public interface IPersistenceEntity
{
void AddColumn(string name, object value);
void Execute();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Alphora.Dataphor.DAE;
using Alphora.Dataphor.DAE.NativeCLI;
using Alphora.Dataphor.DAE.Server;
using Newtonsoft.Json.Linq;
namespace Alphora.Dataphor.Dataphoria.Processing
{
public class Processor : IDisposable
{
public const string DefaultProcessorInstanceName = "Processor";
public Processor() : this(DefaultProcessorInstanceName)
{
}
public Processor(string instanceName)
{
if (String.IsNullOrEmpty(instanceName))
{
throw new ArgumentNullException("instanceName");
}
_instanceName = instanceName;
_configuration = InstanceManager.GetInstance(instanceName); // Don't necessarily need this to come from the instance manager, but this is the easiest solution for now
_server = new Server();
_configuration.ApplyTo(_server);
_server.Start();
_nativeServer = new NativeServer(_server);
}
private string _instanceName;
public string InstanceName { get { return _instanceName; } }
private ServerConfiguration _configuration;
private Server _server;
private NativeServer _nativeServer;
#region IDisposable Members
public void Dispose()
{
if (_server != null)
{
_server.Stop();
_server = null;
}
_nativeServer = null;
_configuration = null;
}
#endregion
public object Evaluate(string statement, Dictionary<string, object> args)
{
CheckActive();
var paramsValue =
args != null
? (from e in args select new NativeParam { Name = e.Key, Value = ValueToNativeValue(e.Value), Modifier = NativeModifier.In }).ToArray()
: null;
// Use the NativeCLI here to wrap the result in a NativeResult
// The Web service layer will then convert that to pure Json.
return _nativeServer.Execute(new NativeSessionInfo(), statement, paramsValue, NativeExecutionOptions.Default);
}
public object HostEvaluate(string statement)
{
CheckActive();
var session = _server.Connect(new SessionInfo());
try
{
var process = session.StartProcess(new ProcessInfo());
try
{
return process.Evaluate(statement, null);
}
finally
{
session.StopProcess(process);
}
}
finally
{
_server.Disconnect(session);
}
}
private string GetDataTypeName(NativeValue value)
{
NativeScalarValue scalarValue = value as NativeScalarValue;
if (scalarValue != null)
return scalarValue.DataTypeName;
NativeListValue listValue = value as NativeListValue;
if (listValue != null)
return String.Format("list({0})", listValue.ElementDataTypeName);
NativeRowValue rowValue = value as NativeRowValue;
if (rowValue != null)
{
var sb = new StringBuilder();
sb.Append("row{");
bool first = true;
foreach (NativeColumn column in rowValue.Columns)
{
if (!first)
sb.Append(",");
else
first = false;
sb.AppendFormat("{0}:{1}", column.Name, column.DataTypeName);
}
sb.Append("}");
return sb.ToString();
}
NativeTableValue tableValue = value as NativeTableValue;
if (tableValue != null)
{
var sb = new StringBuilder();
sb.Append("table{");
bool first = true;
foreach (NativeColumn column in tableValue.Columns)
{
if (!first)
sb.Append(",");
else
first = false;
sb.AppendFormat("{0}:{1}", column.Name, column.DataTypeName);
}
sb.Append("}");
return sb.ToString();
}
throw new NotSupportedException("Non-scalar-valued attributes are not supported.");
}
private NativeValue ValueToNativeValue(object value)
{
// If it's a value type or String, send it through as a scalar
if (value == null || value.GetType().IsValueType || value.GetType() == typeof(String))
return new NativeScalarValue { Value = value, DataTypeName = value != null ? value.GetType().Name : "Object" };
// If it's a JObject, send it through as a row
// I really don't want to do this (JSON is part of the communication layer, shouldn't be part of the processor here) but I don't want to build yet another pass-through structure to enable it when JObject is already that...
var jObject = value as JObject;
if (jObject != null)
{
var columns = new List<NativeColumn>();
var values = new List<NativeValue>();
foreach (var property in jObject)
{
var propertyValue = ValueToNativeValue(property.Value);
columns.Add(new NativeColumn { Name = property.Key, DataTypeName = GetDataTypeName(propertyValue) });
values.Add(propertyValue);
}
return new NativeRowValue { Columns = columns.ToArray(), Values = values.ToArray() };
}
var jValue = value as JValue;
if (jValue != null)
{
return ValueToNativeValue(jValue.Value);
}
// If it's an array or collection, send it through as a NativeList or NativeTable...
if (value.GetType().IsArray || value is ICollection)
// TODO: Handle list and table parameters
throw new NotSupportedException("List parameters are not yet supported.");
// Otherwise, send it through as a row
return ObjectToNativeValue(value);
}
private NativeValue ObjectToNativeValue(object value)
{
var columns = new List<NativeColumn>();
var values = new List<NativeValue>();
foreach (var property in value.GetType().GetProperties())
{
if (property.CanRead)
{
var propertyValue = ValueToNativeValue(property.GetValue(value, null));
columns.Add(new NativeColumn { Name = property.Name, DataTypeName = GetDataTypeName(propertyValue) });
values.Add(propertyValue);
}
}
return new NativeRowValue { Columns = columns.ToArray(), Values = values.ToArray() };
}
private void CheckActive()
{
if ((_server == null) || (_server.State != ServerState.Started))
{
throw new InvalidOperationException("Instance is not active.");
}
}
}
}
|
using System;
namespace MonitorBoletos.Util
{
public static class Tools
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProgrammingContest.Library
{
class Utility
{
/// <summary>
/// 配列一覧表示
/// </summary>
string EnumerableToString<T>(IEnumerable<T> enumerable, string sep = " ")
=> string.Join(sep, enumerable.Select(el => el.ToString()));
/// <summary>
/// バイナリ法による法mod のべき乗計算 O(log p)
/// </summary>
long PowMod(long a, long p, long mod)
{
if (p == 0) return 1;
if (p % 2 == 1) return a * PowMod(a, p - 1, mod) % mod;
else
{
long t = PowMod(a, p / 2, mod);
return t * t % mod;
}
}
/// <summary>
/// エラトステネスの篩 による素数列挙 O(N loglogN)
/// </summary>
IEnumerable<int> SieveOfEratosthenes(int maxVal)
{
bool[] isPrime = Enumerable.Repeat(true, maxVal + 1).ToArray();
if (isPrime.Length < 2)
{
yield break;
}
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < maxVal + 1; i++)
{
if (isPrime[i])
{
for (int j = i * 2; j < maxVal + 1; j += i)
{
isPrime[j] = false;
}
yield return i;
}
}
}
/// <summary>
/// 素数判定 O(√N)
/// </summary>
bool IsPrime(long val)
{
if (val < 2)
{
return false;
}
for (long i = 2; i * i <= val; i++)
{
if (val % i == 0)
{
return false;
}
}
return true;
}
/// <summary>
/// 文字列反転 {多分 O(N)}
/// </summary>
string ReverseStr(string str)
=> string.Concat(str.Reverse());
/// <summary>
/// 配列初期化 O(N)
/// </summary>
void Fill<T>(ref T[] ar, T val)
{
for (int i = 0; i < ar.Length; i++)
{
ar[i] = val;
}
}
/// <summary>
/// スワップ O(1)
/// </summary>
void Swap<T>(ref T a, ref T b)
{
T tmp = a;
a = b;
b = tmp;
}
/// <summary>
/// 配列全列挙 O(N(N!))? (ソートされていること!!)
/// </summary>
bool NextPermutation<T>(T[] ar) where T : IComparable<T>
{
int left = ar.Length - 1;
int CompForCalcNextPermutation(int i, int j)
=> ar[i].CompareTo(ar[j]);
while (0 < left && CompForCalcNextPermutation(left - 1, left) >= 0)
{
left--;
}
if (left == 0)
{
return false;
}
int right = ar.Length - 1;
while (CompForCalcNextPermutation(right, left - 1) <= 0)
{
right--;
}
T tmp = ar[left - 1];
ar[left - 1] = ar[right];
ar[right] = tmp;
Array.Reverse(ar, left, ar.Length - left);
return true;
}
/// <summary>
/// 最大公約数 O(log max(a, b))
/// </summary>
long Gcd(long a, long b)
{
if (a < b)
{
var tmp = b;
b = a;
a = tmp;
}
var ret = 1L;
while (b != 0)
{
ret = b;
b = a % b;
a = ret;
}
return ret;
}
/// <summary>
/// 最小公倍数 O(log max(a, b))
/// Gcd使用
/// </summary>
long Lcm(long a, long b) => a / Gcd(a, b) * b;
/// <summary>
/// 約数列挙 O(√N)
/// </summary>
IEnumerable<long> CalcDivisor(long num)
{
for (long i = 1; i * i <= num; i++)
{
if (num % i == 0)
{
yield return i;
if (num / i != i)
{
yield return num / i;
}
}
}
}
int BitCount(long val)
{
val = (val & 0x55555555) + (val >> 1 & 0x55555555);
val = (val & 0x33333333) + (val >> 2 & 0x33333333);
val = (val & 0x0f0f0f0f) + (val >> 4 & 0x0f0f0f0f);
val = (val & 0x00ff00ff) + (val >> 8 & 0x00ff00ff);
return (int)((val & 0x0000ffff) + (val >> 16 & 0x0000ffff));
}
IDictionary<TKey, TValue> Merge<TKey, TValue>(
IEnumerable<IDictionary<TKey, TValue>> source,
Func<IEnumerable<TValue>, TValue> aggregate)
=> source
.SelectMany(e => e.AsEnumerable())
.ToLookup(e => e.Key)
.ToDictionary(e => e.Key, e => aggregate(e.Select(el => el.Value)));
}
}
|
// Copyright (c) 2020, mParticle, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using MP.Json.Validation;
namespace MP.Json.Validation.Test
{
public class LruCacheTests
{
[Fact]
public void AddTest()
{
var lru = new LruCache<string, string>(4);
Assert.Null(lru["foo"]);
Assert.Empty(lru);
lru["foo"] = "bar";
Assert.Single(lru);
lru["foo"] = "xyz";
Assert.Single(lru);
Assert.Equal("xyz", lru["foo"]);
lru["1"] = "1";
Assert.Equal(2, lru.Count);
lru["2"] = "2";
Assert.Equal(3, lru.Count);
lru["1"] = "1b";
Assert.Equal(3, lru.Count);
lru["3"] = "3";
Assert.Equal(4, lru.Count);
lru["4"] = "4";
Assert.Equal(4, lru.Count);
Assert.Null(lru["foo"]);
Assert.NotNull(lru["1"]);
Assert.NotNull(lru["2"]);
Assert.NotNull(lru["3"]);
Assert.NotNull(lru["4"]);
Assert.Equal("1b", lru["1"]);
Assert.Equal("2", lru["2"]);
Assert.Equal("3", lru["3"]);
Assert.Equal("4", lru["4"]);
}
[Fact]
public void RetrieveTest()
{
var lru = new LruCache<string, string>(2);
lru["foo"] = "bar";
Assert.Equal("bar", lru["foo"]);
// Foo2 is added
lru["foo2"] = "bar2";
Assert.Equal("bar", lru["foo"]);
Assert.Equal("bar2", lru["foo2"]);
Assert.Equal("bar", lru["foo"]);
// Foo3 is added, Foo2 is at end and is removed
lru["foo3"] = "bar3";
Assert.Equal("bar3", lru["foo3"]);
Assert.Null(lru["foo2"]);
Assert.Equal("bar", lru["foo"]);
Assert.Equal("bar3", lru["foo3"]);
}
[Fact]
public void CountTest()
{
var lru = new LruCache<string, string>(0);
lru["foo"] = "bar";
Assert.Empty(lru);
lru = new LruCache<string, string>(1);
lru["foo"] = "bar";
Assert.Single(lru);
lru["foo2"] = "bar2";
Assert.Single(lru);
lru = new LruCache<string, string>(2);
lru["foo"] = "bar";
Assert.Single(lru);
lru["foo2"] = "bar2";
Assert.Equal(2, lru.Count);
lru["foo3"] = "bar3";
Assert.Equal(2, lru.Count);
}
}
}
|
using UnityEngine;
namespace Grandma.PF
{
public class PF : MonoBehaviour
{
[SerializeField]
private PFProjectile m_ProjectilePrefab;
[SerializeField]
private Transform m_BarrelTransform;
public SubscriptionValue<int> CurrentAmmo { get; } = new SubscriptionValue<int>();
//State Machine
private IdleState m_IdleState;
private ChargingState m_ChargingState;
private FiringState m_FiringState;
private ReloadState m_ReloadState;
private StateMachine m_StateMachine;
private void Awake()
{
CreateStateMachine();
}
private void LateUpdate()
{
m_StateMachine.Update();
}
private void CreateStateMachine()
{
m_IdleState = new IdleState();
m_FiringState = new FiringState()
{
ProjectilePrefab = m_ProjectilePrefab,
CurrentAmmo = CurrentAmmo,
BarrelTransform = m_BarrelTransform
};
m_ChargingState = new ChargingState()
{
NextState = m_FiringState
};
m_ReloadState = new ReloadState()
{
NextState = m_IdleState,
CurrentAmmo = CurrentAmmo
};
m_IdleState.FireTransition.State = m_ChargingState;
m_IdleState.ReloadTransition.State = m_ReloadState;
m_ChargingState.CancelTransition.State = m_IdleState;
m_ReloadState.CancelTransition.State = m_IdleState;
m_FiringState.StopFiringTransition.State = m_IdleState;
m_StateMachine = new StateMachine(m_IdleState);
}
public void SetData(PFData data)
{
m_ChargingState.Data = data.ChargingData;
m_FiringState.Data = data.FiringData;
m_FiringState.ProjectileData = data.ProjectileData;
m_ReloadState.Data = data.ReloadData;
//cooldown
}
public void Fire()
{
m_IdleState.FireTransition.Transition();
}
public void CancelFire()
{
m_ChargingState.CancelTransition.Transition();
}
public void Reload()
{
m_IdleState.ReloadTransition.Transition();
}
}
}
|
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.UnifiedPlatform.Service.Common.Models;
namespace Microsoft.UnifiedPlatform.Service.Common.Configuration
{
public interface IClusterConfigurationProvider
{
Task<List<ClusterConfigurationDto>> GetAllClusters();
Task<List<AppConfigurationDto>> GetAllApplications(string clusterName);
Task<ClusterConfigurationDto> GetClusterDetails(string clusterName);
Task<AppConfigurationDto> GetApplicationDetails(string clusterName, string appName);
Task<string> GetApplicationSecret(string clusterName, string appName);
Task<string> GetClusterConnectionString(string clusterName, string appName);
}
}
|
namespace Alabo.Domains.Entities.Extensions {
public interface IEntityExtension {
}
} |
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FiiiChain.Framework;
using FiiiChain.IModules;
using FiiiChain.TempData;
using LightDB;
using Newtonsoft.Json;
namespace FiiiChain.DataAgent
{
public class CacheAccess
{
private static IHotDataAccess _default;
public static IHotDataAccess Default
{
get
{
if (_default == null)
{
_default = DbAccessHelper.GetDataAccessInstance();
}
return _default;
}
}
}
} |
using Certificates;
using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
public class ClientProxy : ChannelFactory<IService>, IService, IDisposable
{
IService factory;
public ClientProxy(NetTcpBinding binding, EndpointAddress address) : base(binding, address)
{
/// cltCertCN.SubjectName should be set to the client's username. .NET WindowsIdentity class provides information about Windows user running the given process
string cltCertCN = Formatter.ParseName(WindowsIdentity.GetCurrent().Name);
this.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
/// Set appropriate client's certificate on the channel. Use CertManager class to obtain the certificate based on the "cltCertCN"
this.Credentials.ClientCertificate.Certificate = CertManager.GetCertificateFromStorage(StoreName.My, StoreLocation.LocalMachine, cltCertCN);
factory = this.CreateChannel();
}
public string AdminBan(string ou, string publisher)
{
string name = string.Empty;
try
{
name = factory.AdminBan(ou, publisher);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string[] CheckPublisherSpam(string ou)
{
string[] name = new string[] { };
try
{
name = factory.CheckPublisherSpam(ou);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string PublisherAddTheme(string ou, string cn, string themeName)
{
string name = string.Empty;
try
{
name = factory.PublisherAddTheme(ou, cn, themeName);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string PublisherModifyTheme(string ou, string cn, string oldThemeName, string newThemeName)
{
string name = string.Empty;
try
{
name = factory.PublisherModifyTheme(ou, cn, oldThemeName, newThemeName);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string PublisherReadTheme(string ou, string cn)
{
string name = string.Empty;
try
{
name = factory.PublisherReadTheme(ou, cn);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string PublisherWriteTheme(string ou, string cn)
{
string name = string.Empty;
try
{
name = factory.PublisherWriteTheme(ou, cn);
return name;
}
catch(Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string PublisherRemoveTheme(string ou, string cn, string themeName)
{
string name = string.Empty;
try
{
name = factory.PublisherRemoveTheme(ou, cn, themeName);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string PublisherSendNotifications(string ou, string cn, string themeName, string title, string content, string timeStamp)
{
string name = string.Empty;
try
{
name = factory.PublisherSendNotifications(ou, cn, themeName, title, content, timeStamp);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string Subscribe(string ou, string cn, string themeName)
{
string name = string.Empty;
try
{
name = factory.Subscribe(ou, cn, themeName);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string SubscriberReadNotifications(string ou, string cn)
{
string name = string.Empty;
try
{
name = factory.SubscriberReadNotifications(ou, cn);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string SubscriberReadTheme(string ou)
{
string name = string.Empty;
try
{
name = factory.SubscriberReadTheme(ou);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string Unsubscribe(string ou, string cn, string themeName)
{
string name = string.Empty;
try
{
name = factory.Unsubscribe(ou, cn, themeName);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public string SubscriberCheckUpdates(string ou, string cn)
{
string name = string.Empty;
try
{
name = factory.SubscriberCheckUpdates(ou, cn);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
public bool CheckIfPublisherBanned(string cn)
{
bool name = false;
try
{
name = factory.CheckIfPublisherBanned(cn);
return name;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return name;
}
}
}
} |
using SteamKit2.GC.TF2.Internal;
namespace Titan.Meta
{
public class ReportInfo : TitanPayloadInfo
{
public ulong MatchID { get; set; }
public ulong GameServerID { get; set; } = 0;
public bool AbusiveText { get; set; } = true;
public bool AbusiveVoice { get; set; } = true;
public bool Griefing { get; set; } = true;
public bool AimHacking { get; set; } = true;
public bool WallHacking { get; set; } = true;
public bool OtherHacking { get; set; } = true;
public CMsgGC_ReportPlayer.EReason Reason { get; set; } = CMsgGC_ReportPlayer.EReason.kReason_INVALID;
}
}
|
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Web;
using System.Web.UI;
using Medical_Consulting_AWP_F20;
public partial class Account_Login : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LogIn(object sender, EventArgs e)
{
/*
Tasks:
- after sucess login check user Type and redirect to pages below
- if admin -> admin control
- if doctor -> show cosulation req
- if user -> user consulation
*/
}
} |
using System;
using System.Linq;
using TelegramFootballBot.Core.Helpers;
namespace TelegramFootballBot.Core.Models.CallbackQueries
{
public class PlayerSetCallback : Callback
{
public static string Name => "PlayersSetDetermination";
public DateTime GameDate { get; private set; }
public PlayerSetCallback(string callbackData) : base(callbackData)
{
GameDate = ParseGameDate(callbackData);
}
public static string BuildCallbackPrefix(DateTime gameDate)
{
return Name + Constants.CALLBACK_DATA_SEPARATOR + gameDate.ToString("yyyy-MM-dd");
}
private static DateTime ParseGameDate(string callbackData)
{
var gameDateString = Prefix(callbackData).Split(Constants.CALLBACK_DATA_SEPARATOR).Last();
if (!DateTime.TryParse(gameDateString, out DateTime gameDate))
throw new ArgumentException($"Game date was not provided for callback data: {callbackData}", nameof(callbackData));
return gameDate;
}
}
}
|
using P1.Data.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace P1.Data.UnitOfWork
{
public interface IUnitOfWork : IDisposable
{
IMediaRepository Media { get; }
ITagsRepository Tags { get; }
Media AddTagToMedia(Media media, Tags tag);
Media RemoveTagFromMedia(Media media, int tagId);
int Complete();
}
}
|
using Cafe.API.Models.Entities;
using Cafe.API.Models.Repository;
using Cafe.API.Models.SortingParams;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cafe.API.Controllers
{
[Route("api/sales")]
[ApiController]
public class SaleController : ControllerBase
{
private readonly IDataRepository<ClientProduct> _dataRepository;
private readonly ILogger<SaleController> _logger;
public SaleController(IDataRepository<ClientProduct> dataRepository,
ILogger<SaleController> logger)
{
_dataRepository = dataRepository;
_logger = logger;
}
// GET: api/sales
[HttpGet]
public IActionResult Get(DirectionSort? sort)
{
try
{
IEnumerable<ClientProduct> sales;
switch (sort)
{
case DirectionSort.Ascending:
sales = _dataRepository.GetAll().OrderBy(x => x.Date);
break;
case DirectionSort.Descending:
sales = _dataRepository.GetAll().OrderByDescending(x => x.Date);
break;
default:
sales = _dataRepository.GetAll();
break;
}
_logger.LogInformation($"Sales was found succesfully");
return Ok(sales);
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}", ex);
return StatusCode(500, "A problem happened while handling your request");
}
}
// GET api/sales/5
// id - it is a client id, action returns all sales of cusomer with this id
[HttpGet("{id}")]
public IActionResult Get(int id)
{
try
{
var sales = _dataRepository.GetSales(id);
if(sales == null)
{
_logger.LogWarning($"Client with Id {id} not found");
return NotFound($"Can't find client with id {id}");
}
else
{
_logger.LogInformation($"Sales of client with Id {id} were found");
return Ok(sales);
}
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}", ex);
return StatusCode(500, "A problem happened while handling your request");
}
}
// POST api/sales
[HttpPost]
public IActionResult Post([FromBody] ClientProduct sale)
{
try
{
if (sale is null)
{
_logger.LogWarning($"Sale is null reference");
return BadRequest("Client or product is null");
}
if (!ModelState.IsValid)
{
_logger.LogError($"Validation error");
return BadRequest("Data is incorrect");
}
else
{
_dataRepository.Add(sale);
_logger.LogInformation($"New sale was created succesfully");
return StatusCode(StatusCodes.Status201Created);
}
}
catch (Exception ex)
{
_logger.LogInformation($"{ex.Message}", ex);
return StatusCode(500, "A problem happened while handing your request");
}
}
//// PUT api/<SaleController>/5
//[HttpPut("{id}")]
//public IActionResult Put(int id, [FromBody] ClientProduct sale)
//{
//}
//// DELETE api/<SaleController>/5
//[HttpDelete("{id}")]
//public void Delete(int id)
//{
//}
/// <summary>
/// - provide the page Number
/// - provide the page Size
/// - get all the data from the database
/// - apply the simple Skip and Take algorithm to get the simple specific result
/// - quotes.Skip((pageNumber - 1) * pageSize).Take(pageSize)
/// </summary>
[HttpGet("[action]")]
//PagingSales?pageNumber=1&&pageSize=3
public IActionResult PagingSales(int? pageNumber, int? pageSize)
{
try
{
var sales = _dataRepository.GetAll();
var currentPageNumber = pageNumber ?? 1;
var currentPageSize = pageSize ?? 5;
_logger.LogInformation($"Amount of sales on the page {pageNumber}");
return Ok(sales.Skip((currentPageNumber - 1) * currentPageSize).Take(currentPageSize));
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}", ex);
return StatusCode(500, "A problem happened while handing your request");
}
}
[HttpGet]
[Route("[action]")]
// SearchSales?clientId=1&&clientName=2
public IActionResult SearchSales(string clientName) //int? clientId,
{
try
{
var sales = _dataRepository.GetAll()
.Where(s => s.Client.SecondName.ToLower()
.StartsWith(clientName.ToLower()));
// || s.ClientId == clientId);
if (sales == null)
{
_logger.LogWarning($"{clientName}'s sale not found");
return NotFound();
}
_logger.LogInformation($"Sales for client {clientName} was found");
return Ok(sales);
}
catch (Exception ex)
{
_logger.LogError($"{ex.Message}", ex);
return StatusCode(500, "A problem happened while handing your request");
}
}
}
}
|
namespace Assets.Scripts.Core.MVC
{
public class BaseModel
{
}
} |
using System;
using System.Reflection;
using System.Runtime.Loader;
namespace CoherentSolutions.Extensions.Configuration.AnyWhere
{
public class AnyWhereConfigurationTypeSystem : IAnyWhereConfigurationTypeSystem
{
private class TypeSystemLoadContext : AssemblyLoadContext
{
private const int EXE_EXTENSION = 0;
private const int DLL_EXTENSION = 1;
private static readonly string[] extensions = new[]
{
".exe",
".dll"
};
private readonly IAnyWhereConfigurationFileSearch search;
private readonly string basePath;
public TypeSystemLoadContext(
string basePath,
IAnyWhereConfigurationFileSearch search)
{
if (string.IsNullOrWhiteSpace(basePath))
{
throw new ArgumentException("Value cannot be null or whitespace.", nameof(basePath));
}
this.basePath = basePath;
this.search = search ?? throw new ArgumentNullException(nameof(search));
}
protected override Assembly Load(
AssemblyName assemblyName)
{
try
{
return Default.LoadFromAssemblyName(assemblyName);
}
catch
{
var results = this.search.Find(this.basePath, assemblyName.Name, extensions);
if (results is null || results.Count == 0)
{
return null;
}
var assembly = results[EXE_EXTENSION] ?? results[DLL_EXTENSION];
return !AssemblyName.ReferenceMatchesDefinition(assemblyName, GetAssemblyName(assembly.Path))
? null
: this.LoadFromAssemblyPath(assembly.Path);
}
}
}
private readonly IAnyWhereConfigurationFileSearch search;
public AnyWhereConfigurationTypeSystem(
IAnyWhereConfigurationFileSearch search)
{
this.search = search ?? throw new ArgumentNullException(nameof(search));
}
public IAnyWhereConfigurationType Get(
IAnyWhereConfigurationFile assembly,
string name)
{
var lc = new TypeSystemLoadContext(assembly.Directory, this.search);
try
{
return new AnyWhereConfigurationType(
lc.LoadFromAssemblyPath(assembly.Path).GetType(name, true));
}
catch (Exception e)
{
throw new InvalidOperationException(
$"Could not load assembly '{assembly.Path}' or it's dependencies. Please see inner exception for details.",
e);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.MDM
{
public class ProductSeriesTreeNode : TreeViewNode
{
public int T213LeafID { get; set; }
public string T213NodeName { get; set; }
public new ProductSeriesTreeNode Clone()
{
ProductSeriesTreeNode rlt = MemberwiseClone() as ProductSeriesTreeNode;
rlt.IconImage = IconImage;
return rlt;
}
}
} |
using Fbtc.Domain.Entities;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Fbtc.Application.Interfaces
{
public interface IPagSeguroApplication
{
// string GetNotificationCode(string notificationCode);
/// <summary>
/// Recebendo uma notificação de transação:
/// Uma vez configurado o endereço para onde o PagSeguro irá enviar notificações,
/// o próximo passo é preparar seu sistema para receber, nesse endereço, um código de notificação.
/// O PagSeguro envia as notificações para a URL que você configurou usando o protocolo HTTP,
/// pelo método POST.
/// O PagSeguro envia as
/// notificações para a URL que você configurou usando o protocolo HTTP, pelo método POST.
/// </summary>
/// <param name="notificationCode"></param>
/// <param name="notificationType"></param>
/// <returns></returns>
string NotificationTransacao(string notificationCode, string notificationType);
string UpdateRecebimentoPagSeguro(TransacaoPagSeguro transacaoPagSeguro);
string SaveDadosTransacaoPagSeguro(TransacaoPagSeguro transacaoPagSeguro);
int UpdateRecebimentosPeriodoPagSeguro(TransactionSearchResult transactionSearchResult);
CheckOutPagSeguro getDadosParaCheckOutPagSeguro(int associadoId, string valor, string tipoEndereco,
int anoInicio, int anoTermino, bool enderecoRequerido, bool isAnuidade);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Kunai_Spawner_Controller : MonoBehaviour
{
public float TiempoEntreKunai;
public GameObject KunaiPrefab;
public bool puedeTirar;
public Vector3 direccionATirar;
public float CantidadKunaisSinPadre;
private float clockInterno;
private _Joestick Joestick_del_Padre;
private float contadorKunais;
private Color color;
// Use this for initialization
void Start()
{
clockInterno = TiempoEntreKunai;
if (transform.parent != null)
{
Joestick_del_Padre = this.transform.parent.GetComponent<Player1_controller>().joestick;
contadorKunais = 30;
color = this.transform.parent.GetComponent<Player_Ataques>().colorChidori;
}
else //si el padre es null.
{
contadorKunais = CantidadKunaisSinPadre;
color = Color.white;
}
color.a = 1f;
}
// Update is called once per frame
void Update()
{
if (transform.parent != null)
this.direccionATirar = Joestick_del_Padre.direccionJoestickDerecho;
else //si no tiene padre, es porque sale derecho.
this.direccionATirar = new Vector3(1, 0, 0);
if (puedeTirar)
{
if (clockInterno >= TiempoEntreKunai)
{
clockInterno = 0;
InvocaKunai(this.transform.position, direccionATirar);
if (transform.parent == null)
contadorKunais = contadorKunais - 1;
}
clockInterno = clockInterno + Time.deltaTime;
}
if (contadorKunais <= 0)
puedeTirar = false;
}
public void InvocaKunai(Vector3 posicion, Vector3 dondeTiro)
{
GameObject a = Instantiate(KunaiPrefab) as GameObject;
a.transform.position = posicion;
if (transform.parent != null)
{
color = this.transform.parent.GetComponent<Player_Ataques>().colorChidori;
color.a = 1f;
}
a.GetComponent<SpriteRenderer>().color = color;
if (transform.parent != null)
a.GetComponent<Kunai_Controller>().Objecto_Fundador = this.transform.parent.gameObject;
a.GetComponent<Kunai_Controller>().direccionATirar = dondeTiro;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace jaytwo.Common.Parse
{
public static partial class ParseUtility
{
public static bool ParseBoolean(string value)
{
return ParseBoolean(value, BoolStyles.Any);
}
public static bool ParseBoolean(string value, BoolStyles styles)
{
bool? result = null;
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Trim().Length > 0)
{
if (InternalParseHelpers.IsBoolStylesMatch(BoolStyles.TrimWhiteSpace, styles))
{
value = value.Trim();
}
if (!result.HasValue && InternalParseHelpers.IsBoolStylesMatch(BoolStyles.TF, styles))
{
if (string.Equals(value, "T", StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else if (string.Equals(value, "F", StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
if (!result.HasValue && InternalParseHelpers.IsBoolStylesMatch(BoolStyles.TrueFalse, styles))
{
if (string.Equals(value, "True", StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else if (string.Equals(value, "False", StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
if (!result.HasValue && InternalParseHelpers.IsBoolStylesMatch(BoolStyles.YesNo, styles))
{
if (string.Equals(value, "Yes", StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else if (string.Equals(value, "No", StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
if (!result.HasValue && InternalParseHelpers.IsBoolStylesMatch(BoolStyles.YN, styles))
{
if (string.Equals(value, "Y", StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else if (string.Equals(value, "N", StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
if (!result.HasValue && InternalParseHelpers.IsBoolStylesMatch(BoolStyles.ZeroOne, styles))
{
if (InternalParseHelpers.IsZeroInt(value))
{
result = false;
}
else if (InternalParseHelpers.IsOneInt(value))
{
result = true;
}
}
if (!result.HasValue && InternalParseHelpers.IsBoolStylesMatch(BoolStyles.ZeroNonzero, styles))
{
if (InternalParseHelpers.IsZeroInt(value))
{
result = false;
}
else if (InternalParseHelpers.IsNonZeroInt(value))
{
result = true;
}
}
if (!result.HasValue && (styles <= BoolStyles.Default))
{
result = bool.Parse(value);
}
}
if (!result.HasValue)
{
throw new FormatException("String was not recognized as a valid Boolean.");
}
return result.Value;
}
public static bool? TryParseBoolean(string value)
{
try
{
return ParseBoolean(value);
}
catch
{
return null;
}
}
public static bool? TryParseBoolean(string value, BoolStyles styles)
{
try
{
return ParseBoolean(value, styles);
}
catch
{
return null;
}
}
}
}
|
using RoleManagement.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoleManagement.EFDAL
{
public class MenuDal:BaseDal<Menu>
{
}
}
|
using Alabo.Domains.Dtos;
using Alabo.Domains.Entities;
using Alabo.Domains.UnitOfWork;
using Alabo.Validations.Aspects;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Alabo.Domains.Services.Update {
/// <summary>
/// 修改操作
/// </summary>
public interface IUpdateAsync<TEntity, in TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> {
/// <summary>
/// 修改
/// </summary>
/// <param name="request">修改参数</param>
[UnitOfWork]
Task<bool> UpdateAsync<TUpdateRequest>([Valid] TUpdateRequest request) where TUpdateRequest : IRequest, new();
/// <summary>
/// 更新单个实体
/// </summary>
/// <param name="model"></param>
Task<bool> UpdateAsync([Valid] TEntity model);
/// <summary>
/// 更新单个实体
/// </summary>
/// <param name="updateAction"></param>
/// <param name="predicate">查询条件</param>
Task<bool> UpdateAsync(Action<TEntity> updateAction, Expression<Func<TEntity, bool>> predicate = null);
}
} |
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Domain.AbstractRepository;
using Infrastructure.FilterAttributes;
using Infrastructure.FlashMessages;
using Infrastructure.PasswordPolicies;
using Infrastructure.QueueMessages.RazorMailMessages;
using Infrastructure.Translations;
using MassTransit;
using Web.Controllers.Base;
using Web.ViewModels.Login;
namespace Web.Controllers
{
public class LoginController : BaseController
{
private readonly IUserRepository _userRepository;
private readonly IServiceBus _bus;
private readonly ITranslationService _translationService;
private readonly IPasswordPolicy _passwordPolicy;
public LoginController(IUserRepository userRepository, IServiceBus bus, ITranslationService translationService, IPasswordPolicy passwordPolicy)
{
_userRepository = userRepository;
_bus = bus;
_translationService = translationService;
_passwordPolicy = passwordPolicy;
}
[HttpGet]
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
return View();
}
[HttpPost]
public ActionResult Index(LoginViewModel loginViewModel, string returnUrl)
{
if (_userRepository.Authenticate(loginViewModel.Email, loginViewModel.Password))
{
FormsAuthentication.SetAuthCookie(loginViewModel.Email, loginViewModel.RememberMe);
// Prevent open redirection attack (http://weblogs.asp.net/jgalloway/archive/2011/01/25/preventing-open-redirection-attacks-in-asp-net-mvc.aspx#comments)
if (Url.IsLocalUrl(returnUrl) && returnUrl != "/")
{
Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
AddFlashMessage(null, _translationService.Translate.EmailAndPasswordCombinationNotValid, FlashMessageType.Error, "messageContainer");
return View(loginViewModel);
}
[HttpGet]
public ActionResult ResetPassword()
{
return View();
}
[HttpPost]
public ActionResult ResetPassword(ResetPasswordViewModel resetPasswordViewModel)
{
var user = _userRepository.GetOne(x => x.Email == resetPasswordViewModel.Email.Trim());
if (user == null)
{
AddFlashMessage(null, string.Format(_translationService.Translate.UserWithEmailAddressWasNotFound, resetPasswordViewModel.Email), FlashMessageType.Success, "messageContainer");
return View(resetPasswordViewModel);
}
var resetPasswordUrl = Url.Action("ChangePassword", "Login", new { userId = user.Id, hash = _userRepository.GetHashForNewPasswordRequest(user)}, Request.Url.Scheme);
_bus.Publish(new ResetPasswordRequestMessage { DisplayName = user.DisplayName, Email = user.Email, ResetPasswordUrl = resetPasswordUrl, CultureInfo = user.Culture});
AddFlashMessage(null, _translationService.Translate.AnEmailWasSendToYourEmailaddressWithInstructionsOnHowToResetYourPassword, FlashMessageType.Success, "messageContainer");
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult ChangePassword(int userId, string hash)
{
var user = _userRepository.Get(userId);
if (!_userRepository.IsHashForNewPasswordRequestValid(user, hash))
{
throw new HttpException(403, "You don't have access to this page");
}
var changePasswordViewModel = new ChangePasswordViewModel { Hash = hash, UserId = userId };
return View(changePasswordViewModel);
}
[HttpPost]
public ActionResult ChangePassword(ChangePasswordViewModel changePasswordViewModel)
{
var user = _userRepository.Get(changePasswordViewModel.UserId);
if (!_userRepository.IsHashForNewPasswordRequestValid(user, changePasswordViewModel.Hash))
{
throw new HttpException(403, "You don't have access to this page");
}
if (!_passwordPolicy.Validate(changePasswordViewModel.Password))
{
AddFlashMessage(null, _translationService.Translate.PasswordShouldContainAtLeast5Characters, FlashMessageType.Error, "messageContainer");
return View(changePasswordViewModel);
}
_userRepository.ChangePassword(user, changePasswordViewModel.Password);
AddFlashMessage(null, _translationService.Translate.YourPasswordWasChangedSuccessfully, FlashMessageType.Success, "messageContainer");
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index");
}
}
}
|
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 MySql.Data.MySqlClient;
namespace TableroComando.Formularios
{
public partial class Form_ModificarObjetivoDetalle : Form
{
Clases.Modelo.Objetivo objetivo = new Clases.Modelo.Objetivo();
public Form_ModificarObjetivoDetalle(string idObjetivo)
{
InitializeComponent();
objetivo.setidobjectivo(idObjetivo);
}
private void Form_ModificarObjetivoDetalle_Load(object sender, EventArgs e)
{
try
{ // Cargo las perspectivas
string consulta = "select idperspectiva, nombreperspectiva from perspectivas;";
Clases.Herramientas.ejecutar ConsultaObject = new Clases.Herramientas.ejecutar();
MySqlDataAdapter Perspectivas = ConsultaObject.AdaptadorSQL(consulta);
DataSet DSConsulta = new DataSet();
Perspectivas.Fill(DSConsulta);
CBPerspectiva.DataSource = DSConsulta.Tables[0];
CBPerspectiva.ValueMember = "idperspectiva";
CBPerspectiva.DisplayMember = "nombreperspectiva";
// Cargo los datos del objetivo
objetivo = Clases.Modelo.Objetivo.buscarObjetivo(objetivo.getidobjetivo());
TXTTitulo.Text = objetivo.gettitulo();
TXTNumero.Text = objetivo.getnumero();
RTBDescripcion.Text = objetivo.getdescripcion();
CBPerspectiva.SelectedValue = objetivo.getperspectiva();
foreach (Clases.Modelo.Objetivo Obj in Clases.Modelo.Objetivo.objetivosPermitidos(objetivo.getidobjetivo(), objetivo.getperspectiva()))
{
DGVObjetivosDepende.Rows.Add(Obj.getidobjetivo(), Obj.getnumero(), Obj.gettitulo(), Obj.getnombreperspectiva());
}
foreach (string asociado in Clases.Modelo.Objetivo.objetivosAsociados(objetivo.getidobjetivo()))
{
foreach (char id in DGVObjetivosDepende.Rows[0].ToString())
{
if (Convert.ToString(id) == asociado)
{
DGVObjetivosDepende.SelectedCells[0].Selected = true;
}
}
}
}
catch
{
}
}
private void BTNModificar_Click(object sender, EventArgs e)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using System;
using System.IO;
using System.Text;
public class StageData_Hard : MonoBehaviour
{
//piecenum為確認拿到的拼圖的位置
//puzzlenum為確認拿到的拼圖種類 目前1-6種
//puzzlecheck為確認拿到了幾塊拼圖
//public static int piecenum = 0;
public static int puzzlenum = 0;
public static int puzzlecheck = 0;
//倒數計時
public int time_int = 90;
public int Qtime_int = 10;
//拼圖倒數計時
public static int puzzle_time = 40;
public Text time_UI;
public Text Qtime_UI;
//選項全內容
public string Option1 = " ";
public string Option2 = " ";
public string Option3 = " ";
public string Option4 = " ";
public string Option5 = " ";
public string Option6 = " ";
public string Option7 = " ";
public string Option8 = " ";
//data導入
public TextAsset data;
public TextAsset record;
public string[] lineArray;
string[][] Array;
public static string[] AllOption = new string[8]; //產生選項存放陣列
//儲存本題答案
string[] QuestionAns = new string[3];
int[] q = new int[3];
//產生確認此題為2ans類型或3ans類型
public static int ModeCheck;
//產生題號
int x ;
//產生答案與時間
int anscheck = 0;
int score=0;
int times = 0;
//產生各種視窗
public GameObject Panel; //下一關視窗
public GameObject Panel2; //失敗視窗
public GameObject Panel3; //獲取全部拼圖視窗
public GameObject QuestionPanel;
//產生英文題目與其備份
string EQ = " ";
string EQ_Re = " ";
public int Re_Check = 0;
//產生紀錄用時間以及答題記錄
public string DateTimeText;
public string record1;
public string record2;
public string record3;
//存檔路徑
public string path;
public string finishpath;
public string puzzlepath;
//產生儲存題目語音
public static string speak;
//儲存題目正確答案
public string FinalAnswer;
//儲存中文題目
public string CHQ;
//儲存獲取拼圖序號,初始為3x3拼圖
public static int[] PuzzleNumber = new int[9];
public int nn = 0; //確認puzzle的類別,決定個數
//計算獲得拼圖數
public void Start()
{
ModeCheck = 0;
StageData.ModeCheck = 0;
InvokeRepeating("timer", 1, 1);
lineArray = data.text.Split("\r"[0]);
Array = new string[lineArray.Length][];
for (int i = 0; i < lineArray.Length; i++)
{
Array[i] = lineArray[i].Split(">"[0]);
}
Data();
}
//題目計時器
void timer()
{
time_int -= 1;
time_UI.text = time_int + "";
if (time_int <= 0)
{
time_UI.text = "0";
OpenPanel2();
CancelInvoke("timer");
}
}
//中文題目預覽計時器
void Qtimer()
{
Qtime_int -= 1;
Qtime_UI.text = Qtime_int + "";
if (Qtime_int <= 0)
{
Qtime_UI.text = "0";
CloseQuestionPanel();
CancelInvoke("Qtimer");
}
}
//答題資料
public void Data()
{
//遊戲紀錄
path = Application.persistentDataPath + "/record.txt";
finishpath = Application.persistentDataPath + "/FinishPuzzle.txt";
puzzlepath = Application.persistentDataPath + "/puzzle.txt";
//系統時間紀錄
DateTimeText = DateTime.Now.ToString();
print(DateTimeText);
//拼圖模式確認
if (puzzlecheck == 0)
{
if (puzzlesetting.puzzletype == 3)
{
PuzzleCheck();
puzzle_time = 40;
nn = 9;
}
if (puzzlesetting.puzzletype == 4)
{
PuzzleCheck();
puzzle_time = 60;
nn = 16;
}
if (puzzlesetting.puzzletype == 5)
{
PuzzleCheck();
puzzle_time = 90;
nn = 25;
}
PuzzleNumber = new int[nn];
for (int pp = 0; pp < nn; pp++)
{
x = UnityEngine.Random.Range(1, nn + 1);
for (int j = 0; j < nn; j++)
{
if (PuzzleNumber[j] == null)
{
break;
}
while (x == PuzzleNumber[j])
{
x = UnityEngine.Random.Range(1, nn + 1);
j = 0;
continue;
}
}
PuzzleNumber[pp] = x;
//print("隨機:" + PuzzleNumber[pp]);
}
}
//問題選擇(目前沒有隨機問題選擇)
//題目從2開始
x = UnityEngine.Random.Range(1, 200);
if (x == 113)
{
x = UnityEngine.Random.Range(1, 200);
}
//Debug用
if (inputQ.question != null)
{
x = int.Parse(inputQ.question)-1;
inputQ.question = null;
}
int DebugNum = x+1;
print("目前題目:" + DebugNum) ;
//從data.txt獲取題目
CHQ = Array[x][0];
GameObject.Find("Canvas/Question/Q").GetComponent<Text>().text = CHQ;
print("中文字數:" + CHQ.Length);
if (CHQ.Length > 20)
{
Qtime_int = 5;
time_int = 95;
}
InvokeRepeating("Qtimer", 1, 1);
EQ = Array[x][2];
FinalAnswer = EQ;
GameObject.Find("Canvas/GameContent/Debug").GetComponent<Text>().text = EQ;
//Debug用
GameObject.Find("Canvas/DebugNum").GetComponent<Text>().text = DebugNum.ToString();
string Problem = Array[x][14];
int QuestionNum = 0;
print(EQ);
//例句的問題選擇
string OptionCheck = " ";
string[] Answer; //存入答案
string[] GetOption;
//OP存入 T F,F,F ; T F,F,F,F ; T F,F,F,F..
string OP = Array[x][14];
OP = OP.TrimEnd(';');
//OptionGroup 存入 T F,F,F
string[] OptionGroup = OP.Split(';');
string[][] WrongOption;
WrongOption = new string[OptionGroup.Length][];
Answer = new string[OptionGroup.Length];
string[][] Cache;
Cache = new string[OptionGroup.Length][];
int num = 0;
string[] P = new string[Answer.Length];
for (int i = 0; i < OptionGroup.Length; i++)
{
//Cache[0] 存入 T ; Cache[1]存入F,F,F
Cache[i] = OptionGroup[i].Split(" "[0]);
//Answer 存入 T
Answer[i] = Cache[i][0];
string PhCache = Answer[i];
//去除片語底線
if (PhCache.Contains("_"))
{
PhCache = PhCache.Replace('_', ' ');
Answer[i] = PhCache;
}
P[i] = Answer[i];
//將F分開存入二維陣列
string textcache = Cache[i][1];
WrongOption[i] = textcache.Split(","[0]);
}
//選擇挖空的問題導入P陣列
//確定題目中問題挖空數量有沒有大於等於3
if (P.Length >= 3)
{
ModeCheck = 1;
//選擇要出的問題(從P中取出3個選項)
int Q1 = UnityEngine.Random.Range(0, P.Length);
int Q2 = UnityEngine.Random.Range(0, P.Length);
int Q3 = UnityEngine.Random.Range(0, P.Length);
while(Q1 == Q3 || Q1 == Q2 || Q2 == Q3)
{
Q1 = UnityEngine.Random.Range(0, P.Length);
Q2 = UnityEngine.Random.Range(0, P.Length);
Q3 = UnityEngine.Random.Range(0, P.Length);
}
//將例句中之問題轉為底線
string P1 = P[Q1];
string P2 = P[Q2];
string P3 = P[Q3];
//確認隨機變數指到的選項有沒有在例句中,並且作替代以及確認選項產生
print(EQ);
while (Q1 != null && Q2 != null && Q3 != null)
{
if (Q1 < Q2 && Q1 < Q3)
{
QuestionAns[0] = P1;
if (Q2 < Q3)
{
QuestionAns[1] = P2;
QuestionAns[2] = P3;
break;
}
if (Q3 < Q2)
{
QuestionAns[1] = P3;
QuestionAns[2] = P2;
break;
}
}
if (Q2 < Q1 && Q2 < Q3)
{
QuestionAns[0] = P2;
if (Q1 < Q3)
{
QuestionAns[1] = P1;
QuestionAns[2] = P3;
break;
}
if (Q3 < Q1)
{
QuestionAns[1] = P3;
QuestionAns[2] = P1;
break;
}
}
if (Q3 < Q2 && Q3 < Q1)
{
QuestionAns[0] = P3;
if (Q1 < Q2)
{
QuestionAns[1] = P1;
QuestionAns[2] = P2;
break;
}
if (Q2 < Q1)
{
QuestionAns[1] = P2;
QuestionAns[2] = P1;
break;
}
}
}
speak = EQ;
EQ = EQ.Replace(QuestionAns[0], "1.______");
EQ = EQ.Replace(QuestionAns[1], "2.______");
EQ = EQ.Replace(QuestionAns[2], "3.______");
EQ_Re = EQ;
}
//確定題目中問題挖空數量少於3
if (P.Length < 3 )
{
ModeCheck = 2;
int Q1 = UnityEngine.Random.Range(0, P.Length);
int Q2 = UnityEngine.Random.Range(0, P.Length);
while (Q1==Q2)
{
Q2 = UnityEngine.Random.Range(0, P.Length);
}
//將例句中之問題轉為底線
string P1 = P[Q1];
string P2 = P[Q2];
//確認隨機變數指到的選項有沒有在例句中,並且作替代以及確認選項產生
if (Q1 < Q2)
{
QuestionAns[0] = P1;
QuestionAns[1] = P2;
}
if (Q2 < Q1)
{
QuestionAns[0] = P2;
QuestionAns[1] = P1;
}
speak = EQ;
EQ = EQ.Replace(QuestionAns[0], "1.______");
EQ = EQ.Replace(QuestionAns[1], "2.______");
EQ_Re = EQ;
}
else{
print("No Data");
}
print("答案:");
print(QuestionAns[0]);
print(QuestionAns[1]);
print(QuestionAns[2]);
//中英文問題
GameObject.Find("Canvas/GameContent/ChineseQ/Text").GetComponent<Text>().text = CHQ;
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ;
//確認答案順序
for (int i = 0; i < OptionGroup.Length; i++)
{
if (Answer[i] == QuestionAns[0] || Answer[i] == QuestionAns[1] || Answer[i] == QuestionAns[2])
{
q[num] = i;
//print(i);
//print(q[num]);
num++;
continue;
}
}
//確認此題解答數量是否超過2
if (ModeCheck==1)
{
int ii = 0;
while (ii<8)
{
//從3個答案隨機挑一個
int ran1 = UnityEngine.Random.Range(0, 3);
int ran = q[ran1];
//放入選項中
//if(ii<8&& Answer[ran] == null)
//{
// continue;
//}
if (ii == 0 && Answer[ran] != null)
{
AllOption[ii] = Answer[ran];
int ran3 = UnityEngine.Random.Range(0, WrongOption[ran].Length);
AllOption[ii + 1] = WrongOption[ran][ran3];
Answer[ran] = null;
WrongOption[ran][ran3] = null;
ii += 2;
continue;
}
if (ii == 2 && Answer[ran] != null)
{
AllOption[ii] = Answer[ran];
int ran3 = UnityEngine.Random.Range(0, WrongOption[ran].Length);
AllOption[ii + 1] = WrongOption[ran][ran3];
Answer[ran] = null;
WrongOption[ran][ran3] = null;
ii += 2;
continue;
}
if (ii == 2 && Answer[ran] == null)
{
continue;
}
if (ii == 4 && Answer[ran] != null)
{
AllOption[ii] = Answer[ran];
int ran3 = UnityEngine.Random.Range(0, WrongOption[ran].Length);
AllOption[ii + 1] = WrongOption[ran][ran3];
Answer[ran] = null;
WrongOption[ran][ran3] = null;
ii += 2;
continue;
}
if (ii == 4 && Answer[ran] == null)
{
continue;
}
if (ii == 6)
{
AllOption[ii] = GameObject.Find("Canvas/GameContent").GetComponent<OtherData>().GotData();
}
if (ii == 7)
{
AllOption[ii] = GameObject.Find("Canvas/GameContent").GetComponent<OtherData>().GotData();
}
ii += 1;
}
int iii = 0;
while (iii < 8)
{
int xx = UnityEngine.Random.Range(0, 8);
if (iii == 0 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_"," ");
}
Option1 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 1 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option2 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 1 && AllOption[xx] == null)
{
continue;
}
if (iii == 2 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option3 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 2 && AllOption[xx] == null)
{
continue;
}
if (iii == 3 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option4 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 3 && AllOption[xx] == null)
{
continue;
}
if (iii == 4 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option5 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 4 && AllOption[xx] == null)
{
continue;
}
if (iii == 5 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option6 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 5 && AllOption[xx] == null)
{
continue;
}
if (iii == 6 && AllOption[xx] != null)
{
Option7 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 6 && AllOption[xx] == null)
{
continue;
}
if (iii == 7 && AllOption[xx] != null)
{
Option8 = AllOption[xx];
AllOption[xx] = null;
iii += 1;
continue;
}
if (iii == 7 && AllOption[xx] == null)
{
continue;
}
iii += 1;
}
GameObject.Find("Canvas/GameContent/Pool/Option1/Text").GetComponent<Text>().text = Option1;
GameObject.Find("Canvas/GameContent/Pool/Option2/Text").GetComponent<Text>().text = Option2;
GameObject.Find("Canvas/GameContent/Pool/Option3/Text").GetComponent<Text>().text = Option3;
GameObject.Find("Canvas/GameContent/Pool/Option4/Text").GetComponent<Text>().text = Option4;
GameObject.Find("Canvas/GameContent/Pool/Option5/Text").GetComponent<Text>().text = Option5;
GameObject.Find("Canvas/GameContent/Pool/Option6/Text").GetComponent<Text>().text = Option6;
GameObject.Find("Canvas/GameContent/Pool/Option7/Text").GetComponent<Text>().text = Option7;
GameObject.Find("Canvas/GameContent/Pool/Option8/Text").GetComponent<Text>().text = Option8;
}
//解答數量小於2
if (ModeCheck==2)
{
int jj = 0;
while (jj < 8)
{
int ran1 = UnityEngine.Random.Range(0, 2);
int ran = q[ran1];
if (jj < 4 && Answer[ran] == null)
{
continue;
}
if (jj == 0 && Answer[ran] != null)
{
AllOption[jj] = Answer[ran];
int ran3 = UnityEngine.Random.Range(0, WrongOption[ran].Length);
AllOption[jj + 1] = WrongOption[ran][ran3];
Answer[ran] = null;
WrongOption[ran][ran3] = null;
jj += 2;
continue;
}
if (jj == 2 && Answer[ran] != null)
{
AllOption[jj] = Answer[ran];
int ran3 = UnityEngine.Random.Range(0, WrongOption[ran].Length);
AllOption[jj + 1] = WrongOption[ran][ran3];
Answer[ran] = null;
WrongOption[ran][ran3] = null;
jj += 2;
continue;
}
if (jj == 2 && Answer[ran] == null)
{
continue;
}
int ran2 = UnityEngine.Random.Range(0, WrongOption[ran].Length);
if (jj>=4&&WrongOption[ran].Length <2)
{
string ch = GameObject.Find("Canvas/GameContent").GetComponent<OtherData>().GotData();
//print("替換的單字:"+ch);
AllOption[jj] = ch;
jj += 1;
continue;
}
if (jj >= 4 && WrongOption[ran][ran2] == null)
{
continue;
}
if (jj == 4 && WrongOption[ran][ran2] != null)
{
AllOption[jj] = WrongOption[ran][ran2];
WrongOption[ran][ran2] = null;
jj += 1;
continue;
}
if (jj >= 5 && WrongOption[ran][ran2] == null)
{
continue;
}
if (jj == 5 && WrongOption[ran][ran2] != null)
{
AllOption[jj] = WrongOption[ran][ran2];
WrongOption[ran][ran2] = null;
jj += 1;
continue;
}
if (jj == 6)
{
AllOption[jj] = GameObject.Find("Canvas/GameContent").GetComponent<OtherData>().GotData();
}
if (jj == 7)
{
AllOption[jj] = GameObject.Find("Canvas/GameContent").GetComponent<OtherData>().GotData();
}
jj += 1;
}
int jjj = 0;
while (jjj < 8)
{
int xx = UnityEngine.Random.Range(0, 8);
if (jjj == 0 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option1 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 1 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option2 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 1 && AllOption[xx] == null)
{
continue;
}
if (jjj == 2 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option3 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 2 && AllOption[xx] == null)
{
continue;
}
if (jjj == 3 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option4 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 3 && AllOption[xx] == null)
{
continue;
}
if (jjj == 4 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option5 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 4 && AllOption[xx] == null)
{
continue;
}
if (jjj == 5 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option6 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 5 && AllOption[xx] == null)
{
continue;
}
if (jjj == 6 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option7 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 6 && AllOption[xx] == null)
{
continue;
}
if (jjj == 7 && AllOption[xx] != null)
{
if (AllOption[xx].Contains("_"))
{
AllOption[xx] = AllOption[xx].Replace("_", " ");
}
Option8 = AllOption[xx];
AllOption[xx] = null;
jjj += 1;
continue;
}
if (jjj == 7 && AllOption[xx] == null)
{
continue;
}
jjj += 1;
}
GameObject.Find("Canvas/GameContent/Pool/Option1/Text").GetComponent<Text>().text = Option1;
GameObject.Find("Canvas/GameContent/Pool/Option2/Text").GetComponent<Text>().text = Option2;
GameObject.Find("Canvas/GameContent/Pool/Option3/Text").GetComponent<Text>().text = Option3;
GameObject.Find("Canvas/GameContent/Pool/Option4/Text").GetComponent<Text>().text = Option4;
GameObject.Find("Canvas/GameContent/Pool/Option5/Text").GetComponent<Text>().text = Option5;
GameObject.Find("Canvas/GameContent/Pool/Option6/Text").GetComponent<Text>().text = Option6;
GameObject.Find("Canvas/GameContent/Pool/Option7/Text").GetComponent<Text>().text = Option7;
GameObject.Find("Canvas/GameContent/Pool/Option8/Text").GetComponent<Text>().text = Option8;
}
//創建紀錄
if (!File.Exists(path))
{
File.WriteAllText(path, "錯誤紀錄:\n");
}
if (!File.Exists(finishpath))
{
File.WriteAllText(finishpath, "0");
}
if (!File.Exists(puzzlepath))
{
File.WriteAllText(puzzlepath, "0");
}
//顯示目前所得拼圖數
GameObject.Find("Canvas/Level").GetComponent<Text>().text = "Got " + StageData_Hard.puzzlecheck.ToString() + " puzzles";
//初始設定拼圖塊數以及拼圖時間
GameObject.Find("Canvas/PuzzleTime").GetComponent<Text>().text = "Puzzle Time:"+puzzle_time;
}
public void Update()
{
}
int failcheck = 0;
//答案選擇及確認
public void PushButtom1()
{
string buttom1 = GameObject.Find("Canvas/GameContent/Pool/Option1/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option1").SetActive(false);
AnswerCheck(anscheck, score,buttom1);
}
public void PushButtom2()
{
string buttom2 = GameObject.Find("Canvas/GameContent/Pool/Option2/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option2").SetActive(false);
AnswerCheck(anscheck, score, buttom2);
}
public void PushButtom3()
{
string buttom3 = GameObject.Find("Canvas/GameContent/Pool/Option3/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option3").SetActive(false);
AnswerCheck(anscheck, score, buttom3);
}
public void PushButtom4()
{
string buttom4 = GameObject.Find("Canvas/GameContent/Pool/Option4/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option4").SetActive(false);
AnswerCheck(anscheck, score, buttom4);
}
public void PushButtom5()
{
string buttom5 = GameObject.Find("Canvas/GameContent/Pool/Option5/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option5").SetActive(false);
AnswerCheck(anscheck, score, buttom5);
}
public void PushButtom6()
{
string buttom6 = GameObject.Find("Canvas/GameContent/Pool/Option6/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option6").SetActive(false);
AnswerCheck(anscheck, score, buttom6);
}
public void PushButtom7()
{
string buttom7 = GameObject.Find("Canvas/GameContent/Pool/Option7/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option7").SetActive(false);
AnswerCheck(anscheck, score, buttom7);
}
public void PushButtom8()
{
string buttom8 = GameObject.Find("Canvas/GameContent/Pool/Option8/Text").GetComponent<Text>().text;
if (anscheck == 3 && ModeCheck == 1)
{
return;
}
if (anscheck == 2 && ModeCheck == 2)
{
return;
}
GameObject.Find("Canvas/GameContent/Pool/Option8").SetActive(false);
AnswerCheck(anscheck, score, buttom8);
}
//根據錯誤次數記錄
public int WrongTimes = 0;
//確認答案是否正確給予分數
public void AnswerCheck(int value,int ScoreValue,string ans = " ")
{
if(ans.Equals("re"))
{
return;
}
//選項選擇後的答案確認
if (anscheck == 0 && ans == QuestionAns[0])
{
anscheck += 1;
score += 100;
print("現在模式為:" + ModeCheck);
print("目前分數:" + anscheck + "目前anscheck:" + score);
GameObject.Find("Canvas/Score/text").GetComponent<Text>().text = score.ToString();
EQ = EQ.Replace("1.______", "<color=#0000ff><b>" + ans + "</b></color>"); //選擇後放入答案,並做顏色變換
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ;
return;
}
if (anscheck == 0 && ans != QuestionAns[0])
{
anscheck += 1;
score -= 100;
WrongTimes += 1;
if (WrongTimes == 1)
{
File.AppendAllText(path, "時間:" + DateTimeText + "\n" + "題號:" + x + "\n" + "中文:" + CHQ + "\n");
File.AppendAllText(path, "英文:" + EQ_Re + "\n");
}
print("現在模式為:" + ModeCheck);
print("目前分數:" + anscheck + "目前anscheck:" + score);
GameObject.Find("Canvas/Score/text").GetComponent<Text>().text = score.ToString();
EQ = EQ.Replace("1.______", "<color=#B71B1BFF><b>" + ans + "</b></color>");
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ;
File.AppendAllText(path, "第1格選擇了:" + ans + "正解為:" + QuestionAns[0] + "\n");
return;
}
if (anscheck == 1 && ans == QuestionAns[1])
{
anscheck += 1;
score += 100;
print("現在模式為:" + ModeCheck);
print("目前分數:" + anscheck + "目前anscheck:" + score);
GameObject.Find("Canvas/Score/text").GetComponent<Text>().text = score.ToString();
EQ = EQ.Replace("2.______", "<color=#0000ff><b>" + ans + "</b></color>");
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ;
if (ModeCheck == 1)
{
return;
}
}
if (anscheck == 1 && ans != QuestionAns[1])
{
anscheck += 1;
score -= 100;
WrongTimes += 1;
if (WrongTimes == 1)
{
File.AppendAllText(path, "時間:" + DateTimeText + "\n"+"題號:"+ x+"\n" + "中文:" + CHQ + "\n");
File.AppendAllText(path, "英文:" + EQ_Re + "\n");
}
print("現在模式為:" + ModeCheck);
print("目前分數:" + anscheck + "目前anscheck:" + score);
GameObject.Find("Canvas/Score/text").GetComponent<Text>().text = score.ToString();
EQ = EQ.Replace("2.______", "<color=#B71B1BFF><b>" + ans + "</b></color>");
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ;
File.AppendAllText(path, "第2格選擇了:" + ans + "正解為:" + QuestionAns[1] + "\n");
if (ModeCheck == 1)
{
return;
}
}
if (anscheck == 2 && ans == QuestionAns[2] && ModeCheck == 1)
{
anscheck += 1;
score += 100;
print("現在模式為:" + ModeCheck);
print("目前分數:" + anscheck + "目前anscheck:" + score);
GameObject.Find("Canvas/Score/text").GetComponent<Text>().text = score.ToString();
EQ = EQ.Replace("3.______", "<color=#0000ff><b>" + ans + "</b></color>");
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ;
}
if (anscheck == 2 && ans != QuestionAns[2] && ModeCheck == 1)
{
anscheck += 1;
score -= 100;
WrongTimes += 1;
if (WrongTimes == 1)
{
File.AppendAllText(path, "時間:" + DateTimeText + "\n" + "題號:" + x + "\n" + "中文:" + CHQ + "\n");
File.AppendAllText(path, "英文:" + EQ_Re + "\n");
}
print("現在模式為:" + ModeCheck);
print("目前分數:" + anscheck + "目前anscheck:" + score);
GameObject.Find("Canvas/Score/text").GetComponent<Text>().text = score.ToString();
EQ = EQ.Replace("3.______", "<color=#B71B1BFF><b>" + ans + "</b></color>");
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ;
File.AppendAllText(path, "第3格選擇了:" + ans + "正解為:" + QuestionAns[2] + "\n");
}
return;
}
public void EnterCheck()
{
print("yes");
print("現在模式為:" + ModeCheck);
print("最終分數:" + anscheck + "目前anscheck:" + score);
//最終分數確認是否通關
if (ModeCheck == 1 && anscheck == 3 && score == 300)
{
puzzlecheck += 1;
GameObject.Find("Canvas/Level").GetComponent<Text>().text = "Got " + StageData_Hard.puzzlecheck.ToString() + " puzzles";
if (puzzlesetting.puzzletype == 3)
{
if (puzzlecheck == 9)
{
print("puzzle已打開");
OpenPuzzlePanel();
CancelInvoke("timer");
return;
}
}
if (puzzlesetting.puzzletype == 4)
{
if (puzzlecheck == 16)
{
print("puzzle已打開");
OpenPuzzlePanel();
CancelInvoke("timer");
return;
}
}
if (puzzlesetting.puzzletype == 5)
{
if (puzzlecheck == 25)
{
print("puzzle已打開");
OpenPuzzlePanel();
CancelInvoke("timer");
return;
}
}
print("答對");
OpenPanel();
CancelInvoke("timer");
return;
}
if (ModeCheck == 2 && anscheck == 2 && score == 200)
{
puzzlecheck += 1;
print("現在模式為:" + ModeCheck);
print("最終分數:" + anscheck + "目前anscheck:" + score);
GameObject.Find("Canvas/Level").GetComponent<Text>().text = "Got " + StageData_Hard.puzzlecheck.ToString() + " puzzles";
//確認是否開啟拼圖視窗
if (puzzlesetting.puzzletype==3)
{
if (puzzlecheck == 9)
{
print("puzzle已打開");
OpenPuzzlePanel();
CancelInvoke("timer");
return;
}
}
if (puzzlesetting.puzzletype == 4)
{
if (puzzlecheck == 16)
{
print("puzzle已打開");
OpenPuzzlePanel();
CancelInvoke("timer");
return;
}
}
if (puzzlesetting.puzzletype == 5)
{
if (puzzlecheck == 25)
{
print("puzzle已打開");
OpenPuzzlePanel();
CancelInvoke("timer");
return;
}
}
print("答對");
OpenPanel();
CancelInvoke("timer");
return;
}
if (ModeCheck == 1 && anscheck == 3 && score <= 300)
{
print("失敗");
puzzle_time = puzzle_time - 5;
OpenPanel2();
CancelInvoke("timer");
return;
}
if (ModeCheck == 2 && anscheck == 2 && score <= 200)
{
print("失敗");
puzzle_time = puzzle_time - 5;
OpenPanel2();
CancelInvoke("timer");
return;
}
}
public string[] FinishPuzzle;
public string finish;
public int NumPuzzle;
public void PuzzleCheck()
{
finish = File.ReadAllText(finishpath);
int puzzletype = UnityEngine.Random.Range(1, 312);
FinishPuzzle = finish.Split(',');
for (int i = 0; i < FinishPuzzle.Length; i++)
{
if (int.Parse(FinishPuzzle[i]) == puzzletype)
{
puzzletype = UnityEngine.Random.Range(1, 312);
continue;
}
break;
}
puzzlenum = puzzletype;
File.WriteAllText(puzzlepath, puzzlenum.ToString());
}
public void Re()
{
if(Re_Check == 1)
{
return;
}
//重置答案與分數
anscheck = 0;
score = 0;
EQ = EQ_Re;
//重新打亂順序
int[] RanOpAgain = new int[8];
for (int i = 0; i < 8; i++)
{
int temp = UnityEngine.Random.Range(1, 9);
for(int j = 0; j < 8;j++)
{
while (RanOpAgain[j] == temp)
{
temp = UnityEngine.Random.Range(1, 9);
j = 0;
continue;
}
}
RanOpAgain[i] = temp;
if (i == 0)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option1;
}
if (i == 1)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option2;
}
if (i == 2)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option3;
}
if (i == 3)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option4;
}
if (i == 4)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option5;
}
if (i == 5)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option6;
}
if (i == 6)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option7;
}
if (i == 7)
{
GameObject.Find("Canvas/GameContent/Pool/Option" + temp).SetActive(true);
GameObject.Find("Canvas/GameContent/Pool/Option" + temp + "/Text").GetComponent<Text>().text = Option8;
}
}
//重置英文題目
GameObject.Find("Canvas/GameContent/EnglishQ/Text").GetComponent<Text>().text = EQ_Re;
//重置分數
GameObject.Find("Canvas/Score/text").GetComponent<Text>().text = score.ToString();
//重置時間
time_int -= 10;
//呼叫函式,改變目前答案
AnswerCheck(anscheck, score, "re");
return;
}
public void NextCheck()
{
Re_Check = 1;
EnterCheck();
}
//過關顯示windows
public void OpenPanel()
{
if (Panel != null)
{
Panel.SetActive(true);
GameObject.Find("Canvas/Next/answer2").GetComponent<Text>().text = FinalAnswer;
}
}
//拼圖開始
public void OpenPuzzlePanel()
{
if (Panel3 != null)
{
Panel3.SetActive(true);
GameObject.Find("Canvas/PuzzlePanel/answer").GetComponent<Text>().text = FinalAnswer;
}
}
//通關失敗
public void OpenPanel2()
{
if (Panel2 != null)
{
Panel2.SetActive(true);
}
}
public void CloseQuestionPanel()
{
if (QuestionPanel != null)
{
QuestionPanel.SetActive(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace IniFileLibrary
{
public class Monitor_Ini : IniFile
{
public int IntervalTime = 0;
public int IntervalMinute = 1;
public const int OneMinute = 60000;//1000ms * 60s = 1 min
public Monitor_Ini()
{
Get();
}
public void Set()
{
IniWriteValue("Monitor", "IntervalMinute", IntervalMinute.ToString());
}
public void Get()
{
IntervalMinute = 1;
int.TryParse(IniReadValue("Monitor", "IntervalMinute"), out IntervalMinute); if (0 == IntervalMinute) { IntervalMinute = 1; }
this.IntervalTime = IntervalMinute * OneMinute;
//this.IntervalTime = 2000;
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using LinqToSqlWrongDistinctClauseReproduction;
namespace LinqToSqlWrongDistinctClauseReproduction.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rtm-21431")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.Property", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("Id");
b.Property<DateTime>("CreationDate")
.HasColumnName("CreationDate");
b.Property<string>("Details")
.HasColumnName("Details");
b.Property<string>("ForeignId")
.IsRequired()
.HasColumnName("ForeignId");
b.Property<bool>("IsRemoved")
.HasColumnName("IsRemoved");
b.Property<DateTime?>("LastUpdate")
.HasColumnName("LastUpdate");
b.Property<DateTime?>("RemovalDate");
b.Property<int>("Source")
.HasColumnName("Source");
b.HasKey("Id");
b.HasIndex("ForeignId");
b.HasIndex("Source", "ForeignId")
.IsUnique();
b.ToTable("Property");
});
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.QueryDefinition", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("Id");
b.Property<bool>("IsArchived")
.HasColumnName("IsArchived");
b.Property<string>("Name")
.IsRequired()
.HasColumnName("Name")
.HasAnnotation("MaxLength", 255);
b.Property<string>("QueryString")
.IsRequired()
.HasColumnName("Query");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("QueryDefinition");
});
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.QueryRun", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("Id");
b.Property<DateTime>("DateTime")
.HasColumnName("DateTime");
b.Property<bool>("HasErrors")
.HasColumnName("HasErrors");
b.Property<string>("Message")
.HasColumnName("Message");
b.Property<Guid>("QueryDefinitionId");
b.HasKey("Id");
b.HasIndex("QueryDefinitionId");
b.ToTable("QueryRun");
});
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.QueryRunResult", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("Id");
b.Property<bool>("IsNew")
.HasColumnName("IsNew");
b.Property<Guid>("PropertyId");
b.Property<Guid>("QueryRunId");
b.HasKey("Id");
b.HasIndex("PropertyId");
b.HasIndex("QueryRunId");
b.ToTable("QueryRunResult");
});
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.User", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.QueryDefinition", b =>
{
b.HasOne("LinqToSqlWrongDistinctClauseReproduction.Models.User", "User")
.WithMany("Definitions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.QueryRun", b =>
{
b.HasOne("LinqToSqlWrongDistinctClauseReproduction.Models.QueryDefinition", "QueryDefinition")
.WithMany("Runs")
.HasForeignKey("QueryDefinitionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("LinqToSqlWrongDistinctClauseReproduction.Models.QueryRunResult", b =>
{
b.HasOne("LinqToSqlWrongDistinctClauseReproduction.Models.Property", "Property")
.WithMany()
.HasForeignKey("PropertyId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("LinqToSqlWrongDistinctClauseReproduction.Models.QueryRun", "QueryRun")
.WithMany("Results")
.HasForeignKey("QueryRunId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("LinqToSqlWrongDistinctClauseReproduction.Models.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("LinqToSqlWrongDistinctClauseReproduction.Models.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("LinqToSqlWrongDistinctClauseReproduction.Models.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
|
using System.Collections.Generic;
namespace Tests.Data.Van.Input
{
public class MiniVanExportData
{
public string ListName = "";
public string MiniVanFormat = "";
public string ContactedHow = "";
public Dictionary<string, bool> ScriptOptionsRadioButtonDictionary = new Dictionary<string, bool>
{
{ "Choose a Script for everyone in the List", false },
{ "Choose a Default Script and up to 4 alternate scripts", false },
{ "Choose a Default Script and alternate scripts based on target's subgroups", false }
};
public string Script = "";
public string Canvasser = "";
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
[Header("Shooting")]
[System.NonSerialized] public bool isCanShoot = true;
[SerializeField] float bulletSpeed = 5.0f;
[SerializeField] Transform bulletSpawnPos;
[SerializeField] GameObject bulletPrefab;
[SerializeField] Vector3 minScale = new Vector3(0.2f, 0.2f, 0.2f);
GameObject bullet;
public float GetPathWidth() {
return transform.localScale.x + 0.3f;
}
public float GetBulletWidth() {
return bullet != null ? bullet.transform.localScale.x : 0;
}
public void InitShoot() {
bullet = Instantiate(bulletPrefab, bulletSpawnPos.position, Quaternion.identity, null);
bullet.transform.localScale = minScale;
transform.localScale -= minScale;
}
public void OnHold(Vector3 pos, float holdTime) {
if (bullet == null)
return;
Vector3 scaleChange = Vector3.one * holdTime / 100f;
bullet.transform.localScale += scaleChange;
transform.localScale -= scaleChange;
if (transform.localScale.x < minScale.x) {
GameManager.instance.OnLose();
}
}
public void ShootTo(Vector3 pos, float holdTime) {
if (bullet == null)
return;
Rigidbody rb = bullet.GetComponent<Rigidbody>();
Vector3 velocity = (pos - rb.transform.position).normalized;
velocity.y = 0.0f;
rb.velocity = velocity.normalized * bulletSpeed;
bullet = null;
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Project3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Project3.Controllers
{
public class AdminController : Controller
{
private readonly ProjectContext _context;
public AdminController(ProjectContext context)
{
_context = context;
}
public async Task<IActionResult> Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login([Bind("Aname,Apass")] TblAdmin admin)
{
var user = _context.TblAdmin.Single(x => x.Aname == admin.Aname);
if (user != null)
{
if (user.Apass == admin.Apass)
{
ViewBag.msg = "Valid Credentials";
return RedirectToAction("Dashboard", user.Aid);
}
else
ViewBag.msg = "Invalid Credentials";
}
else
ViewBag.msg = "Invalid Credentials";
return View();
}
// GET: AdminController
public ActionResult Index()
{
return RedirectToAction("Login");
}
public IActionResult Dashboard()
{
return View();
}
public IActionResult GetAllLaptop()
{
return RedirectToRoute(new
{
controller = "AvailableLaptops",
action = "Index",
});
}
public async Task<IActionResult> SaleReport()
{
return RedirectToRoute(new
{
controller = "OrderedLaptops",
action = "Index"
});
}
// GET: AdminController/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AdminController/Create
public ActionResult Create()
{
return View();
}
// POST: AdminController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: AdminController/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: AdminController/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: AdminController/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: AdminController/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, IFormCollection collection)
{
try
{
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
public IActionResult Logout()
{
return RedirectToRoute(new
{
controller = "Home",
action = "Index"
});
}
}
}
|
using UnityEngine;
using System.Collections;
public class GameHUD : MonoBehaviour {
void OnGUI () {
float height = Screen.currentResolution.height;
float buttonSize = height / 8;
// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
if(GUI.Button(new Rect(10,0,buttonSize,buttonSize), "Red")) {
GameObject dasher = GameObject.FindGameObjectWithTag("Player");
if(dasher) {
// ColorChangerScript colorChanger = dasher.GetComponent<ColorChangerScript>();
// if(colorChanger) colorChanger.color = 0;
}
}
if(GUI.Button(new Rect(10,buttonSize,buttonSize,buttonSize), "Green")) {
GameObject dasher = GameObject.FindGameObjectWithTag("Player");
if(dasher) {
// ColorChangerScript colorChanger = dasher.GetComponent<ColorChangerScript>();
// if(colorChanger) colorChanger.color = 1;
}
}
if(GUI.Button(new Rect(10,2 * buttonSize,buttonSize,buttonSize), "Blue")) {
GameObject dasher = GameObject.FindGameObjectWithTag("Player");
if(dasher) {
// ColorChangerScript colorChanger = dasher.GetComponent<ColorChangerScript>();
// if(colorChanger) colorChanger.color = 2;
}
}
}
}
|
using AGL.DeveloperTest.Contracts.DataProviders;
using AGL.DeveloperTest.Contracts.Services;
using AGL.DeveloperTest.DataProviders;
using AGL.DeveloperTest.Models;
using System.Collections.Generic;
using System.Linq;
namespace AGL.DeveloperTest.Services
{
/// <summary>
/// PeopleService class
/// </summary>
public class PeopleService : IPeopleService
{
private IJosnDataProvider _josnDataProvider;
/// <summary>
/// Default constructor
/// </summary>
public PeopleService(IJosnDataProvider josnDataProvider)
{
_josnDataProvider = josnDataProvider;
}
/// <summary>
/// Get gender
/// </summary>
/// <returns>List of gender</returns>
public List<string> GetGenders()
{
return _josnDataProvider.GetPeople().Select(d => d.Gender).Distinct().ToList();
}
/// <summary>
/// Get pet names by gender
/// </summary>
/// <param name="type">string</param>
/// <returns>List of PetNamesByGender</returns>
public List<PetNamesByGender> GetPetsByGender(string type)
{
var result = new List<PetNamesByGender>();
var gendersList = GetGenders();
foreach(var gender in gendersList)
{
var petsByGender = new PetNamesByGender();
petsByGender.Gender = gender;
petsByGender.PetNames = _josnDataProvider.GetPeople()
.Where(e => e.Gender.ToLower() == gender.ToLower() && e.Pets != null)
.SelectMany(r => r.Pets)
.Where(e => e.Type.ToLower() == type.ToLower())
.Select(r => r.Name)
.OrderBy(r => r).ToList();
result.Add(petsByGender);
}
return result;
}
/// <summary>
/// Get cat names by gender
/// </summary>
/// <returns>List of PetNamesByGender</returns>
public List<PetNamesByGender> GetCatsByGender()
{
return GetPetsByGender("cat");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Vista_Inicio_avisos_generales : System.Web.UI.Page
{
private int iMODIFICAR = 1;
private int iCONSULTA = 2;
private int iSIN_ACCESO = 3;
/// <summary>
/// PAGE_LOAD
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
#region Page_Load
protected void Page_Load(object sender, EventArgs e)
{
//Instancia a la clase SessionTimeOut
SessionTimeOut obj_Session = new SessionTimeOut();
//****************
//se manda llamar al metodo de validar sesion
bool bSessionE = obj_Session.IsSessionTimedOut();
//***********
//se valida la sesion
if (!bSessionE)
{
//SE asigna el ID de usuario Loggeado
ahddUser.Value = Session["iIdUsuario"].ToString();
//**************************
//Inicio TRY
try
{
//Se declaran y crean los breadCrumbs
string[] sDatos = { "Inicio", "Avisos" };
string[] sUrl = { "" };
breadCrum.migajas(sDatos, sUrl);
//*********************************
///MANDA LLAMAR MÉTODO PARA GENERAR DETALLE
fn_generar_detalle_aviso(Session["iIdUsuario"].ToString());
///INSTANCIA A LA CLASE AVISOS
Avisos aviso = new Avisos();
///VARIABLE PARA RECUPERAR ID DE USUARIO
Security secUser = new Security(Session["iIdUsuario"].ToString());
aviso.gsUsuario = int.Parse(secUser.DesEncriptar());
///SE MANDA LLAMAR MÉTODO PARA ACTUALIZAR ESTATUS
aviso.getActualizarEstatusAviso(aviso, 2);
}
//*******
//Inicio Catch
catch
{
//si ocurre algun error se redirecciona al usuario al Inicio
Response.Redirect("../Inicio/Inicio.aspx");
//******
}
//******************
}
//**********
else
{
//si se termino el tiempo de sesion se redirecciona al Login y se limpia sesion
Session.Clear();
Session.Abandon();
Response.Redirect("../../Login.aspx");
//***********
}
//*************
}
#endregion
/// <summary>
/// MÉTODO PARA GENERAR DETALLE DE AVISOS SIN VER
/// </summary>
/// <param name="sCveUser"></param>
#region fn_generar_detalle_aviso
public void fn_generar_detalle_aviso(string sCveUser)
{
///
Conexion conn = new Conexion();
///
string dFECHA_ACTUAL = DateTime.Now.ToString("yyyy-MM-dd");
///Instancia a objeto para desencryptar id de usuario
Security encUser = new Security(sCveUser.ToString());
///
string sQuery = "SELECT COUNT(*) FROM tb_Avisos WHERE '" + dFECHA_ACTUAL + " 00:00:00' BETWEEN dFechaInicio AND dFechaFin AND iIdUsuario = " + encUser.DesEncriptar();
string[] sTotal = conn.ejecutarConsultaRegistroSimple(sQuery);
if (sTotal[0] == "1")
{
//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "none","<script>$('#hdvAvisosUsuario').modal('show');</script>", false);
if (sTotal[1] != "0")
{
///INTANCIA A CLASE AVISOS
Avisos aviso = new Avisos();
///ASIGNA ID DE USUARIO
aviso.gsUsuario = int.Parse(encUser.DesEncriptar());
///MANDA LLAMAR MÉTODO PARA GENERAR LISTADO
aviso.getGeneraListadoAvisos(aviso, 2);
///VERIFICA ÉXITO EN EJECUCIÓN
if (aviso.iResultado == 1)
{
///ASIGNA CONTENIDO A VARIABLE
alblListadoAvisos.Text = aviso.sContenido;
}
}
else {
hdvAlertaAviso.Visible = true;
}
}
}
#endregion
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.Basics
{
/// <summary>
/// 库房
/// </summary>
public class E_StorageRoom
{
/// <summary>
/// 库房ID
/// </summary>
public int id { get; set; }
/// <summary>
/// 库房名称
/// </summary>
public string roomid { get; set; }
}
}
|
namespace MySurveys.Web.ViewModels.Account
{
using System.Collections.Generic;
using System.Configuration;
using Newtonsoft.Json;
public class ReCaptcha
{
private string m_Success;
private List<string> m_ErrorCodes;
[JsonProperty("success")]
public string Success
{
get { return this.m_Success; }
set { this.m_Success = value; }
}
[JsonProperty("error-codes")]
public List<string> ErrorCodes
{
get { return this.m_ErrorCodes; }
set { this.m_ErrorCodes = value; }
}
public static bool Validate(string EncodedResponse)
{
var client = new System.Net.WebClient();
string privateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"];
var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", privateKey, EncodedResponse));
var captchaResponse = JsonConvert.DeserializeObject<ReCaptcha>(GoogleReply);
return captchaResponse.Success == "true";
}
}
} |
using System;
using System.ComponentModel;
using Spectre.Console;
using Spectre.Console.Cli;
namespace WitsmlExplorer.Console.ListCommands
{
public class ListRisksSettings : CommandSettings
{
[CommandOption("--uidWell")]
[Description("Well UID")]
[DefaultValue("")]
public string WellUid { get; init; }
[CommandOption("--uidWellbore")]
[Description("Wellbore UID")]
[DefaultValue("")]
public string WellboreUid { get; init; }
[CommandOption("--source")]
[Description("Source for the risk")]
[DefaultValue("")]
public string Source { get; init; }
[CommandOption("--lastChanged")]
[Description("A valid timestamp for when the risk was last changed (example: 2021-06-17T01:37:16.594Z)")]
[DefaultValue("")]
public string LastChanged { get; init; }
public override ValidationResult Validate()
{
if (string.IsNullOrEmpty(WellUid) && string.IsNullOrEmpty(LastChanged))
return ValidationResult.Error("You need to filter on either uidWell/uidWellbore or last changed");
if (!string.IsNullOrEmpty(LastChanged) && !DateTime.TryParse(LastChanged, out _))
return ValidationResult.Error("Invalid format for last changed");
return ValidationResult.Success();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.