text stringlengths 13 6.01M |
|---|
using Microsoft.EntityFrameworkCore;
using SkillsGardenApi.Models;
using SkillsGardenApi.Repositories.Context;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SkillsGardenApi.Repositories
{
public class ComponentRepository : IDatabaseRepository<Component>
{
private readonly DatabaseContext ctx;
public ComponentRepository(DatabaseContext ctx)
{
this.ctx = ctx;
}
/**
* Create
*/
public async Task<Component> CreateAsync(Component component)
{
ctx.Components.Add(component);
await ctx.SaveChangesAsync();
return component;
}
/**
* Delete
*/
public async Task<bool> DeleteAsync(int id)
{
Component component = await ReadAsync(id);
if (component == null)
{
return false;
}
ctx.Components.Remove(component);
await ctx.SaveChangesAsync();
return true;
}
/**
* List
*/
public async Task<List<Component>> ListAsync()
{
return await ctx.Components.ToListAsync();
}
/**
* Read
*/
public async Task<Component> ReadAsync(int componentId)
{
return await ctx.Components
.Include(c => c.ComponentExercises)
.Where(c => c.Id == componentId)
.FirstOrDefaultAsync();
}
/**
* Update
*/
public async Task<Component> UpdateAsync(Component component)
{
Component componentToBeUpdated = await ctx.Components.Where(x => x.Id == component.Id).FirstOrDefaultAsync();
if (componentToBeUpdated == null || component == null)
{
return null;
}
if (component.Name != null) componentToBeUpdated.Name = component.Name;
if (component.Description != null) componentToBeUpdated.Description = component.Description;
if (component.Image != null) componentToBeUpdated.Image = component.Image;
if (component.ComponentExercises != null) componentToBeUpdated.ComponentExercises = component.ComponentExercises;
await ctx.SaveChangesAsync();
return componentToBeUpdated;
}
/**
* Exists
*/
public async Task<bool> ComponentExists(int componentId)
{
return await ctx.Components.Where(x => x.Id == componentId).FirstOrDefaultAsync() != null;
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
public class InventoryUI : MonoBehaviour {
public GameObject inventoryUI;
public Transform itemsParent;
private static bool created = false;
Inventory inventory;
// Use this for initialization
void Start()
{
}
void Awake()
{
if (!created)
{
DontDestroyOnLoad(this.gameObject);
inventory = Inventory.instance;
inventory.onItemChangedCallback += UpdateUI;
created = true;
UpdateUI();
}
}
// Update is called once per frame
void Update () {
}
public void UpdateUI()
{
InventorySlot[] slots = GetComponentsInChildren<InventorySlot>();
for (int i = 0; i < slots.Length; i++)
{
Debug.Log("UpdateUI " + i);
if (i < inventory.items.Count)
slots[i].AddItem(inventory.items[i]);
else
slots[i].ClearSlot();
}
}
}
|
using System;
using Platformer.Gameplay;
using UnityEngine;
using static Platformer.Core.Simulation;
namespace Platformer.Mechanics
{
/// <summary>
/// Represebts the current vital statistics of some game entity.
/// </summary>
public class Health : MonoBehaviour
{
GameObject donut;
SkillTree skillT;
public int damageReduction = 0;
/// <summary>
/// The maximum hit points for the entity.
/// </summary>
public int maxHP = 1;
/// <summary>
/// Indicates if the entity should be considered 'alive'.
/// </summary>
public bool IsAlive => currentHP > 0;
public int currentHP;
/// <summary>
/// Increment the HP of the entity.
/// </summary>
///
private void Start()
{
donut = GameObject.Find("Donut");
skillT = donut.GetComponent<SkillTree>();
}
public void Increment(int value)
{
currentHP = Mathf.Clamp(currentHP + value, 0, maxHP);
}
/// <summary>
/// Decrement the HP of the entity. Will trigger a HealthIsZero event when
/// current HP reaches 0.
/// </summary>
public void Decrement(int value)
{
if (gameObject.tag == "Player")
{
for (int i = 0; i < skillT.sTree.Length; i++)
{
if (skillT.sTree[i].skilButtonID == "e1" && skillT.sTree[i].abilityLevel >= 1)
{
damageReduction += 1 * skillT.sTree[i].abilityLevel;
}
if (skillT.sTree[i].skilButtonID == "e2" && skillT.sTree[i].abilityLevel >= 1)
{
damageReduction += 2 * skillT.sTree[i].abilityLevel;
}
if (skillT.sTree[i].skilButtonID == "e3" && skillT.sTree[i].abilityLevel >= 1)
{
damageReduction += 3 * skillT.sTree[i].abilityLevel;
}
}
int damageToTake = Mathf.Clamp(value - damageReduction, 0, maxHP);
currentHP = Mathf.Clamp(currentHP - damageToTake, 0, maxHP);
}
else
{
currentHP = Mathf.Clamp(currentHP - value, 0, maxHP);
}
if (currentHP == 0)
{
var ev = Schedule<HealthIsZero>();
ev.health = this;
}
}
/// <summary>
/// Decrement the HP of the entitiy until HP reaches 0.
/// </summary>
public void Die()
{
Decrement(currentHP);
}
void Awake()
{
//currentHP = maxHP;
}
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using GoalBook.SharedKernel;
using GoalBook.Core.Domain.Entities;
namespace GoalBook.Api.Controllers
{
[ApiController]
[Route("api/[controller]/")]
public class GoalController : ControllerBase
{
private readonly IRepository<Goal> _repository;
public GoalController(IRepository<Goal> repository)
{
_repository = repository;
}
[HttpGet]
[Route("get-all")]
public IActionResult GetGoals()
{
return Ok(_repository.GetAll());
}
[HttpGet("id")]
[Route("get")]
public async Task<IActionResult> GetGoal(string id)
{
if (Guid.TryParse(id, out var goalId))
{
var goal = await _repository.GetByIdAsync(goalId);
return goal != null
? Ok(goal)
: NoContent();
}
return BadRequest();
}
[HttpPost]
[Route("create")]
public async Task<IActionResult> CreateGoal([FromBody] Goal goal)
{
await _repository.CreateAsync(goal);
return CreatedAtRoute("get", new { id = goal.Id.ToString() }, goal);
}
[HttpPut]
[Route("update")]
public async Task<IActionResult> UpdateGoal([FromBody] Goal goal)
{
var result = await _repository.UpdateAsync(goal);
return result
? NoContent()
: BadRequest();
}
[HttpDelete("id")]
[Route("delete")]
public async Task<IActionResult> DeleteGoal(string id)
{
if (Guid.TryParse(id, out var goalId))
{
var result = await _repository.DeleteAsync(goalId);
return result
? NoContent()
: BadRequest();
}
return BadRequest();
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MooshakPP.Services;
using MooshakPP.Models.Entities;
namespace MooshakPP.Tests.Services
{
[TestClass]
public class AdminServiceTest
{
private AdminService service;
[TestInitialize]
public void Initialize()
{
var mockDb = new MockDatabase();
//initilizing the fake DB for ManageCourse and RemoveCourse testing
var c1 = new Course
{
ID = 1,
name = "Gagnaskipan",
};
mockDb.Courses.Add(c1);
var c2 = new Course
{
ID = 3,
name = "Forritun",
};
mockDb.Courses.Add(c2);
var c3 = new Course
{
ID = 33,
name = "Vefforitun 2",
};
mockDb.Courses.Add(c3);
service = new AdminService(mockDb);
}
#region Tests for ManageCourse
[TestMethod]
public void TestManageCourseIdOne()
{
// Arrange:
const int courseID = 1;
// Act:
var result = service.ManageCourse(courseID);
// Assert:
Assert.AreEqual("Gagnaskipan", result.currentCourse.name);
Assert.AreEqual(3, result.courses.Count);
}
[TestMethod]
public void TestManageCourseIdNull()
{
// Arrange:
int? courseID = null;
// Act:
var result = service.ManageCourse(courseID);
// Assert:
Assert.AreEqual(null, result.currentCourse.name);
Assert.AreEqual(3, result.courses.Count);
}
[TestMethod]
public void TestManageCourseIdNotInDB()
{
// Arrange:
int? courseID = 4;
// Act:
var result = service.ManageCourse(courseID);
// Assert:
Assert.AreEqual(null, result.currentCourse.name);
Assert.AreEqual(3, result.courses.Count);
}
#endregion
#region Test for RemoveCourse
[TestMethod]
public void RemoveCourseIdNotInDb()
{
// Arrange:
int courseID = 4;
// Act:
var result = service.RemoveCourse(courseID);
// Assert:
Assert.AreEqual(false, result);
}
[TestMethod]
public void RemoveCourseIdOne()
{
// Arrange:
int courseID = 1;
// Act:
var result = service.RemoveCourse(courseID);
// Assert:
Assert.AreEqual(true, result);
}
#endregion
#region Tests for CreateCourse
[TestMethod]
public void TestCreateCourseForDummyCourse()
{
// Arrange:
Course dummyCourse = new Course();
dummyCourse.name = "arbritary";
// Act:
var result = service.CreateCourse(dummyCourse);
// Assert:
Assert.AreEqual(true, result);
}
[TestMethod]
public void TestCreateCourseForCourseNull()
{
// Arrange:
Course dummyCourse = new Course();
// Act:
var result = service.CreateCourse(dummyCourse);
// Assert:
Assert.AreEqual(false, result);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace HocChuCai_2.Objects
{
public enum ButtState
{
Close,
Open
}
public partial class Butt : UserControl
{
private ButtState _buttState = ButtState.Close;
private int _id;
public int ID
{
get { return _id; }
set { _id = value; }
}
public ButtState ButtState
{
get { return _buttState; }
set { _buttState = value; }
}
public string Character
{
get { return this.textBlock.Text; }
set { this.textBlock.Text = value; }
}
public Butt()
{
InitializeComponent();
}
public void OpenHead()
{
this.stbOpenButt.Begin();
}
public void CloseHead()
{
this.stbCloseButt.Begin();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CardExample
{
[CreateAssetMenu(fileName = "New Card", menuName = "Card")]
public class Card : ScriptableObject
{
[SerializeField] private new string name;
public string Name
{
get { return name; }
protected set { }
}
[SerializeField] private string description;
public string Description
{
get { return description; }
protected set { }
}
[SerializeField] private Sprite artwork;
public Sprite ArtWork
{
get { return artwork; }
protected set { }
}
[SerializeField] private int manaCost;
public int ManaCost
{
get { return manaCost; }
protected set { }
}
[SerializeField] private int attack;
public int Attack
{
get { return attack; }
protected set { }
}
[SerializeField] private int health;
public int Health
{
get { return health; }
protected set { }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace API.Models
{
public partial class Disco
{
[JsonProperty("idDisco", Required = Required.Always)]
public int IdDisco { get; set; }
[JsonProperty("Espaco", Required = Required.Always)]
public int Espaco { get; set; }
[JsonProperty("Marca", Required = Required.Always)]
public string Marca { get; set; }
[JsonProperty("N_Disco", Required = Required.Always)]
public int NDisco { get; set; }
[JsonProperty("Maquina_Disco", Required = Required.Always)]
public int MaquinaDisco { get; set; }
}
} |
/** 版本信息模板在安装目录下,可自行修改。
* ROLL_NEWS.cs
*
* 功 能: N/A
* 类 名: ROLL_NEWS
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2014/8/6 15:00:47 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using Maticsoft.DBUtility;
using System.Collections.Generic;
using System.Data.SqlClient;//Please add references
namespace PDTech.OA.DAL
{
/// <summary>
/// 数据访问类:ROLL_NEWS
/// </summary>
public partial class ROLL_NEWS
{
public ROLL_NEWS()
{}
#region BasicMethod
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(string NEWS_TITLE)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) from ROLL_NEWS");
strSql.Append(" where NEWS_TITLE=@NEWS_TITLE ");
SqlParameter[] parameters = {
new SqlParameter("@NEWS_TITLE", SqlDbType.NVarChar) };
parameters[0].Value = NEWS_TITLE;
return DbHelperSQL.Exists(strSql.ToString(),parameters);
}
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(string NEWS_TITLE, decimal NEWS_ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from ROLL_NEWS");
strSql.Append(" where NEWS_TITLE=@NEWS_TITLE AND NEWS_ID<>@NEWS_ID ");
SqlParameter[] parameters = {
new SqlParameter("@NEWS_TITLE", SqlDbType.NVarChar),
new SqlParameter("@NEWS_ID", SqlDbType.Decimal,4) };
parameters[0].Value = NEWS_TITLE;
parameters[1].Value = NEWS_ID;
return DbHelperSQL.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 增加一条数据
/// </summary>
public int Add(PDTech.OA.Model.ROLL_NEWS model)
{
if (Exists(model.NEWS_TITLE))
{
return -1;
}
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into ROLL_NEWS(");
strSql.Append("NEWS_TITLE,NEWS_CONTENT,CREATOR,CREATE_TIME,IS_ROLLING)");
strSql.Append(" values (");
strSql.Append("@NEWS_TITLE,@NEWS_CONTENT,@CREATOR,@CREATE_TIME,@IS_ROLLING)");
SqlParameter[] parameters = {
//new SqlParameter("@NEWS_ID", SqlDbType.Decimal,4),
new SqlParameter("@NEWS_TITLE", SqlDbType.NVarChar),
new SqlParameter("@NEWS_CONTENT", SqlDbType.Text),
new SqlParameter("@CREATOR", SqlDbType.Decimal,4),
new SqlParameter("@CREATE_TIME", SqlDbType.DateTime),
new SqlParameter("@IS_ROLLING", SqlDbType.Decimal,4)};
//parameters[0].Value = model.NEWS_ID;
parameters[0].Value = model.NEWS_TITLE;
parameters[1].Value = model.NEWS_CONTENT;
parameters[2].Value = model.CREATOR;
parameters[3].Value = model.CREATE_TIME;
parameters[4].Value = model.IS_ROLLING;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return 1;
}
else
{
return 0;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public int Update(PDTech.OA.Model.ROLL_NEWS model)
{
if (Exists(model.NEWS_TITLE, model.NEWS_ID))
{
return -1;
}
StringBuilder strSql=new StringBuilder();
strSql.Append("update ROLL_NEWS set ");
strSql.Append("NEWS_TITLE=@NEWS_TITLE,");
strSql.Append("NEWS_CONTENT=@NEWS_CONTENT,");
strSql.Append("CREATOR=@CREATOR,");
strSql.Append("CREATE_TIME=@CREATE_TIME,");
strSql.Append("IS_ROLLING=@IS_ROLLING");
strSql.Append(" where NEWS_ID=@NEWS_ID ");
SqlParameter[] parameters = {
new SqlParameter("@NEWS_TITLE", SqlDbType.NVarChar),
new SqlParameter("@NEWS_CONTENT", SqlDbType.Text),
new SqlParameter("@CREATOR", SqlDbType.Decimal,4),
new SqlParameter("@CREATE_TIME", SqlDbType.DateTime),
new SqlParameter("@IS_ROLLING", SqlDbType.Decimal,4),
new SqlParameter("@NEWS_ID", SqlDbType.Decimal,4)};
parameters[0].Value = model.NEWS_TITLE;
parameters[1].Value = model.NEWS_CONTENT;
parameters[2].Value = model.CREATOR;
parameters[3].Value = model.CREATE_TIME;
parameters[4].Value = model.IS_ROLLING;
parameters[5].Value = model.NEWS_ID;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return 1;
}
else
{
return 0;
}
}
public bool Update(string NEWS_IDlist, decimal isRolling)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update ROLL_NEWS set IS_ROLLING = " + isRolling.ToString());
strSql.Append(" where NEWS_ID in (" + NEWS_IDlist + ") ");
int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(decimal NEWS_ID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from ROLL_NEWS ");
strSql.Append(" where NEWS_ID=@NEWS_ID ");
SqlParameter[] parameters = {
new SqlParameter("@NEWS_ID", SqlDbType.Decimal,22) };
parameters[0].Value = NEWS_ID;
int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteList(string NEWS_IDlist )
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from ROLL_NEWS ");
strSql.Append(" where NEWS_ID in ("+NEWS_IDlist + ") ");
int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public PDTech.OA.Model.ROLL_NEWS GetModel(decimal NEWS_ID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select NEWS_ID,NEWS_TITLE,NEWS_CONTENT,CREATOR,CREATE_TIME,IS_ROLLING from ROLL_NEWS ");
strSql.Append(" where NEWS_ID=@NEWS_ID ");
SqlParameter[] parameters = {
new SqlParameter("@NEWS_ID", SqlDbType.Decimal,22) };
parameters[0].Value = NEWS_ID;
PDTech.OA.Model.ROLL_NEWS model=new PDTech.OA.Model.ROLL_NEWS();
DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
if(ds.Tables[0].Rows.Count>0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public PDTech.OA.Model.ROLL_NEWS DataRowToModel(DataRow row)
{
PDTech.OA.Model.ROLL_NEWS model=new PDTech.OA.Model.ROLL_NEWS();
if (row != null)
{
if(row["NEWS_ID"]!=null && row["NEWS_ID"].ToString()!="")
{
model.NEWS_ID=decimal.Parse(row["NEWS_ID"].ToString());
}
if(row["NEWS_TITLE"]!=null)
{
model.NEWS_TITLE=row["NEWS_TITLE"].ToString();
}
if (row["NEWS_CONTENT"] != null)
{
model.NEWS_CONTENT = row["NEWS_CONTENT"].ToString();
}
if(row["CREATOR"]!=null && row["CREATOR"].ToString()!="")
{
model.CREATOR=decimal.Parse(row["CREATOR"].ToString());
}
if(row["CREATE_TIME"]!=null && row["CREATE_TIME"].ToString()!="")
{
model.CREATE_TIME=DateTime.Parse(row["CREATE_TIME"].ToString());
}
if(row["IS_ROLLING"]!=null && row["IS_ROLLING"].ToString()!="")
{
model.IS_ROLLING=decimal.Parse(row["IS_ROLLING"].ToString());
}
}
return model;
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select NEWS_ID,NEWS_TITLE,NEWS_CONTENT,CREATOR,CREATE_TIME,IS_ROLLING ");
strSql.Append(" FROM ROLL_NEWS ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
strSql.Append(" order by NEWS_ID ");
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 获取记录总数
/// </summary>
public int GetRecordCount(string strWhere)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) FROM ROLL_NEWS ");
if(strWhere.Trim()!="")
{
strSql.Append(" where "+strWhere);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString());
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
public IList<Model.ROLL_NEWS> Get_Paging_List(string title, int currentpage, int pagesize, out int totalrecord)
{
string strSQL = string.Empty;
if (!string.IsNullOrEmpty(title))
{
strSQL = string.Format("SELECT TOP (100) PERCENT * from ROLL_NEWS WHERE NEWS_TITLE like '%{0}%' order by NEWS_ID desc ", title);
}
else
{
strSQL = string.Format("SELECT TOP (100) PERCENT * from ROLL_NEWS order by NEWS_ID desc ");
}
PageDescribe pdes = new PageDescribe();
pdes.CurrentPage = currentpage;
pdes.PageSize = pagesize;
DataTable dt = pdes.PageDescribes(strSQL);
totalrecord = pdes.RecordCount;
return DAL_Helper.CommonFillList<Model.ROLL_NEWS>(dt);
}
/*
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
SqlParameter[] parameters = {
new SqlParameter("@tblName", SqlDbType.VarChar, 255),
new SqlParameter("@fldName", SqlDbType.VarChar, 255),
new SqlParameter("@PageSize", SqlDbType.Number),
new SqlParameter("@PageIndex", SqlDbType.Number),
new SqlParameter("@IsReCount", SqlDbType.Clob),
new SqlParameter("@OrderType", SqlDbType.Clob),
new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
};
parameters[0].Value = "ROLL_NEWS";
parameters[1].Value = "NEWS_ID";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}*/
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
|
using Microsoft.EntityFrameworkCore;
using MyPage.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyPage.Data.DAL
{
public class AcessoDAL
{
private readonly Contexto _contexto;
public AcessoDAL(Contexto contexto)
{
_contexto = contexto;
}
public IQueryable<Acesso> GetAcessos()
{
return _contexto.Acessos
.Include(a => a.Usuario)
.OrderByDescending(a => a.DataAcesso);
}
}
}
|
using System;
using System.Collections.Generic;
using PropertyManager.Interfaces;
using PropertyManager.Models;
namespace PropertyManager.Data
{
// A mocker just creates a class repository where you can quickly set hardcoded values for testing
public class MockCommanderRepo : ICommanderRepo
{
public void CreateCommand(Command command)
{
throw new NotImplementedException();
}
public void DeleteCommand(Command command)
{
throw new NotImplementedException();
}
public IEnumerable<Command> GetAppCommands()
{
return new List<Command>() {
new Command
{
Id = 1,
HowTo = "Boil an Egg",
Line = "Boil Water with Egg in it",
Platform = "Kettle & Pan"
},
new Command
{
Id = 2,
HowTo = "Boil an Egg",
Line = "Boil Water with Egg in it",
Platform = "Kettle & Pan"
},
new Command
{
Id = 3,
HowTo = "Boil an Egg",
Line = "Boil Water with Egg in it",
Platform = "Kettle & Pan"
}
};
}
public Command GetCommandById(int Id)
{
return new Command
{
Id = 1,
HowTo = "Boil an Egg",
Line = "Boil Water with Egg in it",
Platform = "Kettle & Pan"
};
}
public bool SaveChanges()
{
throw new NotImplementedException();
}
public void UpdatedCommand(Command command)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Linq;
using System.Text;
using System.Web;
using Aqueduct.Domain;
using Aqueduct.SitecoreLib.Domain;
namespace Aqueduct.SitecoreLib.Examples.SampleApplication.Web.Classes
{
public static class RenderingExtensions
{
public static string GetImage<T>(this T entity, Func<T, Image> expression) where T : class
{
return GetImage(entity, expression, 0, string.Empty, string.Empty);
}
public static string GetImage<T>(this T entity, Func<T, Image> expression, int width) where T : class
{
return GetImage(entity, expression, width, string.Empty, string.Empty);
}
public static string GetImage<T>(this T entity, Func<T, Image> expression, string cssClass) where T : class
{
return GetImage(entity, expression, 0, cssClass, string.Empty);
}
public static string GetImage<T>(this T entity, Func<T, Image> expression, string cssClass, string dataAttributes) where T : class
{
return GetImage(entity, expression, 0, cssClass, dataAttributes);
}
public static string GetImage<T>(this T entity, Func<T, Image> expression, int width, string cssClass, string dataAttributes) where T : class
{
if (entity != null)
{
var image = expression.Invoke(entity);
if (image != null && !string.IsNullOrEmpty(image.Url))
{
string newSrc;
if (width > 0)
newSrc = string.Format("{0}?mw={1}", image.Url, width);
else
newSrc = string.Format("{0}", image.Url);
var sb = new StringBuilder(string.Format("<img src=\"{0}\"", newSrc));
if (!string.IsNullOrEmpty(image.Alt))
sb.Append(string.Format(" alt=\"{0}\"", HttpUtility.HtmlEncode(image.Alt)));
if (!string.IsNullOrEmpty(cssClass))
sb.Append(string.Format(" class=\"{0}\"", cssClass));
if (!string.IsNullOrEmpty(dataAttributes))
sb.Append(string.Format(" {0}", dataAttributes));
sb.Append("/>");
return sb.ToString();
}
}
return string.Empty;
}
public static string GetAnchorImage(this Image image, string cssClass, string dataAttributes)
{
return GetAnchorImage(image, x => x, 0, cssClass, dataAttributes);
}
public static string GetAnchorImage(this Image image, string cssClass)
{
return GetAnchorImage(image, x => x, 0, cssClass, null);
}
public static string GetAnchorImage<T>(this T entity, Func<T, Image> expression, int width, string cssClass, string dataAttributes) where T : class
{
if (entity != null)
{
var image = expression.Invoke(entity);
if (image != null && !string.IsNullOrEmpty(image.Url))
{
string newSrc = "";
if (width > 0)
newSrc = string.Format("{0}?mw={1}", image.Url, width);
else
newSrc = string.Format("{0}?mw={1}", image.Url, image.Width);
var sb = new StringBuilder(string.Format("<a href=\"{0}\"", newSrc));
if (!string.IsNullOrEmpty(cssClass))
sb.Append(string.Format(" class=\"{0}\"", cssClass));
if (!string.IsNullOrEmpty(dataAttributes))
sb.Append(string.Format(" {0}", dataAttributes));
if (!string.IsNullOrEmpty(image.Alt))
sb.Append(string.Format(">{0}</a>", HttpUtility.HtmlEncode(image.Alt)));
else
sb.Append("></a>");
return sb.ToString();
}
}
return string.Empty;
}
public static string GetImage(this Image image)
{
return GetImage(image, x => x, 0);
}
public static string GetImage(this Image image, int width)
{
return GetImage(image, x => x, width);
}
public static string GetImage(this Image image, string cssClass)
{
return GetImage(image, x => x, 0, cssClass, string.Empty);
}
public static string GetImage(this Image image, string cssClass, string dataAttributes)
{
return GetImage(image, x => x, 0, cssClass, dataAttributes);
}
public static string GetImage(this Image image, int width, string cssClass, string dataAttributes)
{
return GetImage(image, x => x, width, cssClass, dataAttributes);
}
public static string BeginAnchorTag(this Link link)
{
if (link.IsValidLink())
{
return !string.IsNullOrEmpty(link.Target)
? string.Format("<a href='{0}' target='{1}'>", link.Url, link.Target)
: string.Format("<a href='{0}'>", link.Url);
}
return string.Empty;
}
public static string BeginAnchorTag(this Link link, string cssClass)
{
if (link.IsValidLink())
{
return !string.IsNullOrEmpty(link.Target)
? string.Format("<a href='{0}' target='{1}' class='{2}'>", link.Url, link.Target, cssClass)
: string.Format("<a href='{0}' class='{1}'>", link.Url, cssClass);
}
return string.Empty;
}
public static string EndAnchorTag(this Link link)
{
return link.IsValidLink() ? "</a>" : string.Empty;
}
public static string RendorAnchorTag(this Link link)
{
return RenderAnchorTag(link, string.Empty);
}
public static string RenderAnchorTag(this Link link, string cssClass)
{
if (!link.IsValidLink()) return string.Empty;
var beginTag = string.IsNullOrEmpty(cssClass) ? BeginAnchorTag(link) : BeginAnchorTag(link, cssClass);
return string.Format("{0}{1}</a>", beginTag, link.Caption);
}
public static bool IsValidLink(this Link link)
{
return link != null && !string.IsNullOrEmpty(link.Url);
}
public static string BoldFirstWord(this string original)
{
if (string.IsNullOrEmpty(original)) return original;
var split = original.Split(null);
if (split.Any())
{
var firstWord = split.First();
return original.Replace(firstWord, string.Format(@"<strong>{0}</strong>", firstWord));
}
return original;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class GeneralGame : MonoBehaviour
{
public DetailsPanelHandler targetDetailsPanel;
public LayerMask interactLayer;
Shader generalShader;
Shader outlinedShader;
Renderer targetRenderer;
public Color firstOutlineColor = Color.red;
public float firstOutlineWidth = 0.05f;
public Color secondOutlineColor = Color.blue;
public float secondOutlineWidth = 0.0f;
private void Start()
{
generalShader = Shader.Find("Standard");
outlinedShader = Shader.Find("Outlined/UltimateOutline");
LootSystem lootSystem = new LootSystem();
}
public void ToggleOutline(Renderer renderer, bool show)
{
renderer.material.shader = show ? outlinedShader : generalShader;
if (show)
{
renderer.material.SetColor("_FirstOutlineColor", firstOutlineColor);
renderer.material.SetFloat("_FirstOutlineWidth", firstOutlineWidth);
renderer.material.SetColor("_SecondOutlineColor", secondOutlineColor);
renderer.material.SetFloat("_SecondOutlineWidth", secondOutlineWidth);
}
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, 100, interactLayer))
{
NpcHandler npc = hit.transform.GetComponent<NpcHandler>();
if (!npc)
return;
if (npc.GetComponent<PlayerHandler>())
return;
if (!targetRenderer || targetRenderer.gameObject != npc.gameObject)
{
if (targetRenderer)
ToggleOutline(targetRenderer, false);
targetRenderer = npc.GetComponentInChildren<MeshRenderer>();
ToggleOutline(targetRenderer, true);
}
targetDetailsPanel.UpdateData(npc);
targetDetailsPanel.gameObject.SetActive(true);
}
else
{
if (targetRenderer)
{
ToggleOutline(targetRenderer, false);
targetRenderer = null;
}
targetDetailsPanel.gameObject.SetActive(false);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2 {
class Day18 {
internal static string input = ".^^..^...^..^^.^^^.^^^.^^^^^^.^.^^^^.^^.^^^^^^.^...^......^...^^^..^^^.....^^^^^^^^^....^^...^^^^..^";
internal static int rowlength;
internal static int rows = 400000;
internal static List<bool> tiles = new List<bool>(); // true = trap; false = safe
internal static void part1() {
//input = ".^^.^.^^^^";
foreach (char c in input) {
if (c == '.') {
tiles.Add(false);
} else {
tiles.Add(true);
}
}
int currentrow = 0;
rowlength = input.Length;
while (currentrow < rows - 1) {
for (int i = 0; i < input.Length; i++) {
bool left, center, right;
if (i == 0) { // first tile on row
left = false;
center = tiles[i + currentrow * rowlength];
right = tiles[i + 1 + currentrow * rowlength];
} else if (i == input.Length - 1) { // last tile on row
left = tiles[i - 1 + currentrow * rowlength];
center = tiles[i + currentrow * rowlength];
right = false;
} else {
left = tiles[i - 1 + currentrow * rowlength];
center = tiles[i + currentrow * rowlength];
right = tiles[i + 1 + currentrow * rowlength];
}
tiles.Add(isTrap(left, center, right));
}
currentrow++;
}
//printmap();
Console.WriteLine(tiles.Count(x => x == false));
}
private static void printmap() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < input.Length; j++) {
Console.Write(tiles[j + i * input.Length] ? '^' : '.');
}
Console.Write("\n");
}
}
private static bool isTrap(bool left, bool center, bool right) {
if ((left && center && !right) || (!left && center && right) || (left && !center && !right) || (!left && !center && right)) {
return true;
} else {
return false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model.DataEntity;
using Model.Security.MembershipManagement;
using Business.Helper;
using System.ComponentModel;
using Model.Locale;
namespace eIVOGo.Module.EIVO
{
public partial class AllowancePrintView : System.Web.UI.UserControl
{
protected InvoiceAllowance _item;
protected UserProfileMember _userProfile;
protected void Page_Load(object sender, EventArgs e)
{
_userProfile = WebPageUtility.UserProfile;
}
[Bindable(true)]
public int? AllowanceID
{
get;
set;
}
[Bindable(true)]
public bool? IsFinal
{
get;
set;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreRender += new EventHandler(AllowancePrintView_PreRender);
this.Page.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
}
void Page_PreRenderComplete(object sender, EventArgs e)
{
var mgr = dsEntity.CreateDataManager();
if (!_item.CDS_Document.DocumentPrintLog.Any(l => l.TypeID == (int)Naming.DocumentTypeDefinition.E_Allowance))
{
_item.CDS_Document.DocumentPrintLog.Add(new DocumentPrintLog
{
PrintDate = DateTime.Now,
UID = _userProfile.UID,
TypeID = (int)Naming.DocumentTypeDefinition.E_Allowance
});
}
mgr.DeleteAnyOnSubmit<DocumentPrintQueue>(d => d.DocID == _item.AllowanceID);
mgr.SubmitChanges();
}
protected virtual void AllowancePrintView_PreRender(object sender, EventArgs e)
{
if (AllowanceID.HasValue)
{
var mgr = dsEntity.CreateDataManager();
_item = mgr.GetTable<InvoiceAllowance>().Where(i => i.AllowanceID == AllowanceID).FirstOrDefault();
balanceView.Item = _item;
accountingView.Item = _item;
this.DataBind();
}
}
}
} |
/*
Description: This file declares the Assignment ViewModel and its properties
for the Assignment Controller and views.
Author: EAS
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using static Project._1.Models.Assignment;
using static Project._1.Models.ProbationaryColleague;
namespace Release2.ViewModels
{
/// <summary>
/// Assignment view model from Assignment model and used by Assignment controller
/// </summary>
public class AssignmentViewModel
{
public int Id { get; set; }
public int DepartmentId { get; set; }
public string Department { get; set; }
[Display(Name = "Probation Type")]
public ProbationTypes ProbationType { get; set; }
[Display(Name = "Assignment Creation")]
[Column(TypeName = "date")]
public DateTime? AssignmentDate { get; set; }
[Display(Name = "Assignement Status")]
public AssignStatus AssignmentStatus { get; set; }
[Display(Name = "Inspection Date")]
[Column(TypeName = "date")]
public DateTime? AssignmentInspectionDate { get; set; }
public int HRAssignId { get; set; }
public int LMAssignId { get; set; }
public int? LMInspectId { get; set; }
public int PCId { get; set; }
[Display(Name = "HR Associate")]
public string HRAssigns { get; set; }
[Display(Name = "Assigned to")]
public string LMAssigned { get; set; }
[Display(Name = "Inspected by")]
public string LMInspects { get; set; }
[Display(Name = "Probationary Colleague")]
public string ProbationaryColleague { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
using OmniSharp.Extensions.DebugAdapter.Testing;
using OmniSharp.Extensions.JsonRpc.Testing;
using Xunit;
using Xunit.Abstractions;
namespace Dap.Tests.Integration
{
public class CustomRequestsTests : DebugAdapterProtocolTestBase
{
public CustomRequestsTests(ITestOutputHelper outputHelper) : base(new JsonRpcTestOptions().ConfigureForXUnit(outputHelper))
{
}
[Fact]
public async Task Should_Support_Custom_Attach_Request_Using_Base_Class()
{
var fake = Substitute.For<AttachHandlerBase<CustomAttachRequestArguments>>();
var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); });
await client.Attach(
new CustomAttachRequestArguments
{
ComputerName = "computer",
RunspaceId = "1234",
ProcessId = "4321"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomAttachRequestArguments>().Which;
request.ComputerName.Should().Be("computer");
request.RunspaceId.Should().Be("1234");
request.ProcessId.Should().Be("4321");
}
[Fact]
public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request_Using_Base_Class()
{
var fake = Substitute.For<AttachHandlerBase>();
var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); });
await client.Attach(
new CustomAttachRequestArguments
{
ComputerName = "computer",
RunspaceId = "1234",
ProcessId = "4321"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<AttachRequestArguments>().Which;
request.ExtensionData.Should().ContainKey("computerName").And.Subject["computerName"].Should().Be("computer");
request.ExtensionData.Should().ContainKey("runspaceId").And.Subject["runspaceId"].Should().Be("1234");
request.ExtensionData.Should().ContainKey("processId").And.Subject["processId"].Should().Be("4321");
}
[Fact]
public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Using_Base_Class()
{
var fake = Substitute.For<AttachHandlerBase<CustomAttachRequestArguments>>();
var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); });
await client.Attach(
new AttachRequestArguments
{
ExtensionData = new Dictionary<string, object>
{
["ComputerName"] = "computer",
["RunspaceId"] = "1234",
["ProcessId"] = "4321"
}
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomAttachRequestArguments>().Which;
request.ComputerName.Should().Be("computer");
request.RunspaceId.Should().Be("1234");
request.ProcessId.Should().Be("4321");
}
[Fact]
public async Task Should_Support_Custom_Launch_Request_Using_Base_Class()
{
var fake = Substitute.For<LaunchHandlerBase<CustomLaunchRequestArguments>>();
var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); });
await client.Launch(
new CustomLaunchRequestArguments
{
Script = "build.ps1"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomLaunchRequestArguments>().Which;
request.Script.Should().Be("build.ps1");
}
[Fact]
public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request_Using_Base_Class()
{
var fake = Substitute.For<LaunchHandlerBase>();
var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); });
await client.Launch(
new CustomLaunchRequestArguments
{
Script = "build.ps1"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<LaunchRequestArguments>().Which;
request.ExtensionData.Should().ContainKey("script").And.Subject["script"].Should().Be("build.ps1");
}
[Fact]
public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Base_Class()
{
var fake = Substitute.For<LaunchHandlerBase<CustomLaunchRequestArguments>>();
var (client, _) = await Initialize(options => { }, options => { options.AddHandler(fake); });
await client.Launch(
new CustomLaunchRequestArguments
{
ExtensionData = new Dictionary<string, object>
{
["Script"] = "build.ps1"
}
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomLaunchRequestArguments>().Which;
request.Script.Should().Be("build.ps1");
}
[Fact]
public async Task Should_Support_Custom_Attach_Request_Using_Delegate()
{
var fake = Substitute.For<Func<CustomAttachRequestArguments, CancellationToken, Task<AttachResponse>>>();
var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); });
await client.Attach(
new CustomAttachRequestArguments
{
ComputerName = "computer",
RunspaceId = "1234",
ProcessId = "4321"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomAttachRequestArguments>().Which;
request.ComputerName.Should().Be("computer");
request.RunspaceId.Should().Be("1234");
request.ProcessId.Should().Be("4321");
}
[Fact]
public async Task Should_Support_Custom_Attach_Request_Receiving_Regular_Request_Using_Delegate()
{
var fake = Substitute.For<Func<AttachRequestArguments, CancellationToken, Task<AttachResponse>>>();
var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); });
await client.Attach(
new CustomAttachRequestArguments
{
ComputerName = "computer",
RunspaceId = "1234",
ProcessId = "4321"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<AttachRequestArguments>().Which;
request.ExtensionData.Should().ContainKey("computerName").And.Subject["computerName"].Should().Be("computer");
request.ExtensionData.Should().ContainKey("runspaceId").And.Subject["runspaceId"].Should().Be("1234");
request.ExtensionData.Should().ContainKey("processId").And.Subject["processId"].Should().Be("4321");
}
[Fact]
public async Task Should_Support_Custom_Attach_Request_Using_Extension_Data_Using_Delegate()
{
var fake = Substitute.For<Func<CustomAttachRequestArguments, CancellationToken, Task<AttachResponse>>>();
var (client, _) = await Initialize(options => { }, options => { options.OnAttach(fake); });
await client.Attach(
new AttachRequestArguments
{
ExtensionData = new Dictionary<string, object>
{
["ComputerName"] = "computer",
["RunspaceId"] = "1234",
["ProcessId"] = "4321"
}
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomAttachRequestArguments>().Which;
request.ComputerName.Should().Be("computer");
request.RunspaceId.Should().Be("1234");
request.ProcessId.Should().Be("4321");
}
[Fact]
public async Task Should_Support_Custom_Launch_Request_Using_Delegate()
{
var fake = Substitute.For<Func<CustomLaunchRequestArguments, CancellationToken, Task<LaunchResponse>>>();
var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); });
await client.Launch(
new CustomLaunchRequestArguments
{
Script = "build.ps1"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomLaunchRequestArguments>().Which;
request.Script.Should().Be("build.ps1");
}
[Fact]
public async Task Should_Support_Custom_Launch_Request_Receiving_Regular_Request_Using_Delegate()
{
var fake = Substitute.For<Func<LaunchRequestArguments, CancellationToken, Task<LaunchResponse>>>();
var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); });
await client.Launch(
new CustomLaunchRequestArguments
{
Script = "build.ps1"
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<LaunchRequestArguments>().Which;
request.ExtensionData.Should().ContainKey("script").And.Subject["script"].Should().Be("build.ps1");
}
[Fact]
public async Task Should_Support_Custom_Launch_Request_Using_Extension_Data_Using_Delegate()
{
var fake = Substitute.For<Func<CustomLaunchRequestArguments, CancellationToken, Task<LaunchResponse>>>();
var (client, _) = await Initialize(options => { }, options => { options.OnLaunch(fake); });
await client.Launch(
new CustomLaunchRequestArguments
{
ExtensionData = new Dictionary<string, object>
{
["Script"] = "build.ps1"
}
}
);
var call = fake.ReceivedCalls().Single();
var args = call.GetArguments();
var request = args[0].Should().BeOfType<CustomLaunchRequestArguments>().Which;
request.Script.Should().Be("build.ps1");
}
public record CustomAttachRequestArguments : AttachRequestArguments
{
public string ComputerName { get; init; } = null!;
public string ProcessId { get; init; } = null!;
public string RunspaceId { get; init; } = null!;
}
public record CustomLaunchRequestArguments : LaunchRequestArguments
{
/// <summary>
/// Gets or sets the absolute path to the script to debug.
/// </summary>
public string Script { get; init; } = null!;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
namespace COMP476Proj
{
/// <summary>
/// Node for use with pathfinding
/// </summary>
public class Node
{
// IDs should be unique and are only actually used by the map loader for attaching edges
private static int nextID = 0;
private int id;
public int ID { get { return id; } }
private Vector2 position;
private bool isKey;
public bool IsKey { get { return isKey; } }
public Vector2 Position { get { return position; } }
public List<Edge> Edges; // All associated edges
public Node(float x, float y, bool isKey=false, int id=0)
{
if (id < 1)
{
id = ++nextID;
}
else
{
this.id = id;
if (nextID <= id)
nextID = id + 1;
}
position = new Vector2(x, y);
Edges = new List<Edge>();
this.isKey = isKey;
}
public void Update(GameTime gameTime)
{
// Make sure the edges erode
foreach (Edge edge in Edges)
{
edge.Update(gameTime);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PushBox : MonoBehaviour
{
Rigidbody m_Body;
[SerializeField]
int playerLayerID;
[SerializeField]
float slowMultiplier;
Rigidbody playerBody;
float zDistance;
float xDistance;
Vector3 moveDirection;
public int weight;
private void Awake()
{
m_Body = GetComponent<Rigidbody>();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == playerLayerID)
{
playerBody = other.gameObject.GetComponent<Rigidbody>();
zDistance = Mathf.Abs(playerBody.transform.position.z - transform.position.z);
xDistance = Mathf.Abs(playerBody.transform.position.z - transform.position.z);
}
}
private void OnTriggerStay(Collider other)
{
if (other.gameObject.layer == playerLayerID)
{
playerBody.AddForce(-playerBody.velocity * slowMultiplier);
m_Body.velocity = MoveDirection(xDistance, zDistance);
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.layer == playerLayerID)
{
m_Body.velocity = Vector3.zero;
xDistance = 0;
zDistance = 0;
playerBody = null;
}
}
Vector3 MoveDirection(float xDis, float zDis)
{
if (xDis > zDis)
{
return new Vector3(playerBody.velocity.x, m_Body.velocity.y, m_Body.velocity.z);
}
else if (xDis < zDis)
{
return new Vector3(m_Body.velocity.x, m_Body.velocity.y, playerBody.velocity.z);
}
else return Vector3.zero;
}
}
|
using Calcifer.Engine.Scenegraph;
namespace Calcifer.Engine.Graphics
{
public interface IRenderer
{
void Render(SceneNode rootNode, Camera camera);
void AddRenderPass(RenderPass pass);
}
public class BasicRenderer : IRenderer
{
private RenderPass pass;
public void Render(SceneNode rootNode, Camera camera)
{
rootNode.AcceptPass(this.pass);
}
public void AddRenderPass(RenderPass p)
{
this.pass = p;
}
}
} |
using Reactive.Bindings;
using System;
namespace MultiCommentCollector.Models
{
[Serializable]
public class WindowRect
{
public ReactiveProperty<double> Width { get; set; } = new();
public ReactiveProperty<double> Height { get; set; } = new();
public ReactiveProperty<double> Left { get; set; } = new();
public ReactiveProperty<double> Top { get; set; } = new();
public WindowRect() { }
public WindowRect(double width, double height, double left, double top)
=> (Width.Value, Height.Value, Left.Value, Top.Value) = (width, height, left, top);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.PlottingServices;
using Autodesk.AutoCAD.Colors;
[assembly: CommandClass(typeof(ASI_DOTNET.AcadCLI))]
namespace ASI_DOTNET
{
class AcadCLI
{
[CommandMethod("RackPrompt")]
public static void RackPrompt()
{
// Get the current document and database, and start a transaction
Document acDoc = Application.DocumentManager.MdiActiveDocument;
Database acCurDb = acDoc.Database;
Editor acEd = acDoc.Editor;
// Create rack instance
Rack rack = new Rack(acCurDb);
// Get rack details
if (RackOptions(acEd, rack) == false) { return; }
// Prompt for other rack options
if (RackOtherOptions(acEd, rack) == false) { return; }
// Build rack
rack.Build();
}
public static bool RackOptions(Editor ed, Rack rack)
{
// Prepare prompt for rack type
PromptResult typeRes;
PromptKeywordOptions typeOpts = new PromptKeywordOptions("");
typeOpts.Message = "\nRack Type: ";
typeOpts.Keywords.Add("PAllet");
typeOpts.Keywords.Add("Flow");
typeOpts.Keywords.Add("PUshback");
typeOpts.Keywords.Add("DriveIn");
typeOpts.Keywords.Default = "PAllet";
typeOpts.AllowArbitraryInput = false;
typeOpts.AllowNone = true;
// Prepare prompt for rack depth
PromptIntegerResult deepRes;
PromptIntegerOptions deepOpts = new PromptIntegerOptions("");
deepOpts.Message = "\nEnter the rack depth: ";
deepOpts.DefaultValue = 1;
deepOpts.AllowZero = false;
deepOpts.AllowNegative = false;
// Prepare prompt for rack bays
PromptIntegerResult baysRes;
PromptIntegerOptions baysOpts = new PromptIntegerOptions("");
baysOpts.Message = "\nEnter the number of rack bays: ";
baysOpts.DefaultValue = 1;
baysOpts.AllowZero = false;
baysOpts.AllowNegative = false;
// Prepare prompt for rack levels
PromptIntegerResult highRes;
PromptIntegerOptions highOpts = new PromptIntegerOptions("");
highOpts.Message = "\nEnter the number of rack levels: ";
highOpts.DefaultValue = 1;
highOpts.AllowZero = false;
highOpts.AllowNegative = false;
// Prompt for rack type
typeRes = ed.GetKeywords(typeOpts);
if (typeRes.Status == PromptStatus.Cancel) return false;
rack.rackType = typeRes.StringResult;
// Prompt for rack depth
if (rack.rackType != "pallet")
{
deepRes = ed.GetInteger(deepOpts);
if (deepRes.Status != PromptStatus.OK) return false;
rack.rackCountDeep = deepRes.Value;
}
// Prompt for rack bays
baysRes = ed.GetInteger(baysOpts);
if (baysRes.Status != PromptStatus.OK) return false;
rack.rackCountBays = baysRes.Value;
// Prompt for rack levels
highRes = ed.GetInteger(highOpts);
if (highRes.Status != PromptStatus.OK) return false;
rack.rackCountHigh = highRes.Value;
return true;
}
public static bool RackOtherOptions(Editor ed, Rack rack)
{
// Prepare prompt for other options
PromptResult res;
PromptKeywordOptions opts = new PromptKeywordOptions("");
opts.Message = "\nOptions: ";
opts.Keywords.Add("Frame");
opts.Keywords.Add("Beam");
opts.Keywords.Add("Spacer");
opts.AllowArbitraryInput = false;
opts.AllowNone = true;
// Prompt for other options
res = ed.GetKeywords(opts);
if (res.Status == PromptStatus.Cancel) return false;
while (res.Status == PromptStatus.OK)
{
switch (res.StringResult)
{
case "Frame":
if (RackFrameOptions(ed, rack) == false) { return false; }
break;
case "Beam":
if (RackBeamOptions(ed, rack, "beam") == false) { return false; }
break;
case "Spacer":
if (RackBeamOptions(ed, rack, "spacer") == false) { return false; }
break;
default:
Application.ShowAlertDialog("Invalid Keyword");
break;
}
// Re-prompt for keywords
res = ed.GetKeywords(opts);
if (res.Status == PromptStatus.Cancel) return false;
}
return true;
}
public static bool RackFrameOptions(Editor ed, Rack rack)
{
// Prepare prompt for the frame height
PromptDoubleResult heightRes;
PromptDistanceOptions heightOpts = new PromptDistanceOptions("");
heightOpts.Message = "\nEnter the frame height: ";
heightOpts.DefaultValue = 96;
// Prepare prompt for the frame width
PromptDoubleResult widthRes;
PromptDistanceOptions widthOpts = new PromptDistanceOptions("");
widthOpts.Message = "\nEnter the frame width: ";
widthOpts.DefaultValue = 36;
// Prepare prompt for the frame diameter
PromptDoubleResult diameterRes;
PromptDistanceOptions diameterOpts = new PromptDistanceOptions("");
diameterOpts.Message = "\nEnter the frame width: ";
diameterOpts.DefaultValue = 3.0;
// Prompt for the frame height
heightRes = ed.GetDistance(heightOpts);
rack.frameHeight = heightRes.Value;
if (heightRes.Status != PromptStatus.OK) return false;
// Prompt for the frame width
widthRes = ed.GetDistance(widthOpts);
rack.frameWidth = widthRes.Value;
if (widthRes.Status != PromptStatus.OK) return false;
// Prompt for the frame diameter
diameterRes = ed.GetDistance(diameterOpts);
rack.frameDiameter = diameterRes.Value;
if (diameterRes.Status != PromptStatus.OK) return false;
return true;
}
public static bool RackBeamOptions(Editor ed, Rack rack, string type)
{
// Prepare prompt for the beam length
PromptDoubleResult lengthRes;
PromptDistanceOptions lengthOpts = new PromptDistanceOptions("");
lengthOpts.Message = "\nEnter the beam length: ";
lengthOpts.DefaultValue = 96;
// Prepare prompt for the beam height
PromptDoubleResult heightRes;
PromptDistanceOptions heightOpts = new PromptDistanceOptions("");
heightOpts.Message = "\nEnter the beam height: ";
heightOpts.DefaultValue = 3;
// Prepare prompt for the beam width
PromptDoubleResult widthRes;
PromptDistanceOptions widthOpts = new PromptDistanceOptions("");
widthOpts.Message = "\nEnter the beam width: ";
widthOpts.DefaultValue = 2;
// Prepare prompt for the beam style
string style = "Step";
PromptResult bStyleRes;
PromptKeywordOptions bStyleOpts = new PromptKeywordOptions("");
bStyleOpts.Message = "\nEnter beam style: ";
bStyleOpts.Keywords.Add("Step");
bStyleOpts.Keywords.Add("Box");
bStyleOpts.Keywords.Add("IBeam");
bStyleOpts.Keywords.Add("CChannel");
bStyleOpts.Keywords.Default = "Step";
bStyleOpts.AllowArbitraryInput = false;
// Prompt for beam length
lengthRes = ed.GetDistance(lengthOpts);
if (lengthRes.Status != PromptStatus.OK) return false;
double length = lengthRes.Value;
// Prompt for beam height
heightRes = ed.GetDistance(heightOpts);
if (heightRes.Status != PromptStatus.OK) return false;
double height = heightRes.Value;
// Prompt for beam width
widthRes = ed.GetDistance(widthOpts);
if (widthRes.Status != PromptStatus.OK) return false;
double width = widthRes.Value;
// Prompt for beam style
if (type == "beam") {
bStyleRes = ed.GetKeywords(bStyleOpts);
style = bStyleRes.StringResult;
if (bStyleRes.Status == PromptStatus.Cancel) return false;
}
if (type == "beam")
{
rack.beamLength = length;
rack.beamHeight = height;
rack.beamWidth = width;
rack.beamType = style;
}
else if (type == "spacer")
{
rack.spacerLength = length;
rack.spacerHeight = height;
rack.spacerWidth = width;
rack.spacerType = "Box";
}
else if (type == "tie")
{
rack.tieLength = length;
rack.tieHeight = height;
rack.tieWidth = width;
rack.tieType = "Box";
}
else
{
return false;
}
return true;
}
}
}
|
using AutoMapper;
using Crt.Data.Database.Entities;
using Crt.Data.Repositories.Base;
using Crt.Model;
using Crt.Model.Dtos.FinTarget;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace Crt.Data.Repositories
{
public interface IFinTargetRepository
{
Task<FinTargetDto> GetFinTargetByIdAsync(decimal finTargetId);
Task<CrtFinTarget> CreateFinTargetAsync(FinTargetCreateDto finTarget);
Task UpdateFinTargetAsync(FinTargetUpdateDto finTarget);
Task DeleteFinTargetAsync(decimal finTargetId);
Task<bool> ElementExists(decimal elementId);
Task<CrtFinTarget> CloneFinTargetAsync(decimal finTargetId);
}
public class FinTargetRepository : CrtRepositoryBase<CrtFinTarget>, IFinTargetRepository
{
public FinTargetRepository(AppDbContext dbContext, IMapper mapper, CrtCurrentUser currentUser)
: base(dbContext, mapper, currentUser)
{
}
public async Task<FinTargetDto> GetFinTargetByIdAsync(decimal finTargetId)
{
var finTarget = await DbSet.AsNoTracking()
.Include(x => x.Project)
.Include(x => x.Element)
.Include(x => x.FiscalYearLkup)
.Include(x => x.FundingTypeLkup)
.Include(x => x.PhaseLkup)
.FirstOrDefaultAsync(x => x.FinTargetId == finTargetId);
return Mapper.Map<FinTargetDto>(finTarget);
}
public async Task<CrtFinTarget> CreateFinTargetAsync(FinTargetCreateDto finTarget)
{
var crtFinTarget = new CrtFinTarget();
Mapper.Map(finTarget, crtFinTarget);
await DbSet.AddAsync(crtFinTarget);
return crtFinTarget;
}
public async Task UpdateFinTargetAsync(FinTargetUpdateDto finTarget)
{
var crtFinTarget = await DbSet
.FirstAsync(x => x.FinTargetId == finTarget.FinTargetId);
crtFinTarget.EndDate = finTarget.EndDate?.Date;
Mapper.Map(finTarget, crtFinTarget);
}
public async Task DeleteFinTargetAsync(decimal finTargetId)
{
var crtFinTarget = await DbSet
.FirstAsync(x => x.FinTargetId == finTargetId);
DbSet.Remove(crtFinTarget);
}
public async Task<bool> ElementExists(decimal elementId)
{
return await DbContext.CrtElements.AnyAsync(x => x.ElementId == elementId && (x.EndDate == null || x.EndDate > DateTime.Today));
}
public async Task<CrtFinTarget> CloneFinTargetAsync(decimal finTargetId)
{
var source = await DbSet
.FirstAsync(x => x.FinTargetId == finTargetId);
var target = new FinTargetCreateDto();
Mapper.Map(source, target);
return await CreateFinTargetAsync(target);
}
}
}
|
// Refrences
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Where code lives
// Extends (:) UnityLanguage = MonoBehavior
public class Session_1 : MonoBehaviour {
// 1.Variables
// Type - - Name - - Value
// Scope - - Type - - Name - - Value
// Numbers
public int myFirstIntegerNumber = 97;
float myFirstFloatNumber = 1.71f;
// Text
public string myFirstString = "My text is somewhere";
// Logical variable
bool myFirstBoolean = true;
// Data structures
// Scope - - Type - - Values
//3.a.Arrays
public int[] myIntegerArray = { 1, 2, 3, 4, 5 };
public float[] myFloatArray = new float[5];
//3.b.Lists
//new things always added at the end
public List<int> myIntegerList = new List<int>();
//2.Functions
//Scope - - Type - - Variables - - Body (Instructions)
// Use this for initialization
//Start runs only once - sometimes called Setup
void Start () {
Debug.Log("Addition of 5 and 3 is: " + AdditionofNumbers(5, 3));
//You can only add value in the function therefore
myFloatArray[2] = 3.2f;
myFloatArray[3] = 4.3f;
myFloatArray[4] = 9.2f;
myIntegerList.Add(1);
myIntegerList.Add(2);
myIntegerList.Add(3);
//myIntegerList.Remove(0);
}
// Update is called once per frame
// Runs one time per frame
void Update () {
Debug.Log("Hello world!");
}
int AdditionofNumbers(int number1, int number2)
{
int additionResult = number1 + number2;
return additionResult;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BSTest.Models;
namespace BSTest.DAOs
{
public class Repository : IRepository
{
private static Repository instance;
public static Repository Instance
{
get
{
if (instance == null)
{
instance = new Repository();
}
return instance;
}
}
private MatchDAOTableAdapters.MatchesTableAdapter MatchAdapter;
private TeamDAOTableAdapters.TeamsTableAdapter TeamAdapter;
private Repository()
{
MatchAdapter = new MatchDAOTableAdapters.MatchesTableAdapter();
TeamAdapter = new TeamDAOTableAdapters.TeamsTableAdapter();
}
public List<Match> GetMatches()
{
return MatchAdapter.GetAll().AsEnumerable().Select(row => {
return new Match(row.Id,
row.Team1Id,
row.Team1Score,
row.Team2Id,
row.Team2Score);
}).ToList();
}
public Match GetMatchById(int id)
{
var rows = MatchAdapter.GetById(id).AsEnumerable();
if (rows.Any())
{
return rows.Select(row => new Match(row.Id,
row.Team1Id,
row.Team1Score,
row.Team2Id,
row.Team2Score)).First();
}
return null;
}
public bool ExistMatch(int id)
{
return GetMatchById(id) != null;
}
public Match AddMatch(Match match)
{
MatchAdapter.InsertMatch(match.Team1Id, match.Team1Score, match.Team2Id, match.Team2Score);
// TODO - Need to add at least one more contraint to the match table, as the match id is auto-generated
return MatchAdapter.GetDataByIdsAndScores(match.Team1Id, match.Team1Score, match.Team2Id, match.Team2Score).AsEnumerable().Select(row => new Match(row.Id,
row.Team1Id,
row.Team1Score,
row.Team2Id,
row.Team2Score)).First();
}
public Team GetTeamById(int id)
{
var team = TeamAdapter.GetTeamNameById(id);
if (!String.IsNullOrWhiteSpace(team))
{
return new Team(id, team);
}
return null;
}
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Services.Configuration;
namespace Microsoft.PowerShell.EditorServices.Services
{
public class ConfigurationService
{
// This probably needs some sort of lock... or maybe LanguageServerSettings needs it.
public LanguageServerSettings CurrentSettings { get; } = new LanguageServerSettings();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi.Entities;
using WebApi.Repositories.Contracts.Base;
namespace WebApi.Repositories.Contracts
{
public interface IUserRepository : ICrudBaseRepository<User>
{
User Get(User user);
}
}
|
using System.Collections.Generic;
using RoleTopMVC.Models;
namespace RoleTopMVC.ViewModels
{
public class EventosViewModel : BaseViewModel
{
public List<string> Eventos = new List<string>();
}
}
|
using Domain.Interfaces.InterfaceServices;
using Domain.Interfaces.InterfaceUsuario;
using Entities.Entities;
using Entities.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Domain.Services
{
public class ServiceMontaMenu : IServiceMontaMenu
{
private readonly IUsuario _IUsuario;
public ServiceMontaMenu(IUsuario IUsuario)
{
_IUsuario = IUsuario;
}
public async Task<List<MenuSite>> MontaMenuPorPerfil(string userID)
{
var retorno = new List<MenuSite>();
retorno.Add(new MenuSite { Controller = "Home", Action = "Index", Descricao = "Loja Virtual" });
if (!string.IsNullOrWhiteSpace(userID))
{
// QUANDO USUÁRIO LOGADO USUÁRIO LOGADO
retorno.Add(new MenuSite { Controller = "Produtos", Action = "Index", Descricao = "Meus Produtos" });
retorno.Add(new MenuSite { Controller = "CompraUsuario", Action = "MinhasCompras", Descricao = "Minhas Compras" });
retorno.Add(new MenuSite { Controller = "Produtos", Action = "DashboardVendas", Descricao = "Minhas Vendas" });
var usuario = await _IUsuario.ObterUsuarioPeloID(userID);
if (usuario != null && usuario.Tipo != null)
{
switch ((TipoUsuario)usuario.Tipo)
{
case TipoUsuario.Administrador:
retorno.Add(new MenuSite { Controller = "LogSistemas", Action = "Index", Descricao = "Logs" });
retorno.Add(new MenuSite { Controller = "Usuarios", Action = "ListarUsuarios", Descricao = "Usuários" });
break;
case TipoUsuario.Comum:
break;
default:
break;
}
}
retorno.Add(new MenuSite { Controller = "Produtos", Action = "ListarProdutosCarrinhoUsuario", Descricao = "", IdCampo = "qtdCarrinho", UrlImagem = "../img/carrinho.png" });
}
return retorno;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace EdubranApi.Models
{
public class CommentDTO
{
[Required]
public int Id { get; set; }
[Required]
public string comment { get; set; }
[Required]
public string date { get; set; }
public Int32 timestamp { get; set; }
public int time_seconds { get; set; }
public int time_minutes { get; set; }
public int time_hours { get; set; }
public int time_days { get; set; }
/// <summary>
/// This represents information of either a company or student who have participated in a comment
/// </summary>
public ClientDTO client { get; set; }
}
} |
using FileNamer.Service.DataTypes;
using NUnit.Framework;
namespace FileNamerTest
{
[TestFixture]
public class FileNameTest
{
[Test]
public void TestGetFilePath()
{
Assert.AreEqual("a\\b", FileName.GetFilePath("a", "b"));
}
}
}
|
using Ornithology.Entity;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ornithology.Data
{
public class OrnithologyDbContext : DbContext
{
public OrnithologyDbContext()
{
AppDomain.CurrentDomain.SetData("DataDirectory",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Ave>();
modelBuilder.Entity<Pais>();
modelBuilder.Entity<Zona>();
modelBuilder.Entity<AvePais>();
}
}
}
|
using System;
class Program
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
var p1 = 0;
var p2 = 0;
var p3 = 0;
var p4 = 0;
var p5 = 0;
for (int i = 1; i <= n; i++)
{
var num = int.Parse(Console.ReadLine());
if (num < 200)
p1++;
else if (num >= 200 && num < 400)
p2++;
else if (num >= 400 && num < 600)
p3++;
else if (num >= 600 && num < 800)
p4++;
else
p5++;
}
Console.WriteLine("{0:f2}%", (100 * ((double)p1 / (double)n)));
Console.WriteLine("{0:f2}%", (100 * ((double)p2 / (double)n)));
Console.WriteLine("{0:f2}%", (100 * ((double)p3 / (double)n)));
Console.WriteLine("{0:f2}%", (100 * ((double)p4 / (double)n)));
Console.WriteLine("{0:f2}%", (100 * ((double)p5 / (double)n)));
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Delaunay.Geo;
using Delaunay;
public class GameMap : MonoBehaviour {
[SerializeField]
private GameObject _graphNodePrefab;
[SerializeField]
private GameObject _graphEdgePrefab;
[SerializeField]
private GameObject _playerPrefab;
[SerializeField]
private LayerMask _graphNodeLayerMask;
[SerializeField]
private float _minDistance;
[SerializeField]
private int _mapWidth = 40;
[SerializeField]
private int _mapHeight = 60;
// GameObjects in game map
private Dictionary<string, MapNode> _mapNodes = new Dictionary<string, MapNode>();
private List<MapEdge> _mapEdges = new List<MapEdge>();
private GameObject _player = null;
private MapNode _currentNode = null;
private MapNode _selectedNode = null;
private MapHud _mapHud = null;
private MapBlob _blob = null;
public BattleStageData GetBattleStageData() {
return _currentNode.BattleData;
}
public ShopStageData GetShopStageData() {
return _currentNode.ShopData;
}
public void Initialize( MapHud hud ) {
_mapHud = hud;
_mapHud.Initialize( MoveToSelectedNode );
CreatePlayer();
}
private void CreatePlayer() {
_player = GameObject.Instantiate( _playerPrefab );
_player.transform.position = _currentNode.transform.position;
}
public void MapNodeTappedCallback( MapNode node ) {
Debug.Log( "NodeTapped " + node.NodeId );
// Toggle edge visibility
if ( _selectedNode != node || _selectedNode == null) {
if ( _selectedNode != null && _selectedNode != _currentNode ) {
_selectedNode.ToggleEdgeVisibility( false );
}
node.ToggleEdgeVisibility( true );
_selectedNode = node;
}
if ( _selectedNode == _currentNode ) {
GameManager.Instance.MapNodeSelected( _currentNode );
if ( _selectedNode.BattleData != null ) {
GameManager.Instance.ShowWeaponPicker();
} else if ( _selectedNode.ShopData != null ) {
GameManager.Instance.ShowShopDialog();
}
_mapHud.ToggleTravelButton( false );
} else {
bool canTravelToNode = CanTravelToNode( _selectedNode.NodeId );
_mapHud.ToggleTravelButton( canTravelToNode );
}
}
public bool CanTravelToNode( string nodeId ) {
// Simple for now
bool completedSelectedNode = _blob.CompletedNotes.Contains( nodeId );
bool completedCurrentNode = _blob.CompletedNotes.Contains( _currentNode.NodeId );
if ( (completedCurrentNode || completedSelectedNode) && _currentNode.HasNeighbour(nodeId) ) {
return true;
}
return false;
}
public void MoveToSelectedNode() {
_currentNode.ToggleEdgeVisibility( false );
_currentNode = _selectedNode;
_currentNode.ToggleEdgeVisibility( true );
iTween.MoveTo( _player,
iTween.Hash( "position", _currentNode.transform.position,
"easetype", iTween.EaseType.easeOutQuart,
"time", 1f,
"oncomplete", "MovedToNode",
"oncompletetarget", gameObject
)
);
// Might need saving to elsewhere later
_blob.CurrentNode = _currentNode.NodeId;
SaveMap();
GameManager.Instance.MapNodeSelected( _currentNode );
}
public void MovedToNode() {
GameManager.Instance.ShowWeaponPicker();
}
#region Loading/Generation of Map Data
public void LoadMap( MapBlob blob ) {
_blob = blob;
// Temp
foreach( KeyValuePair<string, MapNodeData> kvp in blob.MapNodes ) {
MapNode mapNode = CreateMapNode( kvp.Key );
mapNode.InitializeFromData( kvp.Value, MapNodeTappedCallback );
}
for ( int i = 0, count = blob.MapEdges.Count; i < count; i++ ) {
MapEdge mapEdge = CreateMapEdge( blob.MapEdges[ i ].P0, blob.MapEdges[ i ].P1 );
mapEdge.Initialize( blob.MapEdges[ i ] );
}
_currentNode = _mapNodes[ blob.CurrentNode ];
_currentNode.ToggleEdgeVisibility( true );
}
public void GenerateNewMap( WorldData worldData ) {
_currentNode = GenerateGraph( worldData );
_blob = CreateNewMapBlob();
SaveMap();
_currentNode.ToggleEdgeVisibility( true );
}
private MapNode GenerateGraph( WorldData worldData ) {
List<Vector2> points = new List<Vector2>();
MapNode startingNode = null;
// world data says... maybe 8 battle stages, 2 shops, 1 quest
int numBattleStages = UnityEngine.Random.Range( worldData.MinNumBattleStages, worldData.MaxNumBattleStages+1 );
int numShopStages = UnityEngine.Random.Range( worldData.MinNumShopStages, worldData.MaxNumShopStages+1 );
// Create battle stage nodes
for ( int i = 0; i < numBattleStages; i++ ) {
Vector3 position;
if ( i == 0 ) {
position = FindStartingPosition();
} else if ( i == numBattleStages ) {
position = FindEndingPosition();
} else {
position = FindOpenPosition();
}
BattleStageData stageData = Database.Instance.GetRandomBattleStageData();
string nodeId = GetNodeIdFromVector3(position);
MapNode mapNode = CreateMapNode( nodeId );
mapNode.InitializeAsBattleStage( nodeId, position, stageData, MapNodeTappedCallback );
points.Add( new Vector2( position.x, position.y ) );
if ( i == 0 ) {
// save current node
startingNode = mapNode;
}
}
// Create shop nodes
for ( int i = 0; i < numShopStages; i++ ) {
Vector3 position = FindOpenPosition();
// depending on the world data, we need to pick from a random set
ShopStageData stageData = Database.Instance.GetRandomShopStageData();
string nodeId = GetNodeIdFromVector3(position);
MapNode mapNode = CreateMapNode( nodeId );
mapNode.InitializeAsShopStage( nodeId, position, stageData, MapNodeTappedCallback );
points.Add( new Vector2( position.x, position.y ) );
}
GenerateEdges( points );
return startingNode;
}
private MapNode CreateMapNode( string nodeId ) {
GameObject graphNodeGO = GameObject.Instantiate( _graphNodePrefab ) as GameObject;
graphNodeGO.transform.SetParent( transform );
MapNode mapNode = graphNodeGO.GetComponent<MapNode>();
_mapNodes.Add( nodeId, mapNode );
return mapNode;
}
private MapEdge CreateMapEdge( Vector3 p0, Vector3 p1 ) {
GameObject graphEdgeGO = GameObject.Instantiate( _graphEdgePrefab ) as GameObject;
graphEdgeGO.transform.SetParent( transform );
MapEdge mapEdge = graphEdgeGO.GetComponent<MapEdge>();
string node1Id = GetNodeIdFromVector3( p0 );
string node2Id = GetNodeIdFromVector3( p1 );
_mapNodes[ node1Id ].AddNeighbour( node2Id );
_mapNodes[ node2Id ].AddNeighbour( node1Id );
_mapNodes[ node1Id ].AddEdge( mapEdge );
_mapNodes[ node2Id ].AddEdge( mapEdge );
_mapEdges.Add( mapEdge );
return mapEdge;
}
private void GenerateEdges( List<Vector2> points ) {
List<LineSegment> minimumSpanningTree;
List<LineSegment> delaunayTriangulation;
List<LineSegment> finalEdges = new List<LineSegment>();
// Create the Voronoi diagram using the AS3 Delaunay library
List<uint> colors = new List<uint> ();
for ( int i = 0; i < points.Count; i++ ) { colors.Add (0); }
Delaunay.Voronoi voronoi = new Delaunay.Voronoi( points, colors, new Rect( 0, 0, _mapWidth, _mapHeight ) );
minimumSpanningTree = voronoi.SpanningTree( KruskalType.MINIMUM );
delaunayTriangulation = voronoi.DelaunayTriangulation ();
// First add any line segment in the minimum spanning tree to the list _edges
for ( int i = delaunayTriangulation.Count-1; i >= 0; i-- ) {
for ( int j = 0; j < minimumSpanningTree.Count; j++ ) {
if ( LineSegmentEquals( minimumSpanningTree[j], delaunayTriangulation[i] ) ) {
finalEdges.Add( delaunayTriangulation[ i ] );
delaunayTriangulation.RemoveAt( i );
break;
}
}
}
// Add a random amount of line segments in the delaunay triangulation but NOT in the minimum spanning tree to the list _edges
for ( int i = 0, count = delaunayTriangulation.Count; i < count; i++ ) {
float rand = UnityEngine.Random.value;
if ( rand <= 0.35 ) {
finalEdges.Add( delaunayTriangulation[ i ] );
}
}
// Create the edges on the map
// Also update neighbours properties on the nodes
for ( int i = 0, count = finalEdges.Count; i < count; i++ ) {
LineSegment line = finalEdges[ i ];
Vector3 p0 = new Vector3( line.p0.Value.x, line.p0.Value.y, 0 );
Vector3 p1 = new Vector3( line.p1.Value.x, line.p1.Value.y, 0 );
MapEdge mapEdge = CreateMapEdge( p0, p1 );
mapEdge.Initialize( p0, p1 );
}
}
private Vector3 FindOpenPosition() {
Collider[] overlappingNodes;
Vector3 candidatePosition;
// Find a random spot, check if there are any nodes, within a distance, at that spot
do {
// Pick a random position within our map boundaries and check if it is an open spot
candidatePosition = new Vector3( Random.Range(0, _mapWidth), Random.Range(0, _mapHeight), 0 );
overlappingNodes = Physics.OverlapSphere( candidatePosition, _minDistance );
}
// If there are any overlapping nodes, we need to choose a new random spot
while ( overlappingNodes.Length > 0 );
return candidatePosition;
}
private Vector3 FindStartingPosition() {
return new Vector3( Random.Range(0, _mapWidth), 0, 0 );
}
private Vector3 FindEndingPosition() {
return new Vector3( Random.Range(0, _mapWidth), _mapHeight-1, 0 );
}
private bool LineSegmentEquals( LineSegment a, LineSegment b ) {
return ( a.p0.HasValue && b.p0.HasValue && a.p0.Value == b.p0.Value ) &&
( a.p1.HasValue && b.p1.HasValue && a.p1.Value == b.p1.Value );
}
#endregion
#region SerializeMap
private MapBlob CreateNewMapBlob() {
MapBlob blob = new MapBlob();
Dictionary<string, MapNodeData> mapNodeData = new Dictionary<string, MapNodeData>();
foreach( KeyValuePair<string, MapNode> kvp in _mapNodes ) {
mapNodeData.Add( kvp.Key, kvp.Value.GetData() );
}
List<MapEdgeData> mapEdgeData = new List<MapEdgeData>();
for( int i = 0, count = _mapEdges.Count; i < count; i++ ) {
mapEdgeData.Add( _mapEdges[ i ].GetData() );
}
blob.MapNodes = mapNodeData;
blob.MapEdges = mapEdgeData;
blob.CurrentNode = _currentNode.NodeId;
return blob;
}
private void SaveMap() {
GameManager.Instance.GetPersistenceManager().SaveMapData( _blob );
}
#endregion
private static string GetNodeIdFromVector3( Vector3 position ) {
return "Node@X_" + position.x + "_Y_" + position.y;
}
}
|
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using System.Text;
using TableTopCrucible.Core.Models.Sources;
using TableTopCrucible.Data.Models.Views;
using TableTopCrucible.Domain.Models.Sources;
namespace TableTopCrucible.Domain.Library.WPF.ViewModels
{
public class FileVersionListViewModel : DisposableReactiveObjectBase
{
private BehaviorSubject<IEnumerable<VersionedFile>> _versionedFilesChanges = new BehaviorSubject<IEnumerable<VersionedFile>>(null);
public ObservableAsPropertyHelper<IEnumerable<VersionedFile>> _versionedFiles;
public IEnumerable<VersionedFile> VersionedFiles => _versionedFiles.Value;
public void SetFiles(IEnumerable<VersionedFile> itemLinks)
{
_versionedFilesChanges.OnNext(itemLinks);
}
public FileVersionListViewModel()
{
this._versionedFiles = _versionedFilesChanges.ToProperty(this, nameof(VersionedFiles));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Proyek_Informatika.Models;
using Telerik.Web.Mvc;
namespace Proyek_Informatika.Controllers.Koordinator
{
public class BimbinganKoordinatorController : Controller
{
//
// GET: /Bimbingan/
SkripsiAutoContainer db = new SkripsiAutoContainer();
public ActionResult Index()
{
return PartialView();
}
public ActionResult IndexMahasiswa()
{
EnumSemesterSkripsiContainer semes = new EnumSemesterSkripsiContainer();
var result = from jn in db.jenis_skripsi
select (new { id = jn.id, nama_jenis = jn.nama_jenis });
List<jenis_skripsi> temp = new List<jenis_skripsi>();
foreach (var x in result)
{
temp.Add(new jenis_skripsi { id = x.id, nama_jenis = x.nama_jenis });
}
semes.jenis_skripsi = temp;
List<semester> temp2 = new List<semester>();
var result2 = from si in db.semesters
select (new { id = si.id, nama = si.periode_semester, curr = si.isCurrent });
foreach (var x in result2)
{
temp2.Add(new semester { id = x.id, periode_semester = x.nama, isCurrent = x.curr });
if (x.curr == 1)
{
semes.selected_value = x.id;
}
}
semes.jenis_semester = temp2;
return PartialView(semes);
}
public ActionResult Report()
{
return PartialView();
}
[HttpPost]
public ActionResult ListMahasiswa(int periode=0, int jenis_skripsi=0)
{
ViewBag.periode = periode;
ViewBag.jenis_skripsi = jenis_skripsi;
return PartialView();
}
[GridAction]
public ActionResult SelectBimbingan(int periode, int jenis_skripsi)
{
return bindingBimbingan(periode, jenis_skripsi);
}
protected ViewResult bindingBimbingan(int periode, int jenis_skripsi)
{
var result = from si in db.skripsis
where si.jenis == jenis_skripsi && si.id_semester_pengambilan == periode
select new KoordinatorListMahasiswa() {
id= si.id,
judul = si.topik.judul,
jumlahBimbingan = 0,
namaDosen = si.dosen.nama,
namaMahasiswa = si.mahasiswa.nama,
nikDosen = si.dosen.NIK,
npmMahasiswa = si.mahasiswa.NPM,
periode = si.semester.periode_semester,
pengambilanke = si.pengambilan_ke,
tipe = si.jenis_skripsi.nama_jenis
};
List<KoordinatorListMahasiswa> temp = new List<KoordinatorListMahasiswa>();
foreach(var x in result)
{
KoordinatorListMahasiswa temp2 = x;
temp2.jumlahBimbingan = db.bimbingans.Where<bimbingan>(a => a.id_skripsi == temp2.id).Count<bimbingan>();
temp.Add(temp2);
}
return View(new GridModel<KoordinatorListMahasiswa> { Data = temp});
}
#region kartubimbingan
public ActionResult KartuBimbingan(int id_skripsi)
{
var result = (from sk in db.skripsis
join mah in db.mahasiswas on sk.NPM_mahasiswa equals mah.NPM
join tp in db.topiks on sk.id_topik equals tp.id
where (sk.id == id_skripsi)
select new DosenMuridBimbinganContainer { id = sk.id, judul = tp.judul, namaMahasiswa = mah.nama, npm = mah.NPM }).Single<DosenMuridBimbinganContainer>();
int count = db.bimbingans.Where(x => x.id_skripsi == id_skripsi).Count();
ViewBag.jumlahBimbingan = count;
ViewBag.nama = result.namaMahasiswa;
ViewBag.npm = result.npm;
ViewBag.judul = result.judul;
ViewBag.id = result.id;
ViewData["kartu"] = db.bimbingans.Where(x => x.id_skripsi == id_skripsi).ToList<bimbingan>();
return PartialView();
}
[GridAction]
public ActionResult _SelectKartu(int id_skripsi)
{
return bindingKartu(id_skripsi);
}
public ViewResult bindingKartu(int id_skripsi)
{
var result = from bm in db.bimbingans
where bm.id_skripsi == id_skripsi
select new { id = bm.id, id_skripsi = bm.id_skripsi, isi = bm.isi, deskripsi = bm.deskripsi, tanggal = bm.tanggal };
List<bimbingan> temp = new List<bimbingan>();
foreach (var i in result)
{
temp.Add(new bimbingan()
{
id = i.id,
isi = i.isi,
tanggal = i.tanggal,
id_skripsi = i.id_skripsi,
deskripsi = i.deskripsi
});
}
return View(new GridModel<bimbingan>() { Data = temp });
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Reserva.Domain.Command.Result
{
public class ReservaCommadResultRegister
{
public ReservaCommadResultRegister(int reservaId, DateTime dataInicio, DateTime dataFim)
{
ReservaId = reservaId;
DataInicio = dataInicio;
DataFim = dataFim;
}
public int ReservaId { get; set; }
public DateTime DataInicio{ get; set; }
public DateTime DataFim { get; set; }
}
}
|
using Opbot.Model;
using Opbot.Services;
using Opbot.Utils;
using System;
namespace Opbot.Core.Tasks
{
class JpegTask : BaseCmdTask, IPipelineTask<Message, Message>
{
public JpegTask(Options options, ILogService logService) : base(options, logService)
{
}
public Message Execute(Message input)
{
try
{
var optLocalFile = this.CreateLocalTargetFile(input.FtpUri);
input.OptFilePath = optLocalFile;
var res = Cmd.Run(Constants.Tools.JpegTran, "-copy none -optimize -progressive " + input.RawFilePath + " " + optLocalFile);
this.logService.Verbose("JpenTran EXEC {0}-{1}", res.ExitCode, res.Output);
return this.HandleCmdResult(res, input);
}
catch (Exception ex)
{
this.logService.Error(ex.ToString());
return this.HandleFault(input, ex.ToString());
}
}
}
}
|
namespace Web.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddAnswers : DbMigration
{
public override void Up()
{
//AddColumn("dbo.Answers", "ScoRecordId", c => c.Int(nullable: false));
//CreateIndex("dbo.Answers", "ScoRecordId");
//AddForeignKey("dbo.Answers", "ScoRecordId", "dbo.ScoRecords", "Id", cascadeDelete: true);
}
public override void Down()
{
//DropForeignKey("dbo.Answers", "ScoRecordId", "dbo.ScoRecords");
//DropIndex("dbo.Answers", new[] { "ScoRecordId" });
//DropColumn("dbo.Answers", "ScoRecordId");
}
}
}
|
using System;
using System.Threading.Tasks;
using Fairmas.PickupTracking.Shared.Interfaces;
using Fairmas.PickupTracking.Shared.Models;
using System.Collections.Generic;
namespace Fairmas.PickupTracking.Shared.Services
{
public class PickupDataService : IPickupDataService
{
public async Task<Hotel[]> GetHotelsAsync()
{
// API
// https://put-development.fairplanner.net/api/Administration/Property/GetProperties
try
{
var client = ServiceLocator.FindService<IWebApiClientService>();
var hotels = await client.GetAsync<Hotel[]>("Administration/Property/", "GetProperties", new[]
{
new KeyValuePair<string, string>("true", "_=1479254387679"),
});
return hotels;
}
catch (Exception)
{
return new Hotel[] { };
}
}
public async Task<ResponseFiguresModel[]> GetMonthlyPickupSummaryAsync(Guid hotelId, DateTime pickupFrom, DateTime pickupTo)
{
//// API
//// https://put-development.fairplanner.net/api/PickupTracking/PickupTracking/MonthlyPickupSummary
var parameter = new[]
{
new KeyValuePair<string, string>("from", DateTime.Today.ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("to", DateTime.Today.AddMonths(24).ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("pickupFrom", pickupFrom.ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("pickupTo", pickupTo.ToString("yyyy-MM-dd")),
//new KeyValuePair<string, string>("_", "1481968644632")
};
var requestedFigures = new RequestFiguresModel
{
Revenue = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
RoomNights = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AvailableRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AverageDailyRate = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AverageDailyRate2 = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
Occupancy = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
OutOfOrderRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
OutOfServiceRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
Overbooking = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
RevPar = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
};
var client = ServiceLocator.FindService<IWebApiClientService>();
var changed = await client.ChangePropertyAsync(hotelId);
if (!changed)
throw new InvalidOperationException("Cannot switch to the selected property at the PickupTracking server.");
var monthlyPickupSummary = await client.PostAsync<ResponseFiguresModel[], RequestFiguresModel>("PickupTracking/PickupTracking/", "MonthlyPickupSummary", requestedFigures, parameter);
return monthlyPickupSummary;
}
public async Task<ResponseFiguresModel[]> GetDailyPickupSummaryAsync(Guid hotelId, DateTime pickupFrom, DateTime pickupTo, DateTime month)
{
//// API
//// https://put-development.fairplanner.net/api/PickupTracking/PickupTracking/DailyPickupSummary
var parameter = new[]
{
new KeyValuePair<string, string>("from", DateTime.Today.ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("to", DateTime.Today.AddMonths(24).ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("pickupFrom", pickupFrom.ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("pickupTo", pickupTo.ToString("yyyy-MM-dd")),
//new KeyValuePair<string, string>("_", "1481968644632")
};
var requestedFigures = new RequestFiguresModel
{
Revenue = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
RoomNights = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AvailableRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AverageDailyRate = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AverageDailyRate2 = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
Occupancy = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
OutOfOrderRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
OutOfServiceRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
Overbooking = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
RevPar = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
};
var client = ServiceLocator.FindService<IWebApiClientService>();
var changed = await client.ChangePropertyAsync(hotelId);
if (!changed)
throw new InvalidOperationException("Cannot switch to the selected property at the PickupTracking server.");
var dailyPickupSummary = await client.PostAsync<ResponseFiguresModel[], RequestFiguresModel>("PickupTracking/PickupTracking/", "DailyPickupSummary", requestedFigures, parameter);
return dailyPickupSummary;
}
public async Task<ResponseFiguresModel[]> GetSegmentedPickupAsync(Guid hotelId, DateTime pickupFrom, DateTime pickupTo, DateTime day)
{
//// API
//// https://put-development.fairplanner.net/api/PickupTracking/PickupTracking/SegmentedPickupSummary
var parameter = new[]
{
new KeyValuePair<string, string>("from", DateTime.Today.ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("to", DateTime.Today.AddMonths(24).ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("pickupFrom", pickupFrom.ToString("yyyy-MM-dd")),
new KeyValuePair<string, string>("pickupTo", pickupTo.ToString("yyyy-MM-dd")),
//new KeyValuePair<string, string>("_", "1481968644632")
};
var requestedFigures = new RequestFiguresModel
{
Revenue = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
RoomNights = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AvailableRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AverageDailyRate = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
AverageDailyRate2 = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
Occupancy = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
OutOfOrderRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
OutOfServiceRooms = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
Overbooking = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
RevPar = new FigureOptions() { IncludePickupValue = true, IncludeSnapshotOneValue = true, IncludeSnapshotTwoValue = true },
};
var client = ServiceLocator.FindService<IWebApiClientService>();
var changed = await client.ChangePropertyAsync(hotelId);
if (!changed)
throw new InvalidOperationException("Cannot switch to the selected property at the PickupTracking server.");
var segmentedPickupSummary = await client.PostAsync<ResponseFiguresModel[], RequestFiguresModel>("PickupTracking/PickupTracking/", "SegmentedPickupSummary", requestedFigures, parameter);
return segmentedPickupSummary;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IndexCameraColliders : MonoBehaviour
{
public int index;
public GameObject camera;
/// <summary>
/// Cuando el jugador entra en el collider la cámara se posiciona según el index asignado
/// </summary>
/// <param name="collision"></param>
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.tag.Equals("Player"))
{
camera.GetComponent<CameraController>().MoveCamera(index);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Net.NetworkInformation;
using System.Threading;
using System.Reflection;
namespace scaner
{
public partial class Register : Form
{
///////////////////////////////////////////////////////////////////////////
///// 0 - ID
///// 1 - Артикул
///// 2 - Код
///// 3 - Шрих
///// 4 - Название
///// 5 - ид типа меры
///// 6 - название типа меры
///// 7 - ид единицы меры
///// 8 - название единицы меры
///// 9 - цена настоящая
///// 10 - цена окончательная
///// 11 - ид группы
///// 12 - название группы
///// 13 - ид секции
///// 14 - название секции
///// 15 - ид налога
///// 16 - название налога
///// 17 - касовый аппарат
///// 18 - статус
///// 19 - количество
///// 20 - скидка 1 (системная по времени на группу или опр товар)
///// 21 - скидка 2 (ручная скидка)
///// 22 - скидка 3
///// 23 - скидка 4
///// 24 - ККМ
///// 25 - Уникальный номер пробитого товара
///// 26 - Уникальный номер чека
///////////////////////////////////////////////////////////////////////////
public string[,] MetaData = new string[1000, 30];
public Globals global;
public int item_count = 1;
public string InputString = "";
public int InputTrigger = 0;
public int CompleteTrigger = 0;
public string ErrorMsg = "";
public string[] datarow = { "", "", "", "", "", "", "" };
private Settings1 settings;
delegate void SetTextCallback();
delegate void SetLoadCallback(int load);
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public Register(Globals global)
{
InitializeComponent();
this.global = global;
settings = new Settings1();
SettingIncremet("data");
TicketIdUpdate();
InitCodePort();
SetDoubleBuffered(dataGrid);
if (settings.configInputRtoL == "0")
InputString = "00";
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void InitCodePort()
{
try
{
ScanerPort.PortName = settings.ScannerPort;
ScanerPort.BaudRate = 9600;
ScanerPort.DataBits = 8;
ScanerPort.Open();
}
catch (Exception ex)
{
MessageBox.Show("Не удалется открыть порт Сканера шрих кодов (" + ex.Message + ")");
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public static void SetDoubleBuffered(Control control)
{
typeof(Control).InvokeMember("DoubleBuffered",
BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
null, control, new object[] { true });
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void Register_Load(object sender, EventArgs e)
{
Form_TableHeader();
for (int i = 0; i < 1000; i++)
{
for (int j = 0; j < 30; j++)
{
MetaData[i, j] = "";
}
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void Form_TableHeader()
{
dataGrid.Columns.Clear();
dataGrid.RowHeadersWidth = 4;
dataGrid.Columns.Add("i", "№");
dataGrid.Columns.Add("id", "uid");
dataGrid.Columns.Add("code1", "Штрихкод");
dataGrid.Columns.Add("title", "Товар");
dataGrid.Columns.Add("count", "Кол-во");
dataGrid.Columns.Add("prize", "Цена");
dataGrid.Columns.Add("sum", "Сумма");
dataGrid.Columns.Add("nalog", "Налог");
dataGrid.Columns.Add("discont", "Скидка");
dataGrid.Columns[0].Width = 32;
dataGrid.Columns[1].Width = 60;
dataGrid.Columns[2].Width = 100;
dataGrid.Columns[3].Width = 230;
dataGrid.Columns[4].Width = 80;
dataGrid.Columns[5].Width = 60;
dataGrid.Columns[6].Width = 90;
dataGrid.Columns[7].Width = 60;
dataGrid.Columns[8].Width = 60;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void Form_TableUpdate()
{
if (dataGrid.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(Form_TableUpdate);
dataGrid.Invoke(d, new object[] { });
}
else
{
int index = 0;
int Increm = 1;
dataGrid.Rows.Clear();
for (int i = 0; i < 1000; i++)
{
if (MetaData[i, 0] != "" && MetaData[i, 0] != null)
{
dataGrid.Rows.Add();
index = dataGrid.Rows.Count - 1;
dataGrid.Rows[index].Cells["i"].Value = Convert.ToString(Increm);
dataGrid.Rows[index].Cells["id"].Value = MetaData[i, 25];
dataGrid.Rows[index].Cells["code1"].Value = MetaData[i, 3];
dataGrid.Rows[index].Cells["title"].Value = MetaData[i, 4];
dataGrid.Rows[index].Cells["count"].Value = MetaData[i, 19];
dataGrid.Rows[index].Cells["prize"].Value = MetaData[i, 9];
dataGrid.Rows[index].Cells["sum"].Value = MetaData[i, 10];
dataGrid.Rows[index].Cells["nalog"].Value = GetNalogTitle(i);
dataGrid.Rows[index].Cells["discont"].Value = GetDiscontTitle(i);
// Cтили
dataGrid.Rows[index].Cells["sum"].Style.Font = new Font(FontFamily.GenericSansSerif,9, FontStyle.Bold);
if (MetaData[i, 18] != "0")
{
dataGrid.Rows[index].DefaultCellStyle.BackColor = Color.LightGreen;
}
else
{
dataGrid.Rows[index].DefaultCellStyle.BackColor = Color.OrangeRed;
}
Increm++;
}
}
}
UpdateTotalPrise();
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public string GetNalogTitle(int i)
{
if (MetaData[i, 15] != "0" && MetaData[i, 15] != null && MetaData[i, 15] != "")
{
if (MetaData[i, 15].Length > 1)
{
if (MetaData[i, 15].Substring(0, 1) == "1")
{
return "+ " + MetaData[i, 15].Substring(1, MetaData[i, 15].Length - 1) + " %";
}
else
{
return "(" + MetaData[i, 15].Substring(1, MetaData[i, 15].Length - 1) + " %)";
}
}
}
else
return "(0 %)";
return "(0 %)";
}
public string GetDiscontTitle(int i)
{
int value = getBiggest(MetaData[i, 20], MetaData[i, 21], MetaData[i, 22], MetaData[i, 23]);
return "("+value+" %)";
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void SearchVisual()
{
ViewItemData f = new ViewItemData(1,global);
f.ShowDialog();
Search(global.LastCode1,3);
}
public bool Search(string data,int way)
{
double count = 1;
string field = "";
switch(way)
{
case 1: field = "art"; data = ConertCodeInput(data); break;
case 2: field = "code0"; data = ConertCodeInput(data); break;
case 3: field = "code1"; data = ConertCode(data); break;
case 4: field = "code1"; data = ConertCode(ConertCodeInput(data)); break;
default: field = "code1"; break;
}
string query = ""
+ " SELECT "
+ " item_data.id, "
+ " item_data.art, "
+ " item_data.code0, "
+ " item_data.code1, "
+ " item_data.title, "
+ " item_data.`type`, "
+ " item_type.title, "
+ " item_data.measure, "
+ " item_measure.title, "
+ " item_data.prize, "
+ " item_data.`group`, "
+ " item_groups.title, "
+ " item_data.section, "
+ " item_section.title, "
+ " item_data.nalog, "
+ " item_nalog.title, "
+ " item_data.kkm "
+ " FROM item_data "
+ " LEFT JOIN item_type ON item_type.id = item_data.type "
+ " LEFT JOIN item_measure ON item_measure.id = item_data.measure "
+ " LEFT JOIN item_groups ON item_groups.id = item_data.group "
+ " LEFT JOIN item_section ON item_section.id = item_data.section "
+ " LEFT JOIN item_nalog ON item_nalog.id = item_data.nalog "
+ " WHERE item_data." + field + " = '" + data + "'; ";
//MessageBox.Show(query);
My db = new My();
db.Connect();
db.Query(query);
if (db.Read())
{
int index = GetEmptyString();
// Заполняем массив данными из выборки
MetaData[index, 0] = db.GetString(0);
MetaData[index, 1] = db.GetString(1);
MetaData[index, 2] = db.GetString(2);
MetaData[index, 3] = db.GetString(3);
MetaData[index, 4] = db.GetString(4);
MetaData[index, 5] = db.GetString(5);
MetaData[index, 6] = db.GetString(6);
MetaData[index, 7] = db.GetString(7);
MetaData[index, 8] = db.GetString(8);
MetaData[index, 9] = db.GetString(9);
MetaData[index, 10] = "0"; // Цена окончательная посчитаем потом
MetaData[index, 11] = db.GetString(10);
MetaData[index, 12] = db.GetString(11);
MetaData[index, 13] = db.GetString(12);
MetaData[index, 14] = db.GetString(13);
MetaData[index, 15] = db.GetString(14);
MetaData[index, 16] = db.GetString(15);
MetaData[index, 17] = db.GetString(16);
MetaData[index, 18] = "1"; // Статус
MetaData[index, 19] = "1"; // Количество
MetaData[index, 20] = "0";
MetaData[index, 21] = "0";
MetaData[index, 22] = "0";
MetaData[index, 23] = "0";
MetaData[index, 24] = "";
MetaData[index, 25] = "";
MetaData[index, 26] = settings.TicketIncrement+"-"+settings.SystemID;
// Считаем количество
// Если весовой до просим ввести вес
if (db.GetString(5) == "1")
{
TicketCount TKc = new TicketCount(1, global); TKc.ShowDialog();
count = global.buffTicketMetaCount;
}
else
{
// Если количественный и в настройках всегда спрашивать спрашиваем количество
if (settings.configTicketMetaCount == "1")
{
TicketCount TKc = new TicketCount(0, global); TKc.ShowDialog();
count = global.buffTicketMetaCount;
}
else { count = 1; }
}
// TЕсли количество ноль то не продалжаем
if (count == 0) return false;
// Округляем на всякий случай
MetaData[index, 19] = Convert.ToString(Math.Round(count, 3));
// Считаем цену
MetaData[index, 10] = Convert.ToString(Math.Round(Convert.ToDouble(MetaData[index, 9]) * count, 2));
// Уникальный номер пробитого товара
SettingIncremet("meta");
MetaData[index, 25] = settings.TicketMetaIncrement + "-" + settings.SystemID;
}
else
{
ErrorMsg = "Товар в базе данных не найден";
ShowError();
return false;
}
CheckList();
Form_TableUpdate();
return true;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public int GetEmptyString()
{
for(int i = 0; i < 1000; i++)
{
if (MetaData[i, 0] == "" || MetaData[i, 0] == null)
{
return i;
}
}
return 999;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public string ConertCode(string code)
{
int lenght = 13;
if (code.Length == lenght)
{
return code;
}
if (code.Length > lenght)
{
return code.Substring(0, 13);
}
if (code.Length < lenght)
{
if(settings.TicketFullZero == "1")
{
int repeat = (lenght - code.Length);
for (int i = 0; i < repeat; i++)
code += "0";
}
return code;
}
return code;
}
public string ConertCodeInput(string data)
{
if (settings.configInputRtoL == "0")
{
if (InputTrigger == 0)
return data.Substring(0, data.Length - 2);
else
return data;
}
else
return data;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void SettingIncremet(string data)
{
if (data == "data")
{
settings.TicketIncrement++;
settings.Save();
}
if (data == "meta")
{
settings.TicketMetaIncrement++;
settings.Save();
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void InputAdd(string add)
{
HideError();
if (settings.configInputRtoL == "1")
{
InputString += add;
}
else
{
if (InputTrigger == 0)
{
InputString = InputString.Substring(0, InputString.Length - 2) + add + InputString.Substring(InputString.Length - 2, 2);
}
else
{
if (InputTrigger == 2)
{
InputString = InputString.Substring(0, InputString.Length - 1) + add;
InputTrigger = 3;
}
if (InputTrigger == 1)
{
InputString = InputString.Substring(0, InputString.Length - 2) + add + "0";
InputTrigger = 2;
}
}
}
InputDraw();
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void InputDraw()
{
if (textboxInput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(InputDraw);
textboxInput.Invoke(d, new object[] { });
}
else
{
if (InputString.Length == 0) textboxInput.Text = "000.00";
else if (InputString.Length == 1) textboxInput.Text = "000.0" + InputString;
else if (InputString.Length == 2) textboxInput.Text = "000." + InputString;
else if (InputString.Length == 3) textboxInput.Text = "00" + InputString[0] + "." + InputString.Substring(InputString.Length - 2, 2);
else if (InputString.Length == 4) textboxInput.Text = "0" + InputString.Substring(0, 2) + "." + InputString.Substring(InputString.Length - 2, 2);
else textboxInput.Text = InputString.Substring(0, InputString.Length - 2) + "." + InputString.Substring(InputString.Length - 2, 2);
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void TicketIdUpdate()
{
labelTicketId.Text = Convert.ToString(settings.TicketIncrement);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void InputEmpty()
{
if (settings.configInputRtoL == "1")
InputString = "";
else
{
InputString = "00";
InputTrigger = 0;
}
InputDraw();
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
private void Register_KeyDown(object sender, KeyEventArgs e)
{
KeyDownCase(e);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
private void ScanerPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
InputEmpty();
Search(ScanerPort.ReadLine(),3);
ScanerPort.DiscardInBuffer();
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void ShowError()
{
if (textboxInput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(ShowError);
textboxInput.Invoke(d, new object[] { });
}
else
{
labelError.Text = ErrorMsg;
labelError.Show();
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void HideError()
{
if (textboxInput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(HideError);
textboxInput.Invoke(d, new object[] { });
}
else
{
labelError.Hide();
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public void UpdateTotalPrise()
{
double sum = 0;
for (int i = 0; i < 1000; i++)
{
if (MetaData[i,18] == "1")
sum += Convert.ToDouble(MetaData[i,10]);
}
sum = Math.Round(sum, 2);
if (dataGrid.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(UpdateTotalPrise);
TotalPrise.Invoke(d, new object[] { });
}
else
{
TotalPrise.Text = Convert.ToString(sum);
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
public double ToDoubleForm(string data)
{
string[] pieces = data.Split(new string[] { "," }, StringSplitOptions.None);
if (pieces[1].Length == 1)
return Convert.ToInt32(pieces[0]) + Convert.ToInt32(pieces[1]) / 10;
else if (pieces[1].Length == 2)
return Convert.ToInt32(pieces[0]) + Convert.ToInt32(pieces[1]) / 100;
else
return Convert.ToInt32(pieces[0]);
}
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
public bool KeyDownCase(KeyEventArgs e)
{
e.Handled = true;
if (global.KeysCodes(e, "SearchVisual"))
{ SearchVisual(); return true; }
if (global.KeysCodes(e, "SearchCode1"))
{ Search(InputString, 4); return true; }
if (global.KeysCodes(e, "SearchCode0"))
{ Search(InputString, 2); return true; }
if (global.KeysCodes(e, "SearchArt"))
{ Search(InputString, 1); return true; }
if (global.KeysCodes(e, "Note"))
{ if (InputTrigger == 0) InputTrigger = 1; return true; }
if (global.KeysCodes(e, "DeleteString"))
{ MetaUnset(); return true; }
if (global.KeysCodes(e, "Close"))
{ this.Close(); return true; }
if (global.KeysCodes(e, "Down"))
{ MoveDataGridDown(); return true; }
if (global.KeysCodes(e, "Up"))
{ MoveDataGridUp(); return true; }
if (global.KeysCodes(e, "Num0"))
{ InputAdd("0"); return true; }
if (global.KeysCodes(e, "Num1"))
{ InputAdd("1"); return true; }
if (global.KeysCodes(e, "Num2"))
{ InputAdd("2"); return true; }
if (global.KeysCodes(e, "Num3"))
{ InputAdd("3"); return true; }
if (global.KeysCodes(e, "Num4"))
{ InputAdd("4"); return true; }
if (global.KeysCodes(e, "Num5"))
{ InputAdd("5"); return true; }
if (global.KeysCodes(e, "Num6"))
{ InputAdd("6"); return true; }
if (global.KeysCodes(e, "Num7"))
{ InputAdd("7"); return true; }
if (global.KeysCodes(e, "Num8"))
{ InputAdd("8"); return true; }
if (global.KeysCodes(e, "Num9"))
{ InputAdd("9"); return true; }
if (global.KeysCodes(e, "Cancel"))
{ InputEmpty(); return true; }
if (global.KeysCodes(e, "KeyDiscontAll"))
{ HandDiscont("All"); return true; }
if (global.KeysCodes(e, "KeyDiscontPos"))
{ HandDiscont("Pos"); return true; }
if (global.KeysCodes(e, "Enter"))
{
if (dataGrid.Rows.Count != 0)
{
CompleteTicket(1);
}
}
return true;
}
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
public bool MoveDataGridDown()
{
if (dataGrid.Rows.Count == 0 || dataGrid.Rows.Count == 1) return false;
int Count = dataGrid.Rows.Count-1;
int Current = dataGrid.SelectedRows[0].Index;
if (Count == Current) Current = 0;
else Current++;
dataGrid.Rows[Current].Selected = true;
dataGrid.FirstDisplayedScrollingRowIndex = Current;
return true;
}
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
public bool MoveDataGridUp()
{
if (dataGrid.Rows.Count == 0 || dataGrid.Rows.Count == 1) return false;
int Count = dataGrid.Rows.Count-1;
int Current = dataGrid.SelectedRows[0].Index;
if (Current == 0) Current = Count;
else Current--;
dataGrid.Rows[Current].Selected = true;
dataGrid.FirstDisplayedScrollingRowIndex = Current;
return true;
}
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
public void CompleteTicket( int way )
{
if (dataGrid.Rows.Count != 0)
{
TicketAccemble tAcc = new TicketAccemble(MetaData,labelTicketId.Text,global);
if (way == 0) tAcc.Cansel();
if (way == 1) tAcc.Accept();
dataGrid.Rows.Clear();
settings.TicketIncrement++;
settings.Save();
item_count = 1;
CompleteTrigger = 3;
Array.Clear(MetaData, 0, MetaData.Length);
UpdateTotalPrise();
TicketIdUpdate();
HideError();
}
}
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
public bool MetaUnset()
{
try
{
int IndexOf = dataGrid.SelectedRows[0].Index;
if (MetaData[IndexOf, 18] == "1")
{
dataGrid.Rows[IndexOf].DefaultCellStyle.BackColor = Color.OrangeRed;
MetaData[IndexOf, 18] = "0";
}
else
{
dataGrid.Rows[IndexOf].DefaultCellStyle.BackColor = Color.LightGreen;
MetaData[IndexOf, 18] = "1";
}
MoveDataGridDown();
UpdateTotalPrise();
}
catch (Exception ex)
{
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
private void Register_FormClosing(object sender, FormClosingEventArgs e)
{
CompleteTicket(0);
ScanerPort.Close();
}
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
public void CheckList()
{
for (int i = 0; i < 1000; i++)
{
if (MetaData[i, 0] != "")
{
// Удаляем нулевые цены
if (settings.TicketDenyZero == "1")
{
if (MetaData[i, 9] == "0" || MetaData[i, 10] == "0")
{
MetaClearString(i);
}
}
// Обьединяем одинаковые позиции
if (settings.TicketFullEqual == "1")
{
for (int j = 0; j < i; j++)
{
if (MetaData[i, 3] == MetaData[j, 3] && MetaData[j, 18] != "0" && MetaData[i, 0] != "" && MetaData[j, 0] != "")
{
MetaData[j, 10] = Convert.ToString(Convert.ToDouble(MetaData[j, 10]) + Convert.ToDouble(MetaData[i, 10]));
MetaData[j, 19] = Convert.ToString(Convert.ToDouble(MetaData[j, 19]) + Convert.ToDouble(MetaData[i, 19]));
MetaClearString(i);
}
}
}
////////////////////////////////
UpdateTotalPrise();
////////////////////////////////
}
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
for (int i = 0; i < 1000; i++)
{
if (MetaData[i, 0] != "" && MetaData[i, 0] != null)
{
MetaData[i, 10] = Convert.ToString(Math.Round(Convert.ToDouble(MetaData[i, 9]) * Convert.ToDouble(MetaData[i, 19]), 2));
// Считаем налог
if (MetaData[i, 15] != "0" && MetaData[i, 15] != null && MetaData[i, 15] != "")
{
if (MetaData[i, 15].Length > 1)
{
if (MetaData[i, 15].Substring(0, 1) == "1")
{
MetaData[i, 10] = Convert.ToString(Math.Round(Convert.ToDouble(MetaData[i, 10]) + Convert.ToDouble(MetaData[i, 10]) / 100 * Convert.ToDouble(MetaData[i, 15].Substring(1, MetaData[i, 15].Length - 1)), 2));
}
}
}
////////////////////////////////
// Считаем скидку системную по времени
MetaData[i, 20] = global.GetDiscontTime(MetaData[i, 0], MetaData[i, 11]);
// Находим большую скидку и перещитываем по ней цену
MetaData[i, 10] = Convert.ToString(Math.Round(Convert.ToDouble(MetaData[i, 10]) - Convert.ToDouble(MetaData[i, 10]) / 100 * getBiggest(MetaData[i, 20], MetaData[i, 21], MetaData[i, 22], MetaData[i, 23]), 2));
}
}
Form_TableUpdate();
UpdateTotalPrise();
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
public void MetaClearString(int i)
{
for (int g = 0; g < 30; g++)
MetaData[i, g] = "";
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
public int getBiggest(string a1, string a2, string a3, string a4)
{
int b1 = Convert.ToInt32(a1);
int b2 = Convert.ToInt32(a2);
int b3 = Convert.ToInt32(a3);
int b4 = Convert.ToInt32(a4);
if (b1 >= b2 && b1 >= b3 && b1 >= b4)
return b1;
if (b2 >= b1 && b2 >= b3 && b2 >= b4)
return b2;
if (b3 >= b1 && b3 >= b2 && b3 >= b4)
return b3;
if (b4 >= b1 && b4 >= b2 && b4 >= b3)
return b4;
return b1;
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
public void HandDiscont(string data)
{
if (data == "All")
{
TicketCount f = new TicketCount(0, global, "Велечина ручной скидки (На все позиции чека)");
f.ShowDialog();
}
if (data == "Pos")
{
TicketCount f = new TicketCount(0, global, "Велечина ручной скидки (На выделенную позицию чека)");
f.ShowDialog();
}
string value = Convert.ToString(global.buffTicketMetaCount);
int Increm = 1;
for (int i = 0; i < 1000; i++)
{
if (MetaData[i, 0] != "" && MetaData[i, 0] != null)
{
if (data == "All")
{
MetaData[i, 21] = value;
}
if (data == "Pos" )
{
if(Convert.ToString(Increm) == dataGrid.SelectedRows[0].Cells["i"].Value.ToString())
MetaData[i, 21] = value;
}
Increm++;
}
}
CheckList();
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Platformer.Mechanics;
using Platformer.UI;
namespace Platformer.Mechanics
{
public class EnemyDetectShoot : MonoBehaviour
{
public bool facingRight = true;
public float timeTemp = 0f;
public float fireRate = 1f;
public Transform enemyEntity;
public int direction = 3;
public GameObject bulletShoot = null;
Vector2 move;
//public void ShootBulletButton() shoot bullet on based on fireRate
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
ShootBulletButton();
}
public void ShootBulletButton()
{
if (bulletShoot != null)
{
if(Time.time > timeTemp)
{
bulletShoot.GetComponent<Player8Shoot>().bulletDirection = direction;
GameObject bullet = Instantiate(bulletShoot) as GameObject;
bullet.transform.position = enemyEntity.transform.position;
timeTemp = Time.time + fireRate;
}
}
}
//UR means upper right direction
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 8;
//UL means upper left direction
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 7;
//shoots up
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 6;
//DR means lower right direction
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 5;
//DL means lower left direction
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 4;
//shoots down
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 3;
//shoots right
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 2;
//shoots left
//bulletShoot.GetComponent<Player8Shoot>().bulletDirection = 1;
}
} |
using FluentAssertions;
using Moq;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tynamix.ObjectFiller;
using ValidationExperiments.Core.Entities;
using Xunit;
namespace ValidationExperiments.Tests.Services
{
public partial class CourseServiceTests
{
[Fact]
public async Task GetCourseAsync_ShouldThrowApplicationExceptionWhenIdIsNotFound()
{
// given (arrange)
int invalidId = 100;
Course invalidCourse = null;
this.appDbContextMock.Setup(db =>
db.SelectCourseByIdAsync(invalidId))
.ReturnsAsync(invalidCourse);
// when (act)
var subjectTask = subject.GetCourseAsync(invalidId);
// then (assert)
await Assert.ThrowsAsync<ApplicationException>(() => subjectTask);
appDbContextMock.Verify(db => db.SelectCourseByIdAsync(invalidId), Times.Once);
appDbContextMock.VerifyNoOtherCalls();
}
[Fact]
public async Task AddCourseAsync_ShouldThrowExceptionForInvalidDataAnnotationRequirement()
{
// given (arrange)
Filler<Course> courseFiller = new Filler<Course>();
courseFiller.Setup()
.OnProperty(p => p.Id).IgnoreIt();
Course invalidCourseToAdd = courseFiller.Create();
invalidCourseToAdd.Name = null;
Course databaseCourse = this.mapper.Map<Course>(invalidCourseToAdd);
databaseCourse.Id = 1;
this.appDbContextMock.Setup(db =>
db.CreateCourseAsync(invalidCourseToAdd))
.ReturnsAsync(databaseCourse);
// when (act)
var actualCourseTask = subject.AddCourseAsync(invalidCourseToAdd);
// then (assert)
await Assert.ThrowsAsync<ValidationException>(() => actualCourseTask);
appDbContextMock.VerifyNoOtherCalls();
}
[Fact]
public async Task AddCourseAsync_ShouldThrowExceptionForInvalidBusinessLogicRequirement()
{
// given (arrange)
Filler<Course> courseFiller = new Filler<Course>();
courseFiller.Setup()
.OnProperty(p => p.Id).IgnoreIt();
Course invalidCourseToAdd = courseFiller.Create();
invalidCourseToAdd.CourseLessons = new List<CourseLesson>();
Course databaseCourse = this.mapper.Map<Course>(invalidCourseToAdd);
databaseCourse.Id = 1;
this.appDbContextMock.Setup(db =>
db.CreateCourseAsync(invalidCourseToAdd))
.ReturnsAsync(databaseCourse);
// when (act)
var actualCourseTask = subject.AddCourseAsync(invalidCourseToAdd);
// then (assert)
await Assert.ThrowsAsync<ValidationException>(() => actualCourseTask);
appDbContextMock.VerifyNoOtherCalls();
}
[Fact]
public async Task AddCourseAsync_ShouldThrowExceptionForInvalidBusinessLogicRequirementNullList()
{
// given (arrange)
Filler<Course> courseFiller = new Filler<Course>();
courseFiller.Setup()
.OnProperty(p => p.Id).IgnoreIt();
Course invalidCourseToAdd = courseFiller.Create();
invalidCourseToAdd.CourseLessons = null;
Course databaseCourse = this.mapper.Map<Course>(invalidCourseToAdd);
databaseCourse.Id = 1;
this.appDbContextMock.Setup(db =>
db.CreateCourseAsync(invalidCourseToAdd))
.ReturnsAsync(databaseCourse);
// when (act)
var actualCourseTask = subject.AddCourseAsync(invalidCourseToAdd);
// then (assert)
await Assert.ThrowsAsync<ValidationException>(() => actualCourseTask);
appDbContextMock.VerifyNoOtherCalls();
}
[Fact]
public async Task AddCourseAsync_ShouldNotThrowExceptionForInvalidChildObjectDataAnnotationRequirement()
{
// Weird test: making sure nothing unexpected changes with the built-in validator
// The expectation is that invalid child objects will NOT be detected (so we know we need to handle them elsewhere)
// Note: the DB itself SHOULD throw an exception with an invalid child object
// given (arrange)
Filler<Course> courseFiller = new Filler<Course>();
courseFiller.Setup()
.OnProperty(p => p.Id).IgnoreIt();
Course invalidCourseToAdd = courseFiller.Create();
invalidCourseToAdd.CourseLessons.First().Authors.First().Author.FirstName = null;
Course databaseCourse = this.mapper.Map<Course>(invalidCourseToAdd);
databaseCourse.Id = 1;
this.appDbContextMock.Setup(db =>
db.CreateCourseAsync(invalidCourseToAdd))
.ReturnsAsync(databaseCourse);
// when (act)
Course actualCourse = await subject.AddCourseAsync(invalidCourseToAdd);
// then (assert)
actualCourse.Should().BeEquivalentTo(databaseCourse);
appDbContextMock.Verify(db => db.CreateCourseAsync(invalidCourseToAdd), Times.Once);
appDbContextMock.VerifyNoOtherCalls();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntidadesCompartidas;
namespace Persistencia.interfaces
{
public interface IPersistenciaSolicitud
{
int AltaSolicitud(Solicitud solicitud, Empleado usLog);
void ModificarEstadoSolicitud(Solicitud solicitud, Empleado usLog);
List<Solicitud> listadoSolicitudesEnCamino();
List<Solicitud> listadoSolicitudesEmpresa(Empresa usLog);
List<Solicitud> listadoSolicitudes(Empleado usLog);
}
}
|
using System.Collections.Generic;
using System.Security.Claims;
namespace DynamicPermission.AspNetCore.Common.Models
{
public class AreaViewModel
{
public Claim Area { get; set; }
public List<ControllerViewModel> ControllerViewModels { get; set; } = new List<ControllerViewModel>();
}
public class ControllerViewModel
{
public Claim ParentArea { get; set; }
public Claim Controller { get; set; }
public List<ActionViewModel> ActionViewModels { get; set; } = new List<ActionViewModel>();
}
public class ActionViewModel
{
public Claim ParentController { get; set; }
public Claim Action { get; set; }
public bool Selected { get; set; }
}
} |
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class ExportRegisterPublicSchedules
{
public DateTime? LastQueryExecuted;
public List<Schedule> Schedules;
public Boolean LastExportStatus;
public Int32 Id;
public String Type;
public String FriendlyName;
public Boolean Executing;
public Boolean justOnce;
public DateTime? Started;
public DateTime? Completed;
public Boolean IsQueued;
public Boolean Enabled;
public Boolean IsNew;
public Boolean AllSchedulesDisabled;
public DateTime? NextSchedule;
}
} |
using RevolutionCAD.Composition;
using RevolutionCAD.Tracing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace RevolutionCAD.Placement
{
public class PlacementResult
{
public List<Matrix<int>> BoardsMatrices { get; set; } // список плат с номерами элементов, которые расположены в определённой позиции на плате
public List<Matrix<Cell>> BoardsDRPs { get; set; } // список дрп плат, на которых размещены элементы с контактами
public List<Dictionary<int,List<Position>>> BoardsElementsContactsPos { get; set; } // список словарей плат, в словаре по ключу (номеру элемента) можно получить список координат определённого контакта
public List<List<Wire>> BoardsWiresPositions { get; set; } // список плат, в котором хранится список проводов по 2 контакта для каждой платы
public void CreateBoardsDRPs(CompositionResult cmp, List<int> dips, out string err)
{
err = "";
var elInBoards = cmp.BoardsElements;
var boardsWires = cmp.BoardsWires;
if (BoardsMatrices == null)
{
err = "Список плат пустой";
return;
}
if (BoardsMatrices.Count == 0)
{
err = "Список плат пустой";
return;
}
// список в котором будет хранится размер разъёма для каждой платы
var BoardsCountContactsConnector = new List<int>();
BoardsElementsContactsPos = new List<Dictionary<int, List<Position>>>();
BoardsDRPs = new List<Matrix<Cell>>();
// запускаем цикл для формирования своего дрп для каждого узла
for (int numBoard = 0; numBoard < BoardsMatrices.Count; numBoard++)
{
int countContactsConnector = 0;
countContactsConnector = boardsWires[numBoard].Count(x => x.Any(y => y.ElementNumber == 0));
BoardsCountContactsConnector.Add(countContactsConnector);
// расчёт размера ДРП платы
int drpHeight = 0;
int drpWidth = 0;
var brdMatr = BoardsMatrices[numBoard];
// подсчитываем необходимую высоту платы
// запускаем цикл по столбцам, и определяем его высоту суммируя размер для каждого элемента
for (int j = 0; j<brdMatr.ColsCount; j++)
{
int currentColHeight = 0;
for (int i = 0; i<brdMatr.RowsCount; i++)
{
int elementNumber = brdMatr[i, j];
if (elementNumber != -1) // пропускаем пустые места
{
int elementDip = dips[elementNumber];
int pinsInColumn = elementDip / 2;
currentColHeight += ApplicationData.ElementsDistance + pinsInColumn + (ApplicationData.PinDistance * pinsInColumn) - ApplicationData.PinDistance;
}
}
if (currentColHeight > drpHeight)
drpHeight = currentColHeight;
}
// подсчитываем необходимую ширину платы
for (int i = 0; i < brdMatr.RowsCount; i++)
{
int currentRowWidth = 0;
for (int j = 0; j < brdMatr.ColsCount; j++)
{
int elementNumber = brdMatr[i, j];
if (elementNumber != -1) // пропускаем пустые места
{
int elementDip = dips[elementNumber];
currentRowWidth += ApplicationData.ElementsDistance + 2 + ApplicationData.RowDistance;
}
}
if (currentRowWidth > drpWidth)
drpWidth = currentRowWidth;
}
drpHeight += ApplicationData.ElementsDistance;
drpWidth += ApplicationData.ElementsDistance + 2; // ширина + 2, чтобы учесть разъём
// создаём итоговое дрп на базе расчётов
var boardDRP = new Matrix<Cell>(drpHeight, drpWidth);
// заполняем его пустыми ячейками
for (int drpRow = 0; drpRow < boardDRP.RowsCount; drpRow++)
{
for (int drpCol = 0; drpCol < boardDRP.ColsCount; drpCol++)
{
boardDRP[drpRow, drpCol] = new Cell();
}
}
// создаём словарь координат контактов разъёма и элементов
var ElementsContactsPos = new Dictionary<int, List<Position>>();
// переходим к размещению разъёма
var heightConnector = BoardsCountContactsConnector.Last();
int startRowConnector = drpHeight / 2 - heightConnector / 2;
var ConnectorContactsPos = new List<Position>();
for (int r = 0; r<heightConnector; r++)
{
boardDRP[startRowConnector + r, r % 2].State = CellState.Contact;
ConnectorContactsPos.Add(new Position(startRowConnector + r, r % 2));
}
ElementsContactsPos.Add(0, ConnectorContactsPos);
Position startPos = new Position(ApplicationData.ElementsDistance, ApplicationData.ElementsDistance + 2);
Position currentPos = new Position(ApplicationData.ElementsDistance, ApplicationData.ElementsDistance + 2);
// запускаем цикл по столбцам матрицы, в которой хранятся номера элементов
for (int j = 0; j < brdMatr.ColsCount; j++)
{
// запускаем цикл по строкам матрицы, в которой хранятся номера элементов
for (int i = 0; i < brdMatr.RowsCount; i++)
{
// узнаём номер элемента в позиции
int elementNumber = brdMatr[i, j];
// если -1 - значит место не занято
if (elementNumber != -1) // пропускаем пустые места
{
// список координат каждого контакта
var ElementContactsPos = new List<Position>();
// добавляем заглушку, т.к. нумерация ножек начинается с 1, а у нас список и 0 элемент должен существовать
ElementContactsPos.Add(new Position(-1, -1));
int elementNumberLabelRow = currentPos.Row;
int elementNumberLabelColumn = currentPos.Column + (int)Math.Ceiling((double)ApplicationData.RowDistance / 2);
boardDRP[elementNumberLabelRow, elementNumberLabelColumn].Description = $"D{elementNumber}";
// узнаём номер дипа
int elementDip = dips[elementNumber];
// количество контактов в столбце = номер дипа / 2
int pinsInColumn = elementDip / 2;
int offsetRow = 0;
// сначала формируем первый ряд контактов элемента сверху вниз
boardDRP[currentPos.Row + offsetRow, currentPos.Column].Description = "(X)";
while ( offsetRow < (pinsInColumn * (ApplicationData.PinDistance+1)) - ApplicationData.PinDistance)
{
boardDRP[currentPos.Row + offsetRow, currentPos.Column].State = CellState.Contact;
// записываем текущую координату в список координат контактов
ElementContactsPos.Add(new Position(currentPos.Row + offsetRow, currentPos.Column));
offsetRow += 1 + ApplicationData.PinDistance;
}
offsetRow -= 1 + ApplicationData.PinDistance;
// сдвигаемся вправо на расстояние в клетках от первого ряда контактов
currentPos.Column += ApplicationData.RowDistance + 1;
// теперь идём обратно вверх
while (offsetRow >= 0)
{
boardDRP[currentPos.Row + offsetRow, currentPos.Column].State = CellState.Contact;
// записываем текущую координату в список координат контактов
ElementContactsPos.Add(new Position(currentPos.Row + offsetRow, currentPos.Column));
offsetRow -= 1 + ApplicationData.PinDistance;
}
// добавляем сформированный список координат каждого контакта
ElementsContactsPos.Add(elementNumber, ElementContactsPos);
// возвращаемся опять в позицию для печати первого ряда контактов, но уже следующего элемента
currentPos.Column -= ApplicationData.RowDistance + 1;
// пропускаем ячейки с уже размещённым элементом
currentPos.Row += (pinsInColumn * (ApplicationData.PinDistance + 1)) - ApplicationData.PinDistance;
currentPos.Row += ApplicationData.ElementsDistance;
} else
{
// если позиция пустая, то нужно пропустить определённое количество клеточек
// формула приблизительная
currentPos.Row += drpHeight / (brdMatr.RowsCount + 1);
}
}
// возвращаемся к начальной точке размещения элементов
currentPos.Row = startPos.Row;
currentPos.Column = startPos.Column;
// пропускаем определённое количество столбцов, которое определяется по количеству уже размещённых умноженное на отступы
currentPos.Column += ((j + 1) * (ApplicationData.RowDistance + 2)) + ((j + 1) * ApplicationData.ElementsDistance);
}
BoardsDRPs.Add(boardDRP);
BoardsElementsContactsPos.Add(ElementsContactsPos);
}
return;
}
public void CreateWires(List<List<List<Contact>>> BoardsWires)
{
BoardsWiresPositions = new List<List<Wire>>();
for(int boardNum = 0; boardNum < BoardsWires.Count; boardNum++)
{
int countConnectorPins = 0;
var boardWires = new List<Wire>();
foreach(var contactsPair in BoardsWires[boardNum])
{
var wire = new Wire();
var contactA = contactsPair[0];
if (contactA.ElementNumber == 0)
{
contactA.ElementContact = countConnectorPins++;
}
var contactB = contactsPair[1];
if (contactB.ElementNumber == 0)
{
contactB.ElementContact = countConnectorPins++;
}
int drpRowContact = BoardsElementsContactsPos[boardNum][contactA.ElementNumber][contactA.ElementContact].Row;
int drpColumnContact = BoardsElementsContactsPos[boardNum][contactA.ElementNumber][contactA.ElementContact].Column;
wire.A.PositionContact = new Position(drpRowContact, drpColumnContact);
drpRowContact = BoardsElementsContactsPos[boardNum][contactB.ElementNumber][contactB.ElementContact].Row;
drpColumnContact = BoardsElementsContactsPos[boardNum][contactB.ElementNumber][contactB.ElementContact].Column;
wire.B.PositionContact = new Position(drpRowContact, drpColumnContact);
boardWires.Add(wire);
}
BoardsWiresPositions.Add(boardWires);
}
}
}
}
|
namespace HCL.Academy.Model
{
public class TrainingAssignment
{
public string TrainingName { get; set; }
public int TrainingId { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public int EmployeeId { get; set; }
}
}
|
using System;
namespace OmniGui
{
public interface IRenderSurface
{
void ForceRender();
void ShowVirtualKeyboard();
void SetFocusedElement(Layout textBoxView);
IObservable<Layout> FocusedElement { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using LiveCharts;
using LiveCharts.Wpf;
using MyPrivateFinance.util;
using MyPrivateFinance.data.entities;
namespace MyPrivateFinance
{
/// <summary>
/// Interaktionslogik für Statistics.xaml
/// </summary>
public partial class Statistics : Window
{
private ChartManager<double> chartManager = new ChartManager<double>();
public Statistics(List<Payment> payments)
{
InitializeComponent();
//Get income and expenses
double income = GetIncomes(payments);
double expenses = GetExpenses(payments);
SeriesCollection series = chartManager.CreateIncomeExpensesCollection(new List<double> { income } , new List<double> { expenses });
MyChart.Series = series;
MyChart.LegendLocation = LegendLocation.Right;
}
/// <summary>
/// Method to get total income from a payment list
/// </summary>
/// <param name="payments"></param>
/// <returns></returns>
private double GetIncomes(List<Payment> payments)
{
double totalIncome = 0.0;
foreach(Payment payment in payments)
{
if (payment.isIncome)
{
totalIncome += payment.amount;
}
}
return totalIncome;
}
/// <summary>
/// List to get total expenses from a payment list
/// </summary>
/// <param name="payments"></param>
/// <returns></returns>
private double GetExpenses(List<Payment> payments)
{
List<double> expenses = new List<double>();
double totalExpenses = 0.0;
foreach(Payment payment in payments)
{
if (!payment.isIncome)
{
expenses.Add(payment.amount);
totalExpenses += payment.amount;
}
}
return totalExpenses;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UserProgression : MonoBehaviour {
public bool Emp_6A_01_Locked;
public bool Emp_6A_02_Locked;
public bool Emp_6A_03_Locked;
public bool Quiz_Locked;
public bool Emp_6B_Locked;
public bool Wrapup_Locked;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MGL_API.Model.Entrada
{
public class EntradaAvaliarGame
{
public int IdGame { get; set; }
public string Classificacao { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace ICOMSClient
{
public partial class FrmICOMSClient : Form
{
public FrmICOMSClient()
{
InitializeComponent();
}
private void btnSendReq_Click(object sender, EventArgs e)
{
txtOPICOMMessage.Text= Connect(txtIPAddress.Text.Trim(), txtIPPort.Text.Trim(), txtIPICOMMessage.Text.Trim());
}
public static string Connect(string server, string strPort, string message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = Convert.ToInt32(strPort);
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
stream.Close();
client.Close();
return responseData;
}
catch (ArgumentNullException e)
{
return e.ToString();
}
catch (SocketException e)
{
return e.ToString();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void txtOPICOMMessage_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
txtIPICOMMessage.Text = "I000CUI,TI:000000000000000000,AN:010203040,SI:013,HE:A1,ND:B1234,BD:05,TL:Mrs ,LNixpack ,FN:Joe ,MI:Y,A1:123 Street St. ,A2:Apt#123 ,CT:Greenville ,STA,ZP:12345 ,HP:213 123 1234,WP:215 123 1234,AS:A,E1:ENG456789012345,E2:ENG112211221122,E3:ENG334433443344.00039V000CUI,0000000,TI:000000000000000000.select HomePhone from Subscriber where SmsTag='013010203040'213 123 1234select SecondPhone from Subscriber where SmsTag='013010203040'215 123 1234";
//txtIPICOMMessage.Text = string.Empty;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed = 10f;
public float jumpSpeed = 20;
[SerializeField]
private Stat health;
[SerializeField]
private Stat armor;
private void Awake()
{
health.Initialize();
armor.Initialize();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
if (armor.CurrentVal <= 0)
{
health.CurrentVal -= 10;
}
else
{
armor.CurrentVal -= 20;
}
}
if (Input.GetKeyDown(KeyCode.W))
{
if (health.CurrentVal >= 100)
{
armor.CurrentVal += 20;
}
else
{
health.CurrentVal += 10;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Contoso.Parameters.Expressions
{
public interface IExpressionParameter
{
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
public class GameController : MonoBehaviour {
public GameObject ground;
public UIController uiController;
public CarController carController;
public HUDController hudController;
public GameObject redCar;
public GameObject greenCar;
public ParticleSystem redCarLeftSmoke;
public ParticleSystem redCarRightSmoke;
public ParticleSystem greenCarLeftSmoke;
public ParticleSystem greenCarRightSmoke;
public ObstacleSpawner redSpawner;
public ObstacleSpawner greenSpawner;
public float maxSpeed;
public float initialSpeed;
public static float actualSpeed;
public static float pauseSpeed;
public static bool engineStart = false;
private GameObject[] allBlocks;
private GameObject[] allCircles;
private GameObject[] allShields;
void Start () {
}
void Update () {
if (engineStart) {
if (actualSpeed < maxSpeed) {
actualSpeed += 0.1f;
}
}
}
public void StartEngine () {
redSpawner.Spawn ();
greenSpawner.Spawn ();
engineStart = true;
actualSpeed = initialSpeed;
ObstacleSpawner.isShieldAllowed = true;
}
public void DisplayGround () {
ground.SetActive (true);
StartCoroutine (GroundFadeIn ());
carController.ToggleCarState (redCar);
carController.ToggleCarState (greenCar);
carController.ResetCarPos (redCar, "Red");
carController.ResetCarPos (greenCar, "Green");
StartCoroutine (carController.MoveCarIntoScene (redCar));
StartCoroutine (carController.MoveCarIntoScene (greenCar));
}
private IEnumerator GroundFadeIn () {
Hashtable ft = new Hashtable ();
ft.Add ("alpha", 0);
ft.Add ("time", 0.5f);
ft.Add ("easetype", iTween.EaseType.easeInOutSine);
iTween.FadeFrom (ground, ft);
yield return new WaitForSeconds (0.5f);
}
public void PauseGameAction () {
engineStart = false;
pauseSpeed = actualSpeed;
actualSpeed = 0;
PauseAllParticleEffects ();
}
public void ResumeGameAction () {
engineStart = true;
actualSpeed = pauseSpeed;
pauseSpeed = 0;
PlayAllParticleEffects ();
}
public void HomeGameAction () {
iTween.Stop ();
engineStart = false;
allBlocks = GameObject.FindGameObjectsWithTag ("block");
allCircles = GameObject.FindGameObjectsWithTag ("circle");
allShields = GameObject.FindGameObjectsWithTag ("shield");
DestroyObjects (allBlocks);
DestroyObjects (allCircles);
DestroyObjects (allShields);
PlayAllParticleEffects ();
carController.ResetCarPos (redCar, "Red");
carController.ResetCarPos (greenCar, "Green");
hudController.ResetScore ();
}
public void RestartGameAction () {
iTween.Stop ();
allBlocks = GameObject.FindGameObjectsWithTag ("block");
allCircles = GameObject.FindGameObjectsWithTag ("circle");
allShields = GameObject.FindGameObjectsWithTag ("shield");
DestroyObjects (allBlocks);
DestroyObjects (allCircles);
DestroyObjects (allShields);
PlayAllParticleEffects ();
StartEngine ();
carController.ResetCarPos (redCar, "Red");
carController.ResetCarPos (greenCar, "Green");
hudController.ResetScore ();
}
public void GameOverAction () {
iTween.Pause ();
actualSpeed = 0;
engineStart = false;
hudController.GameOverScoreUpdate ();
uiController.GameOverUIAction ();
PauseAllParticleEffects ();
}
public void ShareButtonClick () {
StartCoroutine (ShareScreenshot ());
}
private void DestroyObjects (GameObject[] objects) {
foreach (GameObject target in objects) {
GameObject.Destroy (target);
}
}
private void PauseAllParticleEffects () {
redCarLeftSmoke.Pause ();
redCarRightSmoke.Pause ();
greenCarLeftSmoke.Pause ();
greenCarRightSmoke.Pause ();
}
private void PlayAllParticleEffects () {
redCarLeftSmoke.Play ();
redCarRightSmoke.Play ();
greenCarLeftSmoke.Play ();
greenCarRightSmoke.Play ();
}
public IEnumerator ShareScreenshot () {
yield return new WaitForEndOfFrame();
Texture2D screenTexture = new Texture2D(Screen.width, Screen.height,TextureFormat.RGB24,true);
screenTexture.ReadPixels(new Rect(0f, 0f, Screen.width, Screen.height),0,0);
screenTexture.Apply();
byte[] dataToSave = screenTexture.EncodeToPNG();
string destination = Path.Combine(Application.persistentDataPath, System.DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + ".png");
File.WriteAllBytes(destination, dataToSave);
if (!Application.isEditor) {
AndroidJavaClass intentClass = new AndroidJavaClass ("android.content.Intent");
AndroidJavaObject intentObject = new AndroidJavaObject ("android.content.Intent");
intentObject.Call<AndroidJavaObject> ("setAction", intentClass.GetStatic<string> ("ACTION_SEND"));
AndroidJavaClass uriClass = new AndroidJavaClass ("android.net.Uri");
AndroidJavaObject uriObject = uriClass.CallStatic<AndroidJavaObject> ("parse","file://" + destination);
intentObject.Call<AndroidJavaObject> ("putExtra", intentClass.GetStatic<string> ("EXTRA_STREAM"), uriObject);
intentObject.Call<AndroidJavaObject> ("setType", "image/jpeg");
AndroidJavaClass unity = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject> ("currentActivity");
currentActivity.Call ("startActivity", intentObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Planning
{
class PredicateListComparer : IEqualityComparer<List<Predicate>>
{
#region IEqualityComparer<List<Predicate>> Members
public bool Equals(List<Predicate> x, List<Predicate> y)
{
if (x.Count != y.Count)
return false;
foreach (Predicate p in x)
if (!y.Contains(p))
return false;
return true;
}
public int GetHashCode(List<Predicate> obj)
{
int iCode = 0;
foreach (Predicate p in obj)
iCode += p.GetHashCode();
return iCode;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
namespace Lncodes.Algorithm.Search.Jump
{
public sealed class JumpSearch
{
/// <summary>
/// Method for jump search
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <param name="element"></param>
/// <returns cref="int"></returns>
public int Search<T>(IReadOnlyList<T> data, T element) where T : IComparable
{
var currentIndex = 0;
var maxIndex = data.Count - 1;
var jumpDistance = (int)Math.Sqrt(data.Count);
var currentRangeMaxIndex = jumpDistance;
while (data[Math.Min(currentRangeMaxIndex, maxIndex)].CompareTo(element) < 0)
{
currentIndex = currentRangeMaxIndex;
currentRangeMaxIndex += jumpDistance;
if (currentIndex > maxIndex)
return -1;
}
while (data[currentIndex].CompareTo(element) < 0)
{
currentIndex++;
if (currentIndex > Math.Min(currentRangeMaxIndex, maxIndex))
return -1;
}
return data[currentIndex].Equals(element) ? currentIndex : -1;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DemoStandardProject.Data;
using DemoStandardProject.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace DemoStandardProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddHttpContextAccessor();
services.AddResponseCaching();
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
// builder.WithExposedHeaders("totalAmountRecords");
// builder.WithExposedHeaders("totalAmountPages");
// builder.WithExposedHeaders("currentPage");
// builder.WithExposedHeaders("recordsPerPage");
}));
services.AddHealthChecks().AddDbContextCheck<AppDBContext>(tags: new[] { "ready" });
services.AddAutoMapper(typeof(Startup));
services.AddDbContext<AppDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IProductService, ProductService>();
services.AddScoped<IProductGroupService, ProductGroupService>();
services.AddScoped<IProductStockLogService, ProductStockLogService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LETS.Models;
using MongoDB.Driver;
using LETS.Helpers;
using MongoDB.Bson;
using Microsoft.Owin.Security;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
using System;
using System.Collections.Generic;
using System.IO;
using MongoDB.Driver.GridFS;
using static System.Configuration.ConfigurationManager;
namespace LETS.Controllers
{
[Authorize]
public class AccountController : Controller
{
public readonly LETSContext DatabaseContext = new LETSContext();
private static readonly Random Random = new Random();
/// <summary>
/// Get method for the Login Page
/// </summary>
/// <returns>returns Login view if the user is not authenticated, else takes the user to the index page</returns>
[AllowAnonymous]
[HttpGet]
public ActionResult Login()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
}
/// <summary>
/// Post method for the Login Page
/// </summary>
/// <param name="loginUser">Holds the entered user credentials i.e. Username and Password</param>
/// <returns>Verifies the user credentials, takes them to the user profile page if valid else takes them back to the login page.</returns>
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public async Task<ActionResult> Login(LoginViewModel loginUser)
{
if (loginUser != null && ModelState.IsValid)
{
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", loginUser.UserName }
}).ToListAsync();
var passowordEncryption = new PasswordHashAndSalt();
loginUser.Password = passowordEncryption.getHashedPassword(loginUser.Password);
if (userByUsername.Count > 0)
{
if (userByUsername[0].Account.UserName.Equals(loginUser.UserName) && (userByUsername[0].Account.Password.Equals(loginUser.Password) || (!string.IsNullOrEmpty(userByUsername[0].Account.TempPassword) && userByUsername[0].Account.TempPassword.Equals(loginUser.Password))))
{
var userAuthentication = new UserAuthentication();
var identity = userAuthentication.AuthenticateUser(userByUsername[0].Account.UserName);
HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false, ExpiresUtc = DateTime.UtcNow + TimeSpan.FromMinutes(15) }, identity);
return RedirectToAction("UserProfile", "Account");
}
else
{
ModelState.AddModelError("UserName", "Please make sure you entered the correct username.");
ModelState.AddModelError("Password", "Please make sure you entered the correct password.");
View();
}
}
else
{
ModelState.AddModelError("UserName", "Please make sure you entered the correct username.");
ModelState.AddModelError("Password", "Please make sure you entered the correct password.");
return View();
}
}
return View();
}
/// <summary>
/// Get method for the Logoff page.
/// </summary>
/// <returns>Logs off the user, kills the session and redirects the user to the index page.</returns>
[HttpGet]
public ActionResult Logoff()
{
var autheticationManager = HttpContext.GetOwinContext().Authentication;
autheticationManager.SignOut();
if (Session != null)
{
Session.Clear();
Session.Abandon();
}
return RedirectToAction("Index", "Home");
}
/// <summary>
/// Get method for the Register Page
/// </summary>
/// <returns>returns the Register page if the user is not authenticated else takes the user to the index page.</returns>
[AllowAnonymous]
[HttpGet]
public ActionResult Register()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
}
/// <summary>
/// Post method for the Register Page
/// </summary>
/// <param name="registerUser">Holds the data entered by the user on the registration page.</param>
/// <returns>saves the data to the database, sends an email and reloads the page.</returns>
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public ActionResult Register(RegisterUserViewModel registerUser)
{
var recaptcha = new ReCaptcha();
var responseFromServer = recaptcha.OnActionExecuting();
if (responseFromServer.StartsWith("true", StringComparison.Ordinal))
{
if (registerUser != null && ModelState.IsValid)
{
var userByUsername = DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", registerUser.Account.UserName }
}).ToList();
var userByEmail = DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.Email", registerUser.Account.Email }
}).ToList();
if (userByUsername.Count == 0)
{
if (userByEmail.Count == 0)
{
var passwordEncryption = new PasswordHashAndSalt();
registerUser.Id = Guid.NewGuid().ToString();
registerUser.Account.Password = passwordEncryption.getHashedPassword(registerUser.Account.Password);
registerUser.Account.ConfirmPassword = passwordEncryption.getHashedPassword(registerUser.Account.ConfirmPassword);
registerUser.Account.ImageId = "586a7d67cf43d7340cb54670";
var tradingDetails = new LetsTradingDetails { Id = registerUser.Id, Credit = 100 };
DatabaseContext.RegisteredUsers.InsertOne(registerUser);
DatabaseContext.LetsTradingDetails.InsertOne(tradingDetails);
using (var mail = new MailMessage())
{
mail.To.Add(registerUser.Account.Email);
mail.Subject = "Welcome to Royal Holloway LETS";
mail.Body = "<p>Hello " + registerUser.About.FirstName + ",</p><h3>Thanks for joining Royal Holloway LETS</h3><p>Please find your account details below</p><p>Title : <b>" + registerUser.About.Title + "</b></p><p>First Name : <b>" + registerUser.About.FirstName + "</b></p><p>Last Name : <b>" + registerUser.About.LastName + "</b></p><p>Gender : <b>" + registerUser.About.Gender + "</b></p><p>User Name : <b>" + registerUser.Account.UserName + "</b></p><p>Kind Regards,<br/>Royal Holloway LETS</p>";
SendEmail(mail);
TempData.Add("Registered", "You have successfully signed up for Royal Holloway LETS, We have also sent you can email with your account details for your future reference.");
}
return RedirectToAction("Login");
}
else
{
registerUser.Account.Password = null;
registerUser.Account.ConfirmPassword = null;
ModelState.AddModelError("Account.Email", "Sorry, The following email already exists in our system.");
return View(registerUser);
}
}
else
{
registerUser.Account.Password = null;
registerUser.Account.ConfirmPassword = null;
ModelState.AddModelError("Account.UserName", "Sorry, This username is not available.");
if (userByEmail.Count > 0)
{
ModelState.AddModelError("Account.Email", "Sorry, The following email already exists in our system.");
}
return View(registerUser);
}
}
}
else
{
registerUser.Account.Password = null;
registerUser.Account.ConfirmPassword = null;
ModelState.AddModelError("ReCaptcha", "Incorrect CAPTCHA entered.");
return View(registerUser);
}
return View();
}
/// <summary>
/// Checks if a username is present in the database or not
/// </summary>
/// <param name="userName">represents the username entered by the user</param>
/// <returns>returns true or false depending on if the username is present in the database or not</returns>
[AllowAnonymous]
public bool CheckUserName(string userName)
{
var userByUsername = DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", userName }
}).ToList();
return userByUsername.Count == 0;
}
/// <summary>
/// Get Method for the ForgotUsername page.
/// </summary>
/// <returns>returns the forgot username page if the user is not authenticated else takes the user to the index page.</returns>
[AllowAnonymous]
[HttpGet]
public ActionResult ForgotUsername()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
}
/// <summary>
/// Post method for the forgot username
/// </summary>
/// <param name="forgotUsername">Holds the details entered by the user on the forgot username page.</param>
/// <returns>sends an email to the user and returns the user to the login page.</returns>
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotUsername(ForgotUsernameViewModel forgotUsername)
{
var recaptcha = new ReCaptcha();
var responseFromServer = recaptcha.OnActionExecuting();
if (responseFromServer.StartsWith("true", StringComparison.Ordinal))
{
if (forgotUsername != null && ModelState.IsValid)
{
var userByEmail = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.Email", forgotUsername.Email }
}).ToListAsync();
if (userByEmail.Count > 0)
{
using (var mail = new MailMessage())
{
mail.To.Add(forgotUsername.Email);
mail.Subject = "Royal Holloway LETS Username Recovery";
mail.Body = "<p>Hello " + userByEmail[0].About.FirstName + ",</p><h3>Forgotten your username?</h3><p>We got a request about your Royal Holloway LETS account's username.<br/>Please find your username highlighted in bold below.<br/></p><h2>" + userByEmail[0].Account.UserName + "</h2><p>All the best,<br/>Royal Holloway LETS</p>";
SendEmail(mail);
ModelState.AddModelError("Success", "Please check you email, We have sent you your username.");
forgotUsername.Email = null;
}
}
else
{
ModelState.AddModelError("Email", "Sorry, The Email you provided is not present in our system.");
return View(forgotUsername);
}
}
}
else
{
ModelState.AddModelError("ReCaptcha", "Incorrect CAPTCHA entered.");
return View(forgotUsername);
}
return View();
}
/// <summary>
/// Get method for the forgotpassword page
/// </summary>
/// <returns>returns the forgotpassword if the user is not authenticated else takes the user to the index page.</returns>
[AllowAnonymous]
[HttpGet]
public ActionResult ForgotPassword()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
else
{
return View();
}
}
/// <summary>
/// Post method for the forgotpassword page
/// </summary>
/// <param name="forgotPassword">Stores the data entered by the user on the page</param>
/// <returns>sends an email to the user and takes the user to the login page.</returns>
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel forgotPassword)
{
var recaptcha = new ReCaptcha();
var responseFromServer = recaptcha.OnActionExecuting();
if (responseFromServer.StartsWith("true", StringComparison.Ordinal))
{
if (forgotPassword != null && ModelState.IsValid)
{
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", forgotPassword.UserName }
}).ToListAsync();
if (userByUsername.Count > 0)
{
if (userByUsername[0].Account.Email.Equals(forgotPassword.Email))
{
var password = CreatePassword();
var passwordEncryption = new PasswordHashAndSalt();
var tempEncryptedPassword = passwordEncryption.getHashedPassword(password);
userByUsername[0].Account.TempPassword = tempEncryptedPassword;
await DatabaseContext.RegisteredUsers.ReplaceOneAsync(r => r.Account.UserName == userByUsername[0].Account.UserName, userByUsername[0]);
using (var mail = new MailMessage())
{
mail.To.Add(forgotPassword.Email);
mail.Subject = "Royal Holloway LETS Password Recovery";
mail.Body = "<p>Hello " + userByUsername[0].About.FirstName + ",</p><h3>Forgotten your password?</h3><p>We got a request to reset your Royal Holloway LETS account's password.<br/>You use the below code in bold to login to your account.<br/><b>Please change your password to something memorable when you have logged in.</b></p><h2>" + password + "</h2><p>All the best,<br/>Royal Holloway LETS</p>";
SendEmail(mail);
ModelState.AddModelError("Success", "Please check you email, We have sent you your recovery password to your account.");
forgotPassword.UserName = null;
forgotPassword.Email = null;
}
}
else
{
ModelState.AddModelError("Email", "Sorry, The Email you provided is not associated with the username you entered.");
return View(forgotPassword);
}
}
else
{
ModelState.AddModelError("UserName", "Sorry, We didn't find any account associated with this username in our system.");
}
}
}
else
{
ModelState.AddModelError("ReCaptcha", "Incorrect CAPTCHA entered.");
return View(forgotPassword);
}
return View();
}
/// <summary>
/// Creates a random password when the user clicks and submit forgot password.
/// </summary>
/// <returns>returns a random string as a password.</returns>
public string CreatePassword()
{
var randomPassword = RandomCharacter;
return randomPassword;
}
public string RandomCharacter
{
get
{
const string valid = "abcdFGHIJKLefghijklm678STUVW90nopqrstBCDEMNOuvwxyz12345APQRXYZ";
return new string(Enumerable.Repeat(valid, 16).Select(s => s[Random.Next(s.Length)]).ToArray());
}
}
/// <summary>
/// Get method for the RegisteredUsers Page.
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorize(Roles = "admin")]
public ActionResult RegisteredUsers()
{
var registeredUsers = DatabaseContext.RegisteredUsers.Find(new BsonDocument()).ToList();
return View(registeredUsers);
}
/// <summary>
/// Get method for the UserProfile page.
/// </summary>
/// <returns>returns the user profile page is the user is authenticated.</returns>
[HttpGet]
public async Task<ActionResult> UserProfile()
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", username }
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument {
{ "_id", userByUsername[0].Id }
}).ToListAsync();
var letsUser = new LetsUser
{
UserPersonalDetails = userByUsername[0],
UserTradingDetails = userTradingDetails[0]
};
return View(letsUser);
}
/// <summary>
/// Sends an email to the email address provided
/// </summary>
/// <param name="mail">Contains the data of the email like the body and the mailTo: address</param>
public void SendEmail(MailMessage mail)
{
mail.From = new MailAddress("rhulletsteam@gmail.com");
mail.IsBodyHtml = true;
using (var smtp = new SmtpClient("smtp.gmail.com", 587))
{
var email = AppSettings.GetValues("RHLETS.Email").FirstOrDefault();
var password = AppSettings.GetValues("RHLETS.Password").FirstOrDefault();
smtp.Credentials = new NetworkCredential(email, password);
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
/// <summary>
/// Post method for the account settings partial
/// </summary>
/// <param name="registeredUser">stores the data entered by the user on the account settings partial</param>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AccountSettingsEdit(RegisterUserViewModel registeredUser)
{
var userName = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", userName }
}).ToListAsync();
var userByEmail = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.Email", registeredUser.Account.Email }
}).ToListAsync();
registeredUser.Id = userByUsername[0].Id;
registeredUser.Account.UserName = userByUsername[0].Account.UserName;
registeredUser.Account.ImageId = userByUsername[0].Account.ImageId;
registeredUser.Account.Password = userByUsername[0].Account.Password;
registeredUser.Account.ConfirmPassword = userByUsername[0].Account.Password;
ModelState.Clear();
TryValidateModel(registeredUser);
if (ModelState.IsValid)
{
if (userByEmail.Count <= 1)
{
await DatabaseContext.RegisteredUsers.ReplaceOneAsync(r => r.Account.UserName == registeredUser.Account.UserName, registeredUser);
}
}
return RedirectToAction("UserProfile", "Account");
}
/// <summary>
/// Get Method for the account settings partial
/// </summary>
/// <returns>returns the account settings partial when the user clicks edit on the user profile page.</returns>
public async Task<ActionResult> GetAccountSettingsPartial()
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", username }
}).ToListAsync();
return View("AccountSettingsEdit", userByUsername[0]);
}
/// <summary>
/// Get method for the Add skills partial
/// </summary>
/// <returns>returns the add skills partial when the user clicks edit/add skills button.</returns>
public async Task<ActionResult> GetAddSkillsPartial()
{
if (User != null)
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"Account.UserName", username}
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userByUsername[0].Id}
}).ToListAsync();
return View("AddSkills", userTradingDetails[0]);
}
return null;
}
/// <summary>
/// Post method for the skills edit partial
/// </summary>
/// <param name="letsTradingDetails">stores the skills entered by the user.</param>
/// <returns>reloads the user profile page.</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SkillsSettingsEdit(LetsTradingDetails letsTradingDetails)
{
await AddSkill(letsTradingDetails.Skill);
return RedirectToAction("UserProfile", "Account");
}
/// <summary>
/// Adds the skill to the user profile
/// </summary>
/// <param name="skill">stores the skill entered by the user</param>
/// <returns>adds the skill and returns the skills partial</returns>
public async Task<ActionResult> AddSkill(string skill)
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", username }
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument {
{ "_id", userByUsername[0].Id }
}).ToListAsync();
if (userTradingDetails[0].Skills == null || userTradingDetails[0].Skills.Count == 0)
{
userTradingDetails[0].Skills = new List<string>();
}
if (!string.IsNullOrEmpty(skill) && !userTradingDetails[0].Skills.Contains(skill))
{
userTradingDetails[0].Skills.Add(skill);
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == userTradingDetails[0].Id, userTradingDetails[0]);
}
return View("AddedUserSkills", userTradingDetails[0]);
}
/// <summary>
/// Removes the user skills from the user profile
/// </summary>
/// <param name="skill">stores the skill that needs to be removed from the user profile</param>
/// <returns>removes the user skill and returns the skills partial</returns>
public async Task<ActionResult> RemoveSkill(string skill)
{
if (User != null)
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", username }
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument {
{ "_id", userByUsername[0].Id }
}).ToListAsync();
userTradingDetails[0].Skills.Remove(skill);
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == userTradingDetails[0].Id, userTradingDetails[0]);
}
return null;
}
/// <summary>
/// Allows the user to change their account passwords
/// </summary>
/// <param name="registeredUser">stores the users old password, new password and confirm password</param>
/// <returns>verifies and changes the password and reloads the user profile page with an notification message.</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(RegisterUserViewModel registeredUser)
{
if (User != null)
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"Account.UserName", username}
}).ToListAsync();
var passwordEncryption = new PasswordHashAndSalt();
var oldPassword = passwordEncryption.getHashedPassword(registeredUser.Account.OldPassword);
var newPassword = passwordEncryption.getHashedPassword(registeredUser.Account.NewPassword);
var confirmNewPassword = passwordEncryption.getHashedPassword(registeredUser.Account.ConfirmNewPassword);
if (userByUsername != null && userByUsername.Count > 0 && newPassword.Equals(confirmNewPassword))
{
if (userByUsername[0].Account.Password.Equals(oldPassword) ||
(!string.IsNullOrEmpty(userByUsername[0].Account.TempPassword) &&
userByUsername[0].Account.TempPassword.Equals(oldPassword)))
{
userByUsername[0].Account.Password = newPassword;
userByUsername[0].Account.TempPassword = null;
await DatabaseContext.RegisteredUsers.ReplaceOneAsync(r => r.Account.UserName == userByUsername[0].Account.UserName, userByUsername[0]);
TempData.Add("PasswordChanged", "Your Password was changed successfully.");
}
else
{
TempData.Add("PasswordNotChanged", "There was an error in changing you password. Please try again.");
}
}
}
else
{
TempData.Add("PasswordNotChanged", "There was an error in changing you password. Please try again.");
}
return RedirectToAction("UserProfile", "Account");
}
[HttpPost]
public async Task<ActionResult> ChangeProfilePicture()
{
var numberOfDocuments = (Request.Files.Count / 2);
for (var i = 0; i < numberOfDocuments; i++)
{
var file = Request.Files[i];
if (!string.IsNullOrEmpty(file?.FileName) && file.ContentType.Equals("image/jpeg"))
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", username }
}).ToListAsync();
if (userByUsername[0].Account.ImageId != null && !userByUsername[0].Account.ImageId.Equals("586a7d67cf43d7340cb54670"))
{
await DeleteImage(userByUsername[0].Account.ImageId);
}
var options = new GridFSUploadOptions
{
Metadata = new BsonDocument("contentType", file.ContentType)
};
var imageId = await DatabaseContext.ProfilePicturesBucket.UploadFromStreamAsync(file.FileName, file.InputStream, options);
userByUsername[0].Account.ImageId = imageId.ToString();
await DatabaseContext.RegisteredUsers.ReplaceOneAsync(r => r.Account.UserName == userByUsername[0].Account.UserName, userByUsername[0]);
}
}
return RedirectToAction("UserProfile", "Account");
}
public async Task<ActionResult> GetProfilePicture()
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", username }
}).ToListAsync();
try
{
var imageId = userByUsername[0].Account.ImageId;
var stream = await DatabaseContext.ProfilePicturesBucket.OpenDownloadStreamAsync(new ObjectId(imageId));
var contentType = stream.FileInfo.Metadata["contentType"].AsString;
return File(stream, contentType);
}
catch (GridFSFileNotFoundException)
{
return HttpNotFound();
}
}
public async Task DeleteImage(string imageId)
{
await DatabaseContext.ProfilePicturesBucket.DeleteAsync(new ObjectId(imageId));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> PostRequest(string title, string description, int budget, string tags)
{
var username = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument {
{ "Account.UserName", username }
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument {
{ "_id", userByUsername[0].Id }
}).ToListAsync();
if (userTradingDetails[0].Credit > 0)
{
userTradingDetails[0].Request = new RequestPost();
if (userTradingDetails[0].Requests == null)
{
userTradingDetails[0].Requests = new List<RequestPost>();
}
userTradingDetails[0].Request.Id = userTradingDetails[0].Requests.Count();
userTradingDetails[0].Request.HasDeleted = false;
userTradingDetails[0].Request.HasCompleted = false;
userTradingDetails[0].Request.JobCompleted = false;
userTradingDetails[0].Request.Date = DateTime.Now;
userTradingDetails[0].Request.Description = description;
userTradingDetails[0].Request.Title = title;
userTradingDetails[0].Request.Budget = budget;
var tagArray = tags.Split(',');
var tagList = new List<string>(tagArray.Length);
tagList.AddRange(tagArray);
tagList.Reverse();
userTradingDetails[0].Request.Tags = tagList;
userTradingDetails[0].Requests.Add(userTradingDetails[0].Request);
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == userTradingDetails[0].Id, userTradingDetails[0]);
var letsUser = new LetsUser
{
UserPersonalDetails = userByUsername[0],
UserTradingDetails = userTradingDetails[0]
};
return View("NewPostedRequest", letsUser);
}
else
{
return null;
}
}
[HttpPost]
public async Task<ActionResult> ExpandPost(string username, int postId)
{
var user = username;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"Account.UserName", user}
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userByUsername[0].Id}
}).ToListAsync();
return View("ExpandedRequest", userTradingDetails[0].Requests.ElementAt(postId));
}
[HttpPost]
public async Task<bool> AcceptUserBid(string username, int postId)
{
var user = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"Account.UserName", user}
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userByUsername[0].Id}
}).ToListAsync();
var post = userTradingDetails[0].Requests.ElementAt(postId);
post.IsAssignedTo = username;
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == userTradingDetails[0].Id, userTradingDetails[0]);
return true;
}
[HttpGet]
public async Task<JsonResult> GetUserSkills(string skill)
{
var filter = new BsonDocument { { "Skill", new BsonDocument { { "$regex", ".*" + skill + ".*" }, { "$options", "i" } } } };
var userSkills = await DatabaseContext.LetsSkillsDatabase.Find(filter).Limit(15).ToListAsync();
var userSkillList = userSkills.Select(m => m.Skill).ToList();
return Json(userSkillList.ToArray(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public async Task<ActionResult> GetUserJobs()
{
var userName = User.Identity.Name;
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument {
{ "Requests", new BsonDocument { { "$elemMatch", new BsonDocument { { "IsAssignedTo", userName } } } } }
}).ToListAsync();
return View("UserJobs", userTradingDetails);
}
[HttpPost]
public async Task<ActionResult> ExpandYourJob(string userId, string postId)
{
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"_id", userId}
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userByUsername[0].Id}
}).ToListAsync();
var post = userTradingDetails[0].Requests.ElementAt(Convert.ToInt32(postId));
post.OwnerId = userId;
return View("ExpandedYourJob", post);
}
[HttpPost]
public async Task<bool> MarkJobCompleted(string userId, string postId)
{
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"_id", userId}
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userByUsername[0].Id}
}).ToListAsync();
var post = userTradingDetails[0].Requests.ElementAt(Convert.ToInt32(postId));
post.JobCompleted = true;
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == userTradingDetails[0].Id, userTradingDetails[0]);
return true;
}
[HttpPost]
public async Task ArchiveJob(int postId)
{
var user = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"Account.UserName", user}
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userByUsername[0].Id}
}).ToListAsync();
var isAssignedTo = userTradingDetails[0].Requests[postId].IsAssignedTo;
userTradingDetails[0].Requests[postId].HasCompleted = true;
var credit = userTradingDetails[0].Requests[postId].Bids.Find(item => item.Username.Equals(isAssignedTo)).Amount;
userTradingDetails[0].Credit = userTradingDetails[0].Credit - credit;
var userbyAssignedTo = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"Account.UserName", isAssignedTo}
}).ToListAsync();
var isAssignedToTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userbyAssignedTo[0].Id}
}).ToListAsync();
isAssignedToTradingDetails[0].Credit = isAssignedToTradingDetails[0].Credit + credit;
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == userTradingDetails[0].Id, userTradingDetails[0]);
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == isAssignedToTradingDetails[0].Id, isAssignedToTradingDetails[0]);
}
[HttpPost]
public async Task<bool> DeleteRequest(int postId)
{
var user = User.Identity.Name;
var userByUsername = await DatabaseContext.RegisteredUsers.Find(new BsonDocument
{
{"Account.UserName", user}
}).ToListAsync();
var userTradingDetails = await DatabaseContext.LetsTradingDetails.Find(new BsonDocument
{
{"_id", userByUsername[0].Id}
}).ToListAsync();
if (string.IsNullOrEmpty(userTradingDetails[0].Requests[postId].IsAssignedTo))
{
userTradingDetails[0].Requests[postId].HasDeleted = true;
await DatabaseContext.LetsTradingDetails.ReplaceOneAsync(r => r.Id == userTradingDetails[0].Id, userTradingDetails[0]);
}
return (string.IsNullOrEmpty(userTradingDetails[0].Requests[postId].IsAssignedTo));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Team3ADProject.Model;
using Team3ADProject.Code;
using System.Web.Security;
namespace Team3ADProject
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/*
* Sets up session variable based on the user that logged in.
*
* Note: The method only runs if the user is successfully logged in
*/
protected void Login1_LoggedIn(object sender, EventArgs e)
{
// Setup the session variables
Session["username"] = Login1.UserName.ToString();
employee emp = BusinessLogic.GetEmployeeByUserID((string)Session["username"]);
Session["Name"] = emp.employee_name;
Session["Employee"] = emp.employee_id;
Session["Department"] = emp.department_id.Trim();
Session["role"] = Roles.GetRolesForUser((string)Session["username"]).FirstOrDefault();
department dep = BusinessLogic.GetDepartmenthead((string)Session["Department"]);
Session["Head_id"] = dep.head_id;
Session["supervisor_id"] = emp.supervisor_id;
// Redirect users to their dashboard
Response.Redirect(ResolveUrl("~/Protected/Dashboard"));
}
}
} |
using System.Collections;
using UnityEngine;
public class MyCoroutine : MonoBehaviour
{
private bool isRunning = false;
private WaitForFrames myCo = null;
// Use this for initialization
void Start()
{
StartCoroutine(RunInFrames(3));
this.isRunning = true;
}
// Update is called once per frame
void Update()
{
myCo.IncreaseFrame();
if (isRunning)
{
Debug.Log("MyCoroutine is Running Now");
}
}
// FixedUpdate ==> yield WaitForFixedUpdate ==> Update ==> Other Yield ==> LateUpdate ==> yield WaitForEndOfFrame
// Now: Start==>Update==>keepWaiting
private IEnumerator RunInFrames(int num)
{
myCo = new WaitForFrames(num);
yield return myCo;
this.isRunning = false;
Debug.Log("End of MyCoroutine");
}
}
public class WaitForFrames : CustomYieldInstruction
{
private int frames = 0;
private int currFrames = 0;
public WaitForFrames(int num)
{
frames = num;
}
public void IncreaseFrame()
{
currFrames++;
}
public override bool keepWaiting
{
get
{
Debug.Log("Access keepWaiting Now:" + currFrames);
return currFrames < frames;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Business.Helper;
using eIVOGo.Helper;
using eIVOGo.Models.ViewModel;
using Model.Models.ViewModel;
using eIVOGo.Properties;
using Model.DataEntity;
using Model.DocumentManagement;
using Model.Helper;
using Model.InvoiceManagement;
using Model.Locale;
using Model.Schema.EIVO.B2B;
using Model.Schema.TurnKey;
using Model.Schema.TXN;
using Model.Security.MembershipManagement;
using Utility;
using Uxnet.Com.Security.UseCrypto;
using Newtonsoft.Json;
using System.Data;
using ModelExtension.Helper;
using Uxnet.Com.DataAccessLayer;
using DataAccessLayer.basis;
namespace eIVOGo.Controllers.SAM
{
public class SystemExceptionLogController : SampleController<InvoiceItem>
{
// GET: SystemExceptionLog
public ActionResult Index()
{
return View();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
[Header("Stats")]
public float moveSpeed;
public int curHp;
public int maxHp;
public int xpToGive;
[Header("Target")]
public float chaseRange;
public float attackRange;
Player player;
[Header("Attack")]
public int damage;
public float attackRate;
float lastAttackTime;
//components
Rigidbody2D rgb;
private void Awake()
{
rgb = this.GetComponent<Rigidbody2D>();
player = FindObjectOfType<Player>();
}
// Update is called once per frame
void Update()
{
float playerDist = Vector2.Distance(transform.position, player.transform.position);
if (playerDist <= attackRange)
{
if (Time.time - lastAttackTime >= attackRate)
{
Attack();
}
}
else if (playerDist <= chaseRange)
{
Chase();
}
else
{
rgb.velocity = Vector2.zero;
}
}
void Chase()
{
Vector2 dir = (player.transform.position - transform.position).normalized;
rgb.velocity = dir * moveSpeed;
}
void Attack()
{
lastAttackTime = Time.time;
player.TakeDamage(damage);
}
public void TakeDamage(int damageTaken)
{
curHp -= damageTaken;
if (curHp <= 0)
{
Die();
}
}
void Die()
{
player.AddXP(xpToGive);
Destroy(this.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Business.Helper;
using ClosedXML.Excel;
using DataAccessLayer.basis;
using eIVOGo.Helper;
using eIVOGo.Models;
using eIVOGo.Models.ViewModel;
using Model.Models.ViewModel;
using Model.DataEntity;
using Model.InvoiceManagement;
using Model.Locale;
using Model.Helper;
using Model.Resource;
using Model.Security.MembershipManagement;
using Utility;
using Model.InvoiceManagement.InvoiceProcess;
using Uxnet.Com.DataAccessLayer;
using ModelExtension.Helper;
using Newtonsoft.Json;
using eIVOGo.Helper.Security.Authorization;
namespace eIVOGo.Controllers.Merchandise
{
[Authorize]
public class ProductCatalogController : SampleController<InvoiceItem>
{
// GET: ProductCatalog
[RoleAuthorize(RoleID = new Naming.RoleID[] { Naming.RoleID.ROLE_SYS, Naming.RoleID.ROLE_SELLER })]
public ActionResult QueryIndex(ProductCatalogQueryViewModel viewModel)
{
ViewBag.ViewModel = viewModel;
return View("~/Views/ProductCatalog/Module/ProductCatalogQuery.cshtml");
}
public ActionResult InquireProduct(ProductCatalogQueryViewModel viewModel)
{
ViewBag.ViewModel = viewModel;
var profile = HttpContext.GetUser();
if (viewModel.KeyID != null)
{
viewModel.ProductID = viewModel.DecryptKeyValue();
}
IQueryable<ProductCatalog> items = models.GetDataContext().FilterProductCatalogByRole(profile, models.GetTable<ProductCatalog>());
if(viewModel.SupplierID.HasValue)
{
items = items.Where(p => p.ProductSupplier.Any(s => s.SupplierID == viewModel.SupplierID));
}
if (viewModel.ProductID.HasValue)
{
items = items.Where(p => p.ProductID == viewModel.ProductID);
}
viewModel.ProductName = viewModel.ProductName.GetEfficientString();
if (viewModel.ProductName != null && viewModel.ProductName != "*")
{
items = items.Where(p => p.ProductName.Contains(viewModel.ProductName));
}
viewModel.Barcode = viewModel.Barcode.GetEfficientString();
if (viewModel.Barcode != null)
{
items = items.Where(p => p.Barcode == viewModel.Barcode);
}
viewModel.Spec = viewModel.Spec.GetEfficientString();
if (viewModel.Spec != null)
{
items = items.Where(p => p.Spec.Contains(viewModel.Spec));
}
viewModel.RecordCount = items.Count();
ViewBag.CreateNew = new ProductCatalog { };
if (viewModel.PageIndex.HasValue)
{
viewModel.PageIndex--;
return View("~/Views/ProductCatalog/Module/ProductCatalogTable.cshtml", items);
}
else
{
viewModel.ResultView = "~/Views/ProductCatalog/Module/ProductCatalogTable.cshtml";
return View("~/Views/Common/Module/QueryResult.cshtml", items);
}
}
public ActionResult ProcessDataItem(ProductCatalogQueryViewModel viewModel)
{
ViewResult result = (ViewResult)InquireProduct(viewModel);
result.ViewName = "~/Views/ProductCatalog/Module/ProductCatalogTable.cshtml";
if (viewModel.DisplayType == Naming.FieldDisplayType.DataItem)
{
IQueryable<ProductCatalog> items = (IQueryable<ProductCatalog>)result.Model;
if (items.Count() == 0)
{
viewModel.DisplayType = Naming.FieldDisplayType.Create;
}
}
ViewBag.DisplayType = viewModel.DisplayType;
return result;
}
public ActionResult CommitItem(ProductCatalogQueryViewModel viewModel)
{
UserProfileMember profile = HttpContext.GetUser();
ViewBag.ViewModel = viewModel;
if (viewModel.KeyID != null)
{
viewModel.ProductID = viewModel.DecryptKeyValue();
}
viewModel.ProductName = viewModel.ProductName.GetEfficientString();
if (viewModel.ProductName == null)
{
ModelState.AddModelError("ProductName", "請輸入品名");
}
viewModel.Barcode = viewModel.Barcode.GetEfficientString();
viewModel.Spec = viewModel.Spec.GetEfficientString();
viewModel.Remark = viewModel.Remark.GetEfficientString();
viewModel.PieceUnit = viewModel.PieceUnit.GetEfficientString();
if (!viewModel.SalePrice.HasValue)
{
ModelState.AddModelError("SalePrice", "請輸入單價");
}
if (!viewModel.SupplierID.HasValue)
{
ModelState.AddModelError("SupplierID", "請選擇營業人");
}
if (!ModelState.IsValid)
{
ViewBag.ModelState = ModelState;
return View("~/Views/Shared/ReportInputError.cshtml");
}
ProductCatalog item = models.GetDataContext().FilterProductCatalogByRole(profile, models.GetTable<ProductCatalog>())
.Where(p => p.ProductID == viewModel.ProductID)
.FirstOrDefault();
bool isNew = false;
if (item == null)
{
isNew = true;
item = new ProductCatalog
{
};
item.ProductSupplier.Add(new ProductSupplier
{
SupplierID = viewModel.SupplierID.Value
});
models.GetTable<ProductCatalog>().InsertOnSubmit(item);
}
item.Barcode = viewModel.Barcode;
item.ProductName = viewModel.ProductName;
item.SalePrice = viewModel.SalePrice.Value;
item.Spec = viewModel.Spec;
item.Remark = viewModel.Remark;
item.PieceUnit = viewModel.PieceUnit;
models.SubmitChanges();
return Json(new { result = true, item.ProductID, keyID = item.ProductID.EncryptKey(), isNew }, JsonRequestBehavior.AllowGet);
}
public ActionResult DeleteItem(ProductCatalogQueryViewModel viewModel)
{
UserProfileMember profile = HttpContext.GetUser();
ViewBag.ViewModel = viewModel;
if (viewModel.KeyID != null)
{
viewModel.ProductID = viewModel.DecryptKeyValue();
}
ProductCatalog item = models.GetDataContext().FilterProductCatalogByRole(profile, models.GetTable<ProductCatalog>())
.Where(p => p.ProductID == viewModel.ProductID)
.FirstOrDefault();
if (item == null)
{
return Json(new { result = false, message = "資料錯誤" }, JsonRequestBehavior.AllowGet);
}
models.GetTable<ProductCatalog>().DeleteOnSubmit(item);
models.SubmitChanges();
return Json(new { result = true }, JsonRequestBehavior.AllowGet);
}
public ActionResult QuickSearch(ProductCatalogQueryViewModel viewModel)
{
ViewResult result = (ViewResult)InquireProduct(viewModel);
IQueryable<ProductCatalog> items = (IQueryable<ProductCatalog>)result.Model;
return Content(JsonConvert.SerializeObject(items.ToArray()), "application/json");
}
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
namespace ITQJ.Domain.DTOs
{
public class BaseDTO
{
[Required]
[NotNull]
public Guid Value { get; set; }
}
}
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Karkas.Ornek.BsWrapper.Ornekler;
using Karkas.Web.Helpers.BaseClasses;
public partial class Ornekler_OrnekGridToExcelVeWord : KarkasBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonExcelDataTable1_Click(object sender, EventArgs e)
{
DataTable dt = new MusteriBsWrapper().SorgulaHepsiniGetirDataTable();
dt.Columns["Adi"].Caption = "Adı";
dt.Columns["Soyadi"].Caption = "Soyadı";
this.ExportHelper.ToExcel(dt);
}
protected void ButtonExcelDataTable2_Click(object sender, EventArgs e)
{
this.ExportHelper.ToExcel(new MusteriBsWrapper().SorgulaHepsiniGetirDataTable(), "Musteri");
}
protected void ButtonExcelDataTable3_Click(object sender, EventArgs e)
{
DataTable dt = new MusteriBsWrapper().SorgulaHepsiniGetirDataTable();
dt.Columns["Adi"].Caption = "Adı";
dt.Columns["Soyadi"].Caption = "Soyadı";
this.ExportHelper.ToExcel(dt, "Musteri",true);
}
protected void ButtonExcelDataTable4_Click(object sender, EventArgs e)
{
DataTable dt = new MusteriBsWrapper().SorgulaHepsiniGetirDataTable();
dt.Columns.Remove(dt.Columns["MusteriKey"]);
dt.Columns["Adi"].Caption = "Adı";
dt.Columns["Soyadi"].Caption = "Soyadı";
this.ExportHelper.ToExcel(dt, "Musteri", true);
}
protected void ButtonExcelDataView1_Click(object sender, EventArgs e)
{
DataTable dt = new MusteriBsWrapper().SorgulaHepsiniGetirDataTable();
DataView dv = new DataView(dt, "Adi LIKE 'a%'", "Adi ASC",DataViewRowState.OriginalRows);
this.ExportHelper.ToExcel(dv);
}
protected void ButtonExcelDataView2_Click(object sender, EventArgs e)
{
DataTable dt = new MusteriBsWrapper().SorgulaHepsiniGetirDataTable();
DataView dv = new DataView(dt, "Adi LIKE 'a%'", "Adi ASC", DataViewRowState.OriginalRows);
this.ExportHelper.ToExcel(dv,"Musteri");
}
protected void ButtonExcelDataView3_Click(object sender, EventArgs e)
{
DataTable dt = new MusteriBsWrapper().SorgulaHepsiniGetirDataTable();
dt.Columns["Adi"].Caption = "Adı";
dt.Columns["Soyadi"].Caption = "Soyadı";
DataView dv = new DataView(dt, "Adi LIKE 'a%'", "Adi ASC", DataViewRowState.OriginalRows);
this.ExportHelper.ToExcel(dv, "Musteri",false);
}
}
|
namespace HseClass.Api.ViewModels
{
public class TaskLabForm
{
public string CorrectSolution { get; set; }
public string Description { get; set; }
public string Equipment { get; set; }
public string LinkToManual { get; set; }
public string Name { get; set; }
public string Theme { get; set; }
public string RecommendedClass { get; set; }
}
} |
// ----------------------------------------------------------------------------
// <copyright file="CatalogInitializer.cs" company="NanoTaboada">
// Copyright (c) 2013 Nano Taboada, http://openid.nanotaboada.com.ar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// ----------------------------------------------------------------------------
[module: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "For educational purposes only.")]
namespace Dotnet.Samples.WebApi.Models
{
using System;
using System.Collections.Generic;
using Dotnet.Samples.WebApi.Models;
public static class CatalogInitializer
{
public static List<Book> Seed()
{
var books = new List<Book>();
books.Add(
new Book()
{
Isbn = "9781430242338",
Title = "Pro C# 5.0 and the .NET 4.5 Framework",
Author = "Andrew Troelsen",
Publisher = "Apress",
Published = new DateTime(2012, 8, 22),
Pages = 1560,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9781449320102",
Title = "C# 5.0 in a Nutshell",
Author = "Joseph Albahari, et al.",
Publisher = "O'Reilly Media",
Published = new DateTime(2012, 6, 26),
Pages = 1064,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9780672336904",
Title = "C# 5.0 Unleashed",
Author = "Bart De Smet",
Publisher = "Sams Publishing",
Published = new DateTime(2013, 5, 3),
Pages = 1700,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9781617291340",
Title = "C# in Depth, 3rd Edition",
Author = "Jon Skeet",
Publisher = "Manning Publications",
Published = new DateTime(2013, 09, 28),
Pages = 631,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9780735668010",
Title = "Microsoft Visual C# 2012 Step by Step",
Author = "John Sharp",
Publisher = "Microsoft Press",
Published = new DateTime(2013, 1, 11),
Pages = 842,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9780321877581",
Title = "Essential C# 5.0",
Author = "Mark Michaelis",
Publisher = "Addison-Wesley Professional",
Published = new DateTime(2012, 12, 7),
Pages = 1032,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9781890774721",
Title = "Murach's C# 2012",
Author = "Joel Murach, et al.",
Publisher = "Mike Murach & Associates",
Published = new DateTime(2013, 5, 6),
Pages = 842,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9780470502259",
Title = "Professional C# 2012 and .NET 4.5",
Author = "Christian Nagel, et al.",
Publisher = "Wrox",
Published = new DateTime(2012, 10, 6),
Pages = 1584,
InStock = true
});
books.Add(
new Book()
{
Isbn = "9781449320416",
Title = "Programming C# 5.0",
Author = "Ian Griffiths, et al.",
Publisher = "O'Reilly Media",
Published = new DateTime(2012, 10, 5),
Pages = 886,
InStock = true
});
return books;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace TQVaultAE.Domain.Entities;
public record ItemClassMapItem<T>(string ItemClass, T Value)
{
public string ItemClassUpper => ItemClass.ToUpper();
}
|
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.ViewModel;
using Torshify.Radio.Framework;
namespace Torshify.Radio.EightTracks.Views.Tabs
{
[Export(typeof(FavoritesViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class FavoritesViewModel : NotificationObject, IHeaderInfoProvider<HeaderInfo>
{
public FavoritesViewModel()
{
HeaderInfo = new HeaderInfo
{
Title = "Favorites"
};
}
public HeaderInfo HeaderInfo
{
get;
private set;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ENTITY;
using Openmiracle.BLL;
using Openmiracle.DAL;
using System.Data;
namespace Openmiracle.BLL
{
public class MonthlySalaryBll
{
MonthlySalaryInfo InfoMonthlySalary = new MonthlySalaryInfo();
MonthlySalarySP SPMonthlySalary = new MonthlySalarySP();
public List<DataTable> MonthlySalarySettingsEmployeeViewAll(DateTime dtSalaryMonth)
{
List<DataTable> listObj = new List<DataTable>();
try
{
SPMonthlySalary.MonthlySalarySettingsEmployeeViewAll(dtSalaryMonth);
}
catch (Exception ex)
{
MessageBox.Show("MS1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
public decimal MonthlySalarySettingsMonthlySalaryIdSearchUsingSalaryMonth(DateTime dtSalaryMonth)
{
decimal decResult = 0;
try
{
decResult = SPMonthlySalary.MonthlySalarySettingsMonthlySalaryIdSearchUsingSalaryMonth(dtSalaryMonth);
}
catch (Exception ex)
{
MessageBox.Show("Ms2:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decResult;
}
public void MonthlySalaryDeleteAll(decimal decMonthlySalaryId)
{
try
{
SPMonthlySalary.MonthlySalaryDeleteAll(decMonthlySalaryId);
}
catch (Exception ex)
{
MessageBox.Show("MS3:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public decimal MonthlySalaryAddWithIdentity(MonthlySalaryInfo monthlysalaryinfo)
{
decimal decResult = 0;
try
{
decResult = SPMonthlySalary.MonthlySalaryAddWithIdentity(monthlysalaryinfo);
}
catch (Exception ex)
{
MessageBox.Show("MS4:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decResult;
}
public void MonthlySalarySettingsEdit(MonthlySalaryInfo monthlysalaryinfo)
{
try
{
SPMonthlySalary.MonthlySalarySettingsEdit(InfoMonthlySalary);
}
catch (Exception ex)
{
MessageBox.Show("MS5:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public bool CheckSalaryAlreadyPaidOrNotForAdvancePayment(decimal decEmployeeId, DateTime date)
{
bool isPaid = false;
try
{
isPaid = SPMonthlySalary.CheckSalaryAlreadyPaidOrNotForAdvancePayment(decEmployeeId, date);
}
catch (Exception ex)
{
MessageBox.Show("MS6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return isPaid;
}
public bool CheckSalaryStatusForAdvancePayment(decimal decEmployeeId, DateTime date)
{
bool isStatus = false;
try
{
isStatus = SPMonthlySalary.CheckSalaryStatusForAdvancePayment(decEmployeeId, date);
}
catch (Exception ex)
{
MessageBox.Show("MS7:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return isStatus;
}
}
}
|
using System;
using System.Web.Mvc;
using NBTM.Repository;
namespace NBTM.Controllers
{
public class BaseController : Controller
{
#region Members
private UnitOfWork _uow;
#endregion
// Setup the UserContext for Data Inserts and Updates
protected LoggedInUserContext UserContext
{
get
{
var userName = (User != null && User.Identity.Name != null)
? User.Identity.Name
: String.Empty;
if (String.IsNullOrWhiteSpace(userName)) return null;
var ctx = new LoggedInUserContext
{
UserId = new Guid(),
UserName = User.Identity.Name
};
return ctx;
}
}
protected UnitOfWork uow
{
get { return _uow ?? (_uow = new UnitOfWork(UserContext)); }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.AppServices.DataContracts.Cashbag
{
/// <summary>
/// 转账记录
/// </summary>
public class TransferAccountsLogDto
{
/// <summary>
/// 流水号
/// </summary>
public string SerialNum { get; set; }
/// <summary>
/// 转账时间
/// </summary>
public DateTime TransferAccountsTime { get; set; }
/// <summary>
/// 转账方式
/// </summary>
public string TransferAccountsType { get; set; }
/// <summary>
/// 目标账户
/// </summary>
public string TargetAccount { get; set; }
/// <summary>
/// 收支
/// </summary>
public string InComeOrExpenses { get; set; }
/// <summary>
/// 转账金额
/// </summary>
public decimal TransferAccountsMoney { get; set; }
/// <summary>
/// 转账状态
/// </summary>
public string TransferAccountsStatus { get; set; }
/// <summary>
/// 转账类型(转入,转出)
/// </summary>
public string Type { get; set; }
/// <summary>
/// 交易号
/// </summary>
public string OutTradeNo { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoShutDowner
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{ // converting the textbox string to int
int time = Convert.ToInt32(this.textBox1.Text);
// converting sec to mins by * 60. yy is the time in minutes
int yy=time * 60;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C shutdown /s /t " + yy;
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
string q = "";
while (!process.HasExited)
{
// progressBar1.Value = 20;
q += process.StandardOutput.ReadToEnd();
}
// label1.Text = q;
// MessageBox.Show(q);
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C shutdown /a ";
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
string q = "";
while (!process.HasExited)
{
// progressBar1.Value = 20;
q += process.StandardOutput.ReadToEnd();
}
// MessageBox.Show(q);
}
private void button3_Click(object sender, EventArgs e)
{ // convertign to int
int y = Convert.ToInt32(this.textBox1.Text);
// secs >>> to mins
int x = y * 60;
MessageBox.Show("The Window will be Hidden and Your PC will be shut down after " + x + " minutes");
this.Hide();
}
}
}
|
using System;
using System.Web.Mvc;
using Logs.Authentication.Contracts;
using Logs.Services.Contracts;
using Logs.Web.Models.Entries;
using Logs.Web.Models.Logs;
namespace Logs.Web.Controllers
{
public class EntriesController : Controller
{
private readonly IEntryService entryService;
private readonly IAuthenticationProvider authenticationProvider;
public EntriesController(IEntryService entryService, IAuthenticationProvider authenticationProvider)
{
if (entryService == null)
{
throw new ArgumentNullException(nameof(entryService));
}
if (authenticationProvider == null)
{
throw new ArgumentNullException(nameof(authenticationProvider));
}
this.entryService = entryService;
this.authenticationProvider = authenticationProvider;
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult NewEntry(NewEntryViewModel model)
{
if (ModelState.IsValid)
{
var userId = this.authenticationProvider.CurrentUserId;
this.entryService.AddEntryToLog(model.Content, model.LogId, userId);
}
return this.RedirectToAction("Details", "Logs", new { id = model.LogId, page = -1 });
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult EditEntry(LogEntryViewModel model)
{
if (ModelState.IsValid)
{
var result = this.entryService.EditEntry(model.EntryId, model.Content);
model.Content = result.Content;
}
return this.PartialView("_EntryContentPartial", model);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class InspectorExtensions
{
private const float ZFightPreventionOffset = 0.01f;
[MenuItem("BolekTools/Align With Surface Below %g")]
public static void AlignWithSurfaceBelow()
{
var selectedItems = Selection.transforms;
Undo.RecordObjects(selectedItems, "AligningWithSurface");
foreach (var selectedItem in selectedItems)
{
if (Physics.Raycast(selectedItem.position, Vector3.down, out RaycastHit hit, 2))
{
selectedItem.rotation = Quaternion.FromToRotation(selectedItem.up, hit.normal) * selectedItem.rotation;
selectedItem.position = hit.point;
selectedItem.position += new Vector3(0, ZFightPreventionOffset, 0);
}
}
}
[MenuItem("BolekTools/Align With Surface Below %g", true)]
public static bool ValidateAlignWithSurfaceBelow()
{
return Selection.transforms != null && Selection.transforms.Length > 0;
}
}
|
using Bridge.Entities;
using System;
namespace Bridge
{
class Program
{
static void Main(string[] args)
{
BridgePattern bridge = new BridgePattern();
Random random = new Random();
void Sortear()
{
if (random.Next(2) == 1)
bridge.formaSolicitada = new FormaUm();
else
bridge.formaSolicitada = new FormaDois();
if (random.Next(1, 3) == 1)
bridge.formaSolicitada.ICor = new Verde();
else if (random.Next(1, 3) == 2)
bridge.formaSolicitada.ICor = new Laranja();
else if (random.Next(1, 3) == 3)
bridge.formaSolicitada.ICor = new Rosa();
}
Console.WriteLine("Pressione ENTER para enviar uma forma");
while(1 > 0)
{
ConsoleKeyInfo input = Console.ReadKey();
if (input.KeyChar == 13)
Sortear();
Console.WriteLine();
bridge.ExibeQualformaEstaDescendoNaTela();
}
}
}
}
|
using System;
namespace LV1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Note prva = new Note();
Note druga = new Note("Mr. Someone");
Note treca = new Note("Ovo je druga biljeska", "Mr. SomeoneElse", 3);
Console.WriteLine(prva.getText());
Console.WriteLine(prva.getAuthor());
Console.WriteLine(druga.getText());
Console.WriteLine(druga.getAuthor());
Console.WriteLine(treca.getText());
Console.WriteLine(treca.getAuthor());
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BgLayerHorizontalParameters : HorizontalParameters {
[SerializeField]
private GameObject[] _bgImage;
void Start () {
initiateParameters();
}
public override void UpdateParameters()
{
base.UpdateParameters();
foreach (GameObject bgImage in _bgImage)
{
bgImage.transform.position += new Vector3(VelocityX * Time.fixedDeltaTime, 0, 0);
}
}
void FixedUpdate()
{
UpdateParameters();
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Breezy.Sdk.Payloads
{
internal class PrinterListMessage
{
[JsonProperty("printers")]
public List<Printer> Printers { get; set; }
}
} |
using Discord;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WaitingListBot
{
public class Storage
{
public const string GuildDirectory = "guilds";
private ulong guildId;
static Storage()
{
Directory.CreateDirectory(GuildDirectory);
}
public Storage()
{
List = new List<UserInList>();
PlayCounter = new List<PlayCounter>();
CommandPrefix = "wl.";
DMMessageFormat = "You have been invited to play!\n Name: {0}\nPassword: {1}";
Information = new GuildInformation();
PendingInvites = new();
}
public void Save()
{
var json = JsonConvert.SerializeObject(this);
File.WriteAllText(Path.Combine(GuildDirectory, guildId + ".json"), json);
}
public static Storage LoadForGuild(ulong guildId)
{
try
{
var storage = JsonConvert.DeserializeObject<Storage>(File.ReadAllText(Path.Combine(GuildDirectory, guildId + ".json")));
if (storage == null)
{
return new Storage { guildId = guildId };
}
storage.guildId = guildId;
return storage;
}
catch (Exception)
{
return new Storage { guildId = guildId };
}
}
public GuildInformation Information { get; set; }
public ulong WaitingListChannelId { get; set; }
public List<UserInList> List { get; set; }
public IReadOnlyList<UserInListWithCounter> LastInvited { get; set; }
public List<(Guid id, UserInListWithCounter user, DateTime inviteTime, object[] arguments, bool? accepted)> PendingInvites { get; set; }
public List<PlayCounter> PlayCounter { get; set; }
public ulong SubRoleId { get; set; }
public string DMMessageFormat { get; set; }
public string CommandPrefix { get; set; }
public bool IsEnabled { get; set; }
[JsonIgnore]
public bool IsInitialized { get; set; }
public bool IsReactionMode { get; set; }
public ulong ReactionMessageId { get; set; }
public IEmote ReactionEmote { get; } = new Emoji("✅");
public bool IsPaused { get; set; } = false;
public List<UserInListWithCounter> GetSortedList()
{
var newList = new List<UserInList>(List);
newList.Sort((a, b) =>
{
if (GetPlayCounterById(a.Id) < GetPlayCounterById(b.Id))
{
return -1;
}
else if (GetPlayCounterById(a.Id) > GetPlayCounterById(b.Id))
{
return 1;
}
if (a.IsSub && !b.IsSub)
{
return -1;
}
else if (!a.IsSub && b.IsSub)
{
return 1;
}
return a.JoinTime.CompareTo(b.JoinTime);
});
return newList.Select((x) => new UserInListWithCounter(x, GetPlayCounterById(x.Id))).ToList();
}
private int GetPlayCounterById(ulong id)
{
return PlayCounter.SingleOrDefault(x => x.Id == id)?.Counter ?? 0;
}
}
public record UserInList
{
public ulong Id { get; set; }
public string? Name { get; set; }
public bool IsSub { get; set; }
public DateTime JoinTime { get; set; }
}
public record UserInListWithCounter : UserInList
{
public UserInListWithCounter()
{
}
public UserInListWithCounter(UserInList userInList, int counter) : base(userInList)
{
this.Counter = counter;
}
public int Counter { get; set; }
}
public class PlayCounter
{
public ulong Id { get; set; }
public int Counter { get; set; }
}
}
|
using System;
using System.IO;
using System.Net;
namespace SplitPdf.UpgradeChecker
{
public class UpgradeRequiredChecker
{
public DateTime GetLastChecked()
{
var path = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "GrahamDo");
if (!Directory.Exists(path))
return DateTime.MinValue;
path = Path.Combine(path, "SplitPdf");
if (!Directory.Exists(path))
return DateTime.MinValue;
var fileName = $"{path}{Path.DirectorySeparatorChar}" +
"LastUpdateCheck";
return !File.Exists(fileName) ? DateTime.MinValue : DateTime.Parse(File.ReadAllText(fileName));
}
public void SetDateLastChecked()
{
var path = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "GrahamDo");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
path = Path.Combine(path, "SplitPdf");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var fileName = $"{path}{Path.DirectorySeparatorChar}" +
"LastUpdateCheck";
File.WriteAllText(fileName,
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
public LatestVersionInfo GetLatestVersionInfoFromUrl(string url)
{
using (var client = new WebClient())
{
var rawString = client.DownloadString(url);
var elements = rawString.Split('|');
var versionElements = elements[0].Split('.');
var major = Convert.ToInt32(versionElements[0]);
var minor = Convert.ToInt32(versionElements[1]);
var build = Convert.ToInt32(versionElements[2]);
var revision = Convert.ToInt32(versionElements[3]);
return new LatestVersionInfo(major, minor, build, revision,
elements[1]);
}
}
public bool IsUpgradeRequired(int actualMajor, int actualMinor,
int actualBuild, int actualRevision,
LatestVersionInfo versionInfo)
{
if (versionInfo.VersionMajor < actualMajor)
return false;
if (versionInfo.VersionMajor > actualMajor)
return true;
if (versionInfo.VersionMajor != actualMajor)
return false;
if (versionInfo.VersionMinor < actualMinor)
return false;
if (versionInfo.VersionMinor > actualMinor)
return true;
if (versionInfo.VersionMinor != actualMinor)
return false;
if (versionInfo.VersionBuild < actualBuild)
return false;
if (versionInfo.VersionBuild > actualBuild)
return true;
if (versionInfo.VersionBuild == actualBuild)
return versionInfo.VersionRevision > actualRevision;
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CTDLGT.Stack___Queue
{
class GenericStack<T>
{
public class StackNode
{
T data; // phần dữ liệu của Node
StackNode next = null; // next trỏ đến Node tiếp theo
// Contructor Node với dữ liệu t
public StackNode()
{ }
public StackNode(T t)
{
next = null;
data = t;
}
// Định nghĩa các thuộc tính (Propeties)
public T Data
{
get { return data; }
set { data = value; }
}
public StackNode Next
{
get { return next; }
set { next = value; }
}
}
/// <summary>
/// Constructs empty stack with no elements
/// </summary>
public GenericStack()
{
top = null;
}
public GenericStack(object length)
{
this.length = length;
}
/// <summary>
/// Push new node onto the top of the stack
/// </summary>
/// <param name="value"></param>
public void push(T value)
{
var newNode = new StackNode(value);
Size++;
//if this is the first node in stack, it is also the top
if (Size == 1)
{
top = newNode;
return;
}
//else bottom is already established, only change top
newNode.Next = top;
top = newNode;
}
public T TOP()
{
return top.Data;
}
/// <summary>
/// Remove and return the top element from stack.
/// Returns Null if stack is empty
/// </summary>
/// <returns></returns>
public T pop()
{
//if there are elements to pop
if (Size > 0)
{
//get top node's value
var returnValue = top.Data;
//if more node's exist, decrement top pointer to next node in stack
//garbage collector will clean up popped node once de-referenced
if (top.Next != null)
{
top = top.Next;
}
Size--;
return returnValue;
}
else
{
return default(T);
}
}
//public T Pop()
//{
// //StackNode n;
// //n = top;
// //top = n.Next;
// //return n.Data;
// top = top.Next;
// return top.Data;
//}
/// <summary>
/// Returns value of stack's top most element without changing structure of stack
/// </summary>
/// <returns></returns>
public T peek()
{
if (Size > 0)
{
return top.Data;
}
Console.WriteLine("Error -> Unable to view top value of empty stack.");
return default(T);
}
//public void INP_STACK()
//{
// do
// {
// T x;
// Console.Write("Gia tri (nhap <=0 de ket thuc): ");
// int.TryParse(Console.ReadLine(), out x);
// if (x <= 0) break;
// push(x);
// if (!kq)
// {
// Console.WriteLine(">>Stack => full");
// break;
// }
// else
// {
// Console.WriteLine(">> Da push {0} thanh cong", x);
// }
// } while (true);
//}
/// <summary>
/// Print all elements of stack
/// </summary>
public void print()
{
Console.WriteLine("\nPrinting Stack Elments" +
"\n////////////////////\n////////TOP/////////\n////////////////////");
var current = top;
while (current != null)
{
Console.WriteLine(current.Data);
current = current.Next;
}
Console.WriteLine("////////////////////\n//////BOTTOM////////\n////////////////////");
}
/// <summary>
/// Return false if stack size is greater than 0
/// </summary>
/// <returns></returns>
public Boolean isEmpty()
{
if (Size > 0)
{
return false;
}
return true;
}
//define bottom and top of stack
//public StackNode bottom { get; set; }
public StackNode top { get; set; }
public int Size { get => size; set => size = value; }
private int size;
private object length;
}
}
|
using System.Text.Json.Serialization;
namespace PlatformRacing3.Common.Campaign;
public struct CampaignLevelRecord
{
[JsonPropertyName("timeMS")]
public int Time { get; }
[JsonPropertyName("season")]
public string Season { get; }
[JsonPropertyName("medal")]
public CampaignMedal Medal { get; }
public CampaignLevelRecord(int time, string season, CampaignMedal medal)
{
this.Time = time;
this.Season = season;
this.Medal = medal;
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace MyLINQProvider.CoreLINQ
{
// Beta Version Not all Variants Extesion Implemented !
public static class CoreLINQProvider
{
public static IEnumerable<T> CoreWhere<T>(this IEnumerable<T> Src, Func<T, bool> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
List<T> Result = new List<T>();
while (Data.MoveNext())
{
if (Dlg(Data.Current) == true)
{
Result.Add(Data.Current);
}
}
return Result.AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
public static bool CoreAll<T>(this IEnumerable<T> Src, Func<T, bool> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
while (Data.MoveNext())
{
if (Dlg(Data.Current) == false)
{
return false;
}
}
return true;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static double CoreAverage<T>(this IEnumerable<T> Src, Func<T, double> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
double result = default(double);
int Count = default(int);
while (Data.MoveNext())
{
result += Dlg(Data.Current);
Count++;
}
return (result / Count);
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<T> CoreCast<T>(this IEnumerable Src)
{
try
{
List<T> Lists = new List<T>();
IEnumerator Data = Src.GetEnumerator();
try
{
while (Data.MoveNext())
{
Lists.Add((T)Data.Current);
}
}
catch
{
return null;
}
return Lists.AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<T> CoreConcat<T>(this IEnumerable<T> Src, IEnumerable<T> Src2, Func<T, bool> Dlg)
{
try
{
List<T> GlobalResults = Src.ToList();
IEnumerator<T> Data = Src2.GetEnumerator();
while (Data.MoveNext())
{
if (Dlg(Data.Current) == true)
{
GlobalResults.Add(Data.Current);
}
}
return GlobalResults.AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
public static bool CoreContains<T>(this IEnumerable<T> Src, T Item, IEqualityComparer<T> Cmr)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
while (Data.MoveNext())
{
if (Cmr.Equals(Item, Data.Current) == true)
return true;
}
return false;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static bool CoreAny<T>(this IEnumerable<T> Src, Func<T, bool> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
while (Data.MoveNext())
{
if (Dlg(Data.Current) == true)
{
return true;
}
}
return false;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static int CoreCount<T>(this IEnumerable<T> Src, Func<T, bool> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
int Count = 0;
while (Data.MoveNext())
{
if (Dlg(Data.Current) == true)
{
Count++;
}
}
return Count;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static T CoreAggregate<T>(this IEnumerable<T> Src, System.Func<T, T, T> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
T Type = default(T);
T result = default(T);
while (Data.MoveNext())
{
Type = Data.Current;
if (result == null)
{
Data.MoveNext();
result = Dlg(Type, Data.Current);
}
else
result = Dlg(result, Data.Current);
}
return result;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<T> CoreDistinct<T>(this IEnumerable<T> Src, IEqualityComparer<T> Cmr)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
List<T> Results = new List<T>();
while (Data.MoveNext())
{
if (Results.CoreContains(Data.Current, Cmr) == false)
Results.Add(Data.Current);
}
return Results.AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<T> CoreExcept<T>(this IEnumerable<T> Src, IEnumerable<T> Src2, IEqualityComparer<T> Cmr)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
IEnumerator<T> Data2 = Src2.GetEnumerator();
List<T> Result = new List<T>();
while (Data.MoveNext())
{
if (Src2.CoreContains(Data.Current, Cmr) == false)
{
Result.Add(Data.Current);
}
}
return Result.CoreDistinct(Cmr).AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
public static T CoreElementAt<T>(this IEnumerable<T> Src, int Index)
{
try
{
List<T> DataList = Src.ToList();
return DataList[Index];
}
catch (Exception Ex)
{
throw Ex;
}
}
public static T CoreElementAtOrDefault<T>(this IEnumerable<T> Src, int Index)
{
try
{
List<T> DataList = Src.ToList();
return DataList[Index];
}
catch
{
return default(T);
}
}
public static T CoreFirst<T>(this IEnumerable<T> Src, System.Func<T, bool> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
while (Data.MoveNext())
{
if (Dlg(Data.Current) == true)
return Data.Current;
}
return default(T);
}
catch
{
return default(T);
}
}
public static IEnumerable<T> CoreIntersect<T>(this IEnumerable<T> Src, IEnumerable<T> Src2, IEqualityComparer<T> Cmr)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
IEnumerator<T> Data2 = Src2.GetEnumerator();
List<T> Results = new List<T>();
while (Data.MoveNext())
{
Data2.Reset();
while (Data2.MoveNext())
{
if (Cmr.Equals(Data.Current, Data2.Current) == true)
{
Results.Add(Data.Current);
break;
}
}
}
return Results.CoreDistinct(Cmr);
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<TResult> CoreJoin<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> Src,
IEnumerable<TInner> SrcInner,
Func<TOuter, TKey> Dlg,
Func<TInner, TKey> Dlg2,
Func<TOuter, TInner, TResult> DlgResult)
{
try
{
IEnumerator<TOuter> Data = Src.GetEnumerator();
IEnumerator<TInner> Data2 = SrcInner.GetEnumerator();
List<TResult> Results = new List<TResult>();
while (Data.MoveNext())
{
Data2.Reset();
TKey ResultData = Dlg(Data.Current);
while (Data2.MoveNext())
{
TKey ResultData2 = Dlg2(Data2.Current);
if (object.Equals(ResultData, ResultData2) == true)
{
Results.Add(DlgResult(Data.Current, Data2.Current));
}
}
}
return Results.AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
public static T CoreLast<T>(this IEnumerable<T> Src, Func<T, bool> Dlg)
{
try
{
List<T> Data = Src.ToList();
for (int i = Data.Count - 1; i >= 0; i--)
{
if (Dlg(Data[i]) == true)
return Data[i];
}
return default(T);
}
catch
{
return default(T);
}
}
public static int CoreMax<T>(this IEnumerable<T> Src, System.Func<T, int> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
int Result = default(int);
while (Data.MoveNext())
{
if (Dlg(Data.Current) > Result)
{
Result = Dlg(Data.Current);
}
}
return Result;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static double CoreMax<T>(this IEnumerable<T> Src, System.Func<T, double> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
double Result = default(double);
while (Data.MoveNext())
{
if (Dlg(Data.Current) > Result)
{
Result = Dlg(Data.Current);
}
}
return Result;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static int CoreMin<T>(this IEnumerable<T> Src, Func<T, int> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
int Result = Src.CoreMax(Dlg);
while (Data.MoveNext())
{
if (Dlg(Data.Current) <= Result)
{
Result = Dlg(Data.Current);
}
}
return Result;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static double CoreMin<T>(this IEnumerable<T> Src, Func<T, double> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
double Result = Src.CoreMax(Dlg);
while (Data.MoveNext())
{
if (Dlg(Data.Current) <= Result)
{
Result = Dlg(Data.Current);
}
}
return Result;
}
catch (Exception Ex)
{
throw Ex;
}
}
// not optimal
[Obsolete]
public static void CoreReverse<T>(this IEnumerable<T> Src)
{
try
{
List<T> Data = Src.ToList();
List<T> Results = new List<T>();
for (int i = Data.Count - 1; i >= 0; i--)
{
Results.Add(Data[i]);
}
((List<T>)Src).Clear();
for (int i = 0; i < Results.Count; i++)
{
((List<T>)Src).Add(Results[i]);
}
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<TResult> CoreSelect<T, TResult>(this IEnumerable<T> Src, Func<T, TResult> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
List<TResult> Results = new List<TResult>();
while (Data.MoveNext())
{
Results.Add(Dlg(Data.Current));
}
return Results.AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
public static int CoreSum<T>(this IEnumerable<T> Src, Func<T, int> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
int Result = default(int);
while (Data.MoveNext())
{
Result += Dlg(Data.Current);
}
return Result;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static double CoreSum<T>(this IEnumerable<T> Src, Func<T, double> Dlg)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
double Result = default(double);
while (Data.MoveNext())
{
Result += Dlg(Data.Current);
}
return Result;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static List<T> CoreToList<T>(this IEnumerable<T> Src)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
List<T> Results = new List<T>();
while (Data.MoveNext())
{
Results.Add(Data.Current);
}
return Results;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<T> CoreUnion<T>(this IEnumerable<T> Src, IEnumerable<T> Src2, IEqualityComparer<T> Cmr)
{
try
{
return (Src.Concat(Src2)).CoreDistinct(Cmr);
}
catch (Exception Ex)
{
throw Ex;
}
}
public static T CoreSingle<T>(this IEnumerable<T> Src, System.Func<T, bool> Dlg)
{
try
{
List<T> Data = Src.CoreToList();
T Result = default(T);
int Count = 0;
for (int i = 0; i < Data.Count; i++)
{
if (Dlg(Data[i]) == true)
Result = Data[i];
Count++;
}
if (Count >= 2)
throw new Exception();
return Data[0];
}
catch (Exception Ex)
{
throw Ex;
}
}
public static IEnumerable<T> CoreTake<T>(this IEnumerable<T> Src, int Value)
{
try
{
IEnumerator<T> Data = Src.GetEnumerator();
List<T> Results = new List<T>();
int CountLimit = 0;
while (Data.MoveNext())
{
if (CountLimit == Value)
break;
Results.Add(Data.Current);
CountLimit++;
}
return Results.AsEnumerable();
}
catch (Exception Ex)
{
throw Ex;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Controlador_HUD : MonoBehaviour
{
private Toggle toque;
private Toggle som;
private Toggle auxilio;
private Canvas botoes;
private Animator fadeAnim;
private GameObject painel_Pause;
private MusicaForaDoJogo somGeralJogo;
private GameObject textoAuxiliador;
private void Update() {
if(Personagem.acaFinal){
botoes.gameObject.SetActive(false);
}
}
// Start is called before the first frame update
void Awake()
{
fadeAnim = GameObject.Find("FadeGame").GetComponent<Animator>();
StartCoroutine(desativarFade());
botoes = GameObject.Find("CanvasBotoes").GetComponent<Canvas>();
somGeralJogo = GameObject.FindGameObjectWithTag("ControladorInicial").GetComponent<MusicaForaDoJogo>();
//buscarObjetosToggle
toque = GameObject.Find("Toque").GetComponent<Toggle>();
som = GameObject.Find("Audio").GetComponent<Toggle>();
auxilio = GameObject.Find("Ajuda").GetComponent<Toggle>();
textoAuxiliador = GameObject.Find("AuxiliadorTEXT");
painel_Pause = GameObject.Find("PauseGame");
}
void Start()
{
painel_Pause.SetActive(false);
this.verificarToggles();
}
IEnumerator desativarFade(){
yield return new WaitForSeconds(1);
fadeAnim.transform.localScale = new Vector3(0,0,0);
}
public IEnumerator Lose()
{
fadeAnim.transform.localScale = new Vector3(1,1,1);
yield return new WaitForSeconds(1);
Restart();
}
public void OpenOptions()
{
painel_Pause.SetActive(true);
}
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void Seletion()
{
somGeralJogo.tocarMusicar(0);
SceneManager.LoadScene("SeletionFase1");
}
public IEnumerator vitoria()
{
fadeAnim.transform.localScale = new Vector3(1,1,1);
yield return new WaitForSeconds(1);
Seletion();
}
public void Play()
{
painel_Pause.SetActive(false);
}
void verificarToggles()
{
if (PlayerPrefs.GetInt("som") == 0)
{
som.isOn = false;
}
else
{
som.isOn = true;
}
if (PlayerPrefs.GetInt("toque") == 0)
{
toque.isOn = false;
}
else
{
toque.isOn = true;
}
if (PlayerPrefs.GetInt("auxilio") == 0)
{
auxilio.isOn = false;
}
else
{
auxilio.isOn = true;
}
}
public void modificarAtivacaoSom()
{
if (som.isOn)
{
PlayerPrefs.SetInt("som", 1);
}
else
{
PlayerPrefs.SetInt("som", 0);
}
}
public void modificarAtivacaoToque()
{
if (toque.isOn)
{
PlayerPrefs.SetInt("toque", 1);
}
else
{
PlayerPrefs.SetInt("toque", 0);
}
}
public void modificarAtivacaoAuxilio()
{
if (auxilio.isOn)
{
textoAuxiliador.SetActive(true);
PlayerPrefs.SetInt("auxilio", 1);
}
else
{
textoAuxiliador.SetActive(false);
PlayerPrefs.SetInt("auxilio", 0);
}
}
}
|
using LogicBuilder.RulesDirector;
using LogicBuilder.Workflow.Activities.Rules;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Enrollment.Spa.Flow.Rules
{
public class RulesCache : IRulesCache
{
public RulesCache(ConcurrentDictionary<string, RuleEngine> ruleEngines, ConcurrentDictionary<string, string> resourceStrings)
{
concurrentRuleEngines = ruleEngines;
concurrentResourceStrings = resourceStrings;
}
private readonly ConcurrentDictionary<string, RuleEngine> concurrentRuleEngines;
private readonly ConcurrentDictionary<string, string> concurrentResourceStrings;
#region Properties
public IDictionary<string, RuleEngine> RuleEngines => concurrentRuleEngines;
public IDictionary<string, string> ResourceStrings => concurrentResourceStrings;
#endregion Properties
#region Methods
public RuleEngine? GetRuleEngine(string ruleSet)
{
if (this.RuleEngines == null)
return null;
return this.concurrentRuleEngines.TryGetValue(ruleSet.ToLowerInvariant(), out RuleEngine? ruleEngine) ? ruleEngine : null;
}
#endregion Methods
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using MediatR;
using Npgsql;
namespace DDDSouthWest.Domain.Features.Public.ProposedTalkDetail
{
public class ProposedTalkDetail
{
public class Query : IRequest<Response>
{
public readonly int Id;
public Query(int id)
{
Id = id;
}
}
public class Handler : IRequestHandler<Query, Response>
{
private readonly ClientConfigurationOptions _options;
public Handler(ClientConfigurationOptions options)
{
_options = options;
}
public async Task<Response> Handle(Query message, CancellationToken cancellationToken)
{
using (var connection = new NpgsqlConnection(_options.Database.ConnectionString))
{
const string query =
"SELECT t.Id AS TalkId, t.TalkTitle, t.TalkBodyHtml, t.UserId AS SpeakerId, u.GivenName AS SpeakerGivenName, u.FamilyName AS SpeakerFamilyName, p.BioHtml AS SpeakerBioHtml FROM talks AS t LEFT JOIN users AS u ON u.id = t.userid LEFT JOIN Profiles AS p ON p.UserId = t.userid WHERE t.IsApproved = TRUE AND u.IsActivated = TRUE AND t.Id = @Id";
var response = await connection.QuerySingleOrDefaultAsync<ProposedTalkDetailModel>(query, new
{
Id = message.Id
});
return new Response
{
ProposedTalkDetail = response
};
}
}
}
public class Response
{
public ProposedTalkDetailModel ProposedTalkDetail { get; set; }
}
}
} |
namespace Belot.Engine.Cards
{
public enum CardSuit : byte
{
/// <summary>
/// ♣ - Clubs
/// </summary>
Club = 0,
/// <summary>
/// ♦ - Diamonds
/// </summary>
Diamond = 1,
/// <summary>
/// ♥ - Hearts
/// </summary>
Heart = 2,
/// <summary>
/// ♠ - Spades
/// </summary>
Spade = 3,
}
}
|
public int HammingWeight(uint n) {
int sum = 0;
while (n > 0) {
if ((n & amp; 1) == 1) {
sum++;
}
n >>= 1;
}
return sum;
} |
namespace TPLinCSharpSample.Tests
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;
[TestClass]
public class ToDoQueueTest
{
[TestMethod]
public void Ctor_AlwaysReturns_ValidInstance()
{
// Act
var fixture = this.CreateFixture();
// Assert
fixture.ShouldNotBeNull();
}
[TestMethod]
public void AddTrade_OnAdd_PushesIntoTradeQueue()
{
//Arrange
var fixture = this.CreateFixture();
var stubSalesPerson = new SalesPerson("Kiran");
var stubTrade = new Trade(stubSalesPerson, 10);
//Act
fixture.AddTrade(stubTrade);
//Assert
fixture.TradeQueue.Count.ShouldBe(1);
}
[TestMethod]
public void TradeQueue_OnCompleteAdding_ProcessesEntireQueue()
{
//Arrange
var fixture = this.CreateFixture();
//Act
fixture.CompleteAdding();
//Assert
fixture.TradeQueue.Count.ShouldBe(0);
}
private ToDoQueue CreateFixture()
{
var stubStaffLogsForBonuses = new StaffLogsForBonuses();
var fixture = new ToDoQueue(stubStaffLogsForBonuses);
return fixture;
}
}
}
|
namespace CarSelector.Contracts
{
using CarSelector.Model;
public interface ICarEvaluatorService
{
/// <summary>
/// Determine completion time for a single Car configuration against a race track
/// </summary>
CarRaceTrackEvaluation Evaluate(RaceTrack raceTrack, CarConfiguration carConfiguration);
/// <summary>
/// Determine completion times for Car configurations and sort evaluations from fastest to slowest against a race track
/// </summary>
CarRaceTrackEvaluation[] EvaluateAndSort(RaceTrack raceTrack, CarConfiguration[] carConfigurations);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace COM3D2.SimpleUI
{
public interface ITextArea: IContentControl
{
}
}
|
using System.Net;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Common.Concurrency;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using log4net;
using Plus.Network.Codec;
using Plus.Network.Handler;
namespace Plus.Network
{
public class NetworkBootstrap
{
private string Host { get; }
private int Port { get; }
private IEventLoopGroup BossGroup { get; set; }
private IEventLoopGroup WorkerGroup { get; set; }
private IEventExecutorGroup ChannelGroup { get; set; }
private ServerBootstrap ServerBootstrap { get; set; }
private IChannel ServerChannel { get; set; }
private static readonly ILog Log = LogManager.GetLogger(typeof(NetworkBootstrap));
public static readonly int MAX_FRAME_SIZE = 500000;
public NetworkBootstrap(string host, int port)
{
Host = host;
Port = port;
}
public async Task InitAsync()
{
BossGroup = new MultithreadEventLoopGroup(int.Parse(PlusEnvironment.GetConfig().Data["game.tcp.acceptGroupThreads"]));
WorkerGroup = new MultithreadEventLoopGroup(int.Parse(PlusEnvironment.GetConfig().Data["game.tcp.ioGroupThreads"]));
ChannelGroup = new MultithreadEventLoopGroup(int.Parse(PlusEnvironment.GetConfig().Data["game.tcp.channelGroupThreads"]));
ServerBootstrap = new ServerBootstrap()
.Group(BossGroup, WorkerGroup)
.Channel<TcpServerSocketChannel>()
.ChildHandler(new ActionChannelInitializer<IChannel>(channel =>
{
channel.Pipeline.AddLast("messageInterceptor", new MessageInterceptorHandler());
channel.Pipeline.AddLast("xmlDecoder", new GamePolicyDecoder());
channel.Pipeline.AddLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_SIZE, 0, 4, 0, 4));
channel.Pipeline.AddLast("gameEncoder", new GameEncoder());
channel.Pipeline.AddLast("gameDecoder", new GameDecoder());
channel.Pipeline.AddLast(ChannelGroup, "clientHandler", new NetworkChannelHandler());
}))
.ChildOption(ChannelOption.TcpNodelay, true)
.ChildOption(ChannelOption.SoKeepalive, true)
.ChildOption(ChannelOption.SoRcvbuf, 1024)
.ChildOption(ChannelOption.RcvbufAllocator, new FixedRecvByteBufAllocator(1024))
.ChildOption(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);
ServerChannel = await ServerBootstrap.BindAsync(IPAddress.Parse(Host), Port);
Log.Info($"Game Server listening on {((IPEndPoint) ServerChannel.LocalAddress).Address.MapToIPv4()}:{Port}");
}
/// <summary>
/// Close all channels and disconnects clients
/// </summary>
/// <returns></returns>
public async Task Shutdown()
{
await ServerChannel.CloseAsync();
}
/// <summary>
/// Shutdown all workers of netty
/// </summary>
/// <returns></returns>
public void ShutdownWorkers()
{
BossGroup.ShutdownGracefullyAsync();
WorkerGroup.ShutdownGracefullyAsync();
ChannelGroup.ShutdownGracefullyAsync();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Intex.Models
{
[Table("Employee")]
public class Employee
{
[Key]
public int EmployeeID { get; set; }
[Required]
[Display(Name = "Employee First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Employee Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string Phone { get; set; }
[Required]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Required]
[Display(Name = "Employee Username")]
public string Username { get; set; }
[Required]
[Display(Name = "Employee Password")]
public string Password { get; set; }
[Required]
[Display(Name = "Hourly Wage")]
public decimal HourlyWage { get; set; }
//Foreign Keys
[Required]
[ForeignKey("Location")]
public virtual int LocationID { get; set; }
public virtual Location Location { get; set; }
[Required]
[ForeignKey("EmployeeType")]
public virtual int EmployeeTypeID { get; set; }
public virtual EmployeeType EmployeeType { get; set; }
}
} |
using CustomerManagement.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace CustomerManagement.Infrastructure.Data.Mappings
{
public class EnderecoConfiguration : IEntityTypeConfiguration<Endereco>
{
public void Configure(EntityTypeBuilder<Endereco> b)
{
b.ToTable("Enderecos");
b.Property(c => c.Id).HasColumnType("CHAR(36)");
b.HasKey(c => c.Id);
b.Property(c => c.CEP)
.HasColumnType("CHAR(8)")
.HasMaxLength(8)
.IsRequired();
b.Property(c => c.Logradouro)
.HasMaxLength(50)
.IsRequired();
b.Property(c => c.Numero)
.HasColumnType("VARCHAR(20)")
.HasMaxLength(20)
.IsRequired();
b.Property(c => c.Bairro)
.HasMaxLength(150)
.IsRequired();
b.Property(c => c.Complemento)
.HasMaxLength(150);
b.Property(c => c.Localidade)
.HasMaxLength(50)
.IsRequired();
b.Property(c => c.Uf)
.HasColumnType("CHAR(2)")
.HasMaxLength(2)
.IsRequired();
b.HasOne(c => c.Cliente)
.WithMany(e => e.Enderecos)
.HasForeignKey(c => c.ClienteId)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Ignore(e => e.ValidationResult);
b.Ignore(e => e.CascadeMode);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//AI spawn for Circuit 6
public class c6Aicontrol : MonoBehaviour
{
public GameObject AI1;
public void OnTriggerEnter(Collider other)
{
AI1.SetActive(true);
}
}
|
using SO.Urba.Managers;
using SO.Utility.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SO.Urba.Web.Controllers
{
[Authorize]
public class DropDownController : Controller
{
private CompanyCategoryTypeManager companyCategoryTypeManager = new CompanyCategoryTypeManager();
private CompanyManager companyManager = new CompanyManager();
private ClientManager clientManager = new ClientManager();
/// <summary>
/// /DropDown/companyCategoryTypes
///
/// @Html.Action("companyCategoryTypes", "DropDown", new { id = Model.companyCategoryTypeId })
/// </summary>
public ActionResult companyCategoryTypes(int? id = null)
{
var vo = new DropDownVm();
vo.propertyName = "companyCategoryTypeId";
vo.dataValueField = "companyCategoryTypeId";
vo.dataTextField = "name";
vo.selectedValue = id;
vo.items = companyCategoryTypeManager.getAll(true); // CompanyCategoryTypeVo
return View("_DropDownList", vo);
}
/// <summary>
/// /DropDown/companyCategoryTypes2
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult companyCategoryTypes2(int? id = null)
{
var vo = new DropDownVm();
vo.propertyName = "companyCategoryTypeId";
vo.dataValueField = "companyCategoryTypeId";
vo.dataTextField = "name";
vo.selectedValue = id;
vo.optionLabel = "All Providers";
vo.items = companyCategoryTypeManager.getCompanyCategories(true); // CompanyCategoryClass
return View("_DropDownList", vo);
}
/// <summary>
/// /DropDown/companies
///
/// @Html.Action("companies", "DropDown", new { id = Model.companyId })
/// </summary>
public ActionResult companies(int? id = null)
{
var vo = new DropDownVm();
vo.propertyName = "companyId";
vo.dataValueField = "companyId";
vo.dataTextField = "companyName";
vo.selectedValue = id;
vo.optionLabel = "Providers";
vo.items = companyManager.getAll(true); // CompanyCategoryTypeVo
return View("_DropDownList", vo);
}
/// <summary>
/// /DropDown/clients
///
/// @Html.Action("clients", "DropDown", new { id = Model.clientId })
/// </summary>
public ActionResult clients(int? id = null)
{
var vo = new DropDownVm();
vo.propertyName = "clientId";
vo.dataValueField = "clientId";
vo.dataTextField = "clientId";
vo.selectedValue = id;
vo.optionLabel = "All Clients";
vo.items = clientManager.getAll(true); // CompanyCategoryTypeVo
return View("_DropDownList", vo);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.