text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : Item
{
private Transform m_effectParent;
private Transform M_EffectParent
{
get
{
if (m_effectParent == null)
{
m_effectParent = GameObject.Find(Consts.O_EffectParent).transform;
}
return m_effectParent;
}
}
private float m_moveSpeed = 40;
public override void HitPlayer(Transform pos)
{
GameObject go = Game.M_Instance.M_ObjectPool.Spawn(Consts.O_FX_JinBi);
go.transform.SetParent(M_EffectParent,true);
go.transform.position = pos.position;
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_JinBi);
Game.M_Instance.M_ObjectPool.UnSpawn(gameObject);
}
public void OnTriggerEnter(Collider other)
{
if (other.tag == Tag.Tag_Player)
{
HitPlayer(other.transform);
other.SendMessage("HitCoin", SendMessageOptions.RequireReceiver);
}
else if (other.tag==Tag.Tag_MagnetCollider)
{
StartCoroutine(HitMagnet(other.transform));
}
}
IEnumerator HitMagnet(Transform pos)
{
bool isLoop = true;
while (isLoop)
{
transform.position = Vector3.Lerp(transform.position, pos.position, m_moveSpeed * Time.deltaTime);
if (Vector3.Distance(transform.position, pos.position) < 0.3f)
{
isLoop = false;
HitPlayer(pos.parent);
pos.parent.SendMessage("HitCoin", SendMessageOptions.RequireReceiver);
}
yield return null;
}
}
}
|
using System;
using System.Collections.Generic;
using Effigy.Service;
using Effigy.Utility;
using Effigy.Entity.DBContext;
using System.Net.Http;
using System.Web.Services;
using System.Net.Http.Formatting;
namespace Effigy.Web.MasterPage
{
public partial class StateMaster : BasePage
{
MasterService objMstService = new MasterService();
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
FillCountry();
//BindState();
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
private void FillCountry()
{
try
{
IList<CountryMapper> objMstCountry = objMstService.GetCountry();
Common.FillDDL<IList<CountryMapper>>(ddlCountry, objMstCountry, "CountryId", "CountryName", true);
}
catch (Exception ex)
{
Logger.Error(ex);
}
finally { Dispose(); }
}
[WebMethod]
public static IList<ClsStateMaster> GetStateList()
{
try
{
IMasterService objMstService = new MasterService();
IList<ClsStateMaster> objMstState = objMstService.GetState();
return objMstState;
}
catch (Exception ex)
{
Logger.Error(ex);
return null;
}
}
[WebMethod]
public static bool SaveState(Entity.DBContext.ClsStateMaster objStateMaster)
{
try
{
IMasterService objMstService = new MasterService();
MstState objMstState = new MstState();
objMstState.CountryID = objStateMaster.CountryID;
objMstState.StateName = objStateMaster.StateName;
objMstState.CreatedBy = SessionWrapper.UserId;
objMstState.CreatedDate = DateTime.Now;
objMstService.InsertStateDetail(objMstState);
return true;
}
catch (Exception ex)
{
Logger.Error(ex);
return false;
}
}
protected void lnkSave_Click(object sender, EventArgs e)
{
try
{
MstState objMstState = new MstState();
objMstState.StateName = txtStateName.Text.TrimString();
objMstState.CountryID = Convert.ToInt32(ddlCountry.SelectedValue) != 0 ? Convert.ToInt32(ddlCountry.SelectedValue) : 1;
objMstState.IsActive = true;
objMstState.CreatedBy = SessionWrapper.UserId;
objMstState.CreatedDate = System.DateTime.Now;
objMstService.InsertStateDetail(objMstState);
}
catch (Exception ex)
{
Logger.Error(ex);
}
finally
{
Dispose();
}
}
}
} |
using UnityEngine;
namespace Updater {
public abstract class IUpdater : MonoBehaviour {
private void Awake() {
UpdaterManager.Instance.Add(this);
}
public abstract void DoUpdate();
}
} |
namespace OpenApiLib.Json.Models
{
public class CursorMessageJson<T> : MessageJson<T>
{
public string Next { get; set; }
}
}
|
using System.Collections.Generic;
namespace Leprechaun.Filters
{
public interface ITemplateTreeRoot
{
IList<IPresetTreeExclusion> Exclusions { get; set; }
string Name { get; }
string Path { get; }
}
} |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using VoxelSpace.Resources;
namespace VoxelSpace.Graphics {
public abstract class Material : IDisposable {
protected abstract string _effectResourceName { get; }
public Effect Effect { get; private set; }
public EffectParameter this[string name] => Effect.Parameters[name];
public Material() {
Effect = ResourceManager.Load<Effect>(_effectResourceName).Clone();
}
public virtual void Bind() {
Effect.CurrentTechnique.Passes[0].Apply();
}
public void Dispose() {
Effect?.Dispose();
Effect = null;
}
}
} |
namespace T4WFI.App.Code.Pseudo
{
using System.Diagnostics;
public class PseudoContainer : IContainer
{
public T GetInstance<T>() where T : class
{
var target = new PseudoTarget() as T;
Debug.WriteLine($"Created {target}", nameof(PseudoContainer));
return target;
}
public void Release(object o)
{
Debug.WriteLine($"Releasing {o}", nameof(PseudoContainer));
}
private class PseudoTarget : IDummyInterface, IDummyInterface2
{
private static int instanceCount;
private readonly int instance;
static PseudoTarget()
{
PseudoTarget.instanceCount = 0;
}
public PseudoTarget()
{
this.instance = PseudoTarget.instanceCount++;
}
public override string ToString()
{
return $"Instance {this.instance}";
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Banana : MonoBehaviour
{
[Tooltip("바나나의 사라지는 시간"), Range(0.5f, 5f)] public float disappearTime;
private void Start()
{
StartCoroutine(Disappear());
}
private IEnumerator Disappear()
{
float t = 0;
float targetTime = disappearTime;
while (t < targetTime)
{
t += Time.deltaTime;
yield return null;
}
Destroy(this.gameObject);
}
}
|
using Newtonsoft.Json;
using Utilities;
namespace EddiDataDefinitions
{
/// <summary> This class is designed to be deserialized from either shipyard.json or the Frontier API. </summary>
public class OutfittingInfoItem
{
[JsonProperty("id")]
public long EliteID { get; set; }
[JsonProperty("name")]
public string edName { get; set; }
[JsonProperty("category")]
public string edCategory { get; set; }
// Station prices
[JsonProperty("BuyPrice")]
public long buyPrice { get; set; }
// The Frontier API uses `cost` rather than `BuyPrice`, we normalize that here.
[JsonProperty] // As a private property, it shall not be serialized.
private protected long cost { set => buyPrice = value; }
public OutfittingInfoItem()
{ }
public OutfittingInfoItem(long eliteId, string edName, int BuyPrice)
{
this.EliteID = eliteId;
this.edName = edName;
this.buyPrice = BuyPrice;
}
public OutfittingInfoItem(long eliteId, string edName, string edCategory, int BuyPrice)
{
this.EliteID = eliteId;
this.edName = edName;
this.edCategory = edCategory;
this.buyPrice = BuyPrice;
}
public Module ToModule()
{
var module = new Module(Module.FromEliteID(EliteID, this)
?? Module.FromEDName(edName, this)
?? new Module());
if (module.invariantName == null)
{
// Unknown module; report the full object so that we can update the definitions
Logging.Info("Module definition error: " + edName, JsonConvert.SerializeObject(this));
// Create a basic module & supplement from the info available
module = new Module(EliteID, edName, edName, -1, "", buyPrice);
}
else
{
module.price = buyPrice;
}
return module;
}
}
} |
using CarRental.API.BL.Models;
using CarRental.API.BL.Models.Car;
using CarRental.API.DAL.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace CarRental.API.BL.Services
{
public interface ICarService
{
Task<IEnumerable<CarModel>> GetAllAsync();
Task<CarModel> GetAsync(Guid id);
Task<CarItem> CreateAsync(CreateCarModel item);
Task<IEnumerable<CarItem>> UpsertAsync(CarModel item);
Task<IEnumerable<CarItem>> MarkCarAsAvailable(CarAvailabilityModel item);
Task<CarItem> DeleteAsync(Guid id);
}
}
|
using Model.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.DAO
{
public class DocumentBookDAO
{
DocumentManagementDbContext db = null;
public DocumentBookDAO()
{
db = new DocumentManagementDbContext();
}
public List<DocumentBook> ListAll()
{
return db.DocumentBooks.ToList();
}
}
}
|
using System;
namespace Uintra.Infrastructure.TypeProviders
{
public class MediaFolderTypeProvider : EnumTypeProviderBase, IMediaFolderTypeProvider
{
public MediaFolderTypeProvider(params Type[] enums) : base(enums)
{
}
}
} |
using System;
using BSMU_Schedule.Enums;
using BSMU_Schedule.Interfaces;
using BSMU_Schedule.Interfaces.DataAccess.StorageAdapters;
using BSMU_Schedule.Services.DataAccess.StorageAdapters;
namespace BSMU_Schedule.Services.DataAccess
{
public static class StorageAdapterBuilder
{
public static IStorageAdapter<T> BuildAdapter<T>(StorageType storageType, IHasConnectionConfiguration configuration)
{
switch (storageType)
{
case StorageType.XmlFileStorageType:
return new XmlStorageAdapter<T>(configuration);
}
throw new NotImplementedException($"Adapter of type {storageType:G} not supported");
}
}
}
|
using SAAS.FrameWork.Log;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using SAAS.FrameWork.Mq;
using System.Threading;
using SAAS.FrameWork.Util.Threading;
using SAAS.FrameWork.Module.Serialization;
using SAAS.FrameWork.Extensions;
namespace SAAS.Mq.Socket.Channel
{
public class ClientMq: IClientMq
{
#region (x.0) 成员
public ClientMqConfig config { get; private set; }
MqConnect _mqConnect = new MqConnect();
public Action Conn_OnDisconnected
{
set
{
_mqConnect.OnDisconnected = (_) => {
value();
};
}
}
public bool IsConnected => _mqConnect.IsConnected;
public ClientMq(ClientMqConfig config)
{
this.config = config;
}
#endregion
#region (x.1) Connect Close Dispose
#region Connect
public bool Connect()
{
//服务已启动
if (_mqConnect.IsConnected) return false;
#region (x.1)连接服务器
Logger.Info("[消息队列 Socket Client] 连接服务器,host:" + config.host + " port:" + config.port);
TcpClient client;
try
{
client = new System.Net.Sockets.TcpClient(config.host, config.port);
}
catch (Exception ex)
{
//服务启动失败
Logger.Error("[消息队列 Socket Client] 连接服务器 出错", ex);
return false;
}
#endregion
//(x.2) init _mqConnect
if (!_mqConnect.Init(client,config))
{
_mqConnect.Close();
Logger.Info("[消息队列 Socket Client] 无法连接服务器。");
return false;
}
//(x.3)发送身份验证
if (!checkSecretKey()) return false;
//(x.4) start back thread for ping
ping_BackThread.action = Ping_Thread;
ping_BackThread.Start();
Logger.Info("[消息队列 Socket Client] 已连接服务器。");
return true;
#region checkSecretKey
bool checkSecretKey()
{
//发送身份验证
Logger.Info("[消息队列 Socket Client] 发送身份验证请求...");
var secretKey = config.secretKey;
var reply = SendRequest(Serialization.Instance.Serialize(secretKey).BytesToByteData());
if (Serialization.Instance.Deserialize<string>(reply) == "true")
{
Logger.Info("[消息队列 Socket Client] 身份验证通过");
return true;
}
Logger.Info("[消息队列 Socket Client] 身份验证失败");
return false;
}
#endregion
}
#endregion
#region Close Dispose
~ClientMq()
{
Dispose();
}
public void Dispose()
{
Close();
_mqConnect.Dispose();
}
public void Close()
{
if (!IsConnected) return;
Logger.Info("[消息队列 Socket Client] 准备断开连接");
try
{
ping_BackThread.Stop();
}
catch (Exception ex)
{
Logger.Error("[消息队列 Socket Client] 准备断开连接 出错",ex);
}
try
{
_mqConnect.Close();
}
catch (Exception ex)
{
Logger.Error("[消息队列 Socket Client] 准备断开连接 出错", ex);
}
Logger.Info("[消息队列 Socket Client] 已断开连接。");
}
#endregion
#endregion
#region (x.2) Message
public void SendMessage(List<ArraySegment<byte>> msgData)
{
_mqConnect.SendMessage(msgData);
}
public Action<ArraySegment<byte>> OnReceiveMessage { get => _mqConnect.OnReceiveMessage; set => _mqConnect.OnReceiveMessage = value; }
#endregion
#region (x.3) ReqRep
public Func<ArraySegment<byte>, List<ArraySegment<byte>>> OnReceiveRequest
{
set => _mqConnect.OnReceiveRequest = value;
get => _mqConnect.OnReceiveRequest;
}
/// <summary>
///
/// </summary>
/// <param name="requestData"></param>
/// <returns></returns>
public ArraySegment<byte> SendRequest(List<ArraySegment<byte>> requestData)
{
var flag = _mqConnect.SendRequest(requestData, out var replyData);
return replyData;
}
#endregion
#region (x.4) Ping_Thread
LongTaskHelp ping_BackThread = new LongTaskHelp();
void Ping_Thread()
{
while (true)
{
try
{
while (true)
{
bool disconnected = true;
try
{
disconnected = !_mqConnect.Ping();
}
catch (Exception ex)
{
Logger.Error(ex);
}
if (disconnected)
{
try
{
_mqConnect.Close();
}
catch (Exception ex)
{
Logger.Error(ex);
}
return;
}
Thread.Sleep(config.pingInterval);
}
}
catch (Exception ex) when (!(ex is ThreadInterruptedException))
{
Logger.Error(ex);
}
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Abc.MvcWebUI.Entity;
namespace Abc.MvcWebUI.Controllers
{
[Authorize(Roles = "admin")]
public class ProductController : Controller
{
private DataContext db = new DataContext();
// GET: Product
public ActionResult Index()
{
var bag = db.Products.Select(i => new ProductViewModel()
{
Id = i.Id,
Name = i.Name,
Description = i.Description.Length > 50 ? i.Description.Substring(0, 47) + "..." : i.Description,
İmage = i.İmage ?? "unnamed.png",
IsApproved = i.IsApproved,
IsHome = i.IsHome,
Price = i.Price,
Stock = i.Stock,
Category = i.Category
});
var product = db.Products.Include(i=>i.Category).ToList();
return View(bag.ToList());
}
// GET: Product/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// GET: Product/Create
public ActionResult Create()
{
ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name");
return View();
}
// POST: Product/Create
// Aşırı gönderim saldırılarından korunmak için bağlamak istediğiniz belirli özellikleri etkinleştirin.
// Daha fazla bilgi için bkz. https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Description,Price,Stock,İmage,IsHome,IsApproved,CategoryId")] Product product)
{
if (ModelState.IsValid)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", product.CategoryId);
return View(product);
}
// GET: Product/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", product.CategoryId);
return View(product);
}
// POST: Product/Edit/5
// Aşırı gönderim saldırılarından korunmak için bağlamak istediğiniz belirli özellikleri etkinleştirin.
// Daha fazla bilgi için bkz. https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Description,Price,Stock,İmage,IsHome,IsApproved,CategoryId")] Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", product.CategoryId);
return View(product);
}
// GET: Product/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: Product/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System.Web.Mvc;
using CAPCO.Infrastructure.Domain;
using CAPCO.Infrastructure.Data;
namespace CAPCO.Areas.Admin.Controllers
{
public class PriceCodesController : BaseAdminController
{
private readonly IRepository<PriceCode> _PricecodeRepository;
public PriceCodesController(IRepository<PriceCode> pricecodeRepository)
{
_PricecodeRepository = pricecodeRepository;
}
public ViewResult Index()
{
return View(_PricecodeRepository.All);//AllIncluding(x => x.Accounts, x => x.ProductPriceCodes));
}
public ViewResult Show(int id)
{
return View(_PricecodeRepository.Find(id));
}
public ActionResult New()
{
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(PriceCode pricecode)
{
if (ModelState.IsValid) {
_PricecodeRepository.InsertOrUpdate(pricecode);
_PricecodeRepository.Save();
this.FlashInfo("The price code was created successfully.");
return RedirectToAction("Index");
}
this.FlashError("There was a problem creating the price code.");
return View("New", pricecode);
}
public ActionResult Edit(int id)
{
return View(_PricecodeRepository.Find(id));
}
[HttpPut, ValidateAntiForgeryToken]
public ActionResult Update(PriceCode pricecode)
{
if (ModelState.IsValid) {
_PricecodeRepository.InsertOrUpdate(pricecode);
_PricecodeRepository.Save();
this.FlashInfo("The price code was saved successfully.");
return RedirectToAction("Index");
}
this.FlashError("There was a problem removing the price code.");
return View("Edit", pricecode);
}
public ActionResult Delete(int id)
{
_PricecodeRepository.Delete(id);
_PricecodeRepository.Save();
this.FlashInfo("The price code was deleted successfully.");
return RedirectToAction("Index");
}
}
}
|
using Terraria.ID;
using Terraria.ModLoader;
namespace Intalium.Items.Materials
{
public class Hard_Alloy : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Hard Alloy");
Tooltip.SetDefault("This poorly-forged reject alloy still gets the job done");
}
public override void SetDefaults()
{
item.value = 8000;
item.rare = 0;
item.maxStack = 999;
item.width = 34;
item.height = 39;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddRecipeGroup("Intalium:Tier1Bar", 1);
recipe.AddRecipeGroup("Intalium:Tier2Bar", 1);
recipe.AddRecipeGroup("Intalium:Tier3Bar", 1);
recipe.AddRecipeGroup("Intalium:Tier4Bar", 1);
recipe.AddIngredient(null, "Shine", 1);
recipe.AddTile(TileID.Furnaces);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
}
|
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf.Sources
{
public class SourceAuthor : Entity
{
public virtual string Author { get; set; }
}
}
|
using System;
using System.Linq;
using System.Numerics;
namespace Permut
{
public class Program
{
static void Main(string[] args)
{
while (true)
{
var input = Console.ReadLine();
if (input == null || input.Length < 3)
return;
var data = input.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
var n = int.Parse(data[0]);
var i = BigInteger.Parse(data[1]);
var result = FindIthPermutation(n, i);
Console.WriteLine(ArrayToString(result));
}
}
static string ArrayToString(int[] array)
{
return string.Join(" ", array.Select(d => d.ToString()));
}
public static int[] FindIthPermutation(int n, BigInteger i)
{
BigInteger[] fact = new BigInteger[n];
int[] permutation = new int[n];
fact[0] = 1;
for (int k = 1; k < n; k++)
{
fact[k] = fact[k - 1] * k;
}
for (int k = 0; k < n; k++)
{
permutation[k] = (int)BigInteger.Divide(i, fact[n - 1 - k]);
i = i % fact[n - 1 - k];
}
for (int k = n - 1; k > 0; k--)
{
for (int j = k - 1; j >= 0; j--)
{
if (permutation[j] <= permutation[k])
permutation[k]++;
}
}
for (int k = 0; k < n; k++)
{
permutation[k]++;
}
return permutation;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace BankAppCore.Models
{
public class Bill
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(100)]
[Required]
public string Provider { get; set; }
[MaxLength(20)]
[Required]
public string SecretNumber { get; set; }
[Required]
public int Amount { get; set; }
public DateTime Date { get; set; }
[Required]
public virtual Client Client { get; set; }
public Bill()
{
Date = DateTime.Now;
}
}
} |
using Alabo.Domains.Repositories.Mongo.Extension;
using MongoDB.Bson;
using Newtonsoft.Json;
namespace Alabo.Framework.Themes.Dtos {
public class SystemWidgetDataInput {
[JsonConverter(typeof(ObjectIdConverter))]
public ObjectId Id { get; set; }
[JsonConverter(typeof(ObjectIdConverter))]
public ObjectId WidgetId { get; set; }
public bool IsDefault { get; set; }
public string FullName { get; set; }
public string Type { get; set; }
/// <summary>
/// 组件路径
/// </summary>
public string ComponentPath { get; set; }
/// <summary>
/// 默认数据
/// </summary>
public string Value { get; set; }
}
} |
using System;
using System.Collections.Generic;
namespace _04._Songs
{
class Program
{
static void Main(string[] args)
{
int count = int.Parse(Console.ReadLine());
List<Song> allSongs = new List<Song>();
for (int i = 0; i < count; i++)
{
string[] inputInfo = Console.ReadLine()
.Split('_', StringSplitOptions.RemoveEmptyEntries);
string typeList = inputInfo[0];
string name = inputInfo[1];
string time = inputInfo[2];
Song song = new Song();
song.TypeList = typeList;
song.Name = name;
song.Time = time;
allSongs.Add(song);
}
string typeListWanted = Console.ReadLine();
if (typeListWanted == "all")
{
foreach (var item in allSongs)
{
Console.WriteLine(item.Name);
}
}
else
{
foreach (Song song in allSongs)
{
if (song.TypeList == typeListWanted)
{
Console.WriteLine(song.Name);
}
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreatureData
{
public Inventory inventory;
public Stats stats;
public CreatureData()
{
inventory = new Inventory();
stats = new Stats();
}
}
|
using System.Collections.Generic;
using Uintra.Core.Member.Models;
namespace Uintra.Features.Navigation.Models
{
public class TopNavigationViewModel
{
public MemberViewModel CurrentMember { get; set; }
public IEnumerable<TopNavigationItemViewModel> Items { 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;
namespace TableroComando.Formularios
{
public partial class Form_ModificarObjetivos : Form
{
public Form_ModificarObjetivos()
{
InitializeComponent();
foreach (Clases.Modelo.Objetivo Obj in Clases.Modelo.Objetivo.listarObjetivos())
{
DGVFinanciera.Rows.Add(Obj.getidobjetivo(),Obj.getnumero(),Obj.gettitulo(),Obj.getnombreestado(),Obj.getnombreperspectiva());
}
}
private void BTNModificar_Click(object sender, EventArgs e)
{
Form ventana = new Formularios.Form_ModificarObjetivoDetalle(DGVFinanciera.SelectedCells[0].Value.ToString());
ventana.Show();
}
private void button1_Click(object sender, EventArgs e)
{
Form ventana = new Formularios.Form_AgregarIndicador();
ventana.Show();
}
}
}
|
using System;
using PetaPoco;
namespace ZYL.Core.Model
{
[Serializable]
[TableName("Shop_Module_Setting")]
[PrimaryKey("Id", AutoIncrement=false)]
public partial class Shop_Module_Setting
{
/// <summary>
/// 模块ID
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 店铺ID
/// </summary>
public Guid? ShopId { get; set; }
/// <summary>
/// 版本ID
/// </summary>
public string Version { get; set; }
/// <summary>
/// 父级模块ID
/// </summary>
public Guid? ParentId { get; set; }
/// <summary>
/// 模块名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 前端路由
/// </summary>
public string RouteUrl { get; set; }
/// <summary>
/// 前端图标
/// </summary>
public string IconUrl { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime? CreateTime { get; set; }
/// <summary>
/// 创建ID
/// </summary>
public Guid? CreateId { get; set; }
/// <summary>
/// 是否删除
/// </summary>
public int? IsDel { get; set; }
/// <summary>
/// 排序
/// </summary>
public int? Sort { get; set; }
/// <summary>
/// 模块类型 0 或 Null是属于B端,1 属于C端模块
/// </summary>
public int? OriginType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2017 {
public class Problem08 : AdventOfCodeBase {
public override string ProblemName {
get { return "Advent of Code 2017: 8"; }
}
public override string GetAnswer() {
return Answer1(Input());
}
public override string GetAnswer2() {
return Answer2(Input());
}
private Dictionary<string, int> _registers = new Dictionary<string, int>();
private string Answer1(List<string> input) {
foreach (string text in input) {
Register register = new Register(text);
switch (register.IfOp) {
case "!=":
if (GetRegisterValue(register.IfName) != register.IfValue) {
if (!_registers.ContainsKey(register.Name)) {
_registers.Add(register.Name, 0);
}
_registers[register.Name] += register.Offset;
}
break;
case ">=":
if (GetRegisterValue(register.IfName) >= register.IfValue) {
if (!_registers.ContainsKey(register.Name)) {
_registers.Add(register.Name, 0);
}
_registers[register.Name] += register.Offset;
}
break;
case ">":
if (GetRegisterValue(register.IfName) > register.IfValue) {
if (!_registers.ContainsKey(register.Name)) {
_registers.Add(register.Name, 0);
}
_registers[register.Name] += register.Offset;
}
break;
case "<=":
if (GetRegisterValue(register.IfName) <= register.IfValue) {
if (!_registers.ContainsKey(register.Name)) {
_registers.Add(register.Name, 0);
}
_registers[register.Name] += register.Offset;
}
break;
case "<":
if (GetRegisterValue(register.IfName) < register.IfValue) {
if (!_registers.ContainsKey(register.Name)) {
_registers.Add(register.Name, 0);
}
_registers[register.Name] += register.Offset;
}
break;
case "==":
if (GetRegisterValue(register.IfName) == register.IfValue) {
if (!_registers.ContainsKey(register.Name)) {
_registers.Add(register.Name, 0);
}
_registers[register.Name] += register.Offset;
}
break;
}
}
return _registers.Values.Max().ToString();
}
private string Answer2(List<string> input) {
int maxValue = int.MinValue;
foreach (string text in input) {
Register register = new Register(text);
if (!_registers.ContainsKey(register.Name)) {
_registers.Add(register.Name, 0);
}
switch (register.IfOp) {
case "!=":
if (GetRegisterValue(register.IfName) != register.IfValue) {
_registers[register.Name] += register.Offset;
}
break;
case ">=":
if (GetRegisterValue(register.IfName) >= register.IfValue) {
_registers[register.Name] += register.Offset;
}
break;
case ">":
if (GetRegisterValue(register.IfName) > register.IfValue) {
_registers[register.Name] += register.Offset;
}
break;
case "<=":
if (GetRegisterValue(register.IfName) <= register.IfValue) {
_registers[register.Name] += register.Offset;
}
break;
case "<":
if (GetRegisterValue(register.IfName) < register.IfValue) {
_registers[register.Name] += register.Offset;
}
break;
case "==":
if (GetRegisterValue(register.IfName) == register.IfValue) {
_registers[register.Name] += register.Offset;
}
break;
}
if (_registers[register.Name] > maxValue) {
maxValue = _registers[register.Name];
}
}
return maxValue.ToString();
}
private int GetRegisterValue(string registerName) {
if (!_registers.ContainsKey(registerName)) {
_registers.Add(registerName, 0);
}
return _registers[registerName];
}
private int GetOffset(string offset) {
if (offset == "inc") {
return 1;
} else {
return -1;
}
}
private class Register {
public string Name { get; set; }
public int Offset { get; set; }
public string IfName { get; set; }
public string IfOp { get; set; }
public int IfValue { get; set; }
public Register(string text) {
string[] particles = text.Split(' ');
this.Name = particles[0];
this.Offset = (particles[1] == "inc" ? 1 : -1) * Convert.ToInt32(particles[2]);
this.IfName = particles[4];
this.IfOp = particles[5];
this.IfValue = Convert.ToInt32(particles[6]);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Input
{
class Program
{
static void Main(string[] args)
{
string line;
int number = 0;
Console.WriteLine("Introduceti un numar:");
try
{
line = Console.ReadLine();
number = int.Parse(line);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
catch(OverflowException e)
{
Console.WriteLine(e.Message);
}
number *= 2;
Console.WriteLine("Numarul este: {0}. Dublul numarului este: {1}", number, number * 2);
foreach (var item in args)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
|
using Microsoft.Azure.ServiceBus;
using System;
namespace ServiceBusTopicsDemo
{
class Program
{
static void Main(string[] args)
{
// SET VALUES HERE:
var endpoint = "<endpoint>";
var topicName = "<topicName>";
var accessKeyName = "RootManageSharedAccessKey"; // this most likely can stay as-is.
var accessKey = "<accessKey>";
var subscription = "<subscription>";
// DONE
Console.WriteLine("Choose an option:");
Console.WriteLine("------------------");
Console.WriteLine("1. SendMessages");
Console.WriteLine("2. ReceiveMessages");
Console.WriteLine("------------------\n");
Console.Write("Enter choice: ");
var sbcs = GetConnectionStringBuilder(endpoint, topicName, accessKeyName, accessKey);
switch (Console.ReadLine())
{
case "1":
SendMessages.MainAsync(sbcs).GetAwaiter().GetResult();
break;
case "2":
ReceiveMessages.MainAsync(sbcs, subscription).GetAwaiter().GetResult();
break;
default:
break;
}
Console.WriteLine("Done, press ANY KEY to exit.");
Console.ReadKey();
}
static ServiceBusConnectionStringBuilder GetConnectionStringBuilder(string endpoint, string topicName, string accessKeyName, string accessKey, TransportType transportType = TransportType.AmqpWebSockets)
{
return new ServiceBusConnectionStringBuilder(endpoint, topicName, accessKeyName, accessKey, transportType);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ManejadorArmas_controller : MonoBehaviour
{
public bool armado;
public GameObject ArmaActual;
public float FuerzaDeTiradoDeArma;
public float Torque;
public bool HabilitadoTirar = false;
private bool armadoAntes; //variable para saber cuando es la primera vez que se arma.
private GameObject ManoASeguir;
private bool banderaPrimerTiradaArma;
private GameObject Player;
void Start()
{
banderaPrimerTiradaArma = false;
Player = this.transform.root.gameObject;
}
void Update()
{
if (armado)
{
ArmaActual.transform.position = ManoASeguir.transform.position;
if (armadoAntes == false) //primera vez que se arma.
{
armadoAntes = true;
ArmaActual.gameObject.transform.localScale = new Vector3(Mathf.Abs(ArmaActual.gameObject.transform.localScale.x), Mathf.Abs(ArmaActual.gameObject.transform.localScale.y), Mathf.Abs(ArmaActual.gameObject.transform.localScale.z));
ArmaActual.gameObject.transform.rotation = new Quaternion(0, 0, 0, 0);
ArmaActual.gameObject.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;
//le cambio el tipo de rigidbody y le anulo el poligon Collider.
}
if (Player.GetComponent<Player1_controller>().joestick.RB && banderaPrimerTiradaArma == false && Player.GetComponent<Player_Ataques>().doingEscudo == false && Player.GetComponent<Player_Ataques>().doingChidori == false && Player.GetComponent<Player_Ataques>().doingKunais == false && Player.GetComponent<Player_Ataques>().doingPiñas == false)
{
ArmaActual.GetComponent<arma_general_script>().Invocador.GetComponent<Animator>().SetTrigger("TiraArma");
banderaPrimerTiradaArma = true;
}
}
if (HabilitadoTirar)
{
TirarArma();
HabilitadoTirar = false; // se activa mediante el animador.
banderaPrimerTiradaArma = false;
}
}
public void Armar(GameObject Arma)
{
ArmaActual = Arma;
armado = true;
ArmaActual.GetComponent<arma_general_script>().puedeDañar = true;
ArmaActual.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
ArmaActual.GetComponent<PolygonCollider2D>().enabled = false;
ManoASeguir = this.gameObject.transform.root.gameObject.transform.Find("cuerpo").gameObject.transform.Find("mano DER").gameObject;
ArmaActual.transform.position = ManoASeguir.transform.position;
ArmaActual.transform.SetParent(ManoASeguir.transform);
}
public void TirarArma()
{
armado = false;
armadoAntes = false;
ManoASeguir = null;
ArmaActual.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
ArmaActual.GetComponent<PolygonCollider2D>().enabled = true;
//tira el arma.
ArmaActual.transform.SetParent(null);
ArmaActual.GetComponent<arma_general_script>().lanzada = true;
if (ArmaActual.GetComponent<arma_general_script>().Invocador.GetComponent<Player1_controller>().mirandoDerecha)
{
ArmaActual.GetComponent<Rigidbody2D>().velocity = new Vector2(FuerzaDeTiradoDeArma, 0);
ArmaActual.GetComponent<Rigidbody2D>().AddTorque(Torque);
}
else
{
ArmaActual.GetComponent<Rigidbody2D>().velocity = new Vector2(-FuerzaDeTiradoDeArma, 0);
ArmaActual.GetComponent<Rigidbody2D>().AddTorque(-Torque);
}
ArmaActual.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
Invoke("TiradaLogica", 1f);
}
private void TiradaLogica()
{
ArmaActual.GetComponent<arma_general_script>().agarrada = false;
}
public void SueltaArma()
{//todabia no se usa.
Debug.Log(this.gameObject.transform.root.name + "TIRANDO ARMA = " + this.ArmaActual.name);
armado = false;
armadoAntes = false;
ManoASeguir = null;
ArmaActual.GetComponent<arma_general_script>().lanzada = true;
ArmaActual.GetComponent<arma_general_script>().agarrada = false;
ArmaActual.GetComponent<arma_general_script>().NoSePuedeAgarrar = 3f;
ArmaActual.GetComponent<Rigidbody2D>().velocity = new Vector2(0, FuerzaDeTiradoDeArma );
ArmaActual.GetComponent<Rigidbody2D>().AddTorque(Torque);
ArmaActual.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.None;
}
}
|
using UnityEngine;
using System;
using System.Collections.Generic;
public static class Utils
{
public static class Midi {
public static float midiIntToFloat(int midiValue){
return Clamp( ((float)midiValue / 127.0f), 0.0f, 1.0f);
}
public static int floatToMidiInt(float fValue){
return Clamp( (int)(fValue * 127), 0, 127);
}
}
public static float Scale(float value, float min, float max){
return (value - min) / (max - min);
//return Remap(value, 0.0f, 1.0f, min, max);
}
public static int Clamp(int value, int min, int max)
{
return (value < min) ? min : (value > max) ? max : value;
}
public static float Clamp(float value, float min, float max)
{
return (value < min) ? min : (value > max) ? max : value;
}
public static float Remap (float value, float from1, float to1, float from2, float to2) {
return (value - from1) / (to1 - from1) * (to2 - from2) + from2;
}
public static string ReplaceWhitespaceSlashes(string input){
string output = input.Replace("/", "-");
output = input.Replace(" ", "_");
return output;
}
//Generates points on the surface of a sphere
public static Vector3[] PointsOnSphere(int n, float scale){
return PointsOnSphere(n, scale, 0.0f);
}
public static Vector3[] PointsOnSphere(int n, float scale, float randomness){
Vector3[] pts = new Vector3[n];
float inc = Mathf.PI * (3 - Mathf.Sqrt(5));
float off = 2.0f / n;
float x, y, z, r, phi;
float randAngle;
randAngle = (randomness != 0.0f) ? UnityEngine.Random.value * randomness : 1.0f;
for(int k = 0; k < n; k++){
y = k * off -1 + (off / 2);
r = Mathf.Sqrt(1 - y * y);
phi = k * inc * randAngle;
x = Mathf.Cos(phi) * r;
z = Mathf.Sin (phi) * r;
pts[k] = new Vector3(x, y, z) * scale;
}
return pts;
}
/// <summary>
/// Takes an array of input coordinates used to define a Catmull-Rom spline, and then
/// samples the resulting spline according to the specified sample count (per span),
/// populating the output array with the newly sampled coordinates. The returned boolean
/// indicates whether the operation was successful (true) or not (false).
/// NOTE: The first and last points specified are used to describe curvature and will be dropped
/// from the resulting spline. Duplicate them if you wish to include them in the curve.
/// </summary>
public static bool CatmullRom(Vector3[] inCoordinates, out Vector3[] outCoordinates, int samples)
{
if (inCoordinates.Length < 4)
{
outCoordinates = null;
return false;
}
List<Vector3> results = new List<Vector3>();
for (int n = 1; n < inCoordinates.Length - 2; n++)
for (int i = 0; i < samples; i++)
results.Add(PointOnCurve(inCoordinates[n - 1], inCoordinates[n], inCoordinates[n + 1], inCoordinates[n + 2], (1f / samples) * i ));
results.Add(inCoordinates[inCoordinates.Length - 2]);
outCoordinates = results.ToArray();
return true;
}
/// <summary>
/// Return a point on the curve between P1 and P2 with P0 and P4 describing curvature, at
/// the normalized distance t.
/// </summary>
public static Vector3 PointOnCurve(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
Vector3 result = new Vector3();
float t0 = ((-t + 2f) * t - 1f) * t * 0.5f;
float t1 = (((3f * t - 5f) * t) * t + 2f) * 0.5f;
float t2 = ((-3f * t + 4f) * t + 1f) * t * 0.5f;
float t3 = ((t - 1f) * t * t) * 0.5f;
result.x = p0.x * t0 + p1.x * t1 + p2.x * t2 + p3.x * t3;
result.y = p0.y * t0 + p1.y * t1 + p2.y * t2 + p3.y * t3;
result.z = p0.z * t0 + p1.z * t1 + p2.z * t2 + p3.z * t3;
return result;
}
/*
* Color converters
*/
public static string intToHex(int input){
return input.ToString("X");
}
public static Color intToColor(int input){
return new Color( (float)((input >> 16) & 255) / 255, (float)((input >> 8) & 255) / 255, (float)((input) & 255) / 255 );
}
public static Vector3[] BuildArcPositions(float radius, float arcLength, int numPoints){
return BuildArcPositions(radius, arcLength, numPoints, 0.0f, false);
}
public static Vector3[] BuildArcPositions(float radius, float arcLength, int numPoints, float minAngle, bool centered){
Vector3[] points = new Vector3[numPoints];
float angleInc = arcLength / numPoints;
if(angleInc < minAngle) angleInc = minAngle;
float startAngle = (centered) ? ((numPoints-1) * angleInc) * 0.5f : 0.0f;
for(int i =0; i < numPoints; i++){
//Move this to the carousel
points[i] = new Vector3(
Mathf.Cos((i * angleInc) - (startAngle)) * radius,
Mathf.Sin((i * angleInc) - (startAngle)) * radius,
0.0f
);
}
return points;
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using DashBoard.Data.Enums;
namespace DashBoard.Data.Entities
{
public class DomainModel
{
//Pamokele: Value types(such as decimal, int, float, DateTime) are inherently required and don't need the [Required] attribute.
//[BindNever] //padeda nuo over-posting attacks apsisaugot. Neleidzia ideti i DB. Sitas neveikia, tik formose kaip supratau. Ir taip neleidzia nes error: Cannot insert explicit value for identity column in table 'Domains' when IDENTITY_INSERT is set to OFF.
public int Id { get; set; }
[Required]
public string Service_Name { get; set; }
[Required]
[Url]
public string Url { get; set; }
[Range(0, 1)]
public ServiceType Service_Type { get; set; } //EF in SQL enums saves as int.
[Range(0, 1)]
public RequestMethod Method { get; set; }
public bool Basic_Auth { get; set; }
public string Auth_User { get; set; }
public string Auth_Password { get; set; } //pagalvoti kaip saugoti PW
public string Parameters { get; set; } //kaip cia parametrus, jei JSON arba XML ?
[Required]
[EmailAddress]
public string Notification_Email { get; set; }
[Range(3000, int.MaxValue, ErrorMessage = "Interval ms value must be more than 3000")]
public int Interval_Ms { get; set; } = 600000; //default, jei nieko neiveda is front-end
public int Latency_Threshold_Ms { get; set; } = 60000;
public bool Active { get; set; } = true; //Default reiksme
public bool Deleted { get; set; }
public Guid Team_Key { get; set; }
public int Created_By { get; set; } //Useris negali keisti
public int Modified_By { get; set; } //Useris negali keisti
public DateTime Date_Created { get; set; } = DateTime.Now; //Useris negali keisti
public DateTime Date_Modified { get; set; } = DateTime.Now; //Useris negali keisti
public DateTime Last_Fail { get; set; } //Useris negali keisti
public DateTime Last_Notified { get; set; }
}
}
|
using AspCoreBl.Model;
using AspCoreBl.ModelDTO;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace AspCoreBl.Interfaces
{
public interface IApplicationUserRepository
{
Task<KeyValuePair<int, string>> PostApplicationUser(IdentityUserDTO dto);
Task<bool> UserExist(IdentityUserDTO dto);
Task<KeyValuePair<string, LoginSuccessViewModel>> LoginAsync(IdentityUserDTO dto);
Task<bool> ConfirmEmailAsync(string email, string code);
Task<bool> ForgotPasswordAsync(string email);
Task<KeyValuePair<int, LoginSuccessViewModel>> ResetPasswordAsync(ResetPasswordViewModel model);
Task<KeyValuePair<int, object>> ChangePasswordAsync(ChangePasswordViewModel model, ApplicationUser user);
Task<ApplicationUser> GetSingleAsyncs(Expression<Func<ApplicationUser, bool>> predicate, params Expression<Func<ApplicationUser, object>>[] includeProperties);
Task LogoutAsync();
Task<KeyValuePair<string, LoginSuccessViewModel>> ExternalLoginAsync(SocialUser dto);
}
}
|
using System;
using System.Linq;
namespace _01_Matrix_of_Palindromes
{
public class _01_Matrix_of_Palindromes
{
public static void Main()
{
var alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
var dimentions = Console.ReadLine().Split().Select(int.Parse).ToArray();
var rows = dimentions[0];
var cols = dimentions[1];
var matrix = new string[rows][];
for (int i = 0; i < rows; i++)
{
matrix[i] = new string[cols];
var index = i;
for (int j = 0; j < cols; j++)
{
var charString = alphabet[i].ToString() + alphabet[index].ToString() + alphabet[i].ToString();
matrix[i][j] = charString;
index++;
}
}
foreach (var row in matrix)
{
Console.WriteLine(string.Join(" ", row));
}
}
}
}
|
using System;
using System.IO;
namespace VoxelSpace.Resources {
public interface IResourceLoader {
/// <summary>
/// Can this loader load this resource?
/// </summary>
bool CanLoad<T>() where T : class;
T Load<T>(string name) where T : class;
}
public abstract class ResourceLoader<T> : IResourceLoader where T : class {
bool IResourceLoader.CanLoad<U>() where U : class => typeof(U) == typeof(T);
U IResourceLoader.Load<U>(string name) where U : class {
return Load(name) as U;
}
public abstract T Load(string name);
}
} |
using Ninject;
using Ninject.Modules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nailhang.Display.NetPublicSearch
{
public class Module : NinjectModule
{
public override void Load()
{
Kernel.Bind<Processing.NetSearch>()
.ToSelf();
Kernel.Bind<Base.INetSearch>().To<Processing.NetSearch>()
.InSingletonScope();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace IRAP.Client.Actions
{
public interface IUDFActionFactory
{
IUDFAction CreateAction(XmlNode actionParams, ExtendEventHandler extendAction);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApp6.Core;
namespace ConsoleApp6.Actors
{
public class ShopKeeper : Actor
{
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using CommonLibrary.Framework;
using CommonLibrary.Framework.Tracing;
namespace EpisodeGrabber.Library.Entities {
public abstract class EntityBase {
public bool IsAdult { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public int ID { get; set; }
[XmlAttribute]
public string Name { get; set; }
public string AlternateName { get; set; }
public string Description { get; set; }
public string UniqueID { get { return this.ID.ToString(); } }
public List<Image> Images { get; set; }
[XmlIgnore]
public string Path { get; set; }
public List<string> Genres { get; set; }
public List<string> Actors { get; set; }
public EntityBase() {
this.ID = 0;
this.Images = new List<Image>();
this.Actors = new List<string>();
this.Genres = new List<string>();
}
}
} |
namespace CustomerApp.DataAccess.Repositories
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading.Tasks;
using DataAccess;
using Models;
[Export(typeof(ICustomerRepository))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class CustomerRepository : ICustomerRepository
{
private readonly ICustomerContext _context;
[ImportingConstructor]
public CustomerRepository(ICustomerContext context)
{
_context = context;
}
public IEnumerable<CustomerSummary> GetCustomerSummaries()
{
return _context.Customers
.Select(Mapper.AsCustomerSummary)
.ToArray();
}
public async Task<(Result, CustomerDetail)> GetCustomerDetail(int customerId)
{
var customer = await _context.Customers.FindAsync(customerId);
return customer is null
? (Result.NotFound, null)
: (Result.Completed, customer.ToModel());
}
public async Task<Result> UpdateCustomerStatus(int customerId, Status newStatus)
{
var customer = await _context.Customers.FindAsync(customerId);
if (customer is null)
{
return Result.NotFound;
}
customer.Status = newStatus;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(customerId))
{
return Result.NotFound;
}
throw;
}
return Result.Completed;
}
public async Task<CustomerDetail> AddCustomer(CustomerDetail customerDetail)
{
var customer = customerDetail.ToEntity();
customer.Created = DateTime.Now;
_context.Customers.Add(customer);
await _context.SaveChangesAsync();
return customer.ToModel();
}
public async Task<(Result, CustomerDetail)> DeleteCustomer(int customerId)
{
var customer = await _context.Customers.FindAsync(customerId);
if (customer == null)
{
return (Result.NotFound, null);
}
_context.Customers.Remove(customer);
await _context.SaveChangesAsync();
return (Result.Completed, customer.ToModel());
}
public IEnumerable<NoteDetail> GetCustomerNotes(int customerId)
{
return _context.Notes
.Where(n => n.CustomerId == customerId)
.Select(Mapper.ToNoteDetails)
.ToArray();
}
private bool CustomerExists(int id)
{
return _context.Customers.Count(e => e.Id == id) > 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace WarCardGame
{
public sealed class Game
{
readonly Deck[] playDecks;
int rounds, wars;
public Game(Deck player1, Deck player2)
=> playDecks = new[] { player1, player2 };
public int RoundsPlayed
=> rounds;
public int WarsPlayed
=> wars;
public int PlayToFinish()
{
while (playDecks.All(d => d.HasCards)) {
PlayRound();
++rounds;
}
return (playDecks[0].HasCards ? 1 : 2);
}
void PlayRound()
{
var playedCards = new[] { playDecks[0].TakeCard(), playDecks[1].TakeCard() };
int winnerIndex;
if (playedCards[0] == playedCards[1]) {
var warCards = new List<ushort>();
winnerIndex = War(warCards);
playDecks[winnerIndex].AddCards(warCards);
}
else {
winnerIndex = CalculateWinner(playedCards);
}
playDecks[winnerIndex].AddCards(playedCards);
}
int War(List<ushort> cards)
{
int takeCount = CalculateWarCardCount();
int winnerIndex;
if (takeCount > 0) {
var cardsInPlay = new[] { playDecks[0].TakeCards(takeCount), playDecks[1].TakeCards(takeCount) };
ushort player1UpCard = cardsInPlay[0][takeCount - 1];
ushort player2UpCard = cardsInPlay[1][takeCount - 1];
if (player1UpCard == player2UpCard) {
winnerIndex = War(cards);
}
else {
winnerIndex = CalculateWinner(new[] { player1UpCard, player2UpCard });
}
// ensures winner cards are added back to the deck first
cards.AddRange(cardsInPlay[winnerIndex]);
cards.AddRange(cardsInPlay[Math.Abs(winnerIndex - 1 )]);
}
else {
winnerIndex = CalculateWinner(playDecks);
}
++wars;
return winnerIndex;
}
static int CalculateWinner(ushort[] playedCards)
=> (playedCards[0] > playedCards[1] ? 0 : 1);
static int CalculateWinner(Deck[] playDecks)
{
bool player1HasCards = playDecks[0].HasCards;
bool player2HasCards = playDecks[1].HasCards;
if (player1HasCards == player2HasCards) {
throw new ApplicationException("Game ends in a tie.");
}
else {
return (player1HasCards ? 0 : 1);
}
}
int CalculateWarCardCount()
{
var maxCards = Math.Min(playDecks[0].CardCount, playDecks[1].CardCount);
const int DesiredCardCount = 4;
return (maxCards >= DesiredCardCount ? DesiredCardCount : maxCards);
}
}
}
|
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.PageLocation.Models;
using DFC.ServiceTaxonomy.PageLocation.ViewModels;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentManagement.Display.Models;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using System.Linq;
using OrchardCore.Mvc.ModelBinding;
using YesSql;
using OrchardCore.ContentManagement;
using DFC.ServiceTaxonomy.PageLocation.Indexes;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using OrchardCore.ContentManagement.Records;
using System;
using DFC.ServiceTaxonomy.PageLocation.Constants;
using DFC.ServiceTaxonomy.Taxonomies.Helper;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement.Utilities;
namespace DFC.ServiceTaxonomy.PageLocation.Drivers
{
public class PageLocationPartDisplayDriver : ContentPartDisplayDriver<PageLocationPart>
{
private readonly string UrlNamePattern = "^[A-Za-z0-9_-]+$";
private readonly string RedirectLocationUrlNamePattern = "^[A-Za-z0-9\\/_-]+$";
private readonly ISession _session;
private readonly ITaxonomyHelper _taxonomyHelper;
public PageLocationPartDisplayDriver(ISession session, ITaxonomyHelper taxonomyHelper)
{
_session = session;
_taxonomyHelper = taxonomyHelper;
}
public override IDisplayResult Edit(PageLocationPart pageLocationPart, BuildPartEditorContext context)
{
return Initialize<PageLocationPartViewModel>("PageLocationPart_Edit", model =>
{
model.UrlName = pageLocationPart.UrlName;
model.DefaultPageForLocation = pageLocationPart.DefaultPageForLocation;
model.FullUrl = pageLocationPart.FullUrl;
model.RedirectLocations = pageLocationPart.RedirectLocations;
model.PageLocationPart = pageLocationPart;
model.ContentItem = pageLocationPart.ContentItem;
model.Settings = context.TypePartDefinition.GetSettings<PageLocationPartSettings>();
});
}
public override async Task<IDisplayResult> UpdateAsync(PageLocationPart model, IUpdateModel updater, UpdatePartEditorContext context)
{
await updater.TryUpdateModelAsync(model, Prefix, t => t.UrlName, t => t.DefaultPageForLocation, t => t.RedirectLocations, t => t.FullUrl);
await ValidateAsync(model, updater);
return await EditAsync(model, context);
}
private async Task ValidateAsync(PageLocationPart pageLocation, IUpdateModel updater)
{
bool urlNameIsValid = true;
if (urlNameIsValid && string.IsNullOrWhiteSpace(pageLocation.UrlName))
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.UrlName), "A value is required for 'UrlName'");
urlNameIsValid = false;
}
if (urlNameIsValid && !Regex.IsMatch(pageLocation.UrlName!, UrlNamePattern))
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.UrlName), $"'UrlName' contains invalid characters. Valid characters include A-Z, 0-9, '-' and '_'.");
urlNameIsValid = false;
}
var otherContentItems = await _session.Query<ContentItem, PageLocationPartIndex>(x => x.ContentItemId != pageLocation.ContentItem.ContentItemId).ListAsync();
if (otherContentItems.Any(x => ((string)x.Content.PageLocationPart.FullUrl).Equals(pageLocation.FullUrl, StringComparison.OrdinalIgnoreCase)))
{
var duplicate = otherContentItems.First(x => ((string)x.Content.PageLocationPart.FullUrl).Equals(pageLocation.FullUrl, StringComparison.OrdinalIgnoreCase));
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.UrlName), $"There is already a {duplicate.ContentType.CamelFriendly()} with this URL Name at the same Page Location. Please choose a different URL Name, or change the Page Location.");
}
var redirectLocations = pageLocation.RedirectLocations?.Split("\r\n").ToList();
if (redirectLocations?.Any() ?? false)
{
foreach (var otherContentItem in otherContentItems)
{
List<string> otherContentItemRedirectLocations = ((string)otherContentItem.Content.PageLocationPart.RedirectLocations)?.Split("\r\n").ToList() ?? new List<string>();
var redirectConflict = otherContentItemRedirectLocations.FirstOrDefault(x => redirectLocations.Any(y => y.Equals(x, StringComparison.OrdinalIgnoreCase)));
if (redirectConflict != null)
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.RedirectLocations), $"'{redirectConflict}' has already been used as a redirect location for another page.'");
}
var fullUrlConflict = redirectLocations.FirstOrDefault(x => x.Equals((string)otherContentItem.Content.PageLocationPart.FullUrl, StringComparison.OrdinalIgnoreCase));
if (fullUrlConflict != null)
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.RedirectLocations), $"'{fullUrlConflict}' has already been used as the URL for another page.'");
}
}
for (var i = 0; i < redirectLocations.Count; i++)
{
var redirectLocation = redirectLocations[i];
var otherRedirectLocations = redirectLocations.Where((item, index) => index != i);
if (otherRedirectLocations.Any(x => x.Equals(redirectLocation, StringComparison.OrdinalIgnoreCase)))
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.RedirectLocations), $"Redirect Location '{redirectLocation}' has been duplicated.");
}
if (!Regex.IsMatch(redirectLocation, RedirectLocationUrlNamePattern))
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.RedirectLocations), $"Redirect Location '{redirectLocation}' contains invalid characters. Valid characters include A-Z, 0-9, '-' and '_'.");
}
}
}
if (!string.IsNullOrWhiteSpace(pageLocation.FullUrl))
{
if (otherContentItems.Any(x => ((string)x.Content.PageLocationPart.RedirectLocations)?.Split("\r\n").Any(r => r.Trim('/').Equals(pageLocation.FullUrl.Trim('/'), StringComparison.OrdinalIgnoreCase)) ?? false))
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.FullUrl), "Another page is already using this URL as a redirect location");
}
//todo: would be better to use ContentType to lookup PageLocations
ContentItem? taxonomy = await _session.Query<ContentItem, ContentItemIndex>(x =>
x.ContentType == ContentTypes.Taxonomy && x.DisplayText == DisplayTexts.PageLocations && x.Latest && x.Published).FirstOrDefaultAsync();
if (taxonomy != null)
{
RecursivelyBuildUrls(JObject.FromObject(taxonomy));
if (_pageLocations.Any(x => x.Equals(pageLocation.FullUrl.Trim('/'), StringComparison.OrdinalIgnoreCase)))
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.FullUrl), "This URL has already been used as a Page Location");
}
if (redirectLocations != null)
{
foreach (var redirectLocation in redirectLocations)
{
if (_pageLocations.Any(x => x.Equals(redirectLocation.Trim('/'), StringComparison.OrdinalIgnoreCase)))
{
updater.ModelState.AddModelError(Prefix, nameof(pageLocation.RedirectLocations), $"Redirect Location '{redirectLocation}' has already been used as a Page Location.");
}
}
}
}
}
}
private readonly List<string> _pageLocations = new List<string>();
private void RecursivelyBuildUrls(JObject taxonomy)
{
JArray? terms = _taxonomyHelper.GetTerms(taxonomy);
if (terms == null)
return;
//todo: look at this
#pragma warning disable S3217
foreach (JObject term in terms)
#pragma warning restore S3217
{
_pageLocations.Add(_taxonomyHelper.BuildTermUrl(term, taxonomy));
RecursivelyBuildUrls(term);
}
}
}
}
|
using System.Collections.Generic;
using NHibernate.Envers;
using NHibernate.Envers.Query;
using Profiling2.Domain;
using Profiling2.Domain.Contracts.Queries.Audit;
using Profiling2.Domain.Prf.Units;
namespace Profiling2.Infrastructure.Queries.Audit
{
public class OperationRevisionsQuery : NHibernateAuditQuery, IOperationRevisionsQuery
{
public IList<AuditTrailDTO> GetOperationRevisions(Operation op)
{
IList<object[]> objects = AuditReaderFactory.Get(Session).CreateQuery()
.ForRevisionsOfEntity(typeof(Operation), false, true)
.Add(AuditEntity.Id().Eq(op.Id))
.GetResultList<object[]>();
return this.AddDifferences<Operation>(this.TransformToDto(objects));
}
public IList<AuditTrailDTO> GetOperationCollectionRevisions<T>(Operation op)
{
IList<object[]> objects = AuditReaderFactory.Get(Session).CreateQuery()
.ForRevisionsOfEntity(typeof(T), false, true)
.Add(AuditEntity.Property("Operation").Eq(op))
.GetResultList<object[]>();
return this.AddDifferences<T>(this.TransformToDto(objects));
}
}
}
|
using CameraAbstractClass.Cameras;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CameraAbstractClass
{
class Program
{
static void Main(string[] args)
{
//instane IphoneCamera
Console.WriteLine("_______");
IphoneCamera iphoneCamera = new IphoneCamera("Iphone's Camera", TypeCamera.FRONT, false);
Console.WriteLine("***IPHONE*****");
//with getDescrption non override in IphoneCamera commented
Console.WriteLine($"result {iphoneCamera.GetDescription("Iphone's Camera", TypeCamera.FRONT)} is activate ? {iphoneCamera.Activate()} ");
//with getDescription override in IphoneCamera uncommented
//Console.WriteLine($"result {iphoneCamera.GetDescription("Iphone's Camera", TypeCamera.FRONT)} is activate ? {iphoneCamera.Activate()} ");
Console.WriteLine($"result after deactivated {iphoneCamera.GetDescription("Iphone's Camera", TypeCamera.FRONT)} is activate ? {iphoneCamera.DeActivate()} ");
Console.WriteLine("********");
Console.WriteLine($"result after setCamera {iphoneCamera.SetCamera()}");
Console.WriteLine("********");
Console.WriteLine($"result after Charge Camera {iphoneCamera.ChargeCamera()}");
Console.WriteLine("********");
Console.WriteLine($"result after Take Picture {iphoneCamera.TakePicture()}");
Console.WriteLine("_______");
//instane Samsung Camera
Console.WriteLine("***SAMSUNG*****");
SamsungCamera samsungCamera = new SamsungCamera("Samsung Camera", TypeCamera.REAR, false);
//with getDescrption non override in IphoneCamera commented
Console.WriteLine($"result {samsungCamera.GetDescription("Samsung Camera", TypeCamera.REAR)} is activate ? {samsungCamera.Activate()} ");
//with getDescription override in samsungCamera uncommented
//Console.WriteLine($"result {samsungCamera.GetDescription("Samsung's Camera", TypeCamera.FRONT)} is activate ? {samsungCamera.Activate()} ");
// Console.WriteLine($"result after deactivated {samsungCamera.GetDescription("Samsung Camera", TypeCamera.REAR)} is activate ? {samsungCamera.DeActivate()} ");
// Console.WriteLine("********");
Console.WriteLine($"result after setCamera {samsungCamera.SetCamera()}");
Console.WriteLine("********");
Console.WriteLine($"result after Charge Camera {samsungCamera.ChargeCamera()}");
Console.WriteLine("********");
Console.WriteLine($"result after Take Picture {samsungCamera.TakePicture()}");
Console.WriteLine("********");
//istanziate nocamera
Console.WriteLine("***NOKIA NO CAMERA*****");
NoCamera nokiaNocamera = new NoCamera("Nokia no Camera", TypeCamera.NOCAMERA, false);
//with getDescrption non override in IphoneCamera commented
Console.WriteLine($"result {nokiaNocamera.GetDescription("Nokia no Camera", TypeCamera.NOCAMERA)} is activate ? {nokiaNocamera.Activate()} ");
//with getDescription override in samsungCamera uncommented
Console.ReadLine();
}
}
}
|
using Microsoft.AspNetCore.Identity;
namespace WorkScheduleManagement.Data.Entities.Roles
{
public class ApplicationRole : IdentityRole
{
// public int NumberOfWorkingHours { get; set; }
}
} |
using ExitGames.Client.Photon;
using Photon.Pun;
using Photon.Realtime;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
[DefaultExecutionOrder(-1000)]
public class ContuConnectionHandler : ConnectionHandler, IConnectionCallbacks, IMatchmakingCallbacks, ILobbyCallbacks, IInRoomCallbacks, IOnEventCallback
{
private static ContuConnectionHandler instance;
[SerializeField] private AppSettings appSettings = new AppSettings();
State currentState = State.ExpectingRegionList;
public event System.Action RoomJoined;
public event System.Action<Player> PlayerEnteredRoom, PlayerLeftRoom;
public event System.Action StateChanged;
public event System.Action<List<RoomInfo>> RoomListUpdate;
public State CurrentState { get => currentState; }
public static ContuConnectionHandler Instance { get => instance; }
protected override void Awake()
{
if(instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
}
base.Awake();
}
public void Start()
{
Client = new LoadBalancingClient(ConnectionProtocol.Udp);
Client.AddCallbackTarget(this);
if (!this.Client.ConnectUsingSettings(appSettings))
{
Debug.LogError("Error while connecting");
}
StartFallbackSendAckThread();
}
public void Update()
{
Client.Service();
}
public void SetState(State newState)
{
currentState = newState;
StateChanged?.Invoke();
}
public bool TryCreateRoom(string name)
{
if (CurrentState != State.ReadyForRoom)
return false;
EnterRoomParams roomParams = new EnterRoomParams();
roomParams.RoomName = name;
return Client.OpCreateRoom(roomParams);
}
public void RequestRooms()
{
}
public void OnConnected()
{
}
public void OnConnectedToMaster()
{
Debug.Log("Connected To Master");
SetState(State.ReadyForRoom);
Client.OpJoinLobby(TypedLobby.Default);
}
public void OnDisconnected(DisconnectCause cause)
{
Debug.Log(" Disconnected (" + cause + ")");
}
public void OnCustomAuthenticationResponse(Dictionary<string, object> data)
{
}
public void OnCustomAuthenticationFailed(string debugMessage)
{
}
public void OnRegionListReceived(RegionHandler regionHandler)
{
Debug.Log("Region List Received");
SetState(State.ConnectingToMaster);
regionHandler.PingMinimumOfRegions(this.OnRegionPingCompleted, null);
}
public void OnRoomListUpdate(List<RoomInfo> roomList)
{
Debug.Log("Room List Update: " + roomList.Count + " rooms");
RoomListUpdate?.Invoke(roomList);
}
public void OnLobbyStatisticsUpdate(List<TypedLobbyInfo> lobbyStatistics)
{
}
public void OnJoinedLobby()
{
Debug.Log("In Lobby");
}
public void OnLeftLobby()
{
}
public void OnFriendListUpdate(List<FriendInfo> friendList)
{
}
public void OnCreatedRoom()
{
}
public void OnCreateRoomFailed(short returnCode, string message)
{
}
public void OnJoinedRoom()
{
SetState(State.InRoom);
RoomJoined?.Invoke();
}
public void OnJoinRoomFailed(short returnCode, string message)
{
}
public void OnJoinRandomFailed(short returnCode, string message)
{
}
public void OnLeftRoom()
{
SetState(State.ReadyForRoom);
}
/// <summary>A callback of the RegionHandler, provided in OnRegionListReceived.</summary>
/// <param name="regionHandler">The regionHandler wraps up best region and other region relevant info.</param>
private void OnRegionPingCompleted(RegionHandler regionHandler)
{
Debug.Log("RegionPingSummary: " + regionHandler.SummaryToCache);
Debug.Log("OnRegionPingCompleted " + regionHandler.BestRegion);
Client.ConnectToRegionMaster(regionHandler.BestRegion.Code);
}
public void OnPlayerEnteredRoom(Player newPlayer)
{
Debug.Log(newPlayer + " Joined the room");
PlayerEnteredRoom?.Invoke(newPlayer);
}
public void OnPlayerLeftRoom(Player otherPlayer)
{
Debug.Log( otherPlayer.NickName + " left the room");
PlayerLeftRoom?.Invoke(otherPlayer);
}
public void OnRoomPropertiesUpdate(Hashtable propertiesThatChanged)
{
}
public void OnPlayerPropertiesUpdate(Player targetPlayer, Hashtable changedProps)
{
}
public void OnMasterClientSwitched(Player newMasterClient)
{
Debug.Log("MasterClient Switched");
}
public void OnEvent(EventData photonEvent)
{
switch (photonEvent.Code)
{
case (byte)ContuEventCode.LoadScene:
EventDrivenLoadScene((int)photonEvent.CustomData);
break;
}
}
public void EventDrivenLoadScene(int index)
{
SceneManager.LoadScene(index);
}
public enum State
{
ExpectingRegionList,
ConnectingToMaster,
ReadyForRoom,
InRoom,
InGames
}
} |
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MoneyShare.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MoneyShare.Repos
{
public class MemberServices : IMemberServices
{
private ApplicationDbContext _dbContext;
private IEmailService _emailService;
public static Random _rand = new Random();
private UserManager<MemberModel> _userManager;
public MemberServices(ApplicationDbContext dbContext, IEmailService emailService, UserManager<MemberModel> userManager)
{
_dbContext = dbContext;
_emailService = emailService;
_userManager = userManager;
}
public async Task SendTwoFactorCodeAsync(MemberModel member)
{
int code = _rand.Next(0, 999999);
member.TwoFactorCode = code.ToString("000000");
member.TwoFactorCodeDateTime = DateTime.Now;
await _userManager.UpdateAsync(member);
_emailService.EmailTwoFactorCode(member);
}
public void SendResetLink(MemberModel member, String link)
{
_emailService.EmailForgotPassword(member, link);
}
public bool ValidateTwoFactorCodeAsync(MemberModel member, string code)
{
if(member.TwoFactorEnabled && member.TwoFactorCodeDateTime!=null && !string.IsNullOrEmpty(member.TwoFactorCode))
{
TimeSpan codeTimeSpan = DateTime.Now - member.TwoFactorCodeDateTime;
if (codeTimeSpan <= TimeSpan.FromMinutes(5))
{
if(code == member.TwoFactorCode)
{
member.TwoFactorCode = "";
_userManager.UpdateAsync(member);
return true;
}
}
}
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AngularSPAWebAPI.Data;
using AngularSPAWebAPI.Models;
using AngularSPAWebAPI.Models.DatabaseModels.Inventory;
using AngularSPAWebAPI.Models.DatabaseModels.Inventory.PostModels;
using AngularSPAWebAPI.Services;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
namespace AngularSPAWebAPI.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme, Policy = "Manage Accounts")]
public class ProductManagerController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
private readonly ApplicationDbContext _context;
private readonly IEmailService _emailService;
public ProductManagerController(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
SignInManager<ApplicationUser> signInManager,
ILogger<IdentityController> logger, ApplicationDbContext context, IEmailService emailService)
{
_userManager = userManager;
_roleManager = roleManager;
_signInManager = signInManager;
_logger = logger;
_context = context;
_emailService = emailService;
}
[AllowAnonymous]
[HttpGet]
public async Task<IActionResult> TestType()
{
if (ModelState.IsValid)
{
var products = await _context.SubProducts.OfType<UnitProduct>().ToListAsync();
return Ok(products[0].CalculatePrice());
}
return BadRequest();
}
[AllowAnonymous]
[HttpGet("Productcategory")]
public async Task<IActionResult> GetProductcategory()
{
if (ModelState.IsValid)
{
List<ProductCategory> pcs = await _context.productCategories.ToListAsync();
return Ok(pcs);
}
return BadRequest();
}
[AllowAnonymous]
[HttpPost("Productcategory")]
public async Task<IActionResult> Productcategory([FromBody] ProductCategory pc)
{
if (ModelState.IsValid)
{
await _context.productCategories.AddAsync(pc);
await _context.SaveChangesAsync();
return Ok(pc);
}
return BadRequest();
}
[AllowAnonymous]
[HttpPost("Product/{type}")]
public async Task<IActionResult> PostProduct([FromBody] CreateSubProduct subproduct, [FromRoute] string type)
{
if (ModelState.IsValid)
{
ProductCategory pc;
BaseSubProduct sub;
if (type == "unit")
{
sub = new UnitProduct()
{
ProductPrice = subproduct.ProductPrice,
Name = subproduct.Name,
Description = subproduct.Description,
UnitCall = subproduct.UnitCall,
UnitMetric = subproduct.UnitMetric,
UnitValue = subproduct.UnitValue
};
}
else
{
sub = new SingleProduct
{
ProductPrice = subproduct.ProductPrice,
Name = subproduct.Name,
Description = subproduct.Description
};
}
if (subproduct.ProductCategoryID != 0)
{
pc = await _context.productCategories.FirstOrDefaultAsync(i => i.ProductCategoryID == subproduct.ProductCategoryID);
sub.ProductCategory = pc;
}
await _context.SubProducts.AddAsync(sub);
await _context.SaveChangesAsync();
return Ok();
}
return BadRequest();
}
}
}
|
namespace Decima.HZD
{
[RTTI.Serializable(0x7520F5D9A86D15E3)]
public class GeneratedQuestSave : RTTIObject, RTTI.ISaveSerializable
{
[RTTI.Member(0, 0x10, "Saving", true)] public GGUUID QuestUUID;
[RTTI.Member(1, 0x20, "Saving", true)] public GGUUID StartUUID;
[RTTI.Member(2, 0x30, "Saving", true)] public GGUUID EndUUID;
[RTTI.Member(3, 0x40, "Saving", true)] public GGUUID SubSectionUUID;
[RTTI.Member(4, 0x50, "Saving", true)] public GGUUID MainObjectiveUUID;
[RTTI.Member(5, 0x60, "Saving", true)] public GGUUID FinishObjectiveUUID;
[RTTI.Member(6, 0x70, "Saving", true)] public GGUUID TriggerUUID;
[RTTI.Member(7, 0x90, "Saving", true)] public GGUUID Recipe;
[RTTI.Member(8, 0xA0, "Saving", true)] public GGUUID TradingItem;
[RTTI.Member(9, 0xB0, "Saving", true)] public StreamingRef<EntityResource> ItemToBuy;
[RTTI.Member(10, 0xD0, "Saving", true)] public GGUUID TurnInLocationUUID;
[RTTI.Member(11, 0xE0, "Saving", true)] public GGUUID MerchantSpawnSetupUUID;
[RTTI.Member(12, 0xF0, "Saving", true)] public Array<StreamingRef<EntityResource>> ItemsToTradeIn;
[RTTI.Member(13, 0x100, "Saving", true)] public Array<int> AmountOfItemsToTradeIn;
public void DeserializeStateObject(SaveState state)
{
state.DeserializeObjectClassMembers(typeof(GeneratedQuestSave), this);
int count = state.ReadVariableLengthOffset();
for (int i = 0; i < count; i++)
{
var guid1 = state.ReadIndexedGUID();
var guid2 = state.ReadIndexedGUID();
}
}
}
} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace PortsScan
{
public class Program
{
private static string _scanIp = "122.114.52.11";
private static List<int> _ports = new List<int>();
private static readonly ConcurrentDictionary<Task, Tuple<TcpClient, int>> Tasks = new ConcurrentDictionary<Task, Tuple<TcpClient, int>>();
private static ConcurrentBag<int> _openPorts = new ConcurrentBag<int>();
public static void Main(string[] args)
{
var ip = GetIp(args);
if (IsIp(ip))
{
_scanIp = ip;
var ports = GetPorts(args);
_ports = ConvertPorts(ports).ToList();
}
while (!IsIp(_scanIp))
{
Console.WriteLine("input ip address");
var input = Console.ReadLine();
if (IsIp(input))
{
_scanIp = input;
}
}
while (!_ports.Any())
{
Console.WriteLine("input ports,can be a range(1-65535) or all(*)");
var input = Console.ReadLine();
_ports = ConvertPorts(input).ToList();
}
Console.WriteLine("Scan...");
//开始扫描
Parallel.ForEach(_ports, (port, state) =>
{
var tcpClient = new TcpClient();
try
{
var task = tcpClient.ConnectAsync(_scanIp, port);
Tasks.TryAdd(task, new Tuple<TcpClient, int>(tcpClient, port));
//task.Wait();
//if (tcpClient.Connected)
//{
// _openPorts.Add(port);
//}
}
catch
{
// ignored
}
//finally
//{
// tcpClient.Dispose();
//}
});
while (Tasks.Any())
{
var over = new List<Task>();
foreach (var tcpClient in Tasks)
{
var task = tcpClient.Key;
if (task.IsCompleted || task.IsCanceled || task.IsFaulted)
{
if (tcpClient.Value.Item1.Connected)
{
_openPorts.Add(tcpClient.Value.Item2);
Console.Write($"{tcpClient.Value.Item2} ");
}
}
}
foreach (var task in over)
{
Tuple<TcpClient, int> r;
if (Tasks.TryRemove(task, out r))
{
r.Item1.Dispose();
}
}
}
//Console.WriteLine("result:");
//var opens = _openPorts.ToList().OrderBy(s => s).ToList();
//for (int i = 0; i < opens.Count(); i++)
//{
// if (i != opens.Count() - 1)
// {
// Console.WriteLine($"{opens[i]}");
// }
// else
// {
// Console.Write(opens[i]);
// }
//}
Console.ReadKey();
}
private static string GetIp(string[] args)
{
var ipIndex = -1;
for (int i = 0; i < args.Length; i++)
{
if (i == ipIndex)
{
return args[i];
}
var isIpCommand = args[i].Equals("-ip", StringComparison.OrdinalIgnoreCase);
if (isIpCommand)
{
ipIndex = i + 1;
}
}
return String.Empty;
}
private static bool IsIp(string ip)
{
if (!string.IsNullOrEmpty(ip))
{
IPAddress ipAddress;
if (IPAddress.TryParse(ip, out ipAddress))
{
return true;
}
}
return false;
}
private static string GetPorts(string[] args)
{
var ipIndex = -1;
for (int i = 0; i < args.Length; i++)
{
if (i == ipIndex)
{
return args[i];
}
var isIpCommand = args[i].Equals("-ports", StringComparison.OrdinalIgnoreCase);
if (isIpCommand)
{
ipIndex = i + 1;
}
}
return String.Empty;
}
private static IEnumerable<int> ConvertPorts(string ports)
{
var result = new List<int>();
if (!string.IsNullOrEmpty(ports))
{
//判断是否为全部
if (ports.Contains('*'))
{
for (int i = 1; i <= 65535; i++)
{
result.Add(i);
}
}
//判断是否是范围
else if (ports.Contains('-'))
{
var portMinMax = ports.Split('-');
if (portMinMax.Length == 2)
{
var port1 = portMinMax[0];
var port2 = portMinMax[1];
int portInt1;
int portInt2;
if (int.TryParse(port1, out portInt1) && int.TryParse(port2, out portInt2))
{
var minPort = portInt1 <= portInt2 ? portInt1 : portInt2;
if (!IsVolidPort(minPort))
{
minPort = 1;
}
var maxPort = portInt1 >= portInt2 ? portInt1 : portInt2;
if (!IsVolidPort(maxPort))
{
maxPort = 65535;
}
for (int i = minPort; i <= maxPort; i++)
{
result.Add(i);
}
}
}
}
//离散
else if(ports.Contains(","))
{
var portsString = ports.Split(',');
foreach (var s in portsString)
{
int portInt;
if (int.TryParse(s, out portInt) && IsVolidPort(portInt))
{
result.Add(portInt);
}
}
}
//独立
else
{
int portInt;
if (int.TryParse(ports, out portInt) && IsVolidPort(portInt))
{
result.Add(portInt);
}
}
}
return result;
}
private static bool IsVolidPort(int port)
{
return port >= 1 && port <= 65535;
}
}
}
|
using System;
namespace Currency_Converter
{
class Program
{
static void Main(string[] args)
{
string[] currency = new string[] { "BGN", "USD", "EUR", "GBP" };
double[] currencyValue = new double[] { 1, 1.79549, 1.95583, 2.53405 };
double conversionSum = 0;
Console.Write("Enter sum: ");
double sum = double.Parse(Console.ReadLine());
Console.WriteLine("Curreny selection: BGN, USD, EUR, GBP ");
Console.Write("Enter input currency: ");
string inputCurrency = Console.ReadLine();
Console.Write("Enter output currency: ");
string outputCurrency = Console.ReadLine();
int outputField = 0, inputField = 0;
for (int i = 0; i < 4; i++)
{
if (inputCurrency == currency[i]) inputField = i;
if (outputCurrency == currency[i]) outputField = i;
}
conversionSum = Math.Round((sum * currencyValue[inputField]) / currencyValue[outputField],2);
Console.WriteLine("{0} {1}",conversionSum,outputCurrency);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
/// <summary>
/// StudentName: Suvashin
/// Student Number: 19003564
/// Module: PROG6212
/// Task: 1
/// Semester: 2
/// </summary>
namespace BudgetingApp
{
class StaticValues
{
public static double monthlyIncome;//stores the gross income
public static double currentMonthlyIncome;//stores the current income after expenses
public static string username;//stores the users username
public static bool isBuyClickTrue;//helps determine if the user wants to buy or rent
public static double vehicleExpense;//stores the vehicle expense
public static double propertyExpense;//stores the property expense
public static double lifestyleExpense;//stores the lifestyle expense
public static List<Expense> lstExpenses = new List<Expense>();//keeps objects of the different expenses that the user calculates, This is a Generic Collection
public static void CheckGenericList(string message, string type, Expense objExpense)
{
bool canAdd = false;//used for determining whether to add an object or overwrite it
for (int i = 0; i < lstExpenses.Count; i++)//foreach expense in the expense list
{
if (lstExpenses[i].GetType().ToString().Equals(type))//if the object that just came in has the same type as an object in the list
{
currentMonthlyIncome += lstExpenses[i].MonthlyCost;//return the money that was intially deducted
lstExpenses[i] = objExpense;//overwrite the expense
MessageBox.Show(message);//tell the user that the expense was overwritten
canAdd = false;//dont add the object to the list because it was just overwritten
}
else
{
canAdd = true;//else if theres no object in the list with that type then add it
}
}
if (canAdd)
{
lstExpenses.Add(objExpense);//if the bool is true then add the obj to the list
}
if (lstExpenses.Count == 0)
{
lstExpenses.Add(objExpense);//if there is nothing in the list then immediately add the object that came in, into the list
}
}
}
}
|
using System;
namespace Core
{
static class FileLengthConverter
{
public static string Convetrt(long length)
{
string[] suffixes = { "bytes", "KB", "MB", "GB",
"TB", "PB", "EB", "ZB", "YB"};
for (int i = 0; i < suffixes.Length; i++)
{
if (length <= (Math.Pow(1024, i + 1)))
{
string val = Math.Round(length / Math.Pow(1024, i), 2).ToString();
return val + " " + suffixes[i];
}
}
return "0";
}
}
}
|
using System;
using System.Xml;
namespace pjank.BossaAPI.Fixml
{
public enum OrderType
{
PKC = '1', // zlecenie "po każdej cenie"
Limit = 'L', // zlecenie "z limitem ceny"
StopLoss = '3', // "PKC" aktywowany dopiero po osiągnięciu wskazanej ceny
StopLimit = '4', // "Limit" aktywowany dopiero po osiągnięciu wskazanej ceny
PCR_PCRO = 'K' // PCR (po cenie rynkowej) lub PCRO (na otwarcie/zamknięcie, patrz TimeInForce)
}
internal static class OrderTypeUtil
{
public static OrderType? Read(XmlElement xml, string name, bool optional)
{
char? ch = FixmlUtil.ReadChar(xml, name, optional);
if (ch == null) return null;
if (!Enum.IsDefined(typeof(OrderType), (OrderType)ch))
FixmlUtil.Error(xml, name, ch, "- unknown OrderType");
return (OrderType)ch;
}
public static string Write(OrderType value)
{
return ((char)value).ToString();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterStatus : MonoBehaviour
{
public int health = 100;
public float speed = 5f;
public bool hard = false;
private Animator animator;
private float nextActionTime = 0.0f;
private float period = 1f;
private GameObject monster;
public SimpleHealthBar healthBar;
// Start is called before the first frame update
void Start()
{
animator = GetComponentInChildren<Animator>();
monster = GameObject.FindGameObjectWithTag("monsterGroup");
if (hard)
{
StartCoroutine("DoCheck");
}
}
// Update is called once per frame
void Update()
{
if (health <= 0) {
animator.SetTrigger("death");
}
}
IEnumerator DoCheck()
{
for (; ; )
{
// execute block of code here
yield return new WaitForSeconds(1);
health++;
healthBar.UpdateBar(health, 100);
}
}
private void deathEvent()
{
gameObject.SetActive(false);
MonsterRespawn respawn = monster.GetComponent<MonsterRespawn>();
respawn.remainingMonster--;
}
}
|
using UnityEngine;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
[JsonObject(MemberSerialization.OptIn)]
public class JsonCardInfoGatherer: CardInfoGatherer
{
[JsonProperty]
private Dictionary<string, string> _infoPaths; // id - path
public JsonCardInfoGatherer(string baseUrl, Dictionary<string, string> infoPaths) : base(baseUrl)
{
_infoPaths = infoPaths;
}
override public ICollection<string> PotentialHits
{
get
{
return _infoPaths.Keys;
}
}
override protected void HandleFinished(WWW www, System.Action<Dictionary<string,string>> onFinished)
{
if (www.error == null)
{
try
{
JToken jtoken = JToken.Parse(www.text);
// Find all id-value pairs in the jtoken based on the _infoPaths.
var dict = new Dictionary<string,string>(_infoPaths.Count);
foreach(var infoPath in _infoPaths)
{ // infoPath.Key = id; infoPath.Value = path
// TODO: Allow some selects to fail
dict[infoPath.Key] = jtoken.SelectTokens(infoPath.Value, true).Last().ToString();
}
//Debug.Log("Succesfully loaded info for " + card.Name + "\nAdded info: " + info.ToString());
onFinished(dict);
}
catch (System.Exception) //e)
{
//Debug.Log("Failed parsing info as json, with error: " + e.Message + "\nFrom: " + www.url + "\nGotten text: " + www.text);
onFinished(null);
}
}
else
{
//Debug.Log("Failed to load info for: " + card.Name + "; url: " + url + "; error: " + www.error + "\n" + www.text);
onFinished(null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ThesaurusBot
{
public class WordResponse
{
public string Word { get; set; }
public string[] Synonyms { get; set; }
}
} |
using Assets.src.data;
using UnityEngine;
using ViewModelFramework;
public class BuildingModelParams : BaseModelParams
{
public Vector3 Position { get; set; }
public BuildingData BuildingData { get; set; }
}
public class BuildingModel : BaseModel {
public Vector3 Position { get; set; }
public BuildingData Data { get; set; }
protected override void OnInitialize(BaseModelParams param)
{
base.OnInitialize(param);
var buildingParam = param as BuildingModelParams;
if (buildingParam != null)
{
Position = buildingParam.Position;
Data = buildingParam.BuildingData;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelpCylinder.BusinessEntities
{
public class CustomCommandModel
{
public string ProcedureName { get; set; }
public SqlParameter[] ParamArray { get; set; }
public ProcedureType Type { get; set; }
}
public class CustomResponseModel<T>
{
public List<T> ResultDataTable { get; set; }
public bool Status { get; set; }
}
public enum ProcedureType
{
Get,
Post
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grains
{
[Serializable]
public class UserRequest
{
public object Content;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpeedPowerUp : MonoBehaviour
{
public CharacterMover player;
public void OnTriggerEnter(Collider other)
{
Debug.Log("You got the speed");
player.moveSpeed = 20;
}
}
|
using System.Runtime.CompilerServices;
[assembly:
InternalsVisibleTo(
"Vlc.DotNet.Forms, PublicKey=00240000048000009400000006020000002400005253413100040000010001005b09d6d3ef21088919592c4a0c2a9c13b20fb7719cddadf0b765965680508f4b47e9fff77840198e53a5456f6e833aafd7e6e209518d7f5118606924550bc5c7b296355ac06d99354faf031a257a233f7cd1bf65f7d7e81689b840d1ae8da567c94f6ab413b3c132a19f766a3e0709f6078a30b6820976b5587372141b9f87ca"
)]
[assembly:
InternalsVisibleTo(
"Vlc.DotNet.Wpf, PublicKey=00240000048000009400000006020000002400005253413100040000010001005b09d6d3ef21088919592c4a0c2a9c13b20fb7719cddadf0b765965680508f4b47e9fff77840198e53a5456f6e833aafd7e6e209518d7f5118606924550bc5c7b296355ac06d99354faf031a257a233f7cd1bf65f7d7e81689b840d1ae8da567c94f6ab413b3c132a19f766a3e0709f6078a30b6820976b5587372141b9f87ca"
)] |
using System.Xml.Serialization;
namespace Witsml.Data
{
public class WitsmlParentWellbore
{
[XmlAttribute("uidRef")]
public string UidRef { get; set; }
[XmlText]
public string Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace EmployeeDeactivation.Data
{
public class EmployeeDeactivationContext : DbContext
{
public EmployeeDeactivationContext (DbContextOptions<EmployeeDeactivationContext> options)
: base(options)
{
Database.EnsureCreated();
}
public DbSet<Models.DeactivatedEmployeeDetails> DeactivationWorkflow { get; set; }
public DbSet<Models.Teams> Teams { get; set; }
public DbSet<Models.ManagerApprovalStatus> ManagerApprovalStatus { get; set; }
public DbSet<Models.ActivationWorkflowModel> ActivationWorkflow { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Diagnostics;
using SomeTechie.RoundRobinScheduleGenerator;
namespace SomeTechie.RoundRobinScheduleGenerator.UnitTests
{
[TestFixture]
class Tests
{
protected const int minTeams = 0;
protected const int maxTeams = 13;
protected const int minDivisions = 1;
protected const int maxDivisions = 4;
protected const int minCourts = 1;
protected const int maxCourts = 10;
protected int[][] gamesToTest = new int[][] { new int[] { 8 }};
/* [SetUp]
public void generateTournamentObjects()
{
}*/
protected int _getNextDivisionSpecs_numDivisions = 0;
private List<int[]> getNextDivisionSpecs(int[] initialSpecs, int minTeams, int maxTeams, bool includeInitialValue = false, int maxNum = 10)
{
int numDivisions = initialSpecs.Length;
List<int[]> divisionsSpecs = new List<int[]>();
int[] currentDivisionSpecs = (int[])initialSpecs.Clone();
if (includeInitialValue) divisionsSpecs.Add((int[])currentDivisionSpecs.Clone());
bool isFinished = false;
while (divisionsSpecs.Count < maxNum)
{
for (int i = numDivisions - 1; i >= 0; i--)
{
if (currentDivisionSpecs[i] >= maxTeams)
{
if (i == 0)
{
isFinished = true;
break;
}
currentDivisionSpecs[i] = minTeams;
}
else
{
currentDivisionSpecs[i]++;
break;
}
}
if (isFinished) break;
divisionsSpecs.Add((int[])currentDivisionSpecs.Clone());
}
return divisionsSpecs;
}
private int[] buildDefaultDivisionSpecs(int numDivisions, int minTeams, int maxTeams)
{
int[] initialDivisionSpecs = new int[numDivisions];
for (int i = 0; i < numDivisions; i++)
{
initialDivisionSpecs[i] = minTeams;
}
return initialDivisionSpecs;
}
private List<Division> buildDivisions(int[] numTeamsInDivisions)
{
List<Division> divisions = new List<Division>();
int divisionNumber = 1;
foreach (int numTeams in numTeamsInDivisions)
{
string divisionNumberString = divisionNumber.ToString();
string divisionName = "Division" + divisionNumberString;
string divisionAbbreviation = "D" + divisionNumberString + "_";
Division division = new Division(divisionName, divisionAbbreviation);
List<Team> teams = new List<Team>();
for (int i = 1; i <= numTeams; i++)
{
teams.Add(new Team(divisionAbbreviation + i.ToString(), i));
}
division.Teams = teams;
divisions.Add(division);
divisionNumber++;
}
return divisions;
}
private void NotSameTime(Tournament tournament)
{
foreach (CourtRound courtRound in tournament.CourtRounds)
{
List<int> teamsUsed = new List<int>();
foreach (Game game in courtRound.Games)
{
foreach (Team team in game.Teams)
{
Assert.IsFalse(teamsUsed.Contains(team.NumId), GetTournamentId(tournament) + " - {0} exists more than one time in Court Round {1}", team, courtRound.RoundNumber);
teamsUsed.Add(team.NumId);
}
}
}
}
private void PreferBetterTeams(Tournament tournament)
{
if (tournament.NumCourts < 2) return;
foreach (CourtRound courtRound in tournament.CourtRounds)
{
int previousDivisionIndex = -1;
foreach (Game game in courtRound.Games)
{
int divisionIndex = tournament.Divisions.IndexOf(game.Division);
Assert.GreaterOrEqual(divisionIndex, previousDivisionIndex, GetTournamentId(tournament) + " - Prefer better teams failed In Court Round {0}", courtRound.RoundNumber);
previousDivisionIndex = divisionIndex;
}
}
}
private void NoVacantCourts(Tournament tournament)
{
int maxGamesPerCourtRound = 0;
foreach (Division division in tournament.Divisions)
{
maxGamesPerCourtRound += (int)Math.Floor((decimal)division.Teams.Count / 2);
}
if (tournament.NumCourts < maxGamesPerCourtRound) maxGamesPerCourtRound = tournament.NumCourts;
foreach (CourtRound courtRound in tournament.CourtRounds)
{
if (courtRound.RoundNumber != tournament.CourtRounds.Count) Assert.AreEqual(maxGamesPerCourtRound, courtRound.numGames, GetTournamentId(tournament) + " - Vacant courts in Court Round {0}", courtRound.RoundNumber);
}
}
private void DistributeTeamsAcrossCourts(Tournament tournament)
{
if (tournament.NumCourts < 2) return;
Dictionary<Division, Dictionary<int, Dictionary<int, int>>> timesTeamsOnCourtByDivision = new Dictionary<Division, Dictionary<int, Dictionary<int, int>>>();
foreach (CourtRound courtRound in tournament.CourtRounds)
{
foreach (Game game in courtRound.Games)
{
if (!timesTeamsOnCourtByDivision.ContainsKey(game.Division)) timesTeamsOnCourtByDivision.Add(game.Division, new Dictionary<int, Dictionary<int, int>>());
Dictionary<int, Dictionary<int, int>> timesTeamsOnCourtForDivision = timesTeamsOnCourtByDivision[game.Division];
foreach (Team team in game.Teams)
{
if (!timesTeamsOnCourtForDivision.ContainsKey(team.NumId)) timesTeamsOnCourtForDivision.Add(team.NumId, new Dictionary<int, int>());
Dictionary<int, int> timesTeamOnCourt = timesTeamsOnCourtForDivision[team.NumId];
if (timesTeamOnCourt.ContainsKey(game.CourtNumber)) timesTeamOnCourt[game.CourtNumber]++;
else timesTeamOnCourt.Add(game.CourtNumber, 1);
}
}
}
int largestDistributionDifference = int.MinValue;
string largestDistributionDiffereceId = "";
foreach (KeyValuePair<Division, Dictionary<int, Dictionary<int, int>>> timesOnCourtForDivision in timesTeamsOnCourtByDivision)
{
Dictionary<int, int> MaxTimesOnCourt = new Dictionary<int, int>();
Dictionary<int, int> MinTimesOnCourt = new Dictionary<int, int>();
//Initilize the values for the FirstTimesOnCourt dictionary
for (int i = 1; i <= tournament.NumCourts; i++)
{
MaxTimesOnCourt.Add(i, int.MinValue);
MinTimesOnCourt.Add(i, int.MaxValue);
}
foreach (KeyValuePair<int, Dictionary<int, int>> timesOnCourtForTeam in timesOnCourtForDivision.Value)
{
foreach (KeyValuePair<int, int> timesOnCourtPair in timesOnCourtForTeam.Value)
{
int courtNumber = timesOnCourtPair.Key;
int timesOnCourt = timesOnCourtPair.Value;
if (timesOnCourt > MaxTimesOnCourt[courtNumber]) MaxTimesOnCourt[courtNumber] = timesOnCourt;
if (timesOnCourt < MinTimesOnCourt[courtNumber]) MinTimesOnCourt[courtNumber] = timesOnCourt;
}
}
for (int i = 1; i <= tournament.NumCourts; i++)
{
int difference = MaxTimesOnCourt[i] - MinTimesOnCourt[i];
if (difference > largestDistributionDifference)
{
largestDistributionDifference = difference;
largestDistributionDiffereceId = "on " + CourtRound.CourtNumToCourtName(i) + " " + timesOnCourtForDivision.Key.Name;
}
}
}
if (largestDistributionDifference > 5)
{
Trace.WriteLine(GetTournamentId(tournament) + " - Largest team distribution difference: " + largestDistributionDifference.ToString() + "; " + largestDistributionDiffereceId);
}
}
private void TeamsPlayTeams(Tournament tournament)
{
foreach (Division division in tournament.Divisions)
{
foreach (Team team1 in division.Teams)
{
foreach (Team team2 in division.Teams)
{
if (team1 == team2) continue;
bool foundGame = false;
foreach (CourtRound courtRound in tournament.CourtRounds)
{
foreach (Game game in courtRound.Games)
{
if ((game.Team1 == team1 && game.Team2 == team2) || (game.Team1 == team2 && game.Team2 == team1))
{
foundGame = true;
break;
}
}
if (foundGame) break;
}
Assert.IsTrue(foundGame, GetTournamentId(tournament) + " - {0} never plays {1}", team1, team2);
}
}
}
}
private void CorrectNumberOfGamesInRobinRounds(Tournament tournament)
{
Dictionary<int, Dictionary<int, int>> numberOfGamesPerRobinRoundByDivision = new Dictionary<int, Dictionary<int, int>>();
int numberOfRobinRounds = 0;
foreach (Division division in tournament.Divisions)
{
int num = division.Teams.Count;
if (num % 2 == 0) num--;
if(num>numberOfRobinRounds)numberOfRobinRounds=num;
}
foreach (Division division in tournament.Divisions)
{
Dictionary<int,int> numberOfGamesPerRobinRoundForDivision = new Dictionary<int,int>();
for (int robinRoundNum = 0; robinRoundNum < numberOfRobinRounds; robinRoundNum++)
{
numberOfGamesPerRobinRoundForDivision.Add(robinRoundNum, 0);
}
numberOfGamesPerRobinRoundByDivision.Add(division.NumId, numberOfGamesPerRobinRoundForDivision);
}
foreach (CourtRound courtRound in tournament.CourtRounds)
{
foreach (Game game in courtRound.Games)
{
Assert.IsTrue(numberOfGamesPerRobinRoundByDivision[game.Division.NumId].ContainsKey(game.RobinRoundNum - 1), GetTournamentId(tournament) + " - Game {0} is in robin round {1}; only {2} robin rounds", game, game.RobinRoundNum, numberOfRobinRounds);
numberOfGamesPerRobinRoundByDivision[game.Division.NumId][game.RobinRoundNum - 1]++;
}
}
foreach (Division division in tournament.Divisions)
{
int numberOfGames = division.Teams.Count / 2;
for (int robinRoundNum = 0; robinRoundNum < numberOfRobinRounds; robinRoundNum++)
{
Assert.AreEqual(numberOfGames, numberOfGamesPerRobinRoundByDivision[division.NumId][robinRoundNum], GetTournamentId(tournament) + " - Incorrect number of games: Robin Round {0} {1}", robinRoundNum, division);
}
}
}
private static int tournamentNumber = 0;
private void TestTournaments(params Tournament[] tournaments)
{
//Run tests
for (int i = 0; i < tournaments.Length; i++)
{
tournamentNumber++;
Tournament tournament = tournaments[i];
if (tournamentNumber % 100 == 0)
{
Trace.WriteLine("Testing: " + GetTournamentId(tournament));
}
Assert.IsNotNull(tournament.CourtRounds);
this.NotSameTime(tournament);
this.NoVacantCourts(tournament);
this.PreferBetterTeams(tournament);
this.DistributeTeamsAcrossCourts(tournament);
this.TeamsPlayTeams(tournament);
this.CorrectNumberOfGamesInRobinRounds(tournament);
}
}
private string GetTournamentId(Tournament tournament)
{
string numTeamsStr = "";
foreach (Division division in tournament.Divisions)
{
if (numTeamsStr.Length > 0) numTeamsStr += ",";
numTeamsStr += division.Teams.Count;
}
return "NumDivisions:" + tournament.Divisions.Count + " NumTeams:" + numTeamsStr + " NumCourts:" + tournament.NumCourts;
}
private Tournament[] TournamentsFromSpecs(int[][] divisionsSpecs)
{
//Create tournament objects
List<Tournament> Tournaments = new List<Tournament>();
foreach (int[] divisionSpecs in divisionsSpecs)
{
for (int numCourts = minCourts; numCourts <= maxCourts; numCourts++)
{
Tournaments.Add(new Tournament(buildDivisions(divisionSpecs), numCourts));
}
}
return Tournaments.ToArray();
}
[Test]
public void Selective()
{
//Create tournament objects
Tournament[] tournaments = TournamentsFromSpecs(gamesToTest);
TestTournaments(tournaments);
}
[Test]
public void BruteForce()
{
for (int numDivisions = minDivisions; numDivisions <= maxDivisions; numDivisions++)
{
int[] previousDivisionSpecs = buildDefaultDivisionSpecs(numDivisions, minTeams, maxTeams);
List<int[]> divisionsSpecs;
bool shouldIncludeInitialDivisionSpecs = true;
while ((divisionsSpecs = getNextDivisionSpecs(previousDivisionSpecs, minTeams, maxTeams, shouldIncludeInitialDivisionSpecs)).Count > 0)
{
shouldIncludeInitialDivisionSpecs = false;
previousDivisionSpecs = divisionsSpecs[divisionsSpecs.Count - 1];
//Create tournament objects
Tournament[] tournaments = TournamentsFromSpecs(divisionsSpecs.ToArray());
TestTournaments(tournaments);
tournaments = null;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyServiceLibrary
{
public class UserEqualityComparer : IEqualityComparer<User>
{
public bool Equals(User lhs, User rhs)
{
if (ReferenceEquals(lhs, rhs))
{
return true;
}
if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null))
{
return false;
}
return string.Equals(lhs.FirstName, rhs.FirstName, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(lhs.LastName, rhs.LastName, StringComparison.InvariantCultureIgnoreCase);
}
public int GetHashCode(User user)
=> user.FirstName.GetHashCode() + user.LastName.GetHashCode();
}
}
|
public interface IMessageSubject {
void RegisterObserver(IMessageObsever o);
bool RemoveObserver(IMessageObsever o);
void SendMessage(CMessages.eMessages m,object data);
}
|
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 Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.IO;
using System.Text.RegularExpressions;
namespace Test
{
public partial class Form1 : Form
{
private Microsoft.Office.Interop.Word.Application testWord = new Microsoft.Office.Interop.Word.Application();
private Document testDoc = new Document();
private Document regDoc = new Document();
private HandleDocument handleDocument = new HandleDocument();
private Regex regex = new Regex(@"[A-Z]\r");
private Regex over = new Regex(@"[A-Z](\d)*");
private List<string> itemName = new List<string>();
private List<Decimal> originalValue = new List<Decimal>();
private List<Decimal> calValue = new List<Decimal>();
private List<string> compareItemName = new List<string>(); //目标表格中子项名字
private List<string> normalSubitemName = new List<string>();//标准表格中子项名字
Boolean flag = false;
public Form1()
{
InitializeComponent();
}
private string regFileName = "";//规程文档选择
private void selectRegFile_Click(object sender, EventArgs e)
{
string temp = regFileName;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Word文件|*.doc";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
regFileName = openFileDialog.FileName;
if (regFileName != temp && temp != "")
{
regDocLabel.Text = regFileName;
}
else
{
regDocLabel.Text = regFileName;
}
}
}
private string testFileName = "";//测试文档选择
private void selectTestFile_Click(object sender, EventArgs e)
{
string temp = testFileName;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Word文件|*.doc";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
testFileName = openFileDialog.FileName;
if (regFileName != temp && temp != "")
{
testDocLable.Text = testFileName;
}
else
{
testDocLable.Text = testFileName;
}
}
}
//Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
private void btnTest_Click(object sender, EventArgs e)
{
buildShowTable1(dataGridView1);
}
private void quit()
{
//word.Quit();
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD"))
{
p.Kill();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
testWord.Quit();
}
private void buildShowTable1(DataGridView dataTableView)
{
for (int i = 0; i < 2 * 9 + 1; i++)
{
dataTableView.Columns.Add(new DataGridViewTextBoxColumn());
}
dataTableView.Rows.Add();
for (int j = 1; j <= 3; j++)
{
string name = "";
if (j == 1)
{
name = "面积(公顷)";
}
else if (j == 2)
{
name = "占城市建设用地比重";
}
else
{
name = "人均(m2/人)";
}
int start = (j - 1) * 6;
dataTableView.Rows[0].Cells[start + 1].Value = name + "现状";
dataTableView.Rows[0].Cells[start + 2].Value = name + "现状";
dataTableView.Rows[0].Cells[start + 3].Value = name + "近期";
dataTableView.Rows[0].Cells[start + 4].Value = name + "近期";
dataTableView.Rows[0].Cells[start + 5].Value = name + "远期";
dataTableView.Rows[0].Cells[start + 6].Value = name + "远期";
}
dataTableView.Rows.Add();
for (int i = 1; i <= 9; i++)
{
int start = (i - 1) * 2;
dataTableView.Rows[1].Cells[start + 1].Value = "原始数据";
dataTableView.Rows[1].Cells[start + 2].Value = "校验结果";
}
dataTableView.Rows[0].Cells[0].Value = "城市建设用地平衡表";
dataTableView.Rows[1].Cells[0].Value = "城市建设用地平衡表";
dataTableView.Rows[2].Cells[0].Value = "城市建设用地平";
}
private void buildShowTable(DataGridView dataTableView)
{
for (int i = 0; i <= 3; i++)
{
dataTableView.Columns.Add(new DataGridViewTextBoxColumn());
}
dataTableView.Rows.Add();
dataTableView.Rows[0].Cells[0].Value = 1;
dataTableView.Rows[0].Cells[1].Value = 1;
dataTableView.Rows[0].Cells[2].Value = 2;
dataTableView.Rows[0].Cells[3].Value = 2;
dataTableView.Rows[1].Cells[0].Value = 1;
dataTableView.Rows[1].Cells[1].Value = 1;
dataTableView.Rows[1].Cells[2].Value = 2;
dataTableView.Rows[1].Cells[3].Value = 2;
}
Boolean f = false;
int start = 1;
/*
#region 统计行单元格绘制
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex ==0)
{
e.CellStyle.Font = new System.Drawing.Font(dataGridView1.DefaultCellStyle.Font, FontStyle.Bold);
e.CellStyle.WrapMode = DataGridViewTriState.True;
DGVOper.MerageRowSpan(dataGridView1, e, 1, 2);
DGVOper.MerageRowSpan(dataGridView1, e, 3, 4);
DGVOper.MerageRowSpan(dataGridView1, e, 5, 6);
DGVOper.MerageRowSpan(dataGridView1, e, 7, 8);
DGVOper.MerageRowSpan(dataGridView1, e, 9, 10);
DGVOper.MerageRowSpan(dataGridView1, e, 11, 12);
DGVOper.MerageRowSpan(dataGridView1, e, 13, 14);
DGVOper.MerageRowSpan(dataGridView1, e, 15, 16);
DGVOper.MerageRowSpan(dataGridView1, e, 17, 18);
if (start <= e.ColumnIndex && e.ColumnIndex <= start+1)
{
f = DGVOper.MerageRowSpan(dataGridView1, e, start, start+1);
if (f == true)
{
DGVOper.clear();
start+=2;
}
}
}
}
#endregion
*/
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex != -1 && e.RowIndex == 0)
{
using
(
Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor)
)
{
using (Pen gridLinePen = new Pen(gridBrush))
{
try
{
// 清除单元格
e.CellStyle.Font = new System.Drawing.Font(dataGridView1.DefaultCellStyle.Font, FontStyle.Regular);
e.CellStyle.WrapMode = DataGridViewTriState.True;
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
e.Handled = true;
// 画 Grid 边线(仅画单元格的底边线和右边线)
// 如果下一列和当前列的数据不同,则在当前的单元格画一条右边线
if (e.ColumnIndex < dataGridView1.Columns.Count - 1 &&
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value.ToString() !=
e.Value.ToString())
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
e.CellBounds.Top - 1, e.CellBounds.Right - 1,
e.CellBounds.Bottom - 1);
//画最后一条记录的右边线
if (e.ColumnIndex == dataGridView1.Columns.Count - 1)
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
//画底边线
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left - 1,
e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
e.CellBounds.Bottom - 1);
// 画(填写)单元格内容,相同的内容的单元格只填写第一个
if (e.Value != null)
{
if (e.ColumnIndex == dataGridView1.Columns.Count - 1
&& dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Value.ToString() !=e.Value.ToString())
{
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
Brushes.Black, e.CellBounds.Left ,
e.CellBounds.Top+4 , StringFormat.GenericDefault);
}
if (e.ColumnIndex > 0 &&
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex +1].Value.ToString() ==
e.Value.ToString())
{
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
Brushes.Black, e.CellBounds.Left ,
e.CellBounds.Top+4, StringFormat.GenericDefault);
}
if (e.ColumnIndex > 0 &&
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value.ToString() !=
e.Value.ToString() && dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Value.ToString() !=
e.Value.ToString())
{
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
Brushes.Black, e.CellBounds.Left,
e.CellBounds.Top+4, StringFormat.GenericDefault);
}
}
//e.Handled = true;
}
catch
{
}
}
}
}
if (e.ColumnIndex == 0 && e.RowIndex >= 0)
{
using (
Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
// 擦除原单元格背景
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
////绘制线条,这些线条是单元格相互间隔的区分线条,
////因为我们只对列name做处理,所以datagridview自己会处理左侧和上边缘的线条
if (e.RowIndex != 0)
{
if (e.Value.ToString() != this.dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString())
{
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Top - 1,
e.CellBounds.Right - 1, e.CellBounds.Top - 1);//上边缘的线
//绘制值
if (e.Value != null)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
Brushes.Black, e.CellBounds.Left,
e.CellBounds.Top+4, StringFormat.GenericDefault);
}
}
}
else
{
//e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1,
//e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);//下边缘的线
//绘制值
if (e.Value != null)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
Brushes.Black, e.CellBounds.Left,
e.CellBounds.Top+4, StringFormat.GenericDefault);
}
}
if (e.RowIndex == dataGridView1.Rows.Count - 1)
{
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1,
e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);//下边缘的线
}
//右侧的线
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
e.CellBounds.Top, e.CellBounds.Right - 1,
e.CellBounds.Bottom - 1);
e.Handled = true;
}
}
}
}
}
}
|
using Labo_2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Labo_2.Controllers
{
public class ContactController : Controller
{
// GET: Contact
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Contact contact)
{
if (!ModelState.IsValid)
{
return View(contact);
}
return View("Details", contact);
}
}
} |
using System;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;
using com.Sconit.SmartDevice.SmartDeviceRef;
using System.Web.Services.Protocols;
namespace com.Sconit.SmartDevice
{
public partial class UCWMSDeliveryBarCode111 : UCBase
{
//public event MainForm.ModuleSelectHandler ModuleSelectionEvent;
private List<PickTask> pickTasks;
private string binCode;
private DateTime? effDate;
private bool isPickByHu;
//private List<IpDetailInput> ipDetailProcess;
private static UCWMSDeliveryBarCode111 ucWMSDeliveryBarCode;
private static object obj = new object();
public UCWMSDeliveryBarCode111(User user)
: base(user)
{
this.InitializeComponent();
base.btnOrder.Text = "配送标签扫描";
}
public static UCWMSDeliveryBarCode111 GetUCWMSDeliveryBarCode(User user)
{
if (ucWMSDeliveryBarCode == null)
{
lock (obj)
{
if (ucWMSDeliveryBarCode == null)
{
ucWMSDeliveryBarCode = new UCWMSDeliveryBarCode111(user);
}
}
}
ucWMSDeliveryBarCode.user = user;
ucWMSDeliveryBarCode.Reset();
ucWMSDeliveryBarCode.lblMessage.Text = "请扫描条码\\配送标签";
return ucWMSDeliveryBarCode;
}
#region Event
protected override void ScanBarCode()
{
base.ScanBarCode();
if (base.op == CodeMaster.BarCodeType.HU.ToString())
{
Hu hu = smartDeviceService.GetHu(barCode);
MatchPickTask(hu);
}
else
{
throw new BusinessException("条码格式不合法");
}
}
#endregion
private void MatchPickTask(Hu hu)
{
if (hu == null)
{
throw new BusinessException("条码不存在");
}
}
#region DataBind
protected override void gvListDataBind()
{
this.tbBarCode.Text = string.Empty;
this.ts = new DataGridTableStyle();
this.ts.GridColumnStyles.Add(columnItemCode);
this.ts.GridColumnStyles.Add(columnItemDescription);
this.ts.GridColumnStyles.Add(columnLotNo);
if (isPickByHu == true)
{
this.ts.GridColumnStyles.Add(columnHuId);
}
//this.ts.GridColumnStyles.Add(columnIsOdd);
this.ts.GridColumnStyles.Add(columnBin);
this.ts.GridColumnStyles.Add(columnUom);
this.ts.GridColumnStyles.Add(columnReferenceItemCode);
this.dgList.TableStyles.Clear();
this.dgList.TableStyles.Add(this.ts);
this.ResumeLayout();
this.isMasterBind = true;
}
#endregion
#region Init Reset
protected override void Reset()
{
base.Reset();
this.effDate = null;
}
#endregion
protected override void DoSubmit()
{
this.Reset();
//base.lblMessage.Text = string.Format("收货成功,收货单号:{0}", receiptNo);
this.isMark = true;
}
protected override Hu DoCancel()
{
Hu firstHu = base.DoCancel();
this.CancelHu(firstHu);
return firstHu;
}
private void VerifyPermission(string partyTo)
{
if (!this.user.Permissions.Where(t => t.PermissionCategoryType == PermissionCategoryType.Region)
.Select(t => t.PermissionCode).Contains(partyTo))
{
throw new BusinessException("没有目的区域权限不能收货。");
}
}
private void CancelHu(Hu hu)
{
//if (this.ipMaster == null && (this.orderMasters == null || this.orderMasters.Count() == 0))
if (this.hus == null)
{
//this.ModuleSelectionEvent(CodeMaster.TerminalPermission.M_Switch);
this.Reset();
return;
}
if (hu != null)
{
base.hus = base.hus.Where(h => !h.HuId.Equals(hu.HuId, StringComparison.OrdinalIgnoreCase)).ToList();
this.gvHuListDataBind();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommandDesignPattern
{
class Program
{
static void Main(string[] args)
{
CommandGroup obj = new CommandGroup();
obj.AddCommand(new Close());
obj.AddCommand(new Open());
obj.AddCommand(new Print());
obj.ExecuteCommand();
}
}
}
|
namespace BugunNeYesem.Data
{
public class RecommendedRestaurant
{
public string RestaurantName { get; set; }
public string EditorRating { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InoDrive.Domain
{
public enum ApplicationTypes
{
JavaScript = 0,
NativeConfidential = 1
};
public enum Statuses
{
CommonSuccess = 0,
CommonFailure = 100
};
}
|
using System;
namespace Atomic
{
/// <summary>
/// Atomic配置节点接口定义
/// </summary>
public interface IConfigNode
{
/// <summary>
/// 配置节名称(英文名)
/// </summary>
string NodeName { get; }
/// <summary>
/// 本节点的解析方式
/// </summary>
/// <param name="section"></param>
void Resolve(System.Xml.XmlNode section);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Halberd : MonoBehaviour
{
[SerializeField] Transform hand;
Rigidbody rig;
Quaternion criteriaRotQuat;
// Start is called before the first frame update
void Start()
{
rig = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
rig.MovePosition(hand.position);
rig.MoveRotation(hand.rotation);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.GetComponent<Enemy>())
{
var dir = (collision.transform.position - transform.position).normalized;
dir.y = 0.2f;
collision.gameObject.GetComponent<Rigidbody>().AddForce(dir * 20, ForceMode.Impulse);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace SbdProjekto.Models
{
public class Przesylka
{
public int PrzesylkaId { get; set; }
[DisplayName("Waga")]
[RegularExpression(@"\d+(\.\d{1,3})?", ErrorMessage = "Maksymalnie trzy miejsca po przecinku")]
public decimal Waga { get; set; }
[DisplayName("Szerokość")]
[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Maksymalnie dwa miejsca po przecinku")]
public decimal Szerokosc { get; set; }
[DisplayName("Wysokość")]
[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Maksymalnie dwa miejsca po przecinku")]
public decimal Wysokosc { get; set; }
[RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Maksymalnie dwa miejsca po przecinku")]
[DisplayName("Długość")]
public decimal Dlugosc { get; set; }
[DisplayName("Nazwa magazynu")]
public int MagazynId { get; set; }
public Magazyn Magazyn { get; set; }
[DisplayName("Rodzaj przesyłki")]
public int RodzajPrzesylkiId { get; set; }
[DisplayName("Rodzaj przesyłki")]
public RodzajPrzesylki RodzajPrzesylki { get; set; }
[DisplayName("Numer zamówienia")]
public int ZamowienieId { get; set; }
public Zamowienie Zamowienie { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarryController : MonoBehaviour {
private bool isCarrying;
private GameObject item;
// Use this for initialization
void Start () {
isCarrying = false;
}
public bool GiveObject(GameObject obj) {
if (isCarrying)
return false;
item = obj;
isCarrying = true;
return true;
}
public bool TakeObject(GameObject obj) {
if (!isCarrying)
return false;
item = null;
isCarrying = false;
return true;
}
}
|
using System;
namespace NETTRASH.BOT.Telegram.Core.Data
{
public class MessageEntity
{
#region Public properties
public string type { get; set; }
public UInt64 offset { get; set; }
public UInt64 length { get; set; }
public string url { get; set; }
#endregion
}
}
|
namespace gView.Framework.Geometry
{
public interface IRing : IPath
{
double Area { get; }
IPoint Centroid { get; }
void Close(double tolerance = GeometryConst.Epsilon);
IPolygon ToPolygon();
}
}
|
using HBPonto.Kernel.Interfaces.Entities;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HBPonto.Database.Entities
{
public class BaseEntity<TEntity> : IEntity where TEntity: class
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
}
}
|
namespace Uintra.Infrastructure.Constants
{
public static class DocumentTypeAliasConstants
{
public const string HomePage = "homePage";
public const string NotificationPage = "notificationPage";
public const string ProfilePage = "profilePage";
public const string ProfileEditPage = "profileEditPage";
public const string SearchResultPage = "searchResultPage";
public const string NewsOverviewPage = "uintraNewsOverviewPage";
public const string NewsCreatePage = "uintraNewsCreatePage";
public const string NewsEditPage = "uintraNewsEditPage";
public const string NewsDetailsPage = "uintraNewsDetailsPage";
public const string EventsOverviewPage = "eventOverviewPage";
public const string EventsCreatePage = "eventCreatePage";
public const string EventsEditPage = "eventEditPage";
public const string EventsDetailsPage = "eventDetailsPage";
public const string SocialOverviewPage = "socialDetailsPage";
public const string SocialCreatePage = "socialCreatePage";
public const string SocialEditPage = "socialEditPage";
public const string SocialDetailsPage = "socialDetailsPage";
public const string DataFolder = "dataFolder";
public const string UserTagFolder = "userTagFolder";
public const string UserTag = "userTagItem";
public const string GlobalPanelFolder = "globalPanelFolder";
public const string SystemLinkFolder = "systemLinkFolder";
public const string MailTemplatesFolder = "mailTemplatesFolder";
public const string MailTemplate = "MailTemplate";
public const string ErrorPage = "errorPage";
public const string NavigationComposition = "navigationComposition";
public const string ArticlePage = "articlePage";
public const string Heading = "heading";
public const string SystemLink = "systemLink";
public const string GroupsOverviewPage = "uintraGroupsPage";
public const string GroupsCreatePage = "uintraGroupsCreatePage";
public const string GroupsRoomPage = "uintraGroupsRoomPage"; // Group details
public const string GroupsMyGroupsOverviewPage = "uintraMyGroupsPage";
public const string GroupsDocumentsPage = "uintraGroupsDocumentsPage";
public const string GroupsEditPage = "uintraGroupsEditPage"; // Group settings
public const string GroupsMembersPage = "uintraGroupsMembersPage";
//unused for now
public const string GroupsDeactivatedGroupPage = "groupsDeactivatedGroupPage";
}
} |
using System;
namespace training
{
class Program
{
static void Main(string[] args)
{
int arraySize = int.Parse(Console.ReadLine());
int numberOfElements = int.Parse(Console.ReadLine());
int result = 0;
int[] input = new int[arraySize];
for (int i = 0; i < arraySize; i++)
{
input[i] = int.Parse(Console.ReadLine());
}
Array.Sort(input);
for (int i = arraySize - 1; i > arraySize - 1 - numberOfElements; i--)
{
result += input[i];
}
Console.WriteLine(result);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorld_v2
{
class Program
{
static void Main(string[] args)
{
World csharp = new World("C#");
csharp.SayHello();
World java = new World("Java");
java.SayHello();
World js = new World("JavaScript");
js.SayHello();
csharp.SayHello("Salut");
java.SayHello("Bonjour");
Console.ReadKey();
}
}
}
|
using Tests.Data.Van.Input;
namespace Tests.Pages.Van.Main.ScriptSortOptions.ScriptSortOptionsPageSections
{
interface IScriptSortOptionsPageComponent
{
void SetFields(ScriptSortOptionsForm ssoForm);
}
}
|
using Project.Base;
namespace Project.Records {
public class ChairRecord : Record {
public int id;
public int roomId;
public int row;
public int number;
public double price;
public string type;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace DbfDataReader
{
public class DbfRecord
{
private const byte EndOfFile = 0x1a;
public DbfRecord(DbfTable dbfTable)
{
Values = new List<IDbfValue>();
foreach (var dbfColumn in dbfTable.Columns)
{
var dbfValue = CreateDbfValue(dbfColumn, dbfTable.Memo);
Values.Add(dbfValue);
}
}
private static IDbfValue CreateDbfValue(DbfColumn dbfColumn, DbfMemo memo)
{
IDbfValue value;
switch (dbfColumn.ColumnType)
{
case DbfColumnType.Number:
if (dbfColumn.DecimalCount == 0)
{
value = new DbfValueInt(dbfColumn.Length);
}
else
{
value = new DbfValueDecimal(dbfColumn.Length, dbfColumn.DecimalCount);
}
break;
case DbfColumnType.Signedlong:
value = new DbfValueLong(dbfColumn.Length);
break;
case DbfColumnType.Float:
value = new DbfValueFloat(dbfColumn.Length);
break;
case DbfColumnType.Currency:
value = new DbfValueCurrency(dbfColumn.Length, dbfColumn.DecimalCount);
break;
case DbfColumnType.Date:
value = new DbfValueDate(dbfColumn.Length);
break;
case DbfColumnType.DateTime:
value = new DbfValueDateTime(dbfColumn.Length);
break;
case DbfColumnType.Boolean:
value = new DbfValueBoolean(dbfColumn.Length);
break;
case DbfColumnType.Memo:
value = new DbfValueMemo(dbfColumn.Length, memo);
break;
case DbfColumnType.Double:
value = new DbfValueDouble(dbfColumn.Length);
break;
case DbfColumnType.General:
case DbfColumnType.Character:
value = new DbfValueString(dbfColumn.Length);
break;
default:
value = new DbfValueNull(dbfColumn.Length);
break;
}
return value;
}
public bool Read(BinaryReader binaryReader)
{
if (binaryReader.BaseStream.Position == binaryReader.BaseStream.Length)
{
return false;
}
try
{
var value = binaryReader.ReadByte();
if (value == EndOfFile)
{
return false;
}
IsDeleted = (value == 0x2A);
foreach (var dbfValue in Values)
{
dbfValue.Read(binaryReader);
}
return true;
}
catch (EndOfStreamException)
{
return false;
}
}
public bool IsDeleted { get; private set; }
public IList<IDbfValue> Values { get; set; }
public object GetValue(int ordinal)
{
var dbfValue = Values[ordinal];
return dbfValue.GetValue();
}
public T GetValue<T>(int ordinal)
{
var dbfValue = Values[ordinal] as DbfValue<T>;
return dbfValue.Value;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Query.DTO;
using EBS.Domain.Entity;
namespace EBS.Query
{
public interface IAdjustSalePriceQuery
{
IEnumerable<AdjustSalePriceDto> GetPageList(Pager page, SearchAdjustSalePrice condition);
IEnumerable<AdjustSalePriceItemDto> GetAdjustSalePriceItems(int AdjustSalePriceId);
IEnumerable<AdjustSalePriceItemDto> GetItems(int AdjustSalePriceId);
AdjustSalePriceItemDto GetAdjustSalePriceItem(string productCodeOrBarCode);
IEnumerable<AdjustSalePriceItemDto> GetAdjustSalePriceList(string inputProducts);
Dictionary<int, string> GetAdjustSalePriceStatus();
IEnumerable<AdjustSalePriceItemDto> GetProductBySource(string source);
}
}
|
using Contracts;
using Entities;
using Entities.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace Repository
{
class PhoneNumberRepository : RepositoryBase<PhoneNumber>, IPhoneNumberRepository
{
public PhoneNumberRepository(RepositoryContext repositoryContext) : base(repositoryContext)
{
}
public PhoneNumber GetPhoneNumber(int phoneNumberId, bool trackChanges) => RepositoryContext.PhoneNumbers.Find(phoneNumberId);
public IEnumerable<PhoneNumber> GetPhoneNumbersByPerson(Person person, bool trackChanges) => FindByCondition(p => p.PersonId.Equals(person.Id), false);
}
}
|
namespace HTB.Database.LookupRecords
{
public class GegnerLookup
{
#region Property Declaration
public int GegnerID { get; set; }
public int GegnerType { get; set; }
public string GegnerName { get; set; }
public string GegnerZipPrefix { get; set; }
public string GegnerOrt { get; set; }
public string GegnerStrasse { get; set; }
public string GegnerLastZipPrefix { get; set; }
public string GegnerLastOrt { get; set; }
public string GegnerLastStrasse { get; set; }
public string GegnerNameLink { get; set; }
public string GegnerAddress { get; set; }
public string GegnerLastAddress { get; set; }
public string GegnerOldID { get; set; }
#endregion
}
}
|
using ICSharpCode.AvalonEdit.Highlighting;
using JetBrains.Annotations;
using System.Windows;
namespace EddiSpeechResponder
{
public partial class ViewScriptWindow : Window
{
public string ScriptName { get; private set; }
public string ScriptDescription { get; private set; }
public string ScriptValue { get; private set; }
#pragma warning disable IDE0052 // Remove unused private members -- this may be used later
private readonly DocumentHighlighter documentHighlighter;
#pragma warning restore IDE0052 // Remove unused private members
public ViewScriptWindow(Script script, [NotNull]AvalonEdit.CottleHighlighting cottleHighlighting)
{
InitializeComponent();
DataContext = this;
if (script != null)
{
ScriptName = script.Name;
ScriptDescription = script.Description;
ScriptValue = script.Value;
scriptView.Text = ScriptValue;
}
// Set up our Cottle highlighter
documentHighlighter = new DocumentHighlighter(scriptView.Document, cottleHighlighting.Definition);
}
private void okButtonClick(object sender, RoutedEventArgs e)
{
Close();
}
}
}
|
#region
using System;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
#endregion
namespace Audiotica.Core.UserControls
{
public sealed partial class Star : UserControl
{
private const Int32 STAR_SIZE = 12;
/// <summary>
/// BackgroundColor Dependency Property
/// </summary>
public static readonly DependencyProperty BackgroundColorProperty =
DependencyProperty.Register("BackgroundColor",
typeof (SolidColorBrush), typeof (Star),
new PropertyMetadata(new SolidColorBrush(Colors.Transparent),
OnBackgroundColorChanged));
/// <summary>
/// StarForegroundColor Dependency Property
/// </summary>
public static readonly DependencyProperty StarForegroundColorProperty =
DependencyProperty.Register("StarForegroundColor", typeof (SolidColorBrush),
typeof (Star),
new PropertyMetadata(new SolidColorBrush(Colors.Transparent),
OnStarForegroundColorChanged));
/// <summary>
/// StarOutlineColor Dependency Property
/// </summary>
public static readonly DependencyProperty StarOutlineColorProperty =
DependencyProperty.Register("StarOutlineColor", typeof (SolidColorBrush),
typeof (Star),
new PropertyMetadata(new SolidColorBrush(Colors.Transparent),
OnStarOutlineColorChanged));
/// <summary>
/// Value Dependency Property
/// </summary>
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof (double),
typeof (Star),
new PropertyMetadata(0.0,
OnValueChanged));
public Star()
{
DataContext = this;
InitializeComponent();
gdStar.Width = STAR_SIZE;
gdStar.Height = STAR_SIZE;
gdStar.Clip = new RectangleGeometry
{
Rect = new Rect(0, 0, STAR_SIZE, STAR_SIZE)
};
mask.Width = STAR_SIZE;
mask.Height = STAR_SIZE;
SizeChanged += Star_SizeChanged;
}
/// <summary>
/// Gets or sets the BackgroundColor property.
/// </summary>
public SolidColorBrush BackgroundColor
{
get { return (SolidColorBrush) GetValue(BackgroundColorProperty); }
set { SetValue(BackgroundColorProperty, value); }
}
/// <summary>
/// Gets or sets the StarForegroundColor property.
/// </summary>
public SolidColorBrush StarForegroundColor
{
get { return (SolidColorBrush) GetValue(StarForegroundColorProperty); }
set { SetValue(StarForegroundColorProperty, value); }
}
/// <summary>
/// Gets or sets the StarOutlineColor property.
/// </summary>
public SolidColorBrush StarOutlineColor
{
get { return (SolidColorBrush) GetValue(StarOutlineColorProperty); }
set { SetValue(StarOutlineColorProperty, value); }
}
/// <summary>
/// Gets or sets the Value property.
/// </summary>
public double Value
{
get { return (double) GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private void Star_SizeChanged(object sender, SizeChangedEventArgs e)
{
}
/// <summary>
/// Handles changes to the BackgroundColor property.
/// </summary>
private static void OnBackgroundColorChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var control = (Star) d;
control.gdStar.Background = (SolidColorBrush) e.NewValue;
control.mask.Fill = (SolidColorBrush) e.NewValue;
}
/// <summary>
/// Handles changes to the StarForegroundColor property.
/// </summary>
private static void OnStarForegroundColorChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var control = (Star) d;
control.starForeground.Fill = (SolidColorBrush) e.NewValue;
}
/// <summary>
/// Handles changes to the StarOutlineColor property.
/// </summary>
private static void OnStarOutlineColorChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var control = (Star) d;
control.starOutline.Stroke = (SolidColorBrush) e.NewValue;
}
/// <summary>
/// Handles changes to the Value property.
/// </summary>
private static void OnValueChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var starControl = (Star) d;
starControl.starForeground.Fill = Math.Abs(starControl.Value) <= 0 ? new SolidColorBrush(Colors.Gray) : starControl.StarForegroundColor;
var marginLeftOffset = (Int32) (starControl.Value*STAR_SIZE);
starControl.mask.Margin = new Thickness(marginLeftOffset, 0, 0, 0);
starControl.InvalidateArrange();
starControl.InvalidateMeasure();
}
}
} |
[assembly: Xamarin.Forms.Dependency(typeof(MasterDetail.Droid.Implementacion.PathService))]
namespace MasterDetail.Droid.Implementacion
{
using Interface;
using System;
using System.IO;
public class PathService : IPathService
{
public string GetDataBasePath()
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
return Path.Combine(path, "MiTurno.db3");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace GameAPI.Models
{
public class GameManager : IGameManager
{
public static readonly List<MatchDTO> matches = new List<MatchDTO>()
{
new MatchDTO{ Id = 1, Name = "Prvni", AccessToken = "access-token-prvni", State = MatchState.aktivni},
new MatchDTO{ Id = 2, Name = "Druhy", AccessToken = "access-token-druhy", State = MatchState.neaktivni},
new MatchDTO{ Id = 3, Name = "Treti", AccessToken = "access-token-treti", State = MatchState.aktivni },
new MatchDTO{ Id = 4, Name = "Ctvrty", AccessToken = "access-token-ctvrty", State = MatchState.neaktivni},
new MatchDTO{ Id = 5, Name = "Paty", AccessToken = "access-token-paty", State = MatchState.aktivni}
};
public List<LeaderboardScoreDTO> GetLeaderBoardByGameType(string gameType)
{
switch (gameType)
{
case "Akční":
return GetScore();
case "RPG":
return GetScore();
case "MMO":
return GetScore();
case "Sportovní":
return GetScore();
case "Strategické":
return GetScore();
case "Závodní":
return GetScore();
default:
return new List<LeaderboardScoreDTO>();
}
}
private List<LeaderboardScoreDTO> GetScore()
{
List<LeaderboardScoreDTO> result = new List<LeaderboardScoreDTO>();
int score = 10;
for (int i = 1; i < 11; i++)
{
result.Add(new LeaderboardScoreDTO { PlayerName = "Player"+i, Score = score});
score--;
}
return result;
}
public List<MatchDTO> GetActiveMatches()
{
return matches.Where(x => x.State == MatchState.aktivni).ToList();
}
public string JoinMatch(int matchId)
{
var matchToJoin = matches.Find(x => x.Id == matchId);
return matchToJoin.AccessToken;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using cyrka.api.common.events;
using cyrka.api.domain.customers.commands.change;
using cyrka.api.domain.customers.commands.changeTitle;
using cyrka.api.domain.customers.commands.register;
using cyrka.api.domain.customers.commands.registerTitle;
using cyrka.api.domain.customers.commands.removeTitle;
using cyrka.api.domain.customers.commands.retire;
namespace cyrka.api.domain.customers
{
public class CustomerAggregate
{
public string Id { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public Title[] Titles { get; private set; }
public bool IsRetired { get; private set; }
public CustomerAggregate()
{
Titles = new Title[0];
IsRetired = false;
}
public void ApplyEvents(IEnumerable<EventData> eventDatas)
{
if (eventDatas == null)
return;
foreach (var eventData in eventDatas)
{
switch (eventData)
{
case CustomerRegistered customerRegistered:
ApplyEvent(customerRegistered);
break;
case CustomerChanged customerChanged:
ApplyEvent(customerChanged);
break;
case TitleRegistered titleRegistered:
ApplyEvent(titleRegistered);
break;
case TitleChanged titleChanged:
ApplyEvent(titleChanged);
break;
case CustomerRetired customerRetired:
ApplyEvent(customerRetired);
break;
}
}
}
private void ApplyEvent(CustomerRegistered customerEvent)
{
// if (Id == null)
// return;
Id = customerEvent.AggregateId;
Name = customerEvent.Name;
Description = customerEvent.Description;
}
private void ApplyEvent(CustomerChanged customerEvent)
{
Name = customerEvent.Name;
Description = customerEvent.Description;
}
private void ApplyEvent(TitleRegistered customerEvent)
{
var newTitle = new Title
{
Id = customerEvent.TitleId,
Name = customerEvent.Name,
NumberOfSeries = customerEvent.NumberOfSeries,
Description = customerEvent.Description
};
var list = Titles
.ToList();
list.Add(newTitle);
Titles = list.ToArray();
}
private void ApplyEvent(TitleChanged customerEvent)
{
var exTitle = Titles
.FirstOrDefault(t => t.Id == customerEvent.TitleId);
if (exTitle == null)
return;
exTitle.Name = customerEvent.Name;
exTitle.NumberOfSeries = customerEvent.NumberOfSeries;
exTitle.Description = customerEvent.Description;
var list = Titles
.ToList();
list.RemoveAll(t => t.Id == exTitle.Id);
list.Add(exTitle);
Titles = list.ToArray();
}
private void ApplyEvent(CustomerRetired customerEvent)
{
IsRetired = true;
}
private void ApplyEvent(TitleRemoved customerEvent)
{
var exTitle = Titles
.FirstOrDefault(t => t.Id == customerEvent.TitleId);
if (exTitle == null)
return;
var list = Titles
.ToList();
list.RemoveAll(t => t.Id == exTitle.Id);
Titles = list.ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using API.Model;
using API.BL;
namespace coucheAPI.Controllers
{
[Route("api/[controller]")]
public class CategorieController : Controller
{
[HttpGet]
public List<Categorie> Get()
{
return BL_Api.GetCategorie();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIBoard : View
{
public const int m_startTime = 50;
public override string M_Name
{
get
{
return Consts.V_Board;
}
}
[SerializeField]
private Text m_textDistance;
private int m_distance = 0;
public int M_Distance
{
get
{
return m_distance;
}
set
{
m_distance = value;
m_textDistance.text = value.ToString() + "米";
}
}
[SerializeField]
private Text m_textCoin;
private int m_coin = 0;
public int M_Coin
{
get
{
return m_coin;
}
set
{
m_coin = value;
m_textCoin.text = m_coin.ToString();
}
}
[SerializeField]
private Text m_textTimer;
[SerializeField]
private Slider m_sliderTimer;
private float m_time;
public float M_Timer
{
get
{
return m_time;
}
set
{
if (value < 0)
{
value = 0;
MVC.SendEvent(Consts.E_EndGameController);
}
if (value > m_startTime)
{
value = m_startTime;
}
m_time = value;
m_textTimer.text = m_time.ToString("f2") + "s";
m_sliderTimer.value = value / m_startTime;
}
}
private int m_goalCount = 0;
public int M_GoalCount
{
get { return m_goalCount; }
set { m_goalCount = value; }
}
[SerializeField]
private Button m_magnetBtn;
[SerializeField]
private Button m_multiplyBtn;
[SerializeField]
private Button m_invincibleBtn;
private IEnumerator m_multiplyCoroutine;
private IEnumerator m_magnetCoroutine;
private IEnumerator m_invincibleCoroutine;
[SerializeField]
private Text m_textGizmoMultiply;
[SerializeField]
private Text m_textGizmoMagnet;
[SerializeField]
private Text m_textGizmoInvincible;
private int m_skillTime
{
get { return Game.M_Instance.M_GM.M_SkillTime; }
}
[SerializeField]
private Button m_btnGoal;
[SerializeField]
private Slider m_sliderGoal;
private void Awake()
{
M_Timer = m_startTime;
UpdateUI();
}
private void Update()
{
if (Game.M_Instance.M_GM.M_IsPlay && !Game.M_Instance.M_GM.M_IsPause)
{
M_Timer -= Time.deltaTime;
}
}
public override void RegisterAttentionEvent()
{
M_AttentionList.Add(Consts.E_UpdateDisAttention);
M_AttentionList.Add(Consts.E_UpdateCoinAttention);
M_AttentionList.Add(Consts.E_HitAddTimeAttention);
M_AttentionList.Add(Consts.E_HitGoalTriggerAttention);
M_AttentionList.Add(Consts.E_ShootGoalAttention);
}
public override void HandleEvent(string name, object data)
{
switch (name)
{
case Consts.E_UpdateDisAttention:
DistanceArgs e1 = data as DistanceArgs;
M_Distance = e1.M_Distance;
break;
case Consts.E_UpdateCoinAttention:
CoinArgs e2 = data as CoinArgs;
M_Coin += e2.M_Coin;
break;
case Consts.E_HitAddTimeAttention:
M_Timer += 20;
break;
case Consts.E_HitGoalTriggerAttention:
ShowGoalClick();
break;
case Consts.E_ShootGoalAttention:
M_GoalCount += 1;
break;
}
}
void ShowGoalClick()
{
StartCoroutine(StartCountDown());
}
IEnumerator StartCountDown()
{
m_btnGoal.interactable = true;
m_sliderGoal.value = 1;
while (m_sliderGoal.value > 0)
{
if (Game.M_Instance.M_GM.M_IsPlay && !Game.M_Instance.M_GM.M_IsPause)
{
m_sliderGoal.value -= 0.85f * Time.deltaTime;
}
yield return null;
}
m_btnGoal.interactable = false;
m_sliderGoal.value = 0;
}
public void OnPauseClick()
{
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_Button);
PauseArgs e = new PauseArgs
{
M_Coin = this.M_Coin,
M_Distance = this.M_Distance,
M_Score = this.M_Coin + this.M_Distance * (M_GoalCount+1)
};
MVC.SendEvent(Consts.E_PauseGameController,e);
}
public void UpdateUI()
{
ShowOrHide(Game.M_Instance.M_GM.M_Invincible, m_invincibleBtn);
ShowOrHide(Game.M_Instance.M_GM.M_Magnet, m_magnetBtn);
ShowOrHide(Game.M_Instance.M_GM.M_Multiply, m_multiplyBtn);
}
void ShowOrHide(int i,Button btn)
{
if (i > 0)
btn.interactable = true;
else
btn.interactable = false;
}
public void OnMagnetClick()
{
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_Button);
ItemArgs e = new ItemArgs
{
M_HitCount = 1,
M_Kind = ItemKind.ItemMagnet
};
MVC.SendEvent(Consts.E_HitItemController, e);
}
public void OnMultiplyClick()
{
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_Button);
ItemArgs e = new ItemArgs
{
M_HitCount = 1,
M_Kind = ItemKind.ItemMultiply
};
MVC.SendEvent(Consts.E_HitItemController, e);
}
public void OnInvincibleClick()
{
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_Button);
ItemArgs e = new ItemArgs
{
M_HitCount = 1,
M_Kind = ItemKind.ItemInvincible
};
MVC.SendEvent(Consts.E_HitItemController, e);
}
string GetTime(float time)
{
return ((int)time + 1).ToString();
}
public void HitMultiply()
{
if (m_multiplyCoroutine != null)
StopCoroutine(m_multiplyCoroutine);
m_multiplyCoroutine = MultiplyCoroutine();
StartCoroutine(m_multiplyCoroutine);
}
IEnumerator MultiplyCoroutine()
{
float timer = m_skillTime;
m_textGizmoMultiply.transform.parent.gameObject.SetActive(true);
while (timer > 0)
{
if (Game.M_Instance.M_GM.M_IsPlay && !Game.M_Instance.M_GM.M_IsPause)
{
timer -= Time.deltaTime;
m_textGizmoMultiply.text = GetTime(timer);
}
yield return null;
}
m_textGizmoMultiply.transform.parent.gameObject.SetActive(false);
}
public void HitMagnet()
{
if (m_magnetCoroutine != null)
StopCoroutine(m_magnetCoroutine);
m_magnetCoroutine = MagnetCoroutine();
StartCoroutine(m_magnetCoroutine);
}
IEnumerator MagnetCoroutine()
{
m_textGizmoMagnet.transform.parent.gameObject.SetActive(true);
float timer = m_skillTime;
while (timer > 0)
{
if (Game.M_Instance.M_GM.M_IsPlay && !Game.M_Instance.M_GM.M_IsPause)
{
timer -= Time.deltaTime;
m_textGizmoMagnet.text = GetTime(timer);
}
yield return null;
}
m_textGizmoMagnet.transform.parent.gameObject.SetActive(false);
}
public void HitInvincible()
{
if (m_invincibleCoroutine != null)
StopCoroutine(m_invincibleCoroutine);
m_invincibleCoroutine = InvincibleCoroutine();
StartCoroutine(m_invincibleCoroutine);
}
IEnumerator InvincibleCoroutine()
{
float timer = m_skillTime;
m_textGizmoInvincible.transform.parent.gameObject.SetActive(true);
while (timer > 0)
{
if (Game.M_Instance.M_GM.M_IsPlay && !Game.M_Instance.M_GM.M_IsPause)
{
timer -= Time.deltaTime;
m_textGizmoInvincible.text = GetTime(timer);
}
yield return null;
}
m_textGizmoInvincible.transform.parent.gameObject.SetActive(false);
}
public void OnGoalBtnClick()
{
Game.M_Instance.M_Sound.PlayEffect(Consts.S_Se_UI_Button);
MVC.SendEvent(Consts.E_ClickGoalButtonAttention);
m_btnGoal.interactable = false;
m_sliderGoal.value = 0;
}
public void Show()
{
gameObject.SetActive(true);
}
public void Hide()
{
gameObject.SetActive(false);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using V50_IDOMBackOffice.AspxArea.MasterData.Models;
using V50_IDOMBackOffice.AspxArea.MasterData.Controllers;
using IdomOffice.Interface.BackOffice.MasterData;
using V50_IDOMBackOffice.AspxArea.Helper;
using DevExpress.Web;
namespace V50_IDOMBackOffice.AspxArea.MasterData.Forms
{
public partial class TouristUnitView : System.Web.UI.Page
{
TouristUnitController controller = new TouristUnitController();
protected void Page_Load(object sender, EventArgs e)
{
Bind();
}
protected void GridTouristUnitView_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
{
//TODO: Zasto ovdje pravis model i punis sa podacima kada kada ti je potreban samo id ????
string id = e.Keys[0].ToString();
controller.DeleteTouristUnit(id);
e.Cancel = true;
GridTouristUnitView.CancelEdit();
Bind();
}
protected void GridTouristUnitView_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
TouristUnitViewModel model = new TouristUnitViewModel();
model.Bathrooms = e.NewValues["Bathrooms"] == null ? 0 : (int)e.NewValues["Bathrooms"];
model.Bedroom = e.NewValues["Bedroom"]==null? 0:(int)e.NewValues["Bedroom"];
model.SiteCode = e.NewValues["SiteCode"].ToString()?? string.Empty;
//model.SiteName = e.NewValues["SiteName"].ToString()?? string.Empty;
//model.Beds = e.NewValues["Beds"] == null ? 0 : (int)e.NewValues["Beds"];
//model.ImageGalleryPath = e.NewValues["ImageGalleryPath"].ToString()?? string.Empty;
// model.ImageThumbnailsPath = e.NewValues["ImageThumbnailsPath"].ToString()?? string.Empty;
model.CloseDate = e.NewValues["CloseDate"] == null ? DateTime.Now : (DateTime)e.NewValues["CloseDate"];
//model.CountryName = e.NewValues["CountryName"].ToString()?? string.Empty;
model.MaxAdults = e.NewValues["MaxAdults"] == null ? 0 : (int)e.NewValues["MaxAdults"];
model.MaxPersons = e.NewValues["MaxPersons"] == null ? 0 : (int)e.NewValues["MaxPersons"];
model.Description = e.NewValues["Description"] == null ? string.Empty : e.NewValues["Description"].ToString();
model.MobilhomeArea = e.NewValues["MobilhomeArea"] == null ? 0 : (int)e.NewValues["MobilhomeArea"];
model.OpenDate = e.NewValues["OpenDate"] == null ? DateTime.Now : (DateTime)e.NewValues["OpenDate"];
//model.PlaceName = e.NewValues["PlaceName"].ToString()?? string.Empty;
//model.PurchasePriceListId = e.NewValues["PurchasePriceListId"].ToString()?? string.Empty;
//model.RegionName = e.NewValues["RegionName"].ToString()?? string.Empty;
model.TerraceArea = e.NewValues["TerraceArea"] == null ? 0 : (int)e.NewValues["TerraceArea"];
model.TourOperatorCode = e.NewValues["TourOperatorCode"].ToString()?? string.Empty;
model.TravelServiceProvider = e.NewValues["TravelServiceProvider"].ToString()?? string.Empty;
model.UnitCode = e.NewValues["UnitCode"].ToString()?? string.Empty;
//model.UnitOfferInfoList = (List<UnitOfferInfo>)e.NewValues["SiteName"];
model.UnitTitel = e.NewValues["UnitTitel"].ToString()?? string.Empty;
bool contains = controller.ContainsUnitCode(model.UnitCode);
TouristUnitViewModel touristunit = new TouristUnitViewModel();
if (model.SiteCode!=null)
{ //TODO: Ove podatke ne treba ovdje puniti nego u Repositoriju
// prebaciti model u Repository i dodati property koje fale
//Ili pozvati jednu funkciju koja vraca jedan objekt sa svim GEO informacijama
touristunit = controller.GetTouristUnit(model);
}
if (!contains)
{
controller.AddTouristUnit(touristunit);
}
e.Cancel = true;
GridTouristUnitView.CancelEdit();
Bind();
}
protected void GridTouristUnitView_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
var listSaP = (List<TouristUnitViewModel>)GridTouristUnitView.DataSource;
TouristUnitViewModel model = listSaP.Find(m => m.id == e.Keys[0].ToString());
model.Bathrooms = e.NewValues["Bathrooms"] == null ? 0 : (int)e.NewValues["Bathrooms"];
model.Bedroom = e.NewValues["Bedroom"] == null ? 0 : (int)e.NewValues["Bedroom"];
// model.SiteCode = e.NewValues["SiteCode"].ToString() ?? string.Empty;
//model.SiteName = e.NewValues["SiteName"].ToString() ?? string.Empty;
//model.Beds = e.NewValues["Beds"] == null ? 0 : (int)e.NewValues["Beds"];
//model.ImageGalleryPath = e.NewValues["ImageGalleryPath"].ToString() ?? string.Empty;
//model.ImageThumbnailsPath = e.NewValues["ImageThumbnailsPath"].ToString() ?? string.Empty;
model.CloseDate = e.NewValues["CloseDate"] == null ? DateTime.Now : (DateTime)e.NewValues["CloseDate"];
//model.CountryName = e.NewValues["CountryName"].ToString() ?? string.Empty;
model.MaxAdults = e.NewValues["MaxAdults"] == null ? 0 : (int)e.NewValues["MaxAdults"];
model.Description = e.NewValues["Description"] == null ? string.Empty : e.NewValues["Description"].ToString();
model.MaxPersons = e.NewValues["MaxPersons"] == null ? 0 : (int)e.NewValues["MaxPersons"];
model.MobilhomeArea = e.NewValues["MobilhomeArea"] == null ? 0 : (int)e.NewValues["MobilhomeArea"];
model.OpenDate = e.NewValues["OpenDate"] == null ? DateTime.Now : (DateTime)e.NewValues["OpenDate"];
//model.PlaceName = e.NewValues["PlaceName"].ToString() ?? string.Empty;
//model.RegionName = e.NewValues["RegionName"].ToString() ?? string.Empty;
model.TerraceArea = e.NewValues["TerraceArea"] == null ? 0 : (int)e.NewValues["TerraceArea"];
model.TourOperatorCode = e.NewValues["TourOperatorCode"].ToString() ?? string.Empty;
model.TravelServiceProvider = (string) e.NewValues["TravelServiceProvider"] ?? string.Empty;
model.UnitCode = e.NewValues["UnitCode"].ToString() ?? string.Empty;
//model.UnitOfferInfoList = (List<UnitOfferInfo>)e.NewValues["SiteName"];
model.UnitTitel = e.NewValues["UnitTitel"].ToString() ?? string.Empty;
TouristUnitViewModel touristunit = new TouristUnitViewModel();
if (model.SiteCode != null)
{
//TODO: Ove podatke ne treba ovdje puniti nego u Repositoriju
// prebaciti model u Repository i dodati property koje fale
//Ili pozvati jednu funkciju koja vraca jedan objekt sa svim GEO informacijama
touristunit = controller.GetTouristUnit(model);
}
//bool contains = controller.ContainsUnitCode(model.UnitCode);
//if (!contains)
//{
controller.UpdateTouristUnit(touristunit);
//}
e.Cancel = true;
GridTouristUnitView.CancelEdit();
Bind();
}
private void Bind()
{
GridTouristUnitView.DataSource = controller.Init();
GridTouristUnitView.DataBind();
}
protected void GridTouristUnitView_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridViewCustomButtonCallbackEventArgs e)
{
ASPxGridView grid = sender as ASPxGridView;
int index = e.VisibleIndex;
if (e.ButtonID== "ButtonPriceList")
{
string unitcode = grid.GetRowValues(index, "UnitCode").ToString();
string sitecode = grid.GetRowValues(index, "SiteCode").ToString();
// Response.Redirect("~/AspxArea/PriceList/Forms/PurchasePriceForm.aspx?sc=" + sitecode + "&oc=" + unitcode);
ASPxWebControl.RedirectOnCallback(VirtualPathUtility.ToAbsolute("~/AspxArea/PriceList/Forms/PurchasePriceForm.aspx?sc=" + sitecode + "&uc=" + unitcode));
}
else if(e.ButtonID=="ButtonUnit")
{
string unitcode = grid.GetRowValues(index, "UnitCode").ToString();
string sitecode = grid.GetRowValues(index, "SiteCode").ToString();
string tourOperatorCode = grid.GetRowValues(index, "TourOperatorCode").ToString();
string id = grid.GetRowValues(index, "id").ToString();
ASPxWebControl.RedirectOnCallback(VirtualPathUtility.ToAbsolute("~/AspxArea/MasterData/Forms/UnitForm.aspx?id="+ id+"&sc=" + sitecode + "&uc=" + unitcode + "&to=" + tourOperatorCode + "&plt=" + "1"));
}
}
protected void GridTouristUnitView_DataBinding(object sender, EventArgs e)
{
GridTouristUnitView.ForceDataRowType(typeof(TouristUnitViewModel));
}
protected void GridTouristUnitView_Init(object sender, EventArgs e)
{
GridTouristUnitView.Columns["id"].Visible = false;
GridTouristUnitView.Columns["ImageGalleryPath"].Visible = false;
GridTouristUnitView.Columns["ImageThumbnailsPath"].Visible = false;
GridTouristUnitView.Columns["Bathrooms"].Visible = false;
GridTouristUnitView.Columns["Bedroom"].Visible = false;
// GridTouristUnitView.Columns["Beds"].Visible = false;
GridTouristUnitView.Columns["TerraceArea"].Visible = false;
GridTouristUnitView.Columns["PurchasePriceListId"].Visible = false;
GridTouristUnitView.Columns["TourOperatorCode"].Visible = false;
GridTouristUnitView.Columns["TravelServiceProvider"].Visible = false;
GridTouristUnitView.Columns["Description"].Visible = false;
GridTouristUnitView.Columns["MobilhomeArea"].Visible = false;
GridTouristUnitView.Columns["MaxPersons"].Visible = false;
GridTouristUnitView.Columns["MaxAdults"].Visible = false;
}
protected void GridTouristUnitView_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
{
if (GridTouristUnitView.IsNewRowEditing)
GridTouristUnitView.DoRowValidation();
}
protected void GridTouristUnitView_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
{
//GridValidation.ValidateInt("Bedroom", sender, e);
//GridValidation.ValidateInt("MaxAdults", sender, e);
//GridValidation.ValidateInt("MaxPersons", sender, e);
//GridValidation.ValidateInt("MobilhomeArea", sender, e);
//GridValidation.ValidateInt("TerraceArea", sender, e);
////GridValidation.ValidateLength("Bathrooms", sender, e);
//GridValidation.ValidateFixedLength("SiteCode", sender, e);
//GridValidation.ValidateLength("SiteName", sender, e);
////GridValidation.ValidateLength("Beds", sender, e);
//GridValidation.ValidateLength("ImageGalleryPath", sender, e);
//GridValidation.ValidateLength("ImageThumbnailsPath", sender, e);
//GridValidation.ValidateLength("PlaceName", sender, e);
//GridValidation.ValidateLength("PurchasePriceListId", sender, e);
//GridValidation.ValidateLength("RegionName", sender, e);
//GridValidation.ValidateLength("TourOperatorCode", sender, e);
//GridValidation.ValidateLength("TravelServiceProvider", sender, e);
//GridValidation.ValidateFixedLength("UnitCode", sender, e);
//GridValidation.ValidateLength("UnitTitel", sender, e);
}
protected void GridTouristUnitView_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
if (e.Column.FieldName == "SiteCode")
{
ASPxComboBox combo = (ASPxComboBox)e.Editor;
combo.DataSource = controller.GetSiteCodes();
combo.DataBind();
// Combo SiteCode nije moguce mjenjati u edit modu ( mjenjanje je moguce samo kod kreiranja novog recorda)
combo.Enabled = e.Column.Grid.IsNewRowEditing;
}
if(!e.Column.Grid.IsNewRowEditing)
{
//Kod editiranja UnitCode nije moguce mjenjati i zato je ReadOnli
if (e.Column.FieldName == "UnitCode")
e.Editor.ReadOnly = true;
}
}
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace Inventory.Models
{
public class AddressModel : BaseModel
{
public Guid RowGuid { get; set; }
public Guid CustomerGuid { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int CustomerId { get; set; }
private int _cityId;
[Required]
public int CityId
{
get => _cityId;
set => Set(ref _cityId, value);
}
private CityModel _city;
public CityModel City
{
get => _city;
set => Set(ref _city, value);
}
private int _streetId;
[Required]
public int StreetId
{
get => _streetId;
set => Set(ref _streetId, value);
}
private StreetModel _street;
public StreetModel Street
{
get => _street;
set => Set(ref _street, value);
}
[Required]
public string House { get; set; }
/// <summary>
/// Номер квартиры/офиса
/// </summary>
public string Apartment { get; set; }
/// <summary>
/// Корпус
/// </summary>
public string Housing { get; set; }
/// <summary>
/// Подъезд
/// </summary>
public string Entrance { get; set; }
/// <summary>
/// Домофон
/// </summary>
public string Intercom { get; set; }
/// <summary>
/// Этаж
/// </summary>
public string Floor { get; set; }
public bool IsPrimary { get; set; }
public override void Merge(ObservableObject source)
{
if (source is AddressModel model)
{
Merge(model);
}
}
public void Merge(AddressModel source)
{
if (source == null)
{
return;
}
Id = source.Id;
RowGuid = source.RowGuid;
CustomerGuid = source.CustomerGuid;
Name = source.Name;
CustomerId = source.CustomerId;
CityId = source.CityId;
StreetId = source.StreetId;
House = source.House;
Apartment = source.Apartment;
Housing = source.Housing;
Entrance = source.Entrance;
Intercom = source.Intercom;
Floor = source.Floor;
IsPrimary = source.IsPrimary;
}
public override string ToString()
{
return $"{Name}".Trim();
}
}
}
|
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 App_GIIS
{
public partial class FormMain : Form
{
private bool dragMainForm = false;
private Point startPositionMainForm = new Point(0, 0);
private Form activeForm = null;
public FormMain()
{
InitializeComponent();
}
private void OpenChildForm(Form childForm)
{
if (activeForm != null)
activeForm.Close();
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panelChildForm.Controls.Add(childForm);
panelChildForm.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
private void Close_Click(object sender, EventArgs e)
{
System.IO.File.Delete("../../../Data/test2.jpg");
System.IO.File.Delete("../../../Data/test.jpg");
this.Close();
}
private void buttonMinimize_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void buttonFilteringImage_Click(object sender, EventArgs e)
{
this.OpenChildForm(new FormFilteringImage());
}
#region functions of panel Header
private void panelHeader_MouseDown(object sender, MouseEventArgs e)
{
dragMainForm = true;
startPositionMainForm = new Point(e.X, e.Y);
}
private void panelHeader_MouseMove(object sender, MouseEventArgs e)
{
if (dragMainForm)
{
Point point = PointToScreen(e.Location);
this.Location = new Point(point.X - startPositionMainForm.X, point.Y - startPositionMainForm.Y);
}
}
private void panelHeader_MouseUp(object sender, MouseEventArgs e)
{
dragMainForm = false;
}
#endregion
private void buttonMaxRestore_Click(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Maximized)
{
this.WindowState = FormWindowState.Normal;
buttonMaxRestore.BackgroundImage = Image.FromFile(@"../../../Data/Launcher/ButtonMaximize.png");
}
else
{
this.WindowState = FormWindowState.Maximized;
buttonMaxRestore.BackgroundImage = Image.FromFile(@"../../../Data/Launcher/ButtonRestore.png");
}
}
private void buttonFindContours_Click(object sender, EventArgs e)
{
this.OpenChildForm(new FormFindContours());
}
private void buttonSnow_Click(object sender, EventArgs e)
{
this.OpenChildForm(new FormSnow());
}
private void buttonBMP_Click(object sender, EventArgs e)
{
this.OpenChildForm(new FormBMP());
}
}
}
|
namespace FailureSimulator.Core.IO
{
/// <summary>
/// Интерфейс парсера проектов
/// </summary>
public interface IProjectParser
{
/// <summary>
/// Читает проект из файла
/// </summary>
/// <param name="filename">Имя файла</param>
/// <returns></returns>
SimulationProject ReadProject(string filename);
/// <summary>
/// Сохраняет проект в файл
/// </summary>
/// <param name="filename">Имя файла</param>
/// <param name="project">Проект</param>
void SaveProject(string filename, SimulationProject project);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.