text stringlengths 13 6.01M |
|---|
// Copyright © 2020 Void-Intelligence All Rights Reserved.
using Nomad.Core;
using Vortex.Activation.Utility;
using static System.Math;
namespace Vortex.Activation.Kernels
{
public sealed class Tanh : BaseActivation
{
public override Matrix Forward(Matrix input)
{
return input.Map(Activate);
}
public override Matrix Backward(Matrix input)
{
return input.Map(Derivative);
}
public override double Activate(double input)
{
return (Exp(input) - Exp(-input)) / (Exp(input) + Exp(-input));
}
public override double Derivative(double input)
{
return 1 - Pow((Exp(input) - Exp(-input)) / (Exp(input) + Exp(-input)), 2);
}
public override EActivationType Type()
{
return EActivationType.Tanh;
}
}
}
|
using Hayaa.CacheKeyStatic;
using Hayaa.Netcore.SessionEncryption;
using Hayaa.Redis.Client;
using Hayaa.Security.Client.Config;
using Hayaa.Security.Service;
using System;
namespace Hayaa.ConfigSecurity.Client
{
class ConfigSecurityProvider
{
private static SessionEncryption se = new SessionEncryption();
public static Boolean Auth(int appId, String appToken)
{
appToken = se.Decrypt(appToken);
Boolean result = false;
var info = RedisService.Get<AppToken>(DefineTable.CacheName, String.Format(ConfigAuthorityCacheKey.AuthorityCacheKey, appId));
if (info != null)
{
if ((info.Token== appToken) && (info.Status))
{
result = true;
}
if (String.IsNullOrEmpty(appToken))
{
result = false;
}
}
return result;
}
}
}
|
using FrbaOfertas.AbmRubro;
using FrbaOfertas.Helpers;
using FrbaOfertas.Model;
using FrbaOfertas.Model.DataModel;
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 FrbaOfertas.AbmProveedor
{
public partial class NuevoProveedor : Form
{
List<TextBox> noNulos= new List<TextBox>();
List<TextBox> numericos= new List<TextBox>();
List<TextBox> todos = new List<TextBox>();
public object returnDireccion { get; set; }
public object returnProveedor { get; set; }
Dictionary<Int32, String> rubros;
ProveedorData dataP;
DireccionData dataD;
Exception exError = null;
bool noDB=false;
public NuevoProveedor(bool db)
{
InitializeComponent();
noDB = db;
}
public NuevoProveedor()
{
InitializeComponent();
}
private void NuevoCliente_Load(object sender, EventArgs e)
{
noNulos.Add(prov_razon_social);
noNulos.Add(prov_CUIT);
//noNulos.Add(prov_rubro);
//noNulos.Add(prov_contacto);
noNulos.Add(dom_calle);
noNulos.Add(dom_ciudad);
//numericos.Add(prov_CUIT);
numericos.Add(dom_numero);
numericos.Add(dom_depto);
numericos.Add(dom_piso);
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
todos.Add((TextBox)x);
}
}
dataD = new DireccionData(Conexion.getConexion());
dataP = new ProveedorData(Conexion.getConexion());
rubros = dataP.Rubros(out exError);
agregarRubros(rubros);
}
private void setRubro(int p)
{
foreach (KeyValuePair<int, string> entry in rubros)
{
if (entry.Key == p)
rubrosComboBox.Text = entry.Value;
}
}
private void agregarRubros(Dictionary<int, string> rubros)
{
foreach (KeyValuePair<int, string> entry in rubros)
{
rubrosComboBox.Items.Add(entry.Value);
}
}
private void guardar_Click(object sender, EventArgs e)
{
Proveedor proveedor = new Proveedor();
Direccion direccion = new Direccion();
if (!FormHelper.noNullList(noNulos) || !FormHelper.esNumericoList(numericos))
return;
//List<TextBox> datos = FormHelper.getNoNulos(todos);
FormHelper.setearAtributos(todos, proveedor);
FormHelper.setearAtributos(todos, direccion);
proveedor.prov_activo = prov_activo.Checked;
proveedor.rubr_id = getRubroId(rubrosComboBox.Text);
Dictionary<String, Object> exac = new Dictionary<string, Object>() { { "prov_razon_social", proveedor.prov_razon_social } };
if (dataP.FilterSelect(new Dictionary<String, String>(), exac, out exError).Count() > 0)
{
MessageBox.Show("Erro al agregar proveedor, ya existe la razon social", "Proveedor", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
Dictionary<String, Object> exac2 = new Dictionary<string, Object>() { { "prov_CUIT", proveedor.prov_CUIT } };
if (dataP.FilterSelect(new Dictionary<String, String>(), exac2, out exError).Count() > 0)
{
MessageBox.Show("Erro al agregar proveedor, ya existe el CUIT", "Proveedor", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (noDB)
{
returnProveedor= proveedor;
returnDireccion = direccion;
this.DialogResult = DialogResult.OK;
this.Close();
return;
}
Int32 id = dataP.Create(proveedor, direccion, out exError);
if (exError == null)
{
MessageBox.Show("Proveedor " + proveedor.prov_razon_social + " agregado exitosamente.", "Proveedor nuevo", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
else
MessageBox.Show("Erro al agregar Proveedor, " + exError.Message, "Proveedor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private int getRubroId(string p)
{
foreach (KeyValuePair<int, string> entry in rubros)
{
if (entry.Value == rubrosComboBox.Text)
return entry.Key;
}
return 0;
}
private void button1_Click_1(object sender, EventArgs e)
{
NuevoRubro form = new NuevoRubro();
form.Parent = this.Parent;
var dialog = form.ShowDialog();
if (dialog == DialogResult.OK)
{
KeyValuePair<Int32, String> kv = dataP.CreateRubro(form.rubro, out exError);
if (exError != null)
{
MessageBox.Show("Error al agreagar el rubro.", "Proveedor nuevo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
rubros.Add(kv.Key, kv.Value);
rubrosComboBox.Items.Add(kv.Value);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using VesApp.Backend.Models;
using VesApp.Domain;
namespace VesApp.Backend.Controllers
{
[Authorize]
public class ReflexionsController : Controller
{
private DataContextLocal db = new DataContextLocal();
// GET: Reflexions
public async Task<ActionResult> Index()
{
return View(await db.Reflexions.OrderByDescending(reflexion => reflexion.Fecha).ToListAsync());
}
// GET: Reflexions/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reflexion reflexion = await db.Reflexions.FindAsync(id);
if (reflexion == null)
{
return HttpNotFound();
}
return View(reflexion);
}
// GET: Reflexions/Create
public ActionResult Create()
{
return View();
}
// POST: Reflexions/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "IdReflexion,Titulo,Text,UrlVideo,UrlImagen,Fecha,Sacerdote")] Reflexion reflexion)
{
if (ModelState.IsValid)
{
if (reflexion.UrlImagen==null)
{
string urlVideo = reflexion.UrlVideo;
var uri = new Uri(urlVideo);
var query = HttpUtility.ParseQueryString(uri.Query);
var videoId = string.Empty;
if (query.AllKeys.Contains("v"))
{
videoId = query["v"];
}
else
{
videoId = uri.Segments.Last();
}
String urlImagen = "https://img.youtube.com/vi/" + videoId + "/0.jpg";
reflexion.UrlImagen = urlImagen;
}
db.Reflexions.Add(reflexion);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(reflexion);
}
// GET: Reflexions/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reflexion reflexion = await db.Reflexions.FindAsync(id);
if (reflexion == null)
{
return HttpNotFound();
}
return View(reflexion);
}
// POST: Reflexions/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "IdReflexion,Titulo,Text,UrlVideo,UrlImagen,Fecha,Sacerdote")] Reflexion reflexion)
{
if (ModelState.IsValid)
{
if (reflexion.UrlImagen == null)
{
string urlVideo = reflexion.UrlVideo;
var uri = new Uri(urlVideo);
var query = HttpUtility.ParseQueryString(uri.Query);
var videoId = string.Empty;
if (query.AllKeys.Contains("v"))
{
videoId = query["v"];
}
else
{
videoId = uri.Segments.Last();
}
String urlImagen = "https://img.youtube.com/vi/" + videoId + "/0.jpg";
reflexion.UrlImagen = urlImagen;
}
db.Entry(reflexion).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(reflexion);
}
// GET: Reflexions/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reflexion reflexion = await db.Reflexions.FindAsync(id);
if (reflexion == null)
{
return HttpNotFound();
}
return View(reflexion);
}
// POST: Reflexions/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
Reflexion reflexion = await db.Reflexions.FindAsync(id);
db.Reflexions.Remove(reflexion);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
[CreateAssetMenu(fileName = "Base Spell", menuName = "Data/RPG/Base Spell")]
public class BaseSpell : Spell {
public TargetType targets;
public Warhead warhead;
public override IEnumerator ResolveRoutine(Intent intent, List<PrefixSpell> prefixes) {
List<Prefix> effects = new List<Prefix>();
foreach (PrefixSpell prefix in prefixes) {
effects.Add(prefix.effect);
}
yield return warhead.ResolveRoutine((IntentSpell)intent, effects);
}
public override bool LinksToNextSpell() {
return false;
}
public override void ModifyIntent(IntentSpell next) {
Debug.Assert(false);
}
public override IEnumerator AcquireTargetsRoutine(Result<List<BattleUnit>> result, Intent intent) {
BattleController controller = intent.battle.controller;
Result<BattleUnit> unitResult = new Result<BattleUnit>();
switch (targets) {
case TargetType.All:
yield return controller.allSelect.SelectAllRoutine(result, intent);
break;
case TargetType.AllAllies:
yield return controller.allySelect.SelectAllRoutine(result, intent);
break;
case TargetType.AllEnemies:
yield return controller.enemySelect.SelectAllRoutine(result, intent);
break;
case TargetType.AllNotSelf:
yield return controller.allSelect.SelectAllExceptRoutine(result, intent);
break;
case TargetType.Ally:
yield return controller.allySelect.SelectAnyOneRoutine(unitResult, intent);
CopyUnitResult(result, unitResult);
break;
case TargetType.AllyNotSelf:
yield return controller.allySelect.SelectAnyExceptRoutine(unitResult, intent);
CopyUnitResult(result, unitResult);
break;
case TargetType.Anyone:
yield return controller.allSelect.SelectAnyOneRoutine(unitResult, intent);
CopyUnitResult(result, unitResult);
break;
case TargetType.AnyoneNotSelf:
yield return controller.allSelect.SelectAnyExceptRoutine(unitResult, intent);
CopyUnitResult(result, unitResult);
break;
case TargetType.Enemy:
yield return controller.enemySelect.SelectAnyOneRoutine(unitResult, intent);
CopyUnitResult(result, unitResult);
break;
case TargetType.Self:
yield return controller.allySelect.SelectSpecificallyRoutine(unitResult, intent);
CopyUnitResult(result, unitResult);
break;
}
}
public override List<BattleUnit> AcquireAITargets(IntentSpell intent) {
switch (targets) {
case TargetType.All:
return intent.battle.AllUnits().ToList();
case TargetType.AllAllies:
return GetAllies(intent);
case TargetType.AllEnemies:
return GetEnemies(intent);
case TargetType.AllNotSelf:
return Without(intent.battle.AllUnits().ToList(), intent.actor);
case TargetType.Ally:
return RandomLiving(intent, GetAllies(intent));
case TargetType.AllyNotSelf:
return RandomLiving(intent, Without(GetAllies(intent), intent.actor));
case TargetType.Anyone:
case TargetType.Enemy:
case TargetType.AnyoneNotSelf:
return RandomLiving(intent, GetEnemies(intent));
case TargetType.Self:
return new List<BattleUnit> { intent.actor };
default:
return null;
}
}
}
|
using TAiMStore.Domain;
using TAiMStore.Model.Factory;
namespace TAiMStore.Model.Repository
{
public class RoleRepository : RepositoryBase<Role>, IRoleRepository
{
public RoleRepository(IFactory databaseFactory)
: base(databaseFactory)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebDriverFrameworkUnitTests.Capabilities
{
public enum DevicePlatform
{
Android,
IOS,
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RSS_news_feed_bot.data
{
public class AllUsers
{
private ObservableCollection<LoginUser> users { get; set; }
/// <summary>
/// Пусть сохранения.
/// </summary>
private string Path { get; set; }
/// <summary>
/// Сохранять изменения автоматически при изменении коллекции.
/// </summary>
public bool AutoSave { get; set; }
/// <summary>
/// Количество
/// </summary>
public int Count { get { return users.Count; } }
/// <summary>
/// AllUsers. Чтение json файла по пути Path. Если файл не найден, то создается новый.
/// </summary>
/// <param name="Path">Путь к файлу.</param>
/// <param name="AutoSave">Автоматическое сохранение. По умолчанию включено</param>
public AllUsers(string Path, bool AutoSave = true)
{
this.Path = Path;
this.AutoSave = AutoSave;
users = File.Exists(Path) ? JsonConvert.DeserializeObject<ObservableCollection<LoginUser>>(File.ReadAllText(Path)) : new ObservableCollection<LoginUser>();
}
private void Save()
{
if (AutoSave)
File.WriteAllText(@"data.json", JsonConvert.SerializeObject(users));
}
/// <summary>
/// Возвращает или задает элемент по указанному индексу.
/// </summary>
/// <param name="index">Отчитываемый от нуля индекс элемента, который требуется возратить или задать.</param>
/// <returns></returns>
public LoginUser this[int index]
{
get
{
return users[index];
}
}
public void Add(long UserId, string Username, string FirstName, string LastName)
{
users.Add(new LoginUser(UserId, Username, FirstName, LastName));
Save();
}
public LoginUser GetUserById(long UserId)
{
foreach (var user in users)
if (user.UserId == UserId)
return user;
throw new ArgumentException("GetUserById: Пользователь не найден.");
}
/// <summary>
/// Получение перечня ссылок пользователя по UserId.
/// </summary>
/// <param name="UserId">Id чата пользователя.</param>
/// <returns></returns>
public List<RssInfo> GetUserRss(long UserId)
{
return GetUserById(UserId).RssURL;
}
/// <summary>
/// Проверка наличия пользователя в базе.
/// </summary>
/// <param name="UserId">Id чата пользователя.</param>
/// <returns>true - пользователь найден; false - пользователь не найден.</returns>
public bool ContainsId(long UserId)
{
foreach (var user in users)
if (user.UserId == UserId)
return true;
return false;
}
/// <summary>
/// Добавление источника RSS к пользователю.
/// </summary>
/// <param name="UserId">Id чата пользователя.</param>
/// <param name="RssURL">URL RSS источника</param>
public void AddRssToUser(long UserId, string RssURL, string Title, string Description)
{
foreach (var user in users)
if (user.UserId == UserId)
{
foreach (var rss in user.RssURL)
if (rss.RssURL == RssURL)
throw new DuplicateWaitObjectException("AddRssToUser: " + RssURL + " уже присутствует в базе.");
user.RssURL.Add(new RssInfo(RssURL, Title, Description));
Save();
return;
}
throw new ArgumentException("AddRssToUser: пользователь не найден.");
}
public void DeleteUserRss(long UserId, string RssURL)
{
foreach (var user in users)
if (user.UserId == UserId)
{
for(int i = 0; i < user.RssURL.Count; i++)
{
if (user.RssURL[i].RssURL == RssURL)
{
user.RssURL.RemoveAt(i);
break;
}
}
Save();
return;
}
throw new ArgumentException("DeleteUserRss: пользователь не найден.");
}
public string GetLoginUserToString(long UserId)
{
foreach (var user in users)
if(user.UserId == UserId)
{
LoginUser userdata = user;
return userdata.UserId.ToString() + "/" + userdata.Username + "/" + userdata.FirstName + "/" + userdata.LastName;
}
throw new ArgumentException("GetLoginUserToString: пользователь не найден.");
}
}
public class LoginUser
{
public readonly long UserId;
public readonly string Username;
public readonly string FirstName;
public readonly string LastName;
public List<RssInfo> RssURL { get; set; }
public LoginUser(long UserId, string Username, string FirstName, string LastName)
{
this.UserId = UserId;
this.Username = Username;
this.FirstName = FirstName;
this.LastName = LastName;
RssURL = new List<RssInfo>();
}
}
public class RssInfo
{
public readonly string Title;
public readonly string RssURL;
public readonly string Description;
public RssInfo(string RssURL, string Title = null, string Description = null)
{
this.Title = Title;
this.RssURL = RssURL;
this.Description = Description;
}
}
}
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace RestService
{
public interface IRestService
{
/// <summary>
/// Adds CorrelationId. Throws <see cref="RestResponseException"/>
/// </summary>
Task<TResponse> DeleteAsync<TResponse>(Uri apiAction, RestActionOptions options = null);
/// <summary>
/// Adds CorrelationId. Throws <see cref="RestResponseException"/>
/// </summary>
Task<TResponse> GetAsync<TResponse>(Uri apiAction, RestActionOptions options = null);
/// <summary>
/// Adds CorrelationId. Throws <see cref="RestResponseException"/>
/// </summary>
Task<TResponse> PostAsync<TResponse, TRequest>(Uri apiAction, TRequest requestBody, RestActionOptions options = null);
/// <summary>
/// Adds CorrelationId. Throws <see cref="RestResponseException"/>
/// </summary>
Task<TResponse> PostAsync<TResponse>(Uri apiAction, object requestBody, RestActionOptions options = null);
/// <summary>
/// Adds CorrelationId. Throws <see cref="RestResponseException"/>
/// </summary>
Task<TResponse> PutAsync<TResponse, TRequest>(Uri apiAction, TRequest requestBody, RestActionOptions options = null);
/// <summary>
/// Adds CorrelationId. Throws <see cref="RestResponseException"/>
/// </summary>
Task<TResponse> PutAsync<TResponse>(Uri apiAction, object requestBody, RestActionOptions options = null);
/// <summary>
/// Only adds CorrelationId, No Exceptions are thrown
/// </summary>
Task<HttpResponseMessage> SendAsync(HttpRequestMessage httpRequest, RestActionOptions options = null);
}
}
|
using System;
using imod.vendingmachine.core.Contracts;
namespace imod.vendingmachine.infrastructure
{
/// <summary>
/// Implementation of a Vending Maching
/// </summary>
public class VendingMachine:IVendingMachine
{
}
}
|
using System;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Base;
namespace Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual
{
/// <summary>
/// Representa el objeto Logic de Contrato Estadio Consulta
/// </summary>
/// <remarks>
/// Creación : GMD 20150515 <br />
/// Modificación : <br />
/// </remarks>
public class ContratoEstadioConsultaLogic : Logic
{
/// <summary>
/// Codigo de Contrato Estadio Consulta
/// </summary>
public Guid? CodigoContratoEstadioConsulta { get; set; }
/// <summary>
/// Codigo Contrato de Estadio
/// </summary>
public Guid CodigoContratoEstadio { get; set; }
/// <summary>
/// Descripcion
/// </summary>
public string Descripcion { get; set; }
/// <summary>
/// Fecha de Registro
/// </summary>
public DateTime FechaRegistro { get; set; }
/// <summary>
/// Codigo de Parrafo
/// </summary>
public Guid? CodigoContratoParrafo { get; set; }
/// <summary>
/// Destinatario
/// </summary>
public Guid Destinatario { get; set; }
/// <summary>
/// Respuesta
/// </summary>
public string Respuesta { get; set; }
/// <summary>
/// Fecha de Respuesta
/// </summary>
public DateTime? FechaRespuesta { get; set; }
/// <summary>
/// Código de Consultante
/// </summary>
public string Consultor { get; set; }
public Guid? CodigoContrato { get; set; }
}
}
|
using System;
namespace Faker.ValueGenerator.PrimitiveTypes.IntegerTypes
{
public class ByteGenerator : IPrimitiveTypeGenerator
{
private static readonly Random Random = new Random();
public Type GenerateType { get; set; }
public object Generate()
{
GenerateType = typeof(byte);
return (byte) Random.Next();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using System.Diagnostics;
namespace AC.ExtendedRenderer.Toolkit.KryptonOutlookGrid
{
/// <summary>
/// Class for events of the column in the groupbox.
/// </summary>
public class OutlookGridColumnEventArgs : EventArgs
{
private OutlookGridColumn column;
/// <summary>
/// Constructor
/// </summary>
/// <param name="col">The OutlookGridColumn.</param>
public OutlookGridColumnEventArgs(OutlookGridColumn col)
{
this.column = col;
}
/// <summary>
/// Gets or sets the name of the column.
/// </summary>
public OutlookGridColumn Column
{
get
{
return this.column;
}
set
{
this.column = value;
}
}
}
}
|
using Datos;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Negocio
{
public class AccesoEstadisticas
{
public object get(string p, DateTime desde, DateTime hasta)
{
List<ItemEstadistico> lista = new List<ItemEstadistico>();
string[] parametros = { "fecha_desde", "fecha_hasta" };
object[] valores = { desde, hasta };
DataTable tabla = (new DatosSistema()).getDatosTabla(p, parametros, valores);
foreach (DataRow fila in tabla.Rows)
{
lista.Add(new ItemEstadistico(fila["nombre"].ToString(), Convert.ToInt32(fila["valor"].ToString())));
}
return lista;
}
public DataTable getTabla(int estadistica, DateTime desde, DateTime hasta)
{
string[] parametros = { "@desde", "@hasta" };
object[] valores = { desde, hasta };
string sp = string.Empty;
DatosSistema datos = new DatosSistema();
switch (estadistica)
{
case 1:
sp = "[INFONIONIOS].[spDestinosConMasPasajeros]";
break;
case 2:
sp = "[INFONIONIOS].[spDestinosConAeronavesMasVacias]";
break;
case 3:
sp = "[INFONIONIOS].[spClientesConMasPuntos]";
break;
case 4:
sp = "[INFONIONIOS].[spDestinosConMasPasajesCancelados]";
break;
case 5:
sp = "[INFONIONIOS].[spAeronavesMasFueraServicio]";
break;
default:
break;
}
return datos.getDatosTabla(sp, parametros, valores);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ParkingManage.Models;
namespace ParkingManage.Services
{
public class UserService
{
ParkContext db = new ParkContext();
public Models.Park[] Load()
{
var query = from u in db.Users
orderby u.Username
select u;
Park[] park = new Park[query.Count()];
int i = 0;
foreach (var item in query)
{
park[i] = new Park();
i++;
}
return park;
}
public void Save(Models.User user)
{
var query = new User { Username = user.Username,
Password = user.Password,
FullName = user.FullName,
Email = user.Email,
Phone = user.Phone,
UserLevel = uLevel.Member };
db.Users.Add(query);
db.SaveChanges();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Linq;
using DevExpress.XtraGrid.Views.Grid;
using IRAP.Global;
using IRAP.Client.Global;
using IRAP.Client.User;
using IRAP.Entities.FVS;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.GUI.FVS
{
public partial class frmWIPWaitingMonitor : IRAP.Client.Global.GUI.frmCustomKanbanBase
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
List<Dashboard_WIPWaiting> datas = new List<Dashboard_WIPWaiting>();
public frmWIPWaitingMonitor()
{
InitializeComponent();
}
/// <summary>
/// 获取在制品停滞跟踪数据列表
/// </summary>
/// <param name="t132ClickStream"></param>
private void GetDashboardWIPWaiting(string t132ClickStream)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
try
{
IRAPFVSClient.Instance.ufn_Dashboard_WIPWaiting(
IRAPUser.Instance.CommunityID,
t132ClickStream,
IRAPUser.Instance.SysLogID,
ref datas,
out errCode,
out errText);
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
AddLog(new AppOperationLog(DateTime.Now, -1, error.Message));
SetConnectionStatus(false);
return;
}
WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName);
if (errCode == 0)
{
datas = (from row in datas
where row.DLVProgress >= 0
select row).ToList<Dashboard_WIPWaiting>();
grdMODelivery.DataSource = datas;
grdvMODelivery.BestFitColumns();
grdvMODelivery.OptionsView.RowAutoHeight = true;
SetConnectionStatus(true);
}
else
{
AddLog(new AppOperationLog(DateTime.Now, -1, errText));
SetConnectionStatus(false);
grdMODelivery.DataSource = null;
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
private void SetWOStatusPanelColor()
{
lblStatusNormal.BackColor = ColorTranslator.FromHtml("#00FF00");
lblStatusSlower.BackColor = ColorTranslator.FromHtml("#FBF179");
lblStatusSlowest.BackColor = ColorTranslator.FromHtml("#FF0000");
//grdclmnOrdinal.Caption = "序号\nItem";
//grdclmnPWONo.Caption = "生产工单号\nPWO No";
//grdclmnMONumber.Caption = "订单号\nMO No";
//grdclmnMOLineNo.Caption = "行号\nLine No";
//grdclmProductNo.Caption = "产品编号\nProduct No";
//grdclmProductName.Caption = "产品名称\nProdut Name";
//grdclmMinutesWaited.Caption = "等待时间\nWait for Time";
//grdclmT216Name.Caption = "滞在工序\n";
//grdclmDLVProgress.Caption = "等待状态\nWaitting Status";
//grdclmContainerNo.Caption = "容器编号\nContainer No";
//grdclmWIPQty.Caption = "在制品数量\nWIP Quantity";
//grdclmT216Name.Caption = "滞在工序\nWaitting for Operation";
grdclmnOrdinal.Caption = "序号";
grdclmnPWONo.Caption = "生产工单号";
grdclmnMONumber.Caption = "订单号";
grdclmnMOLineNo.Caption = "行号";
grdclmProductNo.Caption = "产品编号";
grdclmProductName.Caption = "产品名称";
grdclmMinutesWaited.Caption = "等待时间";
grdclmT216Name.Caption = "滞在工序";
grdclmDLVProgress.Caption = "等待状态";
grdclmContainerNo.Caption = "容器编号";
grdclmWIPQty.Caption = "在制品数量";
grdclmT216Name.Caption = "滞在工序";
}
private void frmWIPWaitingMonitor_Load(object sender, EventArgs e)
{
SetWOStatusPanelColor();
}
private void frmWIPWaitingMonitor_Resize(object sender, EventArgs e)
{
pnlRemark.Left = (this.Width - pnlRemark.Width) / 2;
}
private void frmWIPWaitingMonitor_Activated(object sender, EventArgs e)
{
GetDashboardWIPWaiting(t132ClickStream);
if (grdMODelivery.DataSource != null)
{
this.grdvMODelivery.MoveFirst();
if (autoSwtich)
{
if (this.datas.Count > 0)
{
timer.Interval = this.nextFunction.WaitForSeconds * 1000;
}
else
{
timer.Interval = 10000;
}
}
else
{
timer.Interval = 60000;
}
timer.Enabled = false;
if (grdvMODelivery.RowCount - 1 > 0 &&
grdvMODelivery.IsRowVisible(grdvMODelivery.RowCount - 1) != RowVisibleState.Visible)
{
tmrPage.Interval = 5000;
tmrPage.Enabled = true;
}
else
{
timer.Enabled = true;
}
}
else
{
timer.Interval = 10000;
timer.Enabled = true;
}
}
private void grdvMODelivery_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
{
if (e.Column != grdclmDLVProgress)
return;
int colIndex = 0;
int.TryParse(e.Value.ToString(), out colIndex);
switch (colIndex)
{
case -1:
e.DisplayText = "计划";
break;
case 0:
e.DisplayText = "正常";
break;
case 1:
e.DisplayText = "偏快";
break;
case 2:
e.DisplayText = "过快";
break;
case 3:
e.DisplayText = "偏长";
break;
case 4:
e.DisplayText = "过长";
break;
}
}
private void grdvMODelivery_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
int rowIndex = e.RowHandle;
string colHtml = datas[rowIndex].BackgroundColor;
colHtml = colHtml.Contains("#") ? colHtml : "#" + colHtml;
e.Appearance.BackColor = ColorTranslator.FromHtml(colHtml);
if (e.Column != grdclmDLVProgress)
return;
int colIndex = 0;
int.TryParse(e.CellValue.ToString(), out colIndex);
string col = "";
switch (colIndex)
{
case -1:
col = "#4567AA";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
break;
case 0:
col = "#00FF00";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
e.Appearance.ForeColor = Color.Black;
break;
case 1:
col = "#24F0E1";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
break;
case 2:
col = "#3867F3";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
e.Appearance.ForeColor = Color.White;
break;
case 3:
col = "#FBF179";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
break;
case 4:
col = "#FF0000";
e.Appearance.BackColor = ColorTranslator.FromHtml(col);
e.Appearance.ForeColor = Color.Black;
break;
}
}
private void frmWIPWaitingMonitor_Shown(object sender, EventArgs e)
{
if (this.lblFuncName.Text.Contains("-"))
{
string lblName = this.lblFuncName.Text;
this.lblFuncName.Text = lblName.Split('-')[1].ToString();
}
pnlRemark.Left = (this.Width - pnlRemark.Width) / 2;
}
private void timer_Tick(object sender, EventArgs e)
{
timer.Enabled = false;
if (autoSwtich)
{
JumpToNextFunction();
tmrPage.Enabled = false;
return;
}
else
{
GetDashboardWIPWaiting(t132ClickStream);
timer.Enabled = true;
}
}
private void tmrPage_Tick(object sender, EventArgs e)
{
if (datas != null)
{
if (datas.Count > 0)
{
if (grdvMODelivery.RowCount - 1 > 0)
{
if (grdvMODelivery.IsRowVisible(grdvMODelivery.RowCount - 1) == RowVisibleState.Visible) //如果滚到了底端
{
timer.Enabled = true;
this.grdvMODelivery.MoveFirst();
}
}
this.grdvMODelivery.MoveNextPage();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace web_ioc.Models
{
public class GribService : IGribService
{
private IGribSession _session;
public GribService(IGribSession session)
{
_session = session;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AdventureGame : MonoBehaviour {
[SerializeField] Text textComponent;
[SerializeField] State startingState;
State state;
// Use this for initialization
void Start()
{
state = startingState;
textComponent.text = state.GetStateStory();
}
// Update is called once per frame
void Update()
{
ManageState();
if(Input.GetKeyDown(KeyCode.Q))
{
QuitGame();
}
}
/// <summary>
/// Controlla i vari stati di tutto il gioco.
/// </summary>
private void ManageState()
{
var nextStates = state.GetNextStates();
for (int i = 0; i < nextStates.Length; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + i))
{
state = nextStates[i];
}
}
textComponent.text = state.GetStateStory();
}
/// <summary>
/// Metodo che controlla se sono nell'editor o nel vero gioco e poi spegne il gioco.
/// </summary>
private void QuitGame()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
|
namespace DemoScanner.DemoStuff.L4D2Branch.PortalStuff.Result
{
public struct Point3D
{
public float X;
public float Y;
public float Z;
public Point3D(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public override bool Equals(object obj)
{
return obj is Point3D d &&
X == d.X &&
Y == d.Y &&
Z == d.Z;
}
public override int GetHashCode()
{
int hashCode = -307843816;
hashCode = hashCode * -1521134295 + X.GetHashCode();
hashCode = hashCode * -1521134295 + Y.GetHashCode();
hashCode = hashCode * -1521134295 + Z.GetHashCode();
return hashCode;
}
public static bool operator ==(Point3D per1, Point3D per2)
{
return !(per1 != per2);
}
public static bool operator !=(Point3D per1, Point3D per2)
{
return per1.X != per2.X || per1.Y != per2.Y || per1.Z != per2.Z;
}
}
public struct DPoint3D
{
public double X;
public double Y;
public double Z;
public DPoint3D(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public override bool Equals(object obj)
{
return obj is DPoint3D d &&
X == d.X &&
Y == d.Y &&
Z == d.Z;
}
public override int GetHashCode()
{
int hashCode = -307843816;
hashCode = hashCode * -1521134295 + X.GetHashCode();
hashCode = hashCode * -1521134295 + Y.GetHashCode();
hashCode = hashCode * -1521134295 + Z.GetHashCode();
return hashCode;
}
public static bool operator ==(DPoint3D per1, DPoint3D per2)
{
return !(per1 != per2);
}
public static bool operator !=(DPoint3D per1, DPoint3D per2)
{
return per1.X != per2.X || per1.Y != per2.Y || per1.Z != per2.Z;
}
}
} |
namespace WinterGrass
{
public class ModConfig
{
public bool DisableWinterGrassGrowth { get; set; } = true;
}
}
|
using BDTest.NetCore.Razor.ReportMiddleware.Models;
namespace BDTest.NetCore.Razor.ReportMiddleware.Extensions;
public static class PagerExtensions
{
public static int? GetPageNumberWhere<T>(this Pager<T> pager, Func<T, bool> predicate)
{
var item = pager.AllItems.FirstOrDefault(predicate);
return item == null ? null : GetPageNumberOfItem(pager, item);
}
public static int? GetPageNumberOfItem<T>(this Pager<T> pager, T item)
{
var items = pager.AllItems;
var indexOfItem = Array.IndexOf(items, item);
for (var i = 1; i <= pager.TotalPages; i++)
{
var itemsIteratedThrough = i * pager.PageSize;
if (indexOfItem <= itemsIteratedThrough)
{
return i;
}
}
return null;
}
} |
using System.Collections.Generic;
namespace ExampleRepo.Models
{
public class BankEntity
{
public BankEntity()
{
Customers = new List<CustomerEntity>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Town { get; set; }
public IList<CustomerEntity> Customers { get; set; }
}
}
|
using EduHome.DataContext;
using EduHome.Models.Entity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EduHome.ViewComponents
{
public class AboutViewComponent : ViewComponent
{
private readonly EduhomeDbContext _db;
public AboutViewComponent(EduhomeDbContext db)
{
_db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
About about = _db.About.FirstOrDefault();
return View(await Task.FromResult(about));
}
}
}
|
namespace chat.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class DataContext:DbContext
{
public DataContext()
: base("name=DataContext")
{
}
public virtual DbSet<User_Account> Accounts { get; set; }
public virtual DbSet<Conversation> Conversations { get; set; }
public virtual DbSet<Friend> Friends { get; set; }
public virtual DbSet<User_Gender> Genders { get; set; }
public virtual DbSet<User_Picture> Pictures { get; set; }
public virtual DbSet<User_Profile> Profiles { get; set; }
public virtual DbSet<User_Picture_Like> Loves { get; set; }
public virtual DbSet<Contact_Skype> Skypes { get; set; }
public virtual DbSet<Contact_Phone> Phones { get; set; }
public virtual DbSet<Contact_Email> Emails { get; set; }
public virtual DbSet<Contact_Other> Contacts { get; set; }
public virtual DbSet<User_Relationship> Relations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User_Account>()
.HasOptional(e => e.Profile)
.WithRequired(e => e.Account);
modelBuilder.Entity<User_Gender>()
.HasMany(e => e.Profiles)
.WithRequired(e => e.Gender)
.HasForeignKey(e => e.Gender_Id);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Pictures)
.WithRequired(e => e.Profile)
.HasForeignKey(e => e.Profile_Id);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Conversations)
.WithRequired(e => e.Profile)
.HasForeignKey(e => e.Profile2_Fk);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Friends)
.WithRequired(e => e.Profile)
.HasForeignKey(e => e.Profile2_Fk);
modelBuilder.Entity<User_Picture>()
.HasMany(e => e.Loves)
.WithRequired(e => e.Picture)
.HasForeignKey(e => e.Picture_Id).WillCascadeOnDelete(true);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Loves)
.WithRequired(e => e.Profile)
.HasForeignKey(e => e.Profile_Id).WillCascadeOnDelete(false);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Contacts)
.WithRequired(e => e.User_Profile)
.HasForeignKey(e => e.User_Profile_Id);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Emails)
.WithRequired(e => e.User_Profile)
.HasForeignKey(e => e.User_Profile_Id);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Phones)
.WithRequired(e => e.User_Profile)
.HasForeignKey(e => e.User_Profile_Id);
modelBuilder.Entity<User_Profile>()
.HasMany(e => e.Skypes)
.WithRequired(e => e.User_Profile)
.HasForeignKey(e => e.User_Profile_Id);
modelBuilder.Entity<User_Relationship>()
.HasMany(e => e.User_Profiles)
.WithRequired(e => e.Relationship)
.HasForeignKey(e => e.Relationship_Id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UBaseline.Shared.Node;
using UBaseline.Shared.PageSettings;
using UBaseline.Shared.Property;
using Uintra.Core.Controls.LightboxGallery;
using Uintra.Features.Groups;
using Uintra.Features.Groups.Models;
using Uintra.Core.UbaselineModels.RestrictedNode;
using Uintra.Features.Links.Models;
using Uintra.Features.Tagging.UserTags.Models;
namespace Uintra.Features.Social.Models
{
public class SocialEditPageViewModel : UintraRestrictedNodeViewModel, IGroupHeader
{
public Guid OwnerId { get; set; }
public PropertyViewModel<INodeViewModel[]> Panels { get; set; }
public PageSettingsCompositionViewModel PageSettings { get; set; }
public string Description { get; set; }
public IEnumerable<UserTag> Tags { get; set; } = Enumerable.Empty<UserTag>();
public LightboxPreviewModel LightboxPreviewModel { get; set; }
public IEnumerable<UserTag> AvailableTags { get; set; } = Enumerable.Empty<UserTag>();
public Guid Id { get; set; }
public string AllowedMediaExtensions { get; set; }
public bool CanDelete { get; set; }
public IActivityLinks Links { get; set; }
public GroupHeaderViewModel GroupHeader { get; set; }
}
} |
using System;
using System.Linq;
using System.Threading.Tasks;
using EventLite.Streams;
using EventLite.Streams.StreamManager;
namespace EventLite
{
public abstract class AggregateBase<T> : IAggregateBase
{
private IStreamManager _streamManager;
private IAggregateSettings _aggregateSettings;
private EventStream _stream;
private Guid _streamId;
public abstract T AggregateDataStructure { get; set; }
protected virtual int CommitsBeforeSnapshot => 0;
public async Task FollowStream(Guid streamId, IStreamManager streamManager, IAggregateSettings aggregateSettings)
{
_streamId = streamId;
_streamManager = streamManager;
_aggregateSettings = aggregateSettings;
var commitMinimumRevision = 0;
_stream = await _streamManager.GetStream(_streamId).ConfigureAwait(false);
if (_stream.SnapshotRevision > 0)
{
var snapshot = await _streamManager.GetSnapshot(_stream.StreamId, _stream.SnapshotRevision);
AggregateDataStructure = (T)snapshot.SnapshotData;
commitMinimumRevision = snapshot.SnapshotHeadCommit + 1;
}
var commits = await _streamManager.GetCommits(_streamId, commitMinimumRevision).ConfigureAwait(false);
var events = commits
.OrderBy(x => x.CommitNumber)
.Select(x => x.Event);
foreach (var @event in events)
{
ApplyEvent(@event);
}
}
public async Task Save(object @event)
{
ApplyEvent(@event);
_stream.HeadRevision += 1;
var commit = new Commit(_streamId, @event, _stream.HeadRevision);
await _streamManager.AddCommit(commit);
_stream.UnsnapshottedCommits += 1;
if (_stream.UnsnapshottedCommits == CommitsBeforeSnapshot)
{
_stream.SnapshotRevision += 1;
var snapshot = new Snapshot(_streamId, _stream.SnapshotRevision, _stream.HeadRevision, AggregateDataStructure);
await _streamManager.AddSnapshot(snapshot);
_stream.UnsnapshottedCommits = 0;
}
await _streamManager.UpsertStream(_stream);
}
private void ApplyEvent(object @event)
{
var handler = this.GetType().FindInterfaces(HandlerInterfaceFilter, ((IRaisedEvent)@event).EventType)[0];
var handlerMethod = handler.GetMethod("Apply");
handlerMethod.Invoke(this, new object[] { @event });
}
private static bool HandlerInterfaceFilter(Type typeObj, Object criteriaObj)
{
return typeObj.GetGenericArguments().Length > 0
&& typeObj.GetGenericArguments()[0].Name == criteriaObj.ToString();
}
}
} |
using Crystal.Plot2D.Common;
using System;
using System.ComponentModel;
using System.Windows;
namespace Crystal.Plot2D.Charts
{
/// <summary>
/// Contains data for custom generation of tick's label.
/// </summary>
/// <typeparam name="T">Type of ticks</typeparam>
public sealed class LabelTickInfo<T>
{
internal LabelTickInfo() { }
/// <summary>
/// Gets or sets the tick.
/// </summary>
/// <value>The tick.</value>
public T Tick { get; internal set; }
/// <summary>
/// Gets or sets additional info about ticks range.
/// </summary>
/// <value>The info.</value>
public object Info { get; internal set; }
/// <summary>
/// Gets or sets the index of tick in ticks array.
/// </summary>
/// <value>The index.</value>
public int Index { get; internal set; }
}
/// <summary>
/// Base class for all label providers.
/// Contains a number of properties that can be used to adjust generated labels.
/// </summary>
/// <typeparam name="T">Type of ticks, which labels are generated for</typeparam>
/// <remarks>
/// Order of apllication of custom label string properties:
/// If CustomFormatter is not null, it is called first.
/// Then, if it was null or if it returned null string,
/// virtual GetStringCore method is called. It can be overloaded in subclasses. GetStringCore should not return null.
/// Then if LabelStringFormat is not null, it is applied.
/// After label's UI was created, you can change it by setting CustomView delegate - it allows you to adjust
/// UI properties of label. Note: not all labelProviders takes CustomView into account.
/// </remarks>
public abstract class LabelProviderBase<T>
{
#region Private
private string labelStringFormat = null;
private Func<LabelTickInfo<T>, string> customFormatter = null;
private Action<LabelTickInfo<T>, UIElement> customView = null;
#endregion
private static readonly UIElement[] emptyLabelsArray = new UIElement[0];
protected static UIElement[] EmptyLabelsArray
{
get { return emptyLabelsArray; }
}
/// <summary>
/// Creates labels by given ticks info.
/// Is not intended to be called from your code.
/// </summary>
/// <param name="ticksInfo">The ticks info.</param>
/// <returns>Array of <see cref="UIElement"/>s, which are axis labels for specified axis ticks.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract UIElement[] CreateLabels(ITicksInfo<T> ticksInfo);
/// <summary>
/// Gets or sets the label string format.
/// </summary>
/// <value>The label string format.</value>
public string LabelStringFormat
{
get { return labelStringFormat; }
set
{
if (labelStringFormat != value)
{
labelStringFormat = value;
RaiseChanged();
}
}
}
/// <summary>
/// Gets or sets the custom formatter - delegate that can be called to create custom string representation of tick.
/// </summary>
/// <value>The custom formatter.</value>
public Func<LabelTickInfo<T>, string> CustomFormatter
{
get { return customFormatter; }
set
{
if (customFormatter != value)
{
customFormatter = value;
RaiseChanged();
}
}
}
/// <summary>
/// Gets or sets the custom view - delegate that is used to create a custom, non-default look of axis label.
/// Can be used to adjust some UI properties of generated label.
/// </summary>
/// <value>The custom view.</value>
public Action<LabelTickInfo<T>, UIElement> CustomView
{
get { return customView; }
set
{
if (customView != value)
{
customView = value;
RaiseChanged();
}
}
}
/// <summary>
/// Sets the custom formatter.
/// This is alternative to CustomFormatter property setter, the only difference is that Visual Studio shows
/// more convenient tooltip for methods rather than for properties' setters.
/// </summary>
/// <param name="formatter">The formatter.</param>
public void SetCustomFormatter(Func<LabelTickInfo<T>, string> formatter)
{
CustomFormatter = formatter;
}
/// <summary>
/// Sets the custom view.
/// This is alternative to CustomView property setter, the only difference is that Visual Studio shows
/// more convenient tooltip for methods rather than for properties' setters.
/// </summary>
/// <param name="view">The view.</param>
public void SetCustomView(Action<LabelTickInfo<T>, UIElement> view)
{
CustomView = view;
}
protected virtual string GetString(LabelTickInfo<T> tickInfo)
{
string text = null;
if (CustomFormatter != null)
{
text = CustomFormatter(tickInfo);
}
if (text == null)
{
text = GetStringCore(tickInfo);
if (text == null)
{
throw new ArgumentNullException(Strings.Exceptions.TextOfTickShouldNotBeNull);
}
}
if (LabelStringFormat != null)
{
text = string.Format(LabelStringFormat, text);
}
return text;
}
protected virtual string GetStringCore(LabelTickInfo<T> tickInfo)
{
return tickInfo.Tick.ToString();
}
protected void ApplyCustomView(LabelTickInfo<T> info, UIElement label)
{
if (CustomView != null)
{
CustomView(info, label);
}
}
/// <summary>
/// Occurs when label provider is changed.
/// Notifies axis to update its view.
/// </summary>
public event EventHandler Changed;
protected void RaiseChanged()
{
Changed.Raise(this);
}
private readonly ResourcePool<UIElement> pool = new();
internal void ReleaseLabel(UIElement label)
{
if (ReleaseCore(label))
{
pool.Put(label);
}
}
protected virtual bool ReleaseCore(UIElement label) { return false; }
protected UIElement GetResourceFromPool()
{
return pool.Get();
}
}
}
|
using System.Threading.Tasks;
using WebApplication2.Models;
namespace WebApplication2.Services
{
public interface ITestService
{
void Test1(Test model);
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Collections.ObjectModel;
using Microsoft.Toolkit.Uwp.UI.Controls;
using VéloMax.bdd;
using VéloMax.pages;
namespace VéloMax.pages
{
public sealed partial class AjouterFideliteUI : Page
{
public AjouterFideliteUI()
{
this.InitializeComponent();
}
public void AjoutProgramme(object sender, RoutedEventArgs e)
{
try
{
new Programme(nomProg.Text, int.Parse(cout.Text), int.Parse(rabais.Text), int.Parse(duree.Text));
((this.Frame.Parent as NavigationView).Content as Frame).Navigate(typeof(FideliteUI));
}
catch { }
}
}
}
|
using System.ComponentModel.DataAnnotations;
// New namespace imports:
using Microsoft.AspNet.Identity.EntityFramework;
using System.Collections.Generic;
using Model.Models;
using System;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations.Schema;
using Model.ViewModel;
namespace Model.ViewModels
{
public class DocumentCancelViewModel : EntityBase
{
public DocumentCancelViewModel()
{
}
public int HeaderId { get; set; }
public DateTime DocDate { get; set; }
public int ReasonId { get; set; }
public string ReasonName { get; set; }
public string Remark { get; set; }
}
}
|
namespace SpaceHosting.Index.Benchmarks
{
public enum VectorsFileFormat
{
DenseVectorArrayJson,
SparseVectorArrayJson,
PandasDataFrameCsv,
PandasDataFrameJson,
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BAH.BOS.Pattern;
namespace BAH.BOS.Core.Const.BillStatus
{
/// <summary>
/// 常用的逻辑状态。
/// </summary>
public class LogicStatus : Singleton<LogicStatus>
{
/// <summary>
/// 否状态。
/// </summary>
/// <returns>返回状态值。</returns>
public string No()
{
return "A";
}
/// <summary>
/// 是状态。
/// </summary>
/// <returns>返回状态值。</returns>
public string Yes()
{
return "B";
}
}//end class
}//end namespace
|
using Pe.Stracon.SGC.Cross.Core.Base;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.CommandContract.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.SGC.Infraestructura.Repository.Base;
using System;
using System.Data;
using System.Data.SqlClient;
namespace Pe.Stracon.SGC.Infraestructura.Repository.Command.Contractual
{
/// <summary>
/// Implementación del Repositorio de Contrato
/// </summary>
/// <remarks>
/// Creación :GMD 20150710 <br />
/// Modificación :<br />
/// </remarks>
public class BienAlquilerEntityRepository : ComandRepository<BienAlquilerEntity>, IBienAlquilerEntityRepository
{
}
}
|
using CaveGeneration.Content_Generation.Parameter_Settings;
using CaveGeneration.Models;
using Microsoft.Xna.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaveGeneration.Content_Generation.Pitfall_Placement
{
class PitfallSpawner
{
private Cell[,] Map;
private Grid grid;
private Settings settings;
private int collumns;
private int rows;
private int NumberOfPitfalls;
private int PitfallWidth;
private int PitfallMaxHeight;
public PitfallSpawner(Settings settings)
{
grid = Grid.Instance();
this.Map = grid.Cells;
this.settings = settings;
collumns = Map.GetLength(0);
rows = Map.GetLength(1);
this.NumberOfPitfalls = settings.NumberOfPitfalls;
this.PitfallMaxHeight = settings.PitfallMaxHeight;
this.PitfallWidth = settings.PitfallWidth;
}
public void GeneratePitfalls()
{
var PositionList = FindPitfallPositions();
Random rand = new Random(settings.Seed.GetHashCode());
for(int i = 0; i < NumberOfPitfalls; i++)
{
int pos = rand.Next(PositionList.Count);
var PitfallPosition = PositionList.ElementAt(pos);
PlacePitfall((int)PitfallPosition.X, (int)PitfallPosition.Y);
PositionList.Remove(PitfallPosition);
}
}
#region Private Functions
private LinkedList<Vector2> FindPitfallPositions()
{
LinkedList<Vector2> positionList = new LinkedList<Vector2>();
for (int y = rows - 1; y >= rows - PitfallMaxHeight; y--)
{
for (int x = 5; x < collumns; x++)
{
if (ValidPosition(x, y))
{
positionList.AddLast(new Vector2(x, y));
}
}
}
return positionList;
}
private bool ValidPosition(int xPosition, int yPosition)
{
for(int x = xPosition; x < xPosition+PitfallWidth; x++)
{
if (Map[x, yPosition].IsVisible == true)
{
return false;
}
}
return true;
}
private void PlacePitfall(int xPosition, int yPosition)
{
for (int x = xPosition; x < xPosition + PitfallWidth; x++)
{
for(int y = yPosition; y < rows; y++)
{
Map[x, y].IsVisible = false;
}
}
}
#endregion
}
}
|
using Euler_Logic.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem643 : ProblemBase {
public override string ProblemName {
get { return "643: 2-Friendly"; }
}
public override string GetAnswer() {
BuildTwos();
return BruteForce(100).ToString();
return "";
}
private HashSet<ulong> _twos = new HashSet<ulong>();
private void BuildTwos() {
ulong num = 2;
for (ulong power = 1; power <= 63; power++) {
_twos.Add(num);
num *= 2;
}
}
private ulong BruteForce(ulong n) {
ulong count = 0;
for (ulong p = 1; p <= n; p++) {
for (ulong q = p + 1; q <= n; q++) {
var gcd = GCD.GetGCD(p, q);
if (_twos.Contains(gcd)) {
count++;
}
}
}
return count;
}
}
}
|
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace XamLottie.ViewModels
{
public class BaseViewModel : INotifyPropertyChanged
{
private string _title;
public string Title
{
get => _title;
set
{
_title = value;
RaisePropertyChanged();
}
}
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Windows;
namespace R6SAdapter
{
class R6SteamLibraryBuilder
{
public R6SteamLibraryBuilder(string R6SPath)
{
SteamLibraryPath = R6SPath.Replace(@"\common\Tom Clancy's Rainbow Six Siege", string.Empty);
}
const string SteamAcfUrl = "https://coldthunder11.com/R6SAdapter/SteamFiles/appmanifest_359550.acf";
const string SteamWorkShopUrl = "https://coldthunder11.com/R6SAdapter/SteamFiles/appworkshop_359550.acf";
readonly string SteamLibraryPath;
/// <returns>true->Exsist</returns>
public bool CheckSteamLibraryExsist()
{
return File.Exists(Path.Combine(SteamLibraryPath, "appmanifest_359550.acf"));
}
public bool RebuildSteamLibrary()
{
try
{
CreateSteamAcfFile();
CreateWorkShopFile();
return true;
}
catch(Exception e)
{
MessageBox.Show(e.Source + e.Message);
return false;
}
}
private void CreateSteamAcfFile()
{
HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri(SteamAcfUrl)
};
var requestTask = httpClient.GetStringAsync(new Uri(SteamAcfUrl));
string steamAcfStr = requestTask.Result;
File.WriteAllText(Path.Combine(SteamLibraryPath, "appmanifest_359550.acf"), steamAcfStr);
}
private void CreateWorkShopFile()
{
string workShopDir = Path.Combine(SteamLibraryPath, "workshop");
HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri(SteamWorkShopUrl)
};
var requestTask = httpClient.GetStringAsync(new Uri(SteamWorkShopUrl));
string workshopStr = requestTask.Result;
File.WriteAllText(Path.Combine(workShopDir, "appworkshop_359550.acf"),workshopStr);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Character : MonoBehaviour {
public enum DamageType { Normal, Critical, Evade }
public string characterName;
[SerializeField]
internal Statistics stats;
[SerializeField]
internal Deck deck;
internal Dictionary<EffectType, EffectValue> effects = new Dictionary<EffectType, EffectValue>();
public GameObject dmgText;
internal bool defense;
internal float dmgBlock;
public float CurrentHP { get; protected set; }
public virtual void Die()
{
//DO NOT FILL THIS!
}
internal void ApplyAffliction(EffectType type, EffectValue value)
{
if (effects.ContainsKey(type))
{
effects[type].amount += value.amount;
effects[type].duration = Mathf.Max(value.duration);
}
else effects.Add(type, value);
}
public void CheckAffliction()
{
if (effects.ContainsKey(EffectType.Burn))
{
var effect = effects[EffectType.Burn];
ChangeHP(effect.amount);
if (effect.duration > 1)
{
if (stats.bonuses.Find(x => x.type == StatBonus.StatBonusType.Burn) == null)
stats.bonuses.Add(
new StatBonus(StatBonus.StatBonusType.Burn, new float[] { 0, 0, 0, 0, 0, -stats.Defense / 2, 0, 0, 0, 0, 0 }));
effect.TurnPass();
}
else
{
stats.bonuses.RemoveAll(x => x.type == StatBonus.StatBonusType.Burn);
effects.Remove(EffectType.Burn);
}
}
if (effects.ContainsKey(EffectType.Poison))
{
var effect = effects[EffectType.Poison];
ChangeHP(effect.amount);
if (effect.duration > 1)
{
if (stats.bonuses.Find(x => x.type == StatBonus.StatBonusType.Poison) == null)
stats.bonuses.Add(
new StatBonus(StatBonus.StatBonusType.Burn, new float[] { 0, 0, 0, 0, -stats.Attack / 2, 0, 0, 0, 0, 0, 0 }));
effect.TurnPass();
}
else
{
stats.bonuses.RemoveAll(x => x.type == StatBonus.StatBonusType.Poison);
effects.Remove(EffectType.Poison);
}
}
if (effects.ContainsKey(EffectType.Curse))
{
var effect = effects[EffectType.Curse];
ChangeHP(effect.amount);
if (effect.duration > 1) effect.TurnPass();
else effects.Remove(EffectType.Curse);
}
}
internal void ApplyEncounterEffect(BoostMode effect, float amount)
{
if (effect != BoostMode.None)
{
float[] ent = new float[11];
if (effect == BoostMode.AttackBoost) ent[4] += amount;
if (effect == BoostMode.DefenseBoost) ent[5] += amount;
if (effect == BoostMode.CritChanceBoost) ent[8] += amount;
if (effect == BoostMode.AddNumber) deck.numbers.Add(Mathf.RoundToInt(amount));
stats.bonuses.Add(new StatBonus(ent));
}
}
internal void ResetEffect()
{
stats.bonuses.RemoveAt(stats.bonuses.Count - 1);
}
public virtual bool Damage(float amount)
{
DamageType t = DamageType.Normal;
if (stats.Evasion >= 100) t = DamageType.Evade;
else if (MathRand.WeightedPick(new float[] { stats.CritChance, 100 - stats.CritChance }) == 0) t = DamageType.Evade;
else
{
amount -= stats.Defense;
if (stats.CritChance >= 100)
{
amount *= stats.CritDamage / 100;
t = DamageType.Critical;
}
else if (MathRand.WeightedPick(new float[] { stats.CritChance, 100 - stats.CritChance }) == 0)
{
amount *= stats.CritDamage / 100;
t = DamageType.Critical;
}
amount -= dmgBlock;
dmgBlock = 0;
}
return ChangeHP(-amount, t);
}
/// <summary>
/// Add or remove HP from the current HP pool. Cannot exceed Maximum HP
/// </summary>
/// <param name="amount">The amount of HP to add. Negative number to remove</param>
public bool ChangeHP(float amount, DamageType type = DamageType.Normal)
{
amount = Mathf.Ceil(amount);
if (defense)
{
amount /= 2;
defense = false;
}
if (type == DamageType.Evade)
{
DamageText dmg = Instantiate(dmgText, new Vector3(transform.position.x, transform.position.y, -1), Quaternion.identity).GetComponent<DamageText>();
dmg.Flag = DamageText.DamageFlag.Evade;
defense = false;
return false;
}
if (amount != 0)
{
DamageText dmg = Instantiate(dmgText, new Vector3(transform.position.x, transform.position.y, -1), Quaternion.identity).GetComponent<DamageText>();
if (amount > 0) dmg.Flag = DamageText.DamageFlag.Heal;
else if (type == DamageType.Critical) dmg.Flag = DamageText.DamageFlag.Critical;
else dmg.Flag = DamageText.DamageFlag.Damage;
dmg.Damage = amount;
CurrentHP = Mathf.Clamp(CurrentHP + amount, 0, stats.MaxHP);
}
if (CurrentHP == 0) {
//Die();
return false;
}
return true;
}
// Use this for initialization
protected virtual void Start () {
//ALWAYS CALL base.Start() ON OVERRIDE!
deck.hand = new List<Card>();
deck.numbers = new List<int>();
CurrentHP = stats.MaxHP;
}
// Update is called once per frame
protected virtual void Update () {
}
}
public enum EffectType
{
Poison, Burn, Curse
}
public class EffectValue
{
public int amount, duration = 3;
public void TurnPass() { duration--; }
}
|
namespace Tests.Data.Oberon
{
//[TestClass]
public class OberonTestUser
{
public string Id;
public string UserName;
public string Domain;
public string Password;
public string EmailAddress;
public string DisplayName;
public OberonTestUser GetAccountTwoUser()
{
var user = new OberonTestUser();
user.Domain = "NGPVAN";
user.UserName = "oberonemail2";
user.Password = "wYMMJ3mfoTyi";
user.EmailAddress = "0beronemail2@ngpvan.com";
user.DisplayName = "Oberon Email2";
return user;
}
public OberonTestUser GetAccountThreeUser()
{
var user = new OberonTestUser();
user.Domain = "NGPVAN";
user.UserName = "oberonemail3";
user.Password = "in28Mh7Ba53v88uiZo7wQXUxzxL278TB";
user.EmailAddress = "0beronemail3@ngpvan.com";
user.DisplayName = "Oberon Email3";
return user;
}
}
} |
using Entitas;
using Entitas.CodeGeneration.Attributes;
[GameState]
[Unique]
[Event(false, EventType.Added)]
[Event(false, EventType.Removed)]
public sealed class GameOverComponent : IComponent
{
} |
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("Serilog.Tests, PublicKey=" +
"0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" +
"6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" +
"d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" +
"94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" +
"b19485ec")]
[assembly: InternalsVisibleTo("Serilog.PerformanceTests, PublicKey=" +
"0024000004800000940000000602000000240000525341310004000001000100fb8d13fd344a1c" +
"6fe0fe83ef33c1080bf30690765bc6eb0df26ebfdf8f21670c64265b30db09f73a0dea5b3db4c9" +
"d18dbf6d5a25af5ce9016f281014d79dc3b4201ac646c451830fc7e61a2dfd633d34c39f87b818" +
"94191652df5ac63cc40c77f3542f702bda692e6e8a9158353df189007a49da0f3cfd55eb250066" +
"b19485ec")]
|
using System.Collections.Generic;
namespace FeriaVirtual.Application.Services.Users.Queries.SearchBycriteria
{
public class SearchUsersByCriteriaResponse
{
public IEnumerable<SearchUserByCriteriaResponse> UsersResponse { get; protected set; }
public SearchUsersByCriteriaResponse(IEnumerable<SearchUserByCriteriaResponse> usersResponse) =>
UsersResponse = usersResponse;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace NStandard.Linq
{
internal class DependencyCollector
{
private readonly List<object> _dependencies = new();
internal void Collect(Expression expression, params Type[] types)
{
object GetMemberValue(MemberExpression member)
{
if (member.Expression is null)
{
if (member.Member is FieldInfo fieldInfo)
{
return fieldInfo.GetValue(null);
}
else if (member.Member is PropertyInfo propertyInfo)
{
return propertyInfo.GetValue(null);
}
else throw new NotImplementedException();
}
else
{
var memberExpression = member.Expression;
if (memberExpression is ConstantExpression memberConstant)
{
var type = memberConstant.Value.GetType();
var innerMember = type.GetField(member.Member.Name);
return innerMember.GetValue(memberConstant.Value);
}
else if (memberExpression is MemberExpression memberMember)
{
return GetMemberValue(memberMember);
}
else throw new NotImplementedException();
}
}
if (expression is LambdaExpression lambda)
{
Collect(lambda.Body, types);
}
else if (expression is UnaryExpression unary)
{
Collect(unary.Operand, types);
}
else if (expression is BinaryExpression binary)
{
Collect(binary.Left, types);
Collect(binary.Right, types);
}
else if (expression is MethodCallExpression methodCall)
{
foreach (var argument in methodCall.Arguments)
{
Collect(argument, types);
}
}
else if (expression is MemberExpression member)
{
if (types.Any(member.Type.IsType))
{
var dependency = GetMemberValue(member);
_dependencies.Add(dependency);
}
else if (member.Type.IsImplement(typeof(IEnumerable<>)))
{
var elementType = member.Type.GetElementType();
if (types.Any(elementType.IsType))
{
var dependencies = GetMemberValue(member) as IEnumerable;
foreach (var dependency in dependencies)
{
_dependencies.Add(dependency);
}
}
}
else
{
Collect(member.Expression, types);
}
}
else if (expression is NewArrayExpression newArray)
{
foreach (var innerExpression in newArray.Expressions)
{
Collect(innerExpression, types);
}
}
else if (expression is NewExpression @new)
{
foreach (var argument in @new.Arguments)
{
Collect(argument, types);
}
}
}
internal IEnumerable<object> GetDependencies()
{
return _dependencies.AsEnumerable();
}
internal void Clear()
{
_dependencies.Clear();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace goPlayApi.Models
{
public class Promotion
{
public int PromotionId { get; set; }
public String PromotionName { get; set; }
public String PromotionPictures { get; set; }
public String Description { get; set; }
public int PromotionAmount { get; set; }
}
}
|
using System;
using System.Collections;
using System.Html;
using System.Net;
using jQueryApi;
using SportsLinkScript.Shared;
using System.Serialization;
namespace SportsLinkScript.Controls
{
/// <summary>
/// Represents a module that displays content in pages
/// - contains the functionality to get the new content upon user navigating to a new page
/// - the paginated module depends upon a hidden input element being present with class "page" and a value equal to the page requested
/// </summary>
public class PaginatedModule : Module
{
/// <summary>
/// The current page that the user is being shown
/// </summary>
protected int Page = 0;
/// <summary>
/// Service to which to post the request
/// </summary>
public string ServiceName;
/// <summary>
/// Filter for the service request
/// </summary>
public string Filter = string.Empty;
/// <summary>
/// Initializes the base class of the paginated module with the DOM element and the service details
/// </summary>
/// <param name="element"></param>
/// <param name="serviceName"></param>
public PaginatedModule(Element element, string serviceName)
: base(element)
{
// Note: The paginated module contains a hidden input with class "page" and a value equal to the page requested
// Get the page
this.Page = int.Parse(this.Obj.Find(".page").GetValue());
// Store the service name
this.ServiceName = serviceName;
// Get the jquery objects for the prev/next anchor elements with class prev/next
jQueryUIObject prev = (jQueryUIObject)this.Obj.Find(".prev");
jQueryUIObject next = (jQueryUIObject)this.Obj.Find(".next");
// Make them buttons
prev.Button();
next.Button();
// Hook into the handlers
prev.Click(PagePrev);
next.Click(PageNext);
}
/// <summary>
/// Handles the button click event - simply posts a request to the service get the requested page
/// </summary>
/// <param name="e"></param>
private void PagePrev(jQueryEvent e)
{
PostBack(this.Page - 1);
}
/// <summary>
/// Handles the button click event - simply posts a request to the service get the requested page
/// </summary>
/// <param name="e"></param>
private void PageNext(jQueryEvent e)
{
PostBack(this.Page + 1);
}
/// <summary>
/// Posts the service request with the requested page
/// Uses the filter with which it was initialized
/// </summary>
/// <param name="page"></param>
protected void PostBack(int page)
{
// Use jquery to set the object as disabled in the DOM before initiating the post
this.Obj.Attribute("disabled", "disabled").AddClass("ui-state-disabled");
// Construct the parameters
JsonObject parameters = new JsonObject("page", page, "filter", this.Filter);
// Do the post - response will be handled by the generic response handler
jQuery.Post("/services/" + this.ServiceName + "?signed_request=" + Utility.GetSignedRequest(), Json.Stringify(parameters), (AjaxRequestCallback<object>)delegate(object data, string textStatus, jQueryXmlHttpRequest<object> request)
{
Utility.ProcessResponse((Dictionary)data);
}
);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateAccount : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("AdminHome.aspx");
}
protected void Button1_Click1(object sender, EventArgs e)
{
if(TextBox1.Text.TrimEnd().Length<1)
{
Label1.Text = "Please Insert A Valid User Name.";
Label1.Visible = true;
return;
}
if(TextBox2.Text.Length<1)
{
Label1.Text = "Please Insert A Valid Password.";
Label1.Visible = true;
return;
}
if(!TextBox2.Text.Equals(TextBox3.Text))
{
Label1.Text = "Passwords Are Not Match.";
Label1.Visible = true;
return;
}
TaskManager ts = new TaskManager();
if(!ts.CreateAccount(TextBox1.Text,TextBox2.Text))
{
Label1.Text = "The UserName Already Exist.";
Label1.Visible = true;
return;
}
else
{
Label1.Text = "The New Account Created Successfully.";
TextBox1.Text = TextBox2.Text = TextBox3.Text = string.Empty;
Label1.Visible = true;
return;
}
}
} |
using Piskvorky.Shapes;
using SFML.System;
using SFML.Window;
namespace Piskvorky.Core
{
class Game : GameWindow
{
private Board board;
private Player player1;
private Player player2;
private Player lastPlayer;
private Loader loader;
protected override void PreInit()
{
Log.SetTag("PIŠKVORKY");
Log.Debug("Initializing...");
TextureManager.CreateAtlas();
}
protected override void Init()
{
loader = new Loader();
board = new Board(new Vector2i(10, 10));
player1 = new Player("Player 1", ShapeType.Circle, board);
player2 = new Player("Player 2", ShapeType.Cross, board);
}
protected override void Update()
{
if(player1.IsPlaying || player2.IsPlaying)
return;
if (lastPlayer == player1)
{
player2.Play();
lastPlayer = player2;
}
else
{
player1.Play();
lastPlayer = player1;
}
}
protected override void Render()
{
window.Draw(board);
}
protected override void OnMouseButtonDown(object sender, MouseButtonEventArgs e)
{
base.OnMouseButtonDown(sender, e);
if (e.Button == Mouse.Button.Left)
{
Vector2f mousePosition = window.MapPixelToCoords(new Vector2i(e.X, e.Y));
lastPlayer.PlaceShape(mousePosition.X, mousePosition.Y);
}
}
protected override void NewGame()
{
player1.IsPlaying = false;
player2.IsPlaying = false;
lastPlayer = null;
board.GameDone = false;
board.Clear();
Log.Debug("========================NEW GAME========================");
}
protected override void Save()
{
GameSave gameSave = new GameSave()
{
GameDone = board.GameDone,
Player1 = player1,
Player2 = player2
};
SlotSave[,] slotSaves = new SlotSave[10, 10];
for (int i = 0; i < board.Slots.GetLength(0); i++)
{
for (int j = 0; j < board.Slots.GetLength(1); j++)
{
slotSaves[i, j] = new SlotSave();
if (board.Slots[i, j].Shape != null)
slotSaves[i, j].ShapeType = board.Slots[i, j].Shape.ShapeType;
else
slotSaves[i, j].Empty = true;
}
}
gameSave.Slots = slotSaves;
loader.Save(gameSave);
Log.Debug("========================GAME SAVED========================");
}
protected override void Load()
{
GameSave gameSave = loader.Load();
player1.IsPlaying = gameSave.Player1.IsPlaying;
player2.IsPlaying = gameSave.Player2.IsPlaying;
player1.Name = gameSave.Player1.Name;
player2.Name = gameSave.Player2.Name;
board.GameDone = gameSave.GameDone;
board.Load(gameSave.Slots);
if (player2.IsPlaying)
lastPlayer = player2;
else
lastPlayer = player1;
Log.Debug("========================GAME LOADED========================");
if(board.GameDone)
Log.Debug(lastPlayer.Name + " won the game");
else
Log.Debug(lastPlayer.Name + " is playing...");
}
}
}
|
using MailSender.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace MailSender
{
public class SchedulerClass
{
DispatcherTimer _timer = new DispatcherTimer();
EmailSendServiceClass _sender;
DateTime _timeSend;
IQueryable<Emails> _emails;
IProgress<double> _progress;
public TimeSpan GetSendTime(string sendTime)
{
TimeSpan tsSendTime = new TimeSpan();
try
{
tsSendTime = TimeSpan.Parse(sendTime);
}
catch(Exception e)
{
var messView = new WindowMessage();
var mess = new WindowMessageViewModel("Ошибка отправки сообщения", e.Message);
mess.ReqestClose += messView.Close;
messView.DataContext = mess;
messView.ShowDialog();
}
return tsSendTime;
}
public void SendEmails(DateTime dateTime, EmailSendServiceClass emailSender, IQueryable<Emails> emails, IProgress<double> progress)
{
_sender = emailSender;
_timeSend = dateTime;
_emails = emails;
_progress = progress;
_timer.Tick += Timer_Tick;
_timer.Interval = new TimeSpan(0, 0, 1);
_timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
if (_timeSend.ToShortTimeString() == DateTime.Now.ToShortTimeString())
{
_sender.SendEmails(_emails, _progress);
_timer.Stop();
var messView = new WindowMessage();
var mess = new WindowMessageViewModel("Сообщение планировщика", "Сообщения отправленны");
mess.ReqestClose += messView.Close;
messView.DataContext = mess;
messView.ShowDialog();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
AppInfo();
string path = @"D:\infoFile.txt";
/*if (File.Exists(path))
{ <- check if file exists
Console.WriteLine("File exsist!");
}*/
/*string[] lines;
lines = File.ReadAllLines(path);
Console.WriteLine(lines[0]); <- reading specific lines
Console.WriteLine(lines[1]);*/
/*string lines;
lines = File.ReadAllText(path); <- read all lines
Console.WriteLine(lines);*/
/*string path1 = @"D:\example.txt";
string copypath = @"D:\ExampleNew.txt"; <- copy from path1 to copypath
File.Copy(path1,copypath);*/
/*string path1 = @"D:\Example.txt"; <- delete file
File.Delete(path1);*/
}
static void AppInfo()
{
string appName = "File I/0";
string appVersion = "0.1";
string appAuthor = "Mateusz Celka";
Console.WriteLine("{0} version: {1} by {2}",appName,appVersion,appAuthor);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class ScoreUI : MonoBehaviour
{
[SerializeField] private Text scoreText = null;
void Update()
{
int score = GameManager.I.Score;
scoreText.text = $"Score: {score.ToString()}";
}
}
|
using Crystal.Plot2D.Charts;
using System;
using System.Windows;
namespace Crystal.Plot2D
{
public sealed class GenericChartPlotter<THorizontal, TVertical>
{
public AxisBase<THorizontal> HorizontalAxis { get; }
private readonly AxisBase<TVertical> verticalAxis;
public AxisBase<TVertical> VerticalAxis => verticalAxis;
private readonly Plotter plotter;
public Plotter Plotter => plotter;
public Func<THorizontal, double> HorizontalToDoubleConverter => HorizontalAxis.ConvertToDouble;
public Func<double, THorizontal> DoubleToHorizontalConverter => HorizontalAxis.ConvertFromDouble;
public Func<TVertical, double> VerticalToDoubleConverter => verticalAxis.ConvertToDouble;
public Func<double, TVertical> DoubleToVerticalConverter => verticalAxis.ConvertFromDouble;
internal GenericChartPlotter(Plotter plotter) : this(plotter, plotter.MainHorizontalAxis as AxisBase<THorizontal>, plotter.MainVerticalAxis as AxisBase<TVertical>) { }
internal GenericChartPlotter(Plotter plotter, AxisBase<THorizontal> horizontalAxis, AxisBase<TVertical> verticalAxis)
{
this.HorizontalAxis = horizontalAxis ?? throw new ArgumentNullException(Strings.Exceptions.PlotterMainHorizontalAxisShouldNotBeNull);
this.verticalAxis = verticalAxis ?? throw new ArgumentNullException(Strings.Exceptions.PlotterMainVerticalAxisShouldNotBeNull);
this.plotter = plotter;
}
public GenericRect<THorizontal, TVertical> ViewportRect
{
get => CreateGenericRect(plotter.Viewport.Visible);
set => plotter.Viewport.Visible = CreateRect(value);
}
public GenericRect<THorizontal, TVertical> DataRect
{
get => CreateGenericRect(plotter.Viewport.Visible.ViewportToData(plotter.Viewport.Transform));
set => plotter.Viewport.Visible = CreateRect(value).DataToViewport(plotter.Viewport.Transform);
}
private DataRect CreateRect(GenericRect<THorizontal, TVertical> value)
{
double xMin = HorizontalToDoubleConverter(value.XMin);
double xMax = HorizontalToDoubleConverter(value.XMax);
double yMin = VerticalToDoubleConverter(value.YMin);
double yMax = VerticalToDoubleConverter(value.YMax);
return new DataRect(new Point(xMin, yMin), new Point(xMax, yMax));
}
private GenericRect<THorizontal, TVertical> CreateGenericRect(DataRect rect)
{
double xMin = rect.XMin;
double xMax = rect.XMax;
double yMin = rect.YMin;
double yMax = rect.YMax;
var res = new GenericRect<THorizontal, TVertical>(
DoubleToHorizontalConverter(xMin),
DoubleToVerticalConverter(yMin),
DoubleToHorizontalConverter(xMax),
DoubleToVerticalConverter(yMax));
return res;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Courier_Management_System.Models;
using Microsoft.AspNetCore.Http;
using Courier_Management_System.Data;
using DataContext = Courier_Management_System.Models.DataContext;
namespace Courier_Management_System.Controllers
{
public class UserController : Controller
{
private readonly DataContext _context;
private readonly IHttpContextAccessor _accessor;
public UserController(DataContext context, IHttpContextAccessor accessor)
{
_context = context;
_accessor = accessor;
}
public async Task<IActionResult> SignUp()
{
return View(await _context.City.ToListAsync());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SignUpAsync(String email,String name,String password,String city,String phone_no,String address)
{
User U = new User();
Console.Write(email + ":" + name + ":" + city + ":" + phone_no);
Console.WriteLine("inside signup post method");
U.email = email;
U.city = city;
U.name = name;
U.password = password;
U.role = "client";
U.phone_no = phone_no;
U.address = address;
if (ModelState.IsValid)
{
_context.Add(U);
_ = await _context.SaveChangesAsync();
return Redirect("/Home/Index");
}
return View(U);
}
public IActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(String email,String password)
{
var user = await _context.users
.FirstOrDefaultAsync(m => m.email == email && m.password==password);
if(user!=null)
{
HttpContext.Session.SetString("logged_in_user",user.email);
HttpContext.Session.SetString("user_role", user.role);
ViewBag.session = HttpContext.Session.GetString("logged_in_user");
Console.WriteLine("stored variable "+ViewBag.session);
return Redirect("/User/Profile/");
}
return View(user);
}
public async Task<IActionResult> Profile()
{
if(new Utility(this._accessor).IsAuthorisedClient()==true)
{
var user = await _context.users
.FirstOrDefaultAsync(m => m.email == HttpContext.Session.GetString("logged_in_user"));
Console.WriteLine(user.name);
return View(user);
}
else
{
return Redirect("/User/Signup");
}
}
public IActionResult LogOut()
{
HttpContext.Session.Clear();
return Redirect("/Home/Index");
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace EduHome.Migrations
{
public partial class AddedTeacherTables : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "SocialLinks");
migrationBuilder.AddColumn<string>(
name: "Facebook",
table: "Footer",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Pinterest",
table: "Footer",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Twitter",
table: "Footer",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Vimeo",
table: "Footer",
nullable: true);
migrationBuilder.CreateTable(
name: "Teachers",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Fullname = table.Column<string>(nullable: true),
Professional = table.Column<string>(nullable: true),
AboutTeacher = table.Column<string>(nullable: true),
Faculty = table.Column<string>(nullable: true),
Experience = table.Column<int>(nullable: false),
Hobbies = table.Column<string>(nullable: true),
Phone = table.Column<string>(nullable: true),
Language = table.Column<int>(nullable: false),
Design = table.Column<int>(nullable: false),
Development = table.Column<int>(nullable: false),
TeamLeader = table.Column<int>(nullable: false),
Innovation = table.Column<int>(nullable: false),
Communication = table.Column<int>(nullable: false),
Email = table.Column<string>(nullable: true),
Facebook = table.Column<string>(nullable: true),
Twitter = table.Column<string>(nullable: true),
Pinterest = table.Column<string>(nullable: true),
Vimeo = table.Column<string>(nullable: true),
Skype = table.Column<string>(nullable: true),
CourseId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teachers", x => x.Id);
table.ForeignKey(
name: "FK_Teachers_Courses_CourseId",
column: x => x.CourseId,
principalTable: "Courses",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.UpdateData(
table: "Footer",
keyColumn: "Id",
keyValue: 1,
columns: new[] { "Facebook", "Pinterest", "Twitter", "Vimeo" },
values: new object[] { "facebook.com", "pinterest.com", "twitter.com", "vimeo.com" });
migrationBuilder.InsertData(
table: "Teachers",
columns: new[] { "Id", "AboutTeacher", "Communication", "CourseId", "Design", "Development", "Email", "Experience", "Facebook", "Faculty", "Fullname", "Hobbies", "Innovation", "Language", "Phone", "Pinterest", "Professional", "Skype", "TeamLeader", "Twitter", "Vimeo" },
values: new object[] { 1, "I must explain to you how all this a mistaken idea of denouncing great explorer of the rut the is lder of human happiness pcias unde omnis iste natus error sit voluptatem accusantium ue laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quas i architeo beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas", 95, 1, 95, 85, " stuart@eduhome.com", 7, "facebook.com", "Din, Department of Micro Biology", "STUART KELVIN", "music, travelling, catching fish", 85, 85, "(+125) 5896 548 9874", "pinterest.com", "Associate Professor", "stuart.k", 90, "twitter.com", "vimeo.com" });
migrationBuilder.CreateIndex(
name: "IX_Teachers_CourseId",
table: "Teachers",
column: "CourseId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Teachers");
migrationBuilder.DropColumn(
name: "Facebook",
table: "Footer");
migrationBuilder.DropColumn(
name: "Pinterest",
table: "Footer");
migrationBuilder.DropColumn(
name: "Twitter",
table: "Footer");
migrationBuilder.DropColumn(
name: "Vimeo",
table: "Footer");
migrationBuilder.CreateTable(
name: "SocialLinks",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FooterId = table.Column<int>(type: "int", nullable: false),
Icon = table.Column<string>(type: "nvarchar(max)", nullable: true),
Link = table.Column<string>(type: "nvarchar(max)", nullable: true),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SocialLinks", x => x.Id);
table.ForeignKey(
name: "FK_SocialLinks_Footer_FooterId",
column: x => x.FooterId,
principalTable: "Footer",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "SocialLinks",
columns: new[] { "Id", "FooterId", "Icon", "Link", "Name" },
values: new object[,]
{
{ 1, 1, "zmdi zmdi-facebook", "facebook.com", "facebook" },
{ 2, 1, "zmdi zmdi-pinterest", "pinterest.com", "pinterest" },
{ 3, 1, "zmdi zmdi-vimeo", "vimeo.com", "vimeo" },
{ 4, 1, "zmdi zmdi-twitter", "twitter.com", "twitter" }
});
migrationBuilder.CreateIndex(
name: "IX_SocialLinks_FooterId",
table: "SocialLinks",
column: "FooterId");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Note: IComparable
{
public Note(string name, int level, int no, string text)
{
Name = name;
Level = level;
No = no;
Text = text;
}
string name;
int level;
int no;
string text;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Level
{
get
{
return level;
}
set
{
level = value;
}
}
public int No
{
get
{
return no;
}
set
{
no = value;
}
}
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
public int CompareTo(object obj)
{
Note note = obj as Note;
return Level.CompareTo(note.Level);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using CountryProject.MODEL.ViewModel;
using System.Data;
using System.Web.Configuration;
namespace CountryProject.DAL
{
public class ViewCountryGateway
{
//SqlConnection sqlconn = new SqlConnection();
//sqlconn.ConnectionString = connectionString;
private SqlConnection connection;
string connectionString = WebConfigurationManager.ConnectionStrings["CountryCityManagement"].ConnectionString;
//private string connectionString = @"Data Source=TANZID\SQLEXPRESS;Initial Catalog=CountryCityDb;Integrated Security=True";
public ViewCountryGateway()
{
connection = new SqlConnection(connectionString);
}
public List<ViewCountry> ViewCountyGetAll()
{
string viewContryGetAllQuery = "SELECT * FROM tb_country";
SqlCommand command = new SqlCommand(viewContryGetAllQuery, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<ViewCountry> viewCountryList = new List<ViewCountry>();
while (reader.Read())
{
ViewCountry viewCountry = new ViewCountry();
viewCountry.ViewCountryid = Convert.ToInt32(reader["id"]);
viewCountry.ViewCountryName = reader["name"].ToString();
viewCountry.ViewCountryAbout = reader["about"].ToString();
viewCountryList.Add(viewCountry);
}
reader.Close();
connection.Close();
return viewCountryList;
}
public List<ViewCountry> ViewCountyGetAll(string searchCountry)
{
string viewContryGetAllQuery = "SELECT * FROM tb_country WHERE name LIKE '%'+ @name +'%' ORDER BY name";
SqlCommand command = new SqlCommand(viewContryGetAllQuery, connection);
command.Parameters.Clear();
command.Parameters.Add("name", SqlDbType.VarChar);
command.Parameters["name"].Value =searchCountry;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<ViewCountry> viewCountryList = new List<ViewCountry>();
while (reader.Read())
{
ViewCountry viewCountry = new ViewCountry();
viewCountry.ViewCountryid = Convert.ToInt32(reader["id"]);
viewCountry.ViewCountryName = reader["name"].ToString();
viewCountry.ViewCountryAbout = reader["about"].ToString();
viewCountryList.Add(viewCountry);
}
reader.Close();
connection.Close();
return viewCountryList;
}
public int NoOfCityGetway(int ViewCountryid)
{
string selectQuery = string.Format("SELECT count(name) as count FROM t_city WHERE countryId='{0}'", ViewCountryid);
SqlCommand command = new SqlCommand(selectQuery, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
ViewCountry viewCountry = new ViewCountry();
while (reader.Read())
{
viewCountry.viewCountryNoOfCitys = Convert.ToInt32(reader["count"]);
}
reader.Close();
connection.Close();
return viewCountry.viewCountryNoOfCitys;
}
public string NoOfCityDrewlersGetway(int ViewCountryid)
{
string selectQuery = string.Format("SELECT sum(noOfDwellers) as count FROM t_city WHERE countryId='{0}'", ViewCountryid);
SqlCommand command = new SqlCommand(selectQuery, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
ViewCountry viewCountry = new ViewCountry();
while (reader.Read())
{
viewCountry.viewCountryNoOfCityDrewlers = reader["count"].ToString();
}
reader.Close();
connection.Close();
return viewCountry.viewCountryNoOfCityDrewlers;
}
}
} |
using System;
using System.Threading.Tasks;
using AutoFixture;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Mappers.Cohort;
using SFA.DAS.ProviderCommitments.Web.Models;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Cohort
{
[TestFixture]
public class WhenIMapChoosePilotStatusViewModelToCreateCohortWithDraftApprenticeshipRequest
{
private CreateCohortWithDraftApprenticeshipRequestFromChoosePilotStatusViewModelMapper _mapper;
private ChoosePilotStatusViewModel _source;
private Func<Task<CreateCohortWithDraftApprenticeshipRequest>> _act;
[SetUp]
public void Arrange()
{
var fixture = new Fixture();
_source = fixture.Create<ChoosePilotStatusViewModel>();
_mapper = new CreateCohortWithDraftApprenticeshipRequestFromChoosePilotStatusViewModelMapper();
_act = async () => await _mapper.Map(_source);
}
[Test]
public async Task ThenProviderIdIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.ProviderId, result.ProviderId);
}
[Test]
public async Task ThenCourseCodeIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.CourseCode, result.CourseCode);
}
[Test]
public async Task ThenEmployerAccountLegalEntityPublicHashedIdIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.EmployerAccountLegalEntityPublicHashedId, result.EmployerAccountLegalEntityPublicHashedId);
}
[Test]
public async Task ThenAccountLegalEntityIdIsMapped()
{
var result = await _act();
Assert.AreEqual(_source.AccountLegalEntityId, result.AccountLegalEntityId);
}
[Test]
public async Task ThenDeliveryModelIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.DeliveryModel, result.DeliveryModel);
}
[Test]
public async Task ThenReservationIdIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.ReservationId, result.ReservationId);
}
[Test]
public async Task ThenStartDateIsMappedCorrectly()
{
var result = await _act();
Assert.AreEqual(_source.StartMonthYear, result.StartMonthYear);
}
[TestCase(ChoosePilotStatusOptions.Pilot, true)]
[TestCase(ChoosePilotStatusOptions.NonPilot, false)]
public async Task ThenPilotChoiceIsMappedCorrectly(ChoosePilotStatusOptions option, bool expected)
{
_source.Selection = option;
var result = await _act();
Assert.AreEqual(expected, result.IsOnFlexiPaymentPilot);
}
}
} |
namespace XF40Demo.Models
{
public class PowerDetails
{
public int Id { get; }
public string ShortName { get; }
public string HQ { get; }
public int YearOfBirth { get; }
public string Allegiance { get; }
public string PreparationEthos { get; }
public string PreparationText { get; }
public string ExpansionEthos { get; }
public string ExpansionText { get; }
public string ExpansionStrongGovernment { get; }
public string ExpansionWeakGovernment { get; }
public string ControlEthos { get; }
public string ControlText { get; }
public string ControlStrongGovernment { get; }
public string ControlWeakGovernment { get; }
public string HQSystemEffect { get; }
public string ControlSystemEffect { get; }
public string AllianceExploitedEffect { get; }
public string EmpireExploitedEffect { get; }
public string FederationExploitedEffect { get; }
public string IndependentExploitedEffect { get; }
public string Rating1 { get; }
public string Rating2 { get; }
public string Rating3 { get; }
public string Rating4 { get; }
public string Rating5 { get; }
public PowerDetails(int id,
string shortName,
string hq,
int yearOfBirth,
string allegiance,
string preparationEthos,
string preparationText,
string expansionEthos,
string expansionText,
string expansionStrongGovernment,
string expansionWeakGovernment,
string controlEthos,
string controlText,
string controlStrongGovernment,
string controlWeakGovernment,
string hqSystemEffect,
string controlSystemEffect,
string allianceExploitedEffect,
string empireExploitedEffect,
string federationExploitedEffect,
string independentExploitedEffect,
string rating1,
string rating2,
string rating3,
string rating4,
string rating5)
{
Id = id;
ShortName = shortName;
HQ = hq;
YearOfBirth = yearOfBirth;
Allegiance = allegiance;
PreparationEthos = preparationEthos;
PreparationText = preparationText;
ExpansionEthos = expansionEthos;
ExpansionText = expansionText;
ExpansionStrongGovernment = expansionStrongGovernment;
ExpansionWeakGovernment = expansionWeakGovernment;
ControlEthos = controlEthos;
ControlText = controlText;
ControlStrongGovernment = controlStrongGovernment;
ControlWeakGovernment = controlWeakGovernment;
HQSystemEffect = hqSystemEffect;
ControlSystemEffect = controlSystemEffect;
AllianceExploitedEffect = allianceExploitedEffect;
EmpireExploitedEffect = empireExploitedEffect;
FederationExploitedEffect = federationExploitedEffect;
IndependentExploitedEffect = independentExploitedEffect;
Rating1 = rating1;
Rating2 = rating2;
Rating3 = rating3;
Rating4 = rating4;
Rating5 = rating5;
}
public override string ToString()
{
return $"{ShortName} ({Allegiance}) - {HQ}";
}
}
}
|
using System;
using System.ComponentModel.Composition;
namespace Autofac.Extras.AttributeMetadata.Test.ScenarioTypes.CombinationalWeakTypedAttributeScenario
{
[MetadataAttribute]
public class CombinationalWeakAgeMetadataAttribute : Attribute
{
public int Age { get; private set; }
public CombinationalWeakAgeMetadataAttribute(int age)
{
Age = age;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace NewRimLiqourProject.Models
{
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Name")]
[Required(ErrorMessage = "Please provide Name.")]
public string Name { get; set; }
[Display(Name = "Surname")]
[Required(ErrorMessage = "Please provide Surname.")]
public string Surname { get; set; }
[Display(Name = "Date of birth")]
public string DateOfBirth { get; set; }
[Required]
[Display(Name = "ID Number")]
// [RegularExpression(@"\d{12,13}", ErrorMessage = "ID number must be 13 digits.")]
[StringLength(13, ErrorMessage = "ID number must be 13 digits.", MinimumLength = 13)]
public string IDnumber { get; set; }
[Display(Name = "Gender")]
[Required(ErrorMessage = "Please provide your Gender")]
// public List<Gendr> Gender { get; set; }
public string Gender { set; get; }
[Required(ErrorMessage = "Please provide Postal address street number and street name.")]
[Display(Name = "Postal Address 1")]
public string Address1 { get; set; }
[Required(ErrorMessage = "Please provide Postal address name of the place you live in.")]
[Display(Name = "Postal address 2")]
public string Address2 { get; set; }
[Required(ErrorMessage = "Please provide address code.")]
[Display(Name = "Postal address Code")]
public int Code { get; set; }
[Required(ErrorMessage = "Email Address is required")]
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
public string UserName { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public string ApplicationUserId { get; set; }
}
} |
using System;
namespace MaterialTransition
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IdomOffice.Interface.BackOffice.Booking;
namespace V50_IDOMBackOffice.AspxArea.Booking.Models
{
public class EmailProcessViewModel
{
public string Id { get; set; }
public string BookingId { get; set; }
public string docType { get; set; }
public DocumentProcessStatus Status { get; set; }
public string Content { get; set; }
public string Sender { get; set; }
public string Receipent { get; set; }
public string Title { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using NewBot.Common;
namespace NewBot.Controllers
{
public class MainController : ApiBase
{
[HttpGet]
public HttpResponseMessage Index()
{
return JsonHelper.GoToJson("this is main");
}
}
}
|
using System;
using System.ComponentModel;
namespace SpeedSlidingTrainer.Application.Services.SessionStatistics
{
public interface IAggregatedSolveStatistics : INotifyPropertyChanged
{
TimeSpan? Time { get; }
double? Moves { get; }
double? Tps { get; }
double? Efficiency { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BugTracker.DataAccessLayer;
namespace BugTracker.BusinessLayer
{
class StockService
{
StockDao oStockDao;
StockService()
{
oStockDao = new StockDao();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCUtils
{
SharedKnowledge sharedKnowledge;
Transform transform;
MonoBehaviour mb;
public MonoBehaviour MB
{
get
{
return mb;
}
}
Grid grid;
public Grid Grid
{
get
{
return grid;
}
}
Pathfinding pathfinder;
public Pathfinding Pathfinder
{
get
{
return pathfinder;
}
}
string targetTag;
public string TargetTag
{
get
{
return targetTag;
}
}
float goalTriggerRange;
public float GoalTriggerRange
{
get
{
return goalTriggerRange;
}
}
float npcTriggerRange;
public float NpcTriggerRange
{
get
{
return npcTriggerRange;
}
}
double reportTimeValidation;
public double ReportTimeValidation
{
get
{
return reportTimeValidation;
}
}
int buildingSeconds;
public int BuildingSeconds
{
get
{
return buildingSeconds;
}
}
int sleepingSeconds;
public int SleepingSeconds
{
get
{
return sleepingSeconds;
}
}
float followSpeed;
public float FollowSpeed
{
get
{
return followSpeed;
}
}
float randomSpeed;
public float RandomSpeed
{
get
{
return randomSpeed;
}
}
GameObject wallPrefab;
public GameObject WallPrefab
{
get
{
return wallPrefab;
}
}
// CONSTRUCTOR
public NPCUtils(MonoBehaviour mb, SharedKnowledge sharedKnowledge, Transform transform, Grid grid, string targetTag, float goalTriggerRange, float npcTriggerRange, double reportTimeValidation, int buildingSeconds, int sleepingSeconds, float followSpeed, float randomSpeed, GameObject wallPrefab)
{
this.mb = mb;
this.sharedKnowledge = sharedKnowledge;
this.transform = transform;
this.grid = grid;
pathfinder = new Pathfinding(transform.GetInstanceID(), grid);
this.targetTag = targetTag;
this.goalTriggerRange = goalTriggerRange;
this.npcTriggerRange = npcTriggerRange;
this.reportTimeValidation = reportTimeValidation;
this.buildingSeconds = buildingSeconds;
this.sleepingSeconds = sleepingSeconds;
this.followSpeed = followSpeed;
this.randomSpeed = randomSpeed;
this.wallPrefab = wallPrefab;
}
// METHODS
public bool SeePlayer()
{
RaycastHit raycastInfo;
Physics.Linecast(transform.position, sharedKnowledge.Player.position, out raycastInfo);
// Debug.DrawLine(transform.position, goalPosition.position);
if (raycastInfo.collider != null && raycastInfo.collider.tag == targetTag && raycastInfo.distance < goalTriggerRange)
{
ReportPlayer();
return true;
}
return false;
}
public void ReportPlayer()
{
sharedKnowledge.Report(transform);
// Debug.Log(transform.GetInstanceID() + " report");
}
public Vector3 GetTarget(Vector3 playerPosition)
{
Vector3 target = new Vector3();
//greedy
Vector3 left, right;
if (transform.forward.x >= 0.5 || transform.forward.x <= -0.5)
{
left = Vector3.forward * grid.nodeRadius;
right = Vector3.back * grid.nodeRadius;
}
else
{
left = Vector3.left * grid.nodeRadius;
right = Vector3.right * grid.nodeRadius;
}
RaycastHit raycastInfoLeft, raycastInfoRight;
Physics.Linecast(transform.position + left, playerPosition + left, out raycastInfoLeft);
Physics.Linecast(transform.position + right, playerPosition + right, out raycastInfoRight);
// Debug.DrawLine(transform.position + Vector3.right * grid.nodeRadius, goalPosition.position);
// Debug.DrawLine(transform.position + Vector3.left * grid.nodeRadius, goalPosition.position);
if ((raycastInfoLeft.collider != null && (raycastInfoLeft.collider.tag == "Wall" || raycastInfoLeft.collider.tag == "NPC"))
|| (raycastInfoRight.collider != null && (raycastInfoRight.collider.tag == "Wall" || raycastInfoRight.collider.tag == "NPC")))
{
pathfinder.FindPath(transform.position, playerPosition, left, right);
List<Node> finalPath = pathfinder.FinalPath;
if (finalPath != null && finalPath.Count > 0)
{
Vector3 firstStep = finalPath[0].position;
// Vector3 firstStep = finalPath.Count > 1 ? finalPath[1].position : finalPath[0].position;
target = firstStep;
}
}
else
target = playerPosition;
return target;
}
public void MoveTo(Vector3 destination, float speed)
{
if ((destination - transform.position) == Vector3.zero)
return;
Quaternion targetRotation = Quaternion.LookRotation(destination - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, destination, speed * Time.deltaTime);
// Vector3 verticalAdj = new Vector3(destination.x, transform.position.y, destination.z);
// Vector3 toDestination = verticalAdj - transform.position;
// transform.LookAt(verticalAdj);
// Vector3 rotagionAdj = new Vector3(0f, transform.rotation.eulerAngles.y, 0f);
// transform.rotation = Quaternion.Euler(rotagionAdj);
// transform.position += transform.forward * speed * Time.deltaTime;
// rb.MovePosition(transform.position + transform.forward * speed * Time.deltaTime);
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.MRP.ORD
{
[Serializable]
public partial class MrpExWorkHour : EntityBase, IAuditable
{
#region O/R Mapping Properties
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "MrpExWorkHour_Flow", ResourceType = typeof(Resources.MRP.MrpExWorkHour))]
public string Flow { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "MrpExWorkHour_Item", ResourceType = typeof(Resources.MRP.MrpExWorkHour))]
public string Item { get; set; }
[Display(Name = "MrpExWorkHour_ItemDescription", ResourceType = typeof(Resources.MRP.MrpExWorkHour))]
public string ItemDescription { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "MrpExWorkHour_StartTime", ResourceType = typeof(Resources.MRP.MrpExWorkHour))]
public DateTime StartTime { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "MrpExWorkHour_WindowTime", ResourceType = typeof(Resources.MRP.MrpExWorkHour))]
public DateTime WindowTime { get; set; }
[Display(Name = "MrpExWorkHour_HaltTime", ResourceType = typeof(Resources.MRP.MrpExWorkHour))]
public double HaltTime { get; set; }
public Int32 CreateUserId { get; set; }
public string CreateUserName { get; set; }
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
public string LastModifyUserName { get; set; }
public DateTime LastModifyDate { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
MrpExWorkHour another = obj as MrpExWorkHour;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using Dapper;
namespace TaskManager.Models
{
public class TodoListViewModel
{
public TodoListViewModel()
{
using (var db = DbHelper.GetConnection())
{
this.EditableItem = new TodoListItem();
this.TodoItems = db.Query<TodoListItem>("SELECT * FROM TodoListItems ORDER BY AddDate DESC").ToList();
}
}
public List<TodoListItem> TodoItems { get; set; }
public TodoListItem EditableItem { get; set; }
}
public static class DbHelper
{
public static SqlConnection GetConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["IdentityDb"].ConnectionString);
}
}
} |
using P03.WildFarm.Models.Foods;
using System;
using System.Collections.Generic;
using System.Text;
namespace P03.WildFarm.Models.Animals
{
public abstract class Animal
{
protected Animal(string name, double weight)
{
this.Name = name;
this.Weight = weight;
this.FoodEaten = 0;
}
public string Name { get; private set; }
public double Weight { get; protected set; }
public int FoodEaten { get; protected set; }
public abstract string ProduceSound();
public void Eat(Food food)
{
string typeFood = food.GetType().Name;
if (typeFood == "Fruit" || typeFood == "Vegetable")
{
this.Weight += food.Quantity * 0.10;
this.FoodEaten += food.Quantity;
return;
}
throw new ArgumentException($"{this.GetType().Name} does not eat {typeFood}!");
}
}
}
|
using AForge.Neuro;
using AForge.Neuro.Learning;
using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionRegression
{
public class RegressionTaskV2B : RegressionTaskV1
{
public RegressionTaskV2B()
{
LearningRange = new Range(0, 1, 0.025);
Function = z => z * Math.Sin(z*10);
MaxError = 0.5;
IterationsCount = 30720;
}
protected override void LearningIteration()
{
int RepetitionCount = 5;
for (int i = 0; i < Inputs.Length / RepetitionCount; i++)
{
var sample = rnd.Next(Inputs.Length);
for (int j = 0; j < RepetitionCount; j++)
teacher.Run(Inputs[sample], Answers[sample]);
}
}
protected override void CreateNetwork()
{
network = new ActivationNetwork(new Tanh(1), 1, 5, 5, 1);
network.ForEachWeight(z => rnd.NextDouble() * 2-1);
teacher = new BackPropagationLearning(network);
teacher.LearningRate = 1;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Javan.Models;
namespace Javan.Data
{
public class JavanContext : DbContext
{
public JavanContext(DbContextOptions<JavanContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ObligasiSecurity>().HasData(
new ObligasiSecurity { ID = 1, Kode = "KE001", Nama = "Bank Victoria", Nominal = 300000 },
new ObligasiSecurity { ID = 2, Kode = "KE002", Nama = "Tunas Baru", Nominal = 1000000000000 },
new ObligasiSecurity { ID = 3, Kode = "KE003", Nama = "Smart TBK", Nominal = 500000 }
);
}
public DbSet<Perubahan> Perubahan { get; set; }
public DbSet<PerubahanIsi> PerubahanIsi { get; set; }
public DbSet<ObligasiSecurity> ObligasiSecurities { get; set; }
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TimeLogger.Web.Models;
namespace TimeLogger.Web.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ProfilesController : ControllerBase
{
private readonly LoggerDBContext _context;
public ProfilesController(LoggerDBContext context)
{
_context = context;
}
// GET: api/Profiles
[HttpGet]
public async Task<ActionResult<IEnumerable<Profile>>> GetProfile()
{
return await _context.Profile.ToListAsync();
}
// GET: api/Profiles/5
[HttpGet("{id}")]
public async Task<ActionResult<Profile>> GetProfile(int id)
{
var profile = await _context.Profile.FindAsync(id);
if (profile == null)
{
return NotFound();
}
return profile;
}
// PUT: api/Profiles/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPut("{id}")]
public async Task<IActionResult> PutProfile(int id, Profile profile)
{
if (id != profile.EmpId)
{
return BadRequest();
}
_context.Entry(profile).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProfileExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Profiles
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Profile>> PostProfile(Profile profile)
{
_context.Profile.Add(profile);
await _context.SaveChangesAsync();
return CreatedAtAction("GetProfile", new { id = profile.EmpId }, profile);
}
// DELETE: api/Profiles/5
[HttpDelete("{id}")]
public async Task<ActionResult<Profile>> DeleteProfile(int id)
{
var profile = await _context.Profile.FindAsync(id);
if (profile == null)
{
return NotFound();
}
_context.Profile.Remove(profile);
await _context.SaveChangesAsync();
return profile;
}
private bool ProfileExists(int id)
{
return _context.Profile.Any(e => e.EmpId == id);
}
}
} |
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.PermissionsPolicy
{
/// <summary>
/// Controls whether the current document is allowed to use audio
/// input devices. When this policy is enabled, the <code>Promise</code>
/// returned by <code>MediaDevices.getUserMedia()</code> will
/// reject with a <code>NotAllowedError</code>.
/// </summary>
public class MicrophonePermissionsPolicyDirectiveBuilder : PermissionsPolicyDirectiveBuilder
{
/// <summary>
/// Initializes a new instance of the <see cref="MicrophonePermissionsPolicyDirectiveBuilder"/> class.
/// </summary>
public MicrophonePermissionsPolicyDirectiveBuilder() : base("microphone")
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2016 {
public class Problem15 : AdventOfCodeBase {
private List<Disc> _discs;
public override string ProblemName => "Advent of Code 2016: 15";
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private int Answer1(List<string> input) {
GetDiscs(input);
return FindDrop();
}
private int Answer2(List<string> input) {
GetDiscs(input);
AddNewDisc();
return FindDrop();
}
private void AddNewDisc() {
_discs.Add(new Disc() { Positions = 11 });
}
private int FindDrop() {
int time = 0;
bool isGood = false;
do {
time++;
isGood = true;
for (int index = 0; index < _discs.Count; index++) {
var disc = _discs[index];
var num = (disc.Current + time + index + 1) % disc.Positions;
if (num != 0) {
isGood = false;
break;
}
}
} while (!isGood);
return time;
}
private void GetDiscs(List<string> input) {
_discs = input.Select(line => {
var split = line.Split(' ');
return new Disc() {
Current = Convert.ToInt32(split[11].Replace(".", " ")),
Positions = Convert.ToInt32(split[3])
};
}).ToList();
}
private class Disc {
public int Positions { get; set; }
public int Current { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tortuga
{
class Tortuga
{
//Se declara las variables necesarias y la matriz
private string vCadena;
private int[,] _matriz1;
// "i" y "j" serán las variables de la matriz
private int i,j;
private int k;
//IMPORTANTE! presta atención a tus principales atributos
private bool derecha = false, izquiera = false, arriba = false, abajo = false;
//Vamos a inicializar nuestra matriz
public Tortuga()
{
_matriz1 = new int[20, 20];
}
//Iniciamos con la primer función, AVANZAR
public void avanzar(int aux)
{
//Si la pluma está abajo vamos a empezar a llenar los vectores que va recorriendo
if (abajo == true)
{
for (k = 0; k < aux; k++)
{
_matriz1[i, j] = 1;
i++;
}
}
//Si la pluma está arriba vamos a empezar a llenar los vectores que va recorriendo
if (arriba == true)
{
for (k = 0; k < aux; k++)
{
_matriz1[i, j] = 1;
i--;
}
}
//Si la tortuga va hacia la derecha vamos a empezar a llenar los vectores que va recorriendo
if (derecha == true)
{
for (k = 0; k < aux; k++)
{
_matriz1[i-1, j+1] = 1;
j++;
}
}
//Si la tortuga se dirge a la izquiera vamos a empezar a llenar los vectores que va recorriendo
if (izquiera == true)
{
for (k = 0; k < aux; k++)
{
_matriz1[i-1, j-1] = 1;
j--;
}
}
}
//Se va a girar a la izquiera cuando esté activado solo el de la izquierda
public void girarIzquierda()
{
izquiera = true;
derecha = false;
abajo = false;
arriba = false;
}
//Se va a girar a la derecha cuando esté activado solo el de la derecha
public void girarDerecha()
{
izquiera = false;
derecha = true;
abajo = false;
arriba = false;
}
//Se va a poner la pluma arriba cuando esté activado solo el de arriba
public void plumaArriba()
{
izquiera = false;
derecha = false;
abajo = false;
arriba = true;
}
//Se va a poner la pluma abajo cuando esté activado solo el de abajo
public void plumaAbajo()
{
izquiera = false;
derecha = false;
abajo = true;
arriba = false;
}
//Para mostrar los vectores que se encuentran dentro de la matriz, se va a imprimir en cada uno un "*"
public string tablero() {
vCadena = "";
for (int i = 0; i<20; i++)
{
for (int j = 0; j<20; j++)
{
vCadena += "*"+ " ";
}
vCadena += Environment.NewLine;
}
vCadena += "\n\n";
return vCadena;
}
//Aquí se va a mostrar el camino que lleve la tortuga :D!
public string mostrar()
{
vCadena = "l";
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
vCadena += _matriz1[i, j].ToString() + " ";
}
vCadena += Environment.NewLine;
}
vCadena += "\n\n";
return vCadena;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TcpServerLibrary;
namespace ClientGui
{
public partial class InteractionAdminWindow : Form
{
TcpClient client;
NetworkStream stream;
ClientComunicator comunicator = new ClientComunicator();
int permision;
public InteractionAdminWindow(TcpClient client, int permision)
{
InitializeComponent();
stream = client.GetStream();
this.client = client;
this.permision = permision;
}
private void registerButton_Click(object sender, EventArgs e)
{
Hide();
RegisterWindow registerWindow = new RegisterWindow(client, permision);
registerWindow.ShowDialog();
}
private void beginButton_Click(object sender, EventArgs e)
{
Hide();
GameWindow gameWindow = new GameWindow(client, permision);
gameWindow.ShowDialog();
}
private void remButton_Click(object sender, EventArgs e)
{
Hide();
RemoveUserWindow removeUser = new RemoveUserWindow(client, permision);
removeUser.ShowDialog();
}
private void rankingButton_Click(object sender, EventArgs e)
{
Hide();
RankingWindow rankingWindow = new RankingWindow(client, permision);
rankingWindow.ShowDialog();
}
private void logoutButton_Click(object sender, EventArgs e)
{
comunicator.SendMessage(stream, "5");
Hide();
LoginWindow loginWindow = new LoginWindow(client);
loginWindow.ShowDialog();
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Internals;
using Microsoft.Bot.Connector;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Microsoft.BotCore.Sample.EchoBot
{
[ServiceFilter(typeof(BotAuthentication))]
[Route("api/[controller]")]
public class MessagesController : Controller
{
private readonly IConfigurationRoot _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IMemoryCache _memoryCache;
public MessagesController(IConfigurationRoot configuration, IHttpContextAccessor httpContextAccessor, IMemoryCache memoryCache)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (httpContextAccessor == null)
{
throw new ArgumentNullException(nameof(httpContextAccessor));
}
if (memoryCache == null)
{
throw new ArgumentNullException(nameof(memoryCache));
}
_configuration = configuration;
_httpContextAccessor = httpContextAccessor;
_memoryCache = memoryCache;
}
/// <summary>
/// POST: api/Messages
/// receive a message from a user and send replies
/// </summary>
/// <param name="activity"></param>
[HttpPost]
public virtual async Task<HttpResponseMessage> Post([FromBody] Activity activity)
{
if (activity != null)
{
IConnectorClientFactory factory = new ConnectorClientFactory(Address.FromActivity(activity), new MicrosoftAppCredentials(_configuration, _httpContextAccessor, _memoryCache));
// one of these will have an interface and process it
switch (activity.GetActivityType())
{
case ActivityTypes.Message:
using (IConnectorClient connectorClient = factory.MakeConnectorClient())
{
IBotToUser botToUser = new AlwaysSendDirect_BotToUser(activity, connectorClient);
await botToUser.PostAsync($"HELLO, {activity.From.Name}!");
// .. OR NOT HELPER EXTENSION:
//IMessageActivity msgActivity = botToUser.MakeMessage();
//msgActivity.Text = "HELLO!!! HI!";
//await botToUser.PostAsync(msgActivity);
}
break;
case ActivityTypes.ConversationUpdate:
case ActivityTypes.ContactRelationUpdate:
case ActivityTypes.Typing:
case ActivityTypes.DeleteUserData:
case ActivityTypes.Ping:
default:
//LOG: Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
break;
}
}
return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Moq;
using Witsml;
using Witsml.Data;
using Witsml.ServiceReference;
using WitsmlExplorer.Api.Jobs;
using WitsmlExplorer.Api.Models;
using WitsmlExplorer.Api.Services;
using WitsmlExplorer.Api.Workers;
using Xunit;
namespace WitsmlExplorer.Api.Tests.Workers
{
public class CreateWellWorkerTests
{
private const string WellUid = "wellUid";
private const string WellName = "wellName";
private const string TimeZone = "+02:00";
private const string Field = "SomeField";
private const string Country = "Norway";
private const string Operator = "Equinor";
private readonly Mock<IWitsmlClient> witsmlClient;
private readonly CreateWellWorker worker;
public CreateWellWorkerTests()
{
var witsmlClientProvider = new Mock<IWitsmlClientProvider>();
witsmlClient = new Mock<IWitsmlClient>();
witsmlClientProvider.Setup(provider => provider.GetClient()).Returns(witsmlClient.Object);
worker = new CreateWellWorker(witsmlClientProvider.Object);
}
[Fact]
public async Task MissingUid_Execute_ThrowsException()
{
var job = CreateJobTemplate(null);
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => worker.Execute(job));
Assert.Equal("Uid cannot be empty", exception.Message);
job = CreateJobTemplate("");
exception = await Assert.ThrowsAsync<InvalidOperationException>(() => worker.Execute(job));
Assert.Equal("Uid cannot be empty", exception.Message);
witsmlClient.Verify(client => client.AddToStoreAsync(It.IsAny<WitsmlWells>()), Times.Never);
}
[Fact]
public async Task MissingName_Execute_ThrowsException()
{
var job = CreateJobTemplate(name: null);
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => worker.Execute(job));
Assert.Equal("Name cannot be empty", exception.Message);
job = CreateJobTemplate(name: "");
exception = await Assert.ThrowsAsync<InvalidOperationException>(() => worker.Execute(job));
Assert.Equal("Name cannot be empty", exception.Message);
witsmlClient.Verify(client => client.AddToStoreAsync(It.IsAny<WitsmlWells>()), Times.Never);
}
[Fact]
public async Task MissingTimeZone_Execute_ThrowsException()
{
var job = CreateJobTemplate(timeZone: null);
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => worker.Execute(job));
Assert.Equal("TimeZone cannot be empty", exception.Message);
job = CreateJobTemplate(timeZone: "");
exception = await Assert.ThrowsAsync<InvalidOperationException>(() => worker.Execute(job));
Assert.Equal("TimeZone cannot be empty", exception.Message);
witsmlClient.Verify(client => client.AddToStoreAsync(It.IsAny<WitsmlWells>()), Times.Never);
}
[Fact]
public async Task ValidCreateWellJob_Execute_StoresWellCorrectly()
{
var job = CreateJobTemplate();
var createdWells = new List<WitsmlWells>();
witsmlClient.Setup(client =>
client.AddToStoreAsync(It.IsAny<WitsmlWells>()))
.Callback<WitsmlWells>(wells => createdWells.Add(wells))
.ReturnsAsync(new QueryResult(true));
witsmlClient.Setup(client => client.GetFromStoreAsync(It.IsAny<WitsmlWells>(), It.IsAny<OptionsIn>()))
.ReturnsAsync(new WitsmlWells() { Wells = new List<WitsmlWell>() { new WitsmlWell() }});
await worker.Execute(job);
Assert.Single(createdWells);
Assert.Single(createdWells.First().Wells);
var createdWell = createdWells.First().Wells.First();
Assert.Equal(WellUid, createdWell.Uid);
Assert.Equal(WellName, createdWell.Name);
Assert.Equal(Field, createdWell.Field);
Assert.Equal(Country, createdWell.Country);
Assert.Equal(Operator, createdWell.Operator);
Assert.Equal(TimeZone, createdWell.TimeZone);
}
private static CreateWellJob CreateJobTemplate(string uid = WellUid, string name = WellName, string timeZone = TimeZone,
string field = Field, string country = Country, string @operator = Operator)
{
return new CreateWellJob
{
Well = new Well
{
Uid = uid,
Name = name,
Field = field,
Country = country,
Operator = @operator,
TimeZone = timeZone
}
};
}
}
}
|
using EmitMapper;
using RestLogger.Domain;
using RestLogger.Infrastructure.Service.Model.ApplicationDtos;
namespace RestLogger.Service.Helpers.Mappers.ApplicationMapper
{
internal static class ApplicationMapper
{
public static ApplicationEntity ToApplication(this ApplicationCreateDto applicationCreateDto)
{
return ObjectMapperManager
.DefaultInstance
.GetMapper<ApplicationCreateDto, ApplicationEntity>()
.Map(applicationCreateDto);
}
public static ApplicationDto ToApplicationDto(this ApplicationEntity application)
{
return ObjectMapperManager
.DefaultInstance
.GetMapper<ApplicationEntity, ApplicationDto>()
.Map(application);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class Interests : MonoBehaviour
{
public Text name;
void Start()
{
name.text = PersistentData.UserName + "'s Interests";
}
public static List<string> interests;
public Toggle[] toggles;
public void Finish()
{
foreach (Toggle toggle in toggles)
{
if (toggle.isOn)
{
PersistentData.Interests += toggle.GetComponentInChildren<Text>().text + ",";
}
}
Debug.Log(PersistentData.Interests);
Application.LoadLevel("Home");
}
}
|
using UnityEngine;
using System.Collections;
public class SphereJump : MonoBehaviour {
private enum Status{
None,
Moving
}
[SerializeField]
private float hight = 1;
[SerializeField]
private float speed = 5;
private Status _status = Status.None;
public void Jump(){
if(this._status == Status.None) StartCoroutine(this.DoJump());
}
private IEnumerator Move(Vector3 source , Vector3 target){
float t = 0;
while(t < 1){
transform.position = Vector3.Lerp(source , target , t);
t += Time.deltaTime * this.speed;
yield return null;
}
transform.position = target;
}
private IEnumerator DoJump(){
this._status = Status.Moving;
Vector3 source = transform.position;
Vector3 target = source;
target.y += this.hight;
yield return StartCoroutine(this.Move(source , target));
yield return StartCoroutine(this.Move(target , source));
this._status = Status.None;
}
} |
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Wpf.Model;
using Wpf.ViewModel;
using static Wpf.ViewModel.TestRouteViewModel;
namespace Wpf
{
/// <summary>
/// PavementTypeWindow.xaml 的交互逻辑
/// </summary>
public partial class PavementTypeWindow : Window
{
public PavementType ptSelf = new PavementType();
private PavementType pt = new PavementType();
public PavementTypeWindow(TestRouteViewModel testRouteViewModel, PavementType pts)
{
InitializeComponent();
this.MouseLeftButtonDown += (sender, e) =>
{
if (e.ButtonState == MouseButtonState.Pressed)
{
this.DragMove();
}
};
if (pts != null)
{
this.ptSelf = Mapper<PavementType, PavementType>(pts);
this.DataContext = this.ptSelf;
this.pt = pts;
}
else
{
this.DataContext = this.ptSelf;
}
}
private void Min(object sender, MouseButtonEventArgs e)
{
}
private void Close(object sender, MouseButtonEventArgs e)
{
ptSelf = this.pt;
this.Close();
}
/// <summary>
/// 提交路面类型信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Submit(object sender, RoutedEventArgs e)
{
if (Verify() == true)
{
OKWindow okWindow = new OKWindow("提交数据", "确实要提交这条数据吗?");
okWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
okWindow.ShowDialog();
if (okWindow.Ret == true)
{
this.Close();
}
else {
return;
}
}
else
{
MessageBox.Show("请检查数据格式!");
}
}
/// <summary>
/// 加载图片通用方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LoadImage(object sender, RoutedEventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "jpg图片|*.jpg|png图片|*.png|所有文件|*.*";
fileDialog.ShowDialog();
if (fileDialog.FileName != "")
{
//获取文件名,复制到相对路径下
System.IO.Path.GetFileName(fileDialog.FileName);
var path = Environment.CurrentDirectory + "\\Resources\\Picture\\" + System.IO.Path.GetFileName(fileDialog.FileName);
if (File.Exists(path))
{
MessageBox.Show("文件已存在!");
//return;
}
else
{
File.Copy(fileDialog.FileName, path);
}
this.ptPicture.Source = new BitmapImage(new Uri(path, UriKind.Absolute));
this.ptSelf.Picture = new BitmapImage(new Uri(path, UriKind.Absolute));
//this.img.Source = new BitmapImage(new Uri(@"/Wpf;component/Resources/Picture/" + System.IO.Path.GetFileName(fileDialog.FileName), UriKind.Relative));
}
}
/// <summary>
/// 反射实现两个类的对象之间相同属性的值的复制
/// 适用于初始化新实体
/// </summary>
/// <typeparam name="D">返回的实体</typeparam>
/// <typeparam name="S">数据源实体</typeparam>
/// <param name="s">数据源实体</param>
/// <returns>返回的新实体</returns>
public static D Mapper<D, S>(S s)
{
D d = Activator.CreateInstance<D>(); //构造新实例
try
{
var Types = s.GetType();//获得类型
var Typed = typeof(D);
foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段
{
foreach (PropertyInfo dp in Typed.GetProperties())
{
if (dp.Name == sp.Name && dp.PropertyType == sp.PropertyType && dp.Name != "Error" && dp.Name != "Item")//判断属性名是否相同
{
dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return d;
}
/// <summary>
/// 数据校验
/// </summary>
/// <returns></returns>
private bool Verify()
{
if (this.ptName.Text != "" &&
this.ptLength.Text != "" &&
this.ptPercent.Text != "" &&
this.ptPicture.Source != null &&
this.ptPicture.Source.ToString() != "" )
{
return true;
}
else
{
return false;
}
}
}
}
|
using System;
using Xunit;
namespace Terminal.Gui.TypeTests {
public class SizeTests {
[Fact]
public void Size_New ()
{
var size = new Size ();
Assert.True (size.IsEmpty);
size = new Size (new Point ());
Assert.True (size.IsEmpty);
size = new Size (3, 4);
Assert.False (size.IsEmpty);
Action action = () => new Size (-3, 4);
var ex = Assert.Throws<ArgumentException> (action);
Assert.Equal ("Either Width and Height must be greater or equal to 0.", ex.Message);
action = () => new Size (3, -4);
ex = Assert.Throws<ArgumentException> (action);
Assert.Equal ("Either Width and Height must be greater or equal to 0.", ex.Message);
action = () => new Size (-3, -4);
ex = Assert.Throws<ArgumentException> (action);
Assert.Equal ("Either Width and Height must be greater or equal to 0.", ex.Message);
}
[Fact]
public void Size_SetsValue ()
{
var size = new Size () {
Width = 0,
Height = 0
};
Assert.True (size.IsEmpty);
size = new Size () {
Width = 3,
Height = 4
};
Assert.False (size.IsEmpty);
Action action = () => {
size = new Size () {
Width = -3,
Height = 4
};
};
var ex = Assert.Throws<ArgumentException> (action);
Assert.Equal ("Width must be greater or equal to 0.", ex.Message);
action = () => {
size = new Size () {
Width = 3,
Height = -4
};
};
ex = Assert.Throws<ArgumentException> (action);
Assert.Equal ("Height must be greater or equal to 0.", ex.Message);
action = () => {
size = new Size () {
Width = -3,
Height = -4
};
};
ex = Assert.Throws<ArgumentException> (action);
Assert.Equal ("Width must be greater or equal to 0.", ex.Message);
}
[Fact]
public void Size_Equals ()
{
var size1 = new Size ();
var size2 = new Size ();
Assert.Equal (size1, size2);
size1 = new Size (3, 4);
size2 = new Size (3, 4);
Assert.Equal (size1, size2);
size1 = new Size (3, 4);
size2 = new Size (4, 4);
Assert.NotEqual (size1, size2);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoginButton_Click(object sender, EventArgs e)
{
string username = UserNameTextbox.Text.Trim();
string password = PasswordTextbox.Text.Trim();
if (username.Length > 0 && password.Length > 0)
{
string errorMessage;
CookieContainer cookieContainer;
ServiceNow serviceNow = new ServiceNow();
if (serviceNow.Authenticate(username, password, out cookieContainer, out errorMessage))
{
//SetAllCookies(cookieContainer);
Session.Add("ServiceNowCookies", cookieContainer);
// Load all of the users from the "CommonUsers.xml" file
ServiceNowUser.LoadCommonUsers(cookieContainer);
Response.Redirect("WorkList.aspx");
}
else
{
ErrorMessageLabel.Text = errorMessage;
}
}
}
/*
private void SetAllCookies(CookieContainer cookieContainer)
{
SetCookies(cookieContainer.GetCookies(new Uri("https://dsp.davita.com")));
SetCookies(cookieContainer.GetCookies(new Uri("https://davita.service-now.com")));
SetCookies(cookieContainer.GetCookies(new Uri("https://sso.davita.com")));
}
private void SetCookies(CookieCollection cookies)
{
foreach (Cookie cookie in cookies)
{
HttpCookie httpCookie = new HttpCookie(cookie.Name);
httpCookie.Domain = cookie.Domain;
httpCookie.Expires = cookie.Expires;
httpCookie.Name = cookie.Name;
httpCookie.Path = cookie.Path;
httpCookie.Secure = cookie.Secure;
httpCookie.Value = cookie.Value;
Response.Cookies.Add(httpCookie);
}
}
*/
} |
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 TableroComando.Dominio;
using Dominio;
using TableroComando.GUIWrapper;
using System.Windows.Forms.DataVisualization.Charting;
using System.Globalization;
using TableroComando.Clases;
using System.IO;
namespace TableroComando.Formularios
{
public partial class Form_InformeIndicador : Form
{
Indicador Indicador;
System.Windows.Forms.DataVisualization.Charting.Chart chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
System.Windows.Forms.DataVisualization.Charting.Series Series1 = new Series();
Series Series2 = new Series();
ChartArea ChartArea1 = new ChartArea();
public Form_InformeIndicador(Indicador indicador)
{
this.Indicador = indicador;
InitializeComponent();
}
private void BtnGenerarReporte_Click(object sender, EventArgs e)
{
Reportes.DsIndicador DsIndicador = new Reportes.DsIndicador();
// Cargo el grafico en la carpeta Temp
Chart chart1 = new Chart();
chart1.Width = 600;
chart1 = Clases.GraficoIndicador.Grafico(chart1, Indicador, dateTimePicker1.Value, dateTimePicker2.Value);
ChartImageFormat format = ChartImageFormat.Png;
chart1.SaveImage(Application.StartupPath + "\\TempGrafico.png", format);
// Cargo el Indicador
DataRow Filaindicador = DsIndicador.Tables["indicadores"].NewRow();
Filaindicador["Id"] = Indicador.Id;
Filaindicador["nombre"] = Indicador.Nombre;
Filaindicador["codigo"] = Indicador.Codigo;
Filaindicador["responsable_id"] = Indicador.Responsable.Id;
Filaindicador["frecuencia_id"] = Indicador.Frecuencia.Id;
Filaindicador["Grafico"] =Clases.Herramientas.ConversionImagen(Application.StartupPath + "\\TempGrafico.png");
// Cargo el color segun el estado
Color Color = VisualHelper.GetColor(Indicador.Estado);
int? ColorInd = null;
if (Color == System.Drawing.Color.Green) ColorInd = 1;
else
if (Color == System.Drawing.Color.Yellow) ColorInd = 0;
else
if (Color == System.Drawing.Color.Red) ColorInd = -1;
else
if (Color == System.Drawing.Color.White) ColorInd = 2;
Filaindicador["Color"] = ColorInd;
DsIndicador.Tables["indicadores"].Rows.Add(Filaindicador);
DsIndicador.Tables["indicadores"].AcceptChanges();
// Cargo el responsable
DataRow FilaResponsable = DsIndicador.Tables["responsables"].NewRow();
FilaResponsable["Id"] = Indicador.Responsable.Id;
FilaResponsable["Area"] = Indicador.Responsable.Area;
FilaResponsable["Persona"] = Indicador.Responsable.Persona;
FilaResponsable["Codigo"] = Indicador.Responsable.Codigo;
DsIndicador.Tables["responsables"].Rows.Add(FilaResponsable);
DsIndicador.Tables["responsables"].AcceptChanges();
// Cargo la Frecuencia
DataRow FilaFrecuencia = DsIndicador.Tables["frecuencias"].NewRow();
FilaFrecuencia["Id"] = Indicador.Frecuencia.Id;
FilaFrecuencia["Periodo"] = Indicador.Frecuencia.Periodo;
DsIndicador.Tables["frecuencias"].Rows.Add(FilaFrecuencia);
DsIndicador.Tables["frecuencias"].AcceptChanges();
// Cargo Las mediciones
foreach(Medicion medicion in Indicador.Mediciones)
{
if ((medicion.Fecha.Date >= dateTimePicker1.Value) & (medicion.Fecha.Date <= dateTimePicker2.Value))
{
DataRow FilaMedicion = DsIndicador.Tables["mediciones"].NewRow();
FilaMedicion["Id"] = medicion.Id;
FilaMedicion["Detalle"] = medicion.Detalle;
FilaMedicion["Fecha"] = medicion.Fecha.Date;
FilaMedicion["Valor"] = medicion.Valor;
FilaMedicion["indicador_id"] = medicion.Indicador.Id;
//FilaMedicion["frecuencia_id"] = medicion.Frecuencia.Id;
DsIndicador.Tables["mediciones"].Rows.Add(FilaMedicion);
}
}
DsIndicador.Tables["mediciones"].AcceptChanges();
Reportes.CrIndicadores reporte = new Reportes.CrIndicadores();
reporte.SetDataSource(DsIndicador);
// Fecha de Medición
reporte.SetParameterValue("FechaDesde", dateTimePicker1.Value.Date);
reporte.SetParameterValue("FechaHasta", dateTimePicker2.Value.Date);
crystalReportViewer1.ReportSource = reporte;
crystalReportViewer1.Refresh();
}
private void Form_InformeIndicador_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CustomReviewModule.Data.Model;
using VirtoCommerce.Platform.Core.Common;
using VirtoCommerce.Platform.Data.Infrastructure;
using VirtoCommerce.Platform.Data.Infrastructure.Interceptors;
namespace CustomReviewModule.Data.Repository
{
public class ReviewRepository : EFRepositoryBase, IReviewRepository
{
public ReviewRepository()
{
}
public ReviewRepository(string nameOrConnectionString, params IInterceptor[] interceptors)
: base(nameOrConnectionString, null, interceptors)
{
Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Review>().HasKey(x => x.Id).Property(x => x.Id);
modelBuilder.Entity<Review>().ToTable("Review");
base.OnModelCreating(modelBuilder);
}
public IQueryable<Review> Reviews
{
get { return GetAsQueryable<Review>(); }
}
public Review GetReviewById( string id)
{
return Reviews.FirstOrDefault(x => x.Id == id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using UFO.Server;
using UFO.Server.Data;
namespace UFO.WebService.Controllers {
public class CategoryController : ApiController {
private ICategoryService cs;
public CategoryController() {
IDatabase db = DatabaseConnection.GetDatabase();
cs = ServiceFactory.CreateCategoryService(db);
}
[HttpGet]
public Category GetCategoryById(uint id) {
return cs.GetCategoryById(id);
}
[HttpGet]
public Category[] GetAllCategories() {
return cs.GetAllCategories().ToArray();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Автошкола
{
public partial class AddEditReplacementCarrierForm : Form
{
public AddEditReplacementCarrierForm(AutoschoolDataSet.ReplacementsCarriersDataTable replacementsCarriersDataTable,
AutoschoolDataSet.CarriersUsesDataTable carriersUsesDataTable, AutoschoolDataSet.CarriersDataTable carriersDataTable,
AutoschoolDataSet.InstructorsDataTable instructorsDataTable,
DataRow row)
{
InitializeComponent();
this.replacementsCarriersDataTable = replacementsCarriersDataTable;
this.carriersUsesDataTable = carriersUsesDataTable;
this.carriersDataTable = carriersDataTable;
this.instructorsDataTable = instructorsDataTable;
dataRow = row;
}
BusinessLogic BusinessLogic = new BusinessLogic();
AutoschoolDataSet.ReplacementsCarriersDataTable replacementsCarriersDataTable;
AutoschoolDataSet.CarriersUsesDataTable carriersUsesDataTable;
AutoschoolDataSet.CarriersDataTable carriersDataTable;
AutoschoolDataSet.InstructorsDataTable instructorsDataTable;
DataRow dataRow;
AutoschoolDataSet dataSetForReplaceableCarriers, dataSetForReplacingCarriers;
int SelectedReplaceableCarrierID = -1;
int SelectedReplacingCarrierID = -1;
bool FormLoad = false;
string LastReplaceableCarrierSearchingText = "";
int LastReplaceableCarrierFoundRow = -1;
string LastReplacingCarrierSearchingText = "";
int LastReplacingCarrierFoundRow = -1;
void ReloadReplaceableCarriers(int InstructorID)
{
ReplaceableCarriers_dataGridView.Rows.Clear();
dataSetForReplaceableCarriers = BusinessLogic.ReadCarriersByInstructorID(InstructorID);
// заполняем dataGridView
for (int i = 0; i < dataSetForReplaceableCarriers.Carriers.Rows.Count; i++)
{
ReplaceableCarriers_dataGridView.Rows.Add(dataSetForReplaceableCarriers.Carriers[i]["ID"],
dataSetForReplaceableCarriers.Carriers[i]["Brand"],
dataSetForReplaceableCarriers.Carriers[i]["Model"],
dataSetForReplaceableCarriers.Carriers[i]["StateNumber"],
dataSetForReplaceableCarriers.Carriers[i]["Color"],
dataSetForReplaceableCarriers.Transmissions.Rows.Find(dataSetForReplaceableCarriers.Carriers[i]["Transmission"])["Transmission"],
dataSetForReplaceableCarriers.Categories.Rows.Find(dataSetForReplaceableCarriers.Carriers[i]["Category"])["Name"],
dataSetForReplaceableCarriers.CarriersStatuses.Rows.Find(dataSetForReplaceableCarriers.Carriers[i]["Status"])["Name"],
dataSetForReplaceableCarriers.Carriers[i]["FinalName"]);
}
/*ReplaceableCarriers_dataGridView.DataSource = dataSetForReplaceableCarriers;
ReplaceableCarriers_dataGridView.DataMember = "Carriers";
ReplaceableCarriers_dataGridView.Columns["ID"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["Brand"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["Model"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["StateNumber"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["Color"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["Transmission"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["Category"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["Status"].Visible = false;
ReplaceableCarriers_dataGridView.Columns["FinalName"].Visible = false;
ID1Column.DataPropertyName = "ID";
Brand1Column.DataPropertyName = "Brand";
Model1Column.DataPropertyName = "Model";
StateNumber1Column.DataPropertyName = "StateNumber";
Color1Column.DataPropertyName = "Color";
Transmission1Column.DataSource = dataSetForReplaceableCarriers.Transmissions;
Transmission1Column.DisplayMember = "Transmission";
Transmission1Column.ValueMember = "ID";
Transmission1Column.DataPropertyName = "Transmission";
Category1Column.DataSource = dataSetForReplaceableCarriers.Categories;
Category1Column.DisplayMember = "Name";
Category1Column.ValueMember = "ID";
Category1Column.DataPropertyName = "Category";
Status1Column.DataSource = dataSetForReplaceableCarriers.CarriersStatuses;
Status1Column.DisplayMember = "Name";
Status1Column.ValueMember = "ID";
Status1Column.DataPropertyName = "Status";
*/
}
private void BeginReplacement_dateTimePicker_ValueChanged(object sender, EventArgs e)
{
EndReplacement_dateTimePicker.MinDate = Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date;
}
void ReloadReplacingCarriers()
{
dataSetForReplacingCarriers = BusinessLogic.ReadCarriersByStatusName("Резерв");
ReplacingCarriers_dataGridView.DataSource = dataSetForReplacingCarriers;
ReplacingCarriers_dataGridView.DataMember = "Carriers";
ReplacingCarriers_dataGridView.Columns["ID"].Visible = false;
ReplacingCarriers_dataGridView.Columns["Brand"].Visible = false;
ReplacingCarriers_dataGridView.Columns["Model"].Visible = false;
ReplacingCarriers_dataGridView.Columns["StateNumber"].Visible = false;
ReplacingCarriers_dataGridView.Columns["Color"].Visible = false;
ReplacingCarriers_dataGridView.Columns["Transmission"].Visible = false;
ReplacingCarriers_dataGridView.Columns["Category"].Visible = false;
ReplacingCarriers_dataGridView.Columns["Status"].Visible = false;
ReplacingCarriers_dataGridView.Columns["FinalName"].Visible = false;
ID2Column.DataPropertyName = "ID";
Brand2Column.DataPropertyName = "Brand";
Model2Column.DataPropertyName = "Model";
StateNumber2Column.DataPropertyName = "StateNumber";
Color2Column.DataPropertyName = "Color";
Transmission2Column.DataSource = dataSetForReplacingCarriers.Transmissions;
Transmission2Column.DisplayMember = "Transmission";
Transmission2Column.ValueMember = "ID";
Transmission2Column.DataPropertyName = "Transmission";
Category2Column.DataSource = dataSetForReplacingCarriers.Categories;
Category2Column.DisplayMember = "Name";
Category2Column.ValueMember = "ID";
Category2Column.DataPropertyName = "Category";
Status2Column.DataSource = dataSetForReplacingCarriers.CarriersStatuses;
Status2Column.DisplayMember = "Name";
Status2Column.ValueMember = "ID";
Status2Column.DataPropertyName = "Status";
if (ReplacingCarriers_dataGridView.RowCount == 1)
{
ReplacingCarriers_dataGridView.Rows[0].Cells["Brand2Column"].Selected = true;
ChangeSelectedReplacingCarrier();
}
}
void ChangeSelectedReplaceableCarrier()
{
if (ReplaceableCarriers_dataGridView.RowCount > 0 && ReplaceableCarriers_dataGridView.SelectedRows.Count > 0)
{
int CurRow = ReplaceableCarriers_dataGridView.SelectedRows[0].Index;
SelectedReplaceableCarrierID = Convert.ToInt32(ReplaceableCarriers_dataGridView[0, CurRow].Value);
SelectedReplaceableCarrier_label.Text = ReplaceableCarriers_dataGridView["FinalName", CurRow].Value.ToString();
}
else
{
SelectedReplaceableCarrierID = -1;
SelectedReplaceableCarrier_label.Text = "";
}
}
private void AddEditReplacementCarrierForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (DialogResult == DialogResult.OK)
{
try
{
if (Instructor_comboBox.SelectedIndex == -1)
{
Instructor_comboBox.Focus();
throw new Exception("Не выбран инструктор");
}
AutoschoolDataSet TempDS = new AutoschoolDataSet();
TempDS = BusinessLogic.ReadInstructorByID(Convert.ToInt32(Instructor_comboBox.SelectedValue.ToString()));
if (TempDS.Instructors[0]["WorkStatusName"].ToString() != "Работает")
{
DialogResult result = MessageBox.Show("Вы выбрали отсутствующего инструктора. Вы уверены, что хотите продолжить?", "Выбор отсутствующего сотрудника", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
e.Cancel = true;
return;
}
}
if (SelectedReplaceableCarrierID == -1)
{
throw new Exception("Не выбрано заменяемое ТС");
}
if (SelectedReplacingCarrierID == -1)
{
throw new Exception("Не выбрано заменяющее ТС");
}
TempDS = BusinessLogic.ReadReplacementsCarriersByCarrierUseID(Convert.ToInt32(BusinessLogic.ReadCarriersUsesByInstructorCarrierID(Convert.ToInt32(Instructor_comboBox.SelectedValue), Convert.ToInt32(ReplaceableCarriers_dataGridView.SelectedRows[0].Cells["ID1Column"].Value)).CarriersUses[0]["ID"].ToString()));
if (dataRow != null)
{
for (int i = 0; i < TempDS.ReplacementsCarriers.Rows.Count; i++)
{
if (dataRow["ID"].ToString() == TempDS.ReplacementsCarriers.Rows[i]["ID"].ToString())
continue;
DateTime BeginReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateBeginReplacement"].ToString()).Date;
DateTime EndReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateEndReplacement"].ToString()).Date;
DateTime Begin = Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date;
DateTime End = Convert.ToDateTime(EndReplacement_dateTimePicker.Text).Date;
if (BeginReplacementInBdRow > Begin && End < BeginReplacementInBdRow)
continue;
if (EndReplacementInBdRow < Begin)
continue;
else
{
throw new Exception("Выбранное заменяемое ТС у данного водителя уже заменяется в указанное время");
}
}
}
else
{
for (int i = 0; i < TempDS.ReplacementsCarriers.Rows.Count; i++)
{
DateTime BeginReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateBeginReplacement"].ToString()).Date;
DateTime EndReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateEndReplacement"].ToString()).Date;
DateTime Begin = Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date;
DateTime End = Convert.ToDateTime(EndReplacement_dateTimePicker.Text).Date;
if (BeginReplacementInBdRow > Begin && End < BeginReplacementInBdRow)
continue;
if (EndReplacementInBdRow < Begin)
continue;
else
{
throw new Exception("Выбранное заменяемое ТС у данного водителя уже заменяется в указанное время");
}
}
}
TempDS = BusinessLogic.ReadReplacementsCarriersByCarrierReplacementID(SelectedReplacingCarrierID);
if (dataRow != null)
{
for (int i = 0; i < TempDS.ReplacementsCarriers.Rows.Count; i++)
{
if (dataRow["ID"].ToString() == TempDS.ReplacementsCarriers.Rows[i]["ID"].ToString())
continue;
DateTime BeginReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateBeginReplacement"].ToString()).Date;
DateTime EndReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateEndReplacement"].ToString()).Date;
DateTime Begin = Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date;
DateTime End = Convert.ToDateTime(EndReplacement_dateTimePicker.Text).Date;
if (BeginReplacementInBdRow > Begin && End < BeginReplacementInBdRow)
continue;
if (EndReplacementInBdRow < Begin)
continue;
else
{
throw new Exception("Выбранное заменяющее ТС уже используется в указанное время");
}
}
}
else
{
for (int i = 0; i < TempDS.ReplacementsCarriers.Rows.Count; i++)
{
DateTime BeginReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateBeginReplacement"].ToString()).Date;
DateTime EndReplacementInBdRow = Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateEndReplacement"].ToString()).Date;
DateTime Begin = Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date;
DateTime End = Convert.ToDateTime(EndReplacement_dateTimePicker.Text).Date;
if (BeginReplacementInBdRow > Begin && End < BeginReplacementInBdRow)
continue;
if (EndReplacementInBdRow < Begin)
continue;
else
{
throw new Exception("Выбранное заменяющее ТС уже используется в указанное время");
}
}
}
TempDS = BusinessLogic.ReadByCarrierID_AND_CrossInBeginEndDates(
SelectedReplacingCarrierID,
Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date,
Convert.ToDateTime(EndReplacement_dateTimePicker.Text).Date);
if (TempDS.CarriersRepairs.Rows.Count > 0)
{
throw new Exception("Выбранное заменяющее ТС само находится в ремонте в одни из указанных дней");
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "Ошибка");
e.Cancel = true;
return;
}
int CarrierUseID = Convert.ToInt32(BusinessLogic.ReadCarriersUsesByInstructorCarrierID(Convert.ToInt32(Instructor_comboBox.SelectedValue), Convert.ToInt32(ReplaceableCarriers_dataGridView.SelectedRows[0].Cells["ID1Column"].Value)).CarriersUses[0]["ID"].ToString());
if (dataRow != null)
{
dataRow["CarrierUse"] = CarrierUseID;
dataRow["CarrierReplacement"] = SelectedReplacingCarrierID;
dataRow["DateBeginReplacement"] = Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date;
dataRow["DateEndReplacement"] = Convert.ToDateTime(EndReplacement_dateTimePicker.Text).Date;
}
else
{
replacementsCarriersDataTable.AddReplacementsCarriersRow((AutoschoolDataSet.CarriersUsesRow)carriersUsesDataTable.Rows.Find(CarrierUseID),
(AutoschoolDataSet.CarriersRow)carriersDataTable.Rows.Find(SelectedReplacingCarrierID),
Convert.ToDateTime(BeginReplacement_dateTimePicker.Text).Date,
Convert.ToDateTime(EndReplacement_dateTimePicker.Text).Date);
}
}
}
private void ReplaceableCarriers_dataGridView_SelectionChanged(object sender, EventArgs e)
{
if (FormLoad)
ChangeSelectedReplaceableCarrier();
}
void InstructorChanged()
{
if (Instructor_comboBox.SelectedIndex != -1 && FormLoad)
{
// отбираем ТС, прикрепленные к выбранному инструктору
ReloadReplaceableCarriers(Convert.ToInt32(Instructor_comboBox.SelectedValue));
if (ReplaceableCarriers_dataGridView.RowCount == 0)
{
MessageBox.Show("У выбранного инструктора отсутствуют прикрепленные ТС. \nДо тех пор, пока инструктору не будет прикреплено хотя бы одно ТС, добавление замены ТС этого инструктора невозможно.", "Ошибка");
}
}
else
{
ReplaceableCarriers_dataGridView.Rows.Clear();
}
SelectedReplaceableCarrier_label.Text = "";
SelectedReplaceableCarrierID = -1;
if (ReplaceableCarriers_dataGridView.RowCount == 1)
{
ReplaceableCarriers_dataGridView.Rows[0].Cells["Brand1Column"].Selected = true;
ChangeSelectedReplaceableCarrier();
}
}
private void Instructor_comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (FormLoad)
InstructorChanged();
}
private void ReplacingCarriers_dataGridView_SelectionChanged(object sender, EventArgs e)
{
if (FormLoad)
ChangeSelectedReplacingCarrier();
}
private void ReloadInstructors_button_Click(object sender, EventArgs e)
{
instructorsDataTable = BusinessLogic.ReadInstructors().Instructors;
}
private void ReloadReplaceableCarriers_button_Click(object sender, EventArgs e)
{
InstructorChanged();
ChangeSelectedReplaceableCarrier();
}
private void ReloadReplacingCarriers_button_Click(object sender, EventArgs e)
{
ReloadReplacingCarriers();
}
void ChangeSelectedReplacingCarrier()
{
if (ReplacingCarriers_dataGridView.SelectedRows.Count > 0)
{
int CurRow = ReplacingCarriers_dataGridView.SelectedRows[0].Index;
SelectedReplacingCarrierID = Convert.ToInt32(ReplacingCarriers_dataGridView[0, CurRow].Value);
SelectedReplacingCarrier_label.Text = ReplacingCarriers_dataGridView["FinalName", CurRow].Value.ToString();
}
else
{
SelectedReplacingCarrierID = -1;
SelectedReplacingCarrier_label.Text = "";
}
}
private void SearchReplaceableCarrier_button_Click(object sender, EventArgs e)
{
SearchingInDataGridViewClass.Search(SearchReplaceableCarrier_textBox, ref ReplaceableCarriers_dataGridView,
DirectionReplaceableCarrier_checkBox, ref LastReplaceableCarrierSearchingText, ref LastReplaceableCarrierFoundRow,
"Brand1Column", "Model1Column", "StateNumber1Column");
}
private void SearchReplaceableCarrier_textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char)e.KeyChar == (Char)Keys.Enter)
{
SearchReplaceableCarrier_button_Click(sender, e);
}
if ((char)e.KeyChar == (Char)Keys.Back)
{
LastReplaceableCarrierSearchingText = "";
}
}
private void SearchReplacingCarrier_button_Click(object sender, EventArgs e)
{
SearchingInDataGridViewClass.Search(SearchReplacingCarrier_textBox, ref ReplacingCarriers_dataGridView,
DirectionReplacingCarrier_checkBox, ref LastReplacingCarrierSearchingText, ref LastReplacingCarrierFoundRow,
"Brand2Column", "Model2Column", "StateNumber2Column");
}
private void SearchReplacingCarrier_textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char)e.KeyChar == (Char)Keys.Enter)
{
SearchReplacingCarrier_button_Click(sender, e);
}
if ((char)e.KeyChar == (Char)Keys.Back)
{
LastReplacingCarrierSearchingText = "";
}
}
private void AddEditReplacementCarrierForm_Load(object sender, EventArgs e)
{
Instructor_comboBox.DataSource = instructorsDataTable;
Instructor_comboBox.DisplayMember = "FIO";
Instructor_comboBox.ValueMember = "ID";
Instructor_comboBox.AutoCompleteMode = AutoCompleteMode.Append;
Instructor_comboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
ReloadReplacingCarriers();
FormLoad = true;
if (dataRow != null)
{
int InstructorID = Convert.ToInt32(BusinessLogic.ReadCarriersUsesByID(Convert.ToInt32(dataRow[1].ToString())).CarriersUses.Rows[0][1].ToString());
Instructor_comboBox.SelectedValue = InstructorID;
ReloadReplaceableCarriers(InstructorID);
// получаем ТС из CarrierUses
int CarrierID = Convert.ToInt32(carriersUsesDataTable.Rows.Find(dataRow["CarrierUse"].ToString())[2].ToString());
// находим ТС среди заменяемых
if (ReplaceableCarriers_dataGridView.Rows.Count > 0)
{
for (int i = 0; i < ReplaceableCarriers_dataGridView.Rows.Count; i++)
{
if (CarrierID == Convert.ToInt32(ReplaceableCarriers_dataGridView["ID1Column", i].Value))
{
ReplaceableCarriers_dataGridView.Rows[i].Cells["Brand1Column"].Selected = true;
ChangeSelectedReplaceableCarrier();
break;
}
}
}
// находим ТС среди заменяющих
if (ReplacingCarriers_dataGridView.Rows.Count > 0)
{
for (int i = 0; i < ReplacingCarriers_dataGridView.Rows.Count; i++)
{
if (Convert.ToInt32(dataRow["CarrierReplacement"].ToString()) == Convert.ToInt32(ReplacingCarriers_dataGridView["ID2Column", i].Value))
{
ReplacingCarriers_dataGridView.Rows[i].Cells["Brand2Column"].Selected = true;
ChangeSelectedReplacingCarrier();
break;
}
}
}
BeginReplacement_dateTimePicker.Text = dataRow["DateBeginReplacement"].ToString();
EndReplacement_dateTimePicker.Text = dataRow["DateEndReplacement"].ToString();
}
else
{
Instructor_comboBox.SelectedIndex = -1;
ReplaceableCarriers_dataGridView.CurrentCell = null;
ReplacingCarriers_dataGridView.CurrentCell = null;
}
BeginReplacement_dateTimePicker_ValueChanged(sender, e);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace ManillenWPhone.Models
{
public class Player
{
#region Properties
public ObservableCollection<Card> PlayerCards { get; set; }
public ObservableCollection<Card> PlayerUpField { get; set; }
public ObservableCollection<Card> PlayerDownField { get; set; }
public ObservableCollection<Card> PlayerScoredCards { get; set; }
#endregion
#region Fields
protected List<Card> allowedCardList;
#endregion
public Player()
{
PlayerCards = new ObservableCollection<Card>();
PlayerScoredCards = new ObservableCollection<Card>();
PlayerUpField = new ObservableCollection<Card>();
PlayerDownField = new ObservableCollection<Card>();
}
#region Events
public event DealedNewCardEventHandler DealedNewCard;
#endregion
#region Virtual Methods
protected virtual void OnDealedNewCard()
{
if (DealedNewCard != null)
DealedNewCard(this);
}
#endregion
#region Public Methods
#region Add Methods
public void AddPlayerCard(Card card)
{
PlayerCards.Add(card);
OnDealedNewCard();
}
public void AddPlayerUpFieldCard(Card card)
{
PlayerUpField.Add(card);
OnDealedNewCard();
}
public void AddPlayerDownFieldCard(Card card)
{
PlayerDownField.Add(card);
OnDealedNewCard();
}
public void AddPlayerScoredCards(Card card)
{
PlayerScoredCards.Add(card);
}
#endregion
public void SortPlayersHand()
{
List<Card> lstCards = PlayerCards.ToList();
lstCards.Sort();
PlayerCards = new ObservableCollection<Card>();
foreach (var ca in lstCards)
PlayerCards.Add(ca);
OnDealedNewCard();
}
public int GetScore()
{
int counter = PlayerScoredCards.Where(card => card.Number > 9).Sum(card => (card.Number - 9));
return counter;
}
public bool IsOutOfCards()
{
return (PlayerCards.Count + PlayerUpField.Count(card => card != null)) == 0;
}
public void PlayCard(Card card)
{
if (PlayerCards.Contains(card))
PlayerCards.Remove(card);
if (PlayerUpField.Contains(card))
{
int place = PlayerUpField.IndexOf(card);
if (PlayerDownField[place] != null)
{
PlayerUpField[place] = PlayerDownField[place];
PlayerDownField[place] = null;
}
else
PlayerUpField[place] = null;
}
}
public bool PlayCard(Card card, Card fieldcard, Suit troef)
{
if (GetAllowedCards(fieldcard, troef).Contains(card))
{
if (PlayerCards.Contains(card))
PlayerCards.Remove(card);
if (PlayerUpField.Contains(card))
{
int place = PlayerUpField.IndexOf(card);
if (PlayerDownField[place] != null)
{
PlayerUpField[place] = PlayerDownField[place];
PlayerDownField[place] = null;
}
else
PlayerUpField[place] = null;
}
return true;
}
return false;
}
#endregion
#region Protected Methods
protected List<Card> GetAllowedCards(Card fieldCard, Suit troef)
{
List<Card> lstAllowedCards = new List<Card>();
lstAllowedCards.AddRange(
PlayerCards.Where(card => card.Number > fieldCard.Number && fieldCard.Suit == card.Suit));
lstAllowedCards.AddRange(
PlayerUpField.Where(
card => card != null && card.Number > fieldCard.Number && fieldCard.Suit == card.Suit));
if (lstAllowedCards.Count > 0)
return lstAllowedCards;
lstAllowedCards.AddRange(PlayerCards.Where(card => fieldCard.Suit == card.Suit));
lstAllowedCards.AddRange(PlayerUpField.Where(card => card != null && fieldCard.Suit == card.Suit));
if (lstAllowedCards.Count > 0)
return lstAllowedCards;
lstAllowedCards.AddRange(PlayerCards.Where(card => troef == card.Suit));
lstAllowedCards.AddRange(PlayerUpField.Where(card => card != null && troef == card.Suit));
if (lstAllowedCards.Count > 0)
return lstAllowedCards;
lstAllowedCards.AddRange(PlayerCards);
lstAllowedCards.AddRange(PlayerUpField.Where(card => card != null));
return lstAllowedCards;
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OTouchPickUp : MonoBehaviour
{
// Use this for initialization
void Start()
{
mask = 1 << LayerMask.NameToLayer("Interactable");
col = GetComponent<SphereCollider>();
myRigid = GetComponent<Rigidbody>();
myBeam.SetActive(false);
if (hand == Hands.LeftHand)
{
handTrigger = OVRInput.Axis1D.PrimaryHandTrigger;
}
else
{
handTrigger = OVRInput.Axis1D.SecondaryHandTrigger;
}
}
public bool grabbing;
public SphereCollider col;
public Hands hand;
OVRInput.Axis1D handTrigger;
Rigidbody myRigid;
GameObject grabbedObject;
//public Transform lTouchController, rTouchController;
public ControllerButton[] myButton;
public GameObject myBeam;
public bool teleGrab=false;
// Update is called once per frame
RaycastHit hit;
int mask;
void FixedUpdate()
{
//OVRInput.Update();
MyButtonUpdate();
if (OVRInput.Get(handTrigger) > 0)
{
grabbing = true;
//Debug.Log(OVRInput.Get( OVRInput.Axis1D.PrimaryHandTrigger) +" ; "+OVRInput.Get( OVRInput.Axis1D.SecondaryHandTrigger));
if (grabbedObject == null)
{
if (myBeam.activeSelf && teleGrab)
{
GameObject hitTarget;
if(CastRayForGrabable(out hitTarget)){
GrabableObject script = hitTarget.GetComponent<GrabableObject>();
if (script != null)
{
script.OnGrab(myRigid);
grabbedObject = hitTarget;
}
}
}
else
{
Collider[] colObjects = Physics.OverlapSphere(transform.position, col.radius, mask);
//Debug.Log("Amount: "+colObjects.Length);
GrabableObject script;
for (int i = 0; i < colObjects.Length; i++)
{
script = colObjects[i].attachedRigidbody.GetComponent<GrabableObject>();
if (script.grabJoint == null)
{
script.OnGrab(myRigid);
grabbedObject = colObjects[i].attachedRigidbody.gameObject;
break;
}
}
}
}
}
else
{
grabbing = false;
if (grabbedObject != null)
{
grabbedObject.GetComponent<GrabableObject>().Release();
grabbedObject = null;
}
}
/*if(myButton[0].state == ButtonStates.Pressed){
Debug.Log("Button 0 pressed on "+gameObject.name+" pressed");
CastRayForMarkable();
}*/
if(myBeam.activeSelf){
if(CastRayForMenu())
if(myButton[0].state == ButtonStates.Pressed && hitButton!=null)
hitButton.GetComponent<MenuButton>().OnClick();
} else {
hitButton = null;
}
if(myBeam.activeSelf && myButton[0].state == ButtonStates.Pressed && hitButton == null){
if(!CastRayForMarkable()){
CreateMark();
}
}
if (myButton[1].state == ButtonStates.Pressed)
{
//Debug.Log("Button 1 pressed on " + gameObject.name + " pressed");
myBeam.SetActive(true);
} else if (myButton[1].state == ButtonStates.LetGo){
myBeam.SetActive(false);
}
if(myBeam.activeSelf && myButton[2].state == ButtonStates.Pressed){
Vector3 targetPos;
if(CastRayForGround(out targetPos)){
VRMove.singleton.TeleportToPosition(targetPos);
}
}
}
float castRadius = 0.2f;
RaycastHit[] hits;
public GameObject hitButton;
public bool CastRayForMenu(){
//Debug.Log("casting ray");
RaycastHit hit;
int newMask = 1 << LayerMask.NameToLayer("OtherUI");
if(Physics.Raycast(transform.position,transform.forward,out hit, 25,newMask)){
hitButton = hit.collider.gameObject;
//hitButton.Select();
//Debug.Log(hitButton.name);
return true;
} else {
hitButton = null;
return false;
}
}
public bool CastRayForGrabable(out GameObject targetHit){
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 100, mask))
{
targetHit = hit.collider.gameObject;
//hitButton.Select();
//Debug.Log(hitButton.name);
return true;
}
else
{
targetHit = null;
return false;
}
}
public bool CastRayForMarkable()
{
bool myBool=false;
hits = Physics.SphereCastAll(transform.position, castRadius, transform.forward, 10, mask);
if (hits.Length > 0)
{
for (int i = 0; i < hits.Length; i++)
{
/*
MarkableObject script;
script = hits[i].collider.attachedRigidbody.GetComponent<MarkableObject>();
if (script != null && !script.marked)
{
script.Mark();
break;
}*/
MenuObject script;
script = hits[i].collider.attachedRigidbody.GetComponent<MenuObject>();
if(script != null && !script.marked){
script.Mark(hits[i].point + Vector3.up*0.75f);
myBool=true;
break;
}
}
}
return myBool;
}
public bool CastRayForGround(out Vector3 _position){
//Debug.Log("casting for ground");
RaycastHit hit;
int groundMask = 1 << LayerMask.NameToLayer("Teleportable");
if(Physics.Raycast(transform.position,transform.forward,out hit,100f,groundMask)){
//Debug.Log("hit "+hit.collider.name);
_position = hit.point;
return true;
}
_position = Vector3.zero;
return false;
}
public void MyButtonUpdate(){
for(int i=0; i < myButton.Length; i++){
myButton[i].value = OVRInput.Get(myButton[i].ovrButton);
if(myButton[i].value){
if(!myButton[i].lastValue){
myButton[i].state = ButtonStates.Pressed;
} else {
myButton[i].state = ButtonStates.Held;
}
} else {
if(myButton[i].lastValue){
myButton[i].state = ButtonStates.LetGo;
} else {
myButton[i].state = ButtonStates.NotPressed;
}
}
myButton[i].lastValue = myButton[i].value;
}
}
public void CreateMark()
{
//Vector3 spawnPos = transform.position + new Vector3(Random.Range(-radius, radius), 1 * 0.5f, Random.Range(-radius, radius));
RaycastHit hit;
if(Physics.Raycast(transform.position,transform.forward,out hit, 25)){
Vector3 spawnPos = hit.point+Vector3.up*0.15f;
Vector3 playerPos = ManagesScene.singleton.player.position;
Quaternion spawnRot = Quaternion.LookRotation(spawnPos - playerPos, Vector3.up);
spawnRot = Quaternion.Euler(0f,spawnRot.eulerAngles.y,0f);
GameObject newMarker = Instantiate(ManagesScene.singleton.markerPrefab, spawnPos, spawnRot);
ManagesScene.singleton.markerCount++;
newMarker.GetComponentInChildren<UnityEngine.UI.Text>().text = ManagesScene.singleton.markerCount.ToString();
}
}
}
public enum Hands { LeftHand, RightHand }
public enum ButtonStates {Held,Pressed,LetGo,NotPressed}
[System.Serializable]
public class ControllerButton {
public ButtonStates state;
public OVRInput.RawButton ovrButton;
public bool value;
public bool lastValue;
} |
using JigsawLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
namespace JigsawWpf
{
internal class Jigsaw
{
private readonly Segment[,] _board;
public Jigsaw(Segment[,] board) => _board = board;
internal void Draw(IEnumerable<Grid> gridSegment)
{
var Segments = new List<Segment>();
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
Segments.Add(_board[x, y]);
}
}
var SegmentsZip = Segments.Zip(gridSegment, (n, w) => new { BoardSegment = n, GuiSegment = w });
foreach (var zip in SegmentsZip)
{
Draw(zip.GuiSegment, zip.BoardSegment);
}
}
private static void Draw(Grid root, Segment segment) =>
segment.Emojis.ForEach(emoji => DrawSegmentEmoji(root, emoji));
private static void DrawSegmentEmoji(Grid root, Emoji emoji)
{
int x;
int y;
JigsawLibrary.Color color;
HorizontalAlignment HorizontalOrientation;
VerticalAlignment VerticalOrientation;
switch (emoji.Location)
{
case Location.Top:
x = 0;
y = 1;
color = emoji.Color;
HorizontalOrientation = HorizontalAlignment.Center;
VerticalOrientation = VerticalAlignment.Top;
break;
case Location.Right:
x = 1;
y = 2;
color = emoji.Color;
HorizontalOrientation = HorizontalAlignment.Right;
VerticalOrientation = VerticalAlignment.Center;
break;
case Location.Left:
x = 1;
y = 0;
color = emoji.Color;
HorizontalOrientation = HorizontalAlignment.Left;
VerticalOrientation = VerticalAlignment.Center;
break;
case Location.Bottom:
x = 2;
y = 1;
color = emoji.Color;
HorizontalOrientation = HorizontalAlignment.Center;
VerticalOrientation = VerticalAlignment.Bottom;
break;
default:
return;
}
DrawEmoji(root, x, y, color);
DrawLabel(root, emoji, x, y, HorizontalOrientation, VerticalOrientation);
}
private static void DrawLabel(Grid root, Emoji emoji, int x, int y, HorizontalAlignment horizontalOrientation, VerticalAlignment verticalOrientation)
{
var dynamicLabel = new Label
{
Name = "EmojiLabel",
Content = emoji.Type.ToString(),
Width = 50,
Height = 30,
HorizontalAlignment = horizontalOrientation,
VerticalAlignment = verticalOrientation,
Foreground = new SolidColorBrush(Colors.White),
Background = new SolidColorBrush(Colors.Black)
};
root.Children.Add(dynamicLabel);
Grid.SetColumn(dynamicLabel, y);
Grid.SetRow(dynamicLabel, x);
}
private static void DrawEmoji(Grid root, int x, int y, JigsawLibrary.Color color)
{
var rectangle = new Rectangle
{
Fill = ((SolidColorBrush) new BrushConverter().ConvertFromString(color.ToString())) ?? throw new InvalidOperationException()
};
root.Children.Add(rectangle);
Grid.SetColumn(rectangle, y);
Grid.SetRow(rectangle, x);
}
}
}
|
// <copyright file="TestExpressionTree.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace SpreadSheet.Test
{
using System.Collections.Generic;
using ExpressionTreeEngine;
// NUnit 3 tests
// See documentation : https://github.com/nunit/docs/wiki/NUnit-Documentation
using NUnit.Framework;
/// <summary>
/// test for the Expression Tree.
/// </summary>
[TestFixture]
public class TestExpressionTree
{
/// <summary>
/// Test Method for Expression Tree.
/// </summary>
[Test]
public void TestExpressionTree1()
{
// TODO: Test eveluation for expression Tree
string expression1 = "A+B+C1+C2+6";
ExpressionTree tree = new ExpressionTree(expression1);
tree.SetVariable("A", 2.0);
tree.SetVariable("B", 3.0);
tree.SetVariable("C1", 4.0);
tree.SetVariable("C2", 5.0);
double value1 = tree.Evaluate();
Assert.AreEqual(20.0, value1);
string expression2 = "C2-9-B2-27";
ExpressionTree tree2 = new ExpressionTree(expression2);
tree2.SetVariable("C2", 50.0);
tree2.SetVariable("B2", 10.0);
double value2 = tree2.Evaluate();
Assert.AreEqual(4.0, value2);
}
/// <summary>
/// Test Method for Expression Tree.
/// </summary>
[Test]
public void TestExpressionTree2()
{
// TODO: Test eveluation for expression Tree
string expression1 = "A*B+C1/C2+6";
ExpressionTree tree = new ExpressionTree(expression1);
tree.SetVariable("A", 9.0);
tree.SetVariable("B", 8.0);
tree.SetVariable("C1", 10.0);
tree.SetVariable("C2", 5.0);
double value1 = tree.Evaluate();
Assert.AreEqual(80.0, value1);
string expression2 = "C2*9+B2-27";
ExpressionTree tree2 = new ExpressionTree(expression2);
tree2.SetVariable("C2", 20.0);
tree2.SetVariable("B2", 10.0);
double value2 = tree2.Evaluate();
Assert.AreEqual(163.0, value2);
string expression3 = "C2*(9+B2)-27";
ExpressionTree tree3 = new ExpressionTree(expression3);
tree3.SetVariable("C2", 20.0);
tree3.SetVariable("B2", 10.0);
double value3 = tree3.Evaluate();
Assert.AreEqual(353.0, value3);
string expression4 = "(A1+B2-5)/5";
ExpressionTree tree4 = new ExpressionTree(expression4);
tree4.SetVariable("A1", 5.0);
tree4.SetVariable("B2", 10.0);
double value4 = tree4.Evaluate();
Assert.AreEqual(2, value4);
string expression5 = "1+2/3*6";
ExpressionTree tree5 = new ExpressionTree(expression5);
double value5 = tree5.Evaluate();
Assert.AreEqual(5, value5);
string expression6 = "(((1+2)/3)*6)";
ExpressionTree tree6 = new ExpressionTree(expression6);
double value6 = tree6.Evaluate();
Assert.AreEqual(6, value6);
}
/// <summary>
/// Test for get varibles.
/// </summary>
[Test]
public void TestGetVaribles()
{
string expression1 = "A*B+C1/C2+6";
ExpressionTree tree = new ExpressionTree(expression1);
List<string> test = tree.GetVaribles(expression1);
Assert.That(test[0], Is.EqualTo("A"));
Assert.That(test[1], Is.EqualTo("B"));
Assert.That(test[2], Is.EqualTo("C1"));
Assert.That(test[3], Is.EqualTo("C2"));
string expression2 = "C2*9+B2-27";
ExpressionTree tree2 = new ExpressionTree(expression2);
List<string> test2 = tree2.GetVaribles(expression2);
Assert.That(test2[0], Is.EqualTo("C2"));
Assert.That(test2[1], Is.EqualTo("B2"));
string expression3 = "B11+C22";
ExpressionTree tree3 = new ExpressionTree(expression3);
List<string> test3 = tree3.GetVaribles(expression3);
Assert.That(test3[0], Is.EqualTo("B11"));
Assert.That(test3[1], Is.EqualTo("C22"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio;
using Infra.Context;
namespace Infra
{
public class UnidadeTrabalho : IUnidadeTrabalho
{
private readonly AuthContext _contexto;
public UnidadeTrabalho(AuthContext contexto)
{
_contexto = contexto;
}
public void Commit()
{
_contexto.SaveChanges();
_contexto.Database.CurrentTransaction?.Commit();
}
public void Rollback()
{
_contexto.Database.CurrentTransaction?.Rollback();
}
public void BeginTran()
{
if (_contexto.Database.CurrentTransaction == null)
{
_contexto.Database.BeginTransaction();
}
}
public void Dispose()
{
_contexto.Dispose();
}
}
}
|
using BusVenta;
using DatVentas;
using EntVenta;
using Reportes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telerik.Reporting.Processing;
namespace VentasD1002
{
public partial class frmCreditosCobrar : Form
{
private PrintDocument TICKET;
public frmCreditosCobrar()
{
InitializeComponent();
}
private void frmCreditosCobrar_Load(object sender, EventArgs e)
{
Listar_TotalCredito_PorCliente();
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedIndex == 0)
{
Listar_TotalCredito_PorCliente();
}
else if(tabControl1.SelectedIndex == 1)
{
ListarVentar_PorCobrar("");
pnlAbonar.Visible = false;
pnlVistaTicket.Visible = false;
pnlListadoClienteCredito.Visible = false;
}
}
private void Listar_TotalCredito_PorCliente()
{
try
{
DataTable data = DatVenta.ListarClientes_TotalALquidar();
gdvTotalCredito.DataSource = data;
gdvTotalCredito.Columns[0].Visible = false;
DataTablePersonalizado.Multilinea(ref gdvTotalCredito);
pnlListadoClienteCredito.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show("Ocurrió un error al consultar los datos : " + ex.Message, "Error de Lectura", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnCobrar_Click(object sender, EventArgs e)
{
if (gdvDetalle.Rows.Count == 0)
{
MessageBox.Show("Seleccione la venta a cobrar", "Venta no existe", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
else
{
txtSaldoActual.Text = lblTotalLiquidar.Text;
pnlAbonar.Visible = true;
txtMontoAbonar.Focus();
}
}
private void gdvListado_CellClick_1(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == this.gdvListado.Columns["Detalle"].Index)
{
if (pnlAbonar.Visible != true)
{
int _idusuario = Convert.ToInt32(gdvListado.SelectedCells[3].Value);
lblCajero.Text = new BusUser().ListarUsuarios().Where(x => x.Id.Equals(_idusuario)).Select(x => x.Nombre).FirstOrDefault();
int _idVenta = Convert.ToInt32(gdvListado.SelectedCells[1].Value);
lblIdVenta.Text = _idVenta.ToString();
lblCliente.Text = gdvListado.SelectedCells[6].Value.ToString();
lblFolio.Text = gdvListado.SelectedCells[7].Value.ToString();
lblTicket.Text = gdvListado.SelectedCells[8].Value.ToString();
lblMontototal.Text = gdvListado.SelectedCells[9].Value.ToString();
lblTotalLiquidar.Text = gdvListado.SelectedCells[10].Value.ToString();
decimal _totalAbonado = Convert.ToDecimal(gdvListado.SelectedCells[9].Value.ToString()) - Convert.ToDecimal(gdvListado.SelectedCells[10].Value.ToString());
lblTotalAbonado.Text = _totalAbonado.ToString();
gdvDetalle.DataSource = new BusDetalleVenta().ListarDetalleVenta_PorCobrar(_idVenta);
gdvDetalle.Columns[0].Visible = false;
gdvDetalle.Columns[1].Visible = false;
gdvDetalle.Columns[2].Visible = false;
//gdvDetalle.Columns[8].Visible = false;
gdvDetalle.Columns[9].Visible = false;
gdvDetalle.Columns[10].Visible = false;
gdvDetalle.Columns[11].Visible = false;
gdvDetalle.Columns[12].Visible = false;
gdvDetalle.Columns[13].Visible = false;
gdvDetalle.Columns[14].Visible = false;
gdvDetalle.Columns[15].Visible = false;
DataTablePersonalizado.Multilinea(ref gdvDetalle);
}
else
{
MessageBox.Show("Ya existe un proceso de cobro en curso!, proceda con el guardado o de lo contrario presione cancelar", "Proceso ocupado ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error al mostrar el detalle: " + ex.Message, "Error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void textBox1_TextChanged_1(object sender, EventArgs e)
{
ListarVentar_PorCobrar(textBox1.Text);
}
private void textBox1_MouseClick_1(object sender, MouseEventArgs e)
{
textBox1.SelectAll();
}
private void bntCancelar_Click_1(object sender, EventArgs e)
{
pnlAbonar.Visible = false;
txtMontoAbonar.Clear();
txtPendienteLiquidar.Clear();
txtSaldoActual.Clear();
}
private void txtMontoAbonar_TextChanged_1(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtMontoAbonar.Text) || txtMontoAbonar.Equals("0"))
{
txtMontoAbonar.Text = "0";
txtMontoAbonar.SelectAll();
}
else
{
decimal _saldo = Convert.ToDecimal(txtSaldoActual.Text);
decimal _Pendiente = _saldo - (Convert.ToDecimal(txtMontoAbonar.Text));
txtPendienteLiquidar.Text = _Pendiente.ToString();
}
}
private void txtMontoAbonar_KeyPress_1(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
}
private void btnAbonar_Click_1(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txtMontoAbonar.Text))
{
MessageBox.Show("Ingrese la cantidad a Abonar", "Datos necesarios", MessageBoxButtons.OK, MessageBoxIcon.Hand);
txtMontoAbonar.Focus();
}
else
{
string _strEstadoPago = Convert.ToDecimal(txtMontoAbonar.Text) >= Convert.ToDecimal(txtSaldoActual.Text) ? "PAGADO" : "PENDIENTE";
decimal _saldo = Convert.ToDecimal(txtPendienteLiquidar.Text) <= 0 ? 0 : Convert.ToDecimal(txtPendienteLiquidar.Text);
int _idVenta = Convert.ToInt32(lblIdVenta.Text);
decimal abonado = Convert.ToDecimal(txtPendienteLiquidar.Text) <= 0 ? Convert.ToDecimal(txtSaldoActual.Text) : Convert.ToDecimal(txtMontoAbonar.Text);
decimal efectivo = Convert.ToDecimal(lblTotalAbonado.Text) + Convert.ToDecimal(txtMontoAbonar.Text);
new BusVentas().Actualizar_VentaACredito(_idVenta, _saldo, _strEstadoPago, efectivo);
#region BITACORA PAGO CLIENTE
ManagementObject mos = new ManagementObject(@"Win32_PhysicalMedia='\\.\PHYSICALDRIVE0'");
string serialPC = mos.Properties["SerialNumber"].Value.ToString().Trim();
int idUsuario = new BusUser().ObtenerUsuario(EncriptarTexto.Encriptar(serialPC)).Id;
DatCatGenerico.Agregar_BitacoraCliente(_idVenta, idUsuario, abonado);
#endregion
#region TICKET
rptComprobanteAbono _rpt = new rptComprobanteAbono();
DataTable dt = new DatVenta().Obtener_ComprobanteCredito(_idVenta, abonado);
_rpt.tbCobro.DataSource = dt;
_rpt.DataSource = dt;
reportViewer1.Report = _rpt;
reportViewer1.RefreshReport();
pnlVistaTicket.Visible = true;
#endregion
try
{
string impresora = DatBox.Obtener_ImpresoraTicket(serialPC, "TICKET");
TICKET = new PrintDocument();
TICKET.PrinterSettings.PrinterName = impresora;
if (TICKET.PrinterSettings.IsValid)
{
PrinterSettings printerSettings = new PrinterSettings();
printerSettings.PrinterName = impresora;
ReportProcessor reportProcessor = new ReportProcessor();
reportProcessor.PrintReport(reportViewer1.ReportSource, printerSettings);
}
}
catch (Exception ex)
{
MessageBox.Show("Error al imprimir el ticket : " + ex.Message, "Error de impresión", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
LimpiarCampos();
ListarVentar_PorCobrar("");
MessageBox.Show("Abono realizado correctamente", "Éxito!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message, "Error de actulizacion de pagos a crédito", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click_2(object sender, EventArgs e)
{
pnlVistaTicket.Visible = false;
}
private void ListarVentar_PorCobrar(string busqueda)
{
try
{
List<Venta> _lstVenta = new BusVentas().ListarVentas_PorCobrar(busqueda);
gdvListado.DataSource = _lstVenta;
gdvListado.Columns[1].Visible = false;
gdvListado.Columns[2].Visible = false;
gdvListado.Columns[3].Visible = false;
gdvListado.Columns[4].Visible = false;
gdvListado.Columns[8].Visible = false;
gdvListado.Columns[9].Visible = false;
gdvListado.Columns[10].Visible = false;
gdvListado.Columns[11].Visible = false;
gdvListado.Columns[12].Visible = false;
gdvListado.Columns[13].Visible = false;
gdvListado.Columns[14].Visible = false;
gdvListado.Columns[15].Visible = false;
gdvListado.Columns[16].Visible = false;
gdvListado.Columns[17].Visible = false;
gdvListado.Columns[18].Visible = false;
DataTablePersonalizado.Multilinea(ref gdvListado);
}
catch (Exception ex)
{
MessageBox.Show("Error al mostrar la lista: " + ex.Message, "Error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LimpiarCampos()
{
pnlAbonar.Visible = false;
txtMontoAbonar.Clear();
txtPendienteLiquidar.Clear();
txtSaldoActual.Clear();
gdvDetalle.DataSource = null;
lblIdVenta.Text = "...";
lblFolio.Text = "...";
lblCajero.Text = "...";
lblCliente.Text = "...";
lblTicket.Text = "...";
lblMontototal.Text = "...";
lblTotalAbonado.Text = "...";
lblTotalLiquidar.Text = "...";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Net.Mime;
namespace DotnetBuicDemos.Controllers
{
public class DemoController : Controller
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// Angular Simple Template
/// </summary>
/// <returns></returns>
public PartialViewResult BUIC1()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
ViewBag.CurrentTime = DateTime.Now.TimeOfDay.ToString();
return PartialView();
}
/// <summary>
/// JSON Data
/// </summary>
/// <returns></returns>
public JsonResult BUIC2()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
var data = new Dictionary<string, object>();
data["fieldDateTimeUtc"] = DateTime.UtcNow;
data["fieldObjectEmpty"] = new object();
data["fieldNull"] = null;
data["fieldLong"] = long.MaxValue.ToString(); //NOTE: Long values must be passed as strings because they are too large for js numeric type
data["fieldDoubleMin"] = double.MinValue;
data["fieldDoubleMax"] = double.MaxValue;
data["fieldString"] = "Test string value";
data["fieldBool"] = true;
data["arrObjEmpty"] = new object[] { new object(), new object(), new object() };
data["arrInt"] = new int[] { int.MinValue, -99, -1, 0, 1, 99, int.MaxValue };
data["arrDouble"] = new double[] { double.MinValue, -99.999, -1.1, 0.0, 1.1, 99.999, double.MaxValue };
data["arrBool"] = new bool[] { true, false };
return Json(data, JsonRequestBehavior.AllowGet); //NOTE: You don't have to use Newtonsoft explicitly when using return Json()
}
/// <summary>
/// Stream image from filesystem
/// </summary>
/// <returns></returns>
public FileResult BUIC3()
{
var fileName = @"\DemoFiles\buic3.png";
var contentType = MimeMapping.GetMimeMapping(fileName); //"image/png";
var result = new FilePathResult(fileName, contentType);
return result;
}
/// <summary>
/// Video Stream - not the entire file for downloading
/// NOTE: Vani says to skip this example for now
/// </summary>
/// <returns></returns>
public ContentResult BUIC4()
{
return NotBuicImplementedYetText("TODO " + System.Reflection.MethodInfo.GetCurrentMethod().Name); //TODO AKM Implement this - see commented method below
}
/// <summary>
/// Video Stream - not the entire file for downloading
/// NOTE: Vani says to skip this example for now
/// </summary>
/// <returns></returns>
//public FileResult BUIC4()
//{ //TODO AKM Incomplete. This stub isn't streaming yet - it is downloading the file
// var fileName = Server.MapPath(@"~\DemoFiles\ferrari-versus-eurofighter.avi");
// byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
// var contentType = octetstream? // MimeMapping.GetMimeMapping(fileName); //"video/avi";
// var contentDisposition = new ContentDisposition
// {
// Inline = true,
// FileName = "buic4.avi"
// };
// var result = new FileContentResultWithContentDisposition(fileBytes, contentType, contentDisposition);
// return result;
//}
/// <summary>
/// Angular Tabbed UI Template
/// </summary>
/// <returns></returns>
public PartialViewResult BUIC5()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return PartialView();
}
/// <summary>
/// Angular MVC, routing, databinding, and filtering
/// </summary>
/// <returns></returns>
public ActionResult BUIC6()
{
return View();
}
/// <summary>
/// Angular App w/client routing
/// </summary>
/// <returns></returns>
public ActionResult BUIC7()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return View();
}
/// <summary>
/// Simple Angular App w/ext Resources (MVC)
/// </summary>
/// <returns></returns>
public ActionResult BUIC8()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return View();
}
/// <summary>
/// ASP.NET Simple WebForm
/// NOTE: Vani says to skip this. WebForms may not ever be supported for BUICs
/// </summary>
/// <returns></returns>
public ContentResult BUIC9()
{
return NotBuicImplementedYetText("TODO " + System.Reflection.MethodInfo.GetCurrentMethod().Name);
}
/// <summary>
/// MVC Form
/// </summary>
/// <returns></returns>
public PartialViewResult BUIC10()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return PartialView();
}
/// <summary>
/// ASP.NET Simple MVC Partial View
/// </summary>
/// <returns></returns>
public PartialViewResult BUIC11()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
ViewBag.CurrentTime = DateTime.Now.TimeOfDay.ToString();
return PartialView();
}
/// <summary>
/// Javascript
/// </summary>
/// <returns></returns>
public JavaScriptResult BUIC12()
{
var result = new JavaScriptResult();
result.Script = "alert('BUIC12');";
return result;
}
/// <summary>
/// Download file from the filesystem
/// </summary>
/// <returns></returns>
public FileResult BUIC13()
{
var fileName = @"\DemoFiles\buic13.txt";
var contentType = MimeMapping.GetMimeMapping(fileName); //"text/plain";
var result = new FilePathResult(fileName, contentType);
result.FileDownloadName = "buic13.txt";
return result;
}
/// <summary>
/// Download image file from the filesystem
/// </summary>
/// <returns></returns>
public FileResult BUIC14()
{
var fileName = @"\DemoFiles\buic14.png";
var contentType = MimeMapping.GetMimeMapping(fileName); //"image/png";
var result = new FilePathResult(fileName, contentType);
result.FileDownloadName = "buic14.png";
return result;
}
/// <summary>
/// File download
/// </summary>
/// <returns></returns>
public FileResult BUIC15()
{
var fileName = @"\DemoFiles\ferrari-versus-eurofighter.avi";
var contentType = MimeMapping.GetMimeMapping(fileName); //"video/avi";
var result = new FilePathResult(fileName, contentType);
result.FileDownloadName = "buic15.avi";
return result;
}
/// <summary>
/// Base64 data
/// </summary>
/// <returns></returns>
public ContentResult BUIC16()
{
var fileName = Server.MapPath(@"~\DemoFiles\buic16.png");
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
var result = new ContentResult();
result.ContentType = "text/plain"; //important because we are returning BASE64
result.ContentEncoding = System.Text.Encoding.UTF8;
result.Content = Convert.ToBase64String(fileBytes);
return result;
}
/// <summary>
/// Image sourced with Base64 data, sourced in html img tag
/// </summary>
/// <returns></returns>
public ContentResult BUIC17()
{
var fileName = Server.MapPath(@"~\DemoFiles\buic17.png");
var contentType = MimeMapping.GetMimeMapping(fileName); // image/png
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
var base64string = Convert.ToBase64String(fileBytes);
var result = new ContentResult();
result.ContentType = "text/plain";
result.ContentEncoding = System.Text.Encoding.UTF8;
result.Content = $"<img src='data:{contentType};base64,{base64string}' />";
return result;
}
private ContentResult NotBuicImplementedYetText(string message)
{
var result = new ContentResult
{
Content = message,
ContentType = "text/plain"
};
return result;
}
}
/// <summary>
/// Enable Content-Disposition to be set without double-including the header, which doesn't work for some browsers (like Chrome)
/// </summary>
public class FileContentResultWithContentDisposition : FileContentResult
{
private const string ContentDispositionHeaderName = "Content-Disposition";
public FileContentResultWithContentDisposition(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
: base(fileContents, contentType)
{
ContentDisposition = contentDisposition;
}
public ContentDisposition ContentDisposition { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
// check for null or invalid method argument
ContentDisposition.FileName = ContentDisposition.FileName ?? FileDownloadName;
var response = context.HttpContext.Response;
response.ContentType = ContentType;
response.AddHeader(ContentDispositionHeaderName, ContentDisposition.ToString());
WriteFile(response);
}
}
} |
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 DotNetRegExConsole
{
public partial class MainForm : Ults.Windows.Forms.MainFormBase
{
public MainForm()
{
InitializeComponent();
var optionItems = Enum.GetValues(typeof(System.Text.RegularExpressions.RegexOptions))
.Cast<System.Text.RegularExpressions.RegexOptions>()
.Where(f => f!= System.Text.RegularExpressions.RegexOptions.None)
.Select(f => new ListBoxItem<System.Text.RegularExpressions.RegexOptions>(f))
.ToArray();
checkedListBoxOptions.Items.AddRange(optionItems);
textBoxExInput.Text = Properties.Settings.Default.InputText;
textBoxExPattern.Text = Properties.Settings.Default.PatternText;
textBoxExReplacement.Text = Properties.Settings.Default.ReplacementText;
if (!Properties.Settings.Default.FormSize.IsEmpty)
{
this.Size = Properties.Settings.Default.FormSize;
splittContainerEx1.SplitterDistance = Properties.Settings.Default.SplitterDistance;
}
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
Properties.Settings.Default.InputText = textBoxExInput.Text;
Properties.Settings.Default.PatternText = textBoxExPattern.Text;
Properties.Settings.Default.ReplacementText = textBoxExReplacement.Text;
Properties.Settings.Default.RegExOptions = 0;
Properties.Settings.Default.SplitterDistance = splittContainerEx1.SplitterDistance;
Properties.Settings.Default.Save();
}
protected override void OnResizeEnd(EventArgs e)
{
base.OnResizeEnd(e);
Properties.Settings.Default.FormSize = this.Size;
Properties.Settings.Default.Save();
}
private void buttonDoMatches_Click(object sender, EventArgs e)
{
try
{
var mts = System.Text.RegularExpressions.Regex.Matches(textBoxExInput.Text, textBoxExPattern.Text, GetSelectedRegExOptions());
if(mts.Count == 0)
{
textBoxExOutput.Text = "No matches.";
return;
}
var matchIndex = 0;
textBoxExOutput.Text = string.Concat(mts.Cast<System.Text.RegularExpressions.Match>().Select(f => string.Format("[Match:{0}] {1}\r\n\r\n", matchIndex++, f.Value)));
}
catch(System.Exception ex)
{
textBoxExOutput.Text = string.Format("[{0}]\r\n{1}", ex.GetType().Name, ex.Message);
}
}
private void buttonDoReplace_Click(object sender, EventArgs e)
{
try
{
textBoxExOutput.Text = System.Text.RegularExpressions.Regex.Replace(textBoxExInput.Text, textBoxExPattern.Text, textBoxExReplacement.Text, GetSelectedRegExOptions());
}
catch (System.Exception ex)
{
textBoxExOutput.Text = string.Format("[{0}]\r\n{1}", ex.GetType().Name, ex.Message);
}
}
private void buttonOpenRead_Click(object sender, EventArgs e)
{
using(var dlg = new System.Windows.Forms.OpenFileDialog())
{
dlg.InitialDirectory = Properties.Settings.Default.FileReadInitialDirectory;
if (dlg.ShowDialog() != DialogResult.OK)
return;
textBoxExInput.Text = System.IO.File.ReadAllText(dlg.FileName);
// Encoding...
Properties.Settings.Default.FileReadInitialDirectory = System.IO.Path.GetDirectoryName(dlg.FileName);
Properties.Settings.Default.Save();
}
}
private System.Text.RegularExpressions.RegexOptions GetSelectedRegExOptions()
{
return checkedListBoxOptions.SelectedItems
.Cast<ListBoxItem<System.Text.RegularExpressions.RegexOptions>>()
.Select(f => f.Value)
.Aggregate(System.Text.RegularExpressions.RegexOptions.None, (v, a) => v | a);
}
private class ListBoxItem<T>
{
public T Value { get; private set; }
public ListBoxItem(T value)
{
this.Value = value;
}
public override string ToString()
{
return this.Value.ToString();
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
// Alias Console to MockConsole so we don't accidentally use Console
using Console = Terminal.Gui.FakeConsole;
namespace Terminal.Gui.DriverTests {
public class ConsoleDriverTests {
readonly ITestOutputHelper output;
public ConsoleDriverTests (ITestOutputHelper output)
{
this.output = output;
}
[Theory]
[InlineData (typeof (FakeDriver))]
//[InlineData (typeof (NetDriver))]
//[InlineData (typeof (CursesDriver))]
//[InlineData (typeof (WindowsDriver))]
public void Init_Inits (Type driverType)
{
var driver = (ConsoleDriver)Activator.CreateInstance (driverType);
Application.Init (driver);
driver.Init (() => { });
Assert.Equal (80, Console.BufferWidth);
Assert.Equal (25, Console.BufferHeight);
// MockDriver is always 80x25
Assert.Equal (Console.BufferWidth, driver.Cols);
Assert.Equal (Console.BufferHeight, driver.Rows);
driver.End ();
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
[Theory]
[InlineData (typeof (FakeDriver))]
//[InlineData (typeof (NetDriver))]
//[InlineData (typeof (CursesDriver))]
//[InlineData (typeof (WindowsDriver))]
public void End_Cleans_Up (Type driverType)
{
var driver = (ConsoleDriver)Activator.CreateInstance (driverType);
Application.Init (driver);
driver.Init (() => { });
Console.ForegroundColor = ConsoleColor.Red;
Assert.Equal (ConsoleColor.Red, Console.ForegroundColor);
Console.BackgroundColor = ConsoleColor.Green;
Assert.Equal (ConsoleColor.Green, Console.BackgroundColor);
driver.Move (2, 3);
Assert.Equal (2, Console.CursorLeft);
Assert.Equal (3, Console.CursorTop);
driver.End ();
Assert.Equal (0, Console.CursorLeft);
Assert.Equal (0, Console.CursorTop);
Assert.Equal (ConsoleColor.Gray, Console.ForegroundColor);
Assert.Equal (ConsoleColor.Black, Console.BackgroundColor);
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
[Theory]
[InlineData (typeof (FakeDriver))]
public void FakeDriver_Only_Sends_Keystrokes_Through_MockKeyPresses (Type driverType)
{
var driver = (ConsoleDriver)Activator.CreateInstance (driverType);
Application.Init (driver);
var top = Application.Top;
var view = new View ();
var count = 0;
var wasKeyPressed = false;
view.KeyPress += (e) => {
wasKeyPressed = true;
};
top.Add (view);
Application.Iteration += () => {
count++;
if (count == 10) Application.RequestStop ();
};
Application.Run ();
Assert.False (wasKeyPressed);
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
[Theory]
[InlineData (typeof (FakeDriver))]
public void FakeDriver_MockKeyPresses (Type driverType)
{
var driver = (ConsoleDriver)Activator.CreateInstance (driverType);
Application.Init (driver);
var text = "MockKeyPresses";
var mKeys = new Stack<ConsoleKeyInfo> ();
foreach (var r in text.Reverse ()) {
var ck = char.IsLetter (r) ? (ConsoleKey)char.ToUpper (r) : (ConsoleKey)r;
var cki = new ConsoleKeyInfo (r, ck, false, false, false);
mKeys.Push (cki);
}
Console.MockKeyPresses = mKeys;
var top = Application.Top;
var view = new View ();
var rText = "";
var idx = 0;
view.KeyPress += (e) => {
Assert.Equal (text [idx], (char)e.KeyEvent.Key);
rText += (char)e.KeyEvent.Key;
Assert.Equal (rText, text.Substring (0, idx + 1));
e.Handled = true;
idx++;
};
top.Add (view);
Application.Iteration += () => {
if (mKeys.Count == 0) Application.RequestStop ();
};
Application.Run ();
Assert.Equal ("MockKeyPresses", rText);
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
[Theory]
[InlineData (typeof (FakeDriver))]
public void TerminalResized_Simulation (Type driverType)
{
var driver = (FakeDriver)Activator.CreateInstance (driverType);
Application.Init (driver);
var wasTerminalResized = false;
Application.Resized = (e) => {
wasTerminalResized = true;
Assert.Equal (120, e.Cols);
Assert.Equal (40, e.Rows);
};
Assert.Equal (80, Console.BufferWidth);
Assert.Equal (25, Console.BufferHeight);
// MockDriver is by default 80x25
Assert.Equal (Console.BufferWidth, driver.Cols);
Assert.Equal (Console.BufferHeight, driver.Rows);
Assert.False (wasTerminalResized);
// MockDriver will now be sets to 120x40
driver.SetBufferSize (120, 40);
Assert.Equal (120, Application.Driver.Cols);
Assert.Equal (40, Application.Driver.Rows);
Assert.True (wasTerminalResized);
Application.Shutdown ();
}
[Theory]
[InlineData (typeof (FakeDriver))]
public void Left_And_Top_Is_Always_Zero (Type driverType)
{
var driver = (FakeDriver)Activator.CreateInstance (driverType);
Application.Init (driver);
Assert.Equal (0, Console.WindowLeft);
Assert.Equal (0, Console.WindowTop);
driver.SetWindowPosition (5, 5);
Assert.Equal (0, Console.WindowLeft);
Assert.Equal (0, Console.WindowTop);
Application.Shutdown ();
}
[Fact, AutoInitShutdown]
public void AddRune_On_Clip_Left_Or_Right_Replace_Previous_Or_Next_Wide_Rune_With_Space ()
{
var tv = new TextView () {
Width = Dim.Fill (),
Height = Dim.Fill (),
Text = @"これは広いルーンラインです。
これは広いルーンラインです。
これは広いルーンラインです。
これは広いルーンラインです。
これは広いルーンラインです。
これは広いルーンラインです。
これは広いルーンラインです。
これは広いルーンラインです。"
};
var win = new Window ("ワイドルーン") { Width = Dim.Fill (), Height = Dim.Fill () };
win.Add (tv);
Application.Top.Add (win);
var lbl = new Label ("ワイドルーン。");
var dg = new Dialog ("テスト", 14, 4, new Button ("選ぶ"));
dg.Add (lbl);
Application.Begin (Application.Top);
Application.Begin (dg);
((FakeDriver)Application.Driver).SetBufferSize (30, 10);
var expected = @"
┌ ワイドルーン ──────────────┐
│これは広いルーンラインです。│
│これは広いルーンラインです。│
│これは ┌ テスト ────┐ です。│
│これは │ワイドルーン│ です。│
│これは │ [ 選ぶ ] │ です。│
│これは └────────────┘ です。│
│これは広いルーンラインです。│
│これは広いルーンラインです。│
└────────────────────────────┘
";
var pos = TestHelpers.AssertDriverContentsWithFrameAre (expected, output);
Assert.Equal (new Rect (0, 0, 30, 10), pos);
}
[Fact, AutoInitShutdown]
public void Write_Do_Not_Change_On_ProcessKey ()
{
var win = new Window ();
Application.Begin (win);
((FakeDriver)Application.Driver).SetBufferSize (20, 8);
System.Threading.Tasks.Task.Run (() => {
System.Threading.Tasks.Task.Delay (500).Wait ();
Application.MainLoop.Invoke (() => {
var lbl = new Label ("Hello World") { X = Pos.Center () };
var dlg = new Dialog ("Test", new Button ("Ok"));
dlg.Add (lbl);
Application.Begin (dlg);
var expected = @"
┌──────────────────┐
│┌ Test ─────────┐ │
││ Hello World │ │
││ │ │
││ │ │
││ [ Ok ] │ │
│└───────────────┘ │
└──────────────────┘
";
var pos = TestHelpers.AssertDriverContentsWithFrameAre (expected, output);
Assert.Equal (new Rect (0, 0, 20, 8), pos);
Assert.True (dlg.ProcessKey (new KeyEvent (Key.Tab, new KeyModifiers ())));
dlg.Redraw (dlg.Bounds);
expected = @"
┌──────────────────┐
│┌ Test ─────────┐ │
││ Hello World │ │
││ │ │
││ │ │
││ [ Ok ] │ │
│└───────────────┘ │
└──────────────────┘
";
pos = TestHelpers.AssertDriverContentsWithFrameAre (expected, output);
Assert.Equal (new Rect (0, 0, 20, 8), pos);
win.RequestStop ();
});
});
Application.Run (win);
Application.Shutdown ();
}
[Theory]
[InlineData (0x0000001F, 0x241F)]
[InlineData (0x0000007F, 0x247F)]
[InlineData (0x0000009F, 0x249F)]
[InlineData (0x0001001A, 0x1001A)]
public void MakePrintable_Converts_Control_Chars_To_Proper_Unicode (uint code, uint expected)
{
var actual = ConsoleDriver.MakePrintable (code);
Assert.Equal (expected, actual.Value);
}
[Theory]
[InlineData (0x20)]
[InlineData (0x7E)]
[InlineData (0xA0)]
[InlineData (0x010020)]
public void MakePrintable_Does_Not_Convert_Ansi_Chars_To_Unicode (uint code)
{
var actual = ConsoleDriver.MakePrintable (code);
Assert.Equal (code, actual.Value);
}
private static object packetLock = new object ();
/// <summary>
/// Sometimes when using remote tools EventKeyRecord sends 'virtual keystrokes'.
/// These are indicated with the wVirtualKeyCode of 231. When we see this code
/// then we need to look to the unicode character (UnicodeChar) instead of the key
/// when telling the rest of the framework what button was pressed. For full details
/// see: https://github.com/gui-cs/Terminal.Gui/issues/2008
/// </summary>
[Theory]
[ClassData (typeof (PacketTest))]
public void TestVKPacket (uint unicodeCharacter, bool shift, bool alt, bool control, uint initialVirtualKey, uint initialScanCode, Key expectedRemapping, uint expectedVirtualKey, uint expectedScanCode)
{
lock (packetLock) {
Application.ForceFakeConsole = true;
Application.Init ();
var modifiers = new ConsoleModifiers ();
if (shift) modifiers |= ConsoleModifiers.Shift;
if (alt) modifiers |= ConsoleModifiers.Alt;
if (control) modifiers |= ConsoleModifiers.Control;
var mappedConsoleKey = ConsoleKeyMapping.GetConsoleKeyFromKey (unicodeCharacter, modifiers, out uint scanCode, out uint outputChar);
if ((scanCode > 0 || mappedConsoleKey == 0) && mappedConsoleKey == initialVirtualKey) Assert.Equal (mappedConsoleKey, initialVirtualKey);
else Assert.Equal (mappedConsoleKey, outputChar < 0xff ? outputChar & 0xff | 0xff << 8 : outputChar);
Assert.Equal (scanCode, initialScanCode);
var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (mappedConsoleKey, modifiers, out uint consoleKey, out scanCode);
//if (scanCode > 0 && consoleKey == keyChar && consoleKey > 48 && consoleKey > 57 && consoleKey < 65 && consoleKey > 91) {
if (scanCode > 0 && keyChar == 0 && consoleKey == mappedConsoleKey) Assert.Equal (0, (double)keyChar);
else Assert.Equal (keyChar, unicodeCharacter);
Assert.Equal (consoleKey, expectedVirtualKey);
Assert.Equal (scanCode, expectedScanCode);
var top = Application.Top;
top.KeyPress += (e) => {
var after = ShortcutHelper.GetModifiersKey (e.KeyEvent);
Assert.Equal (expectedRemapping, after);
e.Handled = true;
Application.RequestStop ();
};
var iterations = -1;
Application.Iteration += () => {
iterations++;
if (iterations == 0) Application.Driver.SendKeys ((char)mappedConsoleKey, ConsoleKey.Packet, shift, alt, control);
};
Application.Run ();
Application.Shutdown ();
}
}
public class PacketTest : IEnumerable, IEnumerable<object []> {
public IEnumerator<object []> GetEnumerator ()
{
lock (packetLock) {
yield return new object [] { 'a', false, false, false, 'A', 30, Key.a, 'A', 30 };
yield return new object [] { 'A', true, false, false, 'A', 30, Key.A | Key.ShiftMask, 'A', 30 };
yield return new object [] { 'A', true, true, false, 'A', 30, Key.A | Key.ShiftMask | Key.AltMask, 'A', 30 };
yield return new object [] { 'A', true, true, true, 'A', 30, Key.A | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 'A', 30 };
yield return new object [] { 'z', false, false, false, 'Z', 44, Key.z, 'Z', 44 };
yield return new object [] { 'Z', true, false, false, 'Z', 44, Key.Z | Key.ShiftMask, 'Z', 44 };
yield return new object [] { 'Z', true, true, false, 'Z', 44, Key.Z | Key.ShiftMask | Key.AltMask, 'Z', 44 };
yield return new object [] { 'Z', true, true, true, 'Z', 44, Key.Z | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 'Z', 44 };
yield return new object [] { '英', false, false, false, '\0', 0, (Key)'英', '\0', 0 };
yield return new object [] { '英', true, false, false, '\0', 0, (Key)'英' | Key.ShiftMask, '\0', 0 };
yield return new object [] { '英', true, true, false, '\0', 0, (Key)'英' | Key.ShiftMask | Key.AltMask, '\0', 0 };
yield return new object [] { '英', true, true, true, '\0', 0, (Key)'英' | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '\0', 0 };
yield return new object [] { '+', false, false, false, 187, 26, (Key)'+', 187, 26 };
yield return new object [] { '*', true, false, false, 187, 26, (Key)'*' | Key.ShiftMask, 187, 26 };
yield return new object [] { '+', true, true, false, 187, 26, (Key)'+' | Key.ShiftMask | Key.AltMask, 187, 26 };
yield return new object [] { '+', true, true, true, 187, 26, (Key)'+' | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 187, 26 };
yield return new object [] { '1', false, false, false, '1', 2, Key.D1, '1', 2 };
yield return new object [] { '!', true, false, false, '1', 2, (Key)'!' | Key.ShiftMask, '1', 2 };
yield return new object [] { '1', true, true, false, '1', 2, Key.D1 | Key.ShiftMask | Key.AltMask, '1', 2 };
yield return new object [] { '1', true, true, true, '1', 2, Key.D1 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '1', 2 };
yield return new object [] { '1', false, true, true, '1', 2, Key.D1 | Key.AltMask | Key.CtrlMask, '1', 2 };
yield return new object [] { '2', false, false, false, '2', 3, Key.D2, '2', 3 };
yield return new object [] { '"', true, false, false, '2', 3, (Key)'"' | Key.ShiftMask, '2', 3 };
yield return new object [] { '2', true, true, false, '2', 3, Key.D2 | Key.ShiftMask | Key.AltMask, '2', 3 };
yield return new object [] { '2', true, true, true, '2', 3, Key.D2 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '2', 3 };
yield return new object [] { '@', false, true, true, '2', 3, (Key)'@' | Key.AltMask | Key.CtrlMask, '2', 3 };
yield return new object [] { '3', false, false, false, '3', 4, Key.D3, '3', 4 };
yield return new object [] { '#', true, false, false, '3', 4, (Key)'#' | Key.ShiftMask, '3', 4 };
yield return new object [] { '3', true, true, false, '3', 4, Key.D3 | Key.ShiftMask | Key.AltMask, '3', 4 };
yield return new object [] { '3', true, true, true, '3', 4, Key.D3 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '3', 4 };
yield return new object [] { '£', false, true, true, '3', 4, (Key)'£' | Key.AltMask | Key.CtrlMask, '3', 4 };
yield return new object [] { '4', false, false, false, '4', 5, Key.D4, '4', 5 };
yield return new object [] { '$', true, false, false, '4', 5, (Key)'$' | Key.ShiftMask, '4', 5 };
yield return new object [] { '4', true, true, false, '4', 5, Key.D4 | Key.ShiftMask | Key.AltMask, '4', 5 };
yield return new object [] { '4', true, true, true, '4', 5, Key.D4 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '4', 5 };
yield return new object [] { '§', false, true, true, '4', 5, (Key)'§' | Key.AltMask | Key.CtrlMask, '4', 5 };
yield return new object [] { '5', false, false, false, '5', 6, Key.D5, '5', 6 };
yield return new object [] { '%', true, false, false, '5', 6, (Key)'%' | Key.ShiftMask, '5', 6 };
yield return new object [] { '5', true, true, false, '5', 6, Key.D5 | Key.ShiftMask | Key.AltMask, '5', 6 };
yield return new object [] { '5', true, true, true, '5', 6, Key.D5 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '5', 6 };
yield return new object [] { '€', false, true, true, '5', 6, (Key)'€' | Key.AltMask | Key.CtrlMask, '5', 6 };
yield return new object [] { '6', false, false, false, '6', 7, Key.D6, '6', 7 };
yield return new object [] { '&', true, false, false, '6', 7, (Key)'&' | Key.ShiftMask, '6', 7 };
yield return new object [] { '6', true, true, false, '6', 7, Key.D6 | Key.ShiftMask | Key.AltMask, '6', 7 };
yield return new object [] { '6', true, true, true, '6', 7, Key.D6 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '6', 7 };
yield return new object [] { '6', false, true, true, '6', 7, Key.D6 | Key.AltMask | Key.CtrlMask, '6', 7 };
yield return new object [] { '7', false, false, false, '7', 8, Key.D7, '7', 8 };
yield return new object [] { '/', true, false, false, '7', 8, (Key)'/' | Key.ShiftMask, '7', 8 };
yield return new object [] { '7', true, true, false, '7', 8, Key.D7 | Key.ShiftMask | Key.AltMask, '7', 8 };
yield return new object [] { '7', true, true, true, '7', 8, Key.D7 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '7', 8 };
yield return new object [] { '{', false, true, true, '7', 8, (Key)'{' | Key.AltMask | Key.CtrlMask, '7', 8 };
yield return new object [] { '8', false, false, false, '8', 9, Key.D8, '8', 9 };
yield return new object [] { '(', true, false, false, '8', 9, (Key)'(' | Key.ShiftMask, '8', 9 };
yield return new object [] { '8', true, true, false, '8', 9, Key.D8 | Key.ShiftMask | Key.AltMask, '8', 9 };
yield return new object [] { '8', true, true, true, '8', 9, Key.D8 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '8', 9 };
yield return new object [] { '[', false, true, true, '8', 9, (Key)'[' | Key.AltMask | Key.CtrlMask, '8', 9 };
yield return new object [] { '9', false, false, false, '9', 10, Key.D9, '9', 10 };
yield return new object [] { ')', true, false, false, '9', 10, (Key)')' | Key.ShiftMask, '9', 10 };
yield return new object [] { '9', true, true, false, '9', 10, Key.D9 | Key.ShiftMask | Key.AltMask, '9', 10 };
yield return new object [] { '9', true, true, true, '9', 10, Key.D9 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '9', 10 };
yield return new object [] { ']', false, true, true, '9', 10, (Key)']' | Key.AltMask | Key.CtrlMask, '9', 10 };
yield return new object [] { '0', false, false, false, '0', 11, Key.D0, '0', 11 };
yield return new object [] { '=', true, false, false, '0', 11, (Key)'=' | Key.ShiftMask, '0', 11 };
yield return new object [] { '0', true, true, false, '0', 11, Key.D0 | Key.ShiftMask | Key.AltMask, '0', 11 };
yield return new object [] { '0', true, true, true, '0', 11, Key.D0 | Key.ShiftMask | Key.AltMask | Key.CtrlMask, '0', 11 };
yield return new object [] { '}', false, true, true, '0', 11, (Key)'}' | Key.AltMask | Key.CtrlMask, '0', 11 };
yield return new object [] { '\'', false, false, false, 219, 12, (Key)'\'', 219, 12 };
yield return new object [] { '?', true, false, false, 219, 12, (Key)'?' | Key.ShiftMask, 219, 12 };
yield return new object [] { '\'', true, true, false, 219, 12, (Key)'\'' | Key.ShiftMask | Key.AltMask, 219, 12 };
yield return new object [] { '\'', true, true, true, 219, 12, (Key)'\'' | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 219, 12 };
yield return new object [] { '«', false, false, false, 221, 13, (Key)'«', 221, 13 };
yield return new object [] { '»', true, false, false, 221, 13, (Key)'»' | Key.ShiftMask, 221, 13 };
yield return new object [] { '«', true, true, false, 221, 13, (Key)'«' | Key.ShiftMask | Key.AltMask, 221, 13 };
yield return new object [] { '«', true, true, true, 221, 13, (Key)'«' | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 221, 13 };
yield return new object [] { 'á', false, false, false, 'á', 0, (Key)'á', 'A', 30 };
yield return new object [] { 'Á', true, false, false, 'Á', 0, (Key)'Á' | Key.ShiftMask, 'A', 30 };
yield return new object [] { 'à', false, false, false, 'à', 0, (Key)'à', 'A', 30 };
yield return new object [] { 'À', true, false, false, 'À', 0, (Key)'À' | Key.ShiftMask, 'A', 30 };
yield return new object [] { 'é', false, false, false, 'é', 0, (Key)'é', 'E', 18 };
yield return new object [] { 'É', true, false, false, 'É', 0, (Key)'É' | Key.ShiftMask, 'E', 18 };
yield return new object [] { 'è', false, false, false, 'è', 0, (Key)'è', 'E', 18 };
yield return new object [] { 'È', true, false, false, 'È', 0, (Key)'È' | Key.ShiftMask, 'E', 18 };
yield return new object [] { 'í', false, false, false, 'í', 0, (Key)'í', 'I', 23 };
yield return new object [] { 'Í', true, false, false, 'Í', 0, (Key)'Í' | Key.ShiftMask, 'I', 23 };
yield return new object [] { 'ì', false, false, false, 'ì', 0, (Key)'ì', 'I', 23 };
yield return new object [] { 'Ì', true, false, false, 'Ì', 0, (Key)'Ì' | Key.ShiftMask, 'I', 23 };
yield return new object [] { 'ó', false, false, false, 'ó', 0, (Key)'ó', 'O', 24 };
yield return new object [] { 'Ó', true, false, false, 'Ó', 0, (Key)'Ó' | Key.ShiftMask, 'O', 24 };
yield return new object [] { 'ò', false, false, false, 'Ó', 0, (Key)'ò', 'O', 24 };
yield return new object [] { 'Ò', true, false, false, 'Ò', 0, (Key)'Ò' | Key.ShiftMask, 'O', 24 };
yield return new object [] { 'ú', false, false, false, 'ú', 0, (Key)'ú', 'U', 22 };
yield return new object [] { 'Ú', true, false, false, 'Ú', 0, (Key)'Ú' | Key.ShiftMask, 'U', 22 };
yield return new object [] { 'ù', false, false, false, 'ù', 0, (Key)'ù', 'U', 22 };
yield return new object [] { 'Ù', true, false, false, 'Ù', 0, (Key)'Ù' | Key.ShiftMask, 'U', 22 };
yield return new object [] { 'ö', false, false, false, 'ó', 0, (Key)'ö', 'O', 24 };
yield return new object [] { 'Ö', true, false, false, 'Ó', 0, (Key)'Ö' | Key.ShiftMask, 'O', 24 };
yield return new object [] { '<', false, false, false, 226, 86, (Key)'<', 226, 86 };
yield return new object [] { '>', true, false, false, 226, 86, (Key)'>' | Key.ShiftMask, 226, 86 };
yield return new object [] { '<', true, true, false, 226, 86, (Key)'<' | Key.ShiftMask | Key.AltMask, 226, 86 };
yield return new object [] { '<', true, true, true, 226, 86, (Key)'<' | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 226, 86 };
yield return new object [] { 'ç', false, false, false, 192, 39, (Key)'ç', 192, 39 };
yield return new object [] { 'Ç', true, false, false, 192, 39, (Key)'Ç' | Key.ShiftMask, 192, 39 };
yield return new object [] { 'ç', true, true, false, 192, 39, (Key)'ç' | Key.ShiftMask | Key.AltMask, 192, 39 };
yield return new object [] { 'ç', true, true, true, 192, 39, (Key)'ç' | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 192, 39 };
yield return new object [] { '¨', false, true, true, 187, 26, (Key)'¨' | Key.AltMask | Key.CtrlMask, 187, 26 };
yield return new object [] { (uint)Key.PageUp, false, false, false, 33, 73, Key.PageUp, 33, 73 };
yield return new object [] { (uint)Key.PageUp, true, false, false, 33, 73, Key.PageUp | Key.ShiftMask, 33, 73 };
yield return new object [] { (uint)Key.PageUp, true, true, false, 33, 73, Key.PageUp | Key.ShiftMask | Key.AltMask, 33, 73 };
yield return new object [] { (uint)Key.PageUp, true, true, true, 33, 73, Key.PageUp | Key.ShiftMask | Key.AltMask | Key.CtrlMask, 33, 73 };
}
}
IEnumerator IEnumerable.GetEnumerator () => GetEnumerator ();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _07.GreatestOfFive
{
class GreatestOfFive
{
static void Main()
{
Console.WriteLine("Enter three numbers and see the biggest of them:");
int firstNum = int.Parse(Console.ReadLine());
int secondNum = int.Parse(Console.ReadLine());
int thirdNum = int.Parse(Console.ReadLine());
int fourthNum = int.Parse(Console.ReadLine());
int fifthNum = int.Parse(Console.ReadLine());
if (firstNum != 0 && secondNum != 0 && thirdNum != 0 && fourthNum != 0 && fifthNum != 0)
{
Console.WriteLine("The biggest number is:");
if (firstNum > secondNum && firstNum > thirdNum && firstNum > fourthNum && firstNum > fifthNum)
{
Console.WriteLine(firstNum);
}
if (secondNum > firstNum && secondNum > thirdNum && secondNum > fourthNum && secondNum > fifthNum)
{
Console.WriteLine(secondNum);
}
if (thirdNum > firstNum && thirdNum > secondNum && thirdNum > fourthNum && thirdNum > fifthNum)
{
Console.WriteLine(thirdNum);
}
if (fourthNum > firstNum && fourthNum > secondNum && fourthNum > thirdNum && fourthNum > fifthNum)
{
Console.WriteLine(fourthNum);
}
if (fifthNum > firstNum && fifthNum > secondNum && fifthNum > thirdNum && fifthNum > fourthNum)
{
Console.WriteLine(fifthNum);
}
}
else
{
Console.WriteLine("The numbers are equal!");
}
}
}
}
|
using System.Collections.Generic;
#nullable disable
namespace Algorithms.LeetCode
{
public class ConstructBinaryTreeFromPreorderAndInorderTraversal
{
public TreeNode BuildTree(int[] preorder, int[] inorder)
{
var rootIndexes = new Dictionary<int, int>();
for (int i = 0; i < inorder.Length; ++i)
rootIndexes.Add(inorder[i], i);
var preorderIndex = 0;
return BuildTree(preorder, ref preorderIndex, 0, inorder.Length - 1, rootIndexes);
}
private TreeNode BuildTree(int[] preorder, ref int preorderIndex, int left, int right, Dictionary<int, int> rootIndexes)
{
if (left > right)
return null;
var rootValue = preorder[preorderIndex++];
var rootIndex = rootIndexes[rootValue];
var root = new TreeNode(rootValue);
root.left = BuildTree(preorder, ref preorderIndex, left, rootIndex - 1, rootIndexes);
root.right = BuildTree(preorder, ref preorderIndex, rootIndex + 1, right, rootIndexes);
return root;
}
#region Definition for a binary tree node.
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
{
this.val = val;
this.left = left;
this.right = right;
}
}
#endregion
}
} |
namespace Uintra.Core.Jobs.Configuration
{
public interface IJobSettingsConfiguration
{
JobSettingsCollection Settings { get; }
}
}
|
using System;
namespace PlayerTracker.Models
{
public class Note
{
public int Id { get; set; }
private string _content;
public string Content
{
get { return _content; }
set
{
this.DateUpdated = DateTime.Now;
_content = value;
}
}
public DateTime? DateUpdated { get; set; } = DateTime.Now;
public void WasUpdated() => this.DateUpdated = DateTime.Now;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.