text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VideoCtrl
{
class Beamer
{
private static Dictionary<string, string> statusList = new Dictionary<string, string>
{
{ "00", "Power On" },
{ "80", "Betriebsbereitschaft (Stand-By)" },
{ "40", "Countdown" },
{ "20", "Abkühlen" },
{ "10", "Stromversorgungsfehler" },
{ "28", "Unregelmäßigkeit beim Abkühlen" },
{ "24", "Abkühlen zum Modus Automatische Lampenabschaltung" },
{ "04", "Modus Automatische Lampenabschaltung nach dem Abkühlen" },
{ "21", "Abkühlen nachdem der Projektor ausgeschaltet wurde wenn die Lampen aus sind." },
{ "81", "Betriebsbereitschaft nach dem Abkühlen wenn die Lampen ausgeschaltet sind." },
{ "88", "Betriebsbereitschaft nach dem Abkühlen wenn Unregelmäßigkeiten mit der Temperatur auftreten." },
{ "2C", "Abkühlen nachdem der Projektor durch die Shutter-Steuerung ausgeschaltet wurde." },
{ "8C", "Betriebsbereitschaft nach dem Abkühlen durch die Shutter-Steuerung" }
};
public string Status
{
get;
private set;
}
public decimal Temperature1 { get; private set; }
public decimal Temperature2 { get; private set; }
public decimal Temperature3 { get; private set; }
public void SetStatus(string value)
{
if (string.IsNullOrEmpty(value))
return;
if (statusList.ContainsKey(value))
{
this.Status = statusList[value];
}
else
{
this.Status = value;
}
}
public void SetTemperatures(string value)
{
if (string.IsNullOrEmpty(value))
return;
string[] values = value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (values.Length != 3)
return;
decimal parsed;
if (decimal.TryParse(values[0], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out parsed))
{
this.Temperature1 = parsed;
}
if (decimal.TryParse(values[1], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out parsed))
{
this.Temperature2 = parsed;
}
if (decimal.TryParse(values[2], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out parsed))
{
this.Temperature3 = parsed;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class UpDownFiles_DownFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//UploadFiles.IUploadDownFiles down = new FTPCommon.FTPs();
string serverPath = Server.UrlDecode(Request["serverPath"]);
string fileName = Server.UrlDecode(Request["fileName"]);
string localPath = Server.MapPath("../UpDownFiles/UploadFile");
//string r = down.OpenDownload(serverPath, localPath + "/" + fileName);
//if (r == "ok")
//{
FileStream outputStream = new FileStream(localPath + "/" + serverPath, FileMode.Open, FileAccess.Read, FileShare.Read);
////解密
byte[] byt = new byte[(int)outputStream.Length];
outputStream.Read(byt, 0, byt.Length);
//byte[] rbyt = Common.DEncrypt.Decrypt(byt);
//file.Write(rbyt, 0, rbyt.Length);
//stream = new MemoryStream(rbyt);
int p = fileName.LastIndexOf(".");
outputStream.Close();
Response.Buffer = true;
this.Context.Response.ContentType = checktype(fileName.Substring(p));
// response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
// string filenames = HttpUtility.UrlEncode(fileName);
//Context.Response.AddHeader("Content-disposition", string.Format("attachment:filename={0}", filenames));
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.AddHeader("Content-Transfer-Encoding", "binary");
this.Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(fileName)));
this.Context.Response.BinaryWrite(byt);
File.Delete(localPath + "/" + fileName);
this.Context.Response.End();
//}
//else
//{
// Response.Write("下载失败");
//}
}
public string checktype(string fileExt)
{
string ContentType;
switch (fileExt)
{
case ".asf":
ContentType = "video/x-ms-asf"; break;
case ".avi":
ContentType = "video/avi"; break;
case ".doc":
ContentType = "application/msword"; break;
case ".zip":
ContentType = "application/zip"; break;
case ".rar":
ContentType = "application/x-zip-compressed"; break;
case ".xls":
ContentType = "application/vnd.ms-excel"; break;
case ".gif":
ContentType = "image/gif"; break;
case ".jpg":
ContentType = "image/jpeg"; break;
case "jpeg":
ContentType = "image/jpeg"; break;
case ".wav":
ContentType = "audio/wav"; break;
case ".mp3":
ContentType = "audio/mpeg3"; break;
case ".mpg":
ContentType = "video/mpeg"; break;
case ".mepg":
ContentType = "video/mpeg"; break;
case ".rtf":
ContentType = "application/rtf"; break;
case ".html":
ContentType = "text/html"; break;
case ".htm":
ContentType = "text/html"; break;
case ".txt":
ContentType = "text/plain"; break;
default:
ContentType = "application/octet-stream";
break;
}
return ContentType;
}
} |
using System;
using NUnit.Framework;
using Moq;
using MessagingExampleApp.Domain;
using MessagingExampleApp.Interfaces;
using MessagingExampleApp.Services;
namespace Tests
{
[TestFixture]
public class OrderUpdateService_ShouldSendMessages
{
private readonly OrderUpdateService _orderService;
public OrderUpdateService_ShouldSendMessages()
{
this._orderService = new OrderUpdateService(this.CreateMockedQueueService());
}
private IQueueService<Order> CreateMockedQueueService()
{
var mockQueueService = new Mock<IQueueService<Order>>();
mockQueueService.Setup(
q => q.Send(It.IsAny<IMessage<Order>>())
).Returns(true);
return mockQueueService.Object;
}
[Test]
public void Should_Send_Create_Order_Message()
{
var order = new Order
{
Id = 1,
Title = "Test Order",
Description = "Testing create order.",
DateCreated = DateTime.Now
};
var result = this._orderService.CreateItem(order);
Assert.AreEqual(true, result);
}
}
} |
using VideoServiceBL.Extensions;
namespace VideoServiceBL.DTOs.MoviesDtos
{
public class MovieDataTableSettings:IQueryObject
{
public int? GenreId { get; set; }
public string Search { get; set; }
public string OrderColumn { get; set; }
public bool IsSortAscending { get; set; }
public int PageIndex { get; set; } = 1;
public int PageSize { get; set; } = 10;
}
} |
using System.Linq;
using Markdig.Helpers;
using Markdig.Parsers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using Xunit;
namespace FlipLeaf.Core.Text.MarkdigSpecifics
{
public class WikiLinkParserTests
{
[Fact]
public void Detect_Url()
{
var md = "[[Hello]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Hello.html", link.Url);
Assert.Equal("Hello", GetSpanText(md, link.UrlSpan));
}
[Fact]
public void Detect_Label()
{
var md = "[[Hello]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Hello", link.Label);
Assert.Equal("Hello", GetSpanText(md, link.LabelSpan));
}
[Fact]
public void Detect_Split()
{
var md = "[[Hello|World]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Hello.html", link.Url);
Assert.Equal("Hello", GetSpanText(md, link.UrlSpan));
Assert.Equal("World", link.Label);
Assert.Equal("World", GetSpanText(md, link.LabelSpan));
}
[Fact]
public void Adapt_Url()
{
var md = "[[Foo Bar]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Foo_Bar.html", link.Url);
Assert.Equal("Foo Bar", GetSpanText(md, link.UrlSpan));
Assert.Equal("Foo Bar", link.Label);
Assert.Equal("Foo Bar", GetSpanText(md, link.LabelSpan));
}
[Fact]
public void Adapt_Url_With_Dash()
{
var md = "[[Foo Bar]]";
var b = TryParse(md, out var link, whiteSpaceUrlChar: '-');
Assert.True(b);
Assert.Equal("Foo-Bar.html", link.Url);
Assert.Equal("Foo Bar", GetSpanText(md, link.UrlSpan));
Assert.Equal("Foo Bar", link.Label);
Assert.Equal("Foo Bar", GetSpanText(md, link.LabelSpan));
}
[Fact]
public void Ignore_NonClosing()
{
var md = "[[Foo";
var b = TryParse(md, out var link);
Assert.False(b);
}
[Fact]
public void Ignore_NonClosing2()
{
var md = "[[Foo]";
var b = TryParse(md, out var link);
Assert.False(b);
}
[Fact]
public void Ignore_Single_Closing()
{
var md = "[[Foo]Bar]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Foo]Bar", link.Label);
}
[Fact]
public void Ignore_Empty()
{
var md = "None";
var b = TryParse(md, out var link);
Assert.False(b);
}
[Fact]
public void Accept_Empty_Link()
{
var md = "[[|Text]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Text", link.Label);
Assert.Equal("Text.html", link.Url);
}
[Fact]
public void Accept_Empty_Label()
{
var md = "[[Url|]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Url", link.Label);
Assert.Equal("Url.html", link.Url);
}
[Fact]
public void Include_Trailing_Characters()
{
var md = "[[Text]]s";
var b = TryParse(md, out var link, includeTrailingCharacters: true);
Assert.True(b);
Assert.Equal("Texts", link.Label);
Assert.Equal("Text", GetSpanText(md, link.LabelSpan));
Assert.Equal("Text.html", link.Url);
Assert.Equal("Text", GetSpanText(md, link.UrlSpan));
}
[Fact]
public void Exclude_Trailing_Whitespaces()
{
var md = "[[Text]] abc";
var b = TryParse(md, out var link, includeTrailingCharacters: true);
Assert.True(b);
Assert.Equal("Text", link.Label);
Assert.Equal("Text.html", link.Url);
}
[Fact]
public void Include_Trailing_Apostrophe()
{
var md = "[[Text]]'s";
var b = TryParse(md, out var link, includeTrailingCharacters: true);
Assert.True(b);
Assert.Equal("Text's", link.Label);
Assert.Equal("Text.html", link.Url);
}
[Fact]
public void Ignore_Trailing_When_Explicit_Text()
{
var md = "[[Url|Text]]'s";
var b = TryParse(md, out var link, includeTrailingCharacters: true);
Assert.True(b);
Assert.Equal("Text", link.Label);
Assert.Equal("Url.html", link.Url);
}
[Fact]
public void Ignore_Escaped_Separator()
{
var md = @"[[Url\|Url|Text]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal("Text", link.Label);
Assert.Equal(@"Url\|Url.html", link.Url);
}
[Fact]
public void Ignore_Escaped_Separator_02()
{
var md = @"[[Url\|Text]]";
var b = TryParse(md, out var link);
Assert.True(b);
Assert.Equal(@"Url\|Text", link.Label);
Assert.Equal(@"Url\|Text.html", link.Url);
}
private string GetSpanText(string markdown, SourceSpan? span)
{
if (!span.HasValue)
return null;
return markdown.Substring(span.Value.Start, span.Value.Length);
}
private bool TryParse(string markdown, out LinkInline link, bool? includeTrailingCharacters = null, char? whiteSpaceUrlChar = null)
{
var pr = BuidProcessor();
var sl = new StringSlice(markdown);
var p = new WikiLinkParser() { Extension = ".html" };
if (includeTrailingCharacters != null) p.IncludeTrailingCharacters = includeTrailingCharacters.Value;
if (whiteSpaceUrlChar != null) p.WhiteSpaceUrlChar = whiteSpaceUrlChar.Value;
var b = p.Match(pr, ref sl);
if (b)
{
link = (LinkInline)pr.Inline;
}
else
{
link = null;
}
return b;
}
private InlineProcessor BuidProcessor()
{
var p = new WikiLinkParser();
var pr = new InlineProcessor(new StringBuilderCache(), new MarkdownDocument(), new InlineParserList(Enumerable.Empty<InlineParser>()), false);
return pr;
}
}
}
|
using CourseProject.Model;
using CourseProject.Repositories;
using System.Collections.Generic;
using System.Linq;
namespace CourseProject_WPF_.Repositories
{
internal class EfUserRepository : IUserRepository
{
private readonly MyShopContext _context = MyShopContext.Instance;
public List<string> GetAllNames()
{
return _context.Users.Select(s => s.FirstName).ToList();
}
public IEnumerable<User> GetAll()
{
return _context.Users;
}
public void Add(User user)
{
_context.Users.Add(user);
_context.SaveChanges();
}
public void Delete(User user)
{
try
{
_context.Users.Remove(_context.Users.FirstOrDefault(x => x.Id == user.Id));
_context.SaveChanges();
}
catch { }
}
public User GetByMail(string mail)
{
return _context.Users.FirstOrDefault(x => x.Mail == mail);
}
public User GetByName(string name)
{
return _context.Users.FirstOrDefault(x => (x.FirstName + " " + x.SecondName) == name);
}
public User GetById(int? id)
{
return _context.Users.FirstOrDefault(x => x.Id == id);
}
public void Update(User oldUser, User newUser)
{
var tmp = _context.Users.FirstOrDefault(x => x.Id == oldUser.Id);
if (tmp != null)
{
tmp.FirstName = newUser.FirstName;
tmp.SecondName = newUser.SecondName;
tmp.Mail = newUser.Mail;
tmp.About = newUser.About;
tmp.Image = newUser.Image;
tmp.TelNumber = newUser.TelNumber;
}
_context.SaveChanges();
}
public void ChangePrivilege(User user, string privilege)
{
var userTarget = _context.Users.FirstOrDefault(x => x.Id == user.Id);
if (userTarget != null)
{
userTarget.Privilege = privilege;
}
_context.SaveChanges();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using SearchFoodServer.CompositeClass;
namespace SearchFoodServer.CAD
{
public class CategoriesCad
{
public List<CompositeCategories> GetCategories()
{
List<CompositeCategories> categoriesList = new List<CompositeCategories>();
List<Categorie> categories;
using (var bdd = new searchfoodEntities())
{
var requete = from c in bdd.Categorie
select c;
categories = requete.ToList();
}
if (categories.Count > 0)
{
foreach (Categorie c in categories)
{
CompositeCategories composite = new CompositeCategories();
composite.IdCategorieValue = c.Id_Categorie;
composite.NomCategorieValue = c.Nom_Categorie;
categoriesList.Add(composite);
}
}
return categoriesList;
}
public CompositeCategories GetCategorie(int id)
{
CompositeCategories compositeCategorie = new CompositeCategories();
Categorie categorie;
using (var bdd = new searchfoodEntities())
{
var requete = from c in bdd.Categorie where c.Id_Categorie == id
select c;
categorie = requete.FirstOrDefault();
}
if (categorie != null)
{
compositeCategorie.IdCategorieValue = categorie.Id_Categorie;
compositeCategorie.NomCategorieValue = categorie.Nom_Categorie;
}
return compositeCategorie;
}
public void AddCategories(Categorie c)
{
using (var bdd = new searchfoodEntities())
{
bdd.Categorie.Add(c);
bdd.SaveChanges();
}
}
public void DeleteCategories(int id)
{
using (var bdd = new searchfoodEntities())
{
var requete = from c in bdd.Categorie
where c.Id_Categorie == id
select c;
Categorie categorie = requete.FirstOrDefault();
if (categorie != null)
{
bdd.Categorie.Remove(categorie);
bdd.SaveChanges();
}
}
}
public void UpdateCategories(Categorie c)
{
using (var bdd = new searchfoodEntities())
{
Categorie categorie = bdd.Categorie.Find(c.Id_Categorie);
if (categorie != null)
{
bdd.Entry(categorie).CurrentValues.SetValues(c);
bdd.SaveChanges();
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace LinearOrdering
{
internal static class Utils
{
public static double[][] GetData(string fileName)
{
var lines = File.ReadAllLines(fileName);
var rawDaa = lines
.Skip(1) // remove header row
.Select(line => line
.Replace(',', '.')
.Split(';')
.Skip(1));
return rawDaa.Select(line => line.Select(double.Parse).ToArray()).ToArray();
}
public static string[] GetFirstColumn(string fileName)
{
var lines = File.ReadAllLines(fileName);
var rawDaa = lines
.Skip(1) // remove header row
.Select(line => line
.Replace(',', '.')
.Split(';')
.FirstOrDefault());
return rawDaa.ToArray();
}
public static void SetCulture()
{
var culture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
}
public static double[][] SwapRowWithColumns(double[][] data)
{
var rowLength = data.First().Length;
var result = new double[rowLength][];
for (var r = 0; r < result.Length; r++)
{
result[r] = new double[data.Length];
}
for (var r = 0; r < data.Length; r++)
{
for (var c = 0; c < result.Length; c++)
{
result[c][r] = data[r][c];
}
}
return result;
}
public static void PrintRanking(string[] columnNames, double[] distances)
{
var sorted = columnNames.Select((x, i) => new KeyValuePair<string, double>(x, distances[i]))
.OrderBy(x => x.Value);
Console.WriteLine($"Ranking:\n{string.Join(",\n", sorted)}");
}
}
} |
/** 版本信息模板在安装目录下,可自行修改。
* MEETING_ROOM_INFO.cs
*
* 功 能: N/A
* 类 名: MEETING_ROOM_INFO
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2014-6-26 9:19:36 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Text;
using System.Data.OracleClient;
using Maticsoft.DBUtility;//Please add references
using System.Collections.Generic;
using System.Data.SqlClient;
namespace PDTech.OA.DAL
{
/// <summary>
/// 数据访问类:MEETING_ROOM_INFO
/// </summary>
public partial class MEETING_ROOM_INFO
{
public MEETING_ROOM_INFO()
{}
#region BasicMethod
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(string MEETING_ROOM_NAME)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("select count(1) from MEETING_ROOM_INFO");
strSql.Append(" where MEETING_ROOM_NAME=@MEETING_ROOM_NAME ");
SqlParameter[] parameters = {
new SqlParameter("@MEETING_ROOM_NAME", SqlDbType.VarChar) };
parameters[0].Value = MEETING_ROOM_NAME;
return DbHelperSQL.Exists(strSql.ToString(),parameters);
}
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(string MEETING_ROOM_NAME, decimal MEETING_ROOM_ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from MEETING_ROOM_INFO");
strSql.Append(" where MEETING_ROOM_NAME=@MEETING_ROOM_NAME AND MEETING_ROOM_ID<>@MEETING_ROOM_ID ");
SqlParameter[] parameters = {
new SqlParameter("@MEETING_ROOM_NAME", SqlDbType.NVarChar),
new SqlParameter("@MEETING_ROOM_ID", SqlDbType.Decimal,22)};
parameters[0].Value = MEETING_ROOM_NAME;
parameters[1].Value = MEETING_ROOM_ID;
return DbHelperSQL.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 增加一条数据
/// </summary>
public int Add(PDTech.OA.Model.MEETING_ROOM_INFO model)
{
if (Exists(model.MEETING_ROOM_NAME))
{
return -1;
}
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into MEETING_ROOM_INFO(");
strSql.Append("MEETING_ROOM_NAME,ROOM_DESC)");
strSql.Append(" values (");
strSql.Append("@MEETING_ROOM_NAME,@ROOM_DESC)");
SqlParameter[] parameters = {
//new SqlParameter("@MEETING_ROOM_ID", SqlDbType.Decimal,4),
new SqlParameter("@MEETING_ROOM_NAME", SqlDbType.VarChar,150),
new SqlParameter("@ROOM_DESC", SqlDbType.VarChar,300)};
//parameters[0].Value = model.MEETING_ROOM_ID;
parameters[0].Value = model.MEETING_ROOM_NAME;
parameters[1].Value = model.ROOM_DESC;
DAL_Helper.get_db_para_value(parameters);
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return 1;
}
else
{
return 0;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public int Update(PDTech.OA.Model.MEETING_ROOM_INFO model)
{
if (Exists(model.MEETING_ROOM_NAME, model.MEETING_ROOM_ID))
{
return -1;
}
StringBuilder strSql=new StringBuilder();
strSql.Append("update MEETING_ROOM_INFO set ");
strSql.Append("MEETING_ROOM_NAME=@MEETING_ROOM_NAME,");
strSql.Append("ROOM_DESC=@ROOM_DESC");
strSql.Append(" where MEETING_ROOM_ID=@MEETING_ROOM_ID ");
SqlParameter[] parameters = {
new SqlParameter("@MEETING_ROOM_NAME", SqlDbType.VarChar,150),
new SqlParameter("@ROOM_DESC", SqlDbType.VarChar,300),
new SqlParameter("@MEETING_ROOM_ID", SqlDbType.Decimal,4)};
parameters[0].Value = model.MEETING_ROOM_NAME;
parameters[1].Value = model.ROOM_DESC;
parameters[2].Value = model.MEETING_ROOM_ID;
DAL_Helper.get_db_para_value(parameters);
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return 1;
}
else
{
return 0;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(decimal MEETING_ROOM_ID)
{
StringBuilder strSql=new StringBuilder();
strSql.Append("delete from MEETING_ROOM_INFO ");
strSql.Append(" where MEETING_ROOM_ID=@MEETING_ROOM_ID ");
SqlParameter[] parameters = {
new SqlParameter("@MEETING_ROOM_ID", SqlDbType.Decimal,22) };
parameters[0].Value = MEETING_ROOM_ID;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 获取信息
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public Model.MEETING_ROOM_INFO GetmRoomInfo(decimal mId)
{
string strSQL = string.Format("SELECT MEETING_ROOM_ID,MEETING_ROOM_NAME,ROOM_DESC FROM MEETING_ROOM_INFO WHERE MEETING_ROOM_ID={0}", mId);
DataTable dt = DbHelperSQL.GetTable(strSQL);
if (dt.Rows.Count > 0)
{
return DAL_Helper.CommonFillList<Model.MEETING_ROOM_INFO>(dt)[0];
}
else
{
return null;
}
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select MEETING_ROOM_ID,MEETING_ROOM_NAME,ROOM_DESC ");
strSql.Append(" FROM MEETING_ROOM_INFO ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public PDTech.OA.Model.MEETING_ROOM_INFO DataRowToModel(DataRow row)
{
PDTech.OA.Model.MEETING_ROOM_INFO model = new PDTech.OA.Model.MEETING_ROOM_INFO();
if (row != null)
{
if (row["MEETING_ROOM_ID"] != null && row["MEETING_ROOM_ID"].ToString() != "")
{
model.MEETING_ROOM_ID = decimal.Parse(row["MEETING_ROOM_ID"].ToString());
}
if (row["MEETING_ROOM_NAME"] != null)
{
model.MEETING_ROOM_NAME = row["MEETING_ROOM_NAME"].ToString();
}
if (row["ROOM_DESC"] != null)
{
model.ROOM_DESC = row["ROOM_DESC"].ToString();
}
}
return model;
}
/// <summary>
/// 获取基础数据信息列表-使用分页
/// </summary>
/// <param name="where"></param>
/// <param name="currentpage"></param>
/// <param name="pagesize"></param>
/// <param name="totalrecord"></param>
/// <returns></returns>
public IList<Model.MEETING_ROOM_INFO> get_Paging_mRoomList(Model.MEETING_ROOM_INFO where, int currentpage, int pagesize, out int totalrecord)
{
string condition = DAL_Helper.GetWhereCondition(where);
string strSQL = string.Format("SELECT TOP (100) PERCENT MEETING_ROOM_ID,MEETING_ROOM_NAME,ROOM_DESC FROM MEETING_ROOM_INFO WHERE 1=1 {0} ", condition);
PageDescribe pdes = new PageDescribe();
pdes.CurrentPage = currentpage;
pdes.PageSize = pagesize;
DataTable dt = pdes.PageDescribes(strSQL, "MEETING_ROOM_ID", "DESC");
totalrecord = pdes.RecordCount;
return DAL_Helper.CommonFillList<Model.MEETING_ROOM_INFO>(dt);
}
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
|
using Snap.Models;
using Snap.Models.Enums;
using System.Linq;
namespace Snap.ViewModels
{
public class GameViewModel
{
public GameViewModel()
{
GameHasStarted = false;
}
public GameViewModel(Game game)
{
GameHasStarted = true;
var currentCard = game.TableDeck.Cards.LastOrDefault();
CurrentCardDescription = $"{currentCard?.Value.ToString() ?? ""} {currentCard?.Suit.ToString() ?? "Empty table"}";
IsPlayersTurn = game.PlayerTurn == game.Players.Where(p => p.PlayerType == PlayerType.Player).FirstOrDefault();
PlayerCardCount = game.Players.Where(p => p.PlayerType == PlayerType.Player).FirstOrDefault().Hand?.Cards?.Count() ?? 0;
ComputerCardCount = game.Players.Where(p => p.PlayerType == PlayerType.Computer).FirstOrDefault().Hand?.Cards?.Count() ?? 0;
if (game.TableDeck.Cards.Count() > 1 )
{
ComputerCallSnap = game.TableDeck.Cards.LastOrDefault().Value == game.TableDeck.Cards[game.TableDeck.Cards.Count() - 2].Value;
}
SnapWasCalled = game.SnapEvent?.EventTriggered ?? false;
if (SnapWasCalled)
{
SnapMessage = game.SnapEvent.IsSuccess ? $"Snap called and won by {game.SnapEvent.TriggerPlayer.Name}" : $"Snap called by {game.SnapEvent.TriggerPlayer.Name} but wasn't valid";
}
GameHasEnded = game.HasEnded;
WinningPlayer = game.WinningPlayer?.Name ?? "";
}
public bool GameHasStarted { get; set; }
public string CurrentCardDescription { get; set; }
public int PlayerCardCount { get; set; }
public bool IsPlayersTurn { get; set; }
public int ComputerCardCount { get; set; }
public bool ComputerCallSnap { get; set; } = false;
public bool SnapWasCalled { get; set; }
public string SnapMessage { get; set; }
public bool GameHasEnded { get; set; }
public string WinningPlayer { get; set; }
}
} |
namespace DpiConverter.Files.Importable
{
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Contracts.Files;
using Data;
using Helpers;
internal class JxlFile : IImportableFile
{
public const string ShemaLocation = "JobXMLSchema-5.64.xsd";
private readonly bool validation = false;
public JxlFile() : this(false)
{
}
public JxlFile(bool validation)
{
this.validation = validation;
}
public void Open(string file, ICollection<Station> stationsList)
{
XDocument document = XmlHelper.CreateXmlDocument(file, JxlFile.ShemaLocation, this.validation);
((List<Station>)stationsList).AddRange(TrimbleJobXmlHelper.FindStations(document));
ICollection<TargetRecord> targetRecords = new List<TargetRecord>(TrimbleJobXmlHelper.FindTargetRecords(document));
var observations = from observation in document.Root
.Elements()
.Where(x => x.Name.LocalName == "FieldBook")
.Elements()
.Where(x => x.Name.LocalName == "PointRecord")
select observation;
foreach (var observation in observations)
{
string method = observation.Element("Method").Value;
switch (method)
{
case "DirectReading":
string targetPointName = observation.Element("Name").Value;
string targetPointCode = string.Empty;
string targetPointDescription = observation.Element("Code").Value;
double horizontalCircle = double.Parse(observation.Element("Circle").Element("HorizontalCircle").Value) * 200 / 180;
double verticalCircle = double.Parse(observation.Element("Circle").Element("VerticalCircle").Value) * 200 / 180;
double distance = double.Parse(observation.Element("Circle").Element("EDMDistance").Value);
string stationIndex = observation.Element("StationID").Value;
string targetIndex = observation.Element("TargetID").Value;
double targetHeight = targetRecords.Where(th => th.TargetIndex == targetIndex).Last().TargetHeight;
Observation currentObservation = new Observation(targetPointCode, targetPointName, targetHeight, horizontalCircle, distance, verticalCircle, targetPointDescription);
stationsList.FirstOrDefault(s => s.StationIndex == stationIndex).Observations.Add(currentObservation);
break;
}
}
}
}
} |
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class VAusleihgrund
{
public int EreignisgrundId { get; set; }
public string Bezeichnung { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthUI : MonoBehaviour {
#region SINGLETON PATTERN
private static HealthUI instance;
public static HealthUI GetInstance()
{
return instance;
}
private void Awake()
{
instance = this;
}
#endregion
public Image healthLevel;
private Player _player;
// Use this for initialization
void Start()
{
_player = Player.GetInstance();
}
// Update is called once per frame
void Update()
{
healthLevel.fillAmount = _player.Health;
if (_player.IsHealing) {
healthLevel.color = Color.green;
}
else {
healthLevel.color = Color.white;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Team3ADProject.Code;
using System.Web.Security;
using Team3ADProject.Model;
//Sruthi
namespace Team3ADProject.Protected
{
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string dept = getmethoddepartment();//to get the department
var q = BusinessLogic.getemployeenames(dept); //to get the employee names of the department
GridView1.DataSource = q;
GridView1.DataBind();
updategrid();
}
}
//to get the department for the logged in employee
public string getmethoddepartment()
{
int employeeid = Convert.ToInt32(Session["Employee"]);
string user = BusinessLogic.GetUserID(employeeid);
string dept = BusinessLogic.getdepartment(user);//to get the department
return dept;
}
public void updategrid()
{
string dept = getmethoddepartment();
//to get the representative history of the department
var k = BusinessLogic.getpreviousrepdetails(dept);
GridView2.DataSource = k;
GridView2.DataBind();
}
//to display the employee by select
protected void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
HiddenField hd = (HiddenField)b.FindControl("HiddenField1");
TextBox2.Text = hd.Value;
}
// event on appointing representative
protected void Button2_Click(object sender, EventArgs e)
{
string name = TextBox2.Text;
if (!string.IsNullOrEmpty(name))
{
Label4.Visible = false;
int id = BusinessLogic.getemployeeid(name);
string dept = getmethoddepartment();
//saving the representative details
BusinessLogic.saverepdetails(dept, id);
//sending the email to the department employees,store clerk on the Representative change.
//adding the person as rep
employee getName = BusinessLogic.GetEmployee(id);
Roles.AddUserToRole(getName.user_id, Constants.ROLES_DEPARTMENT_REPRESENTATIVE);
Roles.RemoveUserFromRole(getName.user_id, Constants.ROLES_EMPLOYEE);
//Send the new rep an email.
string emailAdd = BusinessLogic.GetDptRepEmailAddFromDptID(dept);
string messagebody1 = "Congratulations,\n You have been appointed as the department representative for the collection of items ";
BusinessLogic.sendMail(emailAdd, "Department Representative Change", messagebody1);
updategrid();
//Send email to all inform about the new Rep
List<string> email = BusinessLogic.getEmployeesEmailFromDept(dept);
string messagebody = "The following person has been appointed as the representative for the collection of items \n \n" + name;
BusinessLogic.sendMail(email, "Department Representative Change", messagebody);
}
else
{
Label4.Visible = true;
}
}
// event for getting employee name
protected void Button1_Click(object sender, EventArgs e)
{
string dept = getmethoddepartment();
string name = TextBox1.Text.TrimEnd();
//to get the employee name by search
var q = BusinessLogic.getemployeenamebysearch(dept, name);
if (q.Count() > 0)
{
GridView1.Visible = true;
Label5.Visible = false;
GridView1.DataSource = q.ToList();
GridView1.DataBind();
}
else
{
Label5.Visible = true;
GridView1.Visible = true;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SecondProject.Controllers.Services.Model;
using SecondProject.Controllers.Services.Model.Domain;
using SecondProject.Controllers.Services.Model.Domain.DTOs;
using SecondProject.Controllers.Services.Model.File;
namespace SecondProject.Controllers
{
[Route("api/[controller]")]
public class ValuesController
{
private readonly IHttpServices _IHttpServices;
private readonly IMapper _mapper;
public ValuesController(IHttpServices httpServices, IMapper mapper)
{
_IHttpServices = httpServices;
_mapper = mapper;
}
[HttpGet("getEnvironmentName")]
public async Task<IEnumerable<EnvironmentName>> GetEnvironmentName()
{
List<EnvironmentName> name = new List<EnvironmentName>();
name = await _IHttpServices.GetEnvironmentName();
return name;
}
[HttpGet("checkApplication")]
public async Task<ApplicationResult> checkFileApplication()
{
ApplicationResult application = await _IHttpServices.checkFileApplication();
return application;
}
}
}
|
using System;
namespace Builder
{
class Program
{
static void Main(string[] args)
{
Director director = new Director();
//Construimos un auto basico
BuilderNomal builderNormal = new BuilderNomal();
director.Construir(builderNormal);
var auto1 = builderNormal.ObtenerProducto();
auto1.MostrarAuto();
Console.WriteLine("----------");
Console.WriteLine("----------");
//Construimos un auto deportivo
var builderEspecial = new BuilderEspecial();
director.Construir(builderEspecial);
var auto2 = builderEspecial.ObtenerProducto();
auto1.MostrarAuto();
Console.WriteLine("----------");
}
}
}
|
using IBll;
using IDal;
using Microsoft.Practices.Unity;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utility.Express;
namespace Bll
{
public class User_CatalogBll : IUser_CatalogBll
{
Entities db = new Entities();
[Dependency]
public IUser_CatalogRepository Rep { get; set; }
public List<User_Catalog> GetList(Func<User_Catalog, bool> predicate)
{
IQueryable<User_Catalog> queryData = Rep.GetList(db).Where(predicate).AsQueryable();
return queryData.ToList();
}
public int Create(User_Catalog entity)
{
return Rep.Create(entity);
}
public int Edit(User_Catalog entity)
{
return Rep.Edit(entity);
}
public bool Delete(Func<User_Catalog, bool> predicate)
{
if (Rep.Delete(predicate) == 1)
{
return true;
}
else
{
return false;
}
}
public User_Catalog Get(Func<User_Catalog, bool> predicate)
{
if (IsExist(predicate))
{
User_Catalog entity = Rep.Get(predicate);
return entity;
}
else
{
return null;
}
}
public bool IsExist(Func<User_Catalog, bool> predicate)
{
return Rep.IsExist(predicate);
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebApplication1.Migrations
{
public partial class Seed : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "User",
columns: new[] { "Id", "Address", "Country", "FirstName", "LastName", "Mobile" },
values: new object[] { 1, "DC", "USA", "Samir", "Dadash", 111 });
migrationBuilder.InsertData(
table: "User",
columns: new[] { "Id", "Address", "Country", "FirstName", "LastName", "Mobile" },
values: new object[] { 2, "DC", "USA", "Ilhame", "Dadash", 222 });
migrationBuilder.InsertData(
table: "User",
columns: new[] { "Id", "Address", "Country", "FirstName", "LastName", "Mobile" },
values: new object[] { 3, "DC", "USA", "Nunus", "Dadash", 333 });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: 1);
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: 2);
migrationBuilder.DeleteData(
table: "User",
keyColumn: "Id",
keyValue: 3);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace E_OKUL_PROJE
{
public partial class FrmOgrenciIşlemleri : Form
{
public FrmOgrenciIşlemleri()
{
InitializeComponent();
}
SqlConnection bgl = new SqlConnection(@"Data Source=DESKTOP-6QDVVSR\SQLEXPRESS;Initial Catalog=BonusOkul;Integrated Security=True");
DataSet1TableAdapters.DataTable1TableAdapter ds = new DataSet1TableAdapters.DataTable1TableAdapter();
private void pictureBox6_Click(object sender, EventArgs e)
{
FrmOgretmen fr = new FrmOgretmen();
fr.Show();
this.Hide();
}
private void FrmOgrenciIşlemleri_Load(object sender, EventArgs e)
{
dataGridView1.DataSource=ds.OgrListeleme();
//comboboxa kuluplerin id yerine isimlerini getirme
bgl.Open();
SqlCommand komut = new SqlCommand("select * from tbl_kulupler", bgl);
SqlDataAdapter da = new SqlDataAdapter(komut);
DataTable dt = new DataTable();
da.Fill(dt);
cmbkulüp.DisplayMember = "KULUPAD"; //ne görmek istiyorum
cmbkulüp.ValueMember = "KULUPID"; //kulupler tablomda nasıl tutuluyor
cmbkulüp.DataSource = dt;
bgl.Close();
}
private void btnlistele_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ds.OgrListeleme();
}
string c = "";
private void btnekle_Click(object sender, EventArgs e)
{
if (rdbtnkız.Checked == true)
{
c = "KIZ";
}
if (rdbtnerkek.Checked == true)
{
c = "ERKEK";
}
ds.OgrEkle(txtad.Text,txtsoyad.Text,byte.Parse(cmbkulüp.SelectedValue.ToString()),c);
MessageBox.Show("Öğrenci ekleme işlemi başarılı", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void cmbkulüp_SelectedIndexChanged(object sender, EventArgs e)
{
// txtid.Text = cmbkulüp.SelectedValue.ToString();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int secilen = dataGridView1.SelectedCells[0].RowIndex;
txtid .Text = dataGridView1.Rows[secilen].Cells[0].Value.ToString();
txtad.Text = dataGridView1.Rows[secilen].Cells[1].Value.ToString();
txtsoyad.Text = dataGridView1.Rows[secilen].Cells[2].Value.ToString();
cmbkulüp.Text= dataGridView1.Rows[secilen].Cells[3].Value.ToString();
c = dataGridView1.Rows[secilen].Cells[4].Value.ToString();
if (c=="KIZ")
{
rdbtnkız.Checked = true;
rdbtnerkek.Checked = false;
}
if (c=="ERKEK")
{
rdbtnerkek.Checked = true;
rdbtnkız.Checked = false;
}
}
private void btnsil_Click(object sender, EventArgs e)
{
ds.OgrSil(Convert.ToInt32(txtid.Text));
MessageBox.Show("Öğrenci silme işlemi başarılı", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btngüncelle_Click(object sender, EventArgs e)
{
ds.OgrGüncelle(txtad.Text, txtsoyad.Text ,int.Parse(cmbkulüp.SelectedValue.ToString()), c ,int.Parse(txtid.Text));
MessageBox.Show("Öğrenci güncelleme işlemi başarılı", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void rdbtnkız_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnkız.Checked == true)
{
c = "KIZ";
}
}
private void rdbtnerkek_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnerkek .Checked == true)
{
c = "ERKEK";
}
}
private void btnara_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ds.OgrBul(txtara.Text);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Turnamentor.Interfaces;
namespace Turnamentor.Core
{
class Turnamentor<ScoreBoard, Score> : ITurnamentor<ScoreBoard, Score> where ScoreBoard : IScoreBoard<Score>
{
public Func<dynamic> EngineProvider { get; set; }
public ScoreBoard ScoreBoardInstance { get; set; }
public IEnumerable<IList<dynamic>> AllRounds { get; set; }
public ScoreBoard RunTurnament()
{
dynamic engine = EngineProvider();
foreach (var round in AllRounds)
{
Score s = engine.Play(ToConstestantList(round));
ScoreBoardInstance.Add(s);
}
return ScoreBoardInstance;
}
public Type listOfContestantsType { get; set; }
public void SetContstantType<Contestant>()
{
listOfContestantsType = typeof(List<>).MakeGenericType(typeof(Contestant));
}
private dynamic ToConstestantList(IList<dynamic> enumerable)
{
dynamic list = Activator.CreateInstance(listOfContestantsType);
foreach (var item in enumerable)
list.Add(item);
return list;
}
}
}
|
using Plus.HabboHotel.Items;
namespace Plus.Communication.Packets.Outgoing.Rooms.Engine
{
internal class ObjectRemoveComposer : MessageComposer
{
public Item Item { get; }
public int UserId { get; }
public ObjectRemoveComposer(Item item, int userId)
: base(ServerPacketHeader.ObjectRemoveMessageComposer)
{
Item = item;
UserId = userId;
}
public override void Compose(ServerPacket packet)
{
packet.WriteString(Item.Id.ToString());
packet.WriteBoolean(false);
packet.WriteInteger(UserId);
packet.WriteInteger(0);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Planning
{
public class Argument
{
public string Name { get { return Names[m_iName]; } set { SetName(value); } }
public string Type { get { return Types[m_iType]; } set { SetType(value); } }
private void SetType(string sType)
{
m_iType = Types.IndexOf(sType);
if (m_iType == -1)
{
m_iType = Types.Count;
Types.Add(sType);
}
}
private void SetName(string sName)
{
m_iName = Names.IndexOf(sName);
if (m_iName == -1)
{
m_iName = Names.Count;
Names.Add(sName);
}
}
protected int m_iType;
protected int m_iName;
protected static List<string> Types = new List<string>();
protected static List<string> Names = new List<string>();
public static void ResetStaticFields()
{
Types = new List<string>();
Names = new List<string>();
}
public Argument(string sType, string sName)
{
SetType(sType);
SetName(sName);
}
public Argument(int iType, string sName)
{
SetName(sName);
m_iType = iType;
}
public string FullString()
{
return Name + " - " + Type;
}
public override string ToString()
{
return Name;
}
public override sealed int GetHashCode()
{
return m_iType * 100 + m_iName;
}
public override sealed bool Equals(object obj)
{
if (obj is Argument)
{
Argument arg = (Argument)obj;
return arg.m_iType == m_iType && arg.m_iName == m_iName;
}
return false;
}
}
}
|
using Microsoft.JSInterop;
using System.Threading.Tasks;
namespace BlazorUtils.Interfaces.Invokers
{
public static class JsInvoke
{
public static T Invoke<T>(string funcName, params object[] parameters) => (JSRuntime.Current as IJSInProcessRuntime).Invoke<T>(
$"blazorUtils.core.funcs.{funcName}", parameters);
public static Task<T> InvokeAsync<T>(string funcName, params object[] parameters) => JSRuntime.Current.InvokeAsync<T>($"blazorUtils.core.funcs.{funcName}", parameters);
}
}
|
using System;
//using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataStructures;
using Microsoft.Pex.Framework;
namespace DataStructures.Test.Factories
{
public static class StackFactory
{
[PexFactoryMethod(typeof(DataStructures.Stack<int>))]
public static DataStructures.Stack<int> Create(int[] elems)
{
PexAssume.IsTrue(elems != null && elems.Length < 11);
PexAssume.TrueForAll(0, elems.Length, _i => elems[_i] > -11 && elems[_i] < 11);
DataStructures.Stack<int> ret = new DataStructures.Stack<int>(elems.Length+2 );// DataStructure has big enough capacity for Commutativity Test
for (int i = 0; i < elems.Length; i++)
{
// For stack, add any element.
ret.Push(elems[i]);
}
return ret;
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("ArenaStore")]
public class ArenaStore : Store
{
public ArenaStore(IntPtr address) : this(address, "ArenaStore")
{
}
public ArenaStore(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public void BuyWithGold(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("BuyWithGold", objArray1);
}
public void BuyWithMoney(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("BuyWithMoney", objArray1);
}
public void ExitForgeStore(bool authorizationBackButtonPressed)
{
object[] objArray1 = new object[] { authorizationBackButtonPressed };
base.method_8("ExitForgeStore", objArray1);
}
public static ArenaStore Get()
{
return MonoClass.smethod_15<ArenaStore>(TritonHs.MainAssemblyPath, "", "ArenaStore", "Get", Array.Empty<object>());
}
public void Hide()
{
base.method_8("Hide", Array.Empty<object>());
}
public void OnAuthExit(object userData)
{
object[] objArray1 = new object[] { userData };
base.method_8("OnAuthExit", objArray1);
}
public void OnBackPressed(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("OnBackPressed", objArray1);
}
public void OnDestroy()
{
base.method_8("OnDestroy", Array.Empty<object>());
}
public void OnGoldBalanceChanged(NetCache.NetCacheGoldBalance balance)
{
object[] objArray1 = new object[] { balance };
base.method_8("OnGoldBalanceChanged", objArray1);
}
public void OnMoneySpent()
{
base.method_8("OnMoneySpent", Array.Empty<object>());
}
public bool OnNavigateBack()
{
return base.method_11<bool>("OnNavigateBack", Array.Empty<object>());
}
public void SetUpBuyButtons()
{
base.method_8("SetUpBuyButtons", Array.Empty<object>());
}
public void SetUpBuyWithGoldButton()
{
base.method_8("SetUpBuyWithGoldButton", Array.Empty<object>());
}
public void SetUpBuyWithMoneyButton()
{
base.method_8("SetUpBuyWithMoneyButton", Array.Empty<object>());
}
public void Start()
{
base.method_8("Start", Array.Empty<object>());
}
public void UpdateGoldButtonState(NetCache.NetCacheGoldBalance balance)
{
object[] objArray1 = new object[] { balance };
base.method_8("UpdateGoldButtonState", objArray1);
}
public void UpdateMoneyButtonState()
{
base.method_8("UpdateMoneyButtonState", Array.Empty<object>());
}
public UIBButton m_backButton
{
get
{
return base.method_3<UIBButton>("m_backButton");
}
}
public Network.Bundle m_bundle
{
get
{
return base.method_3<Network.Bundle>("m_bundle");
}
}
public NoGTAPPTransactionData m_goldTransactionData
{
get
{
return base.method_3<NoGTAPPTransactionData>("m_goldTransactionData");
}
}
public GameObject m_storeClosed
{
get
{
return base.method_3<GameObject>("m_storeClosed");
}
}
public static int NUM_BUNDLE_ITEMS_REQUIRED
{
get
{
return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "ArenaStore", "NUM_BUNDLE_ITEMS_REQUIRED");
}
}
}
}
|
#region usings
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
#endregion
namespace Zengo.WP8.FAS.Models
{
[Table]
public class VoteRecord : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property, and database column.
private string _voteId;
[Column(IsPrimaryKey = true, IsDbGenerated = false, DbType = "NVarChar(100) NOT NULL", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public string VoteId
{
get { return _voteId; }
set
{
if (_voteId != value)
{
NotifyPropertyChanging("VoteId");
_voteId = value;
NotifyPropertyChanged("VoteId");
}
}
}
// PlayerId
private int _playerId;
[Column]
public int PlayerId
{
get { return _playerId; }
set
{
if (_playerId != value)
{
NotifyPropertyChanging("PlayerId");
_playerId = value;
NotifyPropertyChanged("PlayerId");
}
}
}
// PositionId
private int _positionId;
[Column]
public int PositionId
{
get { return _positionId; }
set
{
if (_positionId != value)
{
NotifyPropertyChanging("PositionId");
_positionId = value;
NotifyPropertyChanged("PositionId");
}
}
}
// Server Vote Created time
private long _created;
[Column]
public long Created
{
get { return _created; }
set
{
if (_created != value)
{
NotifyPropertyChanging("Created");
_created = value;
NotifyPropertyChanged("Created");
}
}
}
// Server vote cast TimeStamp
private long _timeStamp;
[Column]
public long TimeStamp
{
get { return _timeStamp; }
set
{
if (_timeStamp != value)
{
NotifyPropertyChanging("TimeStamp");
_timeStamp = value;
NotifyPropertyChanged("TimeStamp");
}
}
}
// Local vote cast time timeStamp to time how long it takes
private long _localCastTimeStamp;
[Column]
public long LocalCastTimeStamp
{
get { return _localCastTimeStamp; }
set
{
if (_localCastTimeStamp != value)
{
NotifyPropertyChanging("LocalCastTimeStamp");
_localCastTimeStamp = value;
NotifyPropertyChanged("LocalCastTimeStamp");
}
}
}
// This means submitted towards a pitch?
private bool _submitted;
[Column]
public bool Submitted
{
get { return _submitted; }
set
{
if (_submitted != value)
{
NotifyPropertyChanging("Submitted");
_submitted = value;
NotifyPropertyChanged("Submitted");
}
}
}
// Version column aids update performance.
[Column(IsVersion = true)]
private Binary _version;
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify that a property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify that a property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
namespace JumpAndRun.API
{
public interface IItem
{
string Name { get; }
Vector3 Position { get; set; }
Texture2D Texture { get; }
float Rotation { get; set; }
Dictionary<string, IAnimation> Animations { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Contract;
using DataBase;
using System.Data.Entity;
using Newtonsoft.Json;
namespace Rest_Service
{
/// <summary>
/// This class contains methods that implement IContract interface
/// </summary>
public class MyService : IContract
{
/// <summary>
/// This method returns Json string with all users information
/// </summary>
/// <returns></returns>
public string GetAll()
{
DBRest db = new DBRest();
var users = db.Users.Select(p => new { p.NickName, p.FullName });
/*from p in db.Users
select p.NickName + " " + p.FullName;*/
string serialized = JsonConvert.SerializeObject(users);
return serialized;
}
/// <summary>
/// This method returns Json string with a user information
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public string GetOne(string command)
{
DBRest db = new DBRest();
var users1 = db.Users.Select(p => new { p.NickName, p.FullName }).Where(p => p.NickName == command);
string serialized1 = JsonConvert.SerializeObject(users1);
return serialized1;
}
/// <summary>
/// This method returns Json string with add procedure result
/// </summary>
/// <param name="command1"></param>
/// <param name="command2"></param>
/// <returns></returns>
public string AddUser(string command1, string command2)
{
DBRest db = new DBRest();
string serialized1, serialized2;
try
{
db.Users.Add(new User { NickName = command1, FullName = command2 });
db.SaveChanges();
string answer1 = "Operation successful!";
serialized1 = JsonConvert.SerializeObject(answer1);
}
catch (Exception ex)
{
string answer2 = "Operation failed!" + ex.Message;
serialized2 = JsonConvert.SerializeObject(answer2);
return serialized2;
}
return serialized1;
}
/// <summary>
/// This method returns Json string with delete procedure result
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public string DelUser(string command)
{
DBRest db = new DBRest();
string serialized1, serialized2;
try
{
var deleted = db.Users.Where(p => p.NickName == command).FirstOrDefault();
db.Users.Remove(deleted);
db.SaveChanges();
string answer1 = "Operation successful!";
serialized1 = JsonConvert.SerializeObject(answer1);
}
catch (Exception ex)
{
string answer2 = "Operation failed!" + ex.Message;
serialized2 = JsonConvert.SerializeObject(answer2);
return serialized2;
}
return serialized1;
}
/// <summary>
/// This method returns Json string with update procedure result
/// </summary>
/// <param name="command1"></param>
/// <param name="command2"></param>
/// <param name="command3"></param>
/// <returns></returns>
public string PutUser(string command1, string command2, string command3)
{
DBRest db = new DBRest();
string serialized1, serialized2;
try
{
var deleted = db.Users.Where(p => p.NickName == command1).FirstOrDefault();
db.Users.Remove(deleted);
db.Users.Add(new User { NickName = command2, FullName = command3 });
db.SaveChanges();
string answer1 = "Operation successful!";
serialized1 = JsonConvert.SerializeObject(answer1);
}
catch (Exception ex)
{
string answer2 = "Operation failed!" + ex.Message;
serialized2 = JsonConvert.SerializeObject(answer2);
return serialized2;
}
return serialized1;
}
}
}
|
public class RichTextTag
{
private const string OpenBracket = "<";
private const string CloseBracket = ">";
private const string ParameterDelimeter = "=";
private const string EndTagDelimeter = "/";
public string tagType = "";
public string parameters = "";
public RichTextTag(string tag)
{
if (IsTag(tag))
{
if (HasParameters(tag))
{
int indexStart = tag.IndexOf(OpenBracket);
int indexEnd = tag.IndexOf(ParameterDelimeter) - 1;
int typeLength = indexEnd - indexStart;
tagType = tag.Substring(indexStart + 1, typeLength);
int indexParamDelimiter = tag.IndexOf(ParameterDelimeter);
int indexParamEnd = tag.IndexOf(CloseBracket) - 1;
int paramLength = indexParamEnd - indexParamDelimiter;
parameters = tag.Substring(indexParamDelimiter + 1, paramLength);
}
else
{
int indexStart = tag.IndexOf(OpenBracket);
int indexEnd = tag.IndexOf(CloseBracket) - 1;
int typeLength = indexEnd - indexStart;
tagType = tag.Substring(indexStart + 1, typeLength);
}
}
}
public string OpeningTag
{
get
{
if (!parameters.IsEmpty())
{
return string.Format("<{0}={1}>", tagType, parameters);
}
else
{
return string.Format("<{0}>", tagType);
}
}
}
public string ClosingTag
{
get
{
return string.Format("</{0}>", tagType);
}
}
public static bool IsTag(string tag)
{
bool openTagFormat = tag.StartsWith(OpenBracket) && tag.EndsWith(CloseBracket) && !tag.Contains(EndTagDelimeter);
return openTagFormat && tag.Length >= 3;
}
public bool IsClosingTag(string tag)
{
bool endTagFormat = tag.StartsWith(OpenBracket + EndTagDelimeter) && tag.EndsWith(CloseBracket);
int indexStart = tag.IndexOf(EndTagDelimeter);
int indexEnd = tag.IndexOf(CloseBracket) - 1;
int typeLength = indexEnd - indexStart;
string tagType = tag.Substring(indexStart + 1, typeLength);
return endTagFormat && tag.Length >= 4 && this.tagType.Equals(tagType);
}
public bool HasParameters(string tag)
{
return tag.Contains(ParameterDelimeter);
}
}
|
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// VisualNovelToolkit /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
using UnityEngine;
using UnityEditor;
using System.Collections;
using ViNoToolkit;
[ CustomEditor(typeof( SceneCreator ))]
public class SceneCreatorInspector : Editor {
public override void OnInspectorGUI(){
DrawDefaultInspector();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DBStore.DataAccess.Data.Repository.IRepository;
using DBStore.Models;
using DBStore.Models.VModels;
using DBStore.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace DBStore.Pages.Admin.Order
{
public class ManageOrderModel : PageModel
{
private readonly IUnitOfWorkRepository _unitOfWork;
public ManageOrderModel(IUnitOfWorkRepository unitOfWork)
{
_unitOfWork = unitOfWork;
}
[BindProperty]
public List<OrderDetailsVM> orderDetailsVM { get; set; }
public void OnGet()
{
orderDetailsVM = new List<OrderDetailsVM>();
List<OrderHeader> OrderHeaderList = _unitOfWork.OrderHeader.GetAll().Where(o => o.Status.ToLower() == SD.StatusSubmitted.ToLower() || o.Status.ToLower() == SD.StatusInProcess.ToLower()).OrderByDescending(u => u.PickUpName).ToList();
foreach (OrderHeader item in OrderHeaderList)
{
OrderDetailsVM individual = new OrderDetailsVM
{
OrderHeader = item,
OrderDetails = _unitOfWork.OrderDetails.GetAll(o => o.OrderId == item.Id).ToList()
};
orderDetailsVM.Add(individual);
}
}
}
} |
//--------------------------------------------------------------------------------
/*
* This Script is used for spawning Butterflies.
* Allow input to : Restart(Load StartScene and Input User ID again)
*
* Used in Main Scene, attached to Empty GameObject "ButterflySpawner".
* Require 2 GameObject variables : Butterfly Prefab, All Paths, and 2 Transform variables : Positive/Negative Corners
* Butterfly Prefab can be found in Prefabs folder under Project Assets.
* All Paths is found in Hierarchy.
* The Corners can be found under Range in Hierarchy.
*/
//--------------------------------------------------------------------------------
using UnityEngine; // Default Unity Script (MonoBehaviour, Header, Tooltip, HideInInspector, GameOject, Transform, FindObjectOfType, Instantiate, Vector3, Quaternion, Random, Destroy, Time, Input, KeyCode)
using UnityEngine.SceneManagement; // For SceneManager
public class ButterflySpawner : MonoBehaviour
{
[Tooltip("Default: 5")]
public int TotalNumberOfButterflies = 50;
[Tooltip("In Prefabs")]
public GameObject ButterflyPrefab;
[Tooltip("Default: 1.0f")]
public float SpawningDelay = 0.25f;
public GameObject AllPaths;
[Header("For Randomization of Spawning Position")]
public Transform NegativeCorner;
public Transform PositiveCorner;
[HideInInspector]
public int CurrentNumberOfButterflies = 0;
private float SpawningTimer = 0.0f;
private EditorPath[] Array;
// Runs before Start()
private void Awake()
{
// If DataCollector is alive
if (DataCollector.Instance != null)
{
// Find the SteamVR eye GameObject and assign it to DataCollector
DataCollector.Instance.user = FindObjectOfType<SteamVR_Camera>().gameObject;
}
}
// Runs at the start of first frame
private void Start()
{
// Alternative way to get all the children
Array = AllPaths.GetComponentsInChildren<EditorPath>();
// Initial spawn Butterflies and Set their Path
for (int i = 0; i < TotalNumberOfButterflies; ++i)
{
Spawn();
}
}
// Spawn Butterfly in Random position within the corners, and Randomize a path for it to follow.
// Also Randomize Butterfly's flying speed
private void Spawn()
{
// Spawn Butterfly
GameObject Butterfly = Instantiate(ButterflyPrefab, Vector3.zero, Quaternion.identity);
CurrentNumberOfButterflies++;
// Randomize Spawning position
Butterfly.transform.position = new Vector3(
Random.Range(NegativeCorner.position.x, PositiveCorner.position.x),
Random.Range(NegativeCorner.position.y, PositiveCorner.position.y),
Random.Range(NegativeCorner.position.z, PositiveCorner.position.z));
// Randomly choose a Path from All Paths
int RandomNumber = Random.Range(0, Array.Length);
// Randomize Butterfly's Flying Speed & Rotation Speed
FlyOnPath Path = Butterfly.GetComponent<FlyOnPath>();
Path.Speed = Random.Range(Path.Speed - 3.0f, Path.Speed);
Path.RotationSpeed = Random.Range(Path.RotationSpeed - 3.0f, Path.RotationSpeed);
// Set Path in FlyOnPath Script
Path.PathToFollow = Array[RandomNumber].GetComponent<EditorPath>();
}
// Loads StartScene
private void Restart()
{
SceneManager.LoadScene("StartScene");
// Destroy current DataCollector Instance, as StartScene will have its new instance of DataCollector
Destroy(DataCollector.Instance.gameObject);
}
// Update is called once per frame
private void Update()
{
// Spawn Butterfly when Current Number of Butterflies is less than Total Number of Butterflies allowed
if(CurrentNumberOfButterflies < TotalNumberOfButterflies)
{
SpawningTimer += Time.deltaTime;
// When Reached Spawning Time
if(SpawningTimer >= SpawningDelay)
{
Spawn();
// Reset Timer
SpawningTimer = 0.0f;
}
}
// Proceed to Restart if 'R' is pressed
if (Input.GetKey(KeyCode.R))
{
Restart();
}
}
}
|
namespace _8.MapDistricts
{
using System;
using System.Linq;
public class Startup
{
public static void Main(string[] args)
{
var input = Console.ReadLine();
var bound = long.Parse(Console.ReadLine());
input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(c =>
{
var arguments = c.Split(':');
var cityCode = arguments[0];
var population = long.Parse(arguments[1]);
return new {cityCode, population};
})
.GroupBy(c => c.cityCode, c => c.population,
(city, popul) => new
{
CityCode = city, Populations = popul.ToList()
})
.Where(x => x.Populations.Sum() >= bound)
.OrderByDescending(x => x.Populations.Sum())
.ToList()
.ForEach(x => Console.WriteLine($"{x.CityCode}: {string.Join(" ", x.Populations.OrderByDescending(o => o).Take(5))}"));
}
}
}
|
namespace PDV.DAO.Entidades
{
public class RegimeTributario
{
public decimal Codigo { get; set; }
public string Descricao { get; set; }
public RegimeTributario()
{
}
public RegimeTributario(decimal _Codigo, string _Descricao)
{
Codigo = _Codigo;
Descricao = _Descricao;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Button_Manager : MonoBehaviour
{
private void Start()
{
}
void Update()
{
}
public void StartButton()
{
SceneManager.LoadScene("INGAME");
}
public void ExitButton()
{
Debug.Log("Exit");
Application.Quit();
}
}
|
namespace Plus.Communication.Packets.Outgoing.Catalog
{
public class VoucherRedeemOkComposer : MessageComposer
{
public VoucherRedeemOkComposer()
: base(ServerPacketHeader.VoucherRedeemOkMessageComposer)
{
}
public override void Compose(ServerPacket packet)
{
packet.WriteString(""); //productName
packet.WriteString(""); //productDescription
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.Entity;
using Countries.Data;
namespace Countries.App
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Data.CountriesViewModel copy;
public MainWindow()
{
InitializeComponent();
this.DataContext = new Data.CountriesViewModel();
this.copy = new Data.CountriesViewModel();
}
private void Countries_SaveChangesButton(object sender, RoutedEventArgs e)
{
var dataContext = (Data.CountriesViewModel)this.CountriesGrid.DataContext;
foreach (var country in dataContext.Countries)
{
SaveCountryIfChanged(country);
}
}
private void Towns_SaveChangesButton(object sender, RoutedEventArgs e)
{
var dataContext = (Data.CountriesViewModel)this.TownsGrid.DataContext;
foreach (var town in dataContext.Towns)
{
SaveTownIfChanged(town);
}
}
private void SaveTownIfChanged(Town town)
{
var cachedCopy = this.copy.Towns.FirstOrDefault(t => t.Id == town.Id);
if (cachedCopy == null)
{
using (var context = new Data.WorldEntities())
{
context.Towns.Add(new Town
{
Name = town.Name
});
}
}
if (cachedCopy.Name != town.Name)
{
using (var context = new Data.WorldEntities())
{
var townInDb = context.Towns.Find(town.Id);
townInDb.Name = town.Name;
context.SaveChanges();
}
}
}
private void SaveCountryIfChanged(Country country)
{
var cachedCopy = this.copy.Countries.FirstOrDefault(c => c.Id == country.Id);
if (cachedCopy == null)
{
using (var context = new Data.WorldEntities())
{
context.Countries.Add(new Country
{
Name = country.Name,
Population = country.Population
});
}
}
if (cachedCopy.Name != country.Name || cachedCopy.Population != country.Population)
{
using (var context = new Data.WorldEntities())
{
var countryInDb = context.Countries.Find(country.Id);
countryInDb.Name = country.Name;
countryInDb.Population = country.Population;
context.SaveChanges();
}
}
}
}
}
|
using System.ComponentModel;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace JKMWCFService
{
/// <summary>
/// Interface Name : ICustomer
/// Author : Ranjana Singh
/// Creation Date : 27 Nov 2017
/// Purpose : Contains all information of Customers.
/// Revision :
/// </summary>
/// <returns></returns>
[ServiceContract]
public interface ICustomer
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{email}")]
string GetCustomerID(string email);
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{customerID}/profile")]
string GetCustomerProfileData(string customerID);
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{customerID}/verification")]
string GetCustomerVerificationData(string customerID);
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{customerID}/profile")]
string PostCustomerProfileData(string customerID);
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{customerID}/verification")]
string PostCustomerVerificationData(string customerID);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{customerID}/profile")]
string PutCustomerProfileData(string customerID, CustomerProfile customerProfile);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{customerID}/verification")]
string PutCustomerVerificationData(string customerID, CustomerVerification customerVerification);
}
[DataContract]
public class CustomerProfile
{
// Customer Profile fields
[DataMember]
public string CustomerId { get; set; }
[DataMember]
public bool TermsAgreed { get; set; }
// My Account fields
[DataMember]
public string Phone { get; set; }
[DataMember]
public string PreferredContact { get; set; }
[DataMember]
public string ReceiveNotifications { get; set; }
}
[DataContract]
public class CustomerVerification
{
[DataMember]
public string CustomerId { get; set; }
[DataMember]
public string PasswordHash { get; set; }
[DataMember]
public string PasswordSalt { get; set; }
}
}
|
using System.Web.Mvc;
using Logs.Authentication.Contracts;
using Logs.Services.Contracts;
using Logs.Web.Areas.Administration.Controllers;
using Moq;
using NUnit.Framework;
using TestStack.FluentMVCTesting;
namespace Logs.Web.Tests.Controllers.Administration.UserAdministrationControllerTests
{
[TestFixture]
public class BanTests
{
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", 1)]
[TestCase("99ae8dd3-1067-4141-9675-62e94bb6caaa", 2)]
public void TestBan_ShouldCallAuthProviderBanUser(string userId, int page)
{
// Arrange
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var mockedUserService = new Mock<IUserService>();
var controller = new UserAdministrationController(mockedUserService.Object, mockedAuthenticationProvider.Object);
// Act
controller.Ban(userId, page);
// Assert
mockedAuthenticationProvider.Verify(p => p.BanUser(userId), Times.Once);
}
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", 1)]
[TestCase("99ae8dd3-1067-4141-9675-62e94bb6caaa", 2)]
public void TestBan_ShouldReturnRedirectToActionWithCorrectPage(string userId, int page)
{
// Arrange
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
var mockedUserService = new Mock<IUserService>();
var controller = new UserAdministrationController(mockedUserService.Object, mockedAuthenticationProvider.Object);
// Act, Assert
controller
.WithCallTo(c => c.Ban(userId, page))
.ShouldRedirectTo(c => c.Index(page, It.IsAny<int>()));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GraphicHeightChange : MonoBehaviour
{
private float gravity = 1f;
private float velocity = 0f;
private float t = 0f;
void Update()
{
float heightTarget = -1 + GameManager.instance.Height.heightCurrent;
if (transform.localPosition.y != heightTarget)
{
transform.localPosition = new Vector3(0f, Mathf.Lerp(transform.localPosition.y, heightTarget, t), 0f);
t += velocity * Time.deltaTime;
velocity += gravity;
}
else
{
t = 0.0f;
velocity = 0f;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Tivo.Hme.Samples
{
class TicTacToe : HmeApplicationHandler
{
Application _app;
View _piecesView;
TextStyle _tokenStyle = new TextStyle("default", FontStyle.Bold, 72);
TextView[,] _pieces = new TextView[3, 3];
int _gridX;
int _gridY;
int movesElapsed = 0;
static TicTacToe()
{
Application.Images.Add("background", Properties.Resources.bg, Properties.Resources.bg.RawFormat);
Application.Images.Add("grid", Properties.Resources.grid, Properties.Resources.grid.RawFormat);
}
public override void OnApplicationStart(HmeApplicationStartArgs e)
{
_app = e.Application;
_app.Root = new ImageView(_app.GetImageResource("background"));
_piecesView = new View();
_piecesView.Bounds = _app.Root.Bounds;
_app.Root.Children.Add(_piecesView);
_gridX = (_app.Root.Bounds.Width - 300) / 2;
_gridY = 130;
ImageView grid = new ImageView(_app.GetImageResource("grid"));
grid.Bounds = new Rectangle(_gridX - 5, _gridY - 5, 310, 310);
_app.Root.Children.Add(grid);
_app.CreateTextStyle(_tokenStyle);
_app.KeyPress += new EventHandler<KeyEventArgs>(_app_KeyPress);
}
public override void OnApplicationEnd()
{
}
void _app_KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode >= KeyCode.Num1 && e.KeyCode <= KeyCode.Num9)
{
int movePosition = (int)e.KeyCode - (int)KeyCode.Num1;
// convert pos to x/y and make a move
MakeMove(movePosition % 3, movePosition / 3);
e.Handled = true;
}
else if (e.KeyCode == KeyCode.Left)
{
e.Handled = true;
_app.Close();
}
else
{
_app.GetSound("bonk").Play();
}
}
private void MakeMove(int x, int y)
{
// is this a valid move?
if (_pieces[x, y] != null)
{
_app.GetSound("bonk").Play();
return;
}
int player = (movesElapsed++) % 2;
// create the piece
_pieces[x, y] = CreatePiece(player, x, y);
bool victory = IsVictory();
bool draw = !victory && movesElapsed == 9;
if (victory || draw)
{
_app.GetSound(victory ? "tivo" : "thumbsdown").Play();
System.Threading.Thread.Sleep(2000);
TimeSpan sec1 = TimeSpan.FromSeconds(1);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
View piece = _pieces[i, j];
if (piece != null)
{
Animation animation = new Animation();
if (victory)
animation.AddMove(piece.Location + new Size((i - 1) * 400, (j - 1) * 300), 0, sec1);
animation.AddFade(1, 0, sec1);
piece.Animate(animation);
_piecesView.Children.Remove(piece, sec1);
_pieces[i, j] = null;
}
}
}
movesElapsed = 0;
}
}
private bool IsVictory()
{
for (int i = 0; i < 3; ++i)
{
if (IsVictoryRun(0, i, 1, 0) || IsVictoryRun(i, 0, 0, 1))
return true;
}
return IsVictoryRun(0, 0, 1, 1) || IsVictoryRun(0, 2, 1, -1);
}
private bool IsVictoryRun(int ox, int oy, int dx, int dy)
{
int x = ox;
int y = oy;
for (int i = 0; i < 3; ++i)
{
if (_pieces[x, y] == null)
return false;
if (i > 0 && _pieces[x, y].Text != _pieces[x - dx, y - dy].Text)
return false;
x += dx;
y += dy;
}
// win - highlight pieces
x = ox;
y = oy;
for (int i = 0; i < 3; ++i)
{
_pieces[x, y].Update(_pieces[x, y].Text, _tokenStyle, Color.FromArgb(0xff, 0xa0, 0x00));
x += dx;
y += dy;
}
return true;
}
private TextView CreatePiece(int player, int x, int y)
{
string token = (player == 0) ? "X" : "O";
TextView piece = new TextView(token, _tokenStyle, Color.White);
piece.Bounds = new Rectangle(_gridX + x * 100, _gridY + y * 100, 100, 100);
_piecesView.Children.Add(piece);
return piece;
}
}
//class TicTacToe : IDisposable
//{
// HmeServer _server = new HmeServer("Tic Tac Toe", new Uri("http://localhost:7688/TicTacToe"));
// public TicTacToe()
// {
// Application.Images.Add("background", Properties.Resources.bg, Properties.Resources.bg.RawFormat);
// Application.Images.Add("grid", Properties.Resources.grid, Properties.Resources.grid.RawFormat);
// _server.ApplicationConnected += new EventHandler<HmeApplicationConnectedEventArgs>(_server_ApplicationConnected);
// _server.Start();
// }
// #region IDisposable Members
// public void Dispose()
// {
// _server.Stop();
// }
// #endregion
// void _server_ApplicationConnected(object sender, HmeApplicationConnectedEventArgs e)
// {
// new TicTacToeClientManager(e.Application);
// }
// private class TicTacToeClientManager
// {
// Application _app;
// View _piecesView;
// TextStyle _tokenStyle = new TextStyle("default", FontStyle.Bold, 72);
// TextView[,] _pieces = new TextView[3, 3];
// int _gridX;
// int _gridY;
// int movesElapsed = 0;
// public TicTacToeClientManager(Application app)
// {
// _app = app;
// _app.Root = new ImageView(_app.GetImageResource("background"));
// _piecesView = new View();
// _piecesView.Bounds = _app.Root.Bounds;
// _app.Root.Children.Add(_piecesView);
// _gridX = (_app.Root.Bounds.Width - 300) / 2;
// _gridY = 130;
// ImageView grid = new ImageView(_app.GetImageResource("grid"));
// grid.Bounds = new Rectangle(_gridX - 5, _gridY - 5, 310, 310);
// _app.Root.Children.Add(grid);
// _app.CreateTextStyle(_tokenStyle);
// _app.KeyPress += new EventHandler<KeyEventArgs>(_app_KeyPress);
// }
// void _app_KeyPress(object sender, KeyEventArgs e)
// {
// if (e.KeyCode >= KeyCode.Num1 && e.KeyCode <= KeyCode.Num9)
// {
// int movePosition = (int)e.KeyCode - (int)KeyCode.Num1;
// // convert pos to x/y and make a move
// MakeMove(movePosition % 3, movePosition / 3);
// e.Handled = true;
// }
// else if (e.KeyCode == KeyCode.Left)
// {
// e.Handled = true;
// _app.Dispose();
// }
// else
// {
// _app.GetSound("bonk").Play();
// }
// }
// private void MakeMove(int x, int y)
// {
// // is this a valid move?
// if (_pieces[x, y] != null)
// {
// _app.GetSound("bonk").Play();
// return;
// }
// int player = (movesElapsed++) % 2;
// // create the piece
// _pieces[x, y] = CreatePiece(player, x, y);
// bool victory = IsVictory();
// bool draw = !victory && movesElapsed == 9;
// if (victory || draw)
// {
// _app.GetSound(victory ? "tivo" : "thumbsdown").Play();
// System.Threading.Thread.Sleep(2000);
// TimeSpan sec1 = TimeSpan.FromSeconds(1);
// for (int i = 0; i < 3; ++i)
// {
// for (int j = 0; j < 3; ++j)
// {
// View piece = _pieces[i, j];
// if (piece != null)
// {
// Animation animation = new Animation();
// if (victory)
// animation.AddMove(piece.Location + new Size((i - 1) * 400, (j - 1) * 300), 0, sec1);
// animation.AddFade(1, 0, sec1);
// piece.Animate(animation);
// _piecesView.Children.Remove(piece, sec1);
// _pieces[i, j] = null;
// }
// }
// }
// movesElapsed = 0;
// }
// }
// private bool IsVictory()
// {
// for (int i = 0; i < 3; ++i)
// {
// if (IsVictoryRun(0, i, 1, 0) || IsVictoryRun(i, 0, 0, 1))
// return true;
// }
// return IsVictoryRun(0, 0, 1, 1) || IsVictoryRun(0, 2, 1, -1);
// }
// private bool IsVictoryRun(int ox, int oy, int dx, int dy)
// {
// int x = ox;
// int y = oy;
// for (int i = 0; i < 3; ++i)
// {
// if (_pieces[x, y] == null)
// return false;
// if (i > 0 && _pieces[x, y].Text != _pieces[x - dx, y - dy].Text)
// return false;
// x += dx;
// y += dy;
// }
// // win - highlight pieces
// x = ox;
// y = oy;
// for (int i = 0; i < 3; ++i)
// {
// _pieces[x, y].Update(_pieces[x, y].Text, _tokenStyle, Color.FromArgb(0xff, 0xa0, 0x00));
// x += dx;
// y += dy;
// }
// return true;
// }
// private TextView CreatePiece(int player, int x, int y)
// {
// string token = (player == 0) ? "X" : "O";
// TextView piece = new TextView(token, _tokenStyle, Color.White);
// piece.Bounds = new Rectangle(_gridX + x * 100, _gridY + y * 100, 100, 100);
// _piecesView.Children.Add(piece);
// return piece;
// }
// }
//}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using HelperLibrary.Models;
using Microsoft.AspNetCore.Mvc;
using ConnectLibrary.Service;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace WebLectionAPI.Controllers
{
[Route("api/[controller]")]
public class StudentGradesController : Controller
{
CommonService studentGrades = new CommonService();
// GET: api/<controller>
[HttpGet]
public ActionResult<IEnumerable<IGrouping<string, CommonModel>>> Get()
{
JsonResult json = new JsonResult(studentGrades.FindStudentGrades());
return json;
}
// GET api/<controller>/5
[HttpGet("{studentName}")]
public ActionResult<string> Get(string studentName)
{
JsonResult json = new JsonResult(studentGrades.GetAmountOfVisitedLections(studentName, false));
return json;
}
// GET api/<controller>/5
[HttpGet("{subject},{lecturer}")]
public ActionResult<string> Get(string subject, string lecturer)
{
JsonResult json = new JsonResult(studentGrades.GetAmountOfVisitedLections(subject, lecturer, false));
return json;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StartWaveTrigger : MonoBehaviour
{
public static StartWaveTrigger m_instance;
public bool canStartWave = true;
private void Awake()
{
m_instance = this;
}
private void Start()
{
canStartWave = true;
}
private void OnTriggerEnter(Collider other)
{
if (canStartWave)
{
if(other.tag == "Player")
{
WavesManager.instance.StartWaveSystem();
}
canStartWave = false;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PathTileScript : MonoBehaviour
{
public const int NORTH = 0;
public const int EAST = 1;
public const int SOUTH = 2;
public const int WEST = 3;
public bool m_north;
public bool m_south;
public bool m_west;
public bool m_east;
public List<GameObject> m_PathNorth = new List<GameObject>();
public List<GameObject> m_PathEast = new List<GameObject>();
public List<GameObject> m_PathSouth = new List<GameObject>();
public List<GameObject> m_PathWest = new List<GameObject>();
public List<GameObject> m_ParentObject=new List<GameObject>();
public List<int> m_ParentDirection = new List<int>();
private bool[] m_directions;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public bool GetDirection(int index)
{
switch (index)
{
case NORTH: return m_north;
case SOUTH: return m_south;
case EAST: return m_east;
case WEST: return m_west;
}
return false;
}
public List<GameObject> GetPath(int index)
{
switch (index)
{
case NORTH: return m_PathNorth;
case SOUTH: return m_PathSouth;
case EAST: return m_PathEast;
case WEST: return m_PathWest;
}
return null;
}
public void Rotate()
{
bool northCopy = m_north;
m_north = m_west;
m_west = m_south;
m_south = m_east;
m_east = northCopy;
List<GameObject> pathCopy = m_PathNorth;
m_PathNorth = m_PathWest;
m_PathWest = m_PathSouth;
m_PathSouth = m_PathEast;
m_PathEast = pathCopy;
}
}
|
using System.IO;
namespace JarvOS
{
public class WundergroundAPIKey
{
public static WundergroundAPIKey Instance
{
get
{
if (m_instance == null)
{
m_instance = new WundergroundAPIKey();
}
return m_instance;
}
}
private static WundergroundAPIKey m_instance;
/// <summary>
/// Gets Wunderground API Key from file.
/// Returns null if file cannot be found.
/// <summary>
public string Key
{
get
{
if (key == null)
{
var path = Directory.GetCurrentDirectory() + "/api_keys/wunderground.txt";
key = File.ReadAllText(path);
}
return key;
}
}
private WundergroundAPIKey() {}
public string key = null;
}
} |
namespace MvcExample.DTO.User
{
public class UserDto
{
public string UserName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Fullname => $"{Firstname} {Lastname}";
}
}
|
using System.Collections.Generic;
using System.Text;
using System.IO;
using System;
using System.Windows.Forms;
using System.Drawing;
namespace Wc3Engine
{
class W3I
{
internal const string FILE_NAME = "war3map.w3i";
private const int BYTES_TO_SKIP = 12;
public static byte[] bytes = null;
private static List<string> list = new List<string>();
public static string mapName = null;
public static string mapPlayers = null;
public static string mapAutor = null;
public static string mapDescription = null;
public static string RichTextBoxFormat()
{
return "|c00FEBA0EName:|r " + WTS.Get(mapName) + "|n|n" +
"|c00FEBA0EPlayers:|r " + WTS.Get(mapPlayers) + "|n|n" +
"|c00FEBA0EAutor:|r " + WTS.Get(mapAutor) + "|n|n" +
"|c00FEBA0EDescription:|r|n|n" + WTS.Get(mapDescription);
}
byte[] header = new byte[] {
0, // file format version = 18
0, // number of saves (map version)
0, // editor version (little endian)
};
public enum MapInfo : byte
{
/// <summary>
/// No color map was included in the file.
/// </summary>
NO_COLOR_MAP = 0,
/// <summary>
/// Color map was included in the file.
/// </summary>
COLOR_MAP_INCLUDED = 1
}
public static void Read()
{
ShowLabel(true);
bytes = MPQ.File.Read(FILE_NAME, Map.mpq);
BinaryUtility.bytePosition = BYTES_TO_SKIP;
mapName = BinaryUtility.GetSecuentialString(bytes, Encoding.ASCII, 1);
mapAutor = BinaryUtility.GetSecuentialString(bytes, Encoding.ASCII, 1);
mapDescription = BinaryUtility.GetSecuentialString(bytes, Encoding.ASCII, 1);
mapPlayers = BinaryUtility.GetSecuentialString(bytes, Encoding.ASCII, 1);
Tooltip.Print(Wc3Engine.This.mapDescription_richTextBox, RichTextBoxFormat(), true);
}
public static void Write(string key, string value)
{
//bytes = BinaryUtility.ReplaceTextInBytes(bytes, "TRIGSTR_001", "Hello???");
if (mapName == key)
{
WTS.Set(mapName, value);
//Wc3Color.RenderText(value, Launcher.Handle.mapName_pictureBox);
}
else if (mapPlayers == key)
{
WTS.Set(mapPlayers, value);
//Wc3Color.RenderText(value, Launcher.Handle.mapPlayers_pictureBox);
}
else if (mapAutor == key)
{
WTS.Set(mapAutor, value);
//Wc3Color.RenderText(value, Launcher.Handle.mapAutor_pictureBox);
}
else if (mapDescription == key)
{
WTS.Set(mapDescription, value);
}
Tooltip.Print(Wc3Engine.This.mapDescription_richTextBox, RichTextBoxFormat(), true);
}
/*
private static string SecuentialRead()
{
List<byte> list = new List<byte>();
byte currentByte = Buffer.GetByte(bytes, BYTES_TO_SKIP);
while (currentByte != 0)
{
list.Add(currentByte);
bytePosition++;
currentByte = Buffer.GetByte(bytes, bytePosition);
}
bytePosition++;
string result = Encoding.ASCII.GetString(list.ToArray());
list.Clear();
return result;
}*/
public static void ShowLabel(bool flag)
{
//Launcher.Handle.mapName_pictureBox.Visible = flag;
//Launcher.Handle.mapAutor_pictureBox.Visible = flag;
//Launcher.Handle.mapDescription_pictureBox.Visible = flag;
//Launcher.Handle.mapPlayers_pictureBox.Visible = flag;
}
public static void ShowEditBox(bool flag)
{
ShowLabel(!flag);
Wc3Engine.This.mapName_textBox.Text = WTS.Get(mapName);
Wc3Engine.This.mapAutor_textBox.Text = WTS.Get(mapAutor);
Wc3Engine.This.mapDescription_richTextBox.Text = WTS.Get(mapDescription);
Wc3Engine.This.mapPlayers_textBox.Text = WTS.Get(mapPlayers);
Wc3Engine.This.mapName_textBox.Visible = flag;
Wc3Engine.This.mapAutor_textBox.Visible = flag;
Wc3Engine.This.mapDescription_richTextBox.Visible = flag;
Wc3Engine.This.mapPlayers_textBox.Visible = flag;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DomainValueAttribute.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using CGI.Reflex.Core.Entities;
namespace CGI.Reflex.Core.Attributes
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class DomainValueAttribute : Attribute
{
private readonly DomainValueCategory _category;
public DomainValueAttribute(DomainValueCategory category)
{
_category = category;
}
public DomainValueCategory Category
{
get { return _category; }
}
}
} |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using NameSearch.Models.Entities;
using System;
using NameSearch.Models.Entities.Abstracts;
using System.Threading.Tasks;
using System.Threading;
namespace NameSearch.Context
{
/// <summary>
/// Application Entity Framework Database Context
/// </summary>
/// <seealso cref="Microsoft.EntityFrameworkCore.DbContext" />
public class ApplicationDbContext : DbContext
{
/// <summary>
/// The connection string
/// </summary>
private readonly string connectionString;
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationDbContext"/> class.
/// </summary>
public ApplicationDbContext()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
connectionString = configuration.GetConnectionString("DefaultConnection");
}
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationDbContext"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public ApplicationDbContext(string connectionString)
{
this.connectionString = connectionString;
}
/// <summary>
/// <para>
/// Override this method to configure the database (and other options) to be used for this context.
/// This method is called for each instance of the context that is created.
/// </para>
/// <para>
/// In situations where an instance of <see cref="T:Microsoft.EntityFrameworkCore.DbContextOptions" /> may or may not have been passed
/// to the constructor, you can use <see cref="P:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.IsConfigured" /> to determine if
/// the options have already been set, and skip some or all of the logic in
/// <see cref="M:Microsoft.EntityFrameworkCore.DbContext.OnConfiguring(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)" />.
/// </para>
/// </summary>
/// <param name="optionsBuilder">A builder used to create or modify options for this context. Databases (and other extensions)
/// typically define extension methods on this object that allow you to configure the context.</param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(connectionString);
}
//Declare public Entities
/// <summary>
/// Gets or sets the addresses.
/// </summary>
/// <value>
/// The addresses.
/// </value>
public DbSet<Address> Addresses { get; set; }
/// <summary>
/// Gets or sets the associates.
/// </summary>
/// <value>
/// The associates.
/// </value>
public DbSet<Associate> Associates { get; set; }
/// <summary>
/// Gets or sets the people.
/// </summary>
/// <value>
/// The people.
/// </value>
public DbSet<Person> People { get; set; }
/// <summary>
/// Gets or sets the phones.
/// </summary>
/// <value>
/// The phones.
/// </value>
public DbSet<Phone> Phones { get; set; }
/// <summary>
/// Gets or sets the person search results.
/// </summary>
/// <value>
/// The person search results.
/// </value>
public DbSet<PersonSearch> PersonSearchResults { get; set; }
/// <summary>
/// Override this method to further configure the model that was discovered by convention from the entity types
/// exposed in <see cref="T:Microsoft.EntityFrameworkCore.DbSet`1" /> properties on your derived context. The resulting model may be cached
/// and re-used for subsequent instances of your derived context.
/// </summary>
/// <param name="modelBuilder">The builder being used to construct the model for this context. Databases (and other extensions) typically
/// define extension methods on this object that allow you to configure aspects of the model that are specific
/// to a given database.</param>
/// <remarks>
/// If a model is explicitly set on the options for this context (via <see cref="M:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseModel(Microsoft.EntityFrameworkCore.Metadata.IModel)" />)
/// then this method will not be run.
/// </remarks>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//Filter Inactive Records
modelBuilder.Entity<Address>().HasQueryFilter(p => p.IsActive);
modelBuilder.Entity<Associate>().HasQueryFilter(p => p.IsActive);
modelBuilder.Entity<Person>().HasQueryFilter(p => p.IsActive);
modelBuilder.Entity<PersonSearch>().HasQueryFilter(p => p.IsActive);
modelBuilder.Entity<Phone>().HasQueryFilter(p => p.IsActive);
//Cascading deletes will not work with soft deletes. The cascade only happens as the delete command is issued to the database.
//.OnDelete(DeleteBehavior.Cascade)
//modelBuilder.Entity<Person>()
// .HasMany(a => a.Addresses)
// .WithOne(p => p.Person)
// .IsRequired(false);
//modelBuilder.Entity<Person>()
// .HasMany(a => a.Phones)
// .WithOne(p => p.Person)
// .IsRequired(false);
//modelBuilder.Entity<Person>()
// .HasMany(a => a.Associates)
// .WithOne(p => p.Person)
// .IsRequired(false);
//modelBuilder.Entity<Person>()
// .HasOne(a => a.PersonSearchResult)
// .WithOne(p => p.Person)
// .IsRequired(false);
//modelBuilder.Entity<PersonSearchJob>()
// .HasMany(a => a.PersonSearchResults)
// .WithOne(p => p.PersonSearchJob)
// .IsRequired(true);
}
/// <summary>
/// Saves all changes made in this context to the database.
/// </summary>
/// <returns>
/// The number of state entries written to the database.
/// </returns>
/// <remarks>
/// This method will automatically call <see cref="M:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </remarks>
public override int SaveChanges()
{
OnBeforeSaving();
return base.SaveChanges();
}
/// <summary>
/// Saves all changes made in this context to the database.
/// </summary>
/// <param name="acceptAllChangesOnSuccess">Indicates whether <see cref="M:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AcceptAllChanges" /> is called after the changes have
/// been sent successfully to the database.</param>
/// <returns>
/// The number of state entries written to the database.
/// </returns>
/// <remarks>
/// This method will automatically call <see cref="M:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </remarks>
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
OnBeforeSaving();
return base.SaveChanges(acceptAllChangesOnSuccess);
}
/// <summary>
/// Asynchronously saves all changes made in this context to the database.
/// </summary>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous save operation. The task result contains the
/// number of state entries written to the database.
/// </returns>
/// <remarks>
/// <para>
/// This method will automatically call <see cref="M:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </para>
/// </remarks>
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
OnBeforeSaving();
return base.SaveChangesAsync(cancellationToken);
}
/// <summary>
/// Asynchronously saves all changes made in this context to the database.
/// </summary>
/// <param name="acceptAllChangesOnSuccess">Indicates whether <see cref="M:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AcceptAllChanges" /> is called after the changes have
/// been sent successfully to the database.</param>
/// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to complete.</param>
/// <returns>
/// A task that represents the asynchronous save operation. The task result contains the
/// number of state entries written to the database.
/// </returns>
/// <remarks>
/// <para>
/// This method will automatically call <see cref="M:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges" /> to discover any
/// changes to entity instances before saving to the underlying database. This can be disabled via
/// <see cref="P:Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled" />.
/// </para>
/// <para>
/// Multiple active operations on the same context instance are not supported. Use 'await' to ensure
/// that any asynchronous operations have completed before calling another method on this context.
/// </para>
/// </remarks>
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
OnBeforeSaving();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
/// <summary>
/// Soft Deletes and Record Level Auditing.
/// See also https://www.meziantou.net/2017/07/10/entity-framework-core-soft-delete-using-query-filters
/// </summary>
private void OnBeforeSaving()
{
var now = DateTime.Now;
var entries = ChangeTracker.Entries();
foreach (var entry in entries)
{
var entity = entry.Entity as AuditableEntityBase;
switch (entry.State)
{
case EntityState.Added:
entity.CreatedDateTime = now;
entity.IsActive = true;
break;
case EntityState.Modified:
entity.ModifiedDateTime = now;
break;
case EntityState.Deleted:
entity.ModifiedDateTime = now;
entity.IsActive = false;
//Modify instead of deleting
entry.State = EntityState.Modified;
break;
}
}
}
}
}
|
using System;
namespace AbnLookup.SearchClientCSharpe {
class SoapRpcSearch : SoapSearch {
// -----------------------------------------------------------------------------------------------
// Prefix in config file
// -----------------------------------------------------------------------------------------------
protected override AppSettings.EncodingStyle Style {
get {
return AppSettings.EncodingStyle.Rpc;
}
}
// -----------------------------------------------------------------------------------------------
// Return the SOAP message for a search by ABN
// -----------------------------------------------------------------------------------------------
protected override string BuildAbnSoapMessage(string searchText, string history, string guid) {
return
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:tns=\"http://abr.business.gov.au/ABRXMLSearchRPC/\" " +
"xmlns:types=\"http://abr.business.gov.au/ABRXMLSearchRPC/encodedTypes\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
"<tns:ABRSearchByABN> " +
"<searchString xsi:type=\"xsd:string\">" + searchText + "</searchString>" +
"<includeHistoricalDetails xsi:type=\"xsd:string\">" + history + "</includeHistoricalDetails>" +
"<authenticationGuid xsi:type=\"xsd:string\">" + guid + "</authenticationGuid>" +
"</tns:ABRSearchByABN>" +
"</soap:Body>" +
"</soap:Envelope>";
}
// -----------------------------------------------------------------------------------------------
// Return the SOAP message for a search by ASIC
// -----------------------------------------------------------------------------------------------
protected override string BuildAsicSoapMessage(string searchText, string history, string guid) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:tns=\"http://abr.business.gov.au/ABRXMLSearchRPC/\" " +
"xmlns:types=\"http://abr.business.gov.au/ABRXMLSearchRPC/encodedTypes\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
"<tns:ABRSearchByASIC> " +
"<searchString xsi:type=\"xsd:string\">" + searchText + "</searchString>" +
"<includeHistoricalDetails xsi:type=\"xsd:string\">" + history + "</includeHistoricalDetails>" +
"<authenticationGuid xsi:type=\"xsd:string\">" + guid + "</authenticationGuid>" +
"</tns:ABRSearchByASIC>" +
"</soap:Body>" +
"</soap:Envelope>";
}
// -----------------------------------------------------------------------------------------------
// Return the SOAP message for a search by Name
// -----------------------------------------------------------------------------------------------
protected override string BuildNameSoapMessage(string searchText, string act, string nsw, string nt, string qld, string tas, string vic, string wa, string sa, string postcode, string legalName, string tradingName, string guid) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:tns=\"http://abr.business.gov.au/ABRXMLSearchRPC/\" " +
"xmlns:types=\"http://abr.business.gov.au/ABRXMLSearchRPC/encodedTypes\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
"<tns:ABRSearchByName>" +
"<externalNameSearch href=\"#id1\"/>" +
"<authenticationGuid xsi:type=\"xsd:string\">" + guid + "</authenticationGuid>" +
"</tns:ABRSearchByName>" +
"<tns:ExternalRequestNameSearch id=\"id1\" xsi:type=\"tns:ExternalRequestNameSearch\">" +
"<AuthenticationGUID xsi:type=\"xsd:string\">" + guid + "</AuthenticationGUID>" +
"<Name xsi:type=\"xsd:string\">" + searchText + "</Name>" +
"<Filters href=\"#id2\"/>" + "</tns:ExternalRequestNameSearch>" +
"<tns:ExternalRequestFilters id=\"id2\" xsi:type=\"tns:ExternalRequestFilters\" > " +
"<NameType href=\"#id3\"/>" +
"<Postcode xsi:type=\"xsd:string\">" + postcode.Trim() + "</Postcode>" +
"<StateCode href=\"#id4\"/>" +
"</tns:ExternalRequestFilters>" +
"<tns:ExternalRequestFilterNameType id=\"id3\" xsi:type=\"tns:ExternalRequestFilterNameType\">" +
"<TradingName xsi:type=\"xsd:string\">" + tradingName + "</TradingName>" +
"<LegalName xsi:type=\"xsd:string\">" + legalName + "</LegalName>" +
"</tns:ExternalRequestFilterNameType>" +
"<tns:ExternalRequestFilterStateCode id=\"id4\" xsi:type=\"tns:ExternalRequestFilterStateCode\">" +
"<QLD xsi:type=\"xsd:string\">" + qld + "</QLD>" +
"<NT xsi:type=\"xsd:string\">" + nt + "</NT>" +
"<SA xsi:type=\"xsd:string\">" + sa + "</SA>" +
"<WA xsi:type=\"xsd:string\">" + wa + "</WA>" +
"<VIC xsi:type=\"xsd:string\">" + vic + "</VIC>" +
"<ACT xsi:type=\"xsd:string\">" + act + "</ACT>" +
"<TAS xsi:type=\"xsd:string\">" + tas + "</TAS>" +
"<NSW xsi:type=\"xsd:string\">" + nsw + "</NSW>" +
"</tns:ExternalRequestFilterStateCode>" +
"</soap:Body>" +
"</soap:Envelope>";
}
// -----------------------------------------------------------------------------------------------
// Return the SOAP message for a search by Postcode
// -----------------------------------------------------------------------------------------------
protected override string BuildPostcodeSoapMessage(string postcode, string guid) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:tns=\"http://abr.business.gov.au/ABRXMLSearchRPC/\" " +
"xmlns:types=\"http://abr.business.gov.au/ABRXMLSearchRPC/encodedTypes\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
"<tns:SearchByPostcode> " +
"<postcode xsi:type=\"xsd:string\">" + postcode + "</postcode >" +
"<authenticationGuid xsi:type=\"xsd:string\">" + guid + "</authenticationGuid>" +
"</tns:SearchByPostcode>" +
"</soap:Body>" +
"</soap:Envelope>";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aula11_MembrosEstaticos
{
public static class ConversorStatic
{
public static double CelsiusToFah(double temperatura)
{
return (temperatura * 9 / 5) + 32;
}
public static double FahToCelsius(double temperatura)
{
return (temperatura - 32) * 5/9;
}
}
public class ConversorInstancia
{
public static double temperatura;
public double CelsiusToFah()
{
return (temperatura * 9 / 5) + 32;
}
public double FahToCelsius()
{
return (temperatura - 32) * 5 / 9;
}
}
class Program
{
static void Main(string[] args)
{
var c1 = new ConversorInstancia();
var c2 = new ConversorInstancia();
ConversorInstancia.temperatura = 30;
var celsius = c1.CelsiusToFah();
ConversorInstancia.temperatura = 70;
var fah = c1.FahToCelsius();
Console.WriteLine(celsius);
Console.WriteLine(fah);
Console.ReadKey();
}
private static void TesteClasseStatic()
{
double temperatura = 35;
temperatura = ConversorStatic.CelsiusToFah(temperatura);
Console.WriteLine(temperatura);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DEMOChannel.Models
{
[Serializable]
public class DemoResponse
{
public string Message;
public DateTime Time;
public string Test;
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Aor扩展方法封装集合
///
///
/// ** 原生 GetComponentsInChildren 方法,会包含自身节点上挂在的Component;
/// GetComponentsInParent 方法,会包含自身节点上挂在的Component;
///
/// </summary>
public static class TransformExtends
{
public static void Dispose(this Transform trans) {
trans.gameObject.Dispose();
}
/// <summary>
/// 获取对象在Hierarchy中的节点路径
/// </summary>
public static string getHierarchyPath(this Transform tran) {
return _getHierarchPathLoop(tran);
}
private static string _getHierarchPathLoop(Transform t, string path = null) {
if (string.IsNullOrEmpty(path)) {
path = t.gameObject.name;
}
else {
path = t.gameObject.name + "/" + path;
}
if (t.parent != null) {
return _getHierarchPathLoop(t.parent, path);
}
else {
return path;
}
}
/// <summary>
/// 递归子节点设置Layer
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// </summary>
public static void SetLayer(this Transform tran, int layer, Func<Transform, bool> filter = null, Action<Transform> doSomething = null)
{
if (filter != null)
{
if (filter(tran))
{
tran.gameObject.layer = layer;
if (doSomething != null) doSomething(tran);
}
}
else
{
tran.gameObject.layer = layer;
if (doSomething != null) doSomething(tran);
}
if (tran.childCount > 0)
{
int i, len = tran.childCount;
for (i = 0; i < len; i++)
{
Transform sub = tran.GetChild(i);
sub.SetLayer(layer, filter, doSomething);
}
}
}
/// <summary>
/// 获取当前Transform对象上挂载的接口
/// </summary>
public static T GetInterface<T>(this Transform tran) where T : class
{
if (!typeof(T).IsInterface)
{
return null;
}
//return inObj.GetComponents<Component>().OfType<T>().FirstOrDefault();
Component[] cp = tran.gameObject.GetComponents<Component>();
int i, length = cp.Length;
for (i = 0; i < length; i++)
{
if (cp[i] is T)
{
T t = cp[i] as T;
return t;
}
}
return null;
}
/// <summary>
/// 获取当前Transform对象上挂载的接口集合
/// </summary>
public static List<T> GetInterfacesList<T>(this Transform tran) where T : class
{
if (!typeof(T).IsInterface)
{
return null;
}
Component[] cp = tran.gameObject.GetComponents<Component>();
if (cp != null && cp.Length > 0)
{
int i, len = cp.Length;
List<T> list = new List<T>();
for (i = 0; i < len; i++)
{
if (cp[i] is T)
{
T a = cp[i] as T;
list.Add(a);
}
}
if (list != null && list.Count > 0)
{
return list;
}
}
return null;
}
/// <summary>
/// 获取当前Transform对象上挂载的接口集合
/// </summary>
public static T[] GetInterfaces<T>(this Transform tran) where T : class
{
List<T> list = tran.GetInterfacesList<T>();
if (list != null)
{
return list.ToArray();
}
return null;
}
/// <summary>
/// 获取当前Transform对象或者子节点上挂载的接口集合
///
///默认API扩展,GetComponentsInChildren
///
/// </summary>
public static T GetInterfaceInChlidren<T>(this Transform tran) where T : class
{
if (!typeof(T).IsInterface)
{
return null;
}
//return inObj.GetComponents<Component>().OfType<T>().FirstOrDefault();
Component[] cp = tran.gameObject.GetComponentsInChildren<Component>();
int i, length = cp.Length;
for (i = 0; i < length; i++)
{
if (cp[i] is T)
{
T t = cp[i] as T;
return t;
}
}
return null;
}
/// <summary>
/// 获取当前Transform对象上挂载的接口集合
///
///默认API扩展,GetComponentsInChildren
///
/// </summary>
public static List<T> GetInterfacesListInChlidren<T>(this Transform tran) where T : class
{
if (!typeof(T).IsInterface)
{
return null;
}
Component[] cp = tran.gameObject.GetComponentsInChildren<Component>();
if (cp != null && cp.Length > 0)
{
int i, len = cp.Length;
List<T> list = new List<T>();
for (i = 0; i < len; i++)
{
if (cp[i] is T)
{
T t = cp[i] as T;
list.Add(t);
}
}
if (list.Count > 0)
{
return list;
}
}
return null;
}
/// <summary>
/// 获取当前Transform对象上挂载的接口集合
///
///默认API扩展,GetComponentsInChildren
///
/// </summary>
public static T[] GetInterfacesInChlidren<T>(this Transform tran) where T : class
{
List<T> list = tran.GetInterfacesListInChlidren<T>();
if (list != null)
{
return list.ToArray();
}
return null;
}
/// <summary>
/// 获取当前Transform对象上挂载的接口集合
///
/// 默认API扩展,搜索精度同GetComponentsInParent
///
/// </summary>
public static List<T> GetInterfacesListInParent<T>(this Transform tran) where T : class
{
if (!typeof(T).IsInterface)
{
return null;
}
Component[] cp = tran.gameObject.GetComponentsInParent<Component>();
if (cp != null && cp.Length > 0)
{
int i, len = cp.Length;
List<T> list = new List<T>();
for (i = 0; i < len; i++)
{
if (cp[i] is T)
{
T t = cp[i] as T;
list.Add(t);
}
}
if (list.Count > 0)
{
return list;
}
}
return null;
}
/// <summary>
/// 获取当前Transform对象上挂载的接口集合
///
/// 默认API扩展,搜索精度同GetComponentsInParent
///
/// </summary>
public static T[] GetInterfacesInParent<T>(this Transform tran) where T : class
{
List<T> list = tran.GetInterfacesListInParent<T>();
if (list != null)
{
return list.ToArray();
}
return null;
}
/// <summary>
/// 返回当前节点以下的Interface,包含隐藏或者未激活的节点
/// <param name="incudeSelf">是否包含自身节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// </summary>
public static List<T> FindInterfaceListInChildren<T>(this Transform tran, bool incudeSelf = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : class
{
if (!typeof(T).IsInterface)
{
return null;
}
List<Component> cp = tran.FindComponentListInChildren<Component>(incudeSelf);
if (cp != null && cp.Count > 0)
{
List<T> list = new List<T>();
int i, len = cp.Count;
for (i = 0; i < len; i++)
{
if (cp[i] is T)
{
T t = cp[i] as T;
if (filter != null)
{
if (filter(t))
{
list.Add(t);
if (doSomething != null) doSomething(t);
}
}
else
{
list.Add(t);
if (doSomething != null) doSomething(t);
}
}
}
if (list.Count > 0)
{
return list;
}
}
return null;
}
/// <summary>
/// 返回当前节点以下的Interface,包含隐藏或者未激活的节点
/// <param name="incudeSelf">是否包含自身节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// </summary>
public static T[] FindInterfacesInChildren<T>(this Transform tran, bool incudeSelf = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : class
{
List<T> list = tran.FindInterfaceListInChildren<T>(incudeSelf, filter, doSomething);
if (list != null)
{
return list.ToArray();
}
return null;
}
/// <summary>
/// 返回Root节点以下的所有Interface,包含隐藏或者未激活的节点
/// <param name="incudeRoot">是否包含Root节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// </summary>
public static List<T> FindAllInterfaceList<T> (this Transform tran, bool incudeRoot = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : class
{
if (!typeof(T).IsInterface)
{
return null;
}
List<Component> cp = tran.FindAllComponentList<Component>(incudeRoot);
if (cp != null && cp.Count > 0)
{
List<T> list = new List<T>();
int i, len = cp.Count;
for (i = 0; i < len; i++)
{
if (cp[i] is T)
{
T t = cp[i] as T;
if (filter != null)
{
if (filter(t))
{
list.Add(t);
if (doSomething != null) doSomething(t);
}
}
else
{
list.Add(t);
if (doSomething != null) doSomething(t);
}
}
}
if (list.Count > 0)
{
return list;
}
}
return null;
}
/// <summary>
/// 返回Root节点以下的所有Interface,包含隐藏或者未激活的节点
/// <param name="incudeRoot">是否包含Root节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// </summary>
public static T[] FindAllInterfaces<T>(this Transform tran, bool incudeRoot = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : class
{
List<T> list = tran.FindAllInterfaceList<T>(incudeRoot, filter, doSomething);
if (list != null)
{
return list.ToArray();
}
return null;
}
/// <summary>
/// 查找或者创建Component(当前Component在当前节点对象找不到,则在当前对象上创建Component)
/// </summary>
public static T AddMissingComponent<T>(this Transform tran) where T : Component
{
return tran.gameObject.AddMissingComponent<T>();
}
/// <summary>
/// 返回Root节点以下的所有Component,包含隐藏或者未激活的节点
/// <typeparam name="T">Component</typeparam>
/// <param name="incudeRoot">是否包含Root节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// </summary>
public static List<T> FindAllComponentList<T>(this Transform trans, bool incudeRoot = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : Component
{
List<T> list = new List<T>();
if (incudeRoot)
{
T cpt = trans.root.GetComponent<T>();
if (cpt != null)
{
list.Add(cpt);
}
}
_findComponentLoop<T>(trans, ref list, filter, doSomething);
if (list.Count > 0)
{
return list;
}
return null;
}
/// <summary>
/// 返回Root节点以下的所有Component,包含隐藏或者未激活的节点
/// <typeparam name="T">Component</typeparam>
/// <param name="incudeRoot">是否包含Root节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// </summary>
public static T[] FindAllComponents<T>(this Transform trans, bool incudeRoot = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : Component
{
List<T> list = trans.FindAllComponentList<T>(incudeRoot, filter, doSomething);
if (list != null)
{
return list.ToArray();
}
return null;
}
/// <summary>
/// 按照节点顺序返回所有子节点的Component,包含隐藏或者未激活的节点;
/// </summary>
/// <typeparam name="T">Component</typeparam>
/// <param name="incudeSelf">是否包含自身节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// <returns></returns>
public static List<T> FindComponentListInChildren<T>(this Transform trans, bool incudeSelf = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : Component {
List<T> list = new List<T>();
if (incudeSelf)
{
T cpt = trans.GetComponent<T>();
if (cpt != null)
{
list.Add(cpt);
}
}
_findComponentLoop<T>(trans, ref list, filter, doSomething);
if (list.Count > 0)
{
return list;
}
return null;
}
/// <summary>
/// 按照节点顺序返回所有子节点的Component,包含隐藏或者未激活的节点;
/// </summary>
/// <typeparam name="T">Component</typeparam>
/// <param name="incudeSelf">是否包含自身节点</param>
/// <param name="filter">过滤器:返回True为通过过滤</param>
/// <param name="doSomething">遍历时附加行为</param>
/// <returns></returns>
public static T[] FindComponentsInChildren<T>(this Transform trans, bool incudeSelf = false, Func<T, bool> filter = null, Action<T> doSomething = null) where T : Component
{
List<T> list = trans.FindComponentListInChildren<T>(incudeSelf, filter, doSomething);
if (list != null)
{
return list.ToArray();
}
return null;
}
private static void _findComponentLoop<T>(Transform t, ref List<T> list, Func<T,bool> filter = null, Action<T> doSomething = null) where T : Component {
int i, len = t.childCount;
for (i = 0; i < len; i++) {
Transform ct = t.GetChild(i);
T[] cpts = ct.GetComponents<T>();
if (cpts != null && cpts.Length > 0)
{
int c, cLen = cpts.Length;
for (c = 0; c < cLen; c++)
{
T cpt = cpts[c];
if (cpt)
{
if (filter != null)
{
if (filter(cpt)) list.Add(cpt);
if (doSomething != null) doSomething(cpt);
}
else
{
list.Add(cpt);
if (doSomething != null) doSomething(cpt);
}
}
}
}
if (ct.childCount > 0) {
_findComponentLoop<T>(ct, ref list);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.SimpleCalculator
{
class SimpleCalculator
{
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] values = input.Split();
Stack<string> stack = new Stack<string>(values.Reverse());
for (int i = 0; i < values.Length; i++)
{
if (stack.Count > 1)
{
int firstN = int.Parse(stack.Pop());
string operand = stack.Pop();
int secondN = int.Parse(stack.Pop());
switch (operand)
{
case "+":
stack.Push((firstN + secondN).ToString());
break;
case "-":
stack.Push((firstN - secondN).ToString());
break;
default:
break;
}
}
else
{
break;
}
}
Console.WriteLine(stack.Pop());
}
}
}
|
using System;
using System.Collections.Generic;
namespace AddressBook
{
internal class Menu
{
/// <summary>
/// Provides User With Options To Use AddressBook
/// And Handles Each Option
/// </summary>
internal static void Options()
{
HashSet<string> ForRepetition = new HashSet<string>();
AddressBook AllRecords = new AddressBook();
x: try
{
while (true)
{
Console.WriteLine(Constants.SwitchStatements);
int OptionSelected = int.Parse(Console.ReadLine());
if (OptionSelected == 6)
{
break;
}
switch (OptionSelected)
{
case 1:
{
Console.WriteLine(Constants.OptedAddRecord);
Contact NewContact = AddRecord.AddDetails();
Utility.RepetitionCheck(ForRepetition, NewContact.getName());
AllRecords.addContact(NewContact);
break;
}
case 2:
{
Console.WriteLine(Constants.SearchByNameOpted);
Console.WriteLine(Constants.AskNameSearch);
string Name = Console.ReadLine();
AllRecords.SearchByName(Name);
break;
}
case 3:
{
Console.WriteLine(Constants.SearchByOrganisation);
Console.WriteLine(Constants.AskOrganisationSearch);
string OrganisationName = Console.ReadLine();
AllRecords.SearchByOrganisation(OrganisationName);
break;
}
case 4:
{
Console.WriteLine(Constants.UpdateContactOpted);
Console.WriteLine(Constants.UpdateContactName);
string Name = Console.ReadLine();
Contact UpdateContact = AddRecord.AddDetails();
Utility.CheckUpdateFeasibility(ForRepetition, Name, UpdateContact.getName());
AllRecords.UpdateContact(Name, UpdateContact);
Console.WriteLine(Constants.UpdateConfirm);
break;
}
case 5:
{
Console.WriteLine(Constants.DeleteContactOpted);
Console.WriteLine(Constants.AskNameDelete);
string Name = Console.ReadLine();
AllRecords.DeleteContact(Name);
Console.WriteLine(Constants.ContactDeleteConfirmation);
ForRepetition.Remove(Name);
break;
}
default:
{
Console.WriteLine(Constants.DefaultStatement);
break;
}
}
}
}
catch(Exception exp)
{
Console.WriteLine(exp.Message+"\n");
goto x;
}
}
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Linq;
using System.Windows.Resources;
using System.Collections.Generic;
using Tff.Panzer.Models.Geography;
using Tff.Panzer.Models.Scenario;
namespace Tff.Panzer.Factories.Scenario
{
public class ScenarioUnitFactory
{
public List<ScenarioUnit> ScenarioUnits { get; private set; }
public ScenarioUnitFactory()
{
ScenarioUnits = new List<ScenarioUnit>();
Uri uri = new Uri(Constants.Scenario_UnitDataPath, UriKind.Relative);
XElement applicationXml;
StreamResourceInfo xmlStream = Application.GetResourceStream(uri);
applicationXml = XElement.Load(xmlStream.Stream);
var data = from wz in applicationXml.Descendants("Scenario_Unit")
select wz;
ScenarioUnit scenarioUnit = null;
foreach (var d in data)
{
scenarioUnit = new ScenarioUnit();
scenarioUnit.ScenarioUnitId = (Int32)d.Element("ScenarioUnitId");
scenarioUnit.ScenarioId = (Int32)d.Element("ScenarioId");
scenarioUnit.StartingScenarioTileId = (Int32)d.Element("StartingScenarioTileId");
scenarioUnit.EquipmentId = (Int32)d.Element("EquipmentId");
scenarioUnit.TransportId = (Int32)d.Element("TransportId");
scenarioUnit.SideId = (Int32)d.Element("SideId");
scenarioUnit.NationId = (Int32)d.Element("FlagId");
scenarioUnit.Strength = (Int32)d.Element("Strength");
scenarioUnit.Experience = (Int32)d.Element("Experience");
scenarioUnit.Entrenchment = (Int32)d.Element("Entrenchment");
scenarioUnit.CordInd = !(Boolean)d.Element("AuxiliaryInd");
ScenarioUnits.Add(scenarioUnit);
}
}
public ScenarioUnit GetScenarioUnit(int scenarioUnitId)
{
ScenarioUnit scenarioUnit = (from su in this.ScenarioUnits
where su.ScenarioUnitId == scenarioUnitId
select su).First();
return scenarioUnit;
}
internal List<ScenarioUnit> GetScenarioUnits(int scenarioId)
{
List<ScenarioUnit> scenarioUnits = new List<ScenarioUnit>();
var query = from su in this.ScenarioUnits
where su.ScenarioId == scenarioId
select su;
foreach (ScenarioUnit scenarioUnit in query)
{
scenarioUnits.Add(scenarioUnit);
}
return scenarioUnits;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HighScoreDisplay : MonoBehaviour {
public Text highScoreText1;
public Text highScoreText2;
public Text highScoreText3;
private int highScore1;
private int highScore2;
private int highScore3;
// Update is called once per frame
public void displayScore()
{
highScore1 = PlayerPrefs.GetInt("High Score");
highScore2 = PlayerPrefs.GetInt("High Score 2");
highScore3 = PlayerPrefs.GetInt("High Score 3");
highScoreText1.text = "1. " + highScore1.ToString();
highScoreText2.text = "2. " + highScore2.ToString();
highScoreText3.text = "3. " + highScore3.ToString();
}
}
|
using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections.Generic;
using Karkas.Core.TypeLibrary;
using Karkas.Core.Onaylama;
using Karkas.Core.Onaylama.ForPonos;
using System.ComponentModel.DataAnnotations;
namespace Karkas.Ornek.TypeLibrary.Ornekler
{
[Serializable]
[DebuggerDisplay("AciklamaKey = {AciklamaKey}")]
public partial class Aciklama: BaseTypeLibrary
{
private Guid aciklamaKey;
private string aciklama;
[Key]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public Guid AciklamaKey
{
[DebuggerStepThrough]
get
{
return aciklamaKey;
}
[DebuggerStepThrough]
set
{
if ((this.RowState == DataRowState.Unchanged) && (aciklamaKey!= value))
{
this.RowState = DataRowState.Modified;
}
aciklamaKey = value;
}
}
[StringLength(50)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string AciklamaProperty
{
[DebuggerStepThrough]
get
{
return aciklama;
}
[DebuggerStepThrough]
set
{
if ((this.RowState == DataRowState.Unchanged) && (aciklama!= value))
{
this.RowState = DataRowState.Modified;
}
aciklama = value;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[XmlIgnore, SoapIgnore]
[ScaffoldColumn(false)]
public string AciklamaKeyAsString
{
[DebuggerStepThrough]
get
{
return aciklamaKey.ToString();
}
[DebuggerStepThrough]
set
{
try
{
Guid _a = new Guid(value);
AciklamaKey = _a;
}
catch(Exception)
{
this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"AciklamaKey",string.Format(CEVIRI_YAZISI,"AciklamaKey","Guid")));
}
}
}
public Aciklama ShallowCopy()
{
Aciklama obj = new Aciklama();
obj.aciklamaKey = aciklamaKey;
obj.aciklama = aciklama;
return obj;
}
protected override void OnaylamaListesiniOlusturCodeGeneration()
{
this.Onaylayici.OnaylayiciListesi.Add(new GerekliAlanOnaylayici(this, "AciklamaProperty")); }
public class PropertyIsimleri
{
public const string AciklamaKey = "AciklamaKey";
public const string AciklamaProperty = "Aciklama";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ItemScript : MonoBehaviour
{
public int ID;
public string Type;
public Sprite Icon;
public bool Abgeholt;
public bool AktWaffe;
public GameObject AktSlot;
GameObject player;
public GameObject angelegtesSchwert;
public GameObject angelegterStab;
public GameObject Schwert;
public GameObject Stab;
public bool Ulttrankrdy;
GameObject Waffenslot;
void Start()
{
Type = gameObject.tag;
AktWaffe = false;
player = GameObject.FindWithTag("Player");
Waffenslot = GameObject.FindWithTag("Waffenslot");
Ulttrankrdy = true;
}
void Update()
{
//if (Input.GetKeyDown(KeyCode.F))
//{
// AktWaffe = false;
//}
//if (AktWaffe == false && Abgeholt)
//{
// gameObject.transform.parent = AktSlot.transform;
// gameObject.SetActive(false);
//}
}
public void SchwertNutzen(GameObject aktSlot)
{
angelegtesSchwert.SetActive(true);
angelegterStab.SetActive(false);
player.GetComponent<SkillScript>().Schwert = true;
player.GetComponent<SkillScript>().Stab = false;
}
public void StabNutzen(GameObject aktSlot)
{
angelegterStab.SetActive(true);
angelegtesSchwert.SetActive(false);
player.GetComponent<SkillScript>().Schwert = false;
player.GetComponent<SkillScript>().Stab = true;
}
public void PilzNutzen(GameObject aktSlot)
{
gameObject.transform.parent = null;
gameObject.SetActive(true);
Destroy(gameObject);
if ((player.GetComponent<LebensScript>().hunger + 25) <= player.GetComponent<LebensScript>().maxHunger)
{
player.GetComponent<LebensScript>().hunger += 25;
}
else
{
player.GetComponent<LebensScript>().hunger = player.GetComponent<LebensScript>().maxHunger;
if (player.GetComponent<LebensScript>().leben + 10 <= player.GetComponent<LebensScript>().maxLeben)
{
player.GetComponent<LebensScript>().leben += 10;
}
else
{
player.GetComponent<LebensScript>().leben = player.GetComponent<LebensScript>().maxLeben;
}
}
}
public void FleischNutzen(GameObject aktSlot)
{
gameObject.transform.parent = null;
gameObject.SetActive(true);
Destroy(gameObject);
if ((player.GetComponent<LebensScript>().hunger + 50) <= player.GetComponent<LebensScript>().maxHunger)
{
player.GetComponent<LebensScript>().hunger += 50;
}
else
{
player.GetComponent<LebensScript>().hunger = player.GetComponent<LebensScript>().maxHunger;
if (player.GetComponent<LebensScript>().leben + 20 <= player.GetComponent<LebensScript>().maxLeben)
{
player.GetComponent<LebensScript>().leben += 20;
}
else
{
player.GetComponent<LebensScript>().leben = player.GetComponent<LebensScript>().maxLeben;
}
}
}
public void TrankNutzen(GameObject aktSlot)
{
gameObject.transform.parent = null;
gameObject.SetActive(true);
Destroy(gameObject);
if (player.GetComponent<LebensScript>().leben + 500 <= player.GetComponent<LebensScript>().maxLeben)
{
player.GetComponent<LebensScript>().leben += 500;
}
else
{
player.GetComponent<LebensScript>().leben = player.GetComponent<LebensScript>().maxLeben;
}
}
public void UlttrankNutzen(GameObject aktSlot)
{
if (Ulttrankrdy)
{
if (player.GetComponent<LebensScript>().leben + 500 <= player.GetComponent<LebensScript>().maxLeben)
{
player.GetComponent<LebensScript>().leben += 500;
}
else
{
player.GetComponent<LebensScript>().leben = player.GetComponent<LebensScript>().maxLeben;
}
Ulttrankrdy = false;
Invoke("Ulttrankreset", 10);
}
}
public void Ulttrankreset()
{
Debug.Log("Ulttrank wird zurück gesetzt");
Ulttrankrdy = true;
}
}
|
using System.Collections.Generic;
using KRF.Core.Entities.Customer;
namespace KRF.Web.Models
{
public class JobData
{
/// <summary>
/// Holds Job Information
/// </summary>
public Job Job { get; set; }
/// <summary>
/// Holds Job Assignment records
/// </summary>
public List<JobAssignment> JobAssignments { get; set; }
/// <summary>
/// Holds Job Task Records
/// </summary>
public JobTask JobTask { get; set; }
/// <summary>
/// Holds Job PO Record
/// </summary>
public JobPO JobPO { get; set; }
/// <summary>
/// Holds Job PO Estimate Items
/// </summary>
public List<POEstimateItem> POEstimateItems { get; set; }
/// <summary>
/// Holds Job CO Record
/// </summary>
public JobCO JobCO { get; set; }
/// <summary>
/// Holds Job CO Estimate Items
/// </summary>
public List<COEstimateItem> COEstimateItems { get; set; }
/// <summary>
/// Holds Job WO Record
/// </summary>
public JobWO JobWO { get; set; }
/// <summary>
/// Holds Job WO Estimate Items
/// </summary>
public List<WOEstimateItem> WOEstimateItems { get; set; }
/// <summary>
/// Holds Job Invoice Record
/// </summary>
public JobInvoice JobInvoice { get; set; }
/// <summary>
/// Holds Job Invoice Items
/// </summary>
public List<InvoiceItems> InvoiceItems { get; set; }
/// <summary>
/// Holds Job Inspection Record
/// </summary>
public JobInspection JobInspection { get; set; }
}
public class CrewEmpDetails
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public class ItemAssemblies
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string Code { get; set; }
}
public class JobAssignmentDetails
{
public int JobAssignmentID { get; set; }
public int JobID { get; set; }
/// <summary>
/// Hold EmployeeID/CrewID based on Type field
/// </summary>
public int ObjectPKID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string FromDate { get; set; }
public string ToDate { get; set; }
}
public class POCOEstimateItems
{
public int ID { get; set; }
public int EstimateID { get; set; }
public int ItemAssemblyID { get; set; }
public int ItemAssemblyType { get; set; }
public decimal Price { get; set; }
public decimal Quantity { get; set; }
public decimal Cost { get; set; }
public decimal LaborCost { get; set; }
public decimal MaterialCost { get; set; }
public string ItemNames { get; set; }
public int COID { get; set; }
public int ItemID { get; set; }
}
public class WOCOEstimateItems
{
public int ID { get; set; }
public int EstimateID { get; set; }
public int ItemAssemblyID { get; set; }
public int ItemAssemblyType { get; set; }
public decimal Budget { get; set; }
public decimal Used { get; set; }
public decimal Rate { get; set; }
public decimal Amount { get; set; }
public decimal Balance { get; set; }
public decimal LaborCost { get; set; }
public decimal MaterialCost { get; set; }
public string ItemNames { get; set; }
public int COID { get; set; }
public int ItemID { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace ExercicioFixacaoProduto.Entidades
{
class ProdutoImportado : Produto
{
public double TaxaAlfandega { get; set; }
public ProdutoImportado() { }
public ProdutoImportado(string nome, double preco, double taxaAlfandega)
: base(nome, preco)
{
TaxaAlfandega = taxaAlfandega;
}
public sealed override string EtiquetaDePreco()
{
return Nome + " $ " + PrecoTotal().ToString("F2", CultureInfo.InvariantCulture) + $" (Taxa alfandegária: $ {TaxaAlfandega.ToString("F2", CultureInfo.InvariantCulture)})";
}
public double PrecoTotal()
{
return Preco + TaxaAlfandega;
}
}
}
|
namespace SamMorganWeddingPortal.Models
{
public class BridalPartyBioModel
{
public string Name { get; set; }
public string Title { get; set; }
public string Relationship { get; set; }
public string ImagePath { get; set; }
public BridalPartyBioModel()
{
}
public BridalPartyBioModel(string name, string title, string relationship, string imagePath)
{
this.Name = name;
this.Title = title;
this.Relationship = relationship;
this.ImagePath = imagePath;
}
}
} |
using Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
[TestClass]
public class TestAddNewEmployee : TestBase
{
[TestMethod]
public void TestAddNewEmp()
{
var emp = new DTO.Commands.AddEmployee
{
Employee = new DTO.Commands.Info
{
FirstName = "Adam",
LastName = "John"
},
Dependents = new List<DTO.Commands.Info>
{
new DTO.Commands.Info
{
FirstName = "",
LastName = ""
}
}.ToList()
};
emp.Dependents = emp.Dependents.Where(x => x.FirstName != "");
var test = 0;
using (_context)
{
var service = new EmployeeRespository(_context, _mockLogging.Object, _mockRules);
test = service.Add(emp);
Assert.AreNotEqual(test, 0);
}
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Diagnostics;
using DotNetNuke.Web.Api;
namespace DotNetNuke.Tests.Web.Api
{
//various ServiceRouteMappers that will be reflected upon by the tests
public class ReflectedServiceRouteMappers
{
#region Nested type: EmbeddedServiceRouteMapper
public class EmbeddedServiceRouteMapper : IServiceRouteMapper
{
#region IServiceRouteMapper Members
public void RegisterRoutes(IMapRoute mapRouteManager)
{
throw new NotImplementedException();
}
#endregion
}
#endregion
}
public class ExceptionOnCreateInstanceServiceRouteMapper : IServiceRouteMapper
{
public ExceptionOnCreateInstanceServiceRouteMapper(int i)
{
//no default constructor prevents Activator.CreateInstance from working
Debug.WriteLine(i);
}
#region IServiceRouteMapper Members
public void RegisterRoutes(IMapRoute mapRouteManager)
{
throw new NotImplementedException();
}
#endregion
}
public class ExceptionOnRegisterServiceRouteMapper : IServiceRouteMapper
{
#region IServiceRouteMapper Members
public void RegisterRoutes(IMapRoute mapRouteManager)
{
throw new NotImplementedException();
}
#endregion
}
public class FakeServiceRouteMapper : IServiceRouteMapper
{
public static int RegistrationCalls { get; set; }
#region IServiceRouteMapper Members
public void RegisterRoutes(IMapRoute mapRouteManager)
{
RegistrationCalls++;
}
#endregion
}
public abstract class AbstractServiceRouteMapper : IServiceRouteMapper
{
#region IServiceRouteMapper Members
public void RegisterRoutes(IMapRoute mapRouteManager)
{
throw new NotImplementedException();
}
#endregion
}
internal class InternalServiceRouteMapper : IServiceRouteMapper
{
#region IServiceRouteMapper Members
public void RegisterRoutes(IMapRoute mapRouteManager)
{
throw new NotImplementedException();
}
#endregion
}
}
|
using System;
using System.Threading.Tasks;
using HangmanGame.App.Menu;
using HangmanGame.App.Services.Interfaces;
using HangmanGame.Common.Console.Interfaces;
using HangmanGame.Common.Delegates;
using Microsoft.Extensions.DependencyInjection;
namespace HangmanGame.App
{
public class Program
{
private static async Task Main()
{
// ReSharper disable once AssignNullToNotNullAttribute - used to set window title
Console.Title = typeof(Program).Namespace;
var serviceConfiguration = new ServiceConfiguration();
var config = serviceConfiguration.BuildConfigurationProvider();
var serviceProvider =
serviceConfiguration.BuildServiceProvider(config);
await ShowMainMenu(serviceProvider);
}
private static async Task ShowMainMenu(IServiceProvider serviceProvider)
{
var consoleCommandExecutor = serviceProvider.GetService<IConsoleCommandExecutor>();
var wordProvider = serviceProvider.GetService<IWordsProvider>();
var userOutput = serviceProvider.GetService<UserOutput>();
var userInputParser = serviceProvider.GetService<IUserInputParser>();
var gameDrawer = serviceProvider.GetService<IGameInterfaceManager>();
var gameMediator = serviceProvider.GetService<IGameMediator>();
var mainMenu =
new MainMenu(wordProvider,
userOutput,
userInputParser,
gameDrawer,
gameMediator);
gameDrawer.ShowGreeting();
await consoleCommandExecutor.ShowMenuWithActions(mainMenu, true);
}
}
}
|
using System.Threading;
using MediatR;
using NSubstitute;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Workspace;
namespace Lsp.Tests
{
internal static class ExecuteCommandSyncExtensions
{
public static IExecuteCommandHandler With(Container<string> commands) => Substitute.For<IExecuteCommandHandler>().With(commands);
public static IExecuteCommandHandler With(this IExecuteCommandHandler handler, Container<string> commands)
{
handler.GetRegistrationOptions(Arg.Any<ExecuteCommandCapability>(), Arg.Any<ClientCapabilities>()).Returns(new ExecuteCommandRegistrationOptions { Commands = commands });
handler.Handle(Arg.Any<ExecuteCommandParams>(), Arg.Any<CancellationToken>()).Returns(Unit.Value);
return handler;
}
}
}
|
using System;
using MXDbhelper.Common;
namespace MXQHLibrary
{
[TableView("Sys_EntityRelation")]
public class EntityRelation
{
/// <summary>
/// 父级实体名称
/// </summary>
[ColumnProperty(Key.True)]
public string ParEntity { get; set; }
/// <summary>
/// 实体关联名
/// </summary>
[ColumnProperty(Key.True)]
public string ColumnName { get; set; }
/// <summary>
/// 关联实体名
/// </summary>
[ColumnProperty(Key.True)]
public string EntityName { get; set; }
/// <summary>
/// 父实体栏或值
/// </summary>
[ColumnProperty(Key.True)]
public string ParentKey { get; set; }
/// <summary>
/// 实体栏位或值
/// </summary>
[ColumnProperty(Key.True)]
public string ChildKey { get; set; }
/// <summary>
/// 栏位或值 0-栏位, 1-数值,2-文本
/// </summary>
public bool ChildType { get; set; }
/// <summary>
/// 栏位或值 0-栏位, 1-数值,2-文本
/// </summary>
public bool ParenType { get; set; }
/// <summary>
/// 属性关系, =,<, <=, >, >=, LIKE
/// </summary>
public string Expression { get; set; }
/// <summary>
/// 条件关系, 空 AND, OR
/// </summary>
public string Associate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using liteCMS.Logic;
using liteCMS.Entity.CMS;
using System.Xml;
using System.Collections;
namespace liteCMS.Web.Controller
{
public partial class WebContent : System.Web.UI.Page, IWebContent
{
private eArticulo _oPagina = null;
private eMenuWebDetalle _oSeccionWeb = null;
private List<eTerminoIdioma> _lTerminoIdioma = new List<eTerminoIdioma>();
private sArticulo.Estado _Estado;
private sArticulo.Directorio _Directorio;
private int _IdMenuWeb, _IdArticulo;
private short _IdIdioma = 1;
private liteCMS.Entity.Ventas.eGoogleProfile _oGoogleProfile = null;
private string _currentPage;
private string[] restrictedPages = { "Landing.aspx", "Login.aspx", "Logoff.aspx", "Disclaimer.aspx", "Error.aspx" };
override protected void OnPreInit(EventArgs e)
{
LoadRequests();
//Término x Idiom: Grupo Parámetros Web
lTerminoIdioma = lCMS.TerminoIdioma_listarWeb(1, IdIdioma);
}
private void SetPageTitle(string Titulo)
{
Page.Title = (Titulo != "") ? Titulo : "Ferreyros Portal de Vendedores";
}
private void LoadRequests()
{
_currentPage = Request.Url.Segments[Request.Url.Segments.Length - 1];
if (restrictedPages.Contains(_currentPage))
{
//Excluir Paginas
return;
}
//Validar Login al Portal
if (oGoogleProfile == null)
{
Response.Redirect(ClientScriptHelper.getURLLogin());
return;
}
eMenuWebDetalle oMenuWebDetalle=null;
if (Request["aID"] == null)
{
if (Request["lgID"] != null) IdIdioma = Convert.ToInt16(Request["lgID"]);
else if (Session["IdIdioma"] != null) IdIdioma = Convert.ToInt16(Session["IdIdioma"]);
Session["IdIdioma"] = IdIdioma;
IdMenuWeb = (Request["mwID"] != null) ? Convert.ToInt32(Request["mwID"]) : 0;
oSeccionWeb = lCMS.MenuWebDetalle_item(IdMenuWeb, IdIdioma);
if (oSeccionWeb == null)
{
IdMenuWeb = 1; //Cargar Home Page
oSeccionWeb = lCMS.MenuWebDetalle_item(IdMenuWeb, IdIdioma);
}
else
{
if (!oSeccionWeb.VerContenido)
{
if((oPagina=ClientScriptHelper.getFirstArticulo(oSeccionWeb))!=null)
{
Response.Redirect(ClientScriptHelper.getEnlace_Articulo(oPagina));
}
}
}
SetPageTitle("");
return;
}
else
{
oPagina = ClientScriptHelper.ValidarPagina(lCMS.Articulo_item(Convert.ToInt32(Request["aID"])), this.Context);
if (oPagina != null)
{
IdArticulo = oPagina.IdArticulo;
IdMenuWeb = oPagina.IdMenuWeb;
IdIdioma = oPagina.IdIdioma;
if (oMenuWebDetalle == null) oSeccionWeb = lCMS.MenuWebDetalle_item(oPagina.IdMenuWeb, oPagina.IdIdioma);
SetPageTitle(oPagina.Titulo);
}
else
ClientScriptHelper.ErrorHandler(404, this.Context);
}
//SetMinisite();
return;
}
#region Public Methods
public void LoadUserControl(WebContentUC ucWebContent, short IDIdioma)
{
ucWebContent.LoadUserControl(ucWebContent, IDIdioma);
ucWebContent.lTerminoIdioma = lTerminoIdioma;
}
public void LoadUserControl(WebContentUC ucWebContent, short IDIdioma, int IDMenuWeb)
{
ucWebContent.LoadUserControl(ucWebContent, IDIdioma, IDMenuWeb);
ucWebContent.lTerminoIdioma = lTerminoIdioma;
}
public void LoadUserControl(WebContentUC ucWebContent, eMenuWebDetalle oMenuWebDetalle)
{
ucWebContent.LoadUserControl(ucWebContent, oMenuWebDetalle);
ucWebContent.lTerminoIdioma = lTerminoIdioma;
}
public void LoadUserControl(WebContentUC ucWebContent, eArticulo oArticulo)
{
ucWebContent.LoadUserControl(ucWebContent, oArticulo);
ucWebContent.lTerminoIdioma = lTerminoIdioma;
}
public string TerminoIdioma_GetValor(string Variable)
{
return TerminoIdiomaHelper.GetValor(lTerminoIdioma, Variable);
}
public void TerminoIdioma_AddGrupo(short IDTerminoGrupo)
{
lTerminoIdioma = TerminoIdiomaHelper.AddGrupo(lTerminoIdioma, IDTerminoGrupo, IdIdioma);
}
public void LoadMetaTags(string strXML)
{
if (strXML == "") return;
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(strXML);
XmlNodeList lItems = xDoc.GetElementsByTagName("ListItem");
Trace.Warn("xDoc.InnerXml", xDoc.InnerXml);
foreach (XmlElement nodo in lItems)
{
HtmlMeta hMeta = new HtmlMeta();
hMeta.Name = nodo.GetAttribute("Nombre");
hMeta.Content = nodo.GetAttribute("Valor");
if (hMeta.Name != "Title")
{
Page.Header.Controls.AddAt(0, hMeta);
}
if (hMeta.Name == "Title" && hMeta.Content != "")
{
Page.Title = hMeta.Content;
}
}
}
//public eCliente GetClienteSession()
//{
// return (Session["oCliente"] != null) ? (eCliente)Session["oCliente"] : null;
//}
//public eContacto GetContactoSession()
//{
// return (Session["oContacto"] != null) ? (eContacto)Session["oContacto"] : null;
//}
public liteCMS.Entity.Ventas.eGoogleProfile GetGoogleProfileSession()
{
return (Session["oGoogleProfile"] != null) ? (liteCMS.Entity.Ventas.eGoogleProfile)Session["oGoogleProfile"] : null;
}
public ArrayList GetUsuarioGrupos()
{
return (Session["UsuarioGrupos"] != null) ? (ArrayList)Session["UsuarioGrupos"] : new ArrayList();
}
#endregion
#region Properties
public eArticulo oPagina
{
set
{
_oPagina = value;
}
get
{
return _oPagina;
}
}
public eMenuWebDetalle oSeccionWeb
{
set
{
_oSeccionWeb = value;
}
get
{
return _oSeccionWeb;
}
}
public liteCMS.Entity.Ventas.eGoogleProfile oGoogleProfile
{
set
{
_oGoogleProfile = value;
}
get
{
if (_oGoogleProfile == null) _oGoogleProfile = GetGoogleProfileSession();
return _oGoogleProfile;
}
}
public ArrayList UsuarioGrupos = new ArrayList();
public sArticulo.Estado Estado
{
set
{
_Estado = value;
}
get
{
return _Estado;
}
}
public sArticulo.Directorio Directorio
{
set
{
_Directorio = value;
}
get
{
return _Directorio;
}
}
public List<eTerminoIdioma> lTerminoIdioma
{
set
{
_lTerminoIdioma = value;
}
get
{
return _lTerminoIdioma;
}
}
public int IdMenuWeb
{
set
{
_IdMenuWeb = value;
}
get
{
return _IdMenuWeb;
}
}
public short IdIdioma
{
set
{
_IdIdioma = value;
}
get
{
return _IdIdioma;
}
}
public int IdArticulo
{
set
{
_IdArticulo = value;
}
get
{
return _IdArticulo;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using PackageActionsContrib.Helpers;
using umbraco.cms.businesslogic.packager.standardPackageActions;
using umbraco.interfaces;
namespace PackageActionsContrib
{
/// <summary>
/// Moves a file
/// </summary>
/// <remarks>
/// Can be used for renaming as well
/// </remarks>
public class MoveFile : IPackageAction
{
public bool Execute(string packageName, XmlNode xmlData)
{
File.Move(
HttpContext.Current.Server.MapPath(GetSourceFileName(xmlData)),
HttpContext.Current.Server.MapPath(GetTargetFileName(xmlData)));
return true;
}
private string GetSourceFileName(XmlNode xmlData)
{
return XmlHelper.GetAttributeValueFromNode(xmlData, "sourceFile");
}
private string GetTargetFileName(XmlNode xmlData)
{
return XmlHelper.GetAttributeValueFromNode(xmlData, "targetFile");
}
public string Alias()
{
return "MoveFile";
}
public bool Undo(string packageName, XmlNode xmlData)
{
File.Delete(HttpContext.Current.Server.MapPath(GetTargetFileName(xmlData)));
return true;
}
public XmlNode SampleXml()
{
string sample = string.Format("<Action runat=\"install\" undo=\"false\" alias=\"{0}\" sourceFile=\"~/bin/UCommerce.Uninstaller.dll.tmp\" targetFile=\"~/bin/UCommerce.Uninstaller.dll\"/>", Alias());
return helper.parseStringToXmlNode(sample);
}
}
}
|
using NoLibrary.Infrastructures;
using System;
namespace NoLibrary.ViewModels
{
class DateTimeControlViewModel : BindableBase
{
public string Time { get; }
public DateTimeControlViewModel(DateTime time)
{
Time = time.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using assignment1;
namespace Assignment1
{
class Magazine : BookStoreItem
{
public string ReleaseDay { get; set; }
public Magazine(string title, double price, string releaseDay) : base(title, price)
{
this.ReleaseDay = releaseDay;
}
public override string ToString()
{
return $"[Magazine] {this.Title} - release day:{this.ReleaseDay}, {this.Price:##.00}";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParticelDecalPool : MonoBehaviour {
public int maxDecals = 100;
public float decalSizeMin = 0.5f;
public float decalSizeMax = 1.5f;
private int particleDecalDataIndex;
private ParticleDecalData[] particleData;
private ParticleSystem.Particle[] particles;
private ParticleSystem decalParticleSystem;
// Use this for initialization
void Start () {
decalParticleSystem = GetComponent<ParticleSystem>();
particles = new ParticleSystem.Particle[maxDecals];
particleData = new ParticleDecalData[maxDecals];
for (int i = 0; i < maxDecals; i++) {
particleData[i] = new ParticleDecalData();
}
}
public void ParticleHit(Collision particleCollisionEvent, Color splatColor){
setParticleData(particleCollisionEvent, splatColor);
DisplayParticles();
}
// records collision position, rotation, size and colour
void setParticleData(Collision col, Color splatColor){
if (particleDecalDataIndex >= maxDecals) {
particleDecalDataIndex = 0;
}
// so here's the ""fun"" part
// The only reason I'm having to write any of this code at all is that Unity doesn't come with a decals system
// So you need to write your own
// Already fun, right? It gets better
// The tutorial on the Unity website that this code is all from took ParticleCollisionEvents as the spawnpoint for the decal
// While this is purportedly because the code was written for a paintgun example,
// I suspect the entire example was built that way because it's a lot easier to use ParticleCollisionEvents..
// ...than Collisions.
// What follows is the line to store position based off of a PCE:
// particleData[particleDecalDataIndex].position = particleCollisionEvent.intersection;
// Nice and straightforward. Now let's the same line but with Collision:
particleData[particleDecalDataIndex].position = col.contacts[0].point;
// Not much more cryptic
// But just different enough to make me slightly annoyed.
Vector3 particleRotationEuler = Quaternion.LookRotation (col.contacts[0].normal).eulerAngles;
particleRotationEuler.z = Random.Range (0, 360);
particleData[particleDecalDataIndex].rotation = particleRotationEuler;
particleData[particleDecalDataIndex].size = Random.Range (decalSizeMin, decalSizeMax);
particleData[particleDecalDataIndex].color = splatColor;
particleDecalDataIndex++;
}
void DisplayParticles(){
for (int i = 0; i < particleData.Length; i++) {
particles[i].position = particleData [i].position;
particles[i].rotation3D = particleData [i].rotation;
particles[i].startSize = particleData [i].size;
particles[i].startColor = particleData [i].color;
}
decalParticleSystem.SetParticles(particles, particles.Length);
}
}
|
using Hiraya.Domain.MongoDBCollections.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hiraya.Domain.MongoDBCollections.Entities
{
/// <summary>
/// This will clasify the products or services of the particular business account which will help identify automatically the tax types linked to each account.
/// </summary>
public class BusinessPurpose : AuditedEntity
{
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using DotNetNuke.Framework;
#endregion
namespace DotNetNuke.Services.Search.Internals
{
/// <summary>
/// Internal Search Controller. This is an Internal class and should not be used outside of Core
/// </summary>
public class InternalSearchController : ServiceLocator<IInternalSearchController, InternalSearchController>
{
protected override Func<IInternalSearchController> GetFactory()
{
return () => new InternalSearchControllerImpl();
}
}
}
|
using System;
using UnityEngine;
using Object = UnityEngine.Object;
public static class GameObjectExtensions
{
public static void AddChild(this GameObject parent, GameObject child)
{
if (parent == null)
throw new NullReferenceException();
if (child == null)
throw new ArgumentNullException();
child.transform.parent = parent.transform;
}
public static void AddChildren(this GameObject parent, GameObject[] children)
{
if (parent == null)
throw new NullReferenceException();
if (children == null)
throw new ArgumentNullException();
foreach (var child in children)
{
AddChild(parent, child);
}
}
public static int CountChildren(this GameObject parent)
{
if (parent == null)
throw new NullReferenceException();
return parent.transform.childCount;
}
public static void DestroyChildren(this GameObject parent)
{
if (parent == null)
throw new NullReferenceException();
foreach (Transform child in parent.transform)
{
Object.Destroy(child.gameObject);
}
}
public static GameObject FindChild(this GameObject parent, string childName, bool exactMatch = true)
{
if (parent == null)
throw new NullReferenceException();
if (childName == null)
throw new ArgumentNullException();
if (exactMatch)
{
foreach (Transform childTransform in parent.transform)
{
if (childTransform.name.Equals(childName))
{
return childTransform.gameObject;
}
}
}
else
{
foreach (Transform childTransform in parent.transform)
{
if (childTransform.name.Contains(childName))
{
return childTransform.gameObject;
}
}
}
return null;
}
public static GameObject FindDescendant(this GameObject ancestor, string descendantName, bool exactMatch = true)
{
if (ancestor == null)
throw new NullReferenceException();
if (descendantName == null)
throw new ArgumentNullException();
var descendant = ancestor.FindChild(descendantName, exactMatch);
if (descendant)
{
return descendant;
}
foreach (Transform currentDescendantTransform in ancestor.transform)
{
if (descendant = currentDescendantTransform.gameObject.FindDescendant(descendantName, exactMatch))
{
return descendant;
}
}
return null;
}
public static bool IsParentOf(this GameObject parent, GameObject child)
{
if (parent == null)
throw new NullReferenceException();
if (child == null)
throw new ArgumentNullException();
return child.transform.IsChildOf(parent.transform);
}
public static bool IsAncestorOf(this GameObject ancestor, GameObject descendant)
{
if (ancestor == null)
throw new NullReferenceException();
if (descendant == null)
throw new ArgumentNullException();
if (ancestor.IsParentOf(descendant))
{
return true;
}
foreach (Transform currentDescendantTransform in ancestor.transform)
{
if (ancestor.IsAncestorOf(currentDescendantTransform.gameObject))
{
return true;
}
}
return false;
}
} |
using console;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace ConsoleTestProj
{
/// <summary>
///This is a test class for _029_FindSqureRootTest and is intended
///to contain all _029_FindSqureRootTest Unit Tests
///</summary>
[TestClass()]
public class _029_FindSqureRootTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for FindSqrt
///</summary>
[TestMethod()]
public void FindSqrtTest()
{
_029_FindSqureRoot target = new _029_FindSqureRoot(); // TODO: Initialize to an appropriate value
double input = 64; // TODO: Initialize to an appropriate value
double expected = 8; // TODO: Initialize to an appropriate value
double actual;
actual = target.FindSqrt(input);
Assert.AreEqual(expected, actual);
input = 144; // TODO: Initialize to an appropriate value
expected = 12; // TODO: Initialize to an appropriate value
actual = target.FindSqrt(input);
Assert.IsTrue(Math.Abs(expected- actual) < 0.0001);
input = 0.64;
expected = 0.8;
actual = target.FindSqrt(input);
Assert.IsTrue(Math.Abs(expected - actual) < 0.0001);
}
}
}
|
using System.Threading.Tasks;
using lauthai_api.DataAccessLayer.Repository;
using Microsoft.AspNetCore.Mvc;
namespace lauthai_api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UniversityController : ControllerBase
{
private readonly IUnitOfWork _uow;
public UniversityController(IUnitOfWork uow)
{
_uow = uow;
}
[HttpGet("all")]
public async Task<IActionResult> GetAllUniversities()
{
var universities = await _uow.UniversityRepository.GetAllUni();
if (universities != null)
return Ok(universities);
return NotFound();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio42
{
public class Clase4
{
public void MetodoInstancia()
{
try
{
new Clase3();
}
catch (UnaExcepcion e)
{
throw new MiException("\nMsj ANterior: "+e.Message+" y lanzo MiException\n",e);
}
}
}
}
|
using System;
//There are 3 types of edits that can be performed on strings.
//insert a char. remove a char. replace a char.
//given 2 strings write a function to check if they are 1 or 0 edits away
//EXAMPLE
//pale, ple -) true
//pales, pale -) true
//pale, bale -) true
//pale, bae -) false
class OneAway
{
public bool isOneAway(string s1, string s2)
{
//check 0 edits
if (string.Compare(s1, s2) == 0)
return true;
int diff = 0;
//check Replace a Char
if (s1.Length == s2.Length)
{
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] != s2[i])
diff++;
}
if (diff > 1)
return false;
}
//check Replace a Char
int length = s1.Length < s2.Length ? s1.Length : s2.Length;
if (Math.Abs(s1.Length - s2.Length) == 1)
{
int i = 0;
int j = 0;
while (i < s1.Length && j < s2.Length)
{
if (s1[i] != s2[j])
{
if (s1.Length < s2.Length)
return s2.Substring(i + 1).CompareTo(s1.Substring(i)) == 0;
else
return s1.Substring(i + 1).CompareTo(s2.Substring(i)) == 0;
}
i++; j++;
}
}
return true;
}
public void Test()
{
//pale, ple -) true
//pales, pale -) true
//pale, bale -) true
//pale, bae -) false
Console.WriteLine(isOneAway("pale", "ple"));
Console.WriteLine(isOneAway("pales", "pale"));
Console.WriteLine(isOneAway("pale", "bale"));
Console.WriteLine(isOneAway("pale", "bae"));
}
} |
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Linq;
namespace NtApiDotNet.Ndr.Marshal
{
/// <summary>
/// Type for a synchronous NDR pipe.
/// </summary>
/// <typeparam name="T">The base type of pipe blocks.</typeparam>
public sealed class NdrPipe<T> where T : struct
{
/// <summary>
/// The list of blocks for the pipe.
/// </summary>
public IEnumerable<T[]> Blocks { get; }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="blocks">The list of blocks to return.</param>
public NdrPipe(IEnumerable<T[]> blocks)
{
Blocks = blocks;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="block">A single block to return.</param>
public NdrPipe(T[] block)
{
Blocks = new[] { block };
}
/// <summary>
/// Convert the pipe blocks to a flat array.
/// </summary>
/// <returns>The flat array.</returns>
public T[] ToArray()
{
return Blocks.SelectMany(a => a).ToArray();
}
}
}
|
using CheckMySymptoms.ViewModels;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace CheckMySymptoms.Flow.ScreenSettings
{
public class MenuItem : ObservableObject
{
public int Stage { get; set; }
public string Text { get; set; }
public string Tooltip { get; set; }
public string Icon { get; set; }
private bool _last;
public bool Last
{
get { return _last; }
set
{
Set(ref _last, value);
Enabled = !Last;
}
}
public double FromHorizontalOffset => Last ? 1500 : 0;
private bool _enabled;
public bool Enabled
{
get { return _enabled; }
set { Set(ref _enabled, value); }
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj.GetType() != typeof(MenuItem))
return false;
MenuItem other = (MenuItem)obj;
return other.Text == this.Text && other.Last == this.Last;
}
public override int GetHashCode()
=> (this.Text ?? string.Empty).GetHashCode();
}
}
|
/*
* Copyright 2019 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Flora License, Version 1.1 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://floralicense.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Windows.Input;
using Ultraviolet.Enums;
using Ultraviolet.Interfaces;
using Xamarin.Forms;
namespace Ultraviolet.ViewModels
{
/// <summary>
/// ViewModel class for MainPage.
/// </summary>
public class MainViewModel : BaseViewModel, IDisposable
{
/// <summary>
/// Field backing level property.
/// </summary>
private UvLevel _level;
/// <summary>
/// Navigation service obtained by dependency service.
/// </summary>
private readonly INavigationService _navigationService;
/// <summary>
/// Ultraviolet sensor service obtained by dependency service.
/// </summary>
private readonly IUltravioletSensorService _ultravioletSensorService;
/// <summary>
/// Property indicating uv level.
/// </summary>
public UvLevel Level
{
get => _level;
set => SetProperty(ref _level, value);
}
/// <summary>
/// Command for showing details about uv index.
/// </summary>
public ICommand ShowDetailsPageCommand { get; private set; }
/// <summary>
/// Initializes class.
/// </summary>
public MainViewModel()
{
_ultravioletSensorService = DependencyService.Get<IUltravioletSensorService>();
_ultravioletSensorService.UvLevelUpdated += OnUvLevelUpdated;
_ultravioletSensorService.Start();
_navigationService = DependencyService.Get<INavigationService>();
ShowDetailsPageCommand = new Command(ExecuteShowDetailsPage);
}
/// <summary>
/// Handles UvLevelUpdated event.
/// </summary>
/// <param name="sender">Object which invoked the event.</param>
/// <param name="e">Uv level - event argument.</param>
private void OnUvLevelUpdated(object sender, UvLevel e)
{
Level = e;
}
/// <summary>
/// Executed by <see cref="ShowDetailsPageCommand"/>.
/// </summary>
private void ExecuteShowDetailsPage()
{
_navigationService.NavigateTo(new DetailsViewModel(Level));
}
/// <summary>
/// Disposes main view model.
/// </summary>
public void Dispose()
{
if (_ultravioletSensorService != null)
_ultravioletSensorService.UvLevelUpdated -= OnUvLevelUpdated;
_ultravioletSensorService?.Stop();
}
}
}
|
using System.Collections.Generic;
namespace Zoological
{
public class Zoological {
public List<PaintedDog> PaintedDogs { get; set; } = new List<PaintedDog>();
public List<Human> Humans { get; set; } = new List<Human>();
public List<Fish> Fishes { get; set; } = new List<Fish>();
public List<IWalking> WalkingAnimals()
{
List<IWalking> WalkingAnimals = new List<IWalking>() {
new PaintedDog(),
new PaintedDog(),
new PaintedDog(),
new Human(),
};
return WalkingAnimals ;
}
public List<ISwimming> SwimmingAnimals()
{
List<ISwimming> SwimmingAnimals = new List<ISwimming>() {
new Fish(),
new Fish(),
new Dolphin(),
new Dolphin(),
};
return SwimmingAnimals ;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PDTech.OA.Model
{
public class TestAnswer
{
/// <summary>
/// 试卷ID
/// </summary>
public string TestGuid
{
get;
set;
}
/// <summary>
/// 试卷名称
/// </summary>
public string TestName
{
get;
set;
}
/// <summary>
/// 试题总数
/// </summary>
public decimal TestCount
{
get;
set;
}
/// <summary>
/// 试卷总分
/// </summary>
public decimal TestScore
{
get;
set;
}
/// <summary>
/// 作答ID
/// </summary>
public string AnswerGuid
{
get;
set;
}
/// <summary>
/// 作答时间
/// </summary>
public DateTime? AnswerTime
{
get;
set;
}
}
}
|
using UnityEngine;
using System.Collections;
public class BeseigedCityEventFunctions : IslandEventFunctions {
public ResourceManager resourceManager;
public GameObject defaultConversation;
public ConversationManager conManager;
public ChoicesManager choiceManager;
public string AttackBattle;
public string DefendBattle;
// Use this for initialization
void Start () {
resourceManager = GameObject.FindGameObjectWithTag("Player").GetComponent<ResourceManager>();
choiceManager = GameObject.Find("Choices").GetComponent<ChoicesManager>();
conManager = defaultConversation.GetComponent<ConversationManager>();
eventHandler = GameObject.FindGameObjectWithTag("EventController").GetComponent<EventManagement>();
}
// Update is called once per frame
void Update () {
}
public void Attack()
{
eventHandler.islandEventIsOn.GetComponent<PortIslandEventScript>().raided = true;
eventHandler.islandEventIsOn.GetComponent<PortIslandEventScript>().explored = true;
//eventHandler.StartBattle(AttackBattle,true,false,4);
}
public void defend()
{
eventHandler.islandEventIsOn.GetComponent<PortIslandEventScript>().explored = true;
//eventHandler.StartBattle(DefendBattle,true,false,4);
}
}
|
using Diligent.BOL;
namespace Diligent.DAL.Core
{
public interface IProjectRepository : IRepository<Project>
{
Project GetProjectWithTasks(int id);
}
}
|
using System;
using System.Collections.Generic;
namespace Auction_proj.Models
{
public class Bid : BaseEntity
{
public int Userid { get; set; }
public User User { get; set; }
public int Auctionid { get; set; }
public Auction Auction { get; set; }
public int Bidid { get; set; }
public int Amount { get; set; }
}
} |
namespace _1.Logger
{
using _1.Logger.Core;
internal class Startup
{
private static void Main(string[] args)
{
var controller = new Controller();
controller.Run();
}
}
} |
using System.Xml.Serialization;
namespace PlatformRacing3.Web.Responses;
public class SingleRowResponse<T>
{
[XmlElement("Row")]
public T Row;
public SingleRowResponse()
{
}
public SingleRowResponse(T row)
{
this.Row = row;
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace IotWebServer
{
public class HtmlDoc
{
public HtmlDoc()
{
ReadFile();
}
public string ResponseText { get; private set; }
void ReadFile()
{
try
{
string basePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string s = basePath.Remove(basePath.Length - 10);
string path = $"{s}Pages\\response.html";
using (StreamReader sr = new StreamReader(path))
{
ResponseText = sr.ReadToEnd();
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace WS_PosData_PMKT.Models.Request
{
[DataContract]
public class FileReceptionRequest
{
[DataMember]
public string IdSync { get; set; }
[DataMember]
public string CodeTypeFile { get; set; }
[DataMember]
public Byte[] FileToSave { get; set; }
}
} |
namespace Assets.Scripts.Enemies {
class Ability {
}
}
|
using Soko.Domain;
using System;
using System.Drawing;
namespace Soko.Report
{
/// <summary>
/// Summary description for Izvestaj.
/// </summary>
public class Izvestaj
{
private float relHeight = 24.5f;
private float relHeaderHeight = 2.7f;
public const float relWidth = 17.2f;
private float relPictureWidth = 4.7f;
private StringFormat titleFormat;
private StringFormat subTitleFormat;
private StringFormat dateFormat;
private Font titleFont;
private Font subTitleFont;
private Font pageNumFont;
private Font sokDruVojFont;
private Font adresaFont;
protected Brush blackBrush;
protected RectangleF headerBounds;
protected RectangleF contentBounds;
protected RectangleF pageBounds;
protected FinansijskaCelina finCelina;
protected int lastPageNum;
public int LastPageNum
{
get { return lastPageNum; }
}
private bool a4;
public bool A4
{
get { return a4; }
set { a4 = value; }
}
private string printerName;
public string PrinterName
{
get { return printerName; }
set { printerName = value; }
}
public Izvestaj()
{
createFormats();
createFonts();
A4 = true;
PrinterName = Options.Instance.PrinterNameIzvestaj;
}
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private string subTitle = String.Empty;
public string SubTitle
{
get { return subTitle; }
set { subTitle = value; }
}
private string documentName;
public string DocumentName
{
get { return documentName; }
set { documentName = value; }
}
private bool contentSetupDone;
public bool ContentSetupDone
{
get { return contentSetupDone; }
}
private DateTime timeOfPrint;
public DateTime TimeOfPrint
{
get { return timeOfPrint; }
set { timeOfPrint = value; }
}
private void createFormats()
{
titleFormat = new StringFormat();
titleFormat.Alignment = StringAlignment.Center;
titleFormat.LineAlignment = StringAlignment.Near;
subTitleFormat = new StringFormat();
subTitleFormat.Alignment = StringAlignment.Center;
subTitleFormat.LineAlignment = StringAlignment.Far;
dateFormat = new StringFormat();
dateFormat.Alignment = StringAlignment.Far;
dateFormat.LineAlignment = StringAlignment.Near;
}
public virtual void BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
//createFonts();
//e.Cancel = true;
}
private void createFonts()
{
titleFont = new Font("Tahoma", 14, FontStyle.Bold);
subTitleFont = new Font("Tahoma", 10, FontStyle.Bold);
pageNumFont = new Font("Arial", 8);
sokDruVojFont = new Font("Arial Narrow", 8);
adresaFont = new Font("Arial Narrow", 7);
blackBrush = Brushes.Black;
}
public virtual void EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
//releaseFonts();
}
public virtual float getHeaderHeight(Graphics g, RectangleF marginBounds)
{
return relHeaderHeight / relHeight * marginBounds.Height;
}
public void drawPage(Graphics g, int pageNum)
{
drawHeader(g, pageNum);
drawContent(g, pageNum);
}
public virtual void drawHeader(Graphics g, int pageNum)
{
float pictureWidth = relPictureWidth / relWidth * headerBounds.Width;
float pictureHeight = headerBounds.Height * 0.8f;
RectangleF pictureBounds = new RectangleF(headerBounds.X, headerBounds.Y, pictureWidth, pictureHeight);
drawSokoWithCaption(g, pictureBounds);
float lineOffset = headerBounds.Height * 0.9f;
using(Pen pen = new Pen(Color.Black, 1/72f * 2f))
{
g.DrawLine(pen, new PointF(headerBounds.X, headerBounds.Y + lineOffset),
new PointF(headerBounds.X + headerBounds.Width, headerBounds.Y + lineOffset));
}
float titleHeight = titleFont.GetHeight(g);
if (subTitle != "")
titleHeight += subTitleFont.GetHeight(g) * 1.5f;
float titleY = headerBounds.Y + (headerBounds.Height - titleHeight) / 3;
RectangleF titleBounds = new RectangleF(headerBounds.X, titleY,
headerBounds.Width, titleHeight);
g.DrawString(title, titleFont, blackBrush, titleBounds, titleFormat);
if (subTitle != "")
g.DrawString(subTitle, subTitleFont, blackBrush, titleBounds, subTitleFormat);
System.Resources.ResourceManager resourceManager = new
System.Resources.ResourceManager("Soko.Resources.PreviewResursi", this.GetType().Assembly);
String page = resourceManager.GetString("izvestaj_header_strana");
String from = resourceManager.GetString("izvestaj_header_od");
string datum = TimeOfPrint.ToShortDateString();
string vreme = TimeOfPrint.ToShortTimeString();
g.DrawString(datum + " " + vreme, pageNumFont, blackBrush,
headerBounds.Right, headerBounds.Top, dateFormat);
g.DrawString(String.Format("{0} {1} {2} {3}", page, pageNum, from, LastPageNum), pageNumFont, blackBrush,
headerBounds.Right, headerBounds.Top + pageNumFont.GetHeight(g) * 1.5f, dateFormat);
}
private void drawSokoWithCaption(Graphics g, RectangleF pictureBounds)
{
System.Resources.ResourceManager resourceManager = new
System.Resources.ResourceManager("Soko.Resources.SlikeResursi", this.GetType().Assembly);
Image sokoImage = (Image)resourceManager.GetObject("slika_soko");
resourceManager = new
System.Resources.ResourceManager("Soko.Resources.PreviewResursi", this.GetType().Assembly);
bool sokolskiCentar = finCelina != null && finCelina.Naziv.ToLower() == "sokolski centar";
string sokDruVoj;
if (!sokolskiCentar)
{
sokDruVoj = resourceManager.GetString("izvestaj_header_sok_dru_voj");
}
else
{
sokDruVoj = "SOKOLSKI CENTAR";
}
string adresa = resourceManager.GetString("izvestaj_header_adresa");
float ySokDruVoj = pictureBounds.Y + 0.7f * pictureBounds.Height;
float yAdresa = pictureBounds.Y + 0.85f * pictureBounds.Height;
RectangleF sokDruVojBounds = new RectangleF(pictureBounds.X, ySokDruVoj,
pictureBounds.Width, yAdresa - ySokDruVoj);
RectangleF adresaBounds = new RectangleF(pictureBounds.X, yAdresa,
pictureBounds.Width, pictureBounds.Y + pictureBounds.Height - yAdresa);
float sokoHeight = 0.7f * pictureBounds.Height;
float sokoWidth = sokoHeight;
float sokoX = pictureBounds.X + (pictureBounds.Width - sokoWidth) / 2;
RectangleF sokoBounds = new RectangleF(sokoX, pictureBounds.Y, sokoWidth, sokoHeight);
if (!sokolskiCentar)
{
g.DrawImage(sokoImage, sokoBounds);
}
else
{
// TODO3: Crtanje okvira je potrebno samo dok se ne napravi slika za "sokolski centar"
using (Pen pen = new Pen(Color.Black, 1 / 72f * 0.25f))
{
g.DrawRectangle(pen, pictureBounds.X, pictureBounds.Y, pictureBounds.Width, pictureBounds.Height);
}
}
g.DrawString(sokDruVoj, sokDruVojFont, blackBrush, sokDruVojBounds, titleFormat);
g.DrawString(adresa, adresaFont, blackBrush, adresaBounds, titleFormat);
}
public void setupContent(Graphics g, RectangleF marginBounds, RectangleF pageBounds)
{
headerBounds = getHeaderBounds(g, marginBounds);
contentBounds = getContentBounds(g, marginBounds);
this.pageBounds = pageBounds;
doSetupContent(g);
contentSetupDone = true;
}
private RectangleF getHeaderBounds(Graphics g, RectangleF marginBounds)
{
return new RectangleF(marginBounds.Location,
new SizeF(marginBounds.Width, getHeaderHeight(g, marginBounds)));
}
private RectangleF getContentBounds(Graphics g, RectangleF marginBounds)
{
float headerHeight = getHeaderHeight(g, marginBounds);
return new RectangleF(marginBounds.X,
marginBounds.Y + headerHeight,
marginBounds.Width,
marginBounds.Height - headerHeight);
}
protected virtual void doSetupContent(Graphics g)
{
}
public virtual void drawContent(Graphics g, int pageNum)
{
}
public void QueryPageSettings(object sender, System.Drawing.Printing.QueryPageSettingsEventArgs e)
{
// Set margins to .5" all the way around
//e.PageSettings.Margins = new Margins(50, 50, 50, 50);
}
}
}
|
using PDV.DAO.DB.Controller;
using System;
using System.Collections;
using System.Linq;
namespace PDV.DAO.DB.Utils
{
public class Sequence
{
private static Hashtable HashSequences = new Hashtable();
private static string GetCreateSequence(string Name, decimal Next)
{
return string.Format("CREATE SEQUENCE {0} START WITH {1} INCREMENT BY 1", Name.ToUpper().Trim(), Next);
}
private static string GetMaxStatement(string Table, string Field)
{
return string.Format("SELECT COALESCE(MAX({0}) + 1, 1) FROM {1}", Field, Table);
}
private static bool SequenceExists(string Key)
{
using (SQLQuery oSQL = new SQLQuery())
{
try
{
oSQL.SQL = string.Format("SELECT * FROM PG_CLASS WHERE RELKIND = 'S' AND RELNAME ILIKE '{0}'", Key);
oSQL.Open();
return oSQL.dtDados.Rows.Count > 0;
}
catch
{
return false;
}
}
}
public static int GetMaxID(string Table, string Field)
{
using (SQLQuery oSQL = new SQLQuery())
{
try
{
oSQL.SQL = GetMaxStatement(Table, Field);
oSQL.Open();
int id = Convert.ToInt32(oSQL.dtDados.Rows[0][0]);
if (id < 1)
throw new Exception();
return id;
}
catch
{
return 1;
}
}
}
public static int GetNextID(string Table, string Field = "")
{
try
{
if (string.IsNullOrEmpty(Field))
Field = "ID" + Table;
if (!HashSequences.Contains(Field))
if (SequenceExists(Field))
HashSequences.Add(Field, Table);
using (SQLQuery oSQL = new SQLQuery())
{
if (HashSequences.Contains(Field))
{
oSQL.SQL = string.Format("SELECT NEXTVAL('{0}')", Field.ToUpper().Trim());
oSQL.Open();
return Convert.ToInt32(oSQL.dtDados.Rows[0][0]);
}
else
{
oSQL.SQL = GetCreateSequence(Field, GetMaxID(Table, Field));
oSQL.ExecSQL();
return GetNextID(Table, Field);
}
}
}
catch (Exception ex)
{
return 1;
}
}
public static bool AtualizarValorSequence(string NomeSequence, decimal Valor)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "DROP SEQUENCE IF EXISTS " + NomeSequence;
oSQL.ExecSQL();
oSQL.ClearAll();
oSQL.SQL = $"CREATE SEQUENCE {NomeSequence} START WITH {Valor}";
oSQL.ExecSQL();
return true;
}
}
public static int GetProxCodigo(string Tabela, string Campo = "CODIGO")
{
using (SQLQuery oSQL = new SQLQuery())
{
try
{
oSQL.SQL = String.Format("SELECT COALESCE(MAX({0}), 0) + 1 FROM {1}", Campo, Tabela);
oSQL.Open();
return Convert.ToInt32(oSQL.dtDados.Rows[0][0]);
}
catch
{
return 1;
}
}
}
public static int GetValorAtualSequence(string Seq, int? IDConexao = null)
{
try
{
using (SQLQuery oSQL = new SQLQuery(IDConexao))
{
oSQL.SQL = "SELECT LAST_VALUE FROM " + Seq;
oSQL.Open();
return Convert.ToInt32(oSQL.dtDados.Rows[0][0]);
}
}
catch
{
return 1;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using AdvUtils;
/// <summary>
/// RNNSharp written by Zhongkai Fu (fuzhongkai@gmail.com)
/// </summary>
namespace RNNSharp
{
enum TFEATURE_WEIGHT_TYPE_ENUM
{
BINARY,
FREQUENCY
}
enum PRETRAIN_TYPE
{
AUTOENCODER,
EMBEDDING
}
public class Featurizer
{
public TagSet TagSet { get; set; }
public RNNSharp.RNNDecoder AutoEncoder = null;
public int SparseFeatureSize;
Dictionary<string, List<int>> FeatureContext;
int PretrainedModelColumn;
TFEATURE_WEIGHT_TYPE_ENUM TFeatureWeightType = TFEATURE_WEIGHT_TYPE_ENUM.BINARY;
WordEMWrapFeaturizer PretainedModel;
TemplateFeaturizer TFeaturizer;
bool bSeq2Seq = false;
PRETRAIN_TYPE preTrainType = RNNSharp.PRETRAIN_TYPE.EMBEDDING;
string autoEncoderModelFile = String.Empty;
string autoEncoderFeatureConfigFile = String.Empty;
static string TFEATURE_CONTEXT = "TFEATURE_CONTEXT";
static string TFEATURE_FILENAME = "TFEATURE_FILENAME";
static string RT_FEATURE_CONTEXT = "RTFEATURE_CONTEXT";
static string TFEATURE_WEIGHT_TYPE = "TFEATURE_WEIGHT_TYPE";
static string PRETRAIN_TYPE = "PRETRAIN_TYPE";
static string WORDEMBEDDING_CONTEXT = "WORDEMBEDDING_CONTEXT";
static string PRETRAINEDMODEL_FILENAME = "WORDEMBEDDING_FILENAME";
static string PRETRAINEDMODEL_RAW_FILENAME = "WORDEMBEDDING_RAW_FILENAME";
static string PRETRAINEDMODEL_COLUMN = "WORDEMBEDDING_COLUMN";
static string AUTOENCODER_MODEL = "AUTOENCODER_MODEL";
static string AUTOENCODER_FEATURECONFIG = "AUTOENCODER_FEATURECONFIG";
//The format of configuration file
public void LoadFeatureConfigFromFile(string strFileName)
{
StreamReader sr = new StreamReader(strFileName);
string strLine = null;
FeatureContext = new Dictionary<string, List<int>>();
while ((strLine = sr.ReadLine()) != null)
{
strLine = strLine.Trim();
if (strLine.Length == 0)
{
//Emtpy line, ignore it
continue;
}
if (strLine.StartsWith("#") == true)
{
//Comments line, ignore it
continue;
}
int idxSeparator = strLine.IndexOf(':');
string strKey = strLine.Substring(0, idxSeparator).Trim();
string strValue = strLine.Substring(idxSeparator + 1).Trim();
if (strKey == PRETRAINEDMODEL_FILENAME)
{
if (PretainedModel != null)
{
throw new ArgumentException("Static pretrained model has already been loaded. Please check if settings is duplicated in configuration file.");
}
Logger.WriteLine("Loading pretrained dense feature set from model {0}", strValue);
PretainedModel = new WordEMWrapFeaturizer(strValue);
}
else if (strKey == PRETRAINEDMODEL_RAW_FILENAME)
{
if (PretainedModel != null)
{
throw new ArgumentException("Static pretrained model has already been loaded. Please check if settings is duplicated in configuration file.");
}
Logger.WriteLine("Loading pretrained dense feature set from model {0} in text format", strValue);
PretainedModel = new WordEMWrapFeaturizer(strValue, true);
}
else if (strKey == TFEATURE_FILENAME)
{
Logger.WriteLine("Loading template feature set...");
TFeaturizer = new TemplateFeaturizer(strValue);
}
else if (strKey == PRETRAINEDMODEL_COLUMN)
{
PretrainedModelColumn = int.Parse(strValue);
Logger.WriteLine("Pretrained model feature column: {0}", PretrainedModelColumn);
}
else if (strKey == TFEATURE_WEIGHT_TYPE)
{
Logger.WriteLine("TFeature weighting type: {0}", strValue);
if (strValue == "binary")
{
TFeatureWeightType = TFEATURE_WEIGHT_TYPE_ENUM.BINARY;
}
else
{
TFeatureWeightType = TFEATURE_WEIGHT_TYPE_ENUM.FREQUENCY;
}
}
else if (strKey == PRETRAIN_TYPE)
{
if (strValue.Equals(RNNSharp.PRETRAIN_TYPE.AUTOENCODER.ToString(), StringComparison.InvariantCultureIgnoreCase))
{
preTrainType = RNNSharp.PRETRAIN_TYPE.AUTOENCODER;
}
else
{
preTrainType = RNNSharp.PRETRAIN_TYPE.EMBEDDING;
}
Logger.WriteLine("Pretrain type: {0}", preTrainType);
}
else if (strKey == AUTOENCODER_FEATURECONFIG)
{
autoEncoderFeatureConfigFile = strValue;
Logger.WriteLine("Auto encoder configuration file: {0}", autoEncoderFeatureConfigFile);
}
else if (strKey == AUTOENCODER_MODEL)
{
autoEncoderModelFile = strValue;
Logger.WriteLine("Auto encoder model file: {0}", autoEncoderModelFile);
}
else
{
string[] values = strValue.Split(',');
if (FeatureContext.ContainsKey(strKey) == false)
{
FeatureContext.Add(strKey, new List<int>());
}
foreach (string value in values)
{
FeatureContext[strKey].Add(int.Parse(value));
}
}
}
sr.Close();
}
// truncate current to range [lower, upper)
public int TruncPosition(int current, int lower, int upper)
{
return (current < lower) ? lower : ((current >= upper) ? upper - 1 : current);
}
public Featurizer(string strFeatureConfigFileName, TagSet tagSet, bool seq2seq = false)
{
bSeq2Seq = seq2seq;
LoadFeatureConfigFromFile(strFeatureConfigFileName);
TagSet = tagSet;
InitComponentFeaturizer();
}
void InitComponentFeaturizer()
{
var fc = FeatureContext;
SparseFeatureSize = 0;
if (TFeaturizer != null)
{
if (fc.ContainsKey(TFEATURE_CONTEXT) == true)
{
SparseFeatureSize += TFeaturizer.GetFeatureSize() * fc[TFEATURE_CONTEXT].Count;
}
}
if (fc.ContainsKey(RT_FEATURE_CONTEXT) == true)
{
SparseFeatureSize += TagSet.GetSize() * fc[RT_FEATURE_CONTEXT].Count;
}
if (preTrainType == RNNSharp.PRETRAIN_TYPE.AUTOENCODER || bSeq2Seq)
{
InitializeAutoEncoder();
}
}
public bool IsRunTimeFeatureUsed()
{
var fc = FeatureContext;
return fc.ContainsKey(RT_FEATURE_CONTEXT);
}
public void ShowFeatureSize()
{
var fc = FeatureContext;
if (TFeaturizer != null)
Logger.WriteLine("Template feature size: {0}", TFeaturizer.GetFeatureSize());
if (fc.ContainsKey(TFEATURE_CONTEXT) == true)
Logger.WriteLine("Template feature context size: {0}", TFeaturizer.GetFeatureSize() * fc[TFEATURE_CONTEXT].Count);
if (fc.ContainsKey(RT_FEATURE_CONTEXT) == true)
Logger.WriteLine("Run time feature size: {0}", TagSet.GetSize() * fc[RT_FEATURE_CONTEXT].Count);
if (fc.ContainsKey(WORDEMBEDDING_CONTEXT) == true)
Logger.WriteLine("Pretrained dense feature size: {0}", PretainedModel.GetDimension() * fc[WORDEMBEDDING_CONTEXT].Count);
}
void ExtractSparseFeature(int currentState, int numStates, List<string[]> features, State pState)
{
Dictionary<int, float> sparseFeature = new Dictionary<int, float>();
int start = 0;
var fc = FeatureContext;
//Extract TFeatures in given context window
if (TFeaturizer != null)
{
if (fc.ContainsKey(TFEATURE_CONTEXT) == true)
{
List<int> v = fc[TFEATURE_CONTEXT];
for (int j = 0; j < v.Count; j++)
{
int offset = TruncPosition(currentState + v[j], 0, numStates);
List<int> tfeatureList = TFeaturizer.GetFeatureIds(features, offset);
foreach (int featureId in tfeatureList)
{
if (TFeatureWeightType == TFEATURE_WEIGHT_TYPE_ENUM.BINARY)
{
sparseFeature[start + featureId] = 1;
}
else
{
if (sparseFeature.ContainsKey(start + featureId) == false)
{
sparseFeature.Add(start + featureId, 1);
}
else
{
sparseFeature[start + featureId]++;
}
}
}
start += TFeaturizer.GetFeatureSize();
}
}
}
// Create place hold for run time feature
// The real feature value is calculated at run time
if (fc.ContainsKey(RT_FEATURE_CONTEXT) == true)
{
List<int> v = fc[RT_FEATURE_CONTEXT];
pState.RuntimeFeatures = new PriviousLabelFeature[v.Count];
for (int j = 0; j < v.Count; j++)
{
if (v[j] < 0)
{
pState.AddRuntimeFeaturePlacehold(j, v[j], sparseFeature.Count, start);
sparseFeature[start] = 0; //Placehold a position
start += TagSet.GetSize();
}
else
{
throw new Exception("The offset of run time feature should be negative.");
}
}
}
SparseVector spSparseFeature = pState.SparseFeature;
spSparseFeature.SetLength(SparseFeatureSize);
spSparseFeature.AddKeyValuePairData(sparseFeature);
}
//Extract word embedding features from current context
public VectorBase ExtractDenseFeature(int currentState, int numStates, List<string[]> features)
{
var fc = FeatureContext;
if (fc.ContainsKey(WORDEMBEDDING_CONTEXT) == true)
{
List<int> v = fc[WORDEMBEDDING_CONTEXT];
if (v.Count == 1)
{
string strKey = features[TruncPosition((int)currentState + v[0], 0, (int)numStates)][PretrainedModelColumn];
return PretainedModel.GetTermVector(strKey);
}
CombinedVector dense = new CombinedVector();
for (int j = 0;j < v.Count;j++)
{
int offset = currentState + v[j];
if (offset >= 0 && offset < numStates)
{
string strKey = features[offset][PretrainedModelColumn];
dense.Append(PretainedModel.GetTermVector(strKey));
}
else
{
dense.Append(PretainedModel.m_UnkEmbedding);
}
}
return dense;
}
return new SingleVector();
}
public void InitializeAutoEncoder()
{
Logger.WriteLine("Initialize auto encoder...");
//Create feature extractors and load word embedding data from file
Featurizer featurizer = new Featurizer(autoEncoderFeatureConfigFile, null);
//Create instance for decoder
AutoEncoder = new RNNSharp.RNNDecoder(autoEncoderModelFile);
AutoEncoder.SetFeaturizer(featurizer);
}
public SequencePair ExtractFeatures(SentencePair sentence)
{
SequencePair sPair = new SequencePair();
sPair.autoEncoder = AutoEncoder;
sPair.srcSentence = sentence.srcSentence;
sPair.tgtSequence = ExtractFeatures(sentence.tgtSentence);
return sPair;
}
public State ExtractFeatures(string[] word)
{
State state = new State();
List<string[]> tokenList = new List<string[]>();
tokenList.Add(word);
ExtractSparseFeature(0, 1, tokenList, state);
state.DenseFeature = ExtractDenseFeature(0, 1, tokenList);
return state;
}
public Sequence ExtractFeatures(Sentence sentence)
{
int n = sentence.TokensList.Count;
Sequence sequence = new Sequence(n);
//For each token, get its sparse and dense feature set according configuration and training corpus
for (int i = 0; i < n; i++)
{
State state = sequence.States[i];
ExtractSparseFeature(i, n, sentence.TokensList, state);
}
if (preTrainType == RNNSharp.PRETRAIN_TYPE.AUTOENCODER)
{
List<double[]> outputs = AutoEncoder.ComputeTopHiddenLayerOutput(sentence);
for (int i = 0; i < n; i++)
{
State state = sequence.States[i];
state.DenseFeature = new SingleVector(outputs[i].Length, outputs[i]);
}
}
else
{
for (int i = 0; i < n; i++)
{
State state = sequence.States[i];
state.DenseFeature = ExtractDenseFeature(i, n, sentence.TokensList);
}
}
return sequence;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityStandardAssets._2D;
public class SyringeNeedle : NetworkBehaviour
{
public float slowEffect;
public float slowDuration;
private float startTime;
public float projectileDuration = 4f;
private Rigidbody2D rb;
// Use this for initialization
void Start ()
{
rb = gameObject.GetComponent<Rigidbody2D> ();
//rb.velocity = new Vector2 (50, 0);
this.transform.Rotate (0, 0, 0);
startTime = Time.time;
}
// Update is called once per frame
[ServerCallback]
void Update ()
{
//this object is destroyed after 4 seconds if it hasnt touched anything else yet
if (Time.time - startTime >= projectileDuration && gameObject != null) {
NetworkServer.Destroy(gameObject);
}
//projectileDuration -= Time.deltaTime;
}
private void OnCollisionEnter2D (Collision2D collision)
{
//if this hits a player, it slows their movement speed by 50% for 3 seconds.
GameObject other = collision.gameObject;
if (collision.gameObject.CompareTag ("Player")) {
print("hit player");
Platformer2DUserControl robot = collision.gameObject.GetComponent<Platformer2DUserControl>();
if (robot != null) {
robot.applySlow(0.5f, 3f);
}
}
NetworkServer.Destroy(gameObject);
}
}
|
namespace JetBrains.Annotations
{
using System;
using System.Runtime.CompilerServices;
[AttributeUsage(AttributeTargets.All, AllowMultiple=false, Inherited=true)]
public sealed class LocalizationRequiredAttribute : Attribute
{
[CompilerGenerated]
private bool bool_0;
public LocalizationRequiredAttribute() : this(true)
{
}
public LocalizationRequiredAttribute(bool required)
{
this.Required = required;
}
public override bool Equals(object obj)
{
LocalizationRequiredAttribute attribute = obj as LocalizationRequiredAttribute;
return ((attribute != null) && (attribute.Required == this.Required));
}
public override int GetHashCode()
{
return base.GetHashCode();
}
[UsedImplicitly]
public bool Required
{
[CompilerGenerated]
get
{
return this.bool_0;
}
[CompilerGenerated]
private set
{
this.bool_0 = value;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class EnemyPowerup : PowerUp
{
protected Collider[] FindEnemies(float radius, PowerupNames powerupName, PlayerStateMachine player)
{
List<GameObject> enemies = new List<GameObject>();
Collider[] hits = Physics.OverlapSphere(player.transform.position, radius, LayerMask.GetMask("Enemy"));
// Get all gameobject with EnemyBody script attached
return hits;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SonucManager : MonoBehaviour
{
[SerializeField]
private Text dogruAdetTxt, yanlisAdetTxt, puanTxt;
int puanSure = 10;
bool sureBittimi = true;
int toplamPuan, yazdirilacakPuan, artisPuani;
private void Awake()
{
sureBittimi = true;
}
public void SonuclariGoster(int dogruAdet,int yanlisAdet, int puan)
{
dogruAdetTxt.text = dogruAdet.ToString();
yanlisAdetTxt.text = yanlisAdet.ToString();
puanTxt.text = puan.ToString();
toplamPuan = puan;
artisPuani = toplamPuan / 10;
StartCoroutine(PuaniYazdirRoutine());
}
IEnumerator PuaniYazdirRoutine()
{
while (sureBittimi)
{
yield return new WaitForSeconds(0.1f);
yazdirilacakPuan += toplamPuan;
if (yazdirilacakPuan >= toplamPuan)
{
yazdirilacakPuan = toplamPuan;
}
puanTxt.text = yazdirilacakPuan.ToString();
if (puanSure <= 0)
{
sureBittimi = false;
}
puanSure--;
}
}
public void AnaMenuyeDon()
{
SceneManager.LoadScene("MenuLevel");
}
public void TekrarOyna()
{
SceneManager.LoadScene("GameLevel");
}
}
|
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
#if UNITY_2021_1_OR_NEWER
#define SCENEVIEW_TOOLBAR
#elif UNITY_2020_1_OR_NEWER
#define EDITOR_TOOLBAR
#endif
using System;
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.ShortcutManagement;
using UnityEditorInternal;
using UnityEngine;
namespace EnhancedEditor.Editor {
/// <summary>
/// <see cref="SceneDesigner"/>-related <see cref="EnhancedSettings"/> class.
/// </summary>
[Serializable]
public class SceneDesignerEnhancedSettings : EnhancedSettings {
#region Global Members
[Folder] public List<string> Folders = new List<string>();
// -----------------------
/// <inheritdoc cref="SceneDesignerEnhancedSettings"/>
public SceneDesignerEnhancedSettings(int _guid) : base(_guid) { }
#endregion
#region Settings
private static readonly GUIContent sceneDesignerFoldersGUI = new GUIContent("Scene Designer Folders",
"All folders displayed to select objects to place in the scene using the Scene Designer.");
private static readonly ReorderableList folderList = new ReorderableList(null, typeof(string)) {
drawHeaderCallback = DrawHeaderCallback,
drawElementCallback = DrawElementCallback,
};
private static readonly int settingsGUID = "EnhancedEditorScriptableSceneDesignerSetting".GetHashCode();
private static SceneDesignerEnhancedSettings settings = null;
/// <inheritdoc cref="SceneDesignerEnhancedSettings"/>
public static SceneDesignerEnhancedSettings Settings {
get {
EnhancedEditorUserSettings _userSettings = EnhancedEditorUserSettings.Instance;
if ((settings == null) && !_userSettings.GetSetting(settingsGUID, out settings, out _)) {
settings = new SceneDesignerEnhancedSettings(settingsGUID);
_userSettings.AddSetting(settings);
}
return settings;
}
}
// -------------------------------------------
// Draw
// -------------------------------------------
[EnhancedEditorUserSettings(Order = 50)]
private static void DrawSettings() {
var _ = Settings;
GUILayout.Space(5f);
using (var _scope = new EditorGUI.ChangeCheckScope()) {
folderList.list = settings.Folders;
folderList.DoLayoutList();
// Save on change.
if (_scope.changed) {
SceneDesigner.RefreshFolders();
}
}
}
private static void DrawHeaderCallback(Rect _position) {
EditorGUI.LabelField(_position, sceneDesignerFoldersGUI);
}
private static void DrawElementCallback(Rect _position, int _index, bool _isActive, bool _isFocused) {
_position.yMin += EditorGUIUtility.standardVerticalSpacing;
settings.Folders[_index] = EnhancedEditorGUI.FolderField(_position, settings.Folders[_index]);
}
#endregion
}
/// <summary>
/// Editor toolbar extension used to easily select prefabs from the project and place them in the scene.
/// </summary>
public class SceneDesigner : EditorWindow {
#region Styles
private static class Styles {
public static readonly GUIStyle Label = new GUIStyle(EditorStyles.whiteLabel);
public static readonly GUIContent ToolbarButtonGUI = EditorGUIUtility.IconContent("PreMatCube");
}
#endregion
#region Folder & Asset
private class Folder {
public string Name = string.Empty;
public bool Foldout = false;
public List<Folder> Folders = new List<Folder>();
public List<Asset> Assets = new List<Asset>();
// -----------------------
public Folder(string _name) {
Name = _name;
}
// -----------------------
public void RegisterAsset(string[] _directories, string _fullPath, int _index) {
if (_index == (_directories.Length - 1)) {
// Register new asset.
if (!Assets.Exists(a => a.Path == _fullPath)) {
Asset _asset = new Asset(_fullPath);
Assets.Add(_asset);
}
return;
}
string _directory = _directories[_index];
foreach (Folder _folder in Folders) {
if (_folder.Name == _directory) {
_folder.RegisterAsset(_directories, _fullPath, _index + 1);
return;
}
}
Folder _newFolder = new Folder(_directory);
Folders.Add(_newFolder);
_newFolder.RegisterAsset(_directories, _fullPath, _index + 1);
}
}
private class Asset {
public string Name = string.Empty;
public string Path = string.Empty;
public Texture Icon = null;
// -----------------------
public Asset(string _path) {
Name = $" {System.IO.Path.GetFileNameWithoutExtension(_path)}";
Path = _path;
}
}
#endregion
#region Mesh Infos
private class MeshInfo {
public Mesh Mesh = null;
public Material[] Materials = null;
public Transform Transform = null;
public Bounds Bounds = new Bounds();
// -------------------------------------------
// Constructor(s)
// -------------------------------------------
public MeshInfo(MeshFilter _mesh) {
Mesh = _mesh.sharedMesh;
Transform = _mesh.transform;
if (_mesh.TryGetComponent(out MeshRenderer _meshRenderer)) {
Materials = _meshRenderer.sharedMaterials;
}
Bounds = _mesh.GetComponent<Renderer>().bounds;
}
public MeshInfo(SkinnedMeshRenderer _mesh) {
Mesh = _mesh.sharedMesh;
Materials = _mesh.sharedMaterials;
Transform = _mesh.transform;
Bounds = _mesh.GetComponent<Renderer>().bounds;
}
}
#endregion
#region Global Members
private const string EnabledKey = "SceneDesignerEnabled";
private const string SelectedAssetKey = "SceneDesignerSelectedAsset";
private static bool isEnabled = false;
private static string selectedAssetPath = string.Empty;
private static GameObject selectedAsset = null;
// -----------------------
[InitializeOnLoadMethod]
private static void Initialize() {
// Loads session values.
bool _isEnabled = SessionState.GetBool(EnabledKey, isEnabled);
SelectAsset(SessionState.GetString(SelectedAssetKey, selectedAssetPath));
SetEnable(_isEnabled);
}
#endregion
#region Behaviour
private const EventModifiers RotateModifier = EventModifiers.Control;
private const EventModifiers ScaleModifier = EventModifiers.Shift;
private const KeyCode DisableKey = KeyCode.Escape;
private const KeyCode ResetKey = KeyCode.Tab;
private static MeshInfo[] meshInfos = null;
private static GameObject newInstance = null;
private static Vector3 worldPosition = Vector3.zero;
private static Quaternion rotation = Quaternion.identity;
private static Vector3 scale = Vector3.one;
private static Bounds assetBounds = default;
// -----------------------
private static void OnSceneGUI(SceneView _sceneView) {
Event _event = Event.current;
bool _isRotating = _event.modifiers.HasFlag(RotateModifier);
bool _isScaling = _event.modifiers.HasFlag(ScaleModifier);
if ((mouseOverWindow != _sceneView) && !_isRotating && !_isScaling)
return;
// Destroyed asset management.
if (selectedAsset == null) {
return;
}
// Hot key.
if (_event.isKey) {
switch (_event.keyCode) {
// Reset rotation and scale.
case ResetKey:
rotation = Quaternion.identity;
scale = Vector3.one;
break;
// Disable.
case DisableKey:
SetEnable(false);
return;
default:
break;
}
}
// Create and place a new instance on click.
if ((GUIUtility.hotControl != 0) && (_event.type == EventType.MouseDown) && (_event.button == 0) && !_isRotating && !_isScaling) {
newInstance = PrefabUtility.InstantiatePrefab(selectedAsset) as GameObject;
Transform _transform = newInstance.transform;
_transform.position = worldPosition;
_transform.rotation *= rotation;
_transform.localScale = Vector3.Scale(_transform.localScale, scale);
EditorGUIUtility.PingObject(newInstance);
Selection.activeObject = newInstance;
Undo.RegisterCreatedObjectUndo(newInstance, "New Asset Instantiation");
_event.Use();
} else if ((_event.type == EventType.Used) && (newInstance != null)) {
Selection.activeObject = newInstance;
newInstance = null;
}
// Get the asset preview position in world space according to the user mouse position.
if (!_isRotating && !_isScaling) {
Ray _worldRay = HandleUtility.GUIPointToWorldRay(_event.mousePosition);
if (Physics.Raycast(_worldRay, out RaycastHit _hit, 1000f)) {
// Get the hit normal, rounded to the nearest int for each axis
Vector3 _roundedNormal = new Vector3(Mathf.RoundToInt(_hit.normal.x),
Mathf.RoundToInt(_hit.normal.y),
Mathf.RoundToInt(_hit.normal.z));
// Set the preview position relative to the virtual collider
worldPosition = (_hit.point - Vector3.Scale(assetBounds.center, scale)) + Vector3.Scale(assetBounds.extents, Vector3.Scale(_roundedNormal, scale));
} else {
worldPosition = _worldRay.origin + (_worldRay.direction * 25f);
}
}
// Position handles.
bool _drawHandles = GUIUtility.hotControl == 0;
#if SCENEVIEW_TOOLBAR
_drawHandles &= _event.mousePosition.y > 25f;
#endif
if (_isRotating) {
// Rotation.
rotation = Handles.RotationHandle(rotation, worldPosition);
} else if (_isScaling) {
// Scale.
scale = Handles.ScaleHandle(scale, worldPosition, rotation, 1f);
} else if (_drawHandles) {
// Position.
Transform _transform = selectedAsset.transform;
using (var _scope = EnhancedEditorGUI.HandlesColor.Scope(Handles.xAxisColor)) {
Handles.ArrowHandleCap(0, worldPosition, Quaternion.LookRotation(_transform.right), 1f, EventType.Repaint);
}
using (var _scope = EnhancedEditorGUI.HandlesColor.Scope(Handles.yAxisColor)) {
Handles.ArrowHandleCap(0, worldPosition, Quaternion.LookRotation(_transform.up), 1f, EventType.Repaint);
}
using (var _scope = EnhancedEditorGUI.HandlesColor.Scope(Handles.zAxisColor)) {
Handles.ArrowHandleCap(0, worldPosition, Quaternion.LookRotation(_transform.forward), 1f, EventType.Repaint);
}
}
_sceneView.Repaint();
// Draw the selected mesh on camera.
if (((GUIUtility.hotControl != 0) && !_isRotating && !_isScaling) || (SceneView.lastActiveSceneView != _sceneView))
return;
Camera _camera = _sceneView.camera;
Transform _assetTransform = selectedAsset.transform;
Matrix4x4 _matrix = new Matrix4x4();
foreach (MeshInfo _mesh in meshInfos) {
Quaternion _rotation = _mesh.Transform.rotation * rotation;
Quaternion _local = _assetTransform.rotation * rotation;
Vector3 _offset = _local * Vector3.Scale(_assetTransform.InverseTransformPoint(_mesh.Transform.position), scale);
Vector3 _scale = Vector3.Scale(_mesh.Transform.lossyScale, scale);
// Set the matrix to use for preview
_matrix.SetTRS(worldPosition + _offset, _rotation, _scale);
for (int _i = 0; _i < _mesh.Materials.Length; _i++) {
Material _material = _mesh.Materials[_i];
Graphics.DrawMesh(_mesh.Mesh, _matrix, _material, 2, _camera, _i);
}
}
}
// -------------------------------------------
// Utility
// -------------------------------------------
/// <summary>
/// Set the <see cref="SceneDesigner"/> enabled state.
/// </summary>
/// <param name="_isEnable">Should the <see cref="SceneDesigner"/> be enabled?</param>
public static void SetEnable(bool _isEnable) {
SceneView.duringSceneGui -= OnSceneGUI;
if (_isEnable) {
if (string.IsNullOrEmpty(selectedAssetPath)) {
GetWindow();
return;
}
SceneView.duringSceneGui += OnSceneGUI;
}
isEnabled = _isEnable;
SessionState.SetBool(EnabledKey, _isEnable);
EnhancedEditorToolbar.Repaint();
}
/// <inheritdoc cref="SelectAsset(string)"/>
/// <param name="_asset">New selected asset.</param>
public static void SelectAsset(GameObject _asset) {
string _path = AssetDatabase.GetAssetPath(_asset);
if (!string.IsNullOrEmpty(_path)) {
SelectAsset(_path);
}
}
/// <summary>
/// Set the <see cref="SceneDesigner"/> currently selected asset.
/// </summary>
/// <param name="_assetPath">New selected asset path.</param>
public static void SelectAsset(string _assetPath) {
GameObject _asset = AssetDatabase.LoadAssetAtPath<GameObject>(_assetPath);
if (_asset == null) {
return;
}
Transform _transform = _asset.transform;
// Get mesh infos.
MeshFilter[] _meshFilters = _asset.GetComponentsInChildren<MeshFilter>();
SkinnedMeshRenderer[] _meshRenderers = _asset.GetComponentsInChildren<SkinnedMeshRenderer>();
meshInfos = Array.ConvertAll(_meshFilters, (m) => new MeshInfo(m));
ArrayUtility.AddRange(ref meshInfos, Array.ConvertAll(_meshRenderers, (m) => new MeshInfo(m)));
// Setup bounds.
assetBounds = new Bounds();
foreach (MeshInfo _mesh in meshInfos) {
Bounds _bounds = _mesh.Bounds;
_bounds.center -= _transform.position;
assetBounds.Encapsulate(_bounds);
}
// Select.
selectedAssetPath = _assetPath;
selectedAsset = _asset;
SessionState.SetString(SelectedAssetKey, _assetPath);
SetEnable(true);
}
#endregion
#region Window GUI
private static readonly Vector2 windowSize = new Vector2(400f, 300f);
/// <summary>
/// Creates and shows a new <see cref="SceneDesigner"/> window instance on screen.
/// </summary>
/// <returns><see cref="SceneDesigner"/> window instance on screen.</returns>
public static SceneDesigner GetWindow() {
SceneDesigner _window = CreateInstance<SceneDesigner>();
Vector2 _position = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);
Vector2 _size = windowSize;
_position.x -= 10f;
_position.y = GUIUtility.GUIToScreenPoint(new Vector2(0f, 22f)).y;
_window.position = new Rect(_position, _size);
_window.ShowPopup();
return _window;
}
// -------------------------------------------
// Window GUI
// -------------------------------------------
private const float LineHeight = 14f;
private const string NoAssetMessage = "No asset could be found in the specified folders. " +
"You can edit the scene designers folders using the button on the window top-right corner.";
private static readonly Color headerColor = new Color(.9f, .9f, .9f, 1f);
private static readonly Color prefabColor = new Color(.48f, .67f, .94f, 1f);
private static readonly Color hoverColor = new Color(1f, 1f, 1f, .07f);
private static readonly GUIContent headerGUI = new GUIContent("Game Objects & Prefabs:");
private static readonly Folder root = new Folder("Root");
private static Vector2 scroll = new Vector2();
private new bool hasFocus = false;
// -----------------------
private void OnEnable() {
RefreshFolders();
}
private void OnFocus() {
if (!InternalEditorUtility.isApplicationActive) {
//Close();
//return;
}
hasFocus = true;
}
private void OnGUI() {
// Close if not focused.
if (!hasFocus && !PreviewWindow.HasFocus) {
Close();
return;
}
using (var _scope = new GUILayout.ScrollViewScope(scroll)) {
scroll = _scope.scrollPosition;
GUILayout.Space(2f);
using (var _horizontalScope = new EditorGUILayout.HorizontalScope()) {
// Preferences button.
Rect _position = new Rect(_horizontalScope.rect) {
xMin = _horizontalScope.rect.xMax - 28f,
height = 20f
};
EnhancedEditorSettings.DrawUserSettingsButton(_position);
_position.xMin = 5f;
EnhancedEditorGUI.UnderlinedLabel(_position, headerGUI);
GUILayout.Space(5f);
// Content.
using (var _verticalScope = new GUILayout.VerticalScope()) {
// No asset message.
if (root.Folders.Count == 0) {
GUILayout.FlexibleSpace();
EditorGUILayout.HelpBox(NoAssetMessage, UnityEditor.MessageType.Info, true);
GUILayout.FlexibleSpace();
return;
}
GUILayout.Space(30f);
int _index = 0;
DrawFolder(root, ref _index);
GUILayout.Space(5f);
}
}
}
Repaint();
}
private void OnLostFocus() {
if (!PreviewWindow.HasFocus) {
Close();
}
hasFocus = false;
}
// -------------------------------------------
// GUI
// -------------------------------------------
private void DrawFolder(Folder _folder, ref int _index) {
Rect _origin = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(false, -EditorGUIUtility.standardVerticalSpacing));
Rect _position = new Rect(_origin);
// Folders on top.
foreach (Folder _subfolder in _folder.Folders) {
GUIContent _label = EnhancedEditorGUIUtility.GetLabelGUI(_subfolder.Name, _subfolder.Name);
_position = GetRect(ref _index, false);
using (var _noIndent = EnhancedEditorGUI.ZeroIndentScope())
using (var _scope = EnhancedGUI.GUIContentColor.Scope(headerColor)) {
_subfolder.Foldout = EditorGUI.Foldout(_position, _subfolder.Foldout, _label, true);
}
if (_subfolder.Foldout) {
using (var _scope = new EditorGUI.IndentLevelScope()) {
DrawFolder(_subfolder, ref _index);
}
}
}
// Assets.
foreach (Asset _asset in _folder.Assets) {
_position = GetRect(ref _index, true, _asset.Path);
using (var _noIndent = EnhancedEditorGUI.ZeroIndentScope()) {
// Label.
using (var _scope = EnhancedGUI.GUIContentColor.Scope(prefabColor)) {
Rect _temp = new Rect(_position) {
y = _position.y - 1f,
height = _position.height + 2f,
};
EditorGUI.LabelField(_temp, EnhancedEditorGUIUtility.GetLabelGUI(_asset.Name, _asset.Path), Styles.Label);
}
// Mini thumbnail.
if (_asset.Icon == null) {
GameObject _object = AssetDatabase.LoadAssetAtPath<GameObject>(_asset.Path);
Texture2D _icon = AssetPreview.GetAssetPreview(_object);
if ((_icon == null) && !AssetPreview.IsLoadingAssetPreview(_object.GetInstanceID())) {
_icon = AssetPreview.GetMiniThumbnail(_object);
}
_asset.Icon = _icon;
} else {
Rect _temp = new Rect(_position) {
x = _position.xMax - (_position.height + 3f),
y = _position.y + 1f,
width = LineHeight,
height = LineHeight
};
EditorGUI.DrawPreviewTexture(_temp, _asset.Icon);
// Preview window.
if (!PreviewWindow.HasFocus && _temp.Contains(Event.current.mousePosition)) {
_temp.position += position.position - scroll;
PreviewWindow.GetWindow(_temp, _asset.Icon);
}
}
if (_position.Event(out Event _event) == EventType.MouseDown) {
switch (_event.clickCount) {
// Select.
case 1:
SelectAsset(_asset.Path);
Repaint();
break;
// Close.
case 2:
Close();
break;
default:
break;
}
_event.Use();
}
}
}
// Vertical indent.
if ((Event.current.type == EventType.Repaint) && (EditorGUI.indentLevel != 0)) {
Rect _temp = new Rect() {
x = _origin.x - 9f,
y = _origin.y - 3,
yMax = _position.yMax - 7f,
width = 2f,
};
EnhancedEditorGUI.VerticalDottedLine(_temp, 1f, 1f);
}
}
private Rect GetRect(ref int _index, bool _isAsset, string _path = "") {
// Position.
Rect _position = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(true, LineHeight));
_position.yMin -= EditorGUIUtility.standardVerticalSpacing;
Rect _background = new Rect(_position) {
x = 0f,
width = position.width
};
_index++;
// Line background.
bool _selected = _isAsset && (selectedAssetPath == _path);
bool _isOdd = (_index % 2) != 0;
Color _backgroundColor = _isOdd ? EnhancedEditorGUIUtility.GUIPeerLineColor : EnhancedEditorGUIUtility.GUIThemeBackgroundColor;
EditorGUI.DrawRect(_background, _backgroundColor);
// Feedback background.
if (_selected) {
_backgroundColor = EnhancedEditorGUIUtility.GUISelectedColor;
EditorGUI.DrawRect(_background, _backgroundColor);
} else if (_background.Contains(Event.current.mousePosition)) {
EditorGUI.DrawRect(_background, hoverColor);
}
// Horizontal indent.
if ((Event.current.type == EventType.Repaint) && (EditorGUI.indentLevel != 0)) {
Rect _temp = new Rect() {
x = _position.x - 9f,
y = _position.y + 9f,
xMax = _position.x + 2f,
height = 2f,
};
EnhancedEditorGUI.HorizontalDottedLine(_temp, 1f, 1f);
}
return _position;
}
#endregion
#region Toolbar Extension
[EditorToolbarLeftExtension(Order = 100)]
private static void ToolbarExtension() {
int _result = EnhancedEditorToolbar.DropdownToggle(isEnabled, Styles.ToolbarButtonGUI, GUILayout.Width(32f));
switch (_result) {
// Enbled toggle.
case 0:
SetEnable(!isEnabled);
break;
// Asset selection.
case 1:
GetWindow();
break;
default:
break;
}
}
#endregion
#region Preview Window
/// <summary>
/// Preview <see cref="SceneDesigner"/> asset window.
/// </summary>
private class PreviewWindow : EditorWindow {
public static PreviewWindow GetWindow(Rect _screenPosition, Texture _preview) {
PreviewWindow _window = CreateInstance<PreviewWindow>();
Vector2 _position = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);
Vector2 _size = new Vector2(128f, 128f);
_window.screenPosition = _screenPosition;
_window.preview = _preview;
_window.position = new Rect(_position, _size);
_window.ShowPopup();
return _window;
}
// -------------------------------------------
// Window GUI
// -------------------------------------------
[NonSerialized] public static bool HasFocus = false;
private Rect screenPosition = default;
private Texture preview = null;
// -----------------------
private void OnEnable() {
HasFocus = true;
}
private void OnGUI() {
Vector2 _position = GUIUtility.GUIToScreenPoint(Event.current.mousePosition);
if (!screenPosition.Contains(_position)) {
Close();
return;
}
if (Event.current.type == EventType.Repaint) {
position = new Rect(_position, position.size);
}
Rect _temp = EditorGUILayout.GetControlRect(GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
EditorGUI.DrawPreviewTexture(_temp, preview);
Repaint();
}
private void OnDisable() {
HasFocus = false;
FocusWindowIfItsOpen<SceneDesigner>();
}
}
#endregion
#region Shortcut
private const float DefaultDistance = 999;
private static readonly Collider[] _colliderBuffer = new Collider[16];
// -----------------------
/// <summary>
/// Snaps selected objects to the nearest collider.
/// </summary>
[Shortcut("Enhanced Editor/Snap Object", KeyCode.PageDown)]
private static void SnapSelection() {
foreach (GameObject _gameObject in Selection.gameObjects) {
Collider _closest = null;
Vector3 _normal = default;
float _distance = DefaultDistance;
Transform _transform = _gameObject.transform;
Vector3 _position = _transform.position;
int _amount = Physics.OverlapSphereNonAlloc(_position, 10f, _colliderBuffer);
for (int i = 0; i < _amount; i++) {
Collider _collider = _colliderBuffer[i];
if (_collider.isTrigger || _collider.transform.IsChildOf(_transform))
continue;
Vector3 _point;
if ((_collider is MeshCollider) && Physics.Raycast(_position, -_transform.up, out RaycastHit hit, 10f)) {
_point = hit.point;
} else {
_point = _collider.ClosestPoint(_position);
}
float _pointDistance = (_point - _position).sqrMagnitude;
// Get nearest collider.
if (_pointDistance < _distance) {
_distance = _pointDistance;
_normal = _point - _position;
_closest = _collider;
}
}
// Extract from any overlapping collider.
if (!Mathf.Approximately(_distance, DefaultDistance)) {
_gameObject.transform.position += _normal;
foreach (Collider _collider in _gameObject.GetComponentsInChildren<Collider>()) {
if (_collider.isTrigger) {
continue;
}
if (Physics.ComputePenetration(_collider, _collider.transform.position, _collider.transform.rotation,
_closest, _closest.transform.position, _closest.transform.rotation, out _normal, out _distance)) {
_gameObject.transform.position += _normal * _distance;
}
}
}
}
}
#endregion
#region Utility
/// <summary>
/// Refreshes folders content and assets.
/// </summary>
public static void RefreshFolders() {
var _settings = SceneDesignerEnhancedSettings.Settings;
root.Folders.Clear();
int _count = _settings.Folders.Count;
if (_count == 0)
return;
string[] _pathHelpers = new string[_count];
for (int _i = 0; _i < _count; _i++) {
string _fullPath = Path.Combine("Assets", _settings.Folders[_i]);
_pathHelpers[_i] = _fullPath;
}
// Load all objects.
string[] _assets = Array.ConvertAll(AssetDatabase.FindAssets("t:GameObject", _pathHelpers), AssetDatabase.GUIDToAssetPath);
for (int _i = 0; _i < _count; _i++) {
string _base = _settings.Folders[_i].Split('/', '\\')[0];
_pathHelpers[_i] = string.IsNullOrEmpty(_base)
? InternalEditorUtility.GetAssetsFolder()
: _base;
}
// Register each asset.
foreach (string _path in _assets) {
string[] _directories = _path.Split('/', '\\');
int _index = 0;
while (Array.IndexOf(_pathHelpers, _directories[_index].Trim()) == -1) {
_index++;
}
root.RegisterAsset(_directories, _path, _index);
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.