text stringlengths 13 6.01M |
|---|
namespace AbstractFactory
{
public class CarroLuxo : CarroFactory
{
public override Roda MontarRoda()
{
return new RodaLigaLeve();
}
public override Som MontarSom()
{
return new Bluetooh();
}
}
}
|
using System.Collections.Generic;
public class SCServiceUtils
{
public static string AppendClientId(string baseUrl)
{
if(baseUrl.EndsWith("?")) {
return string.Concat(baseUrl, "client_id=", UniTunesConsts.SC_CLIENT_ID);
}
else {
if(baseUrl.Contains("?")) {
return string.Concat(baseUrl, "&client_id=", UniTunesConsts.SC_CLIENT_ID);
}
return string.Concat(baseUrl, "?client_id=", UniTunesConsts.SC_CLIENT_ID);
}
}
public static string BuildEndpoint(string scApiMethod, Dictionary<string, string> urlVars, bool appendClientId)
{
string endpoint = UniTunesConsts.SC_API;
if(!string.IsNullOrEmpty(scApiMethod)) {
endpoint = endpoint + scApiMethod;
}
//return if not url vars provided
if(urlVars == null) { return endpoint; }
endpoint = endpoint + "?";
//append url vars
foreach(KeyValuePair<string, string> kvp in urlVars) {
if(!endpoint.EndsWith("?")) {
endpoint = string.Concat(endpoint, "&");
}
endpoint = string.Concat(endpoint, kvp.Key, "=", kvp.Value);
}
//append client_id
if(appendClientId) {
endpoint = AppendClientId(endpoint);
}
return endpoint;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TinhLuong.Models;
using TinhLuongBLL;
namespace TinhLuong.Controllers
{
public class PassDefaultController : BaseController
{
// GET: PassDefault
SaveLog sv = new SaveLog();
[CheckCredential(RoleID = "PASS_DEFAULT")]
public ActionResult Index()
{
// sv.save(Session[SessionCommon.Username].ToString(), "He thong->Mat khau mac dinh");
ViewBag.PassDefault = new PhanQuyenBLL().GetPassDefault();
return View();
}
[HttpGet]
public ActionResult ChangePass()
{
return View();
}
[HttpPost]
public ActionResult ChangePass(string NewPass)
{
if (!string.IsNullOrWhiteSpace(NewPass))
{
var rs = new PhanQuyenBLL().ChangePass_Default(NewPass);
if (rs > 0)
{
sv.save(Session[SessionCommon.Username].ToString(), "He thong->Mat khau mac dinh->Thay doi mat khau thanh cong-pass-" + NewPass);
setAlert("Thay đổi mật khẩu mặc định thành công", "success");
}
else
{
sv.save(Session[SessionCommon.Username].ToString(), "He thong->Mat khau mac dinh->Thay doi mat khau that bai-pass-"+NewPass);
setAlert("Cập nhật thất bại", "error");
}
}
else setAlert("Vui lòng không để trống trường!", "error");
return Redirect("/passdefault");
}
}
} |
namespace Bolster.API.Status.Stateless
{
public class Failure : Result, IFailure
{
public string FailureReason { get; }
public Failure(string failureReason = null) {
FailureReason = failureReason;
}
public Failure Reason(string failureReason) =>
new Failure(failureReason);
public override bool IsSuccess => false;
public override bool IsFailure => true;
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using Aop.Api.Util;
using AopSdk.Core.WebTest.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace AopSdk.Core.WebTest.Areas.NoticeTest.Controllers
{
public class NotifyController : Controller
{
private readonly IOptions<AliPayConfig> _settings;
public NotifyController(IOptions<AliPayConfig> _settings)
{
this._settings = _settings;
}
// GET
public IActionResult Index()
{
/* 实际验证过程建议商户添加以下校验。
1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号,
2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额),
3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候,一个商户可能有多个seller_id/seller_email)
4、验证app_id是否为该商户本身。
*/
var sArray = GetRequestPost();
var msg = string.Empty;
if (sArray.Count != 0)
{
var flag = AlipaySignature.RSACheckV1(sArray, _settings.Value.alipay_public_key,
_settings.Value.charset, _settings.Value.sign_type, false);
if (flag)
{
//交易状态
//判断该笔订单是否在商户网站中已经做过处理
//如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
//请务必判断请求时的total_amount与通知时获取的total_fee为一致的
//如果有做过处理,不执行商户的业务程序
//注意:
//退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知
string trade_status = Request.Form["trade_status"];
msg = "success";
}
else
{
msg = "fail";
}
}
System.IO.File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "result.txt"), msg);
return Content(msg);
}
public Dictionary<string, string> GetRequestPost()
{
var sArray = new Dictionary<string, string>();
var coll = Request.Form;
foreach (var item in coll) sArray.Add(item.Key, item.Value);
return sArray;
}
}
} |
using UnityEngine;
using System;
using System.IO;
public enum GameDiffState : int
{
GameDiffLow,
GameDiffMiddle,
GameDiffHigh
}
public class GlobalData {
private static GlobalData Instance;
public static int NetWorkGroup = 0;
static string startCoinInfo = "";
static string FilePath = "";
static public string fileName = "../config/XKGameConfig.xml";
static public HandleJson handleJsonObj = null;
public static int GameAudioVolume = 7;
static public string bikeGameCtrl = "bikegamectrl";
static public string netCtrl = "_NetCtrl";
static public string NetworkServerNet = "_NetworkServerNet";
public static Vector3 HiddenPosition = new Vector3(0f, -1000f, 0f);
public bool IsActiveJuLiFu;
public float PlayerAmmoFrequency = 10f;
public float MinDistancePlayer = 50f;
public static float PlayerPowerShipMax = 2000f;
private GlobalData()
{
//gameLeve=GameLeve.None;
gameLeve = (GameLeve)Application.loadedLevel;
gameMode = GameMode.None;
//InitPlayer();
}
// public void InitPlayer()
// {
// player=new Player();
// player.Energy = 100f;
// player.Speed = 0;
// player.Score = 0;
// player.Life = 30;
// player.LotteryCount = 0;
// player.FinalRank = 8;
// }
public static GlobalData GetInstance()
{
if(Instance==null)
{
Instance=new GlobalData();
Instance.InitInfo();
if (!Directory.Exists(FilePath)) {
Directory.CreateDirectory(FilePath);
}
//init gameMode
Instance.gameMode = GameMode.OnlineMode;
if(Application.loadedLevel == (int)GameLeve.Waterwheel)
{
Instance.gameMode = GameMode.SoloMode;
}
if(handleJsonObj == null)
{
handleJsonObj = HandleJson.GetInstance();
}
//start coin info
startCoinInfo = handleJsonObj.ReadFromFileXml(fileName, "START_COIN");
if(startCoinInfo == null || startCoinInfo == "")
{
startCoinInfo = "1";
handleJsonObj.WriteToFileXml(fileName, "START_COIN", startCoinInfo);
}
Instance.XUTOUBI = Convert.ToInt32( startCoinInfo );
//Instance.XUTOUBI = 3; //test
//free mode
bool isFreeModeTmp = false;
string modeGame = handleJsonObj.ReadFromFileXml(fileName, "GAME_MODE");
if(modeGame == null || modeGame == "")
{
modeGame = "1";
handleJsonObj.WriteToFileXml(fileName, "GAME_MODE", modeGame);
}
if(modeGame == "0")
{
isFreeModeTmp = true;
}
//isFreeModeTmp = true; //test
Instance.IsFreeMode = isFreeModeTmp;
if(Application.loadedLevel == (int)GameLeve.Movie && Application.loadedLevelName == GameLeve.Movie.ToString())
{
Toubi.GetInstance().ShowInsertCoinImg();
}
//output caiPiao
/*bool isOutput = true;
string outputStr = handleJsonObj.ReadFromFileXml(fileName, "GAME_OUTPUT_TICKET");
if(outputStr == null || outputStr == "")
{
outputStr = "1";
handleJsonObj.WriteToFileXml(fileName, "GAME_OUTPUT_TICKET", outputStr);
}
if(outputStr == "0")
{
isOutput = false;
}
Instance.IsOutputCaiPiao = isOutput;*/
//coin to card num
/*string ticketNumStr = handleJsonObj.ReadFromFileXml(fileName, "GAME_TICKET_NUM");
if(ticketNumStr == null || ticketNumStr == "")
{
ticketNumStr = "10";
handleJsonObj.WriteToFileXml(fileName, "GAME_TICKET_NUM", ticketNumStr);
}
float ticketNum = (float)Convert.ToInt32( ticketNumStr );
Instance.CointToTicket = ticketNum;*/
//ticket rate
/*string ticketRateStr = handleJsonObj.ReadFromFileXml(fileName, "GAME_TICKET_RATE");
if(ticketRateStr == null || ticketRateStr == "")
{
ticketRateStr = "1";
handleJsonObj.WriteToFileXml(fileName, "GAME_TICKET_RATE", ticketRateStr);
}
Instance.TicketRate = ticketRateStr;*/
//game diff
string diffStr = handleJsonObj.ReadFromFileXml(fileName, "GAME_DIFFICULTY");
if(diffStr == null || diffStr == "")
{
diffStr = "1";
handleJsonObj.WriteToFileXml(fileName, "GAME_DIFFICULTY", diffStr);
}
Instance.GameDiff = diffStr;
string val = handleJsonObj.ReadFromFileXml(fileName, "GameAudioVolume");
if (val == null || val == "") {
val = "7";
handleJsonObj.WriteToFileXml(fileName, "GameAudioVolume", val);
}
GameAudioVolume = Convert.ToInt32(val);
//SetPanelCtrl.GetInstance();
}
return Instance;
}
void InitInfo()
{
FilePath = Application.dataPath + "/../config";
}
//public Player player;
public int XUTOUBI=3;
public bool IsFreeMode = false;
public bool IsOutputCaiPiao = true;
public string TicketRate = "1";
public float CointToTicket = 10f;
public string GameDiff = "1"; //0 -> diffLow, 1 -> diffMiddel, 2 -> diffHigh
public readonly int GAMETIME=90;
//public int xutoubi;
public delegate void EventHandel();
public GameMode gameMode;
public GameLeve gameLeve;
public bool playCartoonEnd;
//public event EventHandel IcoinCountChange;
private int _icon;
public int Icoin
{
get
{
return _icon;
}
set
{
_icon=value;
// if(IcoinCountChange!=null)
// {
// IcoinCountChange();
// }
}
}
public int BikeHeadSpeedState = 2;
public int BikeZuLiDengJi = 0;
}
public enum GameMode
{
None,
SoloMode,
OnlineMode
}
public enum GameLeve:int
{
None = -1,
Movie = 0,
Waterwheel = 1,
WaterwheelNet = 2,
SetPanel = 3
} |
using System;
using System.Collections.Generic;
using System.Linq;
public class ABC118B
{
public static void Main()
{
var split = Console.ReadLine().Split(' ');
var n = int.Parse(split[0]);
var m = int.Parse(split[1]);
var list = new int[m];
for(int i = 0;i<n;i++){
foreach(var a in Console.ReadLine().Split(' ').Skip(1)){
var a_i = int.Parse(a);
list[a_i-1]++;
}
}
var count = 0;
foreach(var a in list){
if(a==n)count++;
}
Console.WriteLine(count);
}
} |
using Fingo.Auth.DbAccess.Models.Policies.Enums;
using Fingo.Auth.Domain.Policies.ConfigurationClasses;
namespace Fingo.Auth.Domain.Policies.Factories.Actions.Interfaces
{
public interface IGetUserPolicyConfigurationOrDefaultFromProject
{
PolicyConfiguration Invoke(int userId , Policy policy , int projectId);
}
} |
using SecuritySite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SecuritySite.Providers
{
public class AccountInfoProvider
{
public bool IsUserExistByLogin(string login)
{
try
{
using (UserContext _db = new UserContext())
{
var users = from u in _db.Users
where u.Login == login
select u;
if (users.Count() > 0)
return true;
}
}
catch
{
}
return false;
}
public bool IsUserExistByEMail(string email)
{
try
{
using (UserContext _db = new UserContext())
{
var users = from u in _db.Users
where u.Email == email
select u;
if (users.Count() > 0)
return true;
}
}
catch
{
}
return false;
}
public int GetUserId(string login)
{
int id = 0;
try
{
using (UserContext _db = new UserContext())
{
id = (from u in _db.Users
where u.Login == login
select u).FirstOrDefault().Id;
}
}
catch
{
}
return id;
}
public User GetUserById(string Token)
{
User user;
try
{
int id = Int32.Parse(Token);
using (UserContext _db = new UserContext())
{
user = (from u in _db.Users
where u.Id == id
select u).FirstOrDefault();
}
return user;
}
catch
{
}
return null;
}
public void UpdateUserInfo(User user)
{
try
{
using (UserContext _db = new UserContext())
{
User oldUser = (from u in _db.Users
where u.Id == user.Id
select u).FirstOrDefault();
oldUser.ConfirmedEmail = user.ConfirmedEmail;
oldUser.Email = user.Email;
oldUser.Login = user.Login;
oldUser.Password = user.Password;
_db.SaveChanges();
}
}
catch
{
}
}
public bool IsConfirmedEmail(string login)
{
try
{
using (UserContext _db = new UserContext())
{
string conf = (from u in _db.Users
where u.Login == login
select u).FirstOrDefault().ConfirmedEmail;
if (conf != null && conf.Length > 0)
{
if (conf == "Yes")
return true;
}
}
}
catch
{
}
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using VEE.Models.BasedeDatos;
using System.Web.Mvc;
namespace VEE.Models
{
public class AlumnoViewModels
{
[Key]
public int IdAlumno { get; set; }
[Required]
public int IdEscuela { get; set; }
public IEnumerable<Escuela> Escuela { get; set; }
[Required]
public int IdGrado { get; set; }
public IEnumerable<Grado> Grado { get; set; }
[Required]
public string Codigo { get; set; }
[Required]
public string Nombre { get; set; }
[Required]
public string Apellido { get; set; }
[Display(Name = "Foto"), DataType(DataType.Upload, ErrorMessage = "Images not valid")]
public byte[] Image { get; set; }
}
} |
using ADP.CommandAdapter;
using System;
using System.Windows.Forms;
namespace TesDB
{
public partial class frmTesKoneksi : Form
{
public frmTesKoneksi()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private bool TesKoneksi(string Server, string Database, string UserId, string Password, out string pesanError)
{
pesanError = string.Empty;
bool isSuccess = false;
SqlCmdBuilder cmd = new SqlCmdBuilder(tbServer.Text, tbDB.Text, tbUser.Text, tbPassword.Text);
cmd.TestConnection(out pesanError);
if (string.IsNullOrEmpty(pesanError))
isSuccess = true;
return isSuccess;
}
private void btnTes_Click(object sender, EventArgs e)
{
string pesan = string.Empty;
if (TesKoneksi(tbServer.Text, tbDB.Text, tbUser.Text, tbPassword.Text, out pesan))
MessageBox.Show("Koneksi Berhasil", "Perhatian");
else
MessageBox.Show("Koneksi gagal, " + pesan, "Peringatan");
}
}
}
|
using Anywhere2Go.DataAccess;
using Anywhere2Go.DataAccess.Entity;
using Anywhere2Go.DataAccess.Object;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.Business.Master
{
public class CompanyLogic
{
private static readonly ILog logger =
LogManager.GetLogger(typeof(CompanyLogic));
MyContext _context = null;
public CompanyLogic()
{
_context = new MyContext();
}
public CompanyLogic(MyContext context)
{
_context = context;
}
public List<Company> getCompany(Guid comId = new Guid(), bool? isActive = null)
{
var req = new Repository<Company>(_context);
List<Company> result = new List<Company>();
var query = req.GetQuery();
if (comId != Guid.Empty)
{
query = query.Where(t => t.comId == comId);
}
if (isActive != null)
{
query = query.Where(t => t.isActive == isActive);
}
return query.ToList();
}
public List<Insurer> getCompanySubIns(Guid comId = new Guid(), bool? isActive = null)
{
var req = new Repository<Company>(_context);
List<Company> result = new List<Company>();
var query = req.GetQuery();
if (comId != Guid.Empty)
{
query = query.Where(t => t.comId == comId);
}
if (isActive != null)
{
query = query.Where(t => t.isActive == isActive);
}
var Companyinsurers = query.SelectMany(c => c.subscribeInsurer.Select(s => new
{
insId = s.insId,
insName = s.Insurer.InsName,
sort= s.Insurer.sort,
isActive = s.Insurer.isActive,
runningId = s.Insurer.RunningId
})).Where(t=>t.isActive==true).OrderByDescending(t=>t.sort).ThenBy(t=>t.insName).ToList();
var insurers = new List<Insurer>();
foreach (var i in Companyinsurers)
{
var ins = new Insurer()
{
InsID = i.insId,
InsName = i.insName,
sort = i.sort,
RunningId=i.runningId
};
insurers.Add(ins);
}
return insurers;
}
public Company GetCompanyById(Guid ComId)
{
var req = new Repository<Company>(_context);
return req.GetQuery().Where(t => t.comId == ComId).SingleOrDefault();
}
public List<Company> GetCompanyByInsId(string insId)
{
var reqcompany = new Repository<Company>(_context);
return reqcompany.GetQuery().SelectMany(m => m.subscribeInsurer.Select(s => new
{
company = m,
subins = s
})).Where(t => t.subins.insId == insId).Select(t => t.company).ToList();
}
public List<Company> GetCompanyInsureByInsId(string insId)
{
var reqcompany = new Repository<Company>(_context);
return reqcompany.GetQuery().SelectMany(m => m.subscribeInsurer.Select(s => new
{
company = m,
subins = s
})).Where(t => t.subins.insId == insId && t.company.companyTypeId == 1001).Select(t => t.company).ToList();
}
public BaseResult<bool> saveCompany(Company obj, Authentication authen)
{
BaseResult<bool> res = new BaseResult<bool>();
string acc_id = authen != null ? authen.acc_id : "";
string user = authen != null ? authen.first_name + " " + authen.last_name : "";
using (var con = _context.Database.BeginTransaction())
{
try
{
var req = new Repository<Company>(_context);
var countCheckComCode = req.GetQuery().Where(t => t.com_code.Equals(obj.com_code) && t.comId != obj.comId).Count(); // check duplicate
if (countCheckComCode > 0)
{
res.Result = false;
res.Message = "ชื่อย่อบริษัทซ้ำกับในระบบ";
}
else
{
if (obj.comId == Guid.Empty) // insert
{
obj.createBy = user;
obj.createDate = DateTime.Now;
obj.updateBy = user;
obj.updateDate = DateTime.Now;
obj.companyTypeId = obj.comType.comTypeId;
obj.comType = null;
req.Add(obj);
req.SaveChanges();
}
else // update
{
var company = req.Find(t => t.comId == obj.comId).FirstOrDefault();
if (company != null)
{
var temp = company.subscribeInsurer.ToList();
foreach (var item in temp)
{
removeSubscribeInsurer(item);
}
company.subscribeInsurer = obj.subscribeInsurer;
company.com_code = obj.com_code;
company.comName = obj.comName;
company.comTel = obj.comTel;
company.companyTypeId = obj.comType.comTypeId;
company.isActive = obj.isActive;
company.updateBy = user;
company.updateDate = DateTime.Now;
req.SaveChanges();
}
}
res.Result = true;
con.Commit();
}
}
catch (Exception ex)
{
res.Result = false;
res.Message = ex.Message;
con.Rollback();
logger.Error(string.Format("Method = {0},User = {1}", "saveCompany", user), ex);
}
}
return res;
}
public List<CompanyType> getCompanyType(int comTypeId = 0)
{
var req = new Repository<CompanyType>(_context);
List<CompanyType> result = new List<CompanyType>();
if (comTypeId != 0)
{
result = req.GetQuery().Where(t => t.comTypeId == comTypeId && t.isActive == true).ToList();
}
else
{
result = req.GetQuery().Where(t => t.isActive == true).ToList();
}
return result;
}
public void removeSubscribeInsurer(SubscribeInsurer obj)
{
var req = new Repository<SubscribeInsurer>(_context);
req.Remove(obj);
req.SaveChanges();
}
}
}
|
using Euler_Logic.Helpers;
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems {
public class Problem155 : ProblemBase {
private Dictionary<int, Dictionary<int, HashSet<int>>> _counts = new Dictionary<int, Dictionary<int, HashSet<int>>>();
private Dictionary<int, HashSet<int>> _valid = new Dictionary<int, HashSet<int>>();
/*
Ignore the fact that the capacitors use 60 capacitance. Instead, let's just use 1. When (n) is 3, then
the total ways would be:
Using 1 capacitor:
1/1 = 1
Using 2 capacitors:
2/1 = 1+1
1/2 = 1/(1+1)
Using 3 capacitors:
3/1 = 1+1+1
1/3 = 1/(1+1+1)
3/2 = 1+1/(1+1)
2/3 = 1/(1+1/(1+1))
We can therefore determine when using 4 capacitors by looping through all the ways using 1 and 3 capacitors.
For each combination, we consider the parallel and series of the two. For parallel we add the two sets, and
for series we add the inverse of the two sets. See below for 4:
4/1 = 1+(3/1)
1/4 = 1/(3/1)
4/3 = 1+(1/3)
3/4 = 1/(4/3)
5/2 = 1+(3/2)
2/5 = 1/(5/2)
5/3 = 1+(2/3)
3/5 = 1/(5/3)
Adding the count of this new list to the count of the prior lists gives us 15 when (n) is 4. We contintue to
do this up to 18. However, we make sure that we always reduce the resulting fraction and ensure the reduced
fraction has never been used before. To assist with this, I use a dictionary of fractions where the key is
the numerator and the value is a list of all distinct denominators.
*/
public override string ProblemName {
get { return "155: Counting Capacitor Circuits"; }
}
public override string GetAnswer() {
return Solve(18).ToString();
}
private int Solve(int max) {
_counts.Add(1, new Dictionary<int, HashSet<int>>());
_counts[1].Add(1, new HashSet<int>() { 1 });
for (int count = 2; count <= max; count++) {
_counts.Add(count, new Dictionary<int, HashSet<int>>());
for (int a = 1; a < count; a++) {
int b = count - a;
foreach (var top1 in _counts[a]) {
foreach (var bottom1 in top1.Value) {
foreach (var top2 in _counts[b]) {
foreach (var bottom2 in top2.Value) {
var y = LCM.GetLCM(bottom1, bottom2);
var x = (top1.Key * y / bottom1) + (top2.Key * y / bottom2);
AddXOverY(count, x, y);
}
}
}
}
}
}
return _valid.Select(x => x.Value.Count).Sum();
}
private void AddXOverY(int count, int x, int y) {
// x / y
var addX = x;
var addY = y;
var gcd = GCD.GetGCD(addX, addY);
if (gcd != 1) {
addX /= gcd;
addY /= gcd;
}
AddCount(count, addX, addY);
AddValid(addX, addY);
// y / x
addX = y;
addY = x;
gcd = GCD.GetGCD(addX, addY);
if (gcd != 1) {
addX /= gcd;
addY /= gcd;
}
AddCount(count, addX, addY);
AddValid(addX, addY);
}
private void AddCount(int count, int addX, int addY) {
if (!_counts[count].ContainsKey(addX)) {
_counts[count].Add(addX, new HashSet<int>());
}
_counts[count][addX].Add(addY);
}
private void AddValid(int addX, int addY) {
if (!_valid.ContainsKey(addX)) {
_valid.Add(addX, new HashSet<int>());
}
_valid[addX].Add(addY);
}
}
} |
using Question.DAL.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Question.DAL
{
public class AddData
{
//testing
public static void Add(MyContext context)
{
AddQuestion(context);
}
private static void AddQuestion(MyContext context)
{
if (context.Questions.Count() == 0)
{
var question = new Question
{
Text = "З якого боку дозволено виконати" +
"випередження на проїзній частині?",
Image = @"Images\0.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
var answers = new List<Answer>
{
new Answer {Text="тільки з лівого боку",IsTrue=false,QuestionId=question.Id},
new Answer {Text="тільки з правого боку",IsTrue=false,QuestionId=question.Id},
new Answer {Text="з будь-якого боку по суміжній смузі",IsTrue=true,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Які фактори можуть призвести до засліплення водія?",
Image = @"Images\0.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="мокрий сніг",IsTrue=false,QuestionId=question.Id},
new Answer {Text="сильна злива",IsTrue=false,QuestionId=question.Id},
new Answer {Text="інтенсивний снігопад",IsTrue=false,QuestionId=question.Id},
new Answer {Text="світло",IsTrue=true,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Для чого призначений тротуар?",
Image = @"Images\0.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="для велосипедистів з 5-річного віку",IsTrue=false,QuestionId=question.Id},
new Answer {Text="для руху пішоходів",IsTrue=true,QuestionId=question.Id},
new Answer {Text="усі перелічені варіанти",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Учасник дорожнього руху-це:",
Image = @"Images\0.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="регулювальник",IsTrue=false,QuestionId=question.Id},
new Answer {Text="пішоходи,водії,пасажири",IsTrue=true,QuestionId=question.Id},
new Answer {Text="усі перелічені вище",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Скільки перехресть зображено на малюнку?",
Image = @"Images\5.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="одне",IsTrue=true,QuestionId=question.Id},
new Answer {Text="два",IsTrue=false,QuestionId=question.Id},
new Answer {Text="чотири",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Скільки проїзних частин має дана дорога?",
Image = @"Images\6.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="одну",IsTrue=false,QuestionId=question.Id},
new Answer {Text="дві",IsTrue=true,QuestionId=question.Id},
new Answer {Text="чотири",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Чи є тротуари і узбіччя частиною дороги?",
Image = @"Images\0.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="так",IsTrue=false,QuestionId=question.Id},
new Answer {Text="ні",IsTrue=true,QuestionId=question.Id},
new Answer {Text="тільки узбіччя",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Ви водій синього автомобіля"+
"і виконаєте розворот",
Image = @"Images\8.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="перед залізничним переїздом",IsTrue=false,QuestionId=question.Id},
new Answer {Text="після залізничного переїзду",IsTrue=true,QuestionId=question.Id},
new Answer {Text="на залізничному переїзді",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Для регулювання руху яких транспортних" +
"засобів застосовується даний світлофор?",
Image = @"Images\9.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="маршрутних транспортних засобів",IsTrue=false,QuestionId=question.Id},
new Answer {Text="трамваїв",IsTrue=true,QuestionId=question.Id},
new Answer {Text="тролейбусів",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Кому заборонено рух у даній ситуації?",
Image = @"Images\10.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="велосипедисту",IsTrue=false,QuestionId=question.Id},
new Answer {Text="водію мопеда і велосипедисту",IsTrue=true,QuestionId=question.Id},
new Answer {Text="нікому",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Зображений дорожній знак інформує про"+
"місце розташування",
Image = @"Images\11.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="телефону громадського харчування",IsTrue=false,QuestionId=question.Id},
new Answer {Text="телефону для виклику аварійних служб",IsTrue=true,QuestionId=question.Id},
new Answer {Text="відділення зв'язку",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Зображений дорожній знак інформує" +
"про місце розташування:",
Image = @"Images\12.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="газозаправної станції",IsTrue=true,QuestionId=question.Id},
new Answer {Text="автозаправної станції",IsTrue=false,QuestionId=question.Id},
new Answer {Text="гральних автоматів",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "На які транспортні засоби "+
"не поширюється дія знаку?",
Image = @"Images\13.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="мопеди",IsTrue=false,QuestionId=question.Id},
new Answer {Text="велосипеди",IsTrue=true,QuestionId=question.Id},
new Answer {Text="мотоцикли",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Зображений дорожній знак забороняє рух: ",
Image = @"Images\14.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="тракторів",IsTrue=false,QuestionId=question.Id},
new Answer {Text="самохідних машин і механізмів",IsTrue=false,QuestionId=question.Id},
new Answer {Text="всього переліченого вище",IsTrue=true,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Дія зображеного дорожнього знака поширюється на:",
Image = @"Images\15.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="мотоцикли і мопеди",IsTrue=false,QuestionId=question.Id},
new Answer {Text="мопеди",IsTrue=false,QuestionId=question.Id},
new Answer {Text="мопеди і велосипеди з підвісними двигунами",IsTrue=true,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
question = new Question
{
Text = "Зображений дорожній знак забороняє рух:",
Image = @"Images\16.jpg"
};
context.Questions.Add(question);
context.SaveChanges();
answers = new List<Answer>
{
new Answer {Text="велосипедів і мопедів",IsTrue=false,QuestionId=question.Id},
new Answer {Text="велосипедів",IsTrue=true,QuestionId=question.Id},
new Answer {Text="мотоциклів",IsTrue=false,QuestionId=question.Id}
};
context.Answers.AddRange(answers);
context.SaveChanges();
}
if (context.Users.Count() == 0)
{
var user = new User
{
Name = "Петро",
Surname = "Гончарук",
Login = "petro",
Password = PassHash.HashPassword("123"),
};
context.Users.Add(user);
context.SaveChanges();
var session = new List<Session>
{
new Session{UserId=user.Id,Begin=DateTime.Now,End=DateTime.Now.AddMinutes(12),Marks=72M}
};
context.Sessions.AddRange(session);
context.SaveChanges();
var res = new List<Result>
{
new Result{SessionId=1,AnswerId=3},
new Result{SessionId=1,AnswerId=7},
new Result{SessionId=1,AnswerId=9},
new Result{SessionId=1,AnswerId=12},
new Result{SessionId=1,AnswerId=14},
new Result{SessionId=1,AnswerId=18},
new Result{SessionId=1,AnswerId=21},
new Result{SessionId=1,AnswerId=23},
new Result{SessionId=1,AnswerId=28},
new Result{SessionId=1,AnswerId=30},
new Result{SessionId=1,AnswerId=34},
new Result{SessionId=1,AnswerId=35},
new Result{SessionId=1,AnswerId=39},
new Result{SessionId=1,AnswerId=43},
new Result{SessionId=1,AnswerId=46},
new Result{SessionId=1,AnswerId=49}
};
context.Results.AddRange(res);
context.SaveChanges();
}
}// end of Add
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SeaFight.Infrastructure
{
public class PointCoords
{
public PointCoords(int x, int y) {
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
public static PointCoords[] GetHaloByShipCoords(PointCoords[] coords)
{
var list = new List<PointCoords>();
var allDirections = new List<Direction>(){
Direction.Top, Direction.Right, Direction.Bottom, Direction.Left,
Direction.BottomLeft, Direction.BottomRight, Direction.TopLeft, Direction.TopRight
};
foreach (var point in coords)
{
foreach (var direction in allDirections)
{
var tempPoint = AddPointCoords(point, direction);
if (!coords.Contains(tempPoint, new PointCoordsComparer())
&& tempPoint.X < 10 && tempPoint.X >= 0
&& tempPoint.Y < 10 && tempPoint.Y >= 0)
{
list.Add(tempPoint);
}
}
}
return list.ToArray();
}
public static PointCoords AddPointCoords(PointCoords point, Direction direction)
{
switch (direction)
{
case Direction.Top:
return new PointCoords(point.X, point.Y - 1);
case Direction.Right:
return new PointCoords(point.X + 1, point.Y);
case Direction.Bottom:
return new PointCoords(point.X, point.Y + 1);
case Direction.Left:
return new PointCoords(point.X - 1, point.Y);
case Direction.TopRight:
return new PointCoords(point.X + 1, point.Y - 1);
case Direction.TopLeft:
return new PointCoords(point.X - 1, point.Y - 1);
case Direction.BottomLeft:
return new PointCoords(point.X - 1, point.Y + 1);
case Direction.BottomRight:
return new PointCoords(point.X + 1, point.Y + 1);
}
return point;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Condor.Persistence
{
internal class EventStoreWriterMessage<TEvent>
where TEvent: new()
{
public Guid CorrelationId { get; set; }
public int ExpectedVersion { get; set; }
public List<TEvent> Events { get; set; }
public static EventStoreWriterMessage<TEvent> Factory()
{
var outMessage = new EventStoreWriterMessage<TEvent>
{
CorrelationId = Guid.NewGuid(),
ExpectedVersion = ExpectedStreamVersion.Ignore,
Events = new List<TEvent>(),
};
return outMessage;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameOverCandys : MonoBehaviour {
Text instruction;
void Update()
{
instruction = GetComponent<Text>();
var Current_nb_candy = PlayerPrefs.GetInt("CurrentCandy", 0);
instruction.text = " " + Current_nb_candy;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DocumentSystem
{
public abstract class Document : IDocument
{
public string Name { get; protected set; }
public string Content { get; protected set; }
private readonly IList<KeyValuePair<string, object>> properties = new List<KeyValuePair<string, object>>();
public void LoadProperty(string key, string value)
{
properties.Add(new KeyValuePair<string, object>(key, value));
}
public void SaveAllProperties(IList<KeyValuePair<string, object>> output)
{
output = properties;
}
}
}
|
using System;
using System.Threading.Tasks;
namespace WispFramework.Patterns.Monitors
{
public class CountdownOperation
{
private readonly object _syncLock = new object();
private bool _completed;
private DateTime _lastUpdate = DateTime.MinValue;
private Task WorkerTask = null;
public CountdownOperation()
{
}
/// <summary>
/// Invoke the CompletedCallback once the countdown completes
/// </summary>
/// <param name="startCallback"></param>
/// <param name="completedCallback"></param>
/// <param name="delay"></param>
public CountdownOperation(Action startCallback, Action completedCallback, TimeSpan delay)
{
StartCallback = startCallback;
CompletedCallback = completedCallback;
Delay = delay;
WorkLoop();
}
/// <summary>
/// Invoke the CompletedCallback once the countdown completes
/// </summary>
/// <param name="completedCallback"></param>
/// <param name="delay"></param>
public CountdownOperation(Action completedCallback, TimeSpan delay)
{
CompletedCallback = completedCallback;
Delay = delay;
WorkLoop();
}
private Action CompletedCallback { get; set; }
private TimeSpan? Delay { get; set; }
private Action StartCallback { get; set; }
/// <summary>
/// Safely resets the start delay to Now
/// </summary>
public void Reset()
{
SetStartTime(DateTime.Now);
}
/// <summary>
/// Restarts the countdown
/// </summary>
public void Restart()
{
if (!_completed && WorkerTask != null)
{
Reset();
return;
}
_completed = false;
WorkLoop();
}
public CountdownOperation Begin()
{
Restart();
return this;
}
public CountdownOperation WithCompletedCallback(Action completedCallback)
{
CompletedCallback = completedCallback;
return this;
}
public CountdownOperation WithDelay(TimeSpan delay)
{
Delay = delay;
return this;
}
public CountdownOperation WithStartCallback(Action startCallback)
{
StartCallback = startCallback;
return this;
}
private DateTime GetStartTime()
{
lock (_syncLock)
{
return _lastUpdate;
}
}
private void SetStartTime(DateTime time)
{
lock (_syncLock)
{
_lastUpdate = time;
}
}
private void WorkLoop()
{
SetStartTime(DateTime.Now);
if (Delay == null)
{
return;
}
WorkerTask = Task.Run(async () =>
{
StartCallback?.Invoke();
while (DateTime.Now - GetStartTime() < Delay)
{
await Task.Delay(50);
}
CompletedCallback?.Invoke();
_completed = true;
});
}
}
} |
// This software is part of the Autofac IoC container
// Copyright (c) 2007 - 2013 Autofac Contributors
// https://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
namespace Autofac.Extras.AttributeMetadata
{
/// <summary>
/// Translates a type's attribute properties into a set consumable by Autofac.
/// </summary>
public static class MetadataHelper
{
/// <summary>
/// Given a target attribute object, returns a set of public readable properties and associated values.
/// </summary>
/// <param name="target">Target attribute instance to be scanned.</param>
/// <param name="instanceType">
/// The <see cref="Type"/> on which the <paramref name="target" /> attribute
/// is associated. Used when the <paramref name="target" /> is an
/// <see cref="IMetadataProvider"/>.
/// </param>
/// <returns>Enumerable set of property names and associated values.</returns>
/// <exception cref="System.ArgumentNullException">
/// Thrown if <paramref name="target" /> or <paramref name="instanceType"/> is <see langword="null" />.
/// </exception>
public static IEnumerable<KeyValuePair<string, object>> GetProperties(object target, Type instanceType)
{
if (target == null) throw new ArgumentNullException(nameof(target));
if (instanceType == null) throw new ArgumentNullException(nameof(instanceType));
if (target is IMetadataProvider asProvider)
{
// This attribute instance decides its own properties.
return asProvider.GetMetadata(instanceType);
}
return target.GetType()
.GetProperties()
.Where(propertyInfo => propertyInfo.CanRead &&
propertyInfo.DeclaringType != null &&
propertyInfo.DeclaringType.Name != typeof(Attribute).Name)
.Select(propertyInfo =>
new KeyValuePair<string, object>(propertyInfo.Name, propertyInfo.GetValue(target, null)));
}
/// <summary>
/// Given a component type, interrogates the metadata attributes to retrieve a set of property name/value metadata pairs.
/// </summary>
/// <param name="targetType">Type to interrogate for metadata attributes.</param>
/// <returns>Enumerable set of property names and associated values found.</returns>
/// <exception cref="System.ArgumentNullException">
/// Thrown if <paramref name="targetType" /> is <see langword="null" />.
/// </exception>
public static IEnumerable<KeyValuePair<string, object>> GetMetadata(Type targetType)
{
if (targetType == null) throw new ArgumentNullException(nameof(targetType));
var propertyList = new List<KeyValuePair<string, object>>();
foreach (var attribute in targetType.GetCustomAttributes(true)
.Where(p => p.GetType().GetCustomAttributes(typeof(MetadataAttributeAttribute), true).Any()))
{
propertyList.AddRange(GetProperties(attribute, targetType));
}
return propertyList;
}
/// <summary>
/// Given a component type, interrogates the metadata attributes to retrieve
/// a set of property name/value metadata pairs provided by a specific
/// metadata provider.
/// </summary>
/// <typeparam name="TMetadataType">Metadata type to look for in the list of attributes.</typeparam>
/// <param name="targetType">Type to interrogate.</param>
/// <returns>Enumerable set of property names and associated values found.</returns>
/// <exception cref="ArgumentNullException">
/// Thrown if <paramref name="targetType" /> is <see langword="null" />.
/// </exception>
public static IEnumerable<KeyValuePair<string, object>> GetMetadata<TMetadataType>(Type targetType)
{
if (targetType == null) throw new ArgumentNullException(nameof(targetType));
var attribute = (from p in targetType.GetCustomAttributes(typeof(TMetadataType), true) select p).FirstOrDefault();
return attribute != null ? GetProperties(attribute, targetType) : new List<KeyValuePair<string, object>>();
}
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace skyConverter.ModelStructure
{
class Texture : ISerializer
{
private String file = "";
//private Sampler sampler;
public Texture(String _file /*, Sampler _sampler*/)
{
file = _file;
//sampler = _sampler
}
public JObject serializeObject()
{
JObject obj = new JObject();
obj.Add("File", file);
return obj;
}
public JArray serializeArray()
{
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Helpers {
public class BigNumber {
public enum enumSign {
Positive,
Negative
}
public enumSign Sign { get; set; }
private List<int> _digits = new List<int>();
public IEnumerable<int> Digits {
get { return _digits; }
set { _digits = value.ToList(); }
}
public int this[int index] {
get {
if (_digits.Count <= index) {
AddZeros(index);
}
return _digits[index];
}
set {
if (_digits.Count <= index) {
AddZeros(index);
}
_digits[index] = value;
}
}
public void Clear() {
_digits.Clear();
}
public int Count {
get { return _digits.Count; }
}
private void AddZeros(int toIndex) {
for (int index = this.Count - 1; index <= toIndex; index++) {
_digits.Add(0);
}
}
public void MultiplyBy(BigNumber num) {
BigNumber thisOriginal = new BigNumber();
thisOriginal.Digits = this.Digits;
for (int index = 0; index < num.Count; index++) {
if (num[index] > 0) {
MultiplyRecurive(index, num[index], thisOriginal);
}
}
if (num.Sign != this.Sign) {
this.Sign = enumSign.Negative;
} else if (this.Sign == enumSign.Negative) {
this.Sign = enumSign.Positive;
}
}
private void MultiplyRecurive(int index, int count, BigNumber num) {
for (int i = 1; i <= count; i++) {
if (index == 0) {
if (i != 1) {
AbsoluteAddTo(num);
}
} else {
MultiplyRecurive(index - 1, 10, num);
}
}
}
public void AddTo(BigNumber num) {
if (num.Sign != this.Sign) {
int compare = num.CompareAbsolute(this);
if (compare < 0) {
AbsoluteSubtractFrom(num, this);
this.Sign = num.Sign;
} else if (compare > 0) {
AbsoluteSubtractFrom(this, num);
this.Digits = num.Digits;
} else {
this.Clear();
this.Sign = enumSign.Positive;
}
} else {
AbsoluteAddTo(num);
}
}
private void AbsoluteAddTo(BigNumber from) {
int carryOver = 0;
int digit = 0;
while (digit < from.Count || carryOver > 0) {
int sum = 0;
if (digit < from.Count) {
sum = from[digit] + this[digit] + carryOver;
} else {
sum = this[digit] + carryOver;
}
if (sum > 9) {
string sumText = sum.ToString();
this[digit] = Convert.ToInt32(sumText.Substring(1, 1));
carryOver = Convert.ToInt32(sumText.Substring(0, 1));
} else {
this[digit] = sum;
carryOver = 0;
}
digit++;
}
}
public void SubtractFrom(BigNumber num) {
if (num.Sign != this.Sign) {
AbsoluteAddTo(num);
if (this.Sign == enumSign.Negative) {
this.Sign = enumSign.Positive;
} else {
this.Sign = enumSign.Negative;
}
} else {
int compare = num.CompareAbsolute(this);
if (compare < 0) {
AbsoluteSubtractFrom(num, this);
} else if (compare > 0) {
AbsoluteSubtractFrom(this, num);
this.Digits = num.Digits;
if (this.Sign == enumSign.Negative) {
this.Sign = enumSign.Positive;
} else {
this.Sign = enumSign.Negative;
}
} else {
this.Clear();
this.Sign = enumSign.Positive;
}
}
}
private void AbsoluteSubtractFrom(BigNumber from, BigNumber to) {
for (int index = 0; index < from.Count; index++) {
if (from[index] < to[index]) {
BorrowFromNextDigit(from, index + 1);
from[index] += 10;
}
to[index] = from[index] - to[index];
}
}
private void BorrowFromNextDigit(BigNumber num, int index) {
if (num[index] == 0) {
BorrowFromNextDigit(num, index + 1);
num[index] = 9;
} else {
num[index] -= 1;
}
}
public int CompareAbsolute(BigNumber num) {
for (int index = Math.Max(this.Count, num.Count); index >= 0; index--) {
if (num[index] > this[index]) {
return 1;
} else if (num[index] < this[index]) {
return -1;
}
}
return 0;
}
public BigNumber() {
}
public BigNumber(List<int> number) {
_digits = new List<int>(number);
}
public BigNumber(string number) {
_digits = new List<int>();
for (int index = number.Length - 1; index >= 0; index--) {
_digits.Add(Convert.ToInt32(number.Substring(index, 1)));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WAP_ProjetoMIC
{
public partial class _Default : Page
{
private void AtualizaGrid()
{
var db = new MICEntities();
var query = db.Clientes.Join(db.Profissoes,
cliente => cliente.cd_Profissao,
profissao => profissao.cd_Profissao, (cliente, profissao) => new { cliente.cd_Cliente, cliente.Nome, cliente.Cidade, cliente.UF, NomeProfissao = profissao.Nome }).ToList();
GridView_Clientes.DataSource = query;
GridView_Clientes.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AtualizaGrid();
}
}
protected void Botao_Pesquisar_Click(object sender, EventArgs e)
{
var db = new MICEntities();
var query = db.Clientes.Where(cliente => cliente.Nome.StartsWith(CaixaTexto_Pesquisa.Text)).Join(db.Profissoes,
cliente => cliente.cd_Profissao,
profissao => profissao.cd_Profissao, (cliente, profissao) => new
{ cliente.cd_Cliente, cliente.Nome, cliente.Cidade, cliente.UF, NomeProfissao = profissao.Nome }).ToList();
GridView_Clientes.DataSource = query;
GridView_Clientes.DataBind();
}
protected void Botao_Adicionar_Click(object sender, EventArgs e)
{
Response.Redirect("CadastrarCliente.aspx");
}
protected void Botao_Editar_Click(object sender, EventArgs e)
{
int Codigo = Convert.ToInt32(GridView_Clientes.SelectedDataKey.Value);
Response.Redirect("CadastrarCliente.aspx?cd_Cliente=" + Codigo.ToString());
}
protected void Botao_Apagar_Click(object sender, EventArgs e)
{
if (GridView_Clientes.SelectedDataKey != null)
{
if (GridView_Clientes.SelectedDataKey != null)
{
int Codigo = Convert.ToInt32(GridView_Clientes.SelectedDataKey.Value);
var db = new MICEntities();
Clientes cliente = db.Clientes.First(c => c.cd_Cliente == Codigo);
db.Clientes.Remove(cliente);
db.SaveChanges();
AtualizaGrid();
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using BackendApi.DB;
using BackendApi.DB.DataModel;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace BackendApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class OrderListUploadController : ControllerBase
{
private IHostingEnvironment _hostingEnvironment;
private readonly ABD_DbContext myContext;
// 单元格类型
private const String CELL_TYP_STRING = "0";
private const String CELL_TYP_NUMBER = "1";
private const String CELL_TYP_DATE = "2";
// 循环起始行
private const int BUMP_OFFSET = 10;
public OrderListUploadController(IHostingEnvironment hostingEnvironment, ABD_DbContext context)
{
_hostingEnvironment = hostingEnvironment;
myContext = context;
}
// POST api/orderListUpload
[HttpPost]
[EnableCors("CorsPolicy")]
public ActionResult<string> UploadFile()
{
try
{
var file = Request.Form.Files[0];
string folderName = "UploadExcel";
string contentRootPath = _hostingEnvironment.ContentRootPath;
string newPath = Path.Combine(contentRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
IWorkbook workbook = WorkbookFactory.Create(stream);
ISheet sheet = workbook.GetSheetAt(0);
if (sheet != null)
{
/*
* 订单信息
*/
// 订单编号
String ORDER_NO = getCellValue(sheet, "C3", CELL_TYP_STRING);
if (String.IsNullOrEmpty(ORDER_NO))
{
// 订单号(主键)为空时,直接返回
return "OrderNo is empty.";
}
// 合同编号
String CONTRACT_NO = getCellValue(sheet, "C4", CELL_TYP_STRING);
// 项目名称
String PROJECT_NM = getCellValue(sheet, "C5", CELL_TYP_STRING);
// 销售部门/销售员
String SALES_PERSON = getCellValue(sheet, "C6", CELL_TYP_STRING);
// 订货单位
String ORDER_UNIT = getCellValue(sheet, "C7", CELL_TYP_STRING);
// 应用工程师
String APPLICATION_ENGINEER = getCellValue(sheet, "F3", CELL_TYP_STRING);
// 下发日期
String DEPARTURE_DATE_STR = getCellValue(sheet, "F4", CELL_TYP_DATE);
// 交货日期
String DELIVERY_DATE_STR = getCellValue(sheet, "F5", CELL_TYP_DATE);
// 此订单页数
String BUMP_DETAIL_NUM = getCellValue(sheet, "F6", CELL_TYP_NUMBER);
// 构造JObject,并保存订单信息至数据库中
JObject entityObjForOrder = new JObject();
entityObjForOrder.Add("ORDER_NO", ORDER_NO);
entityObjForOrder.Add("CONTRACT_NO", CONTRACT_NO);
entityObjForOrder.Add("PROJECT_NM", PROJECT_NM);
entityObjForOrder.Add("SALES_PERSON", SALES_PERSON);
entityObjForOrder.Add("ORDER_UNIT", ORDER_UNIT);
entityObjForOrder.Add("APPLICATION_ENGINEER", APPLICATION_ENGINEER);
entityObjForOrder.Add("DEPARTURE_DATE", Convert.ToDateTime(DEPARTURE_DATE_STR));
entityObjForOrder.Add("DELIVERY_DATE", Convert.ToDateTime(DELIVERY_DATE_STR));
ORDER_LIST_MST excelOrderListMstEntity = entityObjForOrder.ToObject<ORDER_LIST_MST>();
var orderListMstEntity = myContext.ORDER_LIST_MST.Where(d => d.ORDER_NO.Equals(excelOrderListMstEntity.ORDER_NO));
if (orderListMstEntity.Count() == 0)
{
// INSERT
myContext.ORDER_LIST_MST.Add(excelOrderListMstEntity);
// 以后有可能做一个FLG,到水泵信息保存完成后再保存更改
myContext.SaveChanges();
}
else
{
orderListMstEntity.First().CONTRACT_NO = excelOrderListMstEntity.CONTRACT_NO;
orderListMstEntity.First().PROJECT_NM = excelOrderListMstEntity.PROJECT_NM;
orderListMstEntity.First().ORDER_UNIT = excelOrderListMstEntity.ORDER_UNIT;
orderListMstEntity.First().SALES_PERSON = excelOrderListMstEntity.SALES_PERSON;
orderListMstEntity.First().DEPARTURE_DATE = excelOrderListMstEntity.DEPARTURE_DATE.ToLocalTime();
orderListMstEntity.First().DELIVERY_DATE = excelOrderListMstEntity.DELIVERY_DATE.ToLocalTime();
orderListMstEntity.First().REMARK = excelOrderListMstEntity.REMARK;
orderListMstEntity.First().APPLICATION_ENGINEER = excelOrderListMstEntity.APPLICATION_ENGINEER;
myContext.SaveChanges();
}
/*
* 水泵信息
*/
for (int i = 0; i < Convert.ToInt32(BUMP_DETAIL_NUM); i++)
{
// 序号(校验用)
String NO = getCellValue(sheet, "A" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 序号校验(还应考虑不是数字Convert失败的情况,未写)
if (Convert.ToInt32(NO) != i+1) { return ""; }
// 泵名称
String BUMP_NM = getCellValue(sheet, "B" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 工位
String STATION = getCellValue(sheet, "C" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 型号
String BUMP_TYPE = getCellValue(sheet, "D" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 数量
String NUMBER = getCellValue(sheet, "F" + (BUMP_OFFSET + i), CELL_TYP_NUMBER);
// 流量
String FLOW = getCellValue(sheet, "G" + (BUMP_OFFSET + i), CELL_TYP_NUMBER);
// 扬程
String LIFT = getCellValue(sheet, "H" + (BUMP_OFFSET + i), CELL_TYP_NUMBER);
// 材质
String MATERIAL = getCellValue(sheet, "I" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 机封
String SEAL = getCellValue(sheet, "J" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 序列号
String BUMP_SERIAL_NO = getCellValue(sheet, "K" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 备注
String REMARK = getCellValue(sheet, "L" + (BUMP_OFFSET + i), CELL_TYP_STRING);
// 构造水泵ID
String BUMP_ID = "";
if (String.IsNullOrEmpty(BUMP_TYPE) || String.IsNullOrEmpty(MATERIAL))
{
return "BumpType or material is empty.";
}
else
{
BUMP_ID = BUMP_TYPE + "_" + MATERIAL;
}
// 构造JObject,并保存水泵信息至数据库中
JObject entityObjForBump = new JObject();
entityObjForBump.Add("ORDER_NO", ORDER_NO);
entityObjForBump.Add("BUMP_ID", BUMP_ID);
entityObjForBump.Add("BUMP_NM", BUMP_NM);
entityObjForBump.Add("STATION", STATION);
entityObjForBump.Add("BUMP_TYPE", BUMP_TYPE);
entityObjForBump.Add("NUMBER", Convert.ToInt32(NUMBER));
entityObjForBump.Add("FLOW", Convert.ToInt32(FLOW));
entityObjForBump.Add("LIFT", Convert.ToInt32(LIFT));
entityObjForBump.Add("MATERIAL", MATERIAL);
entityObjForBump.Add("SEAL", SEAL);
entityObjForBump.Add("BUMP_SERIAL_NO", BUMP_SERIAL_NO);
entityObjForBump.Add("REMARK", REMARK);
ORDER_LIST_DETAIL excelOrderListDetailEntity = entityObjForBump.ToObject<ORDER_LIST_DETAIL>();
var orderListDetailEntity =
myContext.ORDER_LIST_DETAIL
.Where(d => d.ORDER_NO.Equals(excelOrderListDetailEntity.ORDER_NO))
.Where(d => d.BUMP_ID.Equals(excelOrderListDetailEntity.BUMP_ID));
if (orderListDetailEntity.Count() == 0)
{
// INSERT
myContext.ORDER_LIST_DETAIL.Add(excelOrderListDetailEntity);
// 以后有可能做一个FLG,到水泵信息保存完成后再保存更改
myContext.SaveChanges();
}
else
{
orderListDetailEntity.First().BUMP_NM = excelOrderListDetailEntity.BUMP_NM;
orderListDetailEntity.First().STATION = excelOrderListDetailEntity.STATION;
orderListDetailEntity.First().BUMP_TYPE = excelOrderListDetailEntity.BUMP_TYPE;
orderListDetailEntity.First().NUMBER = excelOrderListDetailEntity.NUMBER;
orderListDetailEntity.First().FLOW = excelOrderListDetailEntity.FLOW;
orderListDetailEntity.First().LIFT = excelOrderListDetailEntity.LIFT;
orderListDetailEntity.First().MATERIAL = excelOrderListDetailEntity.MATERIAL;
orderListDetailEntity.First().SEAL = excelOrderListDetailEntity.SEAL;
orderListDetailEntity.First().BUMP_SERIAL_NO = excelOrderListDetailEntity.BUMP_SERIAL_NO;
orderListDetailEntity.First().REMARK = excelOrderListDetailEntity.REMARK;
myContext.SaveChanges();
}
}
}
}
}
return String.Empty;
}
catch (System.Exception ex)
{
return "Upload Failed: " + ex.Message;
}
}
/*
* 根据单元格编号取得对应位置内容(目前只提供A-Z)
*/
public String getCellValue(ISheet sheet, string cellNo, string celltyp)
{
char letter = cellNo.ToCharArray()[0];
int rowIndex = Convert.ToInt32(cellNo.Substring(1));
int cellIndex = letter - 65;
IRow mRow = sheet.GetRow(rowIndex - 1);
ICell mCell = mRow.GetCell(cellIndex);
if (celltyp == CELL_TYP_STRING)
{
mCell.SetCellType(CellType.String);
return mCell.StringCellValue;
}
else if (celltyp == CELL_TYP_NUMBER)
{
mCell.SetCellType(CellType.Numeric);
return mCell.NumericCellValue.ToString();
}
else
{
mCell.SetCellType(CellType.Numeric);
return mCell.DateCellValue.ToString();
}
}
}
} |
using System;
namespace gView.Server.AppCode
{
public class AuthToken
{
public AuthToken()
{
this.AuthType = AuthTypes.Unknown;
}
public AuthToken(string username, AuthTypes authType, DateTimeOffset expires)
{
this.Username = username;
this.AuthType = authType;
this.Expire = (DateTime.UtcNow.AddTicks(expires.Ticks)).Ticks;
}
public string Username { get; set; }
public string PasswordHash { get; set; }
public long Expire { get; set; }
public AuthTypes AuthType { get; set; }
public bool IsAnonymous => String.IsNullOrWhiteSpace(this.Username);
public bool IsManageUser => this.IsAnonymous == false && this.AuthType == AuthTypes.Manage;
public bool IsTokenUser => this.IsAnonymous == false && this.AuthType == AuthTypes.Tokenuser;
public bool IsExpired => !IsAnonymous && DateTime.UtcNow.Ticks > Expire;
#region Classes / Enums
public enum AuthTypes
{
Unknown = 0,
Tokenuser = 1,
Manage = 2
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class StudentMono : MonoBehaviour
{
private Lobby loby;
private GameManager manager;
private GameTime gtime;
private StudentFactory Sfactory;
public Student stdudentinfo;
private NavMeshAgent myNavAgent;
private bool LobbyFound = false;
public GameObject ClassSit=null;
public GameObject Chillsit=null;
public bool Paid = false;
//-------------
[SerializeField] private GameObject boyrig;
[SerializeField] private GameObject girlrig;
[SerializeField] private Animator animboy;
[SerializeField] private PercyTestStudentAnim script;
private bool female = false;
bool a = false;
//Special Parts
[SerializeField] private GameObject[] Specialparts;
private void Awake()
{
InvokeRepeating("Schedule",0f,8f);
}
void Start()
{
loby = Lobby.instance;
manager = GameManager.instance;
Sfactory = StudentFactory.instance;
stdudentinfo = Sfactory.CreateStudent();
gtime = GameTime.instance;
manager.AddStudent();
myNavAgent = gameObject.GetComponent<NavMeshAgent>();
loby.TakePlace(gameObject);
//if (!GameObject.Find("Lobby"))myNavAgent.SetDestination(new Vector3(-10, 0, -10));
//InvokeRepeating("OnSpawn", 10, 5f);
if (stdudentinfo.Gender1 == "Female")
{
boyrig.SetActive(false);
animboy.enabled = false;
girlrig.SetActive(true);
script.enabled = false;
female = true;
}
}
// Update is called once per frame
void Update()
{
if (gameObject.transform.position.z < manager.LevelMarkers[2].position.z)
{
Setmylayer(13);
}else
if (gameObject.transform.position.y<manager.LevelMarkers[0].position.y)
{
Setmylayer(8);
}
else if (gameObject.transform.position.y > manager.LevelMarkers[0].position.y && gameObject.transform.position.y < manager.LevelMarkers[1].position.y)
{
Setmylayer(9);
}
else if (gameObject.transform.position.y > manager.LevelMarkers[1].position.y)
{
Setmylayer(10);
}
}
private void Setmylayer(int layer)
{
gameObject.layer = layer;
for (int i = 0; i < transform.childCount; i++)
{
transform.GetChild(i).gameObject.layer = layer;
if (female)
{
for (int u = 0; u < Specialparts.Length; u++)
{
Specialparts[u].gameObject.layer = layer;
}
}
if (transform.GetChild(i).childCount > 0)
{
for (int f = 0; f < gameObject.transform.GetChild(i).childCount; f++)
{
transform.GetChild(i).gameObject.transform.GetChild(f).gameObject.layer = layer;
if (transform.GetChild(i).gameObject.transform.GetChild(f).childCount > 0)
{
for (int g = 0; g < gameObject.transform.GetChild(i).gameObject.transform.GetChild(f).childCount; g++)
{
transform.GetChild(i).gameObject.transform.GetChild(f).gameObject.transform.GetChild(g).gameObject.layer = layer;
}
}
}
}
}
}
public void GetPlaceoncafeteria()
{
if (Chillsit == null)
{
for (int i = 0; i < manager.Chilingspot.Count; i++) {
// if (manager.Chilingspot[i].name == "Caffeteria") {
if (manager.Chilingspot[i].GetComponent<Chillingplace>().IsthereSpace())
{
Chillsit = manager.Chilingspot[i].GetComponent<Chillingplace>().AvalableSit();
}
// }
//else
//{
// if (Chillsit == null && manager.Chilingspot[i].GetComponent<Chillingplace>().IsthereSpace())
// {
// Chillsit = manager.Chilingspot[i].GetComponent<Chillingplace>().AvalableSit();
// }
//}
}
}
}
//public void OnSpawn()
//{
// //if (GameObject.Find("Lobby"))
// // {
// GameObject lobby = GameObject.Find("Lobby");
// //loby.FillList();
// //loby.StudentsInLine.Add(gameObject);
// loby.TakePlace(gameObject);
// // CancelInvoke();
// //}
// // else
// // {
// // myNavAgent.SetDestination(RandomNavmeshLocation(5f));
// //}
//}
public Vector3 RandomNavmeshLocation(float radius)
{
Vector3 randomDirection = Random.insideUnitSphere * radius;
randomDirection += transform.position;
NavMeshHit hit;
Vector3 finalPosition = Vector3.zero;
if (NavMesh.SamplePosition(randomDirection, out hit, radius, 1))
{
finalPosition = hit.position;
}
return finalPosition;
}
public void DetermineHappines()
{
//stdudentinfo.Happines1
int HapyTemp = 0;
if (stdudentinfo.ClassIgot1 == stdudentinfo.ClassIwant1)
{
HapyTemp += 40;//class gotten 40%
}
//if(ClassSit.transform.parent.GetComponent<ClasroomScip>().Teficiency>=0&& ClassSit.transform.parent.GetComponent<ClasroomScip>().Teficiency < 45)
//{
// HapyTemp += 0;
// }
if (ClassSit.transform.parent.GetComponent<ClasroomScip>().Teficiency >= 45 && ClassSit.transform.parent.GetComponent<ClasroomScip>().Teficiency < 65)
{
HapyTemp += 10;
}
else if (ClassSit.transform.parent.GetComponent<ClasroomScip>().Teficiency >= 65 && ClassSit.transform.parent.GetComponent<ClasroomScip>().Teficiency <= 100)
{
HapyTemp += 20;
}//teacher eficiency 20%
if(Chillsit != null)
{
HapyTemp += 10;//Chill spot 10%
}
if (manager.Allregisteredstudents.Count % 2 == 0)//is Even 5%
{
HapyTemp += 5;
}
//else//is odd
HapyTemp += weatherManager.instance.happiness;//whether 5%
HapyTemp += SchoolEventManager.instance.happiness;//events 20%
stdudentinfo.Happines1 = HapyTemp;
}
public void Schedule()
{
if (ClassSit != null)
{
if (gtime.hour > 0 && gtime.hour <= 3)
{
myNavAgent.SetDestination(manager.LocationOfSpawn);
}
if (gtime.hour > 3 && gtime.hour <= 10)
{
myNavAgent.SetDestination(ClassSit.transform.position);
}
if (gtime.hour > 10 && gtime.hour <= 13)
{
if (Chillsit == null)
{
myNavAgent.SetDestination(RandomNavmeshLocation(7f));
}
else
{
myNavAgent.SetDestination(Chillsit.transform.position);
}
}
if (gtime.hour > 13 && gtime.hour <= 15)
{
myNavAgent.SetDestination(ClassSit.transform.position);
}
if (gtime.hour > 15 && gtime.hour <= 19)
{
if (Chillsit == null)
{
myNavAgent.SetDestination(RandomNavmeshLocation(7f));
}
else
{
myNavAgent.SetDestination(Chillsit.transform.position);
}
}
if (gtime.hour > 19 && gtime.hour <= 24)
{
myNavAgent.SetDestination(ClassSit.transform.position);
}
}
}
}
|
using Langium.DataLayer.DbModels;
using Langium.PresentationLayer;
using Langium.PresentationLayer.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Langium.DataLayer.DataAccessObjects
{
public class WordDao
{
public async Task<DataResult<WordModel>> GetWordByIdAsync(int id)
{
using (var context = new LangiumDbContext())
{
try
{
var word = await context.Words
.Include(w => w.Lexeme)
.Include(w => w.Transcription)
.Include(w => w.Translation)
.FirstOrDefaultAsync(c => c.Id == id);
if (word == null)
{
return new DataResult<WordModel>(null, "WORD_NOT_EXISTS");
};
return new DataResult<WordModel>(word);
}
catch (Exception ex)
{
return new DataResult<WordModel>(ex, ex.InnerException.Message);
}
}
}
public async Task<DataResult<IEnumerable<WordModel>>> GetCategoryWordsAsync(int categoryId)
{
using (var context = new LangiumDbContext())
{
try
{
var words = await context.Words
.Include(w => w.Lexeme)
.Include(w => w.Transcription)
.Include(w => w.Translation)
.Where(w => w.CategoryId == categoryId)
.ToListAsync();
return new DataResult<IEnumerable<WordModel>>(words);
}
catch (Exception ex)
{
return new DataResult<IEnumerable<WordModel>>(ex, ex.InnerException.Message);
}
}
}
public async Task<DataResult<IEnumerable<WordModel>>> GetUserWordsAsync(int profileId)
{
CategoryDao categoryDao = new CategoryDao();
try
{
List<WordModel> words = new List<WordModel>();
var categories = categoryDao.GetUserCategoriesAsync(profileId).Result.Data.ToList();
if (categories.Count() != 0 && categories != null)
{
foreach (var c in categories)
{
if (c.Words.Count() != 0 && c.Words != null)
{
words.AddRange(c.Words);
}
}
}
return new DataResult<IEnumerable<WordModel>>(words);
}
catch (Exception ex)
{
return new DataResult<IEnumerable<WordModel>>(ex, ex.InnerException.Message);
}
}
public async Task<DataResult<WordModel>> AddWordAsync(WordAddDto word)
{
using (var context = new LangiumDbContext())
{
try
{
var newWord = new WordModel()
{
Lexeme = new LexemeModel()
{
Lexeme = word.Lexeme
},
Transcription = new TranscriptionModel()
{
Transcription = word.Transcription
},
Translation = new TranslationModel()
{
Translation = word.Translation
},
CategoryId = word.CategoryId
};
CategoryDao categoryDao = new CategoryDao();
var sameWords = categoryDao.GetCategoryByIdAsync(word.CategoryId).Result.Data.Words.Where(w => w.Lexeme.Lexeme == word.Lexeme);
if (sameWords.Count() == 0)
{
var added = await context.Words.AddAsync(newWord);
await context.SaveChangesAsync();
return new DataResult<WordModel>(added.Entity);
}
else
{
return new DataResult<WordModel>(null, "WORD_WITH_SAME_LEXEM_AlREADY_EXISTS");
}
}
catch (Exception ex)
{
return new DataResult<WordModel>(ex, ex.InnerException.Message);
}
}
}
public async Task<DataResult<WordModel>> UpdateWordAsync(WordModel word)
{
using (var context = new LangiumDbContext())
{
try
{
context.Entry(word).State = EntityState.Modified;
context.Entry(word.Lexeme).State = EntityState.Modified;
context.Entry(word.Transcription).State = EntityState.Modified;
context.Entry(word.Translation).State = EntityState.Modified;
await context.SaveChangesAsync();
var updatedWord = context.Words.FirstOrDefault(w => w.Id == word.Id);
return new DataResult<WordModel>(updatedWord);
}
catch (Exception ex)
{
return new DataResult<WordModel>(ex, ex.InnerException.Message);
}
}
}
public async Task<DataResult<bool>> RemoveWordAsync(int id)
{
using (var context = new LangiumDbContext())
{
try
{
var entity = await context.Words.FindAsync(id);
if (entity == null)
{
return new DataResult<bool>(null, "WORD_NOT_EXISTS");
}
context.Remove(entity);
await context.SaveChangesAsync();
return new DataResult<bool>(true);
}
catch (Exception ex)
{
return new DataResult<bool>(ex, ex.Message);
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstacleLogic : MonoBehaviour {
public float speed;
private void Start () {
Destroy (gameObject, 10);
}
void FixedUpdate () {
transform.position -= Vector3.forward * speed;
}
private void OnCollisionEnter (Collision other) {
Debug.Log (other.gameObject.name);
other.gameObject.SetActive(false);
GameManager.SpawnDeathParticles(other.transform.position);
GameManager.instance.EndGame();
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UIMAYE.businesslayer;
using UIMAYE.classes;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace UIMAYE.Istatistik
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Raporx : TabbedPage
{
public Raporx(ObservableCollection<string> projeler, List<int> ids)
{
InitializeComponent();
foreach (string s in projeler)
{
projeadi.Items.Add(s);
}
}
bl b = new bl();
private async void Button_Clicked(object sender, EventArgs e)
{
rapInd.IsRunning = true;
List<LocalLog> ll = await b.getLogs(12, baslangic.Date.ToString("mm-dd-YYYY"), bitis.Date.ToString("mm-dd-YYYY"));
rapInd.IsRunning = false;
int topSure = 0;
int topMola = 0;
int topBekleme = 0;
foreach (LocalLog l in ll)
{
topSure += l.toplamSure;
topMola += l.toplamMola;
topBekleme += l.beklemeSuresi;
}
Raporlama rapor = new Raporlama();
rapor.projeAdi = ll.FirstOrDefault().projeAdi;
rapor.toplamSure = topSure;
rapor.toplamMola = topMola;
rapor.toplamBeklemeSuresi = topBekleme;
GrafikPage.Content = new CrossPieCharts.FormsPlugin.Abstractions.CrossPieChartSample().GetPageWithPieChart(rapor).Content;
topBekle.Text = topBekleme.ToString();
int top = (topSure + topMola + topBekleme)/60;
topCal.Text = top.ToString() + " dk";
topMol.Text = topMola.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// Pour plus d'informations sur le modèle d'élément Page vierge, consultez la page https://go.microsoft.com/fwlink/?LinkId=234238
namespace VéloMax.Pages
{
/// <summary>
/// Une page vide peut être utilisée seule ou constituer une page de destination au sein d'un frame.
/// </summary>
public sealed partial class StocksMain : Page
{
public StocksMain()
{
this.InitializeComponent();
}
private readonly List<(string Tag, Type Page)> _pages = new List<(string Tag, Type Page)>{
("stocksVelos", typeof(VéloMax.Pages.Stocks.StocksVelos)),
("stocksPieces", typeof(VéloMax.Pages.Stocks.StocksPieces)),
("stocksFournisseurs", typeof(VéloMax.Pages.Stocks.StocksFournisseurs)),
};
private void NavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
{
if (args.InvokedItemContainer != null)
{
var navItemTag = args.InvokedItemContainer.Tag.ToString();
}
}
private void NavView_Navigate(
string navItemTag,
Windows.UI.Xaml.Media.Animation.NavigationTransitionInfo transitionInfo)
{
Type _page = null;
var item = _pages.FirstOrDefault(p => p.Tag.Equals(navItemTag));
_page = item.Page;
// Get the page type before navigation so you can prevent duplicate
// entries in the backstack.
var preNavPageType = NavigationContentFrame.CurrentSourcePageType;
// Only navigate if the selected page isn't currently loaded.
if (!(_page is null) && !Type.Equals(preNavPageType, _page))
{
NavigationContentFrame.Navigate(_page, null, transitionInfo);
}
}
private void NavView_BackRequested(NavigationView sender,
NavigationViewBackRequestedEventArgs args)
{
TryGoBack();
}
private bool TryGoBack()
{
if (!NavigationContentFrame.CanGoBack)
return false;
// Don't go back if the nav pane is overlayed.
if (NavViewStocks.IsPaneOpen &&
(NavViewStocks.DisplayMode == NavigationViewDisplayMode.Compact ||
NavViewStocks.DisplayMode == NavigationViewDisplayMode.Minimal))
return false;
NavigationContentFrame.GoBack();
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
namespace Kliiko.Ui.Tests.WebPages.Dashboard.Resources
{
class GalleryPage : WebPage
{
private static readonly By ButtonChangeView = By.XPath(".//*[@id='GalleryController']/ng-include/div[1]/div/div/div[2]/button");
private static readonly By ButtonAddNewResource = By.Id("uploadResourceDropdown");
private static readonly By ButtonDownLoad = By.XPath(".//*[@id='select-section']/button[1]");
private static readonly By ButtonDelete = By.XPath(".//*[@id='select-section']/button[2]");
private static readonly By CheckboxSelectAll = By.Id("selectAll");
private static readonly By LinkAchive = By.PartialLinkText("Achive");
private static readonly By LinkYoutube = By.PartialLinkText("Youtube");
private static readonly By LinkVideo = By.PartialLinkText("Video");
private static readonly By LinkPdf = By.PartialLinkText("PDF");
private static readonly By LinkAudio = By.PartialLinkText("Audio");
private static readonly By LinkLogo = By.PartialLinkText("Brand Logo");
private static readonly By LinkImage = By.PartialLinkText("Image");
private static readonly By LinkAll = By.PartialLinkText("All");
}
}
|
using OpenTK.Graphics.OpenGL4;
namespace Mandelbrot.Rendering;
public class OpenGl : Renderer
{
protected override Shader? Shader { get; set; }
public override void Initialize(out int vbo, out int vao)
{
Shader = new Shader("Shaders/mandelbrot.vert", "Shaders/mandelbrot.frag");
Shader.Use();
float[] vertices =
{
-1f, -1f, 0f,
1f, -1f, 0f,
1f, 1f, 0f,
-1f, 1f, 0f,
};
vbo = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float), vertices, BufferUsageHint.StaticDraw);
var positionLocation = Shader.GetAttribLocation("aPosition");
vao = GL.GenVertexArray();
GL.BindVertexArray(vao);
GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float, false, 3 * sizeof(float), 0);
GL.EnableVertexAttribArray(positionLocation);
}
public override void OnChange()
{
if (Shader is null) return;
GL.Uniform1(Shader.GetUniformLocation("R"), R);
GL.Uniform1(Shader.GetUniformLocation("N"), N);
GL.Uniform1(Shader.GetUniformLocation("M"), M);
GL.Uniform1(Shader.GetUniformLocation("xMin"), (float) XMin);
GL.Uniform1(Shader.GetUniformLocation("xMax"), (float) XMax);
GL.Uniform1(Shader.GetUniformLocation("yMin"), (float) YMin);
GL.Uniform1(Shader.GetUniformLocation("yMax"), (float) YMax);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using FAITutorial2.Models;
namespace FAITutorial2.Controllers
{
public class VendoriController : Controller
{
private readonly FAI2_0Context _context;
public VendoriController(FAI2_0Context context)
{
_context = context;
}
// GET: Vendori
public async Task<IActionResult> Index()
{
return View(await _context.Vendori.ToListAsync());
}
// GET: Vendori/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var vendori = await _context.Vendori
.FirstOrDefaultAsync(m => m.VendoriId == id);
if (vendori == null)
{
return NotFound();
}
return View(vendori);
}
// GET: Vendori/Create
public IActionResult Create()
{
return View();
}
// POST: Vendori/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("VendoriId,Emri,Lokacioni,NrKontaktues,BankAccount")] Vendori vendori)
{
if (ModelState.IsValid)
{
_context.Add(vendori);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(vendori);
}
// GET: Vendori/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var vendori = await _context.Vendori.FindAsync(id);
if (vendori == null)
{
return NotFound();
}
return View(vendori);
}
// POST: Vendori/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("VendoriId,Emri,Lokacioni,NrKontaktues,BankAccount")] Vendori vendori)
{
if (id != vendori.VendoriId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(vendori);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!VendoriExists(vendori.VendoriId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(vendori);
}
// GET: Vendori/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var vendori = await _context.Vendori
.FirstOrDefaultAsync(m => m.VendoriId == id);
if (vendori == null)
{
return NotFound();
}
return View(vendori);
}
// POST: Vendori/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var vendori = await _context.Vendori.FindAsync(id);
_context.Vendori.Remove(vendori);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool VendoriExists(int id)
{
return _context.Vendori.Any(e => e.VendoriId == id);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Interactable : MonoBehaviour
{
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit;
if (hit = Physics2D.Raycast(ray.origin, ray.direction))
{
GameObject go = hit.collider.gameObject;
RegionBehaviour regb = go.GetComponent<RegionBehaviour>();
if (Input.GetMouseButtonUp(0))
{
if (go.GetComponent<ToggleGameObject>() != null)
{
go.GetComponent<ToggleGameObject>().ToggleIt();
}
else if (regb != null && regb.enabled)
{
regb.OnLMBUp();
} else if(go.GetComponent<InteractIt>() != null)
{
go.GetComponent<InteractIt>().InteractLMB();
}
}
else if(Input.GetMouseButtonUp(1))
{
if (regb != null)
{
regb.OnRMBUp();
}
else if (go.GetComponent<InteractIt>() != null)
{
go.GetComponent<InteractIt>().InteractRMB();
}
} else
{
if (regb != null && regb.Region.Type != RegionType.Water)
{
RegionBehaviour.RegionLooking = regb;
} else
{
RegionBehaviour.RegionLooking = null;
}
if (go.GetComponent<InteractIt>() != null)
{
go.GetComponent<InteractIt>().InteractOver();
}
}
}
}
}
|
using ParrisConnection.DataLayer.Entities.Profile;
using ParrisConnection.DataLayer.Entities.Wall;
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace ParrisConnection.DataLayer.Entities
{
public class ParrisDbContext : IdentityDbContext<ConnectionUser>
{
public DbSet<ProfilePhoto> ProfilePhotos { get; set; }
public DbSet<Employer> Employers { get; set; }
public DbSet<Education> Educations { get; set; }
public DbSet<Quote> Quotes { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
public DbSet<EmailType> EmailTypes { get; set; }
public DbSet<Email> Emails { get; set; }
public DbSet<AlbumPhoto> AlbumPhotos { get; set; }
public DbSet<LinkType> LinkTypes { get; set; }
public DbSet<Link> Type { get; set; }
public DbSet<Status> Statuses { get; set; }
public DbSet<Comment> Comments { get; set; }
public ParrisDbContext() : base("ParrisConnection")
{
}
public static ParrisDbContext Create()
{
return new ParrisDbContext();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace SchemaObjectMapper.Tests
{
[TestFixture]
public class FileReaderFixture
{
[SetUp]
public void Setup()
{
var lines = new List<string>
{
"P|Foo|Bar|M|1/2/2003",
"P|John|Smith|M|1/2/2003",
"P|Jane|Smith|F|1/2/1980"
};
File.WriteAllLines("text.txt", lines);
}
[TearDown]
public void TearDown()
{
if(File.Exists("text.txt"))
{
File.Delete("text.txt");
}
}
[Test]
public void FileReader_ReadFile_Enumerates_Each_Line()
{
var schema = new DelimitedSchema<Person>();
schema.AddMapping(s => s.FirstName, 1);
schema.AddMapping(s => s.LastName, 2);
schema.AddMapping(s => s.Gender, 3);
schema.AddMapping(s => s.DateOfBirth, 4);
var mapper = new DelimitedSchemaObjectMapper<Person>(schema, "|");
var persons = new List<Person>();
var fr = new FileReader();
fr.ReadFile("text.txt", line =>
{
if (line.StartsWith("P"))
{
persons.Add(mapper.MapLine(line));
}
});
Assert.AreEqual(3, persons.Count);
}
}
}
|
using System;
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using StardewValley.Menus;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
using System.Reflection;
namespace SB_VerticalToolMenu
{
public class ModEntry : Mod
{
VerticalToolBar verticalToolbar;
bool isInitiated, modOverride;
int currentToolIndex;
int scrolling;
int triggerPolling = 300;
int released = 0;
public override void Entry(IModHelper helper)
{
SaveEvents.AfterLoad += initializeMod;
GameEvents.UpdateTick += checkCurrentTool;
GameEvents.UpdateTick += checkPolling;
ControlEvents.KeyboardChanged += chooseToolKey;
ControlEvents.MouseChanged += checkHoveredItemMouse;
ControlEvents.ControllerTriggerPressed += setScrolling;
ControlEvents.ControllerTriggerReleased += unsetScrolling;
MenuEvents.MenuChanged += hijackInventoryPage;
isInitiated = false;
modOverride = false;
}
private void checkPolling(object sender, EventArgs e)
{
if (isInitiated && verticalToolbar.numToolsinToolbar > 0)
if (scrolling != 0)
{
if ( GamePad.GetState(PlayerIndex.One).IsButtonUp(Buttons.LeftTrigger) && GamePad.GetState(PlayerIndex.One).IsButtonUp(Buttons.RightTrigger))
{
scrolling = 0;
return;
}
Game1.player.CurrentToolIndex = currentToolIndex;
int triggerPolling = this.triggerPolling;
int elapasedGameTime1 = Game1.currentGameTime.ElapsedGameTime.Milliseconds;
this.triggerPolling = triggerPolling - elapasedGameTime1;
if(this.triggerPolling <= 0 && !modOverride)
{
Game1.player.CurrentToolIndex = currentToolIndex;
this.triggerPolling = 100;
checkHoveredItem(scrolling);
}
}
else if (released < 300)
{
Game1.player.CurrentToolIndex = currentToolIndex;
int polling = this.released;
int elapsedGameTime = Game1.currentGameTime.ElapsedGameTime.Milliseconds;
this.released = polling + elapsedGameTime;
if (released > 300 && !modOverride)
{
Game1.player.CurrentToolIndex = currentToolIndex;
released = 300;
}
}
}
private void setScrolling(object sender, EventArgsControllerTriggerPressed e)
{
if (!isInitiated) return;
if(verticalToolbar.numToolsinToolbar > 0 && (e.PlayerIndex == PlayerIndex.One && e.ButtonPressed == Buttons.LeftTrigger || e.ButtonPressed == Buttons.RightTrigger))
{
Game1.player.CurrentToolIndex = currentToolIndex;
int num = e.ButtonPressed == Buttons.LeftTrigger ? -1 : 1;
checkHoveredItem(num);
scrolling = num;
}
}
private void unsetScrolling(object sender, EventArgsControllerTriggerReleased e)
{
if (verticalToolbar.numToolsinToolbar > 0 && (e.PlayerIndex == PlayerIndex.One && e.ButtonReleased == Buttons.LeftTrigger || e.ButtonReleased == Buttons.RightTrigger))
{
Game1.player.CurrentToolIndex = currentToolIndex;
scrolling = 0;
released = 0;
triggerPolling = 300;
}
}
private void hijackInventoryPage(object sender, EventArgsClickableMenuChanged e)
{
if (Game1.activeClickableMenu is GameMenu)
{
GameMenu menu = (GameMenu)Game1.activeClickableMenu;
if (menu.currentTab == GameMenu.inventoryTab)
{
List<IClickableMenu> pages = (List<IClickableMenu>)typeof(GameMenu).GetField("pages", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(menu);
pages.RemoveAt(0);
pages.Insert(0, new InventoryPage(menu.xPositionOnScreen, menu.yPositionOnScreen, menu.width, menu.height));
}
}
}
private void checkCurrentTool(object sender, EventArgs e)
{
if (!isInitiated) return;
if (verticalToolbar.numToolsinToolbar > 0 && Game1.player.CurrentToolIndex != currentToolIndex)
{
if (modOverride || (triggerPolling < 300))
{
Game1.player.CurrentToolIndex = currentToolIndex;
modOverride = false;
}
}
}
private void checkHoveredItem(int num)
{
if ( !(!Game1.player.UsingTool && !Game1.dialogueUp && ((Game1.pickingTool || Game1.player.CanMove) && (!Game1.player.areAllItemsNull() && !Game1.eventUp))) ) return;
if (Game1.options.invertScrollDirection)
num *= -1;
while (true)
{
currentToolIndex += num;
if (num < 0)
{
if (currentToolIndex < 0)
{
currentToolIndex = Convert.ToInt32(verticalToolbar.buttons[verticalToolbar.numToolsinToolbar - 1].name);
}
else if (currentToolIndex > 11 && currentToolIndex < Convert.ToInt32(verticalToolbar.buttons[0].name))
{
currentToolIndex = 11;
}
}
else if (num > 0)
{
if (currentToolIndex > Convert.ToInt32(verticalToolbar.buttons[verticalToolbar.numToolsinToolbar - 1].name))
{
currentToolIndex = 0;
}
else if (currentToolIndex > 11 && currentToolIndex < Convert.ToInt32(verticalToolbar.buttons[0].name))
{
currentToolIndex = Convert.ToInt32(verticalToolbar.buttons[0].name);
}
}
if (Game1.player.items[currentToolIndex] != null)
break;
}
modOverride = true;
}
private void checkHoveredItemMouse(object sender, EventArgsMouseStateChanged e)
{
if (!isInitiated) return;
if (verticalToolbar.numToolsinToolbar > 0 && Mouse.GetState().ScrollWheelValue != Game1.oldMouseState.ScrollWheelValue)
{
int num = Mouse.GetState().ScrollWheelValue > Game1.oldMouseState.ScrollWheelValue ? -1 : 1;
checkHoveredItem(num);
}
}
private void chooseToolKey(object sender, EventArgsKeyboardStateChanged e)
{
if (!Game1.player.UsingTool && e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl))
{
if (e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl) && e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad1))
currentToolIndex = Convert.ToInt32(verticalToolbar.buttons[0].name);
else if (e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl) && e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad2))
currentToolIndex = Convert.ToInt32(verticalToolbar.buttons[1].name);
else if (e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl) && e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad3))
currentToolIndex = Convert.ToInt32(verticalToolbar.buttons[2].name);
else if (e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl) && e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad4))
currentToolIndex = Convert.ToInt32(verticalToolbar.buttons[3].name);
else if (e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl) && e.NewState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad5))
currentToolIndex = Convert.ToInt32(verticalToolbar.buttons[4].name);
modOverride = true;
}
}
private Toolbar getToolbar()
{
for (int index = 0; index < Game1.onScreenMenus.Count; ++index)
{
if (Game1.onScreenMenus[index] is Toolbar)
{
return Game1.onScreenMenus[index] as Toolbar;
}
}
return null;
}
private void initializeMod(object sender, EventArgs e)
{
verticalToolbar = new VerticalToolBar(getToolbar().xPositionOnScreen - (VerticalToolBar.getInitialWidth() / 2), Game1.viewport.Height - VerticalToolBar.getInitialHeight());
Game1.onScreenMenus.Add(verticalToolbar);
currentToolIndex = Game1.player.CurrentToolIndex;
isInitiated = true;
}
}
} |
using AbiokaScrum.Api.Data;
using AbiokaScrum.Api.Entities;
using AbiokaScrum.Api.Exceptions;
using AbiokaScrum.Api.Helper;
using AbiokaScrum.Api.IoC;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace AbiokaScrum.Api.Authentication
{
public interface IAuthProviderValidator
{
bool IsValid(string email, string token);
}
public class LocalAuthProviderValidator : IAuthProviderValidator
{
private readonly IUserOperation userOperation;
public LocalAuthProviderValidator(IUserOperation userOperation) {
this.userOperation = userOperation;
}
public bool IsValid(string email, string token)
{
var dbUser = userOperation.GetByEmail(email);
var result = dbUser != null && dbUser.ProviderToken == token;
return result;
}
}
public class GoogleAuthProviderValidator : IAuthProviderValidator
{
private readonly static string abiokaClientId;
private readonly string googleAddress = "accounts.google.com";
static GoogleAuthProviderValidator()
{
if (!ConfigurationManager.AppSettings.AllKeys.Contains("AbiokaClientId"))
throw new ValidationException("Google client id couldn't be found in web.config.");
abiokaClientId = ConfigurationManager.AppSettings["AbiokaClientId"];
}
public bool IsValid(string email, string token)
{
return Task.Run(() => IsValidToken(email, token)).Result;
}
private async Task<bool> IsValidToken(string email, string token)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com/oauth2/v1/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var url = string.Format("tokeninfo?id_token={0}", token);
var tokenResult = await client.GetAsync(url);
if (!tokenResult.IsSuccessStatusCode)
return false;
var result = await tokenResult.Content.ReadAsAsync<GoogleTokenResult>();
if (result.issuer != googleAddress && result.issuer != string.Format("https://{0}", googleAddress))
return false;
if (result.expires_in < 0)
return false;
if (result.audience != abiokaClientId)
return false;
if (result.email.ToLowerInvariant() != email.ToLowerInvariant())
return false;
return true;
}
}
private class GoogleTokenResult
{
public string issuer { get; set; }
public string issued_to { get; set; }
public string audience { get; set; }
public string user_id { get; set; }
public int expires_in { get; set; }
public string issued_at { get; set; }
public string email { get; set; }
public string email_verified { get; set; }
}
}
public class AuthProviderValidatorFactory
{
private static IDictionary<AuthProvider, IAuthProviderValidator> authProviderValidators;
static AuthProviderValidatorFactory() {
var userOperation = DependencyContainer.Container.Resolve<IUserOperation>();
authProviderValidators = new Dictionary<AuthProvider, IAuthProviderValidator>();
authProviderValidators.Add(AuthProvider.Local, new LocalAuthProviderValidator(userOperation));
authProviderValidators.Add(AuthProvider.Google, new GoogleAuthProviderValidator());
}
public static IAuthProviderValidator GetAuthProviderValidator(AuthProvider authProvider)
{
if (!authProviderValidators.ContainsKey(authProvider))
throw new ValidationException(ErrorMessage.InvalidProvider);
return authProviderValidators[authProvider];
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Nac.Fuzzy.Common {
public class NacFuzzyRuleRegex : Regex {
private static readonly string cSpace0 = @"\s*";
private static readonly string cSpace1 = @"\s+";
private static readonly string cIF = $@"\bIF\b";
private static readonly string cTHEN = $@"\bTHEN\b";
private static readonly string cnIFCond = "IfCond";
private static readonly string cnThenOp = "ThenOp";
private static readonly string cRule = $@"^{cSpace0}{cIF}{cSpace1}(?<{cnIFCond}>.+){cSpace1}{cTHEN}{cSpace1}(?<{cnThenOp}>.+){cSpace0}$";
private static readonly string cAND = $@"(?:\bAND\b)";
private static readonly string cOR = $@"(?:\bOR\b)";
private static readonly string cNOT = $@"(?:\bNOT\b)";
private static readonly string cOP = $@"{cAND}|{cOR}";
private static readonly string cOPNOT = $@"{cAND}{cSpace1}{cNOT}|{cOR}{cSpace1}{cNOT}";
private static readonly string cnLV = $@"LinVar";
private static readonly string cLV = $@"(?<{cnLV}>\w+)";
private static readonly string cnFS = $@"FuzzySet";
private static readonly string cFS = $@"(?<{cnFS}>\w+)";
private static readonly string cIS = $@"(?:\bIS\b)";
private static readonly string cnCLA = $@"Clause";
private static readonly string cCLA = $@"^(?<{cnCLA}>{cLV}{cSpace1}{cIS}{cSpace1}{cFS})$";
private static readonly string cCLANOT = $@"^(?<{cnCLA}>{cLV}{cSpace1}{cIS}({cSpace1}{cNOT})?{cSpace1}{cFS})$";
private string _text;
public string Text {
get { return _text; }
private set {
_text = value;
_fuzzyRule = null;
_inputs = null;
_output = null;
}
}
public NacFuzzyRuleRegex(string text) { Text = text; }
public bool IsFormatValid { get { return FuzzyRule != null; } }
public bool IsOutputValid { get { return _Output != null; } }
public bool AreInputsValid { get { return _Inputs != null; } }
public Tuple<string, string, string> Output {
get {
return new Tuple<string, string, string>(_Output.Groups[cnCLA].Value, _Output.Groups[cnLV].Value, _Output.Groups[cnFS].Value);
}
}
public IEnumerable<Tuple<string, string, string>> Inputs {
get {
foreach(var input in _Inputs.OfType<Match>())
yield return new Tuple<string, string, string>(input.Groups[cnCLA].Value, input.Groups[cnLV].Value, input.Groups[cnFS].Value);
}
}
private Match _fuzzyRule;
private Match FuzzyRule {
get {
if (_fuzzyRule == null) {
var matches = Matches(Text, cRule, RegexOptions.IgnoreCase);
if (matches.Count == 1) _fuzzyRule = matches[0];
}
return _fuzzyRule;
}
}
private string IfCond { get { return FuzzyRule?.Groups[cnIFCond].Value.Trim(); } }
private string ThenOp { get { return FuzzyRule?.Groups[cnThenOp].Value.Trim(); } }
private List<Match> _inputs;
private List<Match> _Inputs {
get {
if (_inputs == null) {
var result = new List<Match>();
var splitNOT = Split(IfCond, cOPNOT, RegexOptions.IgnoreCase);
foreach (var split in splitNOT) {
foreach (var clause in Split(split.Trim(), cOP, RegexOptions.IgnoreCase)) {
var matches = Matches(clause.Trim(), cCLANOT, RegexOptions.IgnoreCase);
if (matches.Count != 1) return null;
result.Add(matches[0]);
}
}
_inputs = result;
}
return _inputs;
}
}
private Match _output;
private Match _Output {
get {
if (_output == null) {
var matches = Matches(ThenOp, cCLA, RegexOptions.IgnoreCase);
if (matches.Count == 1) _output = matches[0];
}
return _output;
}
}
}
}
|
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OTAKURAO_wasm.Pages
{
public partial class Index
{
private int currentCount = 0;
public Index()
{
}
private void IncrementCount()
{
currentCount++;
}
}
}
|
using Cs_IssPrefeitura.Dominio.Entities;
using Cs_IssPrefeitura.Dominio.Interfaces.Repositorios;
using Cs_IssPrefeitura.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Cs_IssPrefeitura.Dominio.Servicos
{
public class ServicoAtoIss: ServicoBase<AtoIss>, IServicoAtoIss
{
private readonly IRepositorioAtoIss _repositorioAtoIss;
public ServicoAtoIss(IRepositorioAtoIss repositorioAtoIss)
:base(repositorioAtoIss)
{
_repositorioAtoIss = repositorioAtoIss;
}
public AtoIss CalcularValoresAtoIss(AtoIss atoCalcular)
{
int index;
string Siss = "0,00";
decimal iss = 0;
decimal aliquota = _repositorioAtoIss.AliquotaIss();
try
{
if (atoCalcular.Emolumentos > 0)
{
if (_repositorioAtoIss.TipoCalculoIss() == "Com Fórmula")
{
iss = atoCalcular.Emolumentos / ((100M - aliquota) / 100M);
iss = iss - atoCalcular.Emolumentos;
}
else
{
iss = (atoCalcular.Emolumentos * aliquota) / 100M;
}
Siss = Convert.ToString(iss);
index = Siss.IndexOf(',');
if (Siss.Length - index > 2)
Siss = Siss.Substring(0, index + 3);
atoCalcular.Iss = Convert.ToDecimal(Siss);
atoCalcular.Total = atoCalcular.Emolumentos + atoCalcular.Acoterj + atoCalcular.Distribuidor + atoCalcular.Fetj + atoCalcular.Funarpen + atoCalcular.Fundperj +
atoCalcular.Funperj + atoCalcular.Iss + atoCalcular.Mutua + atoCalcular.Ressag;
}
else
{
atoCalcular.Iss = 0;
atoCalcular.Total = 0;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return atoCalcular;
}
public List<AtoIss> LerArquivoXml(string caminho)
{
XmlTextReader leituraXml;
var AtoAdd = new AtoIss();
var AtosImpotados = new List<AtoIss>();
string leituraAtual = string.Empty;
leituraXml = new XmlTextReader(caminho);
leituraXml.ReadToFollowing("Relatorio");
string data = leituraXml.GetAttribute("DataPratica");
while (leituraXml.Read())
{
switch (leituraXml.NodeType)
{
case XmlNodeType.Element:
switch (leituraXml.Name)
{
case "DESC_ATRIBUICAO":
leituraAtual = leituraXml.Name;
break;
case "CD_SELO":
leituraAtual = leituraXml.Name;
break;
case "CD_ALEATORIO":
leituraAtual = leituraXml.Name;
break;
case "DESC_TIPO_ATO":
leituraAtual = leituraXml.Name;
break;
case "CD_TIPO_COBRANCA":
leituraAtual = leituraXml.Name;
break;
case "VALOR_EMOLUMENTOS":
leituraAtual = leituraXml.Name;
break;
case "FETJ":
leituraAtual = leituraXml.Name;
break;
case "FUNDPERJ":
leituraAtual = leituraXml.Name;
break;
case "FUNPERJ":
leituraAtual = leituraXml.Name;
break;
case "FUNARPEN":
leituraAtual = leituraXml.Name;
break;
case "RESSAG":
leituraAtual = leituraXml.Name;
break;
case "MUTUA":
leituraAtual = leituraXml.Name;
break;
case "ACOTERJ":
leituraAtual = leituraXml.Name;
break;
case "DISTRIBUIDOR":
leituraAtual = leituraXml.Name;
break;
}
break;
case XmlNodeType.Text:
switch (leituraAtual)
{
case "DESC_ATRIBUICAO":
AtoAdd.Atribuicao = leituraXml.Value;
break;
case "CD_SELO":
AtoAdd.Selo = leituraXml.Value;
break;
case "CD_ALEATORIO":
AtoAdd.Aleatorio = leituraXml.Value;
break;
case "DESC_TIPO_ATO":
AtoAdd.TipoAto = leituraXml.Value;
break;
case "CD_TIPO_COBRANCA":
AtoAdd.TipoCobranca = leituraXml.Value;
break;
case "VALOR_EMOLUMENTOS":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Emolumentos = Convert.ToDecimal(valor);
}
break;
case "FETJ":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Fetj = Convert.ToDecimal(valor);
}
break;
case "FUNDPERJ":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Fundperj = Convert.ToDecimal(valor);
}
break;
case "FUNPERJ":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Funperj = Convert.ToDecimal(valor);
}
break;
case "FUNARPEN":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Funarpen = Convert.ToDecimal(valor);
}
break;
case "RESSAG":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Ressag = Convert.ToDecimal(valor);
}
break;
case "MUTUA":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Mutua = Convert.ToDecimal(valor);
}
break;
case "ACOTERJ":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Acoterj = Convert.ToDecimal(valor);
}
break;
case "DISTRIBUIDOR":
if (leituraXml.Value != "" && leituraXml.Value != null)
{
var valor = leituraXml.Value.Replace('.', ',');
AtoAdd.Distribuidor = Convert.ToDecimal(valor);
}
break;
}
break;
case XmlNodeType.EndElement:
if (leituraXml.Name == "ItemRelatorio")
{
AtoAdd.Data = Convert.ToDateTime(data);
AtosImpotados.Add(AtoAdd);
AtoAdd = new AtoIss();
}
break;
}
}
return AtosImpotados;
}
public List<string> CarregarListaAtribuicoes()
{
return _repositorioAtoIss.CarregarListaAtribuicoes();
}
public List<string> CarregarListaTipoAtos()
{
return _repositorioAtoIss.CarregarListaTipoAtos();
}
public List<AtoIss> ListarAtosPorPeriodo(DateTime inicio, DateTime fim)
{
return _repositorioAtoIss.ListarAtosPorPeriodo(inicio, fim);
}
public List<AtoIss> VerificarRegistrosExistentesPorData(DateTime data)
{
return _repositorioAtoIss.VerificarRegistrosExistentesPorData(data);
}
public List<AtoIss> ConsultaDetalhada(string tipoConsulta, string dados)
{
return _repositorioAtoIss.ConsultaDetalhada(tipoConsulta, dados);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using Assets.Common.HorseGame.States;
using Assets.Common.HorseGame.Board;
using M2MqttUnity.Examples;
namespace Assets.Common {
namespace HorseGame
{
public sealed class GameContext
{
public static bool Victory = false;
public static List<Square> Squares;
public static CList<Player> Players;
public static List<Square> Stables;
public static Transform BoardTransform;
public static GameObject Horse;
public static int Dice;
public static float SquareSize;
public static CoroutineLauncher CoroutineLauncher;
public static MovePawn movePawn;
public static Text DisplayLabel;
public static M2MqttUnityTest MQTT;
public static void MovePawn(Pawn pawn, HorseMoveType horseMoveType, Square destination = null)
{
//if (pawn.Owner().index == 3 && movePawn != null) Debug.Log("bah voila pourquoi ça bouge pas");
movePawn.DynamicInvoke(pawn, horseMoveType, destination);
}
public static Pawn Occupied(Square square)
{
return Players.List.SelectMany(player => player.Pawns).FirstOrDefault(pawn => pawn.ActualSquare().index == square.index);
}
public static Square GoTo(Square startSquare, int dice)
{
Square retSquare = null;
Square stableSquare = GameContext.Stables[GameContext.Players.GetPlayer().boardIndex];
Square sprintSquare = stableSquare.next.next.back;
if (startSquare.index < 56)
{
for (int i=0; i<dice; i++)
{
if (retSquare != null && !(Occupied(retSquare) != null && dice - i > 0)) retSquare = retSquare.ChangeDirection(HorseDirection.next);
else if (retSquare == null) retSquare = startSquare.next;
}
}
else if (startSquare.index == sprintSquare.index && dice == 6 && Occupied(startSquare.right)!=null)
{
Debug.Log("passe par le sprint");
retSquare = startSquare.ChangeDirection(HorseDirection.right);
}
else if (startSquare.index > sprintSquare.index && sprintSquare.index + 6 < startSquare.index && startSquare.index - sprintSquare.right.index + 1 == dice && Occupied(startSquare.next) != null)
{
Debug.Log("passe DANS le sprint");
retSquare = startSquare.ChangeDirection(HorseDirection.next);
}
else if ((startSquare.index == stableSquare.index || startSquare.index == stableSquare.next.index) && dice == 6 && Occupied(stableSquare.next.next) == null)
{
//Debug.Log();
retSquare = stableSquare.next.next;
}
return retSquare;
}
public static bool isBothHorsesInStable(Player player)
{
bool retValue = true;
player.Pawns.ForEach(p =>
{
retValue = retValue && (p.ActualSquare().index == Stables[player.boardIndex].index || p.ActualSquare().index == Stables[player.boardIndex].next.index);
});
return retValue;
}
//public static bool TryNavigateTo
private static List<KeyValuePair<string, trigger>> events = new List<KeyValuePair<string, trigger>>();
public static void Submit(string eventName, System.Object parameters = null)
{
foreach (var trigger in events)
{
if (trigger.Key.Equals(eventName)) trigger.Value.DynamicInvoke(parameters);
}
}
public static void Subscribe(string eventName, trigger trigger)
{
var newEvents = events.Select(e => e).ToList();
newEvents.Add(new KeyValuePair<string, trigger>(eventName, trigger));
events = newEvents;
}
public static void UnSubscribe(string eventName, trigger trigger = null)
{
if (trigger == null) events = events.Where(pair => !pair.Key.Equals(eventName)).ToList();
else events = events.Where(pair => !(pair.Key.Equals(eventName) && pair.Value.Equals(trigger))).ToList();
}
private static IState actualState;
public static IState ActualState
{
get
{
return actualState;
}
set
{
actualState = value;
GameContext.Submit("NextStep");
}
}
public static void StartCoroutine(coroutine coroutine)
{
CoroutineLauncher.LaunchCoroutine(coroutine);
}
}
}
}
|
using Controller.ExaminationAndPatientCard;
using Controller.RoomAndEquipment;
using Controller.UsersAndWorkingTime;
using Model.Manager;
using Model.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Clinic_Health.Views.Employees
{
/// <summary>
/// Interaction logic for AddDoctorView.xaml
/// </summary>
public partial class AddDoctorView : UserControl
{
private static DoctorController dc = new DoctorController();
private UserController uc = new UserController(dc);
public AddDoctorView()
{
InitializeComponent();
}
private void ButtonSacuvajLekara_Click(object sender, RoutedEventArgs e)
{
Doctor doctor = new Doctor();
doctor.Jmbg= JmbgTb.Text as string;
doctor.Name= ImeTb.Text as string;
doctor.DateOfBirth= (DateTime)DatumRTb.SelectedDate;
doctor.DateOfEmployment= (DateTime)DatumZTb.SelectedDate;
doctor.Email= EmailTb.Text as string;
doctor.Phone= TelTb.Text as string;
doctor.HomeAddress= AdresaTb.Text as string;
doctor.Surname = PrezimeTb.Text as string;
doctor.Username= KorisnikTb.Text as string;
doctor.Password= SifraTb.Text as string;
doctor.NumberOfLicence= LicencaTb.Text as string;
doctor.Type= (TypeOfDoctor)TipTb.SelectedItem;
doctor.Gender = (GenderType)PolCb.SelectedItem;
int soba= Convert.ToInt32(SobaTb.Text);
int grad = Convert.ToInt32(GradTb.Text);
RoomController roomController = new RoomController();
Room room=roomController.ViewRoomByNumber(soba);
doctor.DoctorsOffice = room;
CityController cityController = new CityController();
City city = cityController.getCityByZipCode(grad);
doctor.City = city;
Doctor s = new Doctor();
s=(Doctor)uc.ViewProfile(doctor.Jmbg);
if (s==null) {
uc.Register(doctor);
Poruka.Text = "Uspesno ste sacuvali doktora!";
} else {
uc.EditProfile(doctor);
ExaminationController ec = new ExaminationController();
ec.DeleteDoctorExaminations(doctor.Jmbg);
WorkingTimeController wtc = new WorkingTimeController();
WorkingTime novo = new WorkingTime();
novo= wtc.viewWorkingTimeDoctor(doctor.Jmbg);
wtc.EditWorkingTime(novo);
Poruka.Text = "Uspesno ste izmenili doktora!";
}
/* VALIDACIJA
// 1. Resetovati sve validacione poruke
ResetAllErrors();
// 2. Izvrsiti validaciju
bool isValid = true;
if (String.IsNullOrWhiteSpace(ImeTb.Text))
{
ErrorImeTb.Text = "Morate uneti ime";
ImeTb.BorderBrush = Brushes.Red;
isValid = false;
}
//
// Ostatak validacije
//
Poruka.Text = "Uspesno ste sacuvali lekara!";
// 3. Reagovati na rezultat validacije
if (isValid)
{
// Dodaj lekara
// SuccessMessageTb.Text = "Uspesno ste dodali lekara.";
// Resetovati sve textboxove, comboboxove, datepickere.
// Za sve TB stavis .Text = ""
// Za DatePicker.SelectedDate stavis DateTime.Now
// Za CB stavis .SelectedItem = ListZaCB[0]
}*/
}
private void ResetAllErrors()
{
// SuccessMessageTb.Text = "";
ErrorImeTb.Text = "";
ImeTb.BorderBrush = Brushes.Black;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _57_Lesson
{
class Program
{
static void Main(string[] args)
{
int[,] myArray = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
for (int i = 0; i < myArray.GetLength(0); i++)
{
for (int j = 0; j < myArray.GetLength(1); j++)
{
Console.Write(myArray[i, j] + " ");
}
}
Console.WriteLine();
foreach (var item in myArray)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using service.Models;
namespace service.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class WealthapiController : ControllerBase
{
public Logmodel log = new Logmodel();
private Dictionary<object, object> wealth_default_condition;
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "wealth", "ite_smartBiz" };
}
[HttpPost]
public async Task<IActionResult> Post()
{
Mysqlswan swan = new Mysqlswan();
Mysqlwealth wealth = new Mysqlwealth();
var param_ins = new Dictionary<object, object>();
var api_status = "";
var Apiflow_default_condition = new Dictionary<object, object>();
try
{
var body = "";
using (var mem = new MemoryStream())
using (var reader = new StreamReader(mem))
{
Request.Body.CopyTo(mem);
body = reader.ReadToEnd();
mem.Seek(0, SeekOrigin.Begin);
body = reader.ReadToEnd();
}
_ = log.swan_core_log("wealthapi", "log Post Wealth : " + body.ToString());
var request_data = JObject.Parse(body);
_ = log.swan_core_log("wealthapi", "log Parser Wealth : " + request_data.ToString());
var mappingdata = await apimap_wealth(request_data["apiname"].ToString().Replace(request_data["apiname"].ToString().Substring(0, 4), ""));
var sub_prefix_interface = request_data["apiname"].ToString().Substring(0, 4);
_ = log.swan_core_log("wealthapi", "Status sub_prefix apiname : " + sub_prefix_interface);
var ps_mappingdata = JObject.Parse(mappingdata);
switch (sub_prefix_interface)
{
case "ins_":
foreach (var item in ps_mappingdata)
{
param_ins.Add(item.Value.ToString(), request_data[item.Key.ToString()].ToString());
}
var ins_data = wealth.data_ins(request_data["apiname"].ToString().Replace("ins_", ""), JsonConvert.SerializeObject(param_ins));
_ = log.swan_core_log("wealthapi", "Status apiaction : " + JsonConvert.SerializeObject(ins_data));
break;
case "upd_":
foreach (var item in ps_mappingdata)
{
param_ins.Add(item.Value.ToString(), request_data[item.Key.ToString()].ToString());
}
var param_condition = new Dictionary<object, object>();
param_condition.Add("hawkid", request_data["hawkid"].ToString());
var upd_data = wealth.data_update(request_data["apiname"].ToString().Replace("upd_", ""), JsonConvert.SerializeObject(param_ins), JsonConvert.SerializeObject(param_condition));
_ = log.swan_core_log("wealthapi", "Status Update status : " + JsonConvert.SerializeObject(upd_data));
break;
case "str_":
var list_field = new List<object>();
var list_param = new List<object>();
foreach (var item in ps_mappingdata)
{
list_param.Add("@" + item.Key.ToString());
}
string Command = "CALL " + request_data["apiname"].ToString().Replace("str_", "") + "(" + String.Join(',', list_param) + ")";
_ = log.swan_core_log("wealthapi", "Command db" + Command);
Dictionary<object, object> param = new Dictionary<object, object>();
foreach (var item in ps_mappingdata)
{
if (item.Key.ToString() == "apiname")
{
}
else {
param.Add(item.Key.ToString(), request_data[item.Key.ToString()].ToString());
}
}
_ = log.swan_core_log("wealthapi", "Param call stroc proc db" +JsonConvert.SerializeObject(param));
var proc_result = wealth.data_utility(Command, param);
_ = log.swan_core_log("wealthapi", "Status proc_data : " + JsonConvert.SerializeObject(proc_result));
break;
default:
break;
}
Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss"));
Apiflow_default_condition.Add("response", param_ins);
api_status = "true";
}
catch (Exception e) {
_ = log.swan_core_log("wealthapi", "Error : " + e.ToString());
Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss"));
Apiflow_default_condition.Add("response", "Invalid api");
api_status = "fail";
}
var status_api = "";
if (api_status == "Create")
{
status_api = "201";
}
else if (api_status == "true")
{
status_api = "200";
}
else if (api_status == "fail")
{
status_api = "400";
}
else if (api_status == " ")
{
status_api = "500";
}
return StatusCode(Int32.Parse(status_api), Apiflow_default_condition);
// return StatusCode(200, wealth_default_condition);
//return StatusCode(200, JsonConvert.SerializeObject(param_ins));
}
private async Task<string> apimap_wealth(string apicode)
{
Mysqlswan swan = new Mysqlswan();
Mysqlhawk hawk = new Mysqlhawk();
Logmodel log = new Logmodel();
Encryption_model encode = new Encryption_model();
var func_result = new Dictionary<object, object>();
try
{
var command = "SELECT interface_key AS apikey , interface_map AS apivalue FROM mapzila_wealth WHERE apicode = @1 AND `status` = 'Y' ORDER BY sorting ASC";
Dictionary<object, object> param = new Dictionary<object, object>();
param.Add("1", apicode);
var data_8585 = await swan.data_with_col(command, param);
var data_8586 = JsonConvert.SerializeObject(data_8585);
var data_8587 = JArray.Parse(data_8586);
for (int i = 0; i < data_8587.Count; i++)
{
func_result.Add(data_8587[i]["apikey"].ToString(), data_8587[i]["apivalue"].ToString());
}
}
catch (Exception e)
{
_ = log.swan_core_log("apimap_wealth", "Error : " + e.ToString());
}
return JsonConvert.SerializeObject(func_result);
}
// PUT: api/App1/5
// [HttpPut("{id}")]
public async Task<IActionResult> Put()
{
try
{
Mysqlswan swan = new Mysqlswan();
var body = "";
using (var mem = new MemoryStream())
using (var reader = new StreamReader(mem))
{
Request.Body.CopyTo(mem);
body = reader.ReadToEnd();
mem.Seek(0, SeekOrigin.Begin);
body = reader.ReadToEnd();
}
_ = log.swan_core_log("wealthapi", "log PUT Wealth : " + body.ToString());
var request_data = JObject.Parse(body);
_ = log.swan_core_log("wealthapi", "log Parser Wealth : " + request_data.ToString());
var mappingdata = await apimap_wealth(request_data["apiname"].ToString());
var param_ins = new Dictionary<object, object>();
var ps_mappingdata = JObject.Parse(mappingdata);
foreach (var item in ps_mappingdata)
{
param_ins.Add(item.Value.ToString(), request_data[item.Key.ToString()].ToString());
}
var param_condition = new Dictionary<object, object>();
param_condition.Add("hawkid", request_data["hawkid"].ToString());
var upd_data = swan.data_update(request_data["apiname"].ToString().Replace("upd_", ""), JsonConvert.SerializeObject(param_ins), JsonConvert.SerializeObject(param_condition));
}
catch (Exception e)
{
_ = log.swan_core_log("wealthapi", "Error : " + e.ToString());
}
return StatusCode(200, "method Not allow");
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
return StatusCode(200, "method Not allow");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.BackTracking
{
/// <summary>
/// Given a graph and a number m, make sure a graph can be colored by atmost m colors such that no 2 adjacent vetices have the same color.
/// </summary>
class GraphColoringWithMColors
{
/// <summary>
/// Coloring the graph is an NP complete problem. We will solve this in the similar way we solve the Sudoku problem
/// Color node with each of the available color and check whether all the other nodes can be colored with one of the colors in maxColors
///
/// The running time of this algo is O(maxColors^(n)) where n is the number of vertices
/// Recurence relation T(n) = maxColors*T(n-1)
/// </summary>
/// <param name="vertex">start vertex of a graph. This can be any vertex in the graph</param>
/// <returns>whether the whole graph can be colored using MaxColors different color</returns>
public bool ColorGraph(GraphVertex vertex, int maxColors)
{
for (int index = 0; index < maxColors; index++)
{
if (CanColor(vertex, index))
{
vertex.Color = index;
bool allNeighboursCanBeColored = true;
foreach(GraphVertex neighbour in vertex.Neighbours)
{
if(neighbour.Color ==-1 && !ColorGraph(neighbour, maxColors))
{
allNeighboursCanBeColored = false;
break;
}
}
if (allNeighboursCanBeColored)
{
return true;
}
}
}
vertex.Color = -1; // Need for back tracking
return false;
}
/// <summary>
/// Check whether a vertex can have a color
/// </summary>
/// <param name="vertex"></param>
/// <param name="color"></param>
/// <returns></returns>
private bool CanColor(GraphVertex vertex, int color)
{
foreach (GraphVertex neighbour in vertex.Neighbours)
{
if(neighbour.Color == color)
{
return false;
}
}
return true;
}
public static void TestGraphColoringWithMColors()
{
/*
The graph looks like like this
(0)
/\
/ \
/ \
(2) (1)
| \ |
| \ |
| \ |
(4)--(3)
\ /
\ /
(5)
*/
Graph graph = new Graph();
graph.AddUnDirectedEdge(0, 1);
graph.AddUnDirectedEdge(0, 2);
graph.AddUnDirectedEdge(1, 3);
graph.AddUnDirectedEdge(2, 3);
graph.AddUnDirectedEdge(2, 4);
graph.AddUnDirectedEdge(3, 4);
graph.AddUnDirectedEdge(3, 5);
graph.AddUnDirectedEdge(5, 4);
GraphColoringWithMColors coloring = new GraphColoringWithMColors();
int maxColor = 3;
Console.WriteLine("Can this graph be colored with {0} colors: {1}", maxColor, coloring.ColorGraph(graph.AllVertices[0], maxColor));
maxColor = 2;
graph.ResetGraph();
Console.WriteLine("Can this graph be colored with {0} colors: {1}", maxColor, coloring.ColorGraph(graph.AllVertices[0], maxColor));
maxColor = 1;
graph.ResetGraph();
Console.WriteLine("Can this graph be colored with {0} colors: {1}", maxColor, coloring.ColorGraph(graph.AllVertices[0], maxColor));
maxColor = 5;
graph.ResetGraph();
Console.WriteLine("Can this graph be colored with {0} colors: {1}", maxColor, coloring.ColorGraph(graph.AllVertices[0], maxColor));
}
/// <summary>
/// Represents the vertex of a graph
/// </summary>
internal class GraphVertex
{
public int Id { get; set; }
public List<GraphVertex> Neighbours { get; set; }
public int Color { get; set; }
public GraphVertex(int id)
{
Id = id;
Neighbours = new List<GraphVertex>();
Color = -1;
}
}
/// <summary>
/// Represents the graph class
/// </summary>
internal class Graph
{
public Graph()
{
AllVertices = new Dictionary<int, GraphVertex>();
}
/// <summary>
/// Dictionary to store all the graph vertices and give O(1) access using the vertex ids
/// </summary>
public Dictionary<int, GraphVertex> AllVertices { get; set; }
/// <summary>
/// Add the edge from the node having start as the id to node having end as the id
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
public void AddDirectedEdge(int start, int end)
{
if (!AllVertices.ContainsKey(start))
{
AllVertices[start] = new GraphVertex(start);
}
if (!AllVertices.ContainsKey(end))
{
AllVertices[end] = new GraphVertex(end);
}
AllVertices[start].Neighbours.Add(AllVertices[end]);
}
/// <summary>
/// Add an undirected edge between start and end vertex
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
public void AddUnDirectedEdge(int start, int end)
{
if (!AllVertices.ContainsKey(start))
{
AllVertices[start] = new GraphVertex(start);
}
if (!AllVertices.ContainsKey(end))
{
AllVertices[end] = new GraphVertex(end);
}
AllVertices[start].Neighbours.Add(AllVertices[end]);
AllVertices[end].Neighbours.Add(AllVertices[start]);
}
/// <summary>
/// This method will be used to reset the color of all the vertices in the graph to -1
/// </summary>
public void ResetGraph()
{
foreach (GraphVertex vertex in AllVertices.Values)
{
vertex.Color = -1;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Upkeep.Modules.DatabaseExplorer.Models
{
public class SqlSnippet
{
public string Name { get; set; }
public string Sql { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
namespace TestShop.Application.Models.Account
{
public class ResetPasswordModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(150, ErrorMessage = "Password length must be at least 6 symbols", MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare(nameof(Password), ErrorMessage = "Passwords do not match")]
public string ConfirmPassword { get; set; }
public string Code { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//Class to manage insertion to and deletion from the Scroll rect (UI list)
public class AppendProgramList : MonoBehaviour {
public Image panel;
private int programsShownCount = 0;
//Add one new entity to Scroll rect
public void AppendProgram(string name)
{
Image copy = Instantiate(panel);
copy.GetComponentInChildren<Text>().text = name;
copy.transform.SetParent(transform);
copy.enabled = true;
++programsShownCount;
}
//Clear Scroll rect
public void ClearList()
{
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
programsShownCount = 0;
}
//Returns count of entities shown currently
public int GetShownCount()
{
return programsShownCount;
}
}
|
/******************************************************************************\
* Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. *
* Leap Motion proprietary and confidential. Not for distribution. *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
\******************************************************************************/
namespace Leap
{
using System;
using System.Runtime.InteropServices;
/**
* The FailedDevice class provides information about Leap Motion hardware that
* has been physically connected to the client computer, but is not operating
* correctly.
*
* Failed devices do not provide any tracking data and do not show up in the
* Controller:devices() list.
*
* Get the list of failed devices using Controller::failedDevices().
*
* \include FailedDevice_class.txt
*
* @since 3.0
*/
//TODO Implement FailedDevices
public class FailedDevice:
IEquatable<FailedDevice>
{
public FailedDevice() {
Failure = FailureType.FAIL_UNKNOWN;
PnpId = "0";
}
/**
* Test FailedDevice equality.
* True if the devices are the same.
* @since 3.0
*/
public bool Equals(FailedDevice other)
{
return this.PnpId == other.PnpId;
}
/**
* The device plug-and-play id string.
* @since 3.0
*/
public string PnpId { get; private set; }
/**
* The reason for device failure.
*
* The failure reasons are defined as members of the FailureType enumeration:
*
* **FailureType::FAIL_UNKNOWN** The cause of the error is unknown.
*
* **FailureType::FAIL_CALIBRATION** The device has a bad calibration record.
*
* **FailureType::FAIL_FIRMWARE** The device firmware is corrupt or failed to update.
*
* **FailureType::FAIL_TRANSPORT** The device is unresponsive.
*
* **FailureType::FAIL_CONTROL** The service cannot establish the required USB control interfaces.
*
* **FailureType::FAIL_COUNT** Not currently used.
*
* @since 3.0
*/
public FailedDevice.FailureType Failure { get; private set; }
/**
* The errors that can cause a device to fail to properly connect to the service.
*
* @since 3.0
*/
public enum FailureType
{
/** The cause of the error is unknown.
* @since 3.0
*/
FAIL_UNKNOWN,
/** The device has a bad calibration record.
* @since 3.0
*/
FAIL_CALIBRATION,
/** The device firmware is corrupt or failed to update.
* @since 3.0
*/
FAIL_FIRMWARE,
/** The device is unresponsive.
* @since 3.0
*/
FAIL_TRANSPORT,
/** The service cannot establish the required USB control interfaces.
* @since 3.0
*/
FAIL_CONTROL,
/** Not currently used.
* @since 3.0
*/
FAIL_COUNT
}
}
}
|
/*
* Created by SharpDevelop.
* User: Admin
* Date: 5/6/2019
* Time: 4:07 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Collections;
namespace proyeto_poo
{
/// <summary>
/// Description of Functions.
/// </summary>
public class Functions
{
[DllImport("User32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr h, string m, string c, int type);
public Functions()
{
}
static public void WindowLog(){
Console.BackgroundColor = ConsoleColor.Black;
Console.Clear();
ConsoleEx.TextColor(ConsoleForeground.White, ConsoleBackground.Blue);
ConsoleEx.DrawRectangle(BorderStyle.LineDouble, 1, 1, 77, 22, true);
}
static public void WindowLogged(string title, int textX = 3){
Console.BackgroundColor = ConsoleColor.Black;
Console.Clear();
ConsoleEx.TextColor(ConsoleForeground.White, ConsoleBackground.Aquamarine);
ConsoleEx.DrawRectangle(BorderStyle.LineSingle, 1, 1, 77, 3, true);
Write(title, textX, 3);
ConsoleEx.TextColor(ConsoleForeground.White, ConsoleBackground.Blue);
ConsoleEx.DrawRectangle(BorderStyle.LineDouble, 1, 5, 77, 18, true);
Console.Title = title;
}
static public void Write(string text = "",int x = 0, int y = 0 ){
ConsoleEx.WriteAt(x, y, text);
}
static public void Move(int x = 0, int y = 0){
ConsoleEx.CursorVisible = true;
ConsoleEx.Move(x,y);
}
static public string MoveRead(int x = 0, int y = 0){
string value = null;
ConsoleEx.CursorVisible = true;
ConsoleEx.Move(x,y);
value = Console.ReadLine();
return value;
}
static public void PopUp(string message = null, string title = null){
MessageBox((IntPtr)0, message, title, 0);
}
static public void Pause(){
ConsoleEx.CursorVisible = false;
Console.ReadKey();
}
static public string TimeHour(int time){
string timeHour = null;
if (time == 1){
timeHour = time + " AM";
}else if (time == 2){
timeHour = time + " AM";
}else if (time == 3){
timeHour = time + " AM";
}else if (time == 4){
timeHour = time + " AM";
}else if (time == 5){
timeHour = time + " AM";
}else if (time == 6){
timeHour = time + " AM";
}else if (time == 7){
timeHour = time + " AM";
}else if (time == 8){
timeHour = time + " AM";
}else if (time == 9){
timeHour = time + " AM";
}else if (time == 10){
timeHour = time + " AM";
}else if (time == 11){
timeHour = time + " AM";
}else if (time == 12){
timeHour = time + " PM";
}else if (time == 13){
timeHour = (time - 12) + " PM";
}else if (time == 14){
timeHour = (time - 12) + " PM";
}else if (time == 15){
timeHour = (time - 12) + " PM";
}else if (time == 16){
timeHour = (time - 12) + " PM";
}else if (time == 17){
timeHour = (time - 12) + " PM";
}else if (time == 18){
timeHour = (time - 12) + " PM";
}else if (time == 19){
timeHour = (time - 12) + " PM";
}else if (time == 20){
timeHour = (time - 12) + " PM";
}else if (time == 21){
timeHour = (time - 12) + " PM";
}else if (time == 22){
timeHour = (time - 12) + " PM";
}else if (time == 23){
timeHour = (time - 12) + " PM";
}else if (time == 24){
timeHour = (time - 12) + " PM";
}
return timeHour;
}
}
}
|
using GalaSoft.MvvmLight.Messaging;
using Newtonsoft.Json;
using Q400SimpitController.ViewModel.Messaging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Q400SimpitController.ViewModel
{
public class CommunicationVM
{
private UdpClient _client;
private IPEndPoint _endPoint;
private IAsyncResult _curAsyncResult;
private string _setupFilePath;
private JsonSerializerSettings _jsonSerializerSettings;
private SetupMessage Setup;
public CommunicationVM(string setupFilePath, JsonSerializerSettings jsonSerializerSettings)
{
_setupFilePath = setupFilePath;
_jsonSerializerSettings = jsonSerializerSettings;
Messenger.Default.Register<SetupMessage>(this, OnSetup);
}
#region Event part
private void OnSetup(SetupMessage message)
{
if (Setup != null && Setup.SimPcIp == message.SimPcIp && Setup.SimPcPort == message.SimPcPort && Setup.LocalPort == message.LocalPort)
return;
Setup = message;
File.WriteAllText(_setupFilePath, JsonConvert.SerializeObject(message, _jsonSerializerSettings));
CheckStartSimPcCommunication();
}
#endregion
private void CheckStartSimPcCommunication()
{
StopReceivingUdpFromSimPc();
StartReceivingUdpFromSimPc();
}
private void StartReceivingUdpFromSimPc()
{
_client = new UdpClient(Setup.LocalPort);
_endPoint = new IPEndPoint(Setup.SimPcIp, Setup.SimPcPort);
_client.Connect(_endPoint);
_curAsyncResult = _client.BeginReceive(new AsyncCallback(ReceivedUdpFromSimPc), null);
//var msg = Utils.BuildMessage((short) 0x1016, (short) 2, singleByte: true);
//_client.Send(msg, msg.Length);
}
private void StopReceivingUdpFromSimPc()
{
_client?.Close();
}
private void ReceivedUdpFromSimPc(IAsyncResult ar)
{
if (_curAsyncResult != ar) return;
try
{
var buffer = _client.EndReceive(ar, ref _endPoint);
Debugger.Log(0, "trace", string.Join("-", buffer.ToList().Select(b => $"{b:X}")));
_client.BeginReceive(new AsyncCallback(ReceivedUdpFromSimPc), null);
}
catch (Exception ex)
{
if (ex is ObjectDisposedException || ex is SocketException) return;
MessageBox.Show("An exception just occurred: " + ex.Message, "Exception",
MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}
}
|
using UnityEngine;
using UnityEngine.Networking;
using System.Linq;
public class ObjectPosition : NetworkBehaviour
{
private float tps = 15;
private float curTps;
private Vector3 moveDirection;
private Vector3 smooth;
public new Transform transform
{
get
{
for (int i = 0; i < gameObject.transform.Find("Models").childCount; i++)
{
if (gameObject.transform.Find("Models").GetChild(i) != null && gameObject.transform.Find("Models").GetChild(i).gameObject.activeSelf == true)
{
return gameObject.transform.Find("Models").GetChild(i);
}
}
Debug.LogError($"{this.gameObject.name} has no active models!");
return null;
}
}
public void Update()
{
if (transform == null)
return;
if (hasAuthority)
{
curTps += Time.deltaTime;
if (curTps >= (1 / tps))
{
curTps -= (1 / tps);
Cmd_SyncObject(transform.position, transform.rotation, transform.name);
}
}
else
{
transform.position = Vector3.SmoothDamp(transform.position, moveDirection, ref smooth, 0.08f);
}
}
[Command]
public void Cmd_SyncObject(Vector3 position, Quaternion direction, string activeModel)
{
moveDirection = position;
transform.rotation = direction;
Rpc_SyncObject(position, direction, activeModel);
}
[ClientRpc]
private void Rpc_SyncObject(Vector3 position, Quaternion direction, string activeModel)
{
if (!isLocalPlayer)
{
moveDirection = position;
transform.rotation = direction;
}
}
[TargetRpc]
public void Target_SyncObject(NetworkConnection target, string activeModel, Vector3 position)
{
for (int i = 0; i < gameObject.transform.Find("Models").childCount; i++)
{
if (gameObject.transform.Find("Models").GetChild(i).name == activeModel)
{
gameObject.transform.Find("Models").GetChild(i).gameObject.SetActive(true);
}
else
{
gameObject.transform.Find("Models").GetChild(i).gameObject.SetActive(false);
}
}
moveDirection = position;
}
} |
using SamOthellop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static SamOthellop.Model.BoardBase;
namespace SamOthellop.View
{
public static class BoardColorDictionary
{
public static Dictionary<BoardStates, System.Drawing.Color> BoardStateColors = new Dictionary<BoardStates, System.Drawing.Color>()
{
{BoardStates.black, System.Drawing.Color.Black },
{BoardStates.white, System.Drawing.Color.White },
{BoardStates.empty, System.Drawing.Color.DarkOliveGreen }
};
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
public class KH_PlayerController : MonoBehaviour
{
public float moveSpeed = 4.0f; //from https://youtu.be/XhliRnzJe5g (How to Make An Isometric Camera and Character Controller in Unity3D)
public float jumpForce = 7.0f; //from https://youtu.be/vdOFUFMiPDU (How To Jump in Unity - Unity Jumping Tutorial | Make Your Characters Jump in Unity)
public float fallMultiplier = 2.5f; //from https://youtu.be/7KiK0Aqtmzc (Better Jumping in Unity With Four Lines of Code)
public float lowJumpMultiplier = 2.0f;
public LayerMask groundLayers;
private Vector3 forward, right;
private PlayerInputAction controls;
private Vector2 movementInput;
private bool jumpInput;
private bool canDoubleJump; //from https://youtu.be/DEGEEZmfTT0 (Simple Double Jump in Unity 2D (Unity Tutorial for Beginners))
private float horizontalMovement, verticalMovement;
private GameObject mPlayer;
public Animator anim;
public Rigidbody rb;
public Collider playerCollider;
[TextArea]
public string Notes = "1st Box Collider is the actual Collider, referenced in the movement script.\n" +
"2nd Box Collider is slightly wider with NoFriction PhysicsMaterial to prevent player from sticking to the wall mid-jump.\n" +
"The ground needs to be tagged w/ Platform for Jumping to work.";
void Awake()
{
controls = new PlayerInputAction();
controls.PlayerControls.Move.performed += ctx => movementInput = ctx.ReadValue<Vector2>();
controls.PlayerControls.Move.canceled += ctx => movementInput = Vector2.zero;
controls.PlayerControls.Jump.started += ctx => jumpInput = true;
}
void Start()
{
forward = Camera.main.transform.forward;
forward.y = 0;
forward = Vector3.Normalize(forward);
right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
mPlayer = GameObject.Find("Character");
//anim = mPlayer.GetComponent<Animator>();
//rb = GetComponent<Rigidbody>();
//playerCollider = GetComponent<BoxCollider>();
}
// Update is called once per frame
void Update()
{
forward = Camera.main.transform.forward;
forward.y = 0;
forward = Vector3.Normalize(forward);
right = Quaternion.Euler(new Vector3(0, 90, 0)) * forward;
MovePlayer();
}
void MovePlayer()
{
horizontalMovement = movementInput.x;
verticalMovement = movementInput.y;
//Vector3 rightMovement = right * moveSpeed * Time.deltaTime * horizontalMovement;
//Vector3 upMovement = forward * moveSpeed * Time.deltaTime * verticalMovement;
//Vector3 heading = Vector3.Normalize(rightMovement + upMovement);
//transform.position += rightMovement;
//transform.position += upMovement;
//Vector3 rightMovement = right * moveSpeed * Time.deltaTime * horizontalMovement;
//Vector3 upMovement = forward * moveSpeed * Time.deltaTime * verticalMovement;
Vector3 rightMovement = right * moveSpeed * horizontalMovement;
Vector3 upMovement = forward * moveSpeed * verticalMovement;
Vector3 groundMovement = rightMovement + upMovement;
Vector3 heading = Vector3.Normalize(groundMovement);
//rb.MovePosition(transform.position + movement);
//rb.AddForce(movement, ForceMode.Acceleration);
rb.velocity = new Vector3(groundMovement.x, rb.velocity.y, groundMovement.z);
// JUMPING
if (IsGrounded())
{
canDoubleJump = true;
anim.SetFloat("VSpeed", 0);
anim.SetBool("IsJumping", false);
anim.SetBool("IsDoubleJumping", false);
}
if (jumpInput)
{
if (IsGrounded())
{
anim.SetBool("IsJumping", true);
rb.velocity = Vector3.up * jumpForce;
}
else if (canDoubleJump)
{
anim.SetBool("IsJumping", true);
anim.SetBool("IsDoubleJumping", true);
rb.velocity = Vector3.up * jumpForce;
canDoubleJump = false;
}
}
jumpInput = false; //from https://forum.unity.com/threads/how-would-you-handle-a-getbuttondown-situaiton-with-the-new-input-system.627184/#post-5015597
// JUMP MODIFIERS FOR BETTER FEEL
if (rb.velocity.y < 0)
{
rb.velocity += Vector3.up * Physics.gravity.y * fallMultiplier * Time.deltaTime; //using Time.deltaTime due to acceleration
anim.SetFloat("VSpeed", -1);
anim.SetBool("IsJumping", false);
}
else if (rb.velocity.y > 0)
{
anim.SetFloat("VSpeed", 1);
rb.velocity += Vector3.up * Physics.gravity.y * lowJumpMultiplier * Time.deltaTime; //using Time.deltaTime due to acceleration
}
// FULL STOP WHEN JOYSTICK IS RELEASED
if (horizontalMovement == 0 && verticalMovement == 0)
{
rb.velocity = new Vector3(0, rb.velocity.y, 0);
}
// DISABLE RIGIDBODY FUMBLING
rb.constraints = RigidbodyConstraints.FreezeRotation;
// MOVE PLAYER WHEN JOYSTICK MOVES
if (horizontalMovement != 0 || verticalMovement != 0)
{
anim.SetFloat("HSpeed", 1);
if (heading.sqrMagnitude > 0.1f) //better turning, from https://answers.unity.com/questions/422744/rotation-of-character-resets-when-joystick-is-rele.html
{
transform.forward = heading;
}
}
else
{
anim.SetFloat("HSpeed", 0);
}
//if (anim.GetCurrentAnimatorStateInfo(0).IsName("Idle"))
//{
// Debug.Log("Idle");
//}
//if (anim.GetCurrentAnimatorStateInfo(0).IsName("Walk"))
//{
// Debug.Log("Walk");
//}
//if (anim.GetCurrentAnimatorStateInfo(0).IsName("Jump"))
//{
// Debug.Log("Jump");
//}
//if (anim.GetCurrentAnimatorStateInfo(0).IsName("Land"))
//{
// Debug.Log("Land");
//}
}
private bool IsGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, playerCollider.bounds.extents.y + 0.1f, groundLayers);
}
private void OnEnable()
{
controls.Enable();
}
private void OnDisable()
{
controls.Disable();
}
}
|
using GalaSoft.MvvmLight;
using MarkdownUtils.MdAnimated;
using Miktemk;
using Miktemk.TextToSpeech.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarkdownAnimator.ViewModel
{
public class MdDocumentTtsReader : ViewModelBase
{
private Func<MdDocumentEnumerator> funcGetDocPager;
private ITtsService ttsService;
private int lengthsOfPreviouslySaidPhrases;
public bool IsPlaying { get; private set; } = false;
public MdDocumentTtsReader(Func<MdDocumentEnumerator> funcGetDocPager, ITtsService ttsService)
{
this.funcGetDocPager = funcGetDocPager;
this.ttsService = ttsService;
ttsService.AddWordCallback(wordCallback);
}
public void PlayStop()
{
if (ttsService.IsPlaying)
{
Stop();
return;
}
IsPlaying = true;
SayCurPage();
}
public void Stop()
{
IsPlaying = false;
ttsService.StopCurrentSynth();
}
public void SetSpeed(int speed)
{
ttsService.SetVoiceOverrideSpeed(speed);
}
private void SayCurPage()
{
var docPager = funcGetDocPager();
if (docPager.CurPage == null)
return;
ttsService.SayAsyncMany(docPager.CurPage.TtsText, (phrase, index) =>
{
if (index > 0)
{
// if #2 and more, add previous phrase's length to lengthsOfPreviouslySaidPhrases
lengthsOfPreviouslySaidPhrases += docPager.CurPage.TtsText.Phrases[index - 1].Text.Length;
}
if (phrase == null) // .... AKA last
GoToNextPage();
}, 0, 0);
Debug.WriteLine("========== page ============");
Debug.WriteLine($"new-code: {docPager.CurPage.Code}");
Debug.WriteLine($"saying: {docPager.CurPage.TtsTextString}");
}
private void GoToNextPage()
{
var docPager = funcGetDocPager();
var backToStart = docPager.GoToNextPage();
if (!backToStart)
{
lengthsOfPreviouslySaidPhrases = 0;
SayCurPage();
}
else
IsPlaying = false;
}
private void wordCallback(string text, int offset, int start, int length)
{
var indexTotal = offset + lengthsOfPreviouslySaidPhrases;
var docPager = funcGetDocPager();
docPager.ReadUntilThisPoint(indexTotal);
}
}
}
|
namespace RoShamBo
{
public abstract class Player
{
public RoShamBo roshamboValue { get; set; }
public string playerName { get; set; }
public abstract RoShamBo GetRoshamBo();
}
}
|
using System; //using 关键字用于在程序中包含 System 命名空间,一个程序一般有多个 using 语句.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorldApplication //该行是 namespace 声明。一个 namespace 是一系列的类。HelloWorldApplication 命名空间包含了类 HelloWorld。
{
class HelloWorld //该行是 class 声明。类 HelloWorld 包含了程序使用的数据和方法声明。类一般包含多个方法。方法定义了类的行为。在这里,HelloWorld 类只有一个 Main 方法。
{
static void Main(string[] args) //该行定义了 Main 方法,是所有 C# 程序的 入口点。Main 方法说明当执行时 类将做什么动作。
{
Console.WriteLine("Hello World"); //Main 方法通过语句 Console.WriteLine("Hello World"); 指定了它的行为。WriteLine 是一个定义在 System 命名空间中的 Console 类的一个方法。该语句会在屏幕上显示消息 "Hello, World!"。
Console.ReadKey(); // Console.ReadKey(); 是针对 VS.NET 用户的。这使得程序会等待一个按键的动作,防止程序从 Visual Studio .NET 启动时屏幕会快速运行并关闭。
}
}
}
|
using System;
namespace Maybe
{
// implements monad for the Maybe type (similar to Nullable but applyable to any type)
class Program
{
static void Main()
{
var r3 = from x in 5.ToMaybe()
from y in 6.ToMaybe()
select x + y;
Console.WriteLine(r3);
}
}
interface IMaybe<T> { }
class Nothing<T> : IMaybe<T>
{
public override string ToString()
{
return "Nothing";
}
}
class Just<T> : IMaybe<T>
{
public T Value { get; private set; }
public Just(T value)
{
Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}
static class MaybeExtensions
{
public static IMaybe<T> ToMaybe<T>(this T value)
{
return new Just<T>(value);
}
public static IMaybe<B> Bind<A, B>(this IMaybe<A> a, Func<A, IMaybe<B>> func)
{
var justa = a as Just<A>;
if (a == null)
return new Nothing<B>();
return func(justa.Value);
}
public static IMaybe<V> SelectMany<A, B, V>(this IMaybe<A> a, Func<A, IMaybe<B>> func, Func<A, B, V> s)
{
var justa = a as Just<A>;
if (justa == null)
return new Nothing<V>();
var justb = func(justa.Value) as Just<B>;
if (justb == null)
return new Nothing<V>();
return new Just<V>(s(justa.Value, justb.Value));
}
public static IMaybe<int> Div(this int numerator, int denominator)
{
return denominator == 0
? (IMaybe<int>)new Nothing<int>()
: new Just<int>(numerator / denominator);
}
public static IMaybe<double> DivDouble(int numerator)
{
return new Just<double>(numerator / 4.0);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task2
{
class Program
{
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.Write("Введите первую строку str1: ");
string str1 = Console.ReadLine();
Console.Write("Введите слово:");
string str2 = Console.ReadLine();
char[] a = str1.ToCharArray();
char[] b = str2.ToCharArray();
for (int i = 0; i < str1.Length; i++)
{
Console.Write(a[i]);
for (int j = 0; j < str2.Length; j++)
{
if (a[i] == b[j])
{
Console.Write(b[j]);
j = str2.Length;
}
}
}
Console.ReadKey();
}
}
}
|
using UnityEngine;
using UnityAtoms.BaseAtoms;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Base class for all `MonoHook`s of type `Collision`.
/// </summary>
[EditorIcon("atom-icon-delicate")]
public abstract class CollisionHook : MonoHook<
CollisionEvent,
Collision,
CollisionEventReference,
GameObjectGameObjectFunction>
{
/// <summary>
/// Event including a GameObject reference.
/// </summary>
public CollisionGameObjectEvent EventWithGameObject
{
get => _eventWithGameObjectReference != null ? _eventWithGameObjectReference.GetEvent<CollisionGameObjectEvent>() : null;
set
{
if(_eventWithGameObjectReference != null)
{
_eventWithGameObjectReference.SetEvent<CollisionGameObjectEvent>(value);
}
}
}
[SerializeField]
private CollisionGameObjectEventReference _eventWithGameObjectReference = default(CollisionGameObjectEventReference);
protected override void RaiseWithGameObject(Collision value, GameObject gameObject)
{
if(EventWithGameObject)
{
EventWithGameObject.Raise(new CollisionGameObject() { Collision = value, GameObject = gameObject });
}
}
}
}
|
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace Sideris.SiderisServer
{
internal class ByteString
{
private byte[] _bytes;
private int _offset;
private int _length;
public ByteString(byte[] bytes, int offset, int length)
{
_bytes = bytes;
_offset = offset;
_length = length;
}
public byte[] Bytes
{
get
{
return _bytes;
}
}
public bool IsEmpty
{
get
{
return (_bytes == null || _length == 0);
}
}
public int Length
{
get
{
return _length;
}
}
public int Offset
{
get
{
return _offset;
}
}
public byte this[int index]
{
get
{
return _bytes[_offset + index];
}
}
public String GetString()
{
return GetString(Encoding.UTF8);
}
public String GetString(Encoding enc)
{
if(IsEmpty)
return String.Empty;
return enc.GetString(_bytes, _offset, _length);
}
public byte[] GetBytes()
{
byte[] bytes = new byte[_length];
if(_length > 0)
Buffer.BlockCopy(_bytes, _offset, bytes, 0, _length);
return bytes;
}
public int IndexOf(char ch)
{
return IndexOf(ch, 0);
}
public int IndexOf(char ch, int offset)
{
for(int i = offset; i < _length; i++)
{
if(this[i] == (byte) ch)
return i;
}
return -1;
}
public ByteString Substring(int offset)
{
return Substring(offset, _length - offset);
}
public ByteString Substring(int offset, int len)
{
return new ByteString(_bytes, _offset + offset, len);
}
public ByteString[] Split(char sep)
{
List<ByteString> list = new List<ByteString>();
int pos = 0;
while(pos < _length)
{
int i = IndexOf(sep, pos);
if(i < 0)
break;
list.Add(Substring(pos, i - pos));
pos = i + 1;
while(this[pos] == (byte) sep && pos < _length)
pos++;
}
if(pos < _length)
list.Add(Substring(pos));
return list.ToArray();
}
}
}
|
using System;
using System.Collections.Generic;
namespace DFC.ServiceTaxonomy.GraphSync.Interfaces
{
public interface INode : IEntity, IEquatable<INode>
{
/// <summary>
/// Gets the lables of the node.
/// </summary>
IReadOnlyList<string> Labels { get; }
}
}
|
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using OpenOracle.Services;
namespace OpenOracle.Tests
{
[TestFixture]
public class ConfigTests
{
#region Test Helpers
private static Config BuildConfig(
ITomlService tomlService = null)
{
return new Config(tomlService ?? MockTomlService());
}
private static ITomlService MockTomlService(
Dictionary<string, object> dictionary = null)
{
var toml = Mock.Of<ITomlService>();
Mock.Get(toml)
.Setup(t => t.GetSettingsFromFile(It.IsAny<string>()))
.Returns(dictionary ?? new Dictionary<string, object>());
return toml;
}
#endregion
#region Constructor Tests
[Test]
public void GivenAllParameters_WhenConstructingConfig_ThenNoExceptionIsThrown()
{
Assert.That(() => new Config(new TomlService()),
Throws.Nothing);
}
[Test]
public void GivenNullTomlService_WhenConstructingConfig_ThenAnExceptionIsThrown()
{
Assert.That(() => new Config(null),
Throws.Exception.TypeOf<ArgumentNullException>().And.Message.Contains("tomlService"));
}
#endregion
#region Config Tests
[Test]
public void GivenNothing_WhenPopulating_ThenTomlServiceGetSettingsFromFileIsCalledOnce()
{
ITomlService toml = MockTomlService();
Config config = BuildConfig(tomlService: toml);
config.Populate();
Mock.Get(toml)
.Verify(t => t.GetSettingsFromFile(It.IsAny<string>()), Times.Once);
}
[Test]
public void GivenNothing_WhenPopulating_ThenTomlServiceGetSettingsFromFileIsCalledWithCorrectParameters()
{
ITomlService toml = MockTomlService();
Config config = BuildConfig(tomlService: toml);
config.Populate();
Mock.Get(toml)
.Verify(t => t.GetSettingsFromFile(Config.CONFIG_FILE_PATH));
}
[Test]
public void GivenIncorrectKey_WhenGettingSetting_ThenAnErrorOccurs()
{
var dictionary = new Dictionary<string, object> {{"key", "value"}};
ITomlService toml = MockTomlService(dictionary: dictionary);
Config config = BuildConfig(tomlService: toml);
config.Populate();
Assert.That(() => config.GetSetting("notkey"),
Throws.TypeOf<ArgumentException>().And.Message.Contains("key"));
}
[Test]
public void GivenMatchingKey_WhenGettingSetting_ThenCorrectValueIsReturned()
{
const string MATCHING_KEY = "key2";
const string CORRECT_VALUE = "value2";
var dictionary = new Dictionary<string, object>
{
{"key1", "value"},
{MATCHING_KEY, CORRECT_VALUE}
};
ITomlService toml = MockTomlService(dictionary: dictionary);
Config config = BuildConfig(tomlService: toml);
config.Populate();
dynamic value = config.GetSetting(MATCHING_KEY);
Assert.That(() => value, Is.EqualTo(CORRECT_VALUE));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ECS.Legacy
{
public class FakeWindow : IWindow
{
public int OpenWindowCount { get; private set; }
public int CloseWindowCount { get; private set; }
public void Open()
{
OpenWindowCount++;
}
public void Close()
{
CloseWindowCount++;
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
using Amazon.Lambda.Core;
namespace Pobs.MobileNotifications.NotificationsApp
{
public class Function
{
public void FunctionHandler(ILambdaContext context)
{
var webConnectionString = DecodeEnvVar("HonestQWeb_ConnectionString").Result;
var notificationsConnectionString = DecodeEnvVar("HonestQNotifications_ConnectionString").Result;
var notificationRunner = new NotificationsRunner(webConnectionString, notificationsConnectionString, context.Logger.LogLine);
Task.WaitAll(notificationRunner.RunAsync());
}
// Decrypt code should run once and variables stored outside of the
// function handler so that these are decrypted once per container
private static async Task<string> DecodeEnvVar(string envVarName)
{
// Retrieve env var text
var encryptedBase64Text = Environment.GetEnvironmentVariable(envVarName);
// Convert base64-encoded text to bytes
var encryptedBytes = Convert.FromBase64String(encryptedBase64Text);
// Construct client
using (var client = new AmazonKeyManagementServiceClient())
{
// Construct request
var decryptRequest = new DecryptRequest
{
CiphertextBlob = new MemoryStream(encryptedBytes),
};
// Call KMS to decrypt data
var response = await client.DecryptAsync(decryptRequest);
using (var plaintextStream = response.Plaintext)
{
// Get decrypted bytes
var plaintextBytes = plaintextStream.ToArray();
// Convert decrypted bytes to ASCII text
var plaintext = Encoding.UTF8.GetString(plaintextBytes);
return plaintext;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComLib.Test
{
public class TestClass
{
public string TestName { get; set; }
public int TestInt { get; set; }
public DateTime TestDate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using Quark.Attributes;
using Quark.Buffs;
using Quark.Contexts;
using Quark.Effects;
using Quark.Spells;
using Quark.Utilities;
using UnityEngine;
using Attribute = Quark.Attributes.Attribute;
// ReSharper disable ParameterHidesMember
namespace Quark
{
public class Character : Targetable
{
AttributeCollection _attributes;
List<ICastContext> _casting;
BuffContainer _regularBuffs;
BuffContainer _hiddenBuffs;
ItemCollection _inventory;
ConditionCollection<ICastContext> _interruptConditions;
/// <summary>
/// This property stores whether this Character is suspended or not.
/// </summary>
public bool IsSuspended { get; private set; }
/// <summary>
/// This method suspends this Character, practically disabling it.
/// </summary>
public virtual void Suspend()
{
IsSuspended = true;
}
/// <summary>
/// This method continues this Character if it was suspended.
/// </summary>
public virtual void Continue()
{
IsSuspended = false;
}
void Awake()
{
IsTargetable = true;
Tags = new DynamicTags();
_inventory = new ItemCollection(this);
_attributes = QuarkMain.GetInstance().Configuration.DefaultAttributes.DeepCopy();
_attributes.SetCarrier(this);
_regularBuffs = new BuffContainer(this);
_hiddenBuffs = new BuffContainer(this);
_casting = new List<ICastContext>();
_interruptConditions = QuarkMain.GetInstance().Configuration.DefaultInterruption.DeepCopy();
Context = new Context(this);
_attributes.StatManipulated += delegate(Character source, Stat stat, float change)
{
Logger.Debug("Character::HandleStatManipulation");
OnStatManipulated(stat, change);
};
_regularBuffs.BuffDetached += delegate(Character source, IBuff buff) { OnBuffDetached(buff); };
_hiddenBuffs.BuffDetached += delegate(Character source, IBuff buff) { OnBuffDetached(buff); };
Configure();
}
/// <summary>
/// These effects are applied when this Character is instantiated.
/// </summary>
protected virtual EffectCollection<IContext> ConfigurationEffects
{
get
{
return new EffectCollection<IContext>();
}
}
/// <summary>
/// These effects are applied when the GameObject this Character belongs is destroyed.
/// </summary>
protected virtual EffectCollection<IContext> DestructionEffects
{
get
{
return new EffectCollection<IContext>();
}
}
/// <summary>
/// Configure this Character.
/// </summary>
protected virtual void Configure()
{
ConfigurationEffects.Run(this, Context);
}
void OnDestroy()
{
Destruction();
OnCharacterDestruction();
_inventory.Dispose();
_inventory = null;
_attributes.Dispose();
_attributes = null;
_regularBuffs.Dispose();
_regularBuffs = null;
_hiddenBuffs.Dispose();
_hiddenBuffs = null;
List<ICastContext> casts = _casting;
_casting.Clear();
_casting = null;
foreach (ICastContext cast in casts)
{
cast.Interrupt();
cast.Clear();
}
_interruptConditions.Dispose();
_interruptConditions = null;
}
/// <summary>
/// Handle the destruction of this character
/// </summary>
protected virtual void Destruction()
{
DestructionEffects.Run(this, Context);
}
#if DEBUG
public Character()
{
Logger.GC("Character::ctor");
}
#endif
#if DEBUG
~Character()
{
Logger.GC("Character::dtor");
}
#endif
/// <summary>
/// This property stores the Context of this Character.
/// </summary>
public IContext Context { get; private set; }
/// <summary>
/// Gets the <see cref="Attributes.Attribute"/> belonging to this Character with the given tag
/// </summary>
/// <param name="tag">Tag of the attribute</param>
/// <returns>Attribute with the given tag</returns>
public virtual Attribute GetAttribute(string tag)
{
return _attributes.GetAttribute(tag);
}
/// <summary>
/// Gets the <see cref="Stat"/> belonging to this Character with the given tag
/// </summary>
/// <param name="tag">Tag of the stat</param>
/// <returns>Stat with the given tag</returns>
public virtual Stat GetStat(string tag)
{
return _attributes.GetStat(tag);
}
/// <summary>
/// Returns a read-only collection of the casts this Character is casting
/// </summary>
public IList<ICastContext> Casts
{
get
{
return _casting.AsReadOnly();
}
}
/// <summary>
/// This property determines whether this Character is casting currently.
/// </summary>
public bool HasCast
{
get { return _casting.Count > 0; }
}
/// <summary>
/// Determines whether the given <see cref="Spell"/> can be casted by this Character.
/// </summary>
/// <param name="spell"></param>
/// <returns>Boolean representing whether this Character can cast the given Spell or not.</returns>
public virtual bool CanCast(Spell spell)
{
return !HasCast && !IsSuspended;
}
/// <summary>
/// Add the given <see cref="Cast"/> context to this character.
/// </summary>
/// <param name="cast">A <see cref="Cast"/> context.</param>
public void AddCast(ICastContext cast)
{
if (CanCast(cast.Spell))
{
_casting.Add(cast);
}
}
/// <summary>
/// Removes the given <see cref="Cast"/> context from this character.
/// </summary>
/// <param name="cast"></param>
public void ClearCast(ICastContext cast)
{
if (_casting != null)
_casting.Remove(cast);
}
public void AddItem(Item item)
{
_inventory.AddItemRecursive(item);
}
public void RemoveItem(Item item)
{
_inventory.Remove(item);
}
public bool HasItem(Item item)
{
return _inventory.Has(item);
}
public bool EquippedItem(Item item)
{
return _inventory.Equipped(item);
}
public IList<Item> EquippedItems
{
get { return _inventory.Items(); }
}
public void AttachBuff(IBuff buff)
{
if (buff.Hidden)
_hiddenBuffs.AttachBuff(buff);
else
_regularBuffs.AttachBuff(buff);
OnBuffAttached(buff);
}
/// <summary>
/// Returns a readonly collection of the Buffs being carried by this Character
/// </summary>
/// <value>The buffs.</value>
public IList<IBuff> Buffs
{
get
{
return _regularBuffs.Buffs;
}
}
/// <summary>
/// If a buff with the given type exists on this Character, it will return the correct instance on the Character, otherwise it will return null.
/// </summary>
/// <returns>The buff instance being carried by this Character.</returns>
/// <param name="buff">Example of the Buff to find. Only types should match.</param>
public IBuff GetBuff(IBuff buff)
{
return _regularBuffs.GetBuff(buff);
}
public IBuff GetBuff<T>() where T : class, IBuff
{
return _regularBuffs.GetBuff<T>();
}
public IBuff GetHidden(IBuff hidden)
{
return _hiddenBuffs.GetBuff(hidden);
}
public void ApplyBases(Dictionary<string, float> bases)
{
_attributes.ApplyBases(bases);
}
public Attribute[] GetAttributes
{
get
{
return _attributes.GetAttributes();
}
}
public ConditionCollection<ICastContext> InterruptConditions
{
get
{
return _interruptConditions;
}
}
void OnBuffAttached(IBuff buff)
{
Messenger<Character, IBuff>.Broadcast("Character.BuffAttached", this, buff);
BuffAttached(this, buff);
}
void OnBuffDetached(IBuff buff)
{
Messenger<Character, IBuff>.Broadcast("Character.BuffDetached", this, buff);
BuffDetached(this, buff);
}
void OnStatManipulated(Stat stat, float change)
{
Logger.Debug("Character::OnStatManipulated");
Messenger<Character, Stat, float>.Broadcast("Character.StatManipulated", this, stat, change);
StatManipulated(this, stat, change);
}
void OnCharacterDestruction()
{
Messenger<Character>.Broadcast("Character.CharacterDestroyed", this);
CharacterDestroyed(this);
}
/// <summary>
/// This event is raised after the Character component is destroyed
/// </summary>
public event CharacterDel CharacterDestroyed = delegate { };
/// <summary>
/// This event is raised when a new Buff is attached to this Character
/// </summary>
public event BuffDel BuffAttached = delegate { };
/// <summary>
/// This event is raised when a Buff is detached from this Character
/// </summary>
public event BuffDel BuffDetached = delegate { };
/// <summary>
/// This event is raised when a Stat of this Character is manipulated
/// </summary>
public event StatDel StatManipulated = delegate { };
/// <summary>
/// This event is raised when this Character is hit by a projectile.
/// Handlers of this event may invalidate the event.
/// </summary>
public event HitValidateDelegate ProjectileHit = delegate(IHitContext hit, out bool result) { result = true; };
/// <summary>
/// This method validates a projectile hit on this Character.
/// </summary>
/// <returns>Whether the hit was valid or not.</returns>
public bool ValidateHit(IHitContext hit)
{
foreach (Delegate del in ProjectileHit.GetInvocationList())
{
bool validation;
HitValidateDelegate validator = del as HitValidateDelegate;
validator(hit, out validation);
if (!validation)
return false;
}
return true;
}
}
}
|
using System.Collections.Generic;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;
using NHibernate.Transform;
using NHibernate.Type;
using Profiling2.Domain.Contracts.Queries.Search;
using Profiling2.Domain.Prf.Careers;
using SharpArch.NHibernate;
namespace Profiling2.Infrastructure.Queries
{
public class RankSearchQuery : NHibernateQuery, IRankSearchQuery
{
public IList<Rank> GetResults(string term)
{
//var qo = Session.QueryOver<Rank>();
//if (!string.IsNullOrEmpty(term))
// return qo.Where(Restrictions.On<Rank>(x => x.RankName).IsLike("%" + term + "%"))
// .OrderBy(x => x.RankName).Asc
// .Take(50)
// .List<Rank>();
//else
// return new List<Rank>();
// Alphabetically ordered with insensitive LIKE
//if (!string.IsNullOrEmpty(term))
// return Session.CreateCriteria<Rank>()
// .Add(Expression.Sql("RankName LIKE ? COLLATE Latin1_general_CI_AI", "%" + term + "%", NHibernateUtil.String))
// .AddOrder(Order.Asc("RankName"))
// .SetMaxResults(50)
// .List<Rank>();
//else
// return new List<Rank>();
// Sorted by Career popularity with insensitive LIKE
if (!string.IsNullOrEmpty(term))
return Session.CreateCriteria<Career>()
.CreateAlias("Rank", "r", JoinType.RightOuterJoin)
.Add(Expression.Sql(@"
RankName LIKE ? COLLATE Latin1_general_CI_AI
OR RankNameFr LIKE ? COLLATE Latin1_general_CI_AI",
new string[] { "%" + term + "%", "%" + term + "%" }, new IType[] { NHibernateUtil.String, NHibernateUtil.String }))
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("r.Id"), "Id")
.Add(Projections.Property("r.RankName"), "RankName")
.Add(Projections.Property("r.RankNameFr"), "RankNameFr")
.Add(Projections.Property("r.Archive"), "Archive")
.Add(Projections.Property("r.Notes"), "Notes")
.Add(Projections.Count("r.Id"))
.Add(Projections.GroupProperty("r.Id"))
.Add(Projections.GroupProperty("r.RankName"))
.Add(Projections.GroupProperty("r.RankNameFr"))
.Add(Projections.GroupProperty("r.Archive"))
.Add(Projections.GroupProperty("r.Notes"))
)
.AddOrder(Order.Desc(Projections.Count("r.Id")))
.SetMaxResults(50)
.SetResultTransformer(Transformers.AliasToBean<Rank>())
.List<Rank>();
else
return new List<Rank>();
}
}
}
|
using System;
class Solution {
public int Grocery_Store(int []A)
{
int n=A.Length;
int size=0;
int result=0;
for(int i=0;i<n;i++)
{
if(A[i]==0)
size+=1;
else
size-=1;
result=Math.Max(result,-size);
}
return result;
}
public static void Main()
{
Solution s=new Solution();
int []A={1,0,1,0,0};
int []B={1,1,0,0,0,1,1,1};
int []C={0,0,0,0,0};
int []D={1,1,1,1,1};
Console.WriteLine(s.Grocery_Store(A));
Console.WriteLine(s.Grocery_Store(B));
Console.WriteLine(s.Grocery_Store(C));
Console.WriteLine(s.Grocery_Store(D));
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PatientsRegistry.Domain.Repositories
{
public interface IPatientsRepository
{
Task<IEnumerable<Patient>> GetAllAsync();
Task<Patient> FindPatientAsync(Guid id);
Task SavePatientAsync(Patient patient);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebAPITest.Data;
using WebAPITest.Models;
using WebAPITest.Services;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace WebAPITest.Controllers
{
[Route("api/[controller]")]
public class ProductsController : Controller
{
IProduct _productRepository;
public ProductsController(IProduct productRepository)
{
_productRepository = productRepository;
}
// GET: api/values
[HttpGet]
public IEnumerable<Product> Get()
{
return _productRepository.Get();
}
// GET api/values/5
[HttpGet("{id}")]
public Product Get(int id)
{
return _productRepository.Get(id);
}
// POST api/values
[HttpPost]
public void Post([FromBody]Product product)
{
_productRepository.Post(product);
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]Product product)
{
_productRepository.Put(id,product);
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
_productRepository.Delete(id);
}
}
}
|
using PiDataAdayProje.Models.Entities;
using PiDataAdayProje.ProjectContext;
using PiDataAdayProje.Repositories.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PiDataAdayProje.Repositories.Concrete
{
public class IsYeriRepository : IIsyeriRepository
{
private readonly ApplicationDbContext _context;
public IsYeriRepository(ApplicationDbContext context)
{
_context = context;
}
public IQueryable<Isyeri> Isyeriler => _context.Isyeriler;
public Isyeri GetById(Guid id) => _context.Isyeriler.Find(id);
public bool IsyeriEkle(Isyeri isyeri)
{
_context.Isyeriler.Add(isyeri);
return _context.SaveChanges() > 0;
}
public bool IsyeriGuncelle(Isyeri isyeri)
{
_context.Isyeriler.Update(isyeri);
return _context.SaveChanges() > 0;
}
public bool IsyeriSil(Guid id)
{
_context.Isyeriler.Remove(GetById(id));
return _context.SaveChanges() > 0;
}
}
}
|
using System.Collections.Generic;
using System.Web.Mvc;
using CarDealer.App.Security;
using CarDealer.Models.BindingModels.Sale;
using CarDealer.Models.BindingModels.Supplier;
using CarDealer.Models.EntityModels;
using CarDealer.Models.ViewModels;
using CarDealer.Models.ViewModels.Supplier;
using CarDealer.Services;
namespace CarDealer.App.Controllers
{
[RoutePrefix("suppliers")]
public class SuppliersController : Controller
{
private SuppliersService service;
public SuppliersController()
{
this.service = new SuppliersService();
}
[HttpGet]
[Route("{type:regex(local|importers)?}")]
public ActionResult All(string type)
{
var cookie = this.Request.Cookies.Get("sessionId");
if (cookie != null && !AuthenticationManager.IsAuthenticated(cookie.Value))
{
IEnumerable<AllSupplierVM> viewModel = this.service.GetSuppliersByType(type);
return this.View(viewModel);
}
User user = AuthenticationManager.GetAuthenticatedUser(cookie.Value);
ViewBag.Username = user.Username;
IEnumerable<SupplierImportVM> vm = this.service.GetAllSuppliersByTypeForUsers(type);
return this.View("AllSuppliersForUser", vm);
}
[HttpGet]
[Route("edit/{id:int}")]
public ActionResult Edit(int id)
{
SupplierImportVM viewModel = this.service.GetSupplierById(id);
return this.View(viewModel);
}
[HttpPost]
[Route("edit/{id:int}")]
public ActionResult Edit([Bind(Include = "Id, Name, IsImporter")] SupplierEditBM bind)
{
var cookie = this.Request.Cookies.Get("sessionId");
if (cookie == null || !AuthenticationManager.IsAuthenticated(cookie.Value))
{
return this.RedirectToAction("Login", "Users");
}
if (ModelState.IsValid)
{
User user = AuthenticationManager.GetAuthenticatedUser(cookie.Value);
this.service.EditSupplier(bind, user.Id);
return this.RedirectToAction("All");
}
SupplierImportVM viewModel = this.service.GetSupplierById(bind.Id);
return this.View(viewModel);
}
[HttpGet]
[Route("Add")]
public ActionResult Add()
{
var httpCookie = this.Request.Cookies.Get("sessionId");
if (httpCookie == null || !AuthenticationManager.IsAuthenticated(httpCookie.Value))
{
return this.RedirectToAction("All");
}
return this.View(new SupplierAddVm());
}
[HttpPost]
[Route("Add")]
public ActionResult Add([Bind(Include = "Name, IsImporter")] SupplierAddBM bind)
{
var httpCookie = this.Request.Cookies.Get("sessionId");
if (httpCookie == null || !AuthenticationManager.IsAuthenticated(httpCookie.Value))
{
return this.RedirectToAction("All");
}
if (ModelState.IsValid)
{
User user = AuthenticationManager.GetAuthenticatedUser(httpCookie.Value);
this.service.AddSupplier(bind, user.Id);
return this.RedirectToAction("All");
}
return this.View();
}
[HttpGet]
[Route("delete/{id:int}")]
public ActionResult Delete(int id)
{
var httpCookie = this.Request.Cookies.Get("sessionId");
if (httpCookie == null || !AuthenticationManager.IsAuthenticated(httpCookie.Value))
{
return this.RedirectToAction("All");
}
SupplierDeleteVM viewModel = this.service.GetDeleteSupplier(id);
return this.View(viewModel);
}
[HttpPost]
[Route("delete/{id:int}")]
public ActionResult Delete([Bind(Include = "Id")] SupplierDeleteBM bind)
{
var httpCookie = this.Request.Cookies.Get("sessionId");
if (httpCookie == null || !AuthenticationManager.IsAuthenticated(httpCookie.Value))
{
return this.RedirectToAction("All");
}
if (!this.ModelState.IsValid)
{
SupplierDeleteVM viewModel = this.service.GetDeleteSupplier(bind.Id);
return this.View(viewModel);
}
User user = AuthenticationManager.GetAuthenticatedUser(httpCookie.Value);
this.service.DeleteSupplier(bind.Id, user.Id);
return this.RedirectToAction("All");
}
}
} |
using VesApp.CustomRender;
using VesApp.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Content;
[assembly: ExportRenderer(typeof(ShortLabel), typeof(ShortLabelRender))]
namespace VesApp.Droid
{
public class ShortLabelRender : LabelRenderer
{
public ShortLabelRender(Context context):base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.SetMaxLines(7);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class SnakeHead : MonoBehaviour
{
[SerializeField] private AudioSource _deathSource;
[SerializeField] private AudioSource _foodSource;
private SnakeMover _mover;
public event UnityAction FooodCollected;
public event UnityAction Died;
private void Awake()
{
_mover = GetComponent<SnakeMover>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.TryGetComponent(out Food food))
{
_foodSource.Play();
_mover.Grow();
food.Die();
FooodCollected?.Invoke();
}
if (collision.TryGetComponent(out SnakeSegment segment))
{
Die();
}
}
public void Die()
{
_deathSource.Play();
Died?.Invoke();
}
}
|
using Cs_Gerencial.Dominio.Entities;
using Cs_Gerencial.Dominio.Interfaces;
using Cs_Gerencial.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Cs_Gerencial.Dominio.Servicos
{
public class ServicoCompraSelo: ServicoBase<CompraSelo>, IServicoCompraSelo
{
private readonly IRepositorioCompraSelo _repositorioCompraSelo;
public ServicoCompraSelo(IRepositorioCompraSelo repositorioCompraSelo)
: base(repositorioCompraSelo)
{
_repositorioCompraSelo = repositorioCompraSelo;
}
public CompraSelo LerArquivoCompraSelo(string caminho)
{
XElement xml = XElement.Load(caminho);
CompraSelo arquivo = null;
foreach (XElement x in xml.Elements())
{
arquivo = new CompraSelo()
{
CompraSeloId = int.Parse(x.Attribute("id").Value),
NomeSolicitante = x.Attribute("SolicitanteNome").Value,
Quantidade = int.Parse(x.Attribute("Quantidade").Value),
DataGeracao = DateTime.Parse(x.Attribute("DataGeracao").Value),
CpfSolicitante = x.Attribute("SolicitanteCpf").Value,
DataPedido = DateTime.Parse(x.Attribute("DataPedido").Value)
};
}
return arquivo;
}
public IEnumerable<CompraSelo> ConsultaPorIdPedido(int idPedido)
{
return _repositorioCompraSelo.ConsultaPorIdPedido(idPedido);
}
}
}
|
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.SignalR;
using Autofac.Integration.WebApi;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Infrastructure;
using Owin;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using web_ioc.Hubs;
using web_ioc.Models;
namespace web_ioc
{
public static class IocConfig
{
private static string _cookiename;
internal static IContainer Container { get; set; }
private static I SetupSession<T, I>(IComponentContext context) where T : I, new() where I : ISessionModel
{
context.TryResolve<ISessionStore>(out var store);
var cookie = HttpContext.Current.Request.Cookies[SessionName]?.Value;
I session;
if (!System.Guid.TryParse(cookie, out var sessionID))
{
session = CreateSession<T, I>(store);
}
else
{
session = store.Contains(sessionID)
? (I)store.Get(sessionID)
: CreateSession<T, I>(store);
}
return session;
}
private static string SessionName
{
get
{
if (string.IsNullOrEmpty(_cookiename))
{
_cookiename = ConfigurationManager.AppSettings["sessionCookieName"];
}
return _cookiename;
}
}
private static I CreateSession<T, I>(ISessionStore store) where T : I, new() where I : ISessionModel
{
var session = new T();
store.Set(session);
if (HttpContext.Current?.Response == null) return default(I);
HttpContext.Current.Response.Cookies.Add(new HttpCookie(SessionName, $"{session.Id}")
{
Secure = HttpContext.Current.Request.IsSecureConnection,
Shareable = false,
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Path = "/"
});
return session;
}
private static void SetupMvc(ContainerBuilder builder)
{
// register all controllers
builder.RegisterControllers(typeof(IocConfig).Assembly).InstancePerRequest();
// OPTIONAL: Register model binders that require DI.
builder.RegisterModelBinders(typeof(IocConfig).Assembly);
builder.RegisterModelBinderProvider();
// OPTIONAL: Register web abstractions like HttpContextBase.
builder.RegisterModule<AutofacWebTypesModule>();
// OPTIONAL: Enable property injection in view pages.
builder.RegisterSource(new ViewRegistrationSource());
// OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider();
}
private static void SetupWebApi(ContainerBuilder builder)
{
// Register all API controller
builder.RegisterApiControllers(typeof(IocConfig).Assembly).InstancePerRequest();
}
private static void SetupHubs(ContainerBuilder builder)
{
// Register your SignalR hubs.
builder.RegisterHubs(typeof(IocConfig).Assembly).ExternallyOwned();
}
private static void RegisterTypes(ContainerBuilder builder)
{
builder.RegisterInstance(GlobalHost.ConnectionManager).As<IConnectionManager>();
// in online we have to register the IsessionModel because all the online Components will use this interface.
// but when we create the session we habe to create it with a GribSession / IGribSession to ensure the
// controllers / services can use the Grib specific parts.
builder.Register(ctx => SetupSession<GribSession, IGribSession>(ctx)).As<ISessionModel>().ExternallyOwned();
// in grib we have to register the IGribSession because all the grib components will use this interface.
builder.Register(ctx => SetupSession<GribSession, IGribSession>(ctx)).As<IGribSession>().ExternallyOwned();
builder.RegisterType<SessionStore>().As<ISessionStore>().SingleInstance();
//Hub does not support InstancePerRequest...
builder.RegisterType<LegendService>().As<ILegendService>().InstancePerLifetimeScope();
builder.RegisterType<GribService>().As<IGribService>().InstancePerLifetimeScope();
}
internal static void SetupContainer(IAppBuilder app)
{
var builder = new ContainerBuilder();
SetupMvc(builder);
SetupWebApi(builder);
SetupHubs(builder);
RegisterTypes(builder);
Container = builder.Build();
DependencyResolver.SetResolver(new Autofac.Integration.Mvc.AutofacDependencyResolver(Container));
var config = GlobalConfiguration.Configuration;
config.DependencyResolver = new AutofacWebApiDependencyResolver(Container);
app.UseAutofacMiddleware(Container);
//app.UseAutofacMvc();
var hubconfig = new HubConfiguration
{
Resolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(Container)
};
GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(Container);
app.MapSignalR("/signalr", hubconfig);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Banco.Contas
{
public class Conta
{
public string Titular { get; private set; }
public int Numero { get; private set; }
public double Saldo { get; private set; }
public DateTime DataDeCriacao { get; private set; }
public Conta(int numero, double saldo, string titular, DateTime data)
{
Titular = titular;
Numero = numero;
Saldo = saldo;
}
public override string ToString()
{
var str = string.Format("Numero: {0}, Saldo: {1}, Titular: {2}, DataCriacao{3}"
, Convert.ToString(Numero), Convert.ToString(Saldo), Titular, DataDeCriacao.ToString("dd/MM/yyyy"));
return str;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.SegmentDigits
{
class FindDigits
{
static void Main()
{
int linesNumber = Console.ReadLine();
string line = string.Empty;
for (int i = 0; i < linesNumber; i++)
{
line = Console.ReadLine();
}
}
}
}
|
using System;
using System.Diagnostics;
using System.Windows;
using System.Threading.Tasks;
using System.Windows.Threading;
using CatalogSearch.ViewModels;
using System.Linq;
namespace CatalogSearch.Commands
{
class NavigateCommand : CommandBase
{
public NavigateCommand(CatalogSearchViewModel viewModel) : base(viewModel) {}
public override bool CanExecute(object parameter)
{
var result = parameter as CatalogSearchResultViewModel;
return result.IsInCurrentRuleApp;
}
public override void Execute(object parameter)
{
var dispatcher = Dispatcher.CurrentDispatcher;
Task.Factory.StartNew(() =>
{
try
{
var result = parameter as CatalogSearchResultViewModel;
dispatcher.BeginInvoke(new Action(() => { ViewModel.PerformNavigate(result.RuleDef ?? result.RuleSetDef); }));
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
MessageBox.Show(ex.ToString());
throw;
}
});
}
public override event EventHandler CanExecuteChanged;
}
} |
using System;
using System.IO;
using System.Windows.Forms;
namespace UseFul.Uteis
{
public static class AbriFormularioDinamicamente
{
/// <summary>
/// Recebe uma string para Abrir o Formulario
/// </summary>
/// <param name="Namespace_FormName">Nome do Namespace.NomeForm Ex: teste.Form1</param>
/// <param name="System_Modal">True = ShowDialog / False = Show</param>
public static void OpenForm(string Namespace_FormName, bool System_Modal)
{
Type t = Type.GetType(Namespace_FormName);
if (t != null)
{
System.Windows.Forms.Form f =
(System.Windows.Forms.Form)Activator.CreateInstance(t);
if (System_Modal)
f.ShowDialog();
else
f.Show();
}
}
/// <summary>
/// Abre um formulário do FoxPro
/// </summary>
/// <param name="executavel">Objeto de referencia do executavel onde se encontra o formulário</param>
/// <param name="comandoExecFox">Comando utilizado dentro do fox para executar o formulário (concatenar os parametros necessários), aspas no inicio e no fim da string</param>
public static void OpenFormFoxPro(ExecutaveisFoxPro executavel, string comandoExecFox)
{
if (!System.IO.File.Exists(executavel.getCaminhoRede()))
{
MessageBox.Show("O caminho '" + executavel.getCaminhoRede() + "' não é válido. Por favor, contate o núcleo de TI.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (!System.IO.File.Exists(executavel.getCaminhoLocal()))
File.Copy(executavel.getCaminhoRede(), executavel.getCaminhoLocal());
else
{
FileInfo rede = new FileInfo(executavel.getCaminhoRede());
FileInfo local = new FileInfo(executavel.getCaminhoLocal());
if (rede.LastWriteTime != local.LastWriteTime)
{
try
{
File.Delete(executavel.getCaminhoLocal());
File.Copy(executavel.getCaminhoRede(), executavel.getCaminhoLocal());
}
catch (Exception)
{
//Caso de algum erro ao deletar ou copiar utiliza a versão atual local
//Catch apenas para não lançar exceção
}
}
}
////string usuario = Globals.Usuario.ToString();
////string senha = Globals.Login;
////string conexao = Globals.Conexao.Equals("ACAD_TESTE") ? "DBTESTE" : Globals.Conexao;
////string parametros = usuario + " " + senha + " " + conexao + " " + comandoExecFox;
////System.Diagnostics.Process process = System.Diagnostics.Process.Start(executavel.getCaminhoLocal(), parametros);
//while (!process.HasExited)
//{
// //http://msdn.microsoft.com/pt-br/library/system.windows.forms.application.doevents.aspx
// Application.DoEvents();
//}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using HTB.Database;
using HTBUtilities;
using HTB.Database.Views;
namespace HTB.v2.intranetx.aktenintprovfix
{
public class ProvisionCalc
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const string ProvType_AG_AktType_ActionType_User = "AG_TYPE_ACTION_USER";
public const string ProvType_AktType_ActionType_User = "USER_TYPE_ACTION";
public const string ProvType_AG_AktType_ActionType = "AG_TYPE_ACTION";
public const string ProvType_AG_User = "AG_USER";
public const string ProvType_ActionType_User = "USER_ACTION";
public const string ProvType_AG_ActionType = "AG_ACTION";
public const string ProvType_AG_AktType = "AG_TYPE";
public const string ProvType_ActionType = "ACTION";
public const int PeriodCode_Range = 0;
public const int PeriodCode_Weekly = 1;
public const int PeriodCode_Monthly = 2;
private readonly ActionRecordList _actionRecordList = new ActionRecordList();
public double GetProvision(double collectedAmount, double balance, int agId, int aktIntTypeId, int userId, int actionTypeId)
{
Log.Debug("1");
_actionRecordList.Add(agId, aktIntTypeId, actionTypeId, userId, DateTime.Now);
string sqlWhere = " WHERE AGAktTypeAktionUserProvAuftraggeberID = " + agId +
" AND AGAktTypeActionUserProvAktTypeIntID = " + aktIntTypeId +
" AND AGAktTypeActionUserProvUserID = " + userId +
" AND AGAktTypeActionUserProvAktAktionTypeID = " + actionTypeId;
string provType = ProvType_AG_AktType_ActionType_User;
Record prov = (tblAuftraggeberAktTypeActionUserProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberAktTypeActionUserProv " + sqlWhere, typeof(tblAuftraggeberAktTypeActionUserProv));
if (prov == null)
{
sqlWhere = " WHERE UserAktTypeAktionProvUserID = " + userId +
" AND UserAktTypeActionProvAktTypeIntID = " + aktIntTypeId +
" AND UserAktTypeActionProvAktAktionTypeID = " + actionTypeId;
prov = (tblUserAktTypeActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblUserAktTypeActionProv " + sqlWhere, typeof(tblUserAktTypeActionProv));
provType = ProvType_AktType_ActionType_User;
}
if (prov == null)
{
sqlWhere = " WHERE AGAktTypeAktionProvAuftraggeberID = " + agId +
" AND AGAktTypeActionProvAktTypeIntID = " + aktIntTypeId +
" AND AGAktTypeActionProvAktAktionTypeID = " + actionTypeId;
prov = (tblAuftraggeberAktTypeActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberAktTypeActionProv " + sqlWhere, typeof(tblAuftraggeberAktTypeActionProv));
provType = ProvType_AG_AktType_ActionType;
}
if (prov == null)
{
sqlWhere = " WHERE AGUserProvAuftraggeberID = " + agId +
" AND AGUserProvUserID = " + userId +
" AND AGUserProvAktAktionTypeID = " + actionTypeId;
prov = (tblAuftraggeberUserProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberUserProv " + sqlWhere, typeof(tblAuftraggeberUserProv));
provType = ProvType_AG_User;
}
if (prov == null)
{
sqlWhere = " WHERE UserAktionProvUserID = " + userId +
" AND UserActionProvAktAktionTypeID = " + actionTypeId;
prov = (tblUserActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblUserActionProv " + sqlWhere, typeof(tblUserActionProv));
provType = ProvType_ActionType_User;
}
if (prov == null)
{
sqlWhere = " WHERE AGAktionProvAuftraggeberID = " + agId +
" AND AGActionProvAktAktionTypeID = " + actionTypeId;
prov = (tblAuftraggeberActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberActionProv " + sqlWhere, typeof(tblAuftraggeberActionProv));
provType = ProvType_AG_ActionType;
}
if (prov == null)
{
sqlWhere = " WHERE AGAktTypeProvAuftraggeberID = " + agId +
" AND AGAktTypeProvAktTypeIntID = " + aktIntTypeId;
prov = (tblAuftraggeberAktTypeProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberAktTypeProv " + sqlWhere, typeof(tblAuftraggeberAktTypeProv));
provType = ProvType_AG_AktType;
}
if (prov == null)
{
sqlWhere = " WHERE AktIntActionTypeID = " + actionTypeId;
prov = (tblAktenIntActionType)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAktenIntActionType " + sqlWhere, typeof(tblAktenIntActionType));
provType = ProvType_ActionType;
}
return GetProvision(collectedAmount, balance, prov, provType);
}
private double GetProvision(double collectedAmount, double balance, Record provRecord, string provType)
{
if (provRecord is tblAuftraggeberAktTypeActionUserProv)
{
var rec = (tblAuftraggeberAktTypeActionUserProv)provRecord;
return GetProvision(collectedAmount, balance, rec.AGAktTypeActionUserProvHonGrpID, rec.AGAktTypeActionUserProvAmount, rec.AGAktTypeActionUserProvAmountForZeroCollection, rec.AGAktTypeActionUserProvPct, provType);
}
if (provRecord is tblUserAktTypeActionProv)
{
var rec = (tblUserAktTypeActionProv)provRecord;
return GetProvision(collectedAmount, balance, rec.UserAktTypeActionProvHonGrpID, rec.UserAktTypeActionProvAmount, rec.UserAktTypeActionProvAmountForZeroCollection, rec.UserAktTypeActionProvPct, provType);
}
if (provRecord is tblAuftraggeberUserProv)
{
var rec = (tblAuftraggeberUserProv)provRecord;
return GetProvision(collectedAmount, balance, rec.AGUserProvHonGrpID, rec.AGUserProvAmount, rec.AGUserProvAmountForZeroCollection, rec.AGUserProvPct, provType);
}
if (provRecord is tblAuftraggeberAktTypeActionProv)
{
var rec = (tblAuftraggeberAktTypeActionProv)provRecord;
return GetProvision(collectedAmount, balance, rec.AGAktTypeActionProvHonGrpID, rec.AGAktTypeActionProvAmount, rec.AGAktTypeActionProvAmountForZeroCollection, rec.AGAktTypeActionProvPct, provType);
}
if (provRecord is tblUserActionProv)
{
var rec = (tblUserActionProv)provRecord;
return GetProvision(collectedAmount, balance, rec.UserActionProvHonGrpID, rec.UserActionProvAmount, rec.UserActionProvAmountForZeroCollection, rec.UserActionProvPct, provType);
}
if (provRecord is tblAuftraggeberActionProv)
{
var rec = (tblAuftraggeberActionProv)provRecord;
return GetProvision(collectedAmount, balance, rec.AGActionProvHonGrpID, rec.AGActionProvAmount, rec.AGActionProvAmountForZeroCollection, rec.AGActionProvPct, provType);
}
if (provRecord is tblAuftraggeberAktTypeProv)
{
var rec = (tblAuftraggeberAktTypeProv)provRecord;
return GetProvision(collectedAmount, balance, rec.AGAktTypeProvProvisionHonGrpID, rec.AGAktTypeProvProvisionAmount, rec.AGAktTypeProvProvisionAmountForZeroCollection, rec.AGAktTypeProvProvisionPct, provType);
}
if (provRecord is tblAktenIntActionType)
{
var rec = (tblAktenIntActionType)provRecord;
return GetProvision(collectedAmount, balance, rec.AktIntActionProvHonGrpID, rec.AktIntActionProvAmount, rec.AktIntActionProvAmountForZeroCollection, rec.AktIntActionProvPct, provType);
}
return 0;
}
private double GetProvision(double collectedAmount, double balance, int honorarGrpId, double amt, double amtForZero, double amtPct, string provType)
{
if (honorarGrpId > 0)
{
return GetHonorar(honorarGrpId, collectedAmount, balance, provType);
}
double ret;
if (HTBUtils.IsZero(collectedAmount))
{
ret = amtForZero;
}
else
{
if (!HTBUtils.IsZero(amtPct))
{
ret = collectedAmount * (amtPct / 100);
}
else
{
ret = amt;
}
}
return ret;
}
private double GetHonorar(int honorarGrpId, double collectedAmount, double balance, string provType)
{
double ret = 0;
if (balance > 0 || collectedAmount > 0)
{
string sqlQuery = "SELECT * FROM qryAktenIntGroupHonorar WHERE AktIntHonGrpID = " + honorarGrpId + " AND AktIntHonFrom <= " + collectedAmount + " AND AktIntHonTo >= " + collectedAmount;
var honorar = (qryAktenIntGroupHonorar)HTBUtils.GetSqlSingleRecord(sqlQuery.Replace(",", "."), typeof(qryAktenIntGroupHonorar));
if (honorar != null)
{
ret = honorar.AktIntHonProvAmount;
if (honorar.AktIntHonProvPct > 0)
{
if (honorar.AktIntHonProvPctOf == 0)
{
ret += (honorar.AktIntHonProvPct / 100) * collectedAmount;
}
else
{
ret += (honorar.AktIntHonProvPct / 100) * balance;
}
}
if (ret > honorar.AktIntHonMaxProvAmount)
{
ret = honorar.AktIntHonMaxProvAmount;
}
}
}
return ret;
}
public double GetPrice(double collectedAmount, double balance, int agId, int aktIntTypeId, int userId, int actionTypeId)
{
Log.Debug("1");
double price = 0;
if (IsActionVoid(actionTypeId))
return 0;
string sqlWhere = " WHERE AGAktTypeAktionUserProvAuftraggeberID = " + agId +
" AND AGAktTypeActionUserProvAktTypeIntID = " + aktIntTypeId +
" AND AGAktTypeActionUserProvUserID = " + userId +
" AND AGAktTypeActionUserProvAktAktionTypeID = " + actionTypeId;
var agAktTypeUserProv = (tblAuftraggeberAktTypeActionUserProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberAktTypeActionUserProv" + sqlWhere, typeof(tblAuftraggeberAktTypeActionUserProv));
if (agAktTypeUserProv != null)
{
if (agAktTypeUserProv.AGAktTypeActionUserProvHonGrpID > 0)
price = GetHonorarPrice(agAktTypeUserProv.AGAktTypeActionUserProvHonGrpID, collectedAmount, balance);
else if (agAktTypeUserProv.AGAktTypeActionUserProvPrice > 0)
price = agAktTypeUserProv.AGAktTypeActionUserProvPrice;
}
if (price == 0)
{
sqlWhere = " WHERE UserAktTypeAktionProvUserID = " + userId +
" AND UserAktTypeActionProvAktTypeIntID = " + aktIntTypeId +
" AND UserAktTypeActionProvAktAktionTypeID = " + actionTypeId;
var userAktTypeProv = (tblUserAktTypeActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblUserAktTypeActionProv " + sqlWhere, typeof(tblUserAktTypeActionProv));
if (userAktTypeProv != null)
{
if (userAktTypeProv.UserAktTypeActionProvHonGrpID > 0)
price = GetHonorarPrice(userAktTypeProv.UserAktTypeActionProvHonGrpID, collectedAmount, balance);
else if (userAktTypeProv.UserAktTypeActionProvPrice > 0)
price = userAktTypeProv.UserAktTypeActionProvPrice;
}
}
if (price == 0)
{
sqlWhere = " WHERE AGAktTypeAktionProvAuftraggeberID = " + agId +
" AND AGAktTypeActionProvAktTypeIntID = " + aktIntTypeId +
" AND AGAktTypeActionProvAktAktionTypeID = " + actionTypeId;
var agAktTypeProv = (tblAuftraggeberAktTypeActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberAktTypeActionProv " + sqlWhere, typeof(tblAuftraggeberAktTypeActionProv));
if (agAktTypeProv != null)
{
if (agAktTypeProv.AGAktTypeActionProvHonGrpID > 0)
price = GetHonorarPrice(agAktTypeProv.AGAktTypeActionProvHonGrpID, collectedAmount, balance);
else if (agAktTypeProv.AGAktTypeActionProvPrice > 0)
price = agAktTypeProv.AGAktTypeActionProvPrice;
}
}
if (price == 0)
{
sqlWhere = " WHERE AGUserProvAuftraggeberID = " + agId +
" AND AGUserProvUserID = " + userId +
" AND AGUserProvAktAktionTypeID = " + actionTypeId;
var agUserProv = (tblAuftraggeberUserProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberUserProv " + sqlWhere, typeof(tblAuftraggeberUserProv));
if (agUserProv != null)
{
if (agUserProv.AGUserProvHonGrpID > 0)
price = GetHonorarPrice(agUserProv.AGUserProvHonGrpID, collectedAmount, balance);
else if (agUserProv.AGUserProvPrice > 0)
price = agUserProv.AGUserProvPrice;
}
}
if (price == 0)
{
sqlWhere = " WHERE UserAktionProvUserID = " + userId +
" AND UserActionProvAktAktionTypeID = " + actionTypeId;
var userActionProv = (tblUserActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblUserActionProv " + sqlWhere, typeof(tblUserActionProv));
if (userActionProv != null)
{
if (userActionProv.UserActionProvHonGrpID > 0)
price = GetHonorarPrice(userActionProv.UserActionProvHonGrpID, collectedAmount, balance);
else if (userActionProv.UserActionProvPrice > 0)
price = userActionProv.UserActionProvPrice;
}
}
if (price == 0)
{
sqlWhere = " WHERE AGAktionProvAuftraggeberID = " + agId +
" AND AGActionProvAktAktionTypeID = " + actionTypeId;
var agActionProv = (tblAuftraggeberActionProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberActionProv " + sqlWhere, typeof(tblAuftraggeberActionProv));
if (agActionProv != null)
{
if (agActionProv.AGActionProvHonGrpID > 0)
price = GetHonorarPrice(agActionProv.AGActionProvHonGrpID, collectedAmount, balance);
else if (agActionProv.AGActionProvPrice > 0)
price = agActionProv.AGActionProvPrice;
}
}
if (price == 0)
{
sqlWhere = " WHERE AGAktTypeProvAuftraggeberID = " + agId +
" AND AGAktTypeProvAktTypeIntID = " + aktIntTypeId;
var agType = (tblAuftraggeberAktTypeProv)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeberAktTypeProv " + sqlWhere, typeof(tblAuftraggeberAktTypeProv));
if (agType != null)
{
if (agType.AGAktTypeProvProvisionHonGrpID > 0)
price = GetHonorarPrice(agType.AGAktTypeProvProvisionHonGrpID, collectedAmount, balance);
else if (agType.AGAktTypeProvProvisionPrice > 0)
price = agType.AGAktTypeProvProvisionPrice;
}
}
if (price == 0)
{
sqlWhere = " WHERE AktIntActionTypeID = " + actionTypeId;
var action = (tblAktenIntActionType)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAktenIntActionType " + sqlWhere, typeof(tblAktenIntActionType));
if (action != null)
{
if (action.AktIntActionProvHonGrpID > 0)
price = GetHonorarPrice(action.AktIntActionProvHonGrpID, collectedAmount, balance);
else if (action.AktIntActionProvPrice > 0)
price = action.AktIntActionProvPrice;
}
}
if (price == 0)
{
sqlWhere = " WHERE AuftraggeberID = " + agId;
var ag = (tblAuftraggeber)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAuftraggeber " + sqlWhere, typeof(tblAuftraggeber));
if (ag != null)
{
if (ag.AuftraggeberInterventionsKost > 0)
price = ag.AuftraggeberInterventionsKost;
}
}
return price;
}
private double GetHonorarPrice(int honorarGrpId, double collectedAmount, double balance)
{
double ret = 0;
string sqlQuery = "SELECT * FROM qryAktenIntGroupHonorar WHERE AktIntHonGrpID = " + honorarGrpId + " AND AktIntHonFrom <= " + collectedAmount + " AND AktIntHonTo >= " + collectedAmount;
var honorar = (qryAktenIntGroupHonorar)HTBUtils.GetSqlSingleRecord(sqlQuery.Replace(",", "."), typeof(qryAktenIntGroupHonorar));
if (honorar != null)
{
ret = honorar.AktIntHonPrice;
if (honorar.AktIntHonPct > 0)
{
if (honorar.AktIntHonPctOf == 0)
{
ret += (honorar.AktIntHonPct / 100) * collectedAmount;
}
else
{
ret += (honorar.AktIntHonPct / 100) * balance;
}
}
if (ret > honorar.AktIntHonMaxPrice)
{
ret = honorar.AktIntHonMaxPrice;
}
}
return ret;
}
private bool IsActionVoid(int actionTypeId)
{
string sqlWhere = " WHERE AktIntActionTypeID = " + actionTypeId;
var action = (tblAktenIntActionType)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAktenIntActionType " + sqlWhere, typeof(tblAktenIntActionType));
return action.AktIntActionIsVoid;
}
}
public class ActionRecord
{
public int UserId { get; set; }
public int AgId { get; set; }
public int AktType { get; set; }
public int ActionType { get; set; }
public DateTime ActionDate { get; set; }
public ActionRecord(int agId, int aktType, int actionType, int userId, DateTime actionDate)
{
UserId = userId;
AgId = agId;
AktType = aktType;
ActionType = actionType;
ActionDate = actionDate;
}
private void InitDefault()
{
UserId = -1;
AgId = -1;
AktType = -1;
ActionType = -1;
ActionDate = HTBUtils.DefaultDate;
}
}
public class ActionRecordList : List<ActionRecord>
{
public void Add(int agId, int aktType, int actionType, int userId, DateTime actionDate)
{
base.Add(new ActionRecord(agId, aktType, actionType, userId, actionDate));
}
public int GetCount (int agId, int aktType, int actionType, int userId, DateTime actionDate, string provType, int periodCode)
{
var list = new ActionRecordList();
switch (provType)
{
case ProvisionCalc.ProvType_AG_AktType_ActionType_User:
list = FindBy_Ag_AktType_ActionType_User(agId, aktType, actionType, userId);
break;
case ProvisionCalc.ProvType_AktType_ActionType_User:
list = FindBy_AktType_ActionType_User(aktType, actionType, userId);
break;
case ProvisionCalc.ProvType_AG_AktType_ActionType:
list = FindBy_Ag_AktType_ActionType(agId, aktType, actionType);
break;
case ProvisionCalc.ProvType_AG_User:
list = FindBy_Ag_User(agId, userId);
break;
case ProvisionCalc.ProvType_ActionType_User:
list = FindBy_ActionType_User(actionType, userId);
break;
case ProvisionCalc.ProvType_AG_ActionType:
list = FindBy_Ag_ActionType(agId, actionType);
break;
case ProvisionCalc.ProvType_AG_AktType:
list = FindBy_Ag_AktType(agId, aktType);
break;
case ProvisionCalc.ProvType_ActionType:
list = FindBy_ActionType(actionType);
break;
}
switch (periodCode)
{
case ProvisionCalc.PeriodCode_Range:
return list.Count;
case ProvisionCalc.PeriodCode_Weekly:
return list.Count;
case ProvisionCalc.PeriodCode_Monthly:
return list.Count;
}
return 0;
}
public ActionRecordList FindBy_Ag_AktType_ActionType_User(int agId, int aktType, int actionTypeId, int userId)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.AgId == agId && actionRecord.AktType == aktType && actionRecord.ActionType == actionTypeId && actionRecord.UserId == userId));
return list;
}
public ActionRecordList FindBy_AktType_ActionType_User(int aktType, int actionTypeId, int userId)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.AktType == aktType && actionRecord.ActionType == actionTypeId && actionRecord.UserId == userId));
return list;
}
public ActionRecordList FindBy_Ag_AktType_ActionType(int agId, int aktType, int actionTypeId)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.AgId == agId && actionRecord.AktType == aktType && actionRecord.ActionType == actionTypeId));
return list;
}
public ActionRecordList FindBy_Ag_User(int agId, int userId)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.AgId == agId && actionRecord.UserId == userId));
return list;
}
public ActionRecordList FindBy_ActionType_User(int actionTypeId, int userId)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.ActionType == actionTypeId && actionRecord.UserId == userId));
return list;
}
public ActionRecordList FindBy_Ag_ActionType(int agId, int actionTypeId)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.AgId == agId && actionRecord.ActionType == actionTypeId));
return list;
}
public ActionRecordList FindBy_Ag_AktType(int agId, int aktType)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.AgId == agId && actionRecord.AktType == aktType));
return list;
}
public ActionRecordList FindBy_ActionType(int actionTypeId)
{
var list = new ActionRecordList();
list.AddRange(this.Where(actionRecord => actionRecord.ActionType == actionTypeId));
return list;
}
}
} |
using UnityEngine;
namespace Thesis {
public class SinglePeakRoof : Roof
{
public SinglePeakRoof (BuildingMesh parent)
: base(parent)
{
height = 1f;
width = 0.2f;
boundaries = new Vector3[5];
for (int i = 0; i < 4; ++i)
boundaries[i] = parentMesh.roofBase.boundaries[i + 4] +
width * parentMesh.faces[i].normal +
width * parentMesh.faces[(i + 3) % 4].normal;
FindMeshOrigin(boundaries[0], boundaries[2],
boundaries[1], boundaries[3]);
boundaries[4] = new Vector3(meshOrigin.x,
boundaries[0].y + height,
meshOrigin.z);
}
public override void FindVertices()
{
vertices = new Vector3[boundaries.Length * 5];
for (int i = 0; i < 5; ++i)
System.Array.Copy(boundaries, 0, vertices, i * boundaries.Length, boundaries.Length);
}
public override void FindTriangles()
{
triangles = new int[18];
int i = 0;
triangles[i++] = 0;
triangles[i++] = 1;
triangles[i++] = 4;
// +5
triangles[i++] = 6;
triangles[i++] = 7;
triangles[i++] = 9;
// +10
triangles[i++] = 12;
triangles[i++] = 13;
triangles[i++] = 14;
// +15
triangles[i++] = 18;
triangles[i++] = 15;
triangles[i++] = 19;
triangles[i++] = 20;
triangles[i++] = 23;
triangles[i++] = 22;
triangles[i++] = 20;
triangles[i++] = 22;
triangles[i++] = 21;
}
public override void Draw()
{
base.Draw();
var uvs = new Vector2[mesh.vertices.Length];
float _wdiv = material.mainTexture.width / 128f;
float _hdiv = material.mainTexture.height / 128f;
float _dist01 = (boundaries[0] - boundaries[1]).magnitude;
float _dist12 = (boundaries[1] - boundaries[2]).magnitude;
float htimes = _dist01 / _wdiv;
float vtimes = Mathf.Sqrt(Mathf.Pow(_dist12 / 2, 2) +
Mathf.Pow(height, 2)) / _hdiv;
uvs[1] = new Vector2(0f, 0f);
uvs[4] = new Vector2(htimes / 2, vtimes);
uvs[0] = new Vector2(htimes, 0f);
uvs[13] = new Vector2(0f, 0f);
uvs[14] = new Vector2(htimes / 2, vtimes);
uvs[12] = new Vector2(htimes, 0f);
htimes = _dist12 / _wdiv;
vtimes = Mathf.Sqrt(Mathf.Pow(_dist01 / 2, 2) +
Mathf.Pow(height, 2)) / _hdiv;
uvs[7] = new Vector2(0f, 0f);
uvs[9] = new Vector2(htimes / 2, vtimes);
uvs[6] = new Vector2(htimes, 0f);
uvs[15] = new Vector2(0f, 0f);
uvs[19] = new Vector2(htimes / 2, vtimes);
uvs[18] = new Vector2(htimes, 0f);
mesh.uv = uvs;
}
}
} |
void test
{
update1
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
// 1. 将其附加到读/写的sprite图像上
// 2. 将绘图层设置为在光线投射中使用
// 3. 将绘图层设置为在光线投射中使用
// 4. 按住鼠标左键画出这个纹理!
public class ScratchMask : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[Tooltip("笔刷形状精灵,只识别透明度为1的像素点")]
[SerializeField]
Sprite brushSprite;
[Tooltip("笔刷alpha,只有超过此值的才被渲染")]
float brushFilterAlpha;
[Tooltip("笔刷颜色")]
Color brushColor = new Color(255f, 255f, 255f, 0f);
[Tooltip("笔刷宽度")]
[SerializeField]
int brushWidth = 20;
[Tooltip("奖励物品")]
[SerializeField]
Image rewardImage;
[Tooltip("遮挡图片,在Unity的文件编辑器中必须有读/写权限")]
Image maskImage;
Sprite maskSprite;
Texture2D maskTeture;
int maskWidth;
int maskHeight;
Vector2Int lastPos;
Color[] originColors;
Color32[] curMaskColors;
bool isPointIn = false;
//笔刷
List<Vector2Int> brushPixelPosList = new List<Vector2Int>();
//奖品区域
Rect rewardPixelRect;
//奖品像素数量
long rewardPixelCount;
//修改过的像素位置
HashSet<long> changedPos = new HashSet<long>();
void Awake()
{
maskImage = GetComponent<Image>();
maskSprite = maskImage.sprite;
maskTeture = maskSprite.texture;
// 保存图片所有颜色
originColors = maskTeture.GetPixels(0, 0, maskTeture.width, maskTeture.height);
curMaskColors = maskTeture.GetPixels32();
maskWidth = (int)maskSprite.rect.width;
maskHeight = (int)maskSprite.rect.height;
}
void Start()
{
InitBrushPositions();
InitRewardPositions();
}
public void OnPointerDown(PointerEventData eventData)
{
if (eventData.pointerCurrentRaycast.gameObject == gameObject)
{
isPointIn = true;
}
}
public void OnPointerUp(PointerEventData eventData)
{
isPointIn = false;
lastPos = new Vector2Int(0, 0);
}
void Update()
{
if (isPointIn)
{
Vector3 screenPos = Input.mousePosition;
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(screenPos);
Vector3 localPos = transform.InverseTransformPoint(worldPoint);
ChangeColorAtPoint(localPos);
}
}
private void OnDestroy()
{
ResetColor();
}
/// <summary>
/// 初始化笔刷位置点
/// </summary>
private void InitBrushPositions()
{
Color[] brushColors = brushSprite.texture.GetPixels(0, 0, brushSprite.texture.width, brushSprite.texture.height);
int textureWidth = brushSprite.texture.width;
int textureHeight = brushSprite.texture.height;
int widthIndex = 0;
int heightIndex = 0;
foreach (var item in brushColors)
{
if (item.a > brushFilterAlpha)
{
brushPixelPosList.Add(new Vector2Int()
{
x = widthIndex - textureWidth / 2,
y = heightIndex - textureHeight / 2,
});
}
if ((widthIndex + 1) % textureWidth == 0)
{
widthIndex = 0;
heightIndex++;
}
else
{
widthIndex++;
}
}
}
/// <summary>
/// 初始化奖品位置
/// </summary>
void InitRewardPositions()
{
RectTransform rewardRtf = rewardImage.rectTransform;
Vector2 pivot = rewardRtf.pivot;
Vector2 offsetDis = rewardRtf.localPosition - transform.localPosition;
Vector2Int pixelPos = CalculatePixelPositionByOffset(offsetDis);
rewardPixelRect = rewardRtf.rect;
rewardPixelRect.position = pixelPos + new Vector2(-pivot.x * rewardPixelRect.width, -pivot.y * rewardPixelRect.height);
rewardPixelCount = (long)(rewardPixelRect.width * rewardPixelRect.height);
}
/// <summary>
/// 修改相对Mask位置的颜色
/// </summary>
/// <param name="localPos"></param>
public void ChangeColorAtPoint(Vector2 localPos)
{
Vector2Int pixelPos = CalculatePixelPositionByOffset(localPos);
curMaskColors = maskTeture.GetPixels32();
if (lastPos == Vector2.zero)
{
// 如果这是我们第一次拖动这个图像,只需在鼠标位置上着色像素
MarkPixelsToColour(pixelPos);
}
else
{
// 从我们上次更新呼叫的位置上的颜色
ColourBetween(lastPos, pixelPos);
}
ApplyMarkedPixelChanges();
lastPos = pixelPos;
}
/// <summary>
/// 通过偏移计算坐标
/// </summary>
/// <param name="localPos"></param>
/// <returns></returns>
private Vector2Int CalculatePixelPositionByOffset(Vector2 localPos)
{
// 需要把我们的坐标居中
float centered_x = localPos.x + maskWidth / 2;
float centered_y = localPos.y + maskHeight / 2;
// 将鼠标移动到最近的像素点
return new Vector2Int(Mathf.RoundToInt(centered_x), Mathf.RoundToInt(centered_y));
}
// 从起始点一直到终点,将像素的颜色设置为直线,以确保中间的所有内容都是彩色的
public void ColourBetween(Vector2 startPos, Vector2 endPos)
{
// 从开始到结束的距离
float distance = Vector2.Distance(startPos, endPos);
Vector2 curPos = startPos;
// 计算在开始点和结束点之间插入多少次,基于上次更新以来的时间量
float lerpSteps = brushWidth / distance;
for (float lerp = 0; lerp <= 1; lerp += lerpSteps)
{
curPos = Vector2.Lerp(startPos, endPos, lerp);
MarkPixelsToColour(curPos);
}
}
public void MarkPixelsToColour(Vector2 center_pixel)
{
// 算出我们需要在每个方向上着色多少个像素(x和y)
int center_x = (int)center_pixel.x;
int center_y = (int)center_pixel.y;
foreach (var item in brushPixelPosList)
{
MarkPixelToChange(center_x + item.x, center_y + item.y, brushColor);
}
}
/// <summary>
/// 在对应位置着色
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="color"></param>
public void MarkPixelToChange(int x, int y, Color color)
{
// 需要将x和y坐标转换为数组的平面坐标
long array_pos = y * (int)maskSprite.rect.width + x;
// 检查这是否是一个有效的位置
if (array_pos > curMaskColors.Length || array_pos < 0)
{
//Debug.Log("un pos");
return;
}
//记录已经着色的位置
if (x > rewardPixelRect.xMin && x < rewardPixelRect.xMax && y > rewardPixelRect.yMin && y < rewardPixelRect.yMax)
{
changedPos.Add(array_pos);
}
curMaskColors[array_pos] = color;
}
/// <summary>
/// 应用改变
/// </summary>
public void ApplyMarkedPixelChanges()
{
if (changedPos.Count > rewardPixelCount * 0.5)
{
OpenMask();
}
maskTeture.SetPixels32(curMaskColors);
maskTeture.Apply();
}
private void OpenMask()
{
maskImage.color = new Color(1, 1, 1, 0);
}
//还原被擦除的图片颜色
private void ResetColor()
{
maskTeture.SetPixels(originColors);
maskTeture.Apply();
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using Xabe.FFMpeg.Enums;
namespace Xabe.FFMpeg
{
/// <summary>
/// Information about media file
/// </summary>
public class VideoInfo
{
private readonly FileInfo _file;
private FFMpeg _ffmpeg;
/// <summary>
/// Fires when conversion progress changed
/// </summary>
public ConversionHandler OnConversionProgress;
/// <summary>
/// Get VideoInfo from file
/// </summary>
/// <param name="fileInfo">File</param>
public VideoInfo(FileInfo fileInfo)
{
fileInfo.Refresh();
if(!fileInfo.Exists)
throw new ArgumentException($"Input file {fileInfo.FullName} does not exist!");
_file = fileInfo;
new FFProbe().ProbeDetails(this);
}
/// <summary>
/// Get VideoInfo from file
/// </summary>
/// <param name="path">Path to file</param>
public VideoInfo(string path): this(new FileInfo(path))
{
}
private FFMpeg FFmpeg
{
get
{
if(_ffmpeg != null &&
_ffmpeg.IsRunning)
throw new InvalidOperationException(
"Operation on this file is in progress.");
return _ffmpeg ?? (_ffmpeg = new FFMpeg());
}
}
/// <summary>
/// duration of video
/// </summary>
public TimeSpan Duration { get; internal set; }
/// <summary>
/// Audio format
/// </summary>
public string AudioFormat { get; internal set; }
/// <summary>
/// Video format
/// </summary>
public string VideoFormat { get; internal set; }
/// <summary>
/// Screen ratio
/// </summary>
public string Ratio { get; internal set; }
/// <summary>
/// Frame rate
/// </summary>
public double FrameRate { get; internal set; }
/// <summary>
/// Height
/// </summary>
public int Height { get; internal set; }
/// <summary>
/// Width
/// </summary>
public int Width { get; internal set; }
/// <summary>
/// size
/// </summary>
public double Size { get; internal set; }
/// <summary>
/// filename
/// </summary>
public string Name => _file.Name;
/// <summary>
/// Fullname (Path + filename)
/// </summary>
public string FullName => _file.FullName;
/// <summary>
/// Extension
/// </summary>
public string Extension => _file.Extension;
/// <summary>
/// Is readonly
/// </summary>
public bool IsReadOnly => _file.IsReadOnly;
/// <summary>
/// Gets a value indicating whether a file exists
/// </summary>
public bool Exists => _file.Exists;
/// <summary>
/// Creation time
/// </summary>
public DateTime CreationTime => _file.CreationTime;
/// <summary>
/// Directory
/// </summary>
public DirectoryInfo Directory => _file.Directory;
/// <summary>
/// Get the ffmpeg process status
/// </summary>
public bool IsRunning => FFmpeg.IsRunning;
/// <summary>
/// Convert file to specified format. Output file will be in the same directory as source with changed extension.
/// </summary>
/// <param name="type">Destination format</param>
/// <param name="speed">Conversion speed</param>
/// <param name="size">Dimension</param>
/// <param name="audioQuality">Audio quality</param>
/// <param name="multithread">Use multithread</param>
/// <param name="deleteSource"></param>
/// <returns>Output VideoInfo</returns>
public VideoInfo ConvertTo(VideoType type, Speed speed = Speed.Medium, VideoSize size = VideoSize.Original,
AudioQuality audioQuality = AudioQuality.Normal, bool multithread = true, bool deleteSource = false)
{
string outputPath = FullName.Replace(Extension, $".{type.ToString() .ToLower()}");
var output = new FileInfo(outputPath);
return ConvertTo(type, output, speed, size, audioQuality, multithread, deleteSource);
}
/// <summary>
/// Create VideoInfo from file
/// </summary>
/// <param name="fileInfo">File</param>
/// <returns>VideoInfo</returns>
public static VideoInfo FromFile(FileInfo fileInfo)
{
return new VideoInfo(fileInfo);
}
/// <summary>
/// Get formated info about video
/// </summary>
/// <returns>Formated info about vidoe</returns>
public override string ToString()
{
return "Video Path : " + FullName + Environment.NewLine +
"Video Root : " + Directory.FullName + Environment.NewLine +
"Video Name: " + Name + Environment.NewLine +
"Video Extension : " + Extension + Environment.NewLine +
"Video duration : " + Duration + Environment.NewLine +
"Audio format : " + AudioFormat + Environment.NewLine +
"Video format : " + VideoFormat + Environment.NewLine +
"Aspect Ratio : " + Ratio + Environment.NewLine +
"Framerate : " + FrameRate + "fps" + Environment.NewLine +
"Resolution : " + Width + "x" + Height + Environment.NewLine +
"size : " + Size + " MB";
}
/// <summary>
/// Convert file to specified format
/// </summary>
/// <param name="type">Destination format</param>
/// <param name="output">Destination file</param>
/// <param name="speed">Conversion speed</param>
/// <param name="size">Dimension</param>
/// <param name="audioQuality">Audio quality</param>
/// <param name="multithread">Use multithread</param>
/// <param name="deleteSource"></param>
/// <returns>Output VideoInfo</returns>
public VideoInfo ConvertTo(VideoType type, FileInfo output, Speed speed = Speed.SuperFast,
VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false,
bool deleteSource = false)
{
bool success;
FFmpeg.OnProgress += OnConversionProgress;
switch(type)
{
case VideoType.Mp4:
success = FFmpeg.ToMp4(this, output, speed, size, audioQuality, multithread);
break;
case VideoType.Ogv:
success = FFmpeg.ToOgv(this, output, size, audioQuality, multithread);
break;
case VideoType.WebM:
success = FFmpeg.ToWebM(this, output, size, audioQuality);
break;
case VideoType.Ts:
success = FFmpeg.ToTs(this, output);
break;
default:
throw new ArgumentException("VideoType not recognized");
}
if(!success)
throw new OperationCanceledException("The conversion process could not be completed.");
if(deleteSource)
if(Exists)
_file.Delete();
FFmpeg.OnProgress -= OnConversionProgress;
return FromFile(output);
}
/// <summary>
/// Extract video from file
/// </summary>
/// <param name="output">Output audio stream</param>
/// <returns>Conversion result</returns>
public bool ExtractVideo(FileInfo output)
{
return FFmpeg.ExtractVideo(this, output);
}
/// <summary>
/// Extract audio from file
/// </summary>
/// <param name="output">Output video stream</param>
/// <returns>Conversion result</returns>
public bool ExtractAudio(FileInfo output)
{
return FFmpeg.ExtractAudio(this, output);
}
/// <summary>
/// Add audio to file
/// </summary>
/// <param name="audio">Audio file</param>
/// <param name="output">Output file</param>
/// <returns>Conversion result</returns>
public bool AddAudio(FileInfo audio, FileInfo output)
{
return FFmpeg.AddAudio(this, audio, output);
}
/// <summary>
/// Get snapshot of video
/// </summary>
/// <param name="size">Dimension of snapshot</param>
/// <param name="captureTime"></param>
/// <returns>Snapshot</returns>
public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null)
{
var output = new FileInfo($"{Environment.TickCount}.png");
bool success = FFmpeg.Snapshot(this, output, size, captureTime);
if(!success)
throw new OperationCanceledException("Could not take snapshot!");
output.Refresh();
Bitmap result;
using(Image bmp = Image.FromFile(output.FullName))
{
using(var ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Png);
result = new Bitmap(ms);
}
}
if(output.Exists)
output.Delete();
return result;
}
/// <summary>
/// Saves snapshot of video
/// </summary>
/// <param name="output">Output file</param>
/// <param name="size">Dimension of snapshot</param>
/// <param name="captureTime"></param>
/// <returns>Snapshot</returns>
public Bitmap Snapshot(FileInfo output, Size? size = null, TimeSpan? captureTime = null)
{
bool success = FFmpeg.Snapshot(this, output, size, captureTime);
if(!success)
throw new OperationCanceledException("Could not take snapshot!");
Bitmap result;
using(Image bmp = Image.FromFile(Path.ChangeExtension(output.FullName, ".png")))
{
result = (Bitmap) bmp.Clone();
}
return result;
}
/// <summary>
/// Concat multiple videos
/// </summary>
/// <param name="output">Concatenated videos</param>
/// <param name="videos">Videos to add</param>
/// <returns>Conversion result</returns>
public bool JoinWith(FileInfo output, params VideoInfo[] videos)
{
List<VideoInfo> queuedVideos = videos.ToList();
queuedVideos.Insert(0, this);
return FFmpeg.Join(output, queuedVideos.ToArray());
}
/// <summary>
/// Delete file
/// </summary>
private void Delete()
{
_file.Delete();
}
/// <summary>
/// Stop conversion
/// </summary>
public void CancelOperation()
{
FFmpeg.Stop();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EssentialTools.Models
{
public interface IDiscountHelper
{
decimal ApplyDiscount(decimal total);
}
public class DefaultDiscountHelper : IDiscountHelper
{
private decimal discountSize;
public DefaultDiscountHelper(decimal discountSize)
{
this.discountSize = discountSize;
}
public decimal ApplyDiscount(decimal total)
{
return (total - (discountSize / 100m * total));
}
}
} |
using MODEL;
using MODEL.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IBLLService
{
public partial interface IFW_PERMISSION_MANAGER : IBaseBLLService<FW_PERMISSION>
{
/// <summary>
/// 根据条件获取权限信息
/// </summary>
/// <param name="request">请求</param>
/// <param name="Count">总个数</param>
/// <returns></returns>
IEnumerable<VIEW_FW_PERMISSION> GetPermission();
}
}
|
using PaperbanknotesServer.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PaperbanknotesServer.Database
{
public interface ICarRepository
{
void Add(Car item);
IEnumerable<Car> GetAll();
Car Find(long key);
void Remove(long key);
void Update(Car item);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseWindow : MonoBehaviour, IWindow
{
protected bool isActive;
[HideInInspector] public bool isBound = false;
protected CanvasGroup canvas => GetComponent<CanvasGroup>();
public string currentWindowName;
void Start()
{
WindowsManager.OnWindowOpened += Open;
WindowsManager.OnWindowClosed += Close;
isBound = true;
}
public void Close(string windowName)
{
if (windowName == currentWindowName)
{
canvas.alpha = 0;
canvas.blocksRaycasts = false;
isActive = false;
}
}
public void Open(string windowName)
{
if (windowName == currentWindowName)
{
canvas.alpha = 1;
canvas.blocksRaycasts = true;
StartCoroutine(ActivityDelay());
}
}
IEnumerator ActivityDelay()
{
yield return new WaitForSeconds(0.15f);
isActive = true;
}
void OnDestroy()
{
WindowsManager.OnWindowOpened -= Open;
WindowsManager.OnWindowClosed -= Close;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace csvBeolvasás
{
class Beolvas
{
public Beolvas(string fajlnev)
{
if (fajlnev.Contains("txt"))
{
string[] fajl = File.ReadAllLines(fajlnev);
}
else if (fajlnev.Contains("csv"))
{
string fajl = File.ReadAllText(fajlnev);
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Hakaima;
public class ResourceManager : MonoBehaviour
{
public const int SPRITE_MULTI_TYPE = 100;
public const int SPRITE_MULTI_COMPASS = 10;
[SerializeField]
private Sprite spriteTerrainSoil;
[SerializeField]
private Sprite spriteTerrainGrass;
[SerializeField]
private Sprite spriteTerrainMuddy;
[SerializeField]
private Sprite spriteTerrainPavement;
[SerializeField]
private Sprite spriteTerrainIce;
[SerializeField]
private Sprite spriteTerrainRiver0;
[SerializeField]
private Sprite spriteTerrainRiver1;
[SerializeField]
private Sprite spriteTerrainBridgeVertical;
[SerializeField]
private Sprite spriteTerrainBridgeHorizontal;
[HideInInspector]
public Dictionary<int, Sprite> spriteTerrainList;
[SerializeField]
private Sprite spriteObstacleTree;
[SerializeField]
private Sprite spriteObstacleStone;
[SerializeField]
private Sprite spriteObstacleTomb;
[SerializeField]
private Sprite spriteObstacleTombCollapse0;
[SerializeField]
private Sprite spriteObstacleTombCollapse1;
[SerializeField]
private Sprite spriteObstacleTombCollapseEnd;
[SerializeField]
private Sprite spriteObstacleTombPiece0;
[SerializeField]
private Sprite spriteObstacleTombPiece1;
[SerializeField]
private Sprite spriteObstacleTombPieceEnd;
[SerializeField]
private Sprite spriteObstacleCartRight;
[SerializeField]
private Sprite spriteObstacleCartLeft;
[SerializeField]
private Sprite spriteObstacleWell;
[SerializeField]
private Sprite spriteObstacleBale;
[SerializeField]
private Sprite spriteObstacleBathtub0;
[SerializeField]
private Sprite spriteObstacleBathtub1;
[SerializeField]
private Sprite spriteObstacleBathtub2;
[SerializeField]
private Sprite spriteObstacleBathtubCollapse0;
[SerializeField]
private Sprite spriteObstacleBathtubCollapse1;
[SerializeField]
private Sprite spriteObstacleBathtubCollapseEnd;
[SerializeField]
private Sprite spriteObstacleStockpile;
[SerializeField]
private Sprite spriteObstacleStockpileCollapse0;
[SerializeField]
private Sprite spriteObstacleStockpileCollapse1;
[SerializeField]
private Sprite spriteObstacleStockpileCollapseEnd;
[SerializeField]
private Sprite spriteObstacleSignboard;
[SerializeField]
private Sprite spriteObstacleTower0;
[SerializeField]
private Sprite spriteObstacleTower1;
[SerializeField]
private Sprite spriteObstacleTower2;
[SerializeField]
private Sprite spriteObstacleTower3;
[SerializeField]
private Sprite spriteObstacleTower4;
[SerializeField]
private Sprite spriteObstacleFallenTree;
[SerializeField]
private Sprite spriteObstacleStump;
[SerializeField]
private Sprite spriteObstacleBucket;
[SerializeField]
private Sprite spriteObstacleLantern;
[SerializeField]
private Sprite spriteObstacleStupaFence;
[SerializeField]
private Sprite spriteObstacleStupa;
[SerializeField]
private Sprite spriteObstacleLargeTreeRight;
[SerializeField]
private Sprite spriteObstacleLargeTreeLeft;
[SerializeField]
private Sprite spriteObstacleRubble;
[SerializeField]
private Sprite spriteObstacleRubbleOff;
[SerializeField]
private Sprite spriteObstaclePicket;
[HideInInspector]
public Dictionary<int, Sprite> spriteObstacleList;
[SerializeField]
private Sprite spriteHoleMiddle1;
[SerializeField]
private Sprite spriteHoleMiddle2;
[SerializeField]
private Sprite spriteHoleMiddle3;
[SerializeField]
private Sprite spriteHoleComplete;
[HideInInspector]
public Dictionary<int, Sprite> spriteHoleList;
[HideInInspector]
public Dictionary<int, Sprite> spritePlayerList;
[HideInInspector]
public Sprite spriteUpperPlayer;
[HideInInspector]
public Sprite spritePlayerWeapon;
[HideInInspector]
public Dictionary<int, Sprite> spriteEnemyList;
[HideInInspector]
public Sprite spriteEnemyWeapon;
[SerializeField]
public Sprite spriteWeapon;
[SerializeField]
private Sprite spriteItemSandal;
[SerializeField]
private Sprite spriteItemHoe;
[SerializeField]
private Sprite spriteItemStone;
[SerializeField]
private Sprite spriteItemAmulet;
[SerializeField]
private Sprite spriteItemParasol;
[SerializeField]
private Sprite spriteItemTicket;
[HideInInspector]
public Dictionary<int, Sprite> spriteItemList;
[SerializeField]
private Sprite spriteBonus0;
[SerializeField]
private Sprite spriteBonus1;
[SerializeField]
private Sprite spriteBonus2;
[SerializeField]
private Sprite spriteBonus3;
[SerializeField]
private Sprite spriteBonus4;
[SerializeField]
private Sprite spriteBonus5;
[SerializeField]
private Sprite spriteBonus6;
[SerializeField]
public Dictionary<int, Sprite> spriteBonusList;
[SerializeField]
public Sprite spriteUpperItemFrame;
[SerializeField]
public Sprite spriteUpperItemFrameSelect;
[SerializeField]
public Material materialReversal;
[SerializeField]
public Material materialReversalFall;
[SerializeField]
public Material materialReversalHide;
private static ResourceManager instance;
public static ResourceManager Instance {
get {
instance = instance ?? GameObject.FindObjectOfType<ResourceManager> ();
return instance;
}
}
private void Awake ()
{
spriteTerrainList = new Dictionary<int, Sprite> ();
spriteObstacleList = new Dictionary<int, Sprite> ();
spriteHoleList = new Dictionary<int, Sprite> ();
spritePlayerList = new Dictionary<int, Sprite> ();
spriteEnemyList = new Dictionary<int, Sprite> ();
spriteItemList = new Dictionary<int, Sprite> ();
spriteBonusList = new Dictionary<int, Sprite> ();
}
public void SetClear ()
{
spriteTerrainList.Clear ();
spriteObstacleList.Clear ();
spriteHoleList.Clear ();
spritePlayerList.Clear ();
spriteEnemyList.Clear ();
spriteItemList.Clear ();
spriteBonusList.Clear ();
}
public void SetTerrian ()
{
spriteTerrainList = new Dictionary<int, Sprite> (){
{(int)Hakaima.Terrain.Type.Soil * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainSoil },
{(int)Hakaima.Terrain.Type.Grass * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainGrass },
{(int)Hakaima.Terrain.Type.Muddy * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainMuddy },
{(int)Hakaima.Terrain.Type.Pavement * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainPavement },
{(int)Hakaima.Terrain.Type.Ice * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainIce },
{(int)Hakaima.Terrain.Type.River * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainRiver0 },
{(int)Hakaima.Terrain.Type.River * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_1, spriteTerrainRiver1 },
{(int)Hakaima.Terrain.Type.BridgeVertical * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainBridgeVertical },
{(int)Hakaima.Terrain.Type.BridgeHorizontal * SPRITE_MULTI_TYPE + Hakaima.Terrain.IMAGE_0, spriteTerrainBridgeHorizontal },
};
}
public void SetObstacle ()
{
spriteObstacleList = new Dictionary<int, Sprite> (){
{(int)Hakaima.Obstacle.Type.Tree * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTree },
{(int)Hakaima.Obstacle.Type.Stone * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleStone },
{(int)Hakaima.Obstacle.Type.Tomb * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTomb },
{(int)Hakaima.Obstacle.Type.TombCollapse * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTombCollapse0 },
{(int)Hakaima.Obstacle.Type.TombCollapse * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_1, spriteObstacleTombCollapse1 },
{(int)Hakaima.Obstacle.Type.TombCollapseEnd * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTombCollapseEnd },
{(int)Hakaima.Obstacle.Type.TombPiece * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTombPiece0 },
{(int)Hakaima.Obstacle.Type.TombPiece * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_1, spriteObstacleTombPiece1 },
{(int)Hakaima.Obstacle.Type.TombPieceEnd * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTombPieceEnd },
{(int)Hakaima.Obstacle.Type.CartRight * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleCartRight },
{(int)Hakaima.Obstacle.Type.CartLeft * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleCartLeft },
{(int)Hakaima.Obstacle.Type.Well * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleWell },
{(int)Hakaima.Obstacle.Type.Bale * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleBale },
{(int)Hakaima.Obstacle.Type.Bathtub * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleBathtub0 },
{(int)Hakaima.Obstacle.Type.Bathtub * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_1, spriteObstacleBathtub1 },
{(int)Hakaima.Obstacle.Type.Bathtub * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_2, spriteObstacleBathtub2 },
{(int)Hakaima.Obstacle.Type.BathtubCollapse * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleBathtubCollapse0 },
{(int)Hakaima.Obstacle.Type.BathtubCollapse * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_1, spriteObstacleBathtubCollapse1 },
{(int)Hakaima.Obstacle.Type.BathtubCollapseEnd * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleBathtubCollapseEnd },
{(int)Hakaima.Obstacle.Type.Stockpile * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleStockpile },
{(int)Hakaima.Obstacle.Type.StockpileCollapse * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleStockpileCollapse0 },
{(int)Hakaima.Obstacle.Type.StockpileCollapse * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_1, spriteObstacleStockpileCollapse1 },
{(int)Hakaima.Obstacle.Type.StockpileCollapseEnd * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleStockpileCollapseEnd },
{(int)Hakaima.Obstacle.Type.Signboard * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleSignboard },
{(int)Hakaima.Obstacle.Type.Tower * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTower0 },
{(int)Hakaima.Obstacle.Type.Tower * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_1, spriteObstacleTower1 },
{(int)Hakaima.Obstacle.Type.Tower * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_2, spriteObstacleTower2 },
{(int)Hakaima.Obstacle.Type.Tower * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_3, spriteObstacleTower3 },
{(int)Hakaima.Obstacle.Type.Tower * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_4, spriteObstacleTower4 },
{(int)Hakaima.Obstacle.Type.FallenTree * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleFallenTree },
{(int)Hakaima.Obstacle.Type.Stump * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleStump },
{(int)Hakaima.Obstacle.Type.Bucket * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleBucket },
{(int)Hakaima.Obstacle.Type.Lantern * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleLantern },
{(int)Hakaima.Obstacle.Type.StupaFence * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleStupaFence },
{(int)Hakaima.Obstacle.Type.Stupa * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleStupa },
{(int)Hakaima.Obstacle.Type.LargeTreeRight * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleLargeTreeRight },
{(int)Hakaima.Obstacle.Type.LargeTreeLeft * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleLargeTreeLeft },
{(int)Hakaima.Obstacle.Type.Rubble * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleRubble },
{(int)Hakaima.Obstacle.Type.RubbleOff * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleRubbleOff },
{(int)Hakaima.Obstacle.Type.Picket * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstaclePicket },
{(int)Hakaima.Obstacle.Type.FallTombPiece * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTombPiece0 },
{(int)Hakaima.Obstacle.Type.FallTombPiece * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_1, spriteObstacleTombPiece1 },
{(int)Hakaima.Obstacle.Type.FallTombPieceEnd * SPRITE_MULTI_TYPE + Hakaima.Obstacle.IMAGE_0, spriteObstacleTombPieceEnd },
};
}
public void SetHole ()
{
spriteHoleList = new Dictionary<int, Sprite> (){
{Hakaima.Hole.IMAGE_MIDDLE_1, spriteHoleMiddle1 },
{Hakaima.Hole.IMAGE_MIDDLE_2, spriteHoleMiddle2 },
{Hakaima.Hole.IMAGE_MIDDLE_3, spriteHoleMiddle3 },
{Hakaima.Hole.IMAGE_COMPLETE, spriteHoleComplete },
};
}
public void SetItem ()
{
spriteItemList = new Dictionary<int, Sprite> (){
{(int)Item.Type.Sandal * SPRITE_MULTI_TYPE, spriteItemSandal },
{(int)Item.Type.Hoe * SPRITE_MULTI_TYPE, spriteItemHoe },
{(int)Item.Type.Stone * SPRITE_MULTI_TYPE, spriteItemStone },
{(int)Item.Type.Amulet * SPRITE_MULTI_TYPE, spriteItemAmulet },
{(int)Item.Type.Parasol * SPRITE_MULTI_TYPE, spriteItemParasol },
{(int)Item.Type.Ticket * SPRITE_MULTI_TYPE, spriteItemTicket },
};
}
public void SetBonus ()
{
spriteBonusList = new Dictionary<int, Sprite> (){
{(int)Bonus.Type.Bonus0 * SPRITE_MULTI_TYPE, spriteBonus0 },
{(int)Bonus.Type.Bonus1 * SPRITE_MULTI_TYPE, spriteBonus1 },
{(int)Bonus.Type.Bonus2 * SPRITE_MULTI_TYPE, spriteBonus2 },
{(int)Bonus.Type.Bonus3 * SPRITE_MULTI_TYPE, spriteBonus3 },
{(int)Bonus.Type.Bonus4 * SPRITE_MULTI_TYPE, spriteBonus4 },
{(int)Bonus.Type.Bonus5 * SPRITE_MULTI_TYPE, spriteBonus5 },
{(int)Bonus.Type.Bonus6 * SPRITE_MULTI_TYPE, spriteBonus6 },
};
}
public void SetAllEnemy ()
{
spriteEnemyList = new Dictionary<int, Sprite> ();
SetEnemy (Enemy.Type.Person);
SetEnemy (Enemy.Type.Ghost);
SetEnemy (Enemy.Type.Soul);
SetEnemy (Enemy.Type.Skeleton);
SetEnemy (Enemy.Type.Mummy);
SetEnemy (Enemy.Type.Shadowman);
SetEnemy (Enemy.Type.Golem);
SetEnemy (Enemy.Type.Goblin);
SetEnemy (Enemy.Type.Parasol);
SetEnemy (Enemy.Type.Kappa);
SetEnemy (Enemy.Type.Tengu);
}
public void SetPlayer (int charaId)
{
spritePlayerList = new Dictionary<int, Sprite> (){
{0 + (int)Player.Compass.Right * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_right_0", charaId))},
{0 + (int)Player.Compass.Right * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_right_1", charaId))},
{0 + (int)Player.Compass.Right * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_right_2", charaId))},
{0 + (int)Player.Compass.Left * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_left_0", charaId))},
{0 + (int)Player.Compass.Left * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_left_1", charaId))},
{0 + (int)Player.Compass.Left * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_left_2", charaId))},
{0 + (int)Player.Compass.Top * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_top_0", charaId))},
{0 + (int)Player.Compass.Top * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_top_1", charaId))},
{0 + (int)Player.Compass.Top * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_top_2", charaId))},
{0 + (int)Player.Compass.Bottom * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_bottom_0", charaId))},
{0 + (int)Player.Compass.Bottom * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_bottom_1", charaId))},
{0 + (int)Player.Compass.Bottom * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_bottom_2", charaId))},
{SPRITE_MULTI_TYPE + (int)Player.Compass.Right * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_right_0", charaId))},
{SPRITE_MULTI_TYPE + (int)Player.Compass.Right * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_right_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Right * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_right_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Left * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_left_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Left * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_left_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Left * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_left_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Top * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_top_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Top * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_top_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Top * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_top_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Bottom * SPRITE_MULTI_COMPASS + Player.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_bottom_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Bottom * SPRITE_MULTI_COMPASS + Player.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_bottom_0", charaId)) },
{SPRITE_MULTI_TYPE + (int)Player.Compass.Bottom * SPRITE_MULTI_COMPASS + Player.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/player{0}_spin_bottom_0", charaId)) },
};
spriteUpperPlayer = Resources.Load<Sprite> (string.Format ("Textures/upper_player{0}", charaId));
spritePlayerWeapon = Resources.Load<Sprite> (string.Format ("Textures/player{0}_weapon", charaId));
}
public void SetEnemy (Enemy.Type enemyType)
{
if (spriteEnemyList.ContainsKey ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Right * SPRITE_MULTI_COMPASS + Enemy.IMAGE_0))
return;
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Right * SPRITE_MULTI_COMPASS + Enemy.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_right_0", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Right * SPRITE_MULTI_COMPASS + Enemy.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_right_1", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Right * SPRITE_MULTI_COMPASS + Enemy.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_right_2", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Left * SPRITE_MULTI_COMPASS + Enemy.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_left_0", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Left * SPRITE_MULTI_COMPASS + Enemy.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_left_1", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Left * SPRITE_MULTI_COMPASS + Enemy.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_left_2", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Top * SPRITE_MULTI_COMPASS + Enemy.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_top_0", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Top * SPRITE_MULTI_COMPASS + Enemy.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_top_1", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Top * SPRITE_MULTI_COMPASS + Enemy.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_top_2", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Bottom * SPRITE_MULTI_COMPASS + Enemy.IMAGE_0, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_bottom_0", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Bottom * SPRITE_MULTI_COMPASS + Enemy.IMAGE_1, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_bottom_1", enemyType.ToString ().ToLower ())));
spriteEnemyList.Add ((int)enemyType * SPRITE_MULTI_TYPE + (int)Enemy.Compass.Bottom * SPRITE_MULTI_COMPASS + Enemy.IMAGE_2, Resources.Load<Sprite> (string.Format ("Textures/enemy_{0}_bottom_2", enemyType.ToString ().ToLower ())));
if (enemyType == Enemy.Type.Tengu)
spriteEnemyWeapon = Resources.Load<Sprite> ("Textures/enemy_weapon");
}
public Sprite GetContinuePlayerSprite (int charaId)
{
return Resources.Load<Sprite> (string.Format ("Textures/continue_player{0}", charaId));
}
}
|
/*
* Author: Generated Code
* Date Created: 01.04.2011
* Description: Represents a row in the tblDokument table
*/
using System.Data.SqlClient;
using System.Data;
using System;
namespace HTB.Database
{
public class tblDokument : Record
{
#region Property Declaration
[MappingAttribute(FieldType = MappingAttribute.FIELD_TYPE_ID, FieldAutoNumber = true)]
public int DokID { get; set; }
public int DokDokType { get; set; }
public int DokCreator { get; set; }
public string DokCaption { get; set; }
public int DokLevel { get; set; }
public int DokStatus { get; set; }
public DateTime DokCreationTimeStamp { get; set; }
public int DokKlient { get; set; }
public int DokGegner { get; set; }
public string DokAttachment { get; set; }
public int DokPublish { get; set; }
public int DokAbteilung { get; set; }
public int DokAuftraggeber { get; set; }
public int DokProjekt { get; set; }
public int DokAEAkt { get; set; }
public int DokInkAkt { get; set; }
public int DokIntAkt { get; set; }
// public int DokAutoAkt { get; set; }
public DateTime DokChangeDate { get; set; }
public int DokChangeUser { get; set; }
public string DokText { get; set; }
[MappingAttribute(FieldType = MappingAttribute.NO_DB_SAVE)]
public long DokTimestamp { get; set; }
public bool DokSourceIsIPad { get; set; }
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace reviews.Controllers
{
public class Review
{
public int Grade { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Product { get; set; }
}
public class ReviewsStore
{
public static List<Review> Reviews = new List<Review>()
{
new Review()
{
Grade = 5,
Title = "Great movie",
Description = "Great actor playing Thanos",
Product = 1
}
};
}
[ApiController]
public class DefaultController : ControllerBase
{
[Route("/")]
public List<Review> GetReviews()
{
return ReviewsStore.Reviews;
}
}
} |
//Name: UIRotateAroundParent.cs
//Project: Spectral: The Silicon Domain
//Author(s) Conor Hughes - conormpkhughes@yahoo.com
//Description: Simple script that rotates a UI element around its parent object.
using UnityEngine;
using System.Collections;
public class UIRotateAroundParent : MonoBehaviour {
private float rotateSpeed = 120; //the speed of the rotation
public bool rotateRight = true; //if true, rotate right. Otherwise rotate left.
// Update is called once per frame
void Update () {
if(rotateRight) transform.RotateAround(transform.parent.position, Vector3.forward, rotateSpeed * 0.01f);
else transform.RotateAround(transform.parent.position, -Vector3.forward, rotateSpeed * 0.01f);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Application.DTO;
namespace EBS.Application
{
public interface IPurchaseContractFacade
{
void Create(CreatePurchaseContract model);
void Edit(EditPurchaseContract model);
void Delete(int id, int editBy, string editor, string reason);
void Submit(int id, int editBy, string editor);
void Audit(int id, int editBy, string editor);
}
}
|
using System;
using System.Runtime.InteropServices;
namespace IronAHK.Rusty.Linux.X11.Events
{
[StructLayout(LayoutKind.Sequential)]
internal struct XEventPad
{
internal IntPtr pad0;
internal IntPtr pad1;
internal IntPtr pad2;
internal IntPtr pad3;
internal IntPtr pad4;
internal IntPtr pad5;
internal IntPtr pad6;
internal IntPtr pad7;
internal IntPtr pad8;
internal IntPtr pad9;
internal IntPtr pad10;
internal IntPtr pad11;
internal IntPtr pad12;
internal IntPtr pad13;
internal IntPtr pad14;
internal IntPtr pad15;
internal IntPtr pad16;
internal IntPtr pad17;
internal IntPtr pad18;
internal IntPtr pad19;
internal IntPtr pad20;
internal IntPtr pad21;
internal IntPtr pad22;
internal IntPtr pad23;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Comp;
using Model;
using System.Data;
using System.Data.SqlClient;
using Dapper;
namespace DAL
{
/// <summary>
/// 库存盘点
/// </summary>
public class D_StockInventory
{
/// <summary>
/// 查询条件
/// </summary>
private string GetSqlWhere(E_StockInventory model)
{
//查询语句
StringBuilder strWhere = new StringBuilder();
if (model.operationid > 0)
{
strWhere.AddWhere("operationid=@operationid");
}
if (model.classid > 0)
{
strWhere.AddWhere("classid=@classid");
}
if (!string.IsNullOrEmpty(model.pname))
{
strWhere.AddWhere($"pname like '%{model.pname}%'");
}
if (!string.IsNullOrEmpty(model.pnameall))
{
strWhere.AddWhere("pname=@pnameall");
}
if(model.companyid>0)
{
strWhere.AddWhere($"companyid=@companyid");
}
return strWhere.ToString();
}
/// <summary>
/// 查询
/// </summary>
public List<E_StockInventory> GetList(E_StockInventory model)
{
List<E_StockInventory> list = new List<E_StockInventory>();
string pagewhere = "";
if (model.pageindex != null && model.pagesize > 0 && !model.iscountsearch) //分页查询
{
pagewhere = "where rowid between (@pageindex-1)*@pagesize and @pageindex*@pagesize";
}
StringBuilder SearchSql = new StringBuilder();
SearchSql.Append($@"
select * from (
select row_number()over(order by surplusstock asc) as rowid,* from
(
select *,(intotal-outtotal) as surplusstock from
(
select A.*,case when B.outtotal is null then 0 else B.outtotal end as outtotal from
(
select operationid,classid,companyid,pname,sum(number) as intotal from tb_instock group by operationid,classid,companyid,pname
) as A left join
(
select operationid,classid,companyid,pname,sum(number) as outtotal from tb_Outstock group by operationid,classid,companyid,pname
) as B on A.pname=B.pname
) as Temp {GetSqlWhere(model)}
) as T
) as TT
{pagewhere}");
using (IDbConnection conn = new SqlConnection(PubConstant.GetConnectionString()))
{
list = conn.Query<E_StockInventory>(SearchSql.ToString(), model)?.ToList();
}
return list;
}
/// <summary>
/// 数量
/// </summary>
public int GetCount(E_StockInventory model)
{
StringBuilder strSql = new StringBuilder();
model.iscountsearch = true;
strSql.Append($@"select count(1) from
(
select A.*,case when B.outtotal is null then 0 else B.outtotal end as outtotal from
(
select operationid,classid,companyid,pname,sum(number) as intotal from tb_instock group by operationid,classid,companyid,pname
) as A left join
(
select operationid,classid,companyid,pname,sum(number) as outtotal from tb_Outstock group by operationid,classid,companyid,pname
) as B on A.pname=B.pname
) as Temp {GetSqlWhere(model)}");
using (IDbConnection conn = new SqlConnection(PubConstant.GetConnectionString()))
{
return (int)conn.ExecuteScalar(strSql.ToString(), model);
}
}
}
}
|
using LivrariaWEB.Data;
using LivrariaWEB.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LivrariaWEB.DAO
{
public class LivroDAO : ILivroDAO
{
private readonly ApplicationDbContext _context;
public LivroDAO(ApplicationDbContext context)
{
_context = context;
}
public async Task CreateAsync(Livro livro)
{
_context.Add(livro);
await _context.SaveChangesAsync();
}
public async Task UpdateAsync(Livro livro)
{
_context.Update(livro);
await _context.SaveChangesAsync();
}
public async Task Delete(Livro livro)
{
_context.Remove(livro);
await _context.SaveChangesAsync();
}
public async Task<ICollection<Livro>> Listar()
{
return await _context.Livro
.ToListAsync();
}
public IQueryable<Livro> ListFiltroAll(string filter)
{
IQueryable<Livro> livros = _context.Livro
.AsNoTracking()
.Where(p => (filter == null
|| p.Autor == filter
|| p.Nome == filter))
.AsQueryable();
return livros;
}
public IQueryable<Livro>ListFiltroCustom(int? Isbn, string autor, string nome, decimal? preco, DateTime? data_Publicacao)
{
IQueryable<Livro> livros = _context.Livro
.AsNoTracking()
.Where(p => (Isbn == null || p.ISBN.Equals(Isbn))
&& (autor == null || p.Autor.Contains(autor))
&& (nome == null || p.Nome.Contains(nome))
&& (preco == null || p.Preco.Equals(preco))
&& ((!data_Publicacao.HasValue) || (p.Data_Publicacao >= data_Publicacao && p.Data_Publicacao <= data_Publicacao)))
.OrderByDescending(p => p.Data_Publicacao)
.AsQueryable();
return livros;
}
public async Task<ICollection<Livro>> FiltroLivro(int? Isbn, string autor, string nome, decimal? preco, DateTime? data_Publicacao)
{
return await _context.Livro
.AsNoTracking()
.Where(p => (Isbn == null || p.ISBN.Equals(Isbn))
&& (autor == null || p.Autor.Contains(autor))
&& (nome == null || p.Nome.Contains(nome))
&& (preco == null || p.Preco.Equals(preco))
&& ((!data_Publicacao.HasValue) || (p.Data_Publicacao >= data_Publicacao && p.Data_Publicacao <= data_Publicacao)))
.OrderByDescending(p => p.Data_Publicacao)
.ToListAsync();
}
public async Task<Livro> GetByLivroId(int? Id)
{
return await _context.Livro
.AsNoTracking()
.Where(p => p.Id == Id)
.FirstOrDefaultAsync();
}
public async Task<Livro> GetISBN(int? Isbn)
{
return await _context.Livro
.AsNoTracking()
.Where(p => p.ISBN == Isbn)
.FirstOrDefaultAsync();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.