text stringlengths 13 6.01M |
|---|
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Apix.Http.Client;
using Apix.Sync.YaMarket.Models;
namespace Apix.Sync.YaMarket
{
public class YaMarketClient : HttpClientBase
{
private UrlBuilder UrlBuilder => new UrlBuilder();
public YaMarketClient(ProxySettings proxy = null) : base(
new Dictionary<string, string>()
{
{"X-App-Version", "3.71"},
{"X-Platform", "ANDROID"},
{"X-Device-Type", "SMARTPHONE"},
{"User-Agent", "Yandex.Market/3.71 (Android/6.0.1; Nexus 5/google)"}
}, proxy: proxy)
{
}
public async Task<List<Offer>> ListOffers(int id, int count, CancellationToken cancellationToken)
{
var operationResult = await HttpClient.GetAsync(UrlBuilder.Offers(id),
requestParameters: new RequestParameters<OffersResult>
{
OnError = CommonBadResponse<OffersResult>
});
return operationResult?.Offers;
}
public async Task<List<Offer>> ListOffers(int id, int count, string latitude, string longitude, CancellationToken cancellationToken)
{
var operationResult = await HttpClient.GetAsync(UrlBuilder.Offers(id, latitude, longitude),
requestParameters: new RequestParameters<OffersResult>
{
OnError = CommonBadResponse<OffersResult>
});
return operationResult?.Offers;
}
public async Task<Content> Search(string query, CancellationToken cancellationToken)
{
var operationResult = await HttpClient.GetAsync(UrlBuilder.Search(query),
requestParameters: new RequestParameters<SearchResult>
{
OnError = CommonBadResponse<SearchResult>
});
return operationResult?.Redirects?.Content;
}
private Task<T> CommonBadResponse<T>(HttpResponseMessage response, CancellationToken cancellationToken)
where T : class
{
switch (response.StatusCode)
{
case HttpStatusCode.Conflict:
case HttpStatusCode.NotFound:
return Task.FromResult<T>(null);
default:
DefaultBadResponseAction(response, cancellationToken);
break;
}
return Task.FromResult<T>(null);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class HealthManagerPlayer : MonoBehaviour
{
private int maxHealth = 3;
private int currentHealth;
public Slider sliderHealth;
private PlayerManager playerManager;
void Start()
{
currentHealth = maxHealth;
playerManager = FindObjectOfType<PlayerManager>();
}
/// <summary>
/// Se le quita vida al personaje y se comprueba si tiene menos de 0 de vida
/// </summary>
/// <param name="damage">daņo causado al personaje</param>
public void MakeDamage(int damage)
{
currentHealth -= damage;
sliderHealth.value -= damage;
if (currentHealth <= 0)
{
playerManager.collisioned = false;
FindObjectOfType<UIManager>().Dead();
}
}
}
|
using System;
using Scripts.RemoteConfig;
using UnityEngine;
using Util;
namespace Ratings
{
[CreateAssetMenu(menuName = "Stencil/Ratings")]
public class RateSettings : Singleton<RateSettings>
{
public RateConfig Config = new RateConfig();
protected override void OnEnable()
{
base.OnEnable();
if (Application.isPlaying)
{
Config.BindRemoteConfig();
StencilRemote.OnRemoteConfig += OnRemote;
}
}
protected override void OnDisable()
{
base.OnDisable();
if (Application.isPlaying)
{
StencilRemote.OnRemoteConfig -= OnRemote;
}
}
private void OnRemote(object sender, EventArgs e)
{
Config.BindRemoteConfig();
}
}
} |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using SampleDatabaseApp.Model.Objects;
using System;
using System.IO;
namespace SampleDatabaseApp.Model
{
public class SampleDatabaseContext : DbContext
{
private static IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appsettings.json", false)
.Build();
private static SampleDatabaseContext _context;
public SampleDatabaseContext()
{
}
public SampleDatabaseContext(DbContextOptions<SampleDatabaseContext> options)
: base(options)
{
}
public static SampleDatabaseContext GetSampleDatabaseContext()
{
if (_context is null)
{
_context = new SampleDatabaseContext();
}
return _context;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(configuration["ConnectionString"]);
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Order> Orders { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
using API.Interfaces;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
namespace API.Data
{
public class PhotoRepository : IPhotoRepository
{
private readonly DataContext _scontext;
private readonly IMapper _smapper;
public PhotoRepository(DataContext context, IMapper mapper)
{
_smapper = mapper;
_scontext = context;
}
public async Task<Photo> GetPhotoById(int id)
{
return await _scontext.Photos.IgnoreQueryFilters().SingleOrDefaultAsync(x => x.Id == id);
}
public async Task<IEnumerable<PhotoForApprovalDTO>> GetUnapprovedPhotos()
{
return await _scontext.Photos
.IgnoreQueryFilters()
.Where(x => !x.IsApproved)
.ProjectTo<PhotoForApprovalDTO>(_smapper.ConfigurationProvider).ToListAsync();
}
public void RemovePhoto(Photo photo)
{
_scontext.Photos.Remove(photo);
}
}
} |
using EDU_Rent.business_layer;
using EDU_Rent.Data_Layer;
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EDU_Rent.data_layer
{
class Reports : DatabaseConnection
{
// Generates a report of todays orders
internal static void RunTodaysOrdersReport()
{
List<Order> orderlst = new List<Order>();
// load up the list with objects
orderlst = Orders.GetAllOrders();
StringBuilder sb = new StringBuilder();
foreach (Order order in orderlst)
{
if (order.OrderCreatedOn.Date == DateTime.Today && !order.InCart)
{
sb.AppendLine(
"</tr> " +
"<td>" + order.ID.ToString() + "</td>" +
"<td>" + order.BuyerUserName.ToString() + "</td>" +
"<td>" + order.OrderCreatedOn.ToLongDateString() + "</td>" +
"<td>" + order.PayPalEmail.ToString() + "</td>" +
"<td>" + order.RetainedEarnings.ToString("C2") + "</td>" +
"</td> "
);
}
}
if (sb.Length == 0)
{
sb.AppendLine("<div class=\"alert alert-info\">" +
"<a href=\"#\" class=\"alert-link\">No orders have been processed yet today.</a>" +
"</div>");
}
string template = File.ReadAllText(Directory.GetCurrentDirectory() + "\\Reporting\\Report1Template.html");
template = template.Replace("[reblock]", sb.ToString());
template = template.Replace("[ReportName]", "Todays Orders");
template = template.Replace("[SysDate]", DateTime.Now.ToLongDateString() + " at " + DateTime.Now.ToShortTimeString());
File.WriteAllText(Directory.GetCurrentDirectory() + "\\Reporting\\Generated\\Report1.html", template);
}
internal static void RunOutstandingActionReport()
{
List<business_layer.OrderLine> orderlinelst = new List<business_layer.OrderLine>();
// load up the list with objects
orderlinelst = OrderLines.GetAllOrderLine();
Order order = new Order();
StringBuilder sb = new StringBuilder();
foreach (OrderLine ol in orderlinelst)
{
if (!ol.SellerShippedBook || !ol.BuyerRecievedBook || !ol.BuyerShippedBookBack || !ol.SellerRecievedBookBack)
{
sb.AppendLine(
"</tr> " +
"<td>" + ol.ID.ToString() + "</td>" +
"<td>" + ol.BookSeller.ToString() + "</td>" +
"<td>" + order.GetBuyerNameByOrderID(ol.OrderID).ToString() + "</td>" +
(ol.SellerShippedBook ? "<td style=\"Color:green;\">yes</td>" : "<td style=\"Color:red;\">no</td>") +
(ol.BuyerRecievedBook ? "<td style=\"Color:green;\">yes</td>" : "<td style=\"Color:red;\">no</td>") +
(ol.BuyerShippedBookBack ? "<td style=\"Color:green;\">yes</td>" : "<td style=\"Color:red;\">no</td>") +
(ol.SellerRecievedBookBack ? "<td style=\"Color:green;\">yes</td>" : "<td style=\"Color:red;\">no</td>") +
"</td> "
);
}
}
if (sb.Length == 0)
{
sb.AppendLine("<div class=\"alert alert-info\">" +
"<a href=\"#\" class=\"alert-link\">No orderlines pending actions by users.</a>" +
"</div>");
}
string template = File.ReadAllText(Directory.GetCurrentDirectory() + "\\Reporting\\Report2Template.html");
template = template.Replace("[reblock]", sb.ToString());
template = template.Replace("[ReportName]", "Orders pending user actions");
template = template.Replace("[SysDate]", DateTime.Now.ToLongDateString() + " at " + DateTime.Now.ToShortTimeString());
File.WriteAllText(Directory.GetCurrentDirectory() + "\\Reporting\\Generated\\Report2.html", template);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Collections;
namespace TaskControll
{
public partial class TasksList : System.Web.UI.Page
{
string connectString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Malkollm\Documents\GIT\TaskControll\TaskControll\App_Data\FXDPlan.mdf;
Integrated Security = True; MultipleActiveResultSets=True;Application Name = EntityFramework";
protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = true;
Panel2.Visible = false;
if (!IsPostBack)
{
PopulateGridview();
PopulateData();
}
}
void PopulateGridview()
{
DataTable dtbl = new DataTable();
using (SqlConnection sqlCon = new SqlConnection(connectString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM FXDPlan", sqlCon);
sqlDa.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
myGridview.DataSource = dtbl;
myGridview.DataBind();
}
else
{
dtbl.Rows.Add(dtbl.NewRow());
myGridview.DataSource = dtbl;
myGridview.DataBind();
myGridview.Rows[0].Cells.Clear();
myGridview.Rows[0].Cells.Add(new TableCell());
myGridview.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
myGridview.Rows[0].Cells[0].Text = "Данные не найдены ...";
myGridview.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
private void PopulateData()
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
GridView1.DataSource = dc.FXDPlans.
OrderBy(a => a.name).
ThenBy(a => a.responsible).
ThenBy(a => a.executor).
ThenBy(a => a.department).
ThenBy(a => a.report).
ToList();
GridView1.DataBind();
}
}
protected void myGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
using (SqlConnection sqlCon = new SqlConnection(connectString))
{
sqlCon.Open();
string query = "INSERT INTO FXDPlan (name, responsible, executor, department, report) VALUES (@name, @responsible, @executor, @department, @report)";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("@name", (myGridview.FooterRow.FindControl("txtNameFooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@responsible", (myGridview.FooterRow.FindControl("txtResponsibleFooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@executor", (myGridview.FooterRow.FindControl("txtExecutorFooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@department", (myGridview.FooterRow.FindControl("txtDepartmentFooter") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@report", (myGridview.FooterRow.FindControl("txtReportFooter") as TextBox).Text.Trim());
sqlCmd.ExecuteNonQuery();
PopulateGridview();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
if (e.CommandName.Equals("Check"))
{
using (SqlConnection sqlCon = new SqlConnection(connectString))
{
sqlCon.Open();
string query = "SELECT name FROM FXDPlan";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("@name", (myGridview.FooterRow.FindControl("txtNameT") as TextBox).Text.Trim());
sqlCmd.ExecuteNonQuery();
PopulateGridview();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
protected void myGridview_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridview.EditIndex = e.NewEditIndex;
PopulateGridview();
}
//protected void myGridview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
//{
// myGridview.EditIndex = -1;
// PopulateGridview();
//}
protected void myGridview_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectString))
{
sqlCon.Open();
string query = "UPDATE FXDPlan SET name=@name, responsible=@responsible, executor=@executor, department=@department, report=@report WHERE Id=@id";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("@name", (myGridview.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@responsible", (myGridview.Rows[e.RowIndex].FindControl("txtResponsible") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@executor", (myGridview.Rows[e.RowIndex].FindControl("txtExecutor") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@department", (myGridview.Rows[e.RowIndex].FindControl("txtDepartment") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@report", (myGridview.Rows[e.RowIndex].FindControl("txtReport") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@id", Convert.ToInt32(myGridview.DataKeys[e.RowIndex].Value.ToString()));
sqlCmd.ExecuteNonQuery();
myGridview.EditIndex = -1;
PopulateGridview();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
protected void myGridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectString))
{
sqlCon.Open();
string query = "DELETE FROM FXDPlan WHERE Id=@id";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("@id", Convert.ToInt32(myGridview.DataKeys[e.RowIndex].Value.ToString()));
sqlCmd.ExecuteNonQuery();
PopulateGridview();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void ExportGrid(string fileName, string contenttype, Boolean checks = false)
{
GridView grid = GridView1;
if (checks)
{
// if (cb != null && cb.Checked)
//// {
//// gvExport.Rows[i.RowIndex].Visible = true;
//// }
grid.Visible = true;
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
Response.ContentType = contenttype;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.Close();
Response.End();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ExportGrid("GridviewData.doc", "application/vnd.ms-word", true);
////Export selected rows to Excel
////need to check is any row selected
//bool isSelected = false;
//foreach (GridViewRow i in myGridview.Rows)
//{
// CheckBox cb = (CheckBox)i.FindControl("chkSelect");
// if (cb != null && cb.Checked)
// {
// isSelected = true;
// break;
// }
//}
////export here
//if (isSelected)
//{
// GridView gvExport = myGridview;
// //this bellow line for not export to Excel
// gvExport.Columns[0].Visible = false;
// gvExport.Columns[6].Visible = false;
// gvExport.Columns[7].Visible = false;
// foreach (GridViewRow i in myGridview.Rows)
// {
// gvExport.Rows[i.RowIndex].Visible = false;
// CheckBox cb = (CheckBox)i.FindControl("chkSelect");
// if (cb != null && cb.Checked)
// {
// gvExport.Rows[i.RowIndex].Visible = true;
// }
// }
// Response.Clear();
// Response.Buffer = true;
// Response.AddHeader("content-disposition", "attachment;filename=ExportGridData.xls");
// Response.Charset = "";
// Response.ContentType = "application/vnd.ms-excel";
// StringWriter sw = new StringWriter();
// HtmlTextWriter htW = new HtmlTextWriter(sw);
// gvExport.RenderControl(htW);
// Response.Output.Write(sw.ToString());
// Response.End();
//}
//Response.AddHeader("content-disposition", "attachment;filename=ExportGridData.xls");
//Response.ContentType = "application/vnd.ms-excel";
//using(StringWriter sw = new StringWriter())
//{
// HtmlTextWriter htW = new HtmlTextWriter(sw);
// myGridview.AllowPaging = false;
// myGridview.RenderControl(htW);
// string style = @"<style> .textmode { mso-number-format:\@; } </style>";
// Response.Write(style);
// Response.Output.Write(sw);
// Response.Flush();
// Response.Close();
// Response.End();
//}
}
public override void VerifyRenderingInServerForm(Control control)
{
//this is added for error : GridView must be placed inside a form tag with runat=server
}
protected void Button2_Click(object sender, EventArgs e)
{
ExportGrid("GridviewData.xls", "application/vnd.ms-excel", true);
//Export selected rows to Word
//need to check is any row selected
//bool isSelected = false;
//foreach (GridViewRow i in myGridview.Rows)
//{
// CheckBox cb = (CheckBox)i.FindControl("chkSelect");
// if (cb != null && cb.Checked)
// {
// isSelected = true;
// break;
// }
//}
////export here
//if (isSelected)
//{
// GridView gvExport = myGridview;
// //this bellow line for not export to Excel
// gvExport.Columns[0].Visible = false;
// gvExport.Columns[6].Visible = false;
// gvExport.Columns[7].Visible = false;
// foreach (GridViewRow i in myGridview.Rows)
// {
// gvExport.Rows[i.RowIndex].Visible = false;
// CheckBox cb = (CheckBox)i.FindControl("chkSelect");
// if (cb != null && cb.Checked)
// {
// gvExport.Rows[i.RowIndex].Visible = true;
// }
// }
// Response.Clear();
// Response.Buffer = true;
// Response.AddHeader("content-disposition", "attachment;filename=FXDPlanTasks.doc");
// Response.Charset = "";
// Response.ContentType = "application/vnd.ms-word";
// StringWriter sw = new StringWriter();
// HtmlTextWriter htW = new HtmlTextWriter(sw);
// gvExport.RenderControl(htW);
// Response.Output.Write(sw.ToString());
// Response.End();
//}
}
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
Panel1.Visible = false;
Panel2.Visible = true;
}
protected void Button3_Click(object sender, EventArgs e)
{
Panel1.Visible = true;
Panel2.Visible = false;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RespawnTest : PowerUp
{
public override void Activate(PlayerStateMachine player)
{
Debug.Log("Teleport player to target powerup activated");
MyEventSystem.instance.OnTeleportPlayer(_player.transform);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MortgageCalculator.DAL.Data;
using MortgageCalculator.Model;
using System.Data.Entity;
namespace MortgageCalculator.DAL.Repositories
{
public class MortgageRepository : RepositoryBase<Mortgage>
{
public MortgageRepository(DataContext context) : base(context)
{
if (context == null)
throw new ArgumentNullException();
}
public override void Delete(Mortgage entity)
{
if (context.Entry(entity).State == EntityState.Detached)
{
context.Mortgages.Attach(entity);
}
context.Mortgages.Remove(entity);
}
public override IQueryable<Mortgage> GetAll()
{
return context.Mortgages;
}
public override Mortgage GetById(object id)
{
return context.Mortgages.Find(id);
}
public override void Insert(Mortgage entity)
{
context.Mortgages.Add(entity);
}
public override void Update(Mortgage entity)
{
context.Mortgages.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
}
}
|
/* **********************************************
* 版 权:亿水泰科(EWater)
* 创建人:zhujun
* 日 期:2018/11/20 17:09:19
* 描 述:Database
* *********************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Extensions.Configuration;
using System.Linq;
using EWF.Util;
using EWF.Data;
using EWF.Util.Page;
using System.Diagnostics;
namespace EWF.Data.Dapper
{
/// <summary>
/// Database的Dapper实现类
/// </summary>
public class Database : IDatabase, IDisposable
{
#region 构造函数
public Database(string connectionString, DatabaseType _dbType = DatabaseType.SqlServer)
{
ConnectionString = connectionString;
dbType = _dbType;
_connection = ConnectionFactory.CreateConnection(ConnectionString, _dbType);
}
public void Dispose()
{
if (Connection.State != ConnectionState.Closed)
{
if (_transaction != null)
{
_transaction.Rollback();
}
Connection.Close();
}
}
#endregion
#region 属 性
private DatabaseType dbType;
private IDbConnection _connection;
protected string ConnectionString;
public IDbConnection Connection
{
get
{
if (_connection.ConnectionString == "")
{
_connection = ConnectionFactory.CreateConnection(ConnectionString, dbType);
}
if (_connection.State == ConnectionState.Closed)
{
_connection.Open();
}
return _connection;
}
}
protected IDbTransaction _transaction;
public bool HasActiveTransaction
{
get
{
return _transaction != null;
}
}
#endregion
#region 事 务
public void BeginTransaction()
{
if (Connection.State == ConnectionState.Closed)
{
Connection.Open();
}
_transaction = Connection.BeginTransaction();
}
public void Commit()
{
_transaction.Commit();
_transaction = null;
}
public void Rollback()
{
_transaction.Rollback();
_transaction = null;
}
#endregion
#region 操作:Insert,Update,Delete
public virtual int Insert<T>(T entity) where T : class
{
var result = Connection.Insert<T>(entity, _transaction);
return result.ToInt() ;
}
public virtual TKey Insert<TKey, T>(T entity) where T : class
{
var result = Connection.Insert<TKey,T>(entity, _transaction);
return result;
}
public virtual void Insert<T>(IEnumerable<T> entities) where T : class
{
//如果有活动的事务,直接用现有的事务,如果没有事务,则创建事务,批量执行
if (HasActiveTransaction)
{
foreach (var item in entities)
{
Connection.Insert<T>(item, _transaction);
}
}
else
{
BeginTransaction();
try
{
foreach (var item in entities)
{
Connection.Insert<T>(item, _transaction);
}
Commit();
}
catch (Exception ex)
{
if (HasActiveTransaction)
{
Rollback();
}
throw ex;
}
}
}
public virtual void Insert<TKey, T>(IEnumerable<T> entities) where T : class
{
//如果有活动的事务,直接用现有的事务,如果没有事务,则创建事务,批量执行
if (HasActiveTransaction)
{
foreach (var item in entities)
{
Connection.Insert<TKey, T>(item, _transaction);
}
}
else
{
BeginTransaction();
try
{
foreach (var item in entities)
{
Connection.Insert<TKey, T>(item, _transaction);
}
Commit();
}
catch (Exception ex)
{
if (HasActiveTransaction)
{
Rollback();
}
throw ex;
}
}
}
public virtual int Update<T>(T entity) where T : class
{
return Connection.Update<T>(entity, _transaction);
}
public virtual int UpdateIgnoreNull<T>(T entity) where T : class
{
return Connection.UpdateIgnoreNull<T>(entity, _transaction);
}
public virtual void Update<T>(IEnumerable<T> entities) where T : class
{
//如果有活动的事务,直接用现有的事务,如果没有事务,则创建事务,批量执行
if (HasActiveTransaction)
{
foreach (var item in entities)
{
Connection.Update<T>(item, _transaction, null);
}
}
else
{
BeginTransaction();
try
{
foreach (var item in entities)
{
Connection.Update<T>(item, _transaction, null);
}
Commit();
}
catch (Exception ex)
{
if (HasActiveTransaction)
{
Rollback();
}
throw ex;
}
}
}
public virtual int Delete<T>(T entity) where T : class
{
return Connection.Delete<T>(entity, _transaction, null);
}
public virtual int Delete<T>(object id) where T : class
{
return Connection.Delete<T>(id, _transaction, null);
}
public virtual int DeleteList<T>(object whereConditions) where T : class
{
return Connection.DeleteList<T>(whereConditions, _transaction, null);
}
public virtual int DeleteList<T>(string conditions, object parameters = null) where T : class
{
return Connection.DeleteList<T>(conditions, parameters, _transaction, null);
}
#endregion
#region 查询:Single,List,Page,Skip,Take,Count
public virtual T Get<T>(object id) where T : class
{
return Connection.Get<T>(id, _transaction, null);
}
public virtual T GetSingle<T>(object whereCondition) where T : class
{
return Connection.GetList<T>(whereCondition, _transaction).FirstOrDefault();
}
public virtual T GetSingle<T>(string conditions, object parameters = null) where T : class
{
return Connection.GetList<T>(conditions, parameters, _transaction).FirstOrDefault();
}
public virtual IEnumerable<T> GetList<T>(object whereCondition) where T : class
{
return Connection.GetList<T>(whereCondition, _transaction);
}
public virtual IEnumerable<T> GetList<T>(string conditions, object parameters = null) where T : class
{
return Connection.GetList<T>(conditions, parameters, _transaction);
}
public virtual IEnumerable<T> GetSkipTake<T>(int skip, int take, string conditions, string orderby, object parameters = null) where T : class
{
throw new NotImplementedException();
}
public virtual IEnumerable<T> GetPage<T>(int pageNumber, int rowsPerPage, string conditions, string orderby, object parameters = null) where T : class
{
return Connection.GetListPaged<T>(pageNumber, rowsPerPage, conditions, orderby, parameters, _transaction);
}
public virtual IEnumerable<T> GetPage<T>(int pageNumber, int rowsPerPage, string tableName, string fileds, string conditions, string orderby, object parameters = null) where T : class
{
return Connection.GetListPaged<T>(pageNumber, rowsPerPage, tableName, fileds, conditions, orderby, parameters, _transaction);
}
public Page<T> GetListPaged<T>(int pageIndex, int pageSize, string conditions, string orderby, object parameters = null) where T : class
{
var totalItems = Count<T>(conditions);
var items = GetPage<T>(pageIndex, pageSize, conditions, orderby, parameters).ToList();
var lastPageItems = totalItems % pageSize;
var totalPages = totalItems / pageSize;
return new Page<T>
{
PageIndex = pageIndex,
PageSize = pageSize,
TotalItems = totalItems,
Items = items,
TotalPages = lastPageItems == 0 ? totalPages : totalPages + 1
};
}
public Page<T> GetListPaged<T>(int pageIndex, int pageSize, string tableName, string fileds, string conditions, string orderby, object parameters = null) where T : class
{
var items = GetPage<T>(pageIndex, pageSize, tableName, fileds, conditions, orderby, parameters).ToList();
var totalItems = Count(tableName, fileds, conditions, parameters);
var lastPageItems = totalItems % pageSize;
var totalPages = totalItems / pageSize;
return new Page<T>
{
PageIndex = pageIndex,
PageSize = pageSize,
TotalItems = totalItems,//lastPageItems == 0 ? totalPages : totalPages + 1,
Items = items,
TotalPages = lastPageItems == 0 ? totalPages : totalPages + 1//totalPages
};
}
/// <summary>
/// 存储过程分页-表名支持关联查询
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="tableName"></param>
/// <param name="fileds"></param>
/// <param name="conditions"></param>
/// <param name="orderby"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public Page<T> GetPagination_Join<T>(int pageIndex, int pageSize, string tableName, string fileds, string conditions, string orderby) where T : class
{
var parameters = new DynamicParameters();
parameters.Add("SqlWhere", conditions, dbType: DbType.String);
parameters.Add("PageSize", pageSize, dbType: DbType.Int32);
parameters.Add("PageIndex", pageIndex, dbType: DbType.Int32);
parameters.Add("SqlTable",tableName, dbType: DbType.String);
parameters.Add("SqlField", fileds, dbType: DbType.String);
parameters.Add("SqlOrder", orderby, dbType: DbType.String);
parameters.Add("Count", dbType: DbType.Int32, direction: ParameterDirection.Output);
var beforDT = System.DateTime.Now;
//耗时巨大的代码
var items = Connection.Query<T>("Pagination_Join", parameters, commandTimeout: 60, commandType: CommandType.StoredProcedure);
//var total = Convert.ToInt32(new DbHelper(Connection).ExecuteScalar(CommandType.Text, sql, null));
var afterDT = System.DateTime.Now;
var ts = afterDT.Subtract(beforDT);
if (Debugger.IsAttached)
Trace.WriteLine(String.Format("RecordCount总共花费{0}ms.", ts.TotalMilliseconds));
var totalItems = parameters.Get<int>("Count");
var lastPageItems = totalItems % pageSize;
var totalPages = totalItems / pageSize;
return new Page<T>
{
PageIndex = pageIndex,
PageSize = pageSize,
TotalItems = totalItems,//lastPageItems == 0 ? totalPages : totalPages + 1,
Items = items.ToList(),
TotalPages = lastPageItems == 0 ? totalPages : totalPages + 1//totalPages
};
}
public virtual int Count<T>(object whereConditions) where T : class
{
return Connection.RecordCount<T>(whereConditions, _transaction, null);
}
public virtual int Count<T>(string conditions, object parameters = null) where T : class
{
return Connection.RecordCount<T>(conditions, parameters, _transaction, null);
}
public virtual int Count(string tableName,string conditions, object parameters = null)
{
return Connection.RecordCount(tableName,conditions, parameters, _transaction, null);
}
private int Count(string tableName,string fileds, string conditions, object parameters = null)
{
var sb = new StringBuilder();
sb.AppendFormat("select {0} ",fileds);
sb.AppendFormat(" from {0} ", tableName);
if (!string.IsNullOrWhiteSpace(conditions))
{
if (!conditions.ToLower().TrimStart().StartsWith("where"))
{
sb.Append(" where ");
}
sb.Append(" " + conditions);
}
var sql = string.Format("Select Count(1) From ({0}) As t", sb.ToString());
//var beforDT = System.DateTime.Now;
//耗时巨大的代码
var total = Connection.ExecuteScalar<int>(sql, parameters);
//var afterDT = System.DateTime.Now;
//var ts = afterDT.Subtract(beforDT);
//if (Debugger.IsAttached)
// Trace.WriteLine(String.Format("RecordCount总共花费{0}ms.", ts.TotalMilliseconds));
//return total;
return Connection.ExecuteScalar<int>(sql, parameters);
}
#endregion
#region 执行: SQL 语句
public int ExecuteBySql(string strSql)
{
if (_transaction == null)
{
using (var connection = Connection)
{
return connection.Execute(strSql);
}
}
else
{
_transaction.Connection.Execute(strSql, null, _transaction);
return 0;
}
}
public int ExecuteBySql(string strSql, params DbParameter[] dbParameter)
{
if (_transaction == null)
{
using (var connection = Connection)
{
return connection.Execute(strSql, dbParameter);
}
}
else
{
_transaction.Connection.Execute(strSql, dbParameter, _transaction);
return 0;
}
}
public int ExecuteByProc(string procName)
{
if (_transaction == null)
{
using (var connection = Connection)
{
return connection.Execute(procName);
}
}
else
{
_transaction.Connection.Execute(procName, null, _transaction);
return 0;
}
}
public int ExecuteByProc(string procName, params DbParameter[] dbParameter)
{
if (_transaction == null)
{
using (var connection = Connection)
{
return connection.Execute(procName, dbParameter);
}
}
else
{
_transaction.Connection.Execute(procName, dbParameter, _transaction);
return 0;
}
}
#endregion
#region 查询: DataTable
public object FindObject(string strSql)
{
return FindObject(strSql, null);
}
public object FindObject(string strSql, DbParameter[] dbParameter)
{
using (var dbConnection = Connection)
{
return new DbHelper(dbConnection).ExecuteScalar(CommandType.Text, strSql, dbParameter);
}
}
public DataTable FindTable(string strSql)
{
return FindTable(strSql, null);
}
public DataTable FindTable(string strSql, DbParameter[] dbParameter)
{
using (var dbConnection = Connection)
{
var IDataReader = new DbHelper(dbConnection).ExecuteReader(CommandType.Text, strSql, dbParameter);
return ConvertExtension.IDataReaderToDataTable(IDataReader);
}
}
public DataTable FindTable(string strSql, string orderField, bool isAsc, int pageSize, int pageIndex, out int total)
{
return FindTable(strSql, null, orderField, isAsc, pageSize, pageIndex, out total);
}
public DataTable FindTable(string strSql, DbParameter[] dbParameter, string orderField, bool isAsc, int pageSize, int pageIndex, out int total)
{
using (var dbConnection = Connection)
{
StringBuilder sb = new StringBuilder();
if (pageIndex == 0)
{
pageIndex = 1;
}
int num = (pageIndex - 1) * pageSize;
int num1 = (pageIndex) * pageSize;
string OrderBy = "";
if (!string.IsNullOrEmpty(orderField))
{
if (orderField.ToUpper().IndexOf("ASC") + orderField.ToUpper().IndexOf("DESC") > 0)
{
OrderBy = "Order By " + orderField;
}
else
{
OrderBy = "Order By " + orderField + " " + (isAsc ? "ASC" : "DESC");
}
}
else
{
OrderBy = "order by (select 0)";
}
sb.Append("Select * From (Select ROW_NUMBER() Over (" + OrderBy + ")");
sb.Append(" As rowNum, * From (" + strSql + ") As T ) As N Where rowNum > " + num + " And rowNum <= " + num1 + "");
total = Convert.ToInt32(new DbHelper(dbConnection).ExecuteScalar(CommandType.Text, "Select Count(1) From (" + strSql + ") As t", dbParameter));
var IDataReader = new DbHelper(dbConnection).ExecuteReader(CommandType.Text, sb.ToString(), dbParameter);
DataTable resultTable = ConvertExtension.IDataReaderToDataTable(IDataReader);
resultTable.Columns.Remove("rowNum");
return resultTable;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Game.Utils;
using Game.Kernel;
using Game.Facade;
using Game.Entity.NativeWeb;
using System.Data;
namespace Game.Web.Match
{
public partial class Activity : UCPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
DataSet ds = FacadeManage.aideNativeWebFacade.GetList("Activity", 1, 1000, " ORDER BY SortID ASC,InputDate DESC", "").PageSet;
rptData.DataSource = ds;
rptData.DataBind();
if (ds.Tables[0].Rows.Count < anpPage.PageSize)
{
anpPage.Visible = false;
}
}
}
} |
using Swiddler.Security;
using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Serialization;
namespace Swiddler.Serialization
{
public class SslHandshake : IDisposable
{
[XmlAttribute] public string ProtocolVersion { get; set; }
[XmlAttribute] public int ProtocolVersionCode { get; set; }
public string Message { get; set; }
[XmlAttribute] public bool IsServer { get; set; }
[XmlAttribute] public bool IsClient { get; set; }
public SslClientHello ClientHello { get; set; }
public SslServerHello ServerHello { get; set; }
[XmlIgnore] public X509Certificate2[] ServerCertificate { get; set; } // chain as captured in RemoteCertificateValidationCallback; first cert if leaf
[XmlElement(nameof(ServerCertificate))]
public string[] ServerCertificateEncoded { get => EncodeCert(ServerCertificate); set => ServerCertificate = DecodeCert(value); }
[XmlIgnore] public X509Certificate2[] ClientCertificate { get; set; }
[XmlElement(nameof(ClientCertificate))]
public string[] ClientCertificateEncoded { get => EncodeCert(ClientCertificate); set => ClientCertificate = DecodeCert(value); }
[XmlAttribute] public int CipherAlgorithm { get; set; }
[XmlAttribute] public int CipherStrength { get; set; }
[XmlAttribute] public int HashStrength { get; set; }
[XmlAttribute] public int KeyExchangeAlgorithm { get; set; }
[XmlAttribute] public int KeyExchangeStrength { get; set; }
[XmlAttribute] public int HashAlgorithm { get; set; }
[XmlAttribute] public bool IsAuthenticated { get; set; } // true on successfully completed handshake
readonly Lazy<bool> isValidLazy;
public bool IsValid() => isValidLazy.Value;
public SslHandshake()
{
isValidLazy = new Lazy<bool>(() => GetPrimaryCertificateChain().ValidateChain());
}
public X509Certificate2[] GetPrimaryCertificateChain()
{
if (IsClient) return ServerCertificate;
if (IsServer) return ClientCertificate?.Any() == true ? ClientCertificate : ServerCertificate;
return null;
}
public SslHandshake(SslStreamExt stream, X509Certificate2[] chain) : this()
{
IsAuthenticated = stream.IsAuthenticated;
IsServer = stream.IsServer;
IsClient = !stream.IsServer;
ClientHello = stream.ClientHello;
ServerHello = stream.ServerHello;
if (IsClient)
{
Message = $"client connection";
ClientCertificate = GetLocalCert(stream);
ServerCertificate = chain;
}
if (IsServer)
{
Message = $"server connection";
ClientCertificate = chain;
ServerCertificate = GetLocalCert(stream);
}
if (IsAuthenticated)
{
ProtocolVersionCode = (int)stream.SslProtocol;
ProtocolVersion = GetVersionString(ProtocolVersionCode);
CipherAlgorithm = (int)stream.CipherAlgorithm;
CipherStrength = stream.CipherStrength;
HashAlgorithm = (int)stream.HashAlgorithm;
HashStrength = stream.HashStrength;
KeyExchangeAlgorithm = (int)stream.KeyExchangeAlgorithm;
KeyExchangeStrength = stream.KeyExchangeStrength;
if (ServerHello != null) ProtocolVersion += " / " + ServerHello.CipherSuiteName;
}
else
{
ProtocolVersion = "SSL/TLS";
Message += " error";
}
}
static X509Certificate2[] GetLocalCert(SslStreamExt stream)
{
if (stream.IsAuthenticated && stream.LocalCertificate != null)
{
var crt2 = new X509Certificate2(stream.LocalCertificate);
try
{
return new[] { crt2 }.CompleteChain(); // find missing chain certs
}
finally
{
crt2.Reset();
}
}
return new X509Certificate2[0];
}
public string SslProtocol => GetVersionString(ProtocolVersionCode);
string GetVersionString(int /* SslProtocols */ proto)
{
switch (proto)
{
case 12: return "SSLv2.0";
case 48: return "SSLv3.0";
case 192: return "TLSv1.0";
case 768: return "TLSv1.1";
case 3072: return "TLSv1.2";
case 12288: return "TLSv1.3";
}
return "#" + proto;
}
string[] EncodeCert(X509Certificate2[] crt)
{
if ((crt?.Length ?? 0) == 0) return null;
return crt.Select(EncodeCert).ToArray();
}
X509Certificate2[] DecodeCert(string[] base64)
{
if ((base64?.Length ?? 0) == 0) return null;
return base64.Select(DecodeCert).ToArray();
}
string EncodeCert(X509Certificate2 crt)
{
if (crt == null) return null;
return Convert.ToBase64String(crt.GetRawCertData());
}
X509Certificate2 DecodeCert(string base64)
{
if (string.IsNullOrEmpty(base64)) return null;
var crt = new X509Certificate2(Convert.FromBase64String(base64));
return crt;
}
public void Dispose()
{
foreach (var crt in ServerCertificate) crt?.Reset();
foreach (var crt in ClientCertificate) crt?.Reset();
ServerCertificate = null;
ClientCertificate = null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
namespace battleship_warmup_csharp
{
class Program
{
static void Main(string[] args)
{
// GamePlay.startGame("Battleships version 1.0 \n\nGame created by Andrzej && Mateusz","Let`s start");
int playerOcean1 = 1;
int playerOcean2 = 2;
Ocean ocean1 = new Ocean(playerOcean1);
Ocean ocean2 = new Ocean(playerOcean2);
placeShipsOnBoard(ocean1);
placeShipsOnBoard(ocean2);
Ocean currentOcean = ocean2;
string currentPlayer = "Player1";
bool gameOver = false;
while (!gameOver)
{
battle(currentOcean, currentPlayer);
if (currentOcean.isGameOver())
{
gameOver = true;
System.Console.WriteLine(GamePlay.howWin(currentOcean));
Thread.Sleep(500);
}
currentOcean = (currentOcean == ocean2) ? currentOcean = ocean1 : currentOcean = ocean2;
currentPlayer = (currentPlayer == "Player1") ? currentPlayer = "Player2" : currentPlayer = "Player1";
}
}
private static void battle(Ocean currentOcean, string currentPlayer)
{
string hiddenOcean = currentOcean.makeHiddenOcean(currentOcean.playerOcean);
GamePlay.displayOcean(hiddenOcean);
int x, y;
x = ReadCoordinate("X", currentPlayer);
y = ReadCoordinate("Y", currentPlayer);
try
{
if (currentOcean.Shoot(x, y))
{
System.Console.WriteLine("TRAFIONY!");
Thread.Sleep(1000);
}
else
{
System.Console.WriteLine("PUDŁO!");
Thread.Sleep(1000);
}
}
catch (ArgumentException e)
{
System.Console.WriteLine(e);
}
hiddenOcean = currentOcean.makeHiddenOcean(currentOcean.playerOcean);
GamePlay.displayOcean(hiddenOcean.ToString());
if (currentOcean.hasShipSunk())
{
GamePlay.DisplayMessage("hit and sunk");
}
}
private static void placeShipsOnBoard(Ocean ocean)
{
int posX;
int posY;
int numberOfShipsBefore;
foreach (KeyValuePair<string, int> ship in Ocean.shipsToLocate)
{
do
{
System.Console.WriteLine(ocean);
numberOfShipsBefore = ocean.getNumberOfShips();
List<int> shipDetails = askPlayerForShipDetalis(new string[] { "Type X: ", "Type Y: " }, ship.Key);
string orientation = askForShipOrientation("vertical [type v] or horizontal [type h]");
posX = shipDetails[0];
posY = shipDetails[1];
ocean.AddShip(ship.Value, posX, posY, orientation);
// Thread.Sleep(1000);
// Console.Clear();
} while (numberOfShipsBefore == ocean.getNumberOfShips());
}
GamePlay.displayOcean(ocean.ToString());
}
private static string getNameOfOcean(Ocean ocean)
{
return ocean.playerOcean == 1 ? "Player1 Ocean" : "Player 2 Ocean";
}
private static string askForShipOrientation(string orientation)
{
System.Console.WriteLine(orientation);
string answer = System.Console.ReadLine();
return answer;
}
private static List<int> askPlayerForShipDetalis(string[] questions, string shipName)
{
System.Console.WriteLine("Type cordinates for {0}", shipName);
List<Int32> answers = new List<int>();
foreach (var question in questions)
{
Console.WriteLine(question);
string answer = Console.ReadLine();
int cordidante;
while (int.TryParse(answer, out cordidante) == false || int.Parse(answer) < 1 || int.Parse(answer) > 10)
{
System.Console.WriteLine("Wrong. Please try again:\n{0}", question);
answer = System.Console.ReadLine();
}
answers.Add(cordidante);
}
return answers;
}
static int ReadCoordinate(string symbol, string currentPlayer)
{
int coor;
Console.WriteLine(currentPlayer + " provide " + symbol);
string input = Console.ReadLine();
while (int.TryParse(input, out coor) == false | int.Parse(input) < 1 || int.Parse(input) > 10)
{
Console.WriteLine("Invalid input!");
Console.WriteLine("Provide " + symbol);
input = Console.ReadLine();
}
return coor;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PanzerAnimations : MonoBehaviour {
public Animator animator;
//EFECTOS
public GameObject sangre;
public GameObject polv;
//----AGUA
public GameObject splash;
bool inwater;
public GameObject Ondas;
public Transform PasoD;
public Transform PasoI;
public GameObject pasopolvo;
public GameObject pasopolvo2;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(animator.GetCurrentAnimatorStateInfo(0).IsName("giro") || animator.GetCurrentAnimatorStateInfo(0).IsName("giro2"))
{
animator.SetBool("girar", false);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("paracaidasS"))
{
animator.SetBool("paracaidas", true);
}else
{
animator.SetBool("paracaidas", false);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("panzerpose"))
{
animator.SetBool("normal", false);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("jump2"))
{
animator.SetBool("falling", false);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("panzerwalk"))
{
animator.SetBool("walk", false);
animator.SetBool("walking", true);
}
//MUERTE
if(animator.GetCurrentAnimatorStateInfo(0).IsName("KillSimple") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillSimple2") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillBackJump")
|| animator.GetCurrentAnimatorStateInfo(0).IsName("KillEX") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillEX2") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillQuemado"))
{
animator.SetBool("muerto", true);
animator.SetInteger("muerte", 0);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("KillSimple3"))
{
animator.SetBool("muerto", true);
animator.SetBool("headShot", false);
gameObject.layer = LayerMask.NameToLayer("muerto");
//gameObject.tag = "Untagged";
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("KillKnife") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillKnife2"))
{
animator.SetBool("acuchillado", false);
animator.SetInteger("muerte", 0);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("KillJump"))
{
animator.SetInteger("muerte", 0);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("Hit"))
{
animator.SetInteger("cascado", 0);
}
if(animator.GetCurrentAnimatorStateInfo(0).IsName("panzerShot"))
{
animator.SetBool("disparo", false);
}
}
void OnTriggerEnter (Collider col)
{
if(col.gameObject.tag == "Water")
{
if(GetComponent<Rigidbody>().velocity.y <= -4f)
{
var efect = (GameObject)Instantiate(splash, new Vector3(PasoD.transform.position.x, col.gameObject.transform.position.y+0.1f, PasoD.transform.position.z), Quaternion.Euler(90,0,0));
}
Ondass.posOndas = col.gameObject.transform.position.y;
inwater = true;
}
}
void OnTriggerExit (Collider col)
{
if(col.gameObject.tag == "Water")
{
if(GetComponent<Rigidbody>().velocity.y >= 4f)
{
var efect = (GameObject)Instantiate(splash, new Vector3(PasoD.transform.position.x, col.gameObject.transform.position.y+0.1f, PasoD.transform.position.z), Quaternion.Euler(90,0,0));
}
inwater = false;
}
}
//EVENTOS SPINE
void blood ()
{
if(PlayerPrefs.GetInt("violencia") == 1)
{
var efect = (GameObject)Instantiate(sangre, transform.position, transform.rotation);
}
}
void muerto ()
{
Destroy(gameObject);
}
void polvo ()
{
if(!GetComponent<AI>().water )
{
var efect = (GameObject)Instantiate(polv, transform.position, transform.rotation);
Destroy(efect, 1.0f);
}
}
void paso()
{
if(!GetComponent<AI>().water)
{
var efect = (GameObject)Instantiate(pasopolvo, PasoD.transform.position, PasoD.transform.rotation);
}else
{
var efect = (GameObject)Instantiate(splash, transform.position, transform.rotation);
}
}
void paso2()
{
if(!GetComponent<AI>().water)
{
var efect = (GameObject)Instantiate(pasopolvo2, PasoI.transform.position, PasoI.transform.rotation);
}else
{
var efect = (GameObject)Instantiate(splash, transform.position, transform.rotation);
}
}
}
|
using System;
using System.Collections.Generic;
namespace TrainingPrep.collections
{
public class Movie : IEquatable<Movie>
{
public bool Equals(Movie other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return String.Equals(title, other.title);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Movie) obj);
}
public override int GetHashCode()
{
return (title != null ? title.GetHashCode() : 0);
}
public static bool operator ==(Movie left, Movie right)
{
return Equals(left, right);
}
public static bool operator !=(Movie left, Movie right)
{
return !Equals(left, right);
}
public string title { get; set; }
public ProductionStudio production_studio { get; set; }
public Genre genre { get; set; }
public int rating { get; set; }
public DateTime date_published { get; set; }
public override string ToString()
{
return $"title: {title}";
}
public static ICriteria<Movie> IsPublishedByAny(params ProductionStudio[] productionStudio)
{
return new PublishedByCriteria(productionStudio);
}
public static Predicate<Movie> IsProducedByPixarOrDisney()
{
return movie => movie.production_studio == ProductionStudio.Pixar || movie.production_studio == ProductionStudio.Disney;
}
public static ICriteria<Movie> IsNotPublishedBy(ProductionStudio productionStudio)
{
return new Negation<Movie>(IsPublishedByAny(productionStudio));
}
public static Predicate<Movie> IsPublishedAfter(int year)
{
return movie => movie.date_published.Year > year;
}
public static Predicate<Movie> IsPublishedBetween(int startYear, int endYear)
{
return movie => (movie.date_published.Year >= startYear && movie.date_published.Year <= endYear);
}
public class GenreCriteria : ICriteria<Movie>
{
private readonly Genre _kindOf;
public GenreCriteria(Genre kindOf)
{
_kindOf = kindOf;
}
public bool IsSatisfiedBy(Movie movie)
{
return movie.genre == _kindOf;
}
}
private class PublishedByCriteria : ICriteria<Movie>
{
private readonly List<ProductionStudio> _productionStudios;
public PublishedByCriteria(params ProductionStudio[] productionStudios)
{
_productionStudios = new List<ProductionStudio>(productionStudios);
}
public bool IsSatisfiedBy(Movie movie)
{
return _productionStudios.Contains(movie.production_studio);
}
}
}
public class Negation<Movie> : ICriteria<Movie>
{
private ICriteria<Movie> _criteriaToInvert;
public Negation(ICriteria<Movie> criteria)
{
_criteriaToInvert = criteria;
}
public bool IsSatisfiedBy(Movie item)
{
return !_criteriaToInvert.IsSatisfiedBy(item);
}
}
} |
// Decompiled with JetBrains decompiler
// Type: System.Data.Linq.Mapping.Strings
// Assembly: System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 43A00CAE-A2D4-43EB-9464-93379DA02EC9
// Assembly location: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Data.Linq.dll
namespace System.Data.Linq.Mapping
{
internal static class Strings
{
internal static string OwningTeam => SR.GetString(nameof(OwningTeam));
internal static string InvalidFieldInfo(object p0, object p1, object p2) => SR.GetString(nameof(InvalidFieldInfo), p0, p1, p2);
internal static string CouldNotCreateAccessorToProperty(object p0, object p1, object p2) => SR.GetString(nameof(CouldNotCreateAccessorToProperty), p0, p1, p2);
internal static string UnableToAssignValueToReadonlyProperty(object p0) => SR.GetString(nameof(UnableToAssignValueToReadonlyProperty), p0);
internal static string LinkAlreadyLoaded => SR.GetString(nameof(LinkAlreadyLoaded));
internal static string EntityRefAlreadyLoaded => SR.GetString(nameof(EntityRefAlreadyLoaded));
internal static string NoDiscriminatorFound(object p0) => SR.GetString(nameof(NoDiscriminatorFound), p0);
internal static string InheritanceTypeDoesNotDeriveFromRoot(object p0, object p1) => SR.GetString(nameof(InheritanceTypeDoesNotDeriveFromRoot), p0, p1);
internal static string AbstractClassAssignInheritanceDiscriminator(object p0) => SR.GetString(nameof(AbstractClassAssignInheritanceDiscriminator), p0);
internal static string CannotGetInheritanceDefaultFromNonInheritanceClass => SR.GetString(nameof(CannotGetInheritanceDefaultFromNonInheritanceClass));
internal static string InheritanceCodeMayNotBeNull => SR.GetString(nameof(InheritanceCodeMayNotBeNull));
internal static string InheritanceTypeHasMultipleDiscriminators(object p0) => SR.GetString(nameof(InheritanceTypeHasMultipleDiscriminators), p0);
internal static string InheritanceCodeUsedForMultipleTypes(object p0) => SR.GetString(nameof(InheritanceCodeUsedForMultipleTypes), p0);
internal static string InheritanceTypeHasMultipleDefaults(object p0) => SR.GetString(nameof(InheritanceTypeHasMultipleDefaults), p0);
internal static string InheritanceHierarchyDoesNotDefineDefault(object p0) => SR.GetString(nameof(InheritanceHierarchyDoesNotDefineDefault), p0);
internal static string InheritanceSubTypeIsAlsoRoot(object p0) => SR.GetString(nameof(InheritanceSubTypeIsAlsoRoot), p0);
internal static string NonInheritanceClassHasDiscriminator(object p0) => SR.GetString(nameof(NonInheritanceClassHasDiscriminator), p0);
internal static string MemberMappedMoreThanOnce(object p0) => SR.GetString(nameof(MemberMappedMoreThanOnce), p0);
internal static string BadStorageProperty(object p0, object p1, object p2) => SR.GetString(nameof(BadStorageProperty), p0, p1, p2);
internal static string IncorrectAutoSyncSpecification(object p0) => SR.GetString(nameof(IncorrectAutoSyncSpecification), p0);
internal static string UnhandledDeferredStorageType(object p0) => SR.GetString(nameof(UnhandledDeferredStorageType), p0);
internal static string BadKeyMember(object p0, object p1, object p2) => SR.GetString(nameof(BadKeyMember), p0, p1, p2);
internal static string ProviderTypeNotFound(object p0) => SR.GetString(nameof(ProviderTypeNotFound), p0);
internal static string MethodCannotBeFound(object p0) => SR.GetString(nameof(MethodCannotBeFound), p0);
internal static string UnableToResolveRootForType(object p0) => SR.GetString(nameof(UnableToResolveRootForType), p0);
internal static string MappingForTableUndefined(object p0) => SR.GetString(nameof(MappingForTableUndefined), p0);
internal static string CouldNotFindTypeFromMapping(object p0) => SR.GetString(nameof(CouldNotFindTypeFromMapping), p0);
internal static string TwoMembersMarkedAsPrimaryKeyAndDBGenerated(object p0, object p1) => SR.GetString(nameof(TwoMembersMarkedAsPrimaryKeyAndDBGenerated), p0, p1);
internal static string TwoMembersMarkedAsRowVersion(object p0, object p1) => SR.GetString(nameof(TwoMembersMarkedAsRowVersion), p0, p1);
internal static string TwoMembersMarkedAsInheritanceDiscriminator(object p0, object p1) => SR.GetString(nameof(TwoMembersMarkedAsInheritanceDiscriminator), p0, p1);
internal static string CouldNotFindRuntimeTypeForMapping(object p0) => SR.GetString(nameof(CouldNotFindRuntimeTypeForMapping), p0);
internal static string UnexpectedNull(object p0) => SR.GetString(nameof(UnexpectedNull), p0);
internal static string CouldNotFindElementTypeInModel(object p0) => SR.GetString(nameof(CouldNotFindElementTypeInModel), p0);
internal static string BadFunctionTypeInMethodMapping(object p0) => SR.GetString(nameof(BadFunctionTypeInMethodMapping), p0);
internal static string IncorrectNumberOfParametersMappedForMethod(object p0) => SR.GetString(nameof(IncorrectNumberOfParametersMappedForMethod), p0);
internal static string CouldNotFindRequiredAttribute(object p0, object p1) => SR.GetString(nameof(CouldNotFindRequiredAttribute), p0, p1);
internal static string InvalidDeleteOnNullSpecification(object p0) => SR.GetString(nameof(InvalidDeleteOnNullSpecification), p0);
internal static string MappedMemberHadNoCorrespondingMemberInType(object p0, object p1) => SR.GetString(nameof(MappedMemberHadNoCorrespondingMemberInType), p0, p1);
internal static string UnrecognizedAttribute(object p0) => SR.GetString(nameof(UnrecognizedAttribute), p0);
internal static string UnrecognizedElement(object p0) => SR.GetString(nameof(UnrecognizedElement), p0);
internal static string TooManyResultTypesDeclaredForFunction(object p0) => SR.GetString(nameof(TooManyResultTypesDeclaredForFunction), p0);
internal static string NoResultTypesDeclaredForFunction(object p0) => SR.GetString(nameof(NoResultTypesDeclaredForFunction), p0);
internal static string UnexpectedElement(object p0, object p1) => SR.GetString(nameof(UnexpectedElement), p0, p1);
internal static string ExpectedEmptyElement(object p0, object p1, object p2) => SR.GetString(nameof(ExpectedEmptyElement), p0, p1, p2);
internal static string DatabaseNodeNotFound(object p0) => SR.GetString(nameof(DatabaseNodeNotFound), p0);
internal static string DiscriminatorClrTypeNotSupported(object p0, object p1, object p2) => SR.GetString(nameof(DiscriminatorClrTypeNotSupported), p0, p1, p2);
internal static string IdentityClrTypeNotSupported(object p0, object p1, object p2) => SR.GetString(nameof(IdentityClrTypeNotSupported), p0, p1, p2);
internal static string PrimaryKeyInSubTypeNotSupported(object p0, object p1) => SR.GetString(nameof(PrimaryKeyInSubTypeNotSupported), p0, p1);
internal static string MismatchedThisKeyOtherKey(object p0, object p1) => SR.GetString(nameof(MismatchedThisKeyOtherKey), p0, p1);
internal static string InvalidUseOfGenericMethodAsMappedFunction(object p0) => SR.GetString(nameof(InvalidUseOfGenericMethodAsMappedFunction), p0);
internal static string MappingOfInterfacesMemberIsNotSupported(object p0, object p1) => SR.GetString(nameof(MappingOfInterfacesMemberIsNotSupported), p0, p1);
internal static string UnmappedClassMember(object p0, object p1) => SR.GetString(nameof(UnmappedClassMember), p0, p1);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using UnityEngine;
namespace ProBuilder2.Common
{
public static class pbUtil
{
private struct SearchRange
{
public int begin;
public int end;
public SearchRange(int begin, int end)
{
this.begin = begin;
this.end = end;
}
public bool Valid()
{
return this.end - this.begin > 1;
}
public int Center()
{
return this.begin + (this.end - this.begin) / 2;
}
public override string ToString()
{
return string.Concat(new object[]
{
"{",
this.begin,
", ",
this.end,
"} : ",
this.Center()
});
}
}
public static T[] GetComponents<T>(this GameObject[] _gameObjects) where T : Component
{
List<T> list = new List<T>();
for (int i = 0; i < _gameObjects.Length; i++)
{
list.AddRange(_gameObjects[i].get_transform().GetComponentsInChildren<T>());
}
return list.ToArray();
}
public static T[] GetComponents<T>(GameObject go) where T : Component
{
return new Transform[]
{
go.get_transform()
}.GetComponents<T>();
}
public static T[] GetComponents<T>(this Transform[] _transforms) where T : Component
{
List<T> list = new List<T>();
for (int i = 0; i < _transforms.Length; i++)
{
Transform transform = _transforms[i];
list.AddRange(transform.GetComponentsInChildren<T>());
}
return list.ToArray();
}
public static Vector3[] ToWorldSpace(this Transform t, Vector3[] v)
{
Vector3[] array = new Vector3[v.Length];
for (int i = 0; i < array.Length; i++)
{
array[i] = t.TransformPoint(v[i]);
}
return array;
}
public static T[] ValuesWithIndices<T>(T[] arr, int[] indices)
{
T[] array = new T[indices.Length];
for (int i = 0; i < indices.Length; i++)
{
array[i] = arr[indices[i]];
}
return array;
}
public static int[] AllIndexesOf<T>(T[] arr, T instance)
{
List<int> list = new List<int>();
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].Equals(instance))
{
list.Add(i);
}
}
return list.ToArray();
}
public static bool IsEqual<T>(this T[] a, T[] b)
{
if (a.Length != b.Length)
{
return false;
}
for (int i = 0; i < a.Length; i++)
{
if (!a[i].Equals(b[i]))
{
return false;
}
}
return true;
}
public static T[] Add<T>(this T[] arr, T val)
{
T[] array = new T[arr.Length + 1];
Array.ConstrainedCopy(arr, 0, array, 0, arr.Length);
array[arr.Length] = val;
return array;
}
public static T[] AddRange<T>(this T[] arr, T[] val)
{
T[] array = new T[arr.Length + val.Length];
Array.ConstrainedCopy(arr, 0, array, 0, arr.Length);
Array.ConstrainedCopy(val, 0, array, arr.Length, val.Length);
return array;
}
public static T[] Remove<T>(this T[] arr, T val)
{
List<T> list = new List<T>(arr);
list.Remove(val);
return list.ToArray();
}
public static T[] Remove<T>(this T[] arr, IEnumerable<T> val)
{
return Enumerable.ToArray<T>(Enumerable.Except<T>(arr, val));
}
public static T[] RemoveAt<T>(this T[] arr, int index)
{
T[] array = new T[arr.Length - 1];
int num = 0;
for (int i = 0; i < arr.Length; i++)
{
if (i != index)
{
array[num] = arr[i];
num++;
}
}
return array;
}
public static T[] RemoveAt<T>(this IList<T> list, IList<int> indices)
{
List<int> list2 = new List<int>(indices);
list2.Sort();
return list.SortedRemoveAt(list2);
}
public static T[] SortedRemoveAt<T>(this IList<T> list, IList<int> sorted_indices)
{
int count = sorted_indices.get_Count();
int count2 = list.get_Count();
T[] array = new T[count2 - count];
int num = 0;
for (int i = 0; i < count2; i++)
{
if (num < count && sorted_indices.get_Item(num) == i)
{
while (num < count && sorted_indices.get_Item(num) == i)
{
num++;
}
}
else
{
array[i - num] = list.get_Item(i);
}
}
return array;
}
public static int NearestIndexPriorToValue<T>(IList<T> sorted_list, T value) where T : IComparable<T>
{
int count = sorted_list.get_Count();
if (count < 1)
{
return -1;
}
pbUtil.SearchRange searchRange = new pbUtil.SearchRange(0, count - 1);
if (value.CompareTo(sorted_list.get_Item(0)) < 0)
{
return -1;
}
if (value.CompareTo(sorted_list.get_Item(count - 1)) > 0)
{
return count - 1;
}
while (searchRange.Valid())
{
T t = sorted_list.get_Item(searchRange.Center());
if (t.CompareTo(value) > 0)
{
searchRange.end = searchRange.Center();
}
else
{
searchRange.begin = searchRange.Center();
T t2 = sorted_list.get_Item(searchRange.begin + 1);
if (t2.CompareTo(value) >= 0)
{
return searchRange.begin;
}
}
}
return 0;
}
public static T[] FilledArray<T>(T val, int length)
{
T[] array = new T[length];
for (int i = 0; i < length; i++)
{
array[i] = val;
}
return array;
}
public static bool ContainsMatch<T>(this T[] a, T[] b)
{
for (int i = 0; i < a.Length; i++)
{
int num = Array.IndexOf<T>(b, a[i]);
if (num > -1)
{
return true;
}
}
return false;
}
public static bool ContainsMatch<T>(this T[] a, T[] b, out int index_a, out int index_b)
{
index_b = -1;
for (index_a = 0; index_a < a.Length; index_a++)
{
index_b = Array.IndexOf<T>(b, a[index_a]);
if (index_b > -1)
{
return true;
}
}
return false;
}
public static T[] Concat<T>(this T[] x, T[] y)
{
if (x == null)
{
throw new ArgumentNullException("x");
}
if (y == null)
{
throw new ArgumentNullException("y");
}
int num = x.Length;
Array.Resize<T>(ref x, x.Length + y.Length);
Array.Copy(y, 0, x, num, y.Length);
return x;
}
public static int IndexOf<T>(this List<List<T>> InList, T InValue)
{
for (int i = 0; i < InList.get_Count(); i++)
{
for (int j = 0; j < InList.get_Item(i).get_Count(); j++)
{
T t = InList.get_Item(i).get_Item(j);
if (t.Equals(InValue))
{
return i;
}
}
}
return -1;
}
public static Vector3 SnapValue(Vector3 vertex, float snpVal)
{
return new Vector3(snpVal * Mathf.Round(vertex.x / snpVal), snpVal * Mathf.Round(vertex.y / snpVal), snpVal * Mathf.Round(vertex.z / snpVal));
}
public static float SnapValue(float val, float snpVal)
{
return snpVal * Mathf.Round(val / snpVal);
}
public static Vector3 SnapValue(Vector3 vertex, Vector3 snap)
{
float x = vertex.x;
float y = vertex.y;
float z = vertex.z;
Vector3 result = new Vector3((Mathf.Abs(snap.x) >= 0.0001f) ? (snap.x * Mathf.Round(x / snap.x)) : x, (Mathf.Abs(snap.y) >= 0.0001f) ? (snap.y * Mathf.Round(y / snap.y)) : y, (Mathf.Abs(snap.z) >= 0.0001f) ? (snap.z * Mathf.Round(z / snap.z)) : z);
return result;
}
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).get_IsEnum())
{
throw new ArgumentException("T must be an enumerated type");
}
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
using (IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator())
{
while (enumerator.MoveNext())
{
T result = (T)((object)enumerator.get_Current());
if (result.ToString().ToLower().Equals(value.Trim().ToLower()))
{
return result;
}
}
}
return defaultValue;
}
public static Mesh DeepCopyMesh(Mesh _mesh)
{
Vector3[] array = new Vector3[_mesh.get_vertices().Length];
int[][] array2 = new int[_mesh.get_subMeshCount()][];
Vector2[] array3 = new Vector2[_mesh.get_uv().Length];
Vector2[] array4 = new Vector2[_mesh.get_uv2().Length];
Vector4[] array5 = new Vector4[_mesh.get_tangents().Length];
Vector3[] array6 = new Vector3[_mesh.get_normals().Length];
Color32[] array7 = new Color32[_mesh.get_colors32().Length];
Array.Copy(_mesh.get_vertices(), array, array.Length);
for (int i = 0; i < array2.Length; i++)
{
array2[i] = _mesh.GetTriangles(i);
}
Array.Copy(_mesh.get_uv(), array3, array3.Length);
Array.Copy(_mesh.get_uv2(), array4, array4.Length);
Array.Copy(_mesh.get_normals(), array6, array6.Length);
Array.Copy(_mesh.get_tangents(), array5, array5.Length);
Array.Copy(_mesh.get_colors32(), array7, array7.Length);
Mesh mesh = new Mesh();
mesh.Clear();
mesh.set_name(_mesh.get_name());
mesh.set_vertices(array);
mesh.set_subMeshCount(array2.Length);
for (int j = 0; j < array2.Length; j++)
{
mesh.SetTriangles(array2[j], j);
}
mesh.set_uv(array3);
mesh.set_uv2(array4);
mesh.set_tangents(array5);
mesh.set_normals(array6);
mesh.set_colors32(array7);
return mesh;
}
public static string ToFormattedString<T>(this T[] t, string _delimiter)
{
return t.ToFormattedString(_delimiter, 0, -1);
}
public static string ToFormattedString<T>(this T[] t, string _delimiter, int entriesPerLine, int maxEntries)
{
int num = (maxEntries <= 0) ? t.Length : Mathf.Min(t.Length, maxEntries);
if (t == null || num < 1)
{
return "Empty Array.";
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < num - 1; i++)
{
if (entriesPerLine > 0 && (i + 1) % entriesPerLine == 0)
{
stringBuilder.AppendLine(((t[i] != null) ? t[i].ToString() : "null") + _delimiter);
}
else
{
stringBuilder.Append(((t[i] != null) ? t[i].ToString() : "null") + _delimiter);
}
}
stringBuilder.Append((t[num - 1] != null) ? t[num - 1].ToString() : "null");
return stringBuilder.ToString();
}
public static string ToFormattedString(this pb_UV[] t, string _delimiter)
{
int num = t.Length;
if (t == null || num < 1)
{
return "Empty Array.";
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < num - 1; i++)
{
stringBuilder.AppendLine(((t[i] != null) ? t[i].ToString(_delimiter) : "null") + "\n");
}
stringBuilder.Append((t[num - 1] != null) ? t[num - 1].ToString(_delimiter) : "null");
return stringBuilder.ToString();
}
public static string ToFormattedString<T>(this List<T> t, string _delimiter)
{
return t.ToArray().ToFormattedString(_delimiter);
}
public static string ToFormattedString<T>(this HashSet<T> t, string _delimiter)
{
return Enumerable.ToArray<T>(t).ToFormattedString(_delimiter);
}
public static string StringWithDictionary<TKey, TValue>(this Dictionary<TKey, TValue> dict)
{
string text = string.Empty;
using (Dictionary<TKey, TValue>.Enumerator enumerator = dict.GetEnumerator())
{
while (enumerator.MoveNext())
{
KeyValuePair<TKey, TValue> current = enumerator.get_Current();
string text2 = text;
text = string.Concat(new object[]
{
text2,
"Key:",
current.get_Key(),
" Val: ",
current.get_Value(),
"\n"
});
}
}
return text;
}
public static bool ColorWithString(string value, out Color col)
{
string valid = "01234567890.,";
value = new string(Enumerable.ToArray<char>(Enumerable.Where<char>(value, (char c) => Enumerable.Contains<char>(valid, c))));
string[] array = value.Split(new char[]
{
','
});
if (array.Length < 4)
{
col = Color.get_white();
return false;
}
col = new Color(float.Parse(array[0]), float.Parse(array[1]), float.Parse(array[2]), float.Parse(array[3]));
return true;
}
public static Vector3[] StringToVector3Array(string str)
{
List<Vector3> list = new List<Vector3>();
str = str.Replace(" ", string.Empty);
string[] array = str.Split(new char[]
{
'\n'
});
string[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
string text = array2[i];
if (!text.Contains("//"))
{
string[] array3 = text.Split(new char[]
{
','
});
if (array3.Length >= 3)
{
float num;
if (float.TryParse(array3[0], 511, CultureInfo.get_InvariantCulture(), ref num))
{
float num2;
if (float.TryParse(array3[1], 511, CultureInfo.get_InvariantCulture(), ref num2))
{
float num3;
if (float.TryParse(array3[2], 511, CultureInfo.get_InvariantCulture(), ref num3))
{
list.Add(new Vector3(num, num2, num3));
}
}
}
}
}
}
return list.ToArray();
}
public static Vector2 DivideBy(this Vector2 v, Vector2 o)
{
return new Vector2(v.x / o.x, v.y / o.y);
}
public static Vector3 DivideBy(this Vector3 v, Vector3 o)
{
return new Vector3(v.x / o.x, v.y / o.y, v.z / o.z);
}
}
}
|
namespace Crt.Model.Dtos.QtyAccmp
{
public class QtyAccmpCreateDto : QtyAccmpSaveDto
{
}
}
|
namespace DDDSouthWest.Website.Features.Public.Account.Registration
{
public class RegistrationConfirmationViewModel
{
public bool RequireEmailConfirmation { get; set; }
}
} |
namespace Triton.Game.Mapping
{
using System;
public enum ShakeMinionType
{
Angle,
ImpactDirection,
RandomDirection
}
}
|
using System;
using System.Data.SqlClient;
using System.Reflection;
using System.Transactions;
using Microsoft.Practices.TransientFaultHandling;
using NUnit.Framework;
using ReliableDbProvider.SqlAzure;
using ReliableDbProvider.SqlAzureWithTimeoutRetries;
using ReliableDbProvider.Tests.Config;
namespace ReliableDbProvider.Tests
{
[TestFixture]
internal class SqlAzureTransientErrorDetectionStrategyWithTimeoutsShould : LowTimeoutDbTestBase<SqlClientFactory>
{
[Test]
public void Retry_when_timeout_occurs()
{
try
{
using (var context = GetContext())
{
context.Database.ExecuteSqlCommand(@"WAITFOR DELAY '00:02'");
}
}
catch (Exception e)
{
Assert.That(new SqlAzureTransientErrorDetectionStrategyWithTimeouts().IsTransient(e));
return;
}
Assert.Fail("No timeout exception was thrown!");
}
[Test]
public void Mark_unwrapped_timeout_exception_as_transient([Values(-2, 121)] int errorCode)
{
var e = SqlExceptionGenerator.GetSqlException(errorCode);
Assert.That(new SqlAzureTransientErrorDetectionStrategyWithTimeouts().IsTransient(e));
}
[Test]
public void Mark_wrapped_timeout_exception_as_transient([Values(-2, 121)] int errorCode)
{
var e = new Exception("Wrapped exception", SqlExceptionGenerator.GetSqlException(errorCode));
Assert.That(new SqlAzureTransientErrorDetectionStrategyWithTimeouts().IsTransient(e));
}
[Test]
public void Mark_timeout_exception_as_transient()
{
var e = new TimeoutException();
Assert.That(new SqlAzureTransientErrorDetectionStrategyWithTimeouts().IsTransient(e));
}
}
[TestFixture(typeof(SqlAzureTransientErrorDetectionStrategy))]
[TestFixture(typeof(SqlAzureTransientErrorDetectionStrategyWithTimeouts))]
class TransientErrorDetectionStrategyShould<TTransientErrorDetectionStrategy>
where TTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy, new()
{
[Test]
public void Mark_unwrapped_exceptions_as_transient()
{
var e = SqlExceptionGenerator.GetSqlException(40197);
Assert.That(new TTransientErrorDetectionStrategy().IsTransient(e));
}
[Test]
public void Mark_wrapped_exceptions_as_transient()
{
var e = new Exception("Wrapped exception", SqlExceptionGenerator.GetSqlException(40197));
Assert.That(new TTransientErrorDetectionStrategy().IsTransient(e));
}
[Test]
public void Mark_transaction_wrapped_exceptions_as_transient()
{
var e = new TransactionException("Wrapped exception", SqlExceptionGenerator.GetSqlException(40197));
Assert.That(new TTransientErrorDetectionStrategy().IsTransient(e));
}
[Test]
public void Mark_invalid_operation_exception_wrapped_exceptions_as_transient()
{
var e = new InvalidOperationException("Lazy load error", new Exception("Wrapped exception", SqlExceptionGenerator.GetSqlException(40197)));
Assert.That(new TTransientErrorDetectionStrategy().IsTransient(e));
}
}
internal static class SqlExceptionGenerator
{
public static SqlException GetSqlException(int errorCode)
{
var collection = (SqlErrorCollection)Activator.CreateInstance(typeof(SqlErrorCollection), true);
var error = (SqlError)Activator.CreateInstance(typeof(SqlError), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { errorCode, (byte)2, (byte)3, "server name", "error message", "proc", 100 }, null);
typeof(SqlErrorCollection)
.GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(collection, new object[] { error });
return typeof(SqlException)
.GetMethod("CreateException", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(SqlErrorCollection), typeof(string) }, null)
.Invoke(null, new object[] { collection, "7.0.0" }) as SqlException;
}
}
}
|
using ALM.Reclutamiento.Datos;
using ALM.Reclutamiento.Entidades;
using System.Collections.Generic;
using System.IO;
namespace ALM.Reclutamiento.Negocio
{
public class NEmpresa
{
public List<EEmpresa> ObtenerEmpresas(EEmpresa parametros)
{
return new DEmpresa().ObtenerEmpresas(parametros);
}
public List<EEmpresa> ObtenerEmpresasID(EEmpresa parametros)
{
return new DEmpresa().ObtenerEmpresasID(parametros);
}
public List<EEmpresa> ObtenerIdEmpresaSiguiente()
{
return new DEmpresa().ObtenerIdEmpresaSiguiente();
}
public void RegistrarEmpresa(EEmpresa parametro, byte[] archivo, string ruta)
{
if (archivo != null)
{
ruta = ruta + parametro.IdEmpresa.ToString() + @"\";
if (!Directory.Exists(ruta))
{
System.IO.Directory.CreateDirectory(ruta);
}
if (File.Exists(ruta + parametro.Logo))
{
File.Delete(ruta + parametro.Logo);
}
File.WriteAllBytes(ruta + parametro.Logo, archivo);
}
new DEmpresa().RegistrarEmpresa(parametro);
NClaseEstatica.EstablecerLstEmpresa();
}
public void ActualizarEmpresa(EEmpresa parametro, byte[] archivo, string ruta)
{
if (archivo != null)
{
ruta = ruta + parametro.IdEmpresa.ToString() + @"\";
if (!Directory.Exists(ruta))
{
System.IO.Directory.CreateDirectory(ruta);
}
if (File.Exists(ruta + parametro.Logo))
{
File.Delete(ruta + parametro.Logo);
}
File.WriteAllBytes(ruta + parametro.Logo, archivo);
}
new DEmpresa().ActualizarEmpresa(parametro);
NClaseEstatica.EstablecerLstEmpresa();
}
}
} |
using System;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using BIADTemplate.Model;
using Microsoft.Bot.Builder.CognitiveServices.QnAMaker;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using Newtonsoft.Json;
namespace BIADTemplate.Dialogs
{
/// <summary>
/// Qna-Powered dialog that is built to respond in RICH TEXT format
/// </summary>
[Serializable]
public class RichQnaDialog : QnAMakerDialog
{
private static readonly double SCORE_TRESHOLD = 0.8;
public RichQnaDialog()
: base(GetQnaService())
{
}
protected override async Task RespondFromQnAMakerResultAsync(IDialogContext context, IMessageActivity message, QnAMakerResults result)
{
var msg = context.MakeMessage();
var answer = result.Answers.FirstOrDefault(a => a.Score >= SCORE_TRESHOLD);
if (answer == null)
{
msg.Attachments.Add(BuildClarificationResponseCard(result));
}
else
{
msg.Attachments.Add(BuildResponseCard(answer));
}
await context.PostAsync(msg);
//context.Done(string.Empty);
}
private Attachment BuildClarificationResponseCard(QnAMakerResults result)
{
return new HeroCard
{
Text = "Did you mean one of these?",
Buttons = result.Answers.Select(a => new CardAction{
Type = ActionTypes.PostBack,
Title = a.Questions.First(),
Value = a.Questions.First()
}).ToList()
}
.ToAttachment();
}
private Attachment BuildResponseCard(QnAMakerResult answer)
{
var json = answer.Answer;
var response = JsonConvert.DeserializeObject<RichQnaResponse>(json);
return new HeroCard
{
Text = response.Title,
Subtitle = response.Text,
Images = new CardImage[]
{
new CardImage
{
Url = response.Image
}
}
}
.ToAttachment();
}
private static IQnAService GetQnaService()
{
var key = ConfigurationManager.AppSettings["QnaSubscriptionKey"];
var kbId = ConfigurationManager.AppSettings["QnaKnowledgebaseId"];
var qnaMakerAttribute = new QnAMakerAttribute(key, kbId);
return new QnAMakerService(qnaMakerAttribute);
}
}
} |
namespace Blorc.OpenIdConnect
{
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class CustomizeHttpRequestMessageDelegatingHandler : DelegatingHandler
{
private readonly IServiceProvider _serviceProvider;
private readonly Func<IServiceProvider, HttpRequestMessage, Task>? _customizeRequestFunction;
public CustomizeHttpRequestMessageDelegatingHandler(IServiceProvider serviceProvider, Func<IServiceProvider, HttpRequestMessage, Task>? customizeRequestFunction)
{
ArgumentNullException.ThrowIfNull(serviceProvider);
_serviceProvider = serviceProvider;
_customizeRequestFunction = customizeRequestFunction;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
if (_customizeRequestFunction is not null)
{
await _customizeRequestFunction(_serviceProvider, request);
}
return await base.SendAsync(request, cancellationToken);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication14
{
class Program
{
static void Main(string[] args)
{
Console.Write("Insert a number: ");
int number = int.Parse(Console.ReadLine());
bool state = false;
bool result = Number(state, number);
Console.Write("It is "+ result + " that the number is even.");
Console.ReadKey();
}
static bool Number(bool even, int number)
{
number = number % 2;
if (number > 0)
{
even = false;
}
else
{
even = true;
}
return even;
}
}
}
|
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
namespace PmipMyCallStack
{
public class PmipCallStackFilter : IDkmCallStackFilter
{
public DkmStackWalkFrame[] FilterNextFrame(DkmStackContext stackContext, DkmStackWalkFrame input)
{
if (input == null) // after last frame
return null;
if (input.InstructionAddress == null) // error case
return new[] { input };
if (input.InstructionAddress.ModuleInstance != null) // code in existing module
return new[] { input };
var runner = new PmipRunner(stackContext, input);
return new[] { runner.PmipStackFrame() };
}
}
} |
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UILabel : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
UILabel o = new UILabel();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetSides(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Transform relativeTo;
LuaObject.checkType<Transform>(l, 2, out relativeTo);
Vector3[] sides = uILabel.GetSides(relativeTo);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, sides);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int MarkAsChanged(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.MarkAsChanged();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ProcessText(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.ProcessText();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int MakePixelPerfect(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.MakePixelPerfect();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AssumeNaturalSize(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.AssumeNaturalSize();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetCharacterIndexAtPosition(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(Vector2), typeof(bool)))
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Vector2 localPos;
LuaObject.checkType(l, 2, out localPos);
bool precise;
LuaObject.checkType(l, 3, out precise);
int characterIndexAtPosition = uILabel.GetCharacterIndexAtPosition(localPos, precise);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, characterIndexAtPosition);
result = 2;
}
else if (LuaObject.matchType(l, total, 2, typeof(Vector3), typeof(bool)))
{
UILabel uILabel2 = (UILabel)LuaObject.checkSelf(l);
Vector3 worldPos;
LuaObject.checkType(l, 2, out worldPos);
bool precise2;
LuaObject.checkType(l, 3, out precise2);
int characterIndexAtPosition2 = uILabel2.GetCharacterIndexAtPosition(worldPos, precise2);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, characterIndexAtPosition2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetWordAtPosition(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(Vector2)))
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Vector2 localPos;
LuaObject.checkType(l, 2, out localPos);
string wordAtPosition = uILabel.GetWordAtPosition(localPos);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wordAtPosition);
result = 2;
}
else if (LuaObject.matchType(l, total, 2, typeof(Vector3)))
{
UILabel uILabel2 = (UILabel)LuaObject.checkSelf(l);
Vector3 worldPos;
LuaObject.checkType(l, 2, out worldPos);
string wordAtPosition2 = uILabel2.GetWordAtPosition(worldPos);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wordAtPosition2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetWordAtCharacterIndex(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int characterIndex;
LuaObject.checkType(l, 2, out characterIndex);
string wordAtCharacterIndex = uILabel.GetWordAtCharacterIndex(characterIndex);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, wordAtCharacterIndex);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetUrlAtPosition(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(Vector2)))
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Vector2 localPos;
LuaObject.checkType(l, 2, out localPos);
string urlAtPosition = uILabel.GetUrlAtPosition(localPos);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, urlAtPosition);
result = 2;
}
else if (LuaObject.matchType(l, total, 2, typeof(Vector3)))
{
UILabel uILabel2 = (UILabel)LuaObject.checkSelf(l);
Vector3 worldPos;
LuaObject.checkType(l, 2, out worldPos);
string urlAtPosition2 = uILabel2.GetUrlAtPosition(worldPos);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, urlAtPosition2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetUrlAtCharacterIndex(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int characterIndex;
LuaObject.checkType(l, 2, out characterIndex);
string urlAtCharacterIndex = uILabel.GetUrlAtCharacterIndex(characterIndex);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, urlAtCharacterIndex);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetCharacterIndex(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int currentIndex;
LuaObject.checkType(l, 2, out currentIndex);
KeyCode key;
LuaObject.checkEnum<KeyCode>(l, 3, out key);
int characterIndex = uILabel.GetCharacterIndex(currentIndex, key);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, characterIndex);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int PrintOverlay(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int start;
LuaObject.checkType(l, 2, out start);
int end;
LuaObject.checkType(l, 3, out end);
UIGeometry caret;
LuaObject.checkType<UIGeometry>(l, 4, out caret);
UIGeometry highlight;
LuaObject.checkType<UIGeometry>(l, 5, out highlight);
Color caretColor;
LuaObject.checkType(l, 6, out caretColor);
Color highlightColor;
LuaObject.checkType(l, 7, out highlightColor);
uILabel.PrintOverlay(start, end, caret, highlight, caretColor, highlightColor);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int OnFill(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
BetterList<Vector3> verts;
LuaObject.checkType<BetterList<Vector3>>(l, 2, out verts);
BetterList<Vector2> uvs;
LuaObject.checkType<BetterList<Vector2>>(l, 3, out uvs);
BetterList<Color32> cols;
LuaObject.checkType<BetterList<Color32>>(l, 4, out cols);
uILabel.OnFill(verts, uvs, cols);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ApplyOffset(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
BetterList<Vector3> verts;
LuaObject.checkType<BetterList<Vector3>>(l, 2, out verts);
int start;
LuaObject.checkType(l, 3, out start);
Vector2 o = uILabel.ApplyOffset(verts, start);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ApplyShadow(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
BetterList<Vector3> verts;
LuaObject.checkType<BetterList<Vector3>>(l, 2, out verts);
BetterList<Vector2> uvs;
LuaObject.checkType<BetterList<Vector2>>(l, 3, out uvs);
BetterList<Color32> cols;
LuaObject.checkType<BetterList<Color32>>(l, 4, out cols);
int start;
LuaObject.checkType(l, 5, out start);
int end;
LuaObject.checkType(l, 6, out end);
float x;
LuaObject.checkType(l, 7, out x);
float y;
LuaObject.checkType(l, 8, out y);
uILabel.ApplyShadow(verts, uvs, cols, start, end, x, y);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int CalculateOffsetToFit(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
int i = uILabel.CalculateOffsetToFit(text);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, i);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetCurrentProgress(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.SetCurrentProgress();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetCurrentPercent(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.SetCurrentPercent();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetCurrentSelection(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.SetCurrentSelection();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Wrap(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 3)
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
string s;
bool b = uILabel.Wrap(text, out s);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
LuaObject.pushValue(l, s);
result = 3;
}
else if (num == 4)
{
UILabel uILabel2 = (UILabel)LuaObject.checkSelf(l);
string text2;
LuaObject.checkType(l, 2, out text2);
int height;
LuaObject.checkType(l, 4, out height);
string s2;
bool b2 = uILabel2.Wrap(text2, out s2, height);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b2);
LuaObject.pushValue(l, s2);
result = 3;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int UpdateNGUIText(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
uILabel.UpdateNGUIText();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_keepCrispWhenShrunk(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushEnum(l, (int)uILabel.keepCrispWhenShrunk);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_keepCrispWhenShrunk(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
UILabel.Crispness keepCrispWhenShrunk;
LuaObject.checkEnum<UILabel.Crispness>(l, 2, out keepCrispWhenShrunk);
uILabel.keepCrispWhenShrunk = keepCrispWhenShrunk;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isAnchoredHorizontally(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.isAnchoredHorizontally);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isAnchoredVertically(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.isAnchoredVertically);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_material(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.material);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_material(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Material material;
LuaObject.checkType<Material>(l, 2, out material);
uILabel.material = material;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_bitmapFont(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.bitmapFont);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_bitmapFont(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
UIFont bitmapFont;
LuaObject.checkType<UIFont>(l, 2, out bitmapFont);
uILabel.bitmapFont = bitmapFont;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_trueTypeFont(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.trueTypeFont);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_trueTypeFont(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Font trueTypeFont;
LuaObject.checkType<Font>(l, 2, out trueTypeFont);
uILabel.trueTypeFont = trueTypeFont;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_ambigiousFont(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.ambigiousFont);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_ambigiousFont(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Object ambigiousFont;
LuaObject.checkType<Object>(l, 2, out ambigiousFont);
uILabel.ambigiousFont = ambigiousFont;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_text(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.text);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_text(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
uILabel.text = text;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_defaultFontSize(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.defaultFontSize);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_fontSize(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.fontSize);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_fontSize(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int fontSize;
LuaObject.checkType(l, 2, out fontSize);
uILabel.fontSize = fontSize;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_fontStyle(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushEnum(l, uILabel.fontStyle);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_fontStyle(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
FontStyle fontStyle;
LuaObject.checkEnum<FontStyle>(l, 2, out fontStyle);
uILabel.fontStyle = fontStyle;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_alignment(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushEnum(l, (int)uILabel.alignment);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_alignment(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
NGUIText.Alignment alignment;
LuaObject.checkEnum<NGUIText.Alignment>(l, 2, out alignment);
uILabel.alignment = alignment;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_applyGradient(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.applyGradient);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_applyGradient(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
bool applyGradient;
LuaObject.checkType(l, 2, out applyGradient);
uILabel.applyGradient = applyGradient;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_gradientTop(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.gradientTop);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_gradientTop(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Color gradientTop;
LuaObject.checkType(l, 2, out gradientTop);
uILabel.gradientTop = gradientTop;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_gradientBottom(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.gradientBottom);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_gradientBottom(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Color gradientBottom;
LuaObject.checkType(l, 2, out gradientBottom);
uILabel.gradientBottom = gradientBottom;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_spacingX(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.spacingX);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_spacingX(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int spacingX;
LuaObject.checkType(l, 2, out spacingX);
uILabel.spacingX = spacingX;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_spacingY(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.spacingY);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_spacingY(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int spacingY;
LuaObject.checkType(l, 2, out spacingY);
uILabel.spacingY = spacingY;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_useFloatSpacing(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.useFloatSpacing);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_useFloatSpacing(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
bool useFloatSpacing;
LuaObject.checkType(l, 2, out useFloatSpacing);
uILabel.useFloatSpacing = useFloatSpacing;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_floatSpacingX(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.floatSpacingX);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_floatSpacingX(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
float floatSpacingX;
LuaObject.checkType(l, 2, out floatSpacingX);
uILabel.floatSpacingX = floatSpacingX;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_floatSpacingY(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.floatSpacingY);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_floatSpacingY(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
float floatSpacingY;
LuaObject.checkType(l, 2, out floatSpacingY);
uILabel.floatSpacingY = floatSpacingY;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_effectiveSpacingY(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.effectiveSpacingY);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_effectiveSpacingX(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.effectiveSpacingX);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_supportEncoding(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.supportEncoding);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_supportEncoding(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
bool supportEncoding;
LuaObject.checkType(l, 2, out supportEncoding);
uILabel.supportEncoding = supportEncoding;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_symbolStyle(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushEnum(l, (int)uILabel.symbolStyle);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_symbolStyle(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
NGUIText.SymbolStyle symbolStyle;
LuaObject.checkEnum<NGUIText.SymbolStyle>(l, 2, out symbolStyle);
uILabel.symbolStyle = symbolStyle;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_overflowMethod(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushEnum(l, (int)uILabel.overflowMethod);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_overflowMethod(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
UILabel.Overflow overflowMethod;
LuaObject.checkEnum<UILabel.Overflow>(l, 2, out overflowMethod);
uILabel.overflowMethod = overflowMethod;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_multiLine(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.multiLine);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_multiLine(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
bool multiLine;
LuaObject.checkType(l, 2, out multiLine);
uILabel.multiLine = multiLine;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_localCorners(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.localCorners);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_worldCorners(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.worldCorners);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_drawingDimensions(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.drawingDimensions);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_maxLineCount(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.maxLineCount);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_maxLineCount(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
int maxLineCount;
LuaObject.checkType(l, 2, out maxLineCount);
uILabel.maxLineCount = maxLineCount;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_effectStyle(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushEnum(l, (int)uILabel.effectStyle);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_effectStyle(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
UILabel.Effect effectStyle;
LuaObject.checkEnum<UILabel.Effect>(l, 2, out effectStyle);
uILabel.effectStyle = effectStyle;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_effectColor(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.effectColor);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_effectColor(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Color effectColor;
LuaObject.checkType(l, 2, out effectColor);
uILabel.effectColor = effectColor;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_effectDistance(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.effectDistance);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_effectDistance(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
Vector2 effectDistance;
LuaObject.checkType(l, 2, out effectDistance);
uILabel.effectDistance = effectDistance;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_processedText(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.processedText);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_printedSize(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.printedSize);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_localSize(IntPtr l)
{
int result;
try
{
UILabel uILabel = (UILabel)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uILabel.localSize);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UILabel");
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.GetSides));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.MarkAsChanged));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.ProcessText));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.MakePixelPerfect));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.AssumeNaturalSize));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.GetCharacterIndexAtPosition));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.GetWordAtPosition));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.GetWordAtCharacterIndex));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.GetUrlAtPosition));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.GetUrlAtCharacterIndex));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.GetCharacterIndex));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.PrintOverlay));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.OnFill));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.ApplyOffset));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.ApplyShadow));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.CalculateOffsetToFit));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.SetCurrentProgress));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.SetCurrentPercent));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.SetCurrentSelection));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.Wrap));
LuaObject.addMember(l, new LuaCSFunction(Lua_UILabel.UpdateNGUIText));
LuaObject.addMember(l, "keepCrispWhenShrunk", new LuaCSFunction(Lua_UILabel.get_keepCrispWhenShrunk), new LuaCSFunction(Lua_UILabel.set_keepCrispWhenShrunk), true);
LuaObject.addMember(l, "isAnchoredHorizontally", new LuaCSFunction(Lua_UILabel.get_isAnchoredHorizontally), null, true);
LuaObject.addMember(l, "isAnchoredVertically", new LuaCSFunction(Lua_UILabel.get_isAnchoredVertically), null, true);
LuaObject.addMember(l, "material", new LuaCSFunction(Lua_UILabel.get_material), new LuaCSFunction(Lua_UILabel.set_material), true);
LuaObject.addMember(l, "bitmapFont", new LuaCSFunction(Lua_UILabel.get_bitmapFont), new LuaCSFunction(Lua_UILabel.set_bitmapFont), true);
LuaObject.addMember(l, "trueTypeFont", new LuaCSFunction(Lua_UILabel.get_trueTypeFont), new LuaCSFunction(Lua_UILabel.set_trueTypeFont), true);
LuaObject.addMember(l, "ambigiousFont", new LuaCSFunction(Lua_UILabel.get_ambigiousFont), new LuaCSFunction(Lua_UILabel.set_ambigiousFont), true);
LuaObject.addMember(l, "text", new LuaCSFunction(Lua_UILabel.get_text), new LuaCSFunction(Lua_UILabel.set_text), true);
LuaObject.addMember(l, "defaultFontSize", new LuaCSFunction(Lua_UILabel.get_defaultFontSize), null, true);
LuaObject.addMember(l, "fontSize", new LuaCSFunction(Lua_UILabel.get_fontSize), new LuaCSFunction(Lua_UILabel.set_fontSize), true);
LuaObject.addMember(l, "fontStyle", new LuaCSFunction(Lua_UILabel.get_fontStyle), new LuaCSFunction(Lua_UILabel.set_fontStyle), true);
LuaObject.addMember(l, "alignment", new LuaCSFunction(Lua_UILabel.get_alignment), new LuaCSFunction(Lua_UILabel.set_alignment), true);
LuaObject.addMember(l, "applyGradient", new LuaCSFunction(Lua_UILabel.get_applyGradient), new LuaCSFunction(Lua_UILabel.set_applyGradient), true);
LuaObject.addMember(l, "gradientTop", new LuaCSFunction(Lua_UILabel.get_gradientTop), new LuaCSFunction(Lua_UILabel.set_gradientTop), true);
LuaObject.addMember(l, "gradientBottom", new LuaCSFunction(Lua_UILabel.get_gradientBottom), new LuaCSFunction(Lua_UILabel.set_gradientBottom), true);
LuaObject.addMember(l, "spacingX", new LuaCSFunction(Lua_UILabel.get_spacingX), new LuaCSFunction(Lua_UILabel.set_spacingX), true);
LuaObject.addMember(l, "spacingY", new LuaCSFunction(Lua_UILabel.get_spacingY), new LuaCSFunction(Lua_UILabel.set_spacingY), true);
LuaObject.addMember(l, "useFloatSpacing", new LuaCSFunction(Lua_UILabel.get_useFloatSpacing), new LuaCSFunction(Lua_UILabel.set_useFloatSpacing), true);
LuaObject.addMember(l, "floatSpacingX", new LuaCSFunction(Lua_UILabel.get_floatSpacingX), new LuaCSFunction(Lua_UILabel.set_floatSpacingX), true);
LuaObject.addMember(l, "floatSpacingY", new LuaCSFunction(Lua_UILabel.get_floatSpacingY), new LuaCSFunction(Lua_UILabel.set_floatSpacingY), true);
LuaObject.addMember(l, "effectiveSpacingY", new LuaCSFunction(Lua_UILabel.get_effectiveSpacingY), null, true);
LuaObject.addMember(l, "effectiveSpacingX", new LuaCSFunction(Lua_UILabel.get_effectiveSpacingX), null, true);
LuaObject.addMember(l, "supportEncoding", new LuaCSFunction(Lua_UILabel.get_supportEncoding), new LuaCSFunction(Lua_UILabel.set_supportEncoding), true);
LuaObject.addMember(l, "symbolStyle", new LuaCSFunction(Lua_UILabel.get_symbolStyle), new LuaCSFunction(Lua_UILabel.set_symbolStyle), true);
LuaObject.addMember(l, "overflowMethod", new LuaCSFunction(Lua_UILabel.get_overflowMethod), new LuaCSFunction(Lua_UILabel.set_overflowMethod), true);
LuaObject.addMember(l, "multiLine", new LuaCSFunction(Lua_UILabel.get_multiLine), new LuaCSFunction(Lua_UILabel.set_multiLine), true);
LuaObject.addMember(l, "localCorners", new LuaCSFunction(Lua_UILabel.get_localCorners), null, true);
LuaObject.addMember(l, "worldCorners", new LuaCSFunction(Lua_UILabel.get_worldCorners), null, true);
LuaObject.addMember(l, "drawingDimensions", new LuaCSFunction(Lua_UILabel.get_drawingDimensions), null, true);
LuaObject.addMember(l, "maxLineCount", new LuaCSFunction(Lua_UILabel.get_maxLineCount), new LuaCSFunction(Lua_UILabel.set_maxLineCount), true);
LuaObject.addMember(l, "effectStyle", new LuaCSFunction(Lua_UILabel.get_effectStyle), new LuaCSFunction(Lua_UILabel.set_effectStyle), true);
LuaObject.addMember(l, "effectColor", new LuaCSFunction(Lua_UILabel.get_effectColor), new LuaCSFunction(Lua_UILabel.set_effectColor), true);
LuaObject.addMember(l, "effectDistance", new LuaCSFunction(Lua_UILabel.get_effectDistance), new LuaCSFunction(Lua_UILabel.set_effectDistance), true);
LuaObject.addMember(l, "processedText", new LuaCSFunction(Lua_UILabel.get_processedText), null, true);
LuaObject.addMember(l, "printedSize", new LuaCSFunction(Lua_UILabel.get_printedSize), null, true);
LuaObject.addMember(l, "localSize", new LuaCSFunction(Lua_UILabel.get_localSize), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UILabel.constructor), typeof(UILabel), typeof(UIWidget));
}
}
|
using System;
namespace Tools.extensions.enums
{
public static class GetEnumDisplayValue
{
public static string GetStringValue(this Enum value)
{
var type = value.GetType();
var fieldInfo = type.GetField(value.ToString());
var attributes = fieldInfo.GetCustomAttributes(typeof(EnumDisplayAttribute), false) as EnumDisplayAttribute[];
return attributes != null && attributes.Length > 0 ? attributes[0].String : string.Empty;
}
}
} |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Server.Migrations
{
public partial class RenameCreateDateAndModifiedDate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "ModifiedDate",
table: "Users",
newName: "ModifiedDateTime");
migrationBuilder.RenameColumn(
name: "CreatedDate",
table: "Users",
newName: "CreatedDateTime");
migrationBuilder.RenameColumn(
name: "ModifiedDate",
table: "Posts",
newName: "ModifiedDateTime");
migrationBuilder.RenameColumn(
name: "CreatedDate",
table: "Posts",
newName: "CreatedDateTime");
migrationBuilder.RenameColumn(
name: "ModifiedDate",
table: "EventAttendee",
newName: "ModifiedDateTime");
migrationBuilder.RenameColumn(
name: "CreatedDate",
table: "EventAttendee",
newName: "CreatedDateTime");
migrationBuilder.RenameColumn(
name: "ModifiedDate",
table: "Communities",
newName: "ModifiedDateTime");
migrationBuilder.RenameColumn(
name: "CreatedDate",
table: "Communities",
newName: "CreatedDateTime");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "ModifiedDateTime",
table: "Users",
newName: "ModifiedDate");
migrationBuilder.RenameColumn(
name: "CreatedDateTime",
table: "Users",
newName: "CreatedDate");
migrationBuilder.RenameColumn(
name: "ModifiedDateTime",
table: "Posts",
newName: "ModifiedDate");
migrationBuilder.RenameColumn(
name: "CreatedDateTime",
table: "Posts",
newName: "CreatedDate");
migrationBuilder.RenameColumn(
name: "ModifiedDateTime",
table: "EventAttendee",
newName: "ModifiedDate");
migrationBuilder.RenameColumn(
name: "CreatedDateTime",
table: "EventAttendee",
newName: "CreatedDate");
migrationBuilder.RenameColumn(
name: "ModifiedDateTime",
table: "Communities",
newName: "ModifiedDate");
migrationBuilder.RenameColumn(
name: "CreatedDateTime",
table: "Communities",
newName: "CreatedDate");
}
}
}
|
using Android.Content;
using System.Threading.Tasks;
using Xamarin.Forms;
using App1.Droid.Services;
using App1.Services;
[assembly: Dependency(typeof(CClipboard))]
namespace App1.Droid.Services
{
public class CClipboard : IClipboard
{
public string GetText()
{
return GetTextInternal();
}
public Task<string> GetTextAsync()
{
return Task.FromResult(GetTextInternal());
}
private string GetTextInternal()
{
var clipboardManager = (ClipboardManager)Forms.Context.GetSystemService(Context.ClipboardService);
var item = clipboardManager.PrimaryClip.GetItemAt(0);
var text = item.Text;
return text;
}
public void SetText(string data)
{
var clipboardManager = (ClipboardManager)Forms.Context.GetSystemService(Context.ClipboardService);
ClipData clip = ClipData.NewPlainText("", data);
clipboardManager.PrimaryClip = clip;
}
}
} |
using System;
using System.Diagnostics;
using Microsoft.ApplicationServer.Caching;
namespace Jayway.Throttling
{
public class AzureCacheThrottlingService : IThrottlingService
{
readonly ICostCalculator _costCalculator;
readonly DataCache _dataCache;
public AzureCacheThrottlingService(DataCache dataCache, ICostCalculator costCalculator)
{
_dataCache = dataCache;
_costCalculator = costCalculator;
}
public bool Allow(string account, long cost, Func<Interval> intervalFactory)
{
var interval = intervalFactory();
try
{
var result = _dataCache.GetRemainingCredits(account, cost, interval.Credits,
TimeSpan.FromSeconds(interval.Seconds),
_costCalculator);
Debug.WriteLine("Remaining credits: {0}", result);
return result >= 0;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return true;
}
}
}
} |
using System;
using CobWebs.Test.Domain;
using CobWebs.Test.Domain.Strategy;
namespace CobWebs.Test.Abstraction
{
public class PlayerFactory: IPlayerFactory
{
public IPlayer Create(string playerName, PlayerStrategyType strategyType, BasketGameConfig config)
{
switch (strategyType)
{
case PlayerStrategyType.Random:
return new BasketGamePlayer(new RandomPlayerStrategy(config), playerName);
case PlayerStrategyType.Memory:
return new BasketGamePlayer(new MemoryPlayerStrategy(config), playerName);
case PlayerStrategyType.Thorough:
return new BasketGamePlayer(new ThoroughPlayerStrategy(config), playerName);
case PlayerStrategyType.Cheater:
return new BasketGamePlayer(new CheaterPlayerStrategy(config), playerName);
case PlayerStrategyType.ThoroughCheater:
return new BasketGamePlayer(new ThoroughCheaterPlayerStrategy(config), playerName);
default:
throw new ArgumentOutOfRangeException(nameof(strategyType), strategyType, null);
}
}
}
} |
namespace TipsAndTricksLibrary.Extensions
{
using System.Collections.Generic;
using System.Linq;
public static class EnumerableExtensions
{
public static bool EqualsByElements<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
{
if (ReferenceEquals(first, second))
return true;
if (ReferenceEquals(first, null) || ReferenceEquals(second, null))
return false;
return first.SequenceEqual(second);
}
}
} |
using INSADesignPattern.Observer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace INSADesignPattern.Observables
{
class SmileyObservable : IObservable
{
public bool Execute()
{
Console.WriteLine(":(");
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Proyecto_Final.Entidades
{
public class Clientes
{
[Key]
public int ClienteId { get; set; }
public string Nombre { get; set; }
public string Direcion { get; set; }
public long Cedula { get; set; }
public long Telefono { get; set; }
public long Celular { get; set; }
public string Apellidos { get; set; }
public string Email { get; set; }
public DateTime FechaR { get; set; } = DateTime.Now;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public GameObject Item;
public GameObject targetPos;
float pressTime = 0;
float delay = 1;
public GameObject Laser;
//적캐릭터가 목표로 해야하는 대상의 위치=플레이어
Vector3 dir;//에너미의 이동방향
void Start()
{
targetPos = GameObject.Find("Player");
//목표물을 찾아서 변수에 저장
}
void Update()
{
if(targetPos != null)
//target 즉 플레이어가 존재할 때만
//에너미가 플레이어 방향으로 움직이고
//플레이어 방향으로 총알을 발사한다
//플레이어가 총알을 맞고 삭제된다면 더이상 이동도 발사도 하지 않게 된다.
{
dir = targetPos.transform.position - this.transform.position;
//목표물로 가는 방향을 구해서 변수로 저장
//방향 : 목표위치-현재위치
//방향의 계산을 업데이트에 넣어주면
//실시간으로 타겟과 자신의 위치를 기준으로
//새로운 방향을 계산해서 이동하기 때문에
//유도탄처럼 계속 따라온다
if (Vector3.Distance(this.transform.position, targetPos.transform.position) > 1)
{
//Vector3.Distance : 두 벡터 사이의 '거리'를 구해주는 함수
//거리값은 float형으로 반환된다
dir = dir.normalized;
// this.transform.position += dir * Time.deltaTime * 0.8f;
this.transform.forward = dir;
//해당 오브젝트의 정면방향 변경
this.transform.position += this.transform.forward * Time.deltaTime;
//이동방향은 해당 오브젝트가 바라보면 정면으로(forward) 이동시킴
}
//벡터에는 방향과 크기가 모두 포함이 되어있어서
//단순벡터를 이용하여 이동 시키게 되면
//크기(거리)에 따라 이동속도에 차이가 발생한다
//그래서 계산한 벡터의 크기를 배제하고 방향만을 가지고 이동시켜야 하는데
//이때 필요한 것이 벡터의 normalized (단위벡터)의 값이다
//단위벡터는 벡터의 크기를 1로 통일한 벡터이다
//그래서 모든 단위벡터는 동일한 크기를 가지며 오직 방향만 차이가 나게 된다
//적 비행기가 플레이어 방향으로 내려오도록
//Quaternion q = Quaternion.LookRotation(targetPos.transform.position);
//지정하는 대상 방향으로 향하는 각도값을 자동으로 계산해주는 함수
pressTime += Time.deltaTime;
if (pressTime >= delay)
{
pressTime -= delay;
//스페이스바를 누르면 총알이 발사된다
GameObject obj = Instantiate(Laser, this.transform.position, Quaternion.identity);
//플레이어 위치에서 레이저를 발사
obj.transform.up = this.transform.forward;
//레이저의 진행방향==에너미의 진행방향
//레이저의 up == 에너미의 forward가 되도록 값을 변경
obj.GetComponent<Laser>().setTargetTag("Player");
//에너미가 생성한 총알은 에너미가 아닌 플레이어와 부딪혔을 때 삭제된다
GameObject item = Instantiate(Item, transform.position, Quaternion.identity);
obj.GetComponent<ItemScr>().setTargetTag("Player");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Sandbox.Libraries.VariantDictionaries {
public static class IVariantReadonlyDictionaryExtensions {
public static bool TryGetValue<TKey, TValue>(this IVariantReadonlyDictionary<TKey, TValue> source, TKey key, out TValue value) {
if (source.ContainsKey(key)) {
value = source[key];
return true;
} else {
value = default(TValue);
return false;
}
}
}
}
|
using Asset.Core.Repository.Library.Repositorys.AssetsModels.AssetSetups;
using Asset.Core.Repository.Library.UnitOfWorks.AssetModelUnitOfWorks.AssetSetupUnitOfWorks;
using Asset.Infrastucture.Library.Repositorys.AssetModelRepositories.AssetSetupRepositories;
using AssetSqlDatabase.Library.DatabaseContext;
namespace Asset.Infrastucture.Library.UnitOfWorks.AssetModelUniOfWorks.AssetSetupUnitOfWorks
{
public class AssetTypeUnitOfWork : IAssetTypeUnitOfWork
{
private readonly AssetDbContext _context;
public AssetTypeUnitOfWork(AssetDbContext context)
{
_context = context;
AssetType = new AssetTypeRepository(_context);
}
public IAssetTypeRepository AssetType { get; set; }
public void Dispose()
{
_context.Dispose();
}
public int Complete()
{
return _context.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SFP.SIT.SERV.Model.RESP
{
public class SIT_RESP_CLASINFO
{
public string nfodescripcion { set; get; }
public int nfoclave { set; get; }
public SIT_RESP_CLASINFO () {}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace JPAssets.Binary
{
/// <summary>
/// A 32-bit binary data structure.
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = kByteCount)]
[System.Diagnostics.DebuggerDisplay("{" + nameof(GetDebuggerDisplay) + "(),nq}")]
public readonly struct Binary32 : IEquatable<Binary32>
{
/// <summary>
/// Denotes the size of this data structure in bytes.
/// </summary>
private const int kByteCount = 4;
[FieldOffset(0)]
private readonly uint m_data;
public unsafe Binary32(byte* ptr)
{
m_data = BinaryConversionUtility.ToData<uint>(*(ptr + 0), *(ptr + 1), *(ptr + 2), *(ptr + 3));
}
public unsafe Binary32(byte b0, byte b1, byte b2, byte b3)
{
var ptr = stackalloc byte[kByteCount] { b0, b1, b2, b3 };
this = new Binary32(ptr);
}
/// <inheritdoc cref="ValidationUtility.CheckArrayOffsetAndCount{T}(T[], string, int, int)"/>
public unsafe Binary32(byte[] buffer, int offset)
{
ValidationUtility.CheckArrayOffsetAndCount(buffer, nameof(buffer), offset, kByteCount);
fixed (byte* bufferPtr = buffer)
{
var offsetPtr = bufferPtr + offset;
this = new Binary32(offsetPtr);
}
}
public Binary32(Binary16 low, Binary16 high)
{
low.ExtractBytes(out byte b0, out byte b1);
high.ExtractBytes(out byte b2, out byte b3);
this = new Binary32(b0, b1, b2, b3);
}
public Binary32(int value)
{
unsafe
{
this = new Binary32((byte*)&value);
}
}
public Binary32(uint value)
{
unsafe
{
this = new Binary32((byte*)&value);
}
}
public Binary32(float value)
{
unsafe
{
this = new Binary32((byte*)&value);
}
}
/// <summary>
/// Creates a new <see cref="Binary32"/> instance with reversed-endianness.
/// </summary>
public Binary32 Reverse()
{
unsafe
{
var reversedData = EndiannessUtility.ReverseEndianness(m_data);
return new Binary32((byte*)&reversedData);
}
}
/// <inheritdoc cref="BinaryConversionUtility.ExtractBytes{T}(T, out byte, out byte, out byte, out byte)"/>
public void ExtractBytes(out byte b0, out byte b1, out byte b2, out byte b3)
{
BinaryConversionUtility.ExtractBytes(m_data, out b0, out b1, out b2, out b3);
}
/// <returns>A <see cref="int"/> representation of the binary data.</returns>
public int ToInt32()
{
unsafe
{
fixed (uint* dataPtr = &m_data)
return BinaryConversionUtility.ToData<int>((byte*)dataPtr);
}
}
/// <returns>A <see cref="uint"/> representation of the binary data.</returns>
public uint ToUInt32()
{
return m_data;
}
/// <returns>A <see cref="float"/> representation of the binary data.</returns>
public float ToSingle()
{
unsafe
{
fixed (uint* dataPtr = &m_data)
return BinaryConversionUtility.ToData<float>((byte*)dataPtr);
}
}
/// <returns>True if the binary data is equal; Otherwise, false.</returns>
public bool Equals(Binary32 other)
{
return m_data.Equals(other.m_data);
}
public override bool Equals(object obj)
{
return obj is Binary32 other && this.Equals(other);
}
public override int GetHashCode()
{
return m_data.GetHashCode();
}
public static bool operator ==(Binary32 left, Binary32 right)
{
return left.Equals(right);
}
public static bool operator !=(Binary32 left, Binary32 right)
{
return !left.Equals(right);
}
public override string ToString()
{
unsafe
{
fixed (uint* dataPtr = &m_data)
return BinaryStringUtility.ToString(ptr: (byte*)dataPtr, count: kByteCount, delimeter: ' ');
}
}
private string GetDebuggerDisplay()
{
return ToString();
}
}
}
|
using System;
using System.Linq;
using Foundation;
namespace Plugin.HttpTransferTasks
{
public class HttpTransferTasks : AbstractHttpTransferTasks
{
readonly PluginSessionDelegate sessionDelegate;
readonly NSUrlSessionConfiguration sessionConfig;
readonly NSUrlSession session;
public HttpTransferTasks()
{
this.sessionDelegate = new PluginSessionDelegate();
this.sessionConfig = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration(NSBundle.MainBundle.BundleIdentifier + ".BackgroundTransferSession");
this.sessionConfig.HttpMaximumConnectionsPerHost = 1;
this.session = NSUrlSession.FromConfiguration(
this.sessionConfig,
this.sessionDelegate,
new NSOperationQueue()
);
this.session.GetTasks2((_, uploads, downloads) =>
{
foreach (NSUrlSessionUploadTask upload in uploads)
{
// TODO: need localFilePath for what WAS uploading
// TODO: need to set resumed status
this.Add(new HttpTask(this.ToTaskConfiguration(upload), upload));
upload.Resume();
}
foreach (var download in downloads)
{
this.Add(new HttpTask(this.ToTaskConfiguration(download), download));
download.Resume();
}
});
}
public override IHttpTask Upload(TaskConfiguration config)
{
var request = this.CreateRequest(config);
var native = this.session.CreateUploadTask(request, NSUrl.FromFilename(config.LocalFilePath));
var task = new HttpTask(config, native);
this.Add(task);
native.Resume();
return task;
}
public override IHttpTask Download(TaskConfiguration config)
{
var request = this.CreateRequest(config);
var native = this.session.CreateDownloadTask(request);
var task = new HttpTask(config, native);
this.Add(task);
native.Resume();
return task;
}
protected virtual TaskConfiguration ToTaskConfiguration(NSUrlSessionTask native)
=> new TaskConfiguration(native.OriginalRequest.ToString())
{
UseMeteredConnection = native.OriginalRequest.AllowsCellularAccess,
HttpMethod = native.OriginalRequest.HttpMethod,
PostData = native.OriginalRequest.Body.ToString(),
Headers = native.OriginalRequest.Headers.ToDictionary(
x => x.Key.ToString(),
x => x.Value.ToString()
)
};
protected override void Add(IHttpTask task)
{
if (!(task is IIosHttpTask ios))
throw new ArgumentException("You must inherit from IIosHttpTask");
this.sessionDelegate.AddTask(ios);
base.Add(task);
}
protected virtual NSUrlRequest CreateRequest(TaskConfiguration config)
{
var url = NSUrl.FromString(config.Uri);
var request = new NSMutableUrlRequest(url)
{
HttpMethod = config.HttpMethod,
AllowsCellularAccess = config.UseMeteredConnection
};
if (!String.IsNullOrWhiteSpace(config.PostData))
request.Body = NSData.FromString(config.PostData);
if (config.Headers.Any())
request.Headers = NSDictionary.FromObjectsAndKeys(
config.Headers.Values.ToArray(),
config.Headers.Keys.ToArray()
);
return request;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SKT.MES.Model;
namespace SKT.MES.Web.Masters
{
public partial class EditListMaster : System.Web.UI.MasterPage
{
private GridView gridView = null;
private ObjectDataSource objectDataSource = null;
private String recordIDField = null;
private Int32 recordCount = 0;
private bool setPageSize = false;
private SearchSettings searchSettings = null;
private String defaultSortExpression = String.Empty;
private SortDirection defaultSortDirection = SortDirection.Ascending;
#region 公共属性
/// <summary>
/// 设置页面上的 GridView 控件。
/// </summary>
public GridView PageGridView
{
set { this.gridView = value; }
}
/// <summary>
/// 设置页面上的 ObjectDataSource 控件。
/// </summary>
public ObjectDataSource PageObjectDataSource
{
set { this.objectDataSource = value; }
}
/// <summary>
/// 设置记录 ID 的数据字段的名称。
/// 如果设置了该属性,则会自动生成一个选择框列。
/// </summary>
public String RecordIDField
{
set { this.recordIDField = value; }
}
/// <summary>
/// 设置搜索配置信息。
/// </summary>
public SearchSettings SearchSettings
{
set { this.searchSettings = value; }
}
/// <summary>
/// 设置列表的默认排序表达式。
/// </summary>
public String DefaultSortExpression
{
set { this.defaultSortExpression = value; }
}
/// <summary>
/// 设置列表的默认排序方向。
/// </summary>
public SortDirection DefaultSortDirection
{
set { this.defaultSortDirection = value; }
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
#region 设置列表风格
this.gridView.Width = new Unit("100%");
this.gridView.CellSpacing = 0;
this.gridView.CellPadding = 4;
this.gridView.BorderWidth = new Unit(0);
this.gridView.AllowPaging = true;
this.gridView.AllowSorting = true;
this.gridView.AutoGenerateColumns = false;
this.gridView.GridLines = GridLines.None;
this.gridView.EmptyDataText = Resources.Messages.EmptyDataText;
this.gridView.EmptyDataRowStyle.CssClass = "ListTableEmptyDataRow";
this.gridView.CssClass = "ListTable";
this.gridView.HeaderStyle.CssClass = "ListTableHeader";
this.gridView.RowStyle.CssClass = "ListTableOddRow";
this.gridView.SelectedRowStyle.CssClass = "ListTableSelectedRow";
#endregion
if (this.recordIDField != null)
{
BoundField selCol = new BoundField();
selCol.HeaderText = "<input type=\"checkbox\" name=\"chkAll\" id=\"chkAll\" onclick=\"checkAll(this.checked);\"/>";
selCol.HtmlEncode = false;
selCol.HeaderStyle.Width = new Unit("3%");
selCol.DataField = this.recordIDField;
selCol.DataFormatString = "<input type=\"checkbox\" name=\"chkSelect\" value=\"{0}\" onclick=\"chkClk(this)\" />";
selCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
this.gridView.Columns.Insert(0, selCol);
}
this.gridView.RowCreated += new GridViewRowEventHandler(gridView_RowCreated);
this.objectDataSource.Selecting += new ObjectDataSourceSelectingEventHandler(objectDataSource_Selecting);
this.objectDataSource.Selected += new ObjectDataSourceStatusEventHandler(objectDataSource_Selected);
}
void gridView_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "{try{onMi(this);}catch (ex){}}");
e.Row.Attributes.Add("onmouseout", "{try{onMo(this);}catch (ex){}}");
for (int i = 1; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Text = "<input type=\"text\" value=\"" + e.Row.Cells[i].Text + "\"/>";
}
}
}
void objectDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (e.ExecutingSelectCount)
{
return;
}
if (e.InputParameters.Contains("searchSettings") && this.searchSettings != null)
{
this.searchSettings.IsMatchWholeWord = false;
e.InputParameters["searchSettings"] = this.searchSettings;
}
if (e.Arguments.SortExpression == String.Empty && this.defaultSortExpression != String.Empty)
{
e.Arguments.SortExpression = this.defaultSortExpression + (this.defaultSortDirection == SortDirection.Ascending ? "" : " DESC");
}
}
void objectDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
if (e.ReturnValue is Int32)
{
this.recordCount = Convert.ToInt32(e.ReturnValue);
}
}
}
} |
using System;
using System.Globalization;
using MvvmCross.Platform.Converters;
using Tekstomania.Mobile.Core.Models.Enums;
namespace Tekstomania.Mobile.Droid.Converters
{
public class ItemTypeSubQueryValueConverter : MvxValueConverter<ItemType, string>
{
protected override string Convert(ItemType value, Type targetType, object parameter, CultureInfo culture)
{
return value == ItemType.Song ? "Szukaj utworu" : "Szukaj artysty";
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public bool buttonpressed = false;
public int pTier { get; set; }
public int mTier { get; set;}
public int demand { get; set;}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void tavernTier_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
minionOdds.Visible = true;
label4.Visible = true;
buttonpressed = true;
var odds = new Method();
minionOdds.Text = odds.oddsForMinion(pTier, mTier, demand).ToString();
}
private void minionTier_SelectedIndexChanged(object sender, EventArgs e)
{
minionDemand.Visible = true;
label3.Visible = true;
switch (minionTier.Text)
{
case "Tavern Tier 1":
mTier = 1;
break;
case "Tavern Tier 2":
mTier =2;
break;
case "Tavern Tier 3":
mTier = 3;
break;
case "Tavern Tier 4":
mTier = 4;
break;
case "Tavern Tier 5":
mTier = 5;
break;
case "Tavern Tier 6":
mTier = 6;
break;
}
if (buttonpressed == true)
{
var odds = new Method();
minionOdds.Text = odds.oddsForMinion(pTier, mTier, demand).ToString();
}
}
private void playerTier_SelectedIndexChanged(object sender, EventArgs e)
{
switch (playerTier.Text)
{
case "Tavern Tier 1":
pTier = 1;
break;
case "Tavern Tier 2":
pTier = 2;
break;
case "Tavern Tier 3":
pTier = 3;
break;
case "Tavern Tier 4":
pTier = 4;
break;
case "Tavern Tier 5":
pTier = 5;
break;
case "Tavern Tier 6":
pTier = 6;
break;
}
minionTier.Visible = true;
label2.Visible = true;
if(buttonpressed == true)
{
var odds = new Method();
minionOdds.Text = odds.oddsForMinion(pTier, mTier, demand).ToString();
}
}
private void minionDemand_SelectedIndexChanged(object sender, EventArgs e)
{
button.Visible = true;
switch (minionDemand.Text)
{
case "No Demand":
demand = 0;
break;
case "Low Demand":
demand = 1;
break;
case "Medium Demand":
demand = 2;
break;
case "High Demand":
demand = 3;
break;
case "Very High Demand":
demand = 4;
break;
}
if (buttonpressed == true)
{
var odds = new Method();
minionOdds.Text = odds.oddsForMinion(pTier, mTier, demand).ToString();
}
}
}
}
|
using System;
using System.Collections.Generic;
public partial class SysManege_UserControls_ucOnlineList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
/// <summary>
/// 获取并绑定数据
/// </summary>
public void BindData()
{
PDTech.OA.BLL.USER_INFO uBll = new PDTech.OA.BLL.USER_INFO();
PDTech.OA.Model.USER_INFO where = new PDTech.OA.Model.USER_INFO();
where.IS_ONLINE = 1;
int record = 0;
IList<PDTech.OA.Model.USER_INFO> uList = uBll.get_Paging_UserInfoList(where, AspNetPager.CurrentPageIndex, AspNetPager.PageSize, out record);
rpt_UserList.DataSource = uList;
rpt_UserList.DataBind();
AspNetPager.RecordCount = record;
}
/// <summary>
/// 翻页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AspNetPager_PageChanged(object sender, EventArgs e)
{
BindData();
}
/// <summary>
/// 查询
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnRefresh_Click(object sender, EventArgs e)
{
AspNetPager.CurrentPageIndex = 1;
}
} |
#region License
/***
* Copyright © 2018-2025, 张强 (943620963@qq.com).
*
* 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.
*/
#endregion
using System.Dynamic;
using System.Xml.Linq;
namespace ZqUtils.Reflection
{
/// <summary>
/// 动态Xml
/// </summary>
/// <example>
/// 使用示例:
/// <code>
/// dynamic xml = new DynamicXml("Test");
/// xml.Name = "NewLife";
/// xml.Sign = "学无先后达者为师!";
/// xml.Detail = new DynamicXml();
/// xml.Detail.Name = "新生命开发团队";
/// xml.Detail.CreateTime = new DateTime(2002, 12, 31);
/// var node = xml.Node as XElement;
/// var str = node.ToString();
/// Console.WriteLine(str);
/// </code>
/// </example>
public class DynamicXml : DynamicObject
{
/// <summary>
/// 节点
/// </summary>
public XElement Node { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public DynamicXml() { }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="node"></param>
public DynamicXml(XElement node)
{
Node = node;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="name"></param>
public DynamicXml(string name)
{
Node = new XElement(name);
}
/// <summary>
/// 设置
/// </summary>
/// <param name="binder"></param>
/// <param name="value"></param>
/// <returns></returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
var setNode = Node.Element(binder.Name);
if (setNode != null)
setNode.SetValue(value);
else
{
if (value.GetType() == typeof(DynamicXml))
Node.Add(new XElement(binder.Name));
else
Node.Add(new XElement(binder.Name, value));
}
return true;
}
/// <summary>
/// 获取
/// </summary>
/// <param name="binder"></param>
/// <param name="result"></param>
/// <returns></returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
var getNode = Node.Element(binder.Name);
if (getNode == null) return false;
result = new DynamicXml(getNode);
return true;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
public class Nav_Mesh_Controller : MonoBehaviour
{
private NavMeshAgent _agent;
private Vector3 _destination, offset;
public float walkSpeed, runSpeed;
public UnityEvent ReachedDestination;
private void Start()
{
offset.Set(.05f, .05f, .05f);
_agent = GetComponent<NavMeshAgent>();
DisableAgent();
}
public void DisableAgent()
{
_agent.enabled = false;
}
public void EnableAgent()
{
_agent.enabled = true;
}
public void SetDestination(Vector3 newDest)
{
_destination = newDest;
}
public void Walk()
{
_agent.speed = walkSpeed;
StartCoroutine(GoToDest());
}
public void Walk_Back()
{
_agent.speed = walkSpeed;
StartCoroutine(WalkBackwards());
}
public void Run()
{
_agent.speed = runSpeed;
StartCoroutine(GoToDest());
}
private IEnumerator GoToDest()
{
while (true)
{
_agent.destination = _destination;
yield return new WaitForFixedUpdate();
if (((_agent.transform.position.z <= (_destination + offset).z) &&
(_agent.transform.position.x <= (_destination + offset).x))
&& ((_agent.transform.position.z >= (_destination - offset).z) &&
(_agent.transform.position.x >= (_destination - offset).x)))
break;
}
ReachedDestination.Invoke();
print("Done");
}
private IEnumerator WalkBackwards()
{
_agent.updateRotation=false; // disable the automatic rotation
while(true)
{
Vector3 direc = Vector3.zero;
//then i need to prevent the difference from beeing too big (in case one is at 10 and the other 350 for example)
if (Mathf.Abs(direc.y-transform.eulerAngles.y)>180)
{
if(direc.y<180)
direc.y+=360;
else
direc.y-=360;
}
transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, direc, Time.deltaTime);
yield return new WaitForFixedUpdate();
if (((_agent.transform.position.z <= (_destination + offset).z) &&
(_agent.transform.position.x <= (_destination + offset).x))
&& ((_agent.transform.position.z >= (_destination - offset).z) &&
(_agent.transform.position.x >= (_destination - offset).x)))
break;
}
_agent.updateRotation=true; //when no longer need to step back then go to normal
}
}
|
using System;
using System.Net.Sockets;
using System.IO;
using System.Diagnostics;
namespace ParallelExecution
{
public class CommandExecutionClient
{
private int _port;
private string _server;
public CommandExecutionClient(int port, string server)
{
this._port = port;
this._server = server;
}
public Process Start()
{
using (var client = new TcpClient(_server, _port))
{
var stream = client.GetStream();
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
var command = reader.ReadLine();
if (command == null)
{
Console.WriteLine("Failed to read TCP Stream!!");
return null;
}
var index = command.IndexOf(ParallelExecutionMaster.CommandDelimiter);
if (index > -1)
{
var fileName = command.Substring(0, index);
var arguments = command.Substring(index);
Console.WriteLine("Executing command: {0} {1} at {2}", fileName, arguments, DateTime.Now.ToString("O"));
Process process = null;
if (string.IsNullOrWhiteSpace(arguments))
{
process = Process.Start(fileName);
}
else
{
process = Process.Start(fileName, arguments);
}
writer.WriteLine("Success");
writer.Flush();
return process;
}
Console.WriteLine("Invalid Format Command Format Sent to Client!");
writer.WriteLine("Failed");
}
}
return null;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class StructureParameter
{
public float value = 0;
public int priority = 0;
public StructureParameter(float nValue, int nPriority)
{
value = nValue;
priority = nPriority;
}
}
public class Structure
{
public string name;
public Dictionary<string, StructureParameter> parameters;
public Representation representation;
public Structure()
{
name = "";
parameters = new Dictionary<string, StructureParameter> ();
representation = null;
}
public Structure(string nName, Representation nRepresentation)
{
name = nName;
representation = nRepresentation;
parameters = new Dictionary<string, StructureParameter> ();
}
}
|
using System;
using System.Collections.Generic;
namespace ICOMSProvisioningService
{
public class SyncRequest
{
private String _customerID;
private String _customerStatus;
private String _icomsMsgFormat;
public String CustomerId
{
set
{
this._customerID = value;
}
get
{
return this._customerID;
}
}
public String CustomerStatus
{
set
{
this._customerStatus = value;
}
get
{
return this._customerStatus;
}
}
public String ICOMSMsgFormat
{
set
{
this._icomsMsgFormat = value;
}
get
{
return this._icomsMsgFormat;
}
}
}
public class SubscriberSyncRequest : SyncRequest
{
private int _creditLimit;
public int creditLimit
{
set
{
this._creditLimit = value;
}
get
{
return this._creditLimit;
}
}
}
public class EquipmentSyncRequest : SyncRequest
{
private String _macAddress;
private String _smartCardId;
private List<string> _offeringId;
public string macAddress
{
set
{
this._macAddress = value;
}
get
{
return this._macAddress;
}
}
public string smartCardId
{
set
{
this._smartCardId = value;
}
get
{
return this._smartCardId;
}
}
public List<string> offeringId
{
set
{
this._offeringId = value;
}
get
{
return this._offeringId;
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net;
namespace Printer_Status.Helpers.Tests
{
[TestClass]
public class ValueHelperTests
{
[TestMethod]
public void TryIPAddressTest()
{
IPAddress tempIP;
//Valid IP addresses
Assert.IsTrue(ValueHelper.TryIPAddress("172.20.1.6", out tempIP), "Valid IP Address should be determined valid");
//Boundary IP addresses
Assert.IsTrue(ValueHelper.TryIPAddress("0.0.0.0", out tempIP), "Boundary IP Address should be valid.");
Assert.IsTrue(ValueHelper.TryIPAddress("255.255.255.255", out tempIP), "Boundary IP Address should be determined valid.");
Assert.IsFalse(ValueHelper.TryIPAddress("-1.0.0.0", out tempIP), "Boundary IP Address should be determined invalid.");
Assert.IsFalse(ValueHelper.TryIPAddress("0.0.256.20", out tempIP), "Boundary IP Address should be determined invalid.");
//Extreme IP addresses
Assert.IsFalse(ValueHelper.TryIPAddress("hamster", out tempIP), "Extreme IP Address should be determined invalid.");
//Otherwise invalid IP addresses
Assert.IsFalse(ValueHelper.TryIPAddress("2961104948", out tempIP), "IP Address in wrong format should be determined invalid.");
Assert.IsFalse(ValueHelper.TryIPAddress("10110000.01111110.11100000.00110100", out tempIP), "IP Address in wrong format should be determined invalid.");
}
[TestMethod]
public void LevelToPercentTest()
{
//Level special values
Assert.AreEqual("other", ValueHelper.LevelToPercent(50, -1));
Assert.AreEqual("unknown", ValueHelper.LevelToPercent(65, -2));
Assert.AreEqual("OK", ValueHelper.LevelToPercent(23, -3));
Assert.AreEqual("unknown", ValueHelper.LevelToPercent(50, -10));
//Max capacity special values
Assert.AreEqual("50", ValueHelper.LevelToPercent(0, 50));
Assert.AreEqual("71", ValueHelper.LevelToPercent(-12, 71));
//Percentage calculations
Assert.AreEqual("50%", ValueHelper.LevelToPercent(100, 50));
Assert.AreEqual("1%", ValueHelper.LevelToPercent(100, 1));
Assert.AreEqual("0%", ValueHelper.LevelToPercent(100, 0));
Assert.AreEqual("10%", ValueHelper.LevelToPercent(99, 10));
}
[TestMethod]
public void IsLowTest()
{
Assert.IsFalse(ValueHelper.IsLow(-1, 115), "Should return false as indeterminable");
Assert.IsFalse(ValueHelper.IsLow(55, -11), "Should return false as indeterminable");
Assert.IsFalse(ValueHelper.IsLow(-1, -7), "Should return false as indeterminable");
Assert.IsFalse(ValueHelper.IsLow(1,1), "Should return false as full");
Assert.IsTrue(ValueHelper.IsLow(1, 0), "Should return true as empty");
Assert.IsTrue(ValueHelper.IsLow(10,1), "Should return true as equal to LowValuePercent");
Assert.IsTrue(ValueHelper.IsLow(11, 1), "Should return true as less than LowValuePercent");
Assert.IsFalse(ValueHelper.IsLow(9, 1), "Should return false as greater than LowValuePercent");
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using ChatAppUtils.Configuration;
using DAL.Models;
using ChatAppUtils;
using DAL.Enums;
namespace DAL.FriendsData
{
public class FriendsDataProvider : IFriendsDataProvider
{
private readonly string _connectionString;
private const string GetUsersFriendsCmd = "spGetUsersFriends";
private const string SaveFriendStatusCmd = "spSaveFriendStatus";
public FriendsDataProvider()
{
_connectionString = ConfigurationAdapter.GetConnectionString("DefaultConnection");
}
public List<Friend> GetUserFriends(long userId,int statusId)//Status codes: 1-Pending, 2-Accepted, 3-Declined,4-Blocked
{
var result = new List<Friend>();
using(var connection = new SqlConnection(_connectionString))
using(var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = GetUsersFriendsCmd;
cmd.Parameters.AddWithValue("@UserId", userId);
cmd.Parameters.AddWithValue("@StatusId", statusId);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(ReadFriend(reader));
}
return result;
}
}
public void SaveFriendStatus(long userId1,long userId2,UserRelationStatus status)
{
using (var connection = new SqlConnection(_connectionString))
using (var cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = GetUsersFriendsCmd;
cmd.Parameters.AddWithValue("@userId1", userId1);
cmd.Parameters.AddWithValue("@userId2", userId2);
cmd.Parameters.AddWithValue("@status", (int)status);
cmd.ExecuteNonQuery();
}
}
private Friend ReadFriend(SqlDataReader reader)
{
var friend = new Friend();
int ord = 0;
friend.Id = reader.GetInt64Inc(ref ord);
friend.Login = reader.GetStringInc(ref ord);
return friend;
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;
using System.Text;
public class GameManager : MonoBehaviour {
/*void Awake()
{
if (TreeInstance == null) {
TreeInstance = this;
} else {
DestroyImmediate (this);
}
}
private static GameManager instance;
public static GameManager Instance
{
get
{
if (instance == null) {
instance = new GameManager ();
}
return instance;
}
}*/
//bool gameHasEnded = false;
//private static int life = 3;
public float restartDelay = 2f;
public static int score = 0;
public GameObject completeLevelUI;
public GameObject panel;
public Transform player;
//public GameObject menu;
GameState gameState = GameState.Start;
public GameState GameState{ get; set;}
/*void Start() {
menu = GameObject.Find ("MenuBar");
menu.SetActive (false);
}
public void showMenu() {
menu.SetActive(true);
Time.timeScale = 0;
}
public void resume() {
menu.SetActive (false);
Time.timeScale = 1;
}*/
public void CompleteLevel() {
//Debug.Log ("LEVEL WON!");
this.gameState = GameState.Dead;
player.GetComponent<playerMovement> ().enabled = false;
player.GetComponent<playerName> ().enabled = false;
panel.SetActive(false);
saveScore ();
completeLevelUI.SetActive(true);
}
private void saveScore() {
if (PlayerPrefs.GetInt ("CUR") < score)
PlayerPrefs.SetInt ("CUR", score);
if (!PlayerPrefs.HasKey ("_SCORE"))
PlayerPrefs.SetInt ("_SCORE", score);
else {
if (PlayerPrefs.GetInt ("_SCORE") < score)
PlayerPrefs.SetInt ("_SCORE", score);
}
}
public void EndGame() {
if (this.gameState != GameState.Dead) {
//Debug.Log ("GAME OVER");
//SceneManager.LoadScene ("Credits");
//restart game
//life -= 1;
//scores[3- life] = score;
//Debug.Log (score);
saveScore ();
if (PlayerPrefs.GetInt("LIFE") > 0) {
PlayerPrefs.SetInt("LIFE", PlayerPrefs.GetInt("LIFE") - 1);
//btn.setActive (true);
Debug.Log ("life - 1");
//player.GetComponent<playerName> ().setLoseLife (false);
//return true;
} else {
player.transform.GetComponent<playerMovement>().enabled = false;
//FindObjectOfType<playerMovement> ().enabled = false;
//getHighScore ();
//Debug.Log(PlayerPrefs.GetInt("LIFE"));
SceneManager.LoadScene ("Credits");
this.gameState = GameState.Dead;
//saveResult(PlayerPrefs.GetInt("CUR"));
}
}
}
public void setScore(int value) {
score = value;
}
public int getScore() {
return score;
}
public void Restart () {
SceneManager.LoadScene (SceneManager.GetActiveScene().name);
}
public void quit() {
Application.Quit ();
}
}
|
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.IO;
namespace CharacterFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Character cChar = new Character();
}
private void button1_Click(object sender, EventArgs e)
{
Random rand = new Random();
numericUpDown1.Value = rand.Next(100);
numericUpDown2.Value = rand.Next(100);
numericUpDown3.Value = rand.Next(100);
numericUpDown4.Value = rand.Next(100);
numericUpDown5.Value = rand.Next(100);
numericUpDown6.Value = rand.Next(100);
numericUpDown7.Value = rand.Next(100);
numericUpDown8.Value = rand.Next(100);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
Character c = (Character)listBox1.Items[listBox1.SelectedIndex];
FNameBox.Text = c.Name;
LNameBox.Text = c.LastName;
AgeBox.Value = c.Age;
comboBox1.Text = c.Race;
numericUpDown1.Value = c.Skill.Brave;
numericUpDown2.Value = c.Skill.Cheat;
numericUpDown3.Value = c.Skill.Disguise;
numericUpDown4.Value = c.Skill.Endur;
numericUpDown5.Value = c.Skill.Heal;
numericUpDown6.Value = c.Skill.Know;
numericUpDown7.Value = c.Skill.Lead;
numericUpDown8.Value = c.Skill.Steal;
}
}
private void hideToolStripMenuItem_Click(object sender, EventArgs e)
{
FNameBox.Text = "";
LNameBox.Text = "";
AgeBox.Value = 0;
numericUpDown1.Value = 0;
numericUpDown2.Value = 0;
numericUpDown3.Value = 0;
numericUpDown4.Value = 0;
numericUpDown5.Value = 0;
numericUpDown6.Value = 0;
numericUpDown7.Value = 0;
numericUpDown8.Value = 0;
listBox1.Items.Clear();
}
private void addCharactersToolStripMenuItem_Click(object sender, EventArgs e)
{
Character c = new Character();
c.Name = FNameBox.Text;
c.LastName = LNameBox.Text;
c.Age = AgeBox.Value;
c.Race = comboBox1.Text;
c.Skill.Brave = numericUpDown1.Value;
c.Skill.Cheat = numericUpDown2.Value;
c.Skill.Disguise = numericUpDown3.Value;
c.Skill.Endur = numericUpDown4.Value;
c.Skill.Heal = numericUpDown5.Value;
c.Skill.Know = numericUpDown6.Value;
c.Skill.Lead = numericUpDown7.Value;
c.Skill.Steal = numericUpDown8.Value;
FNameBox.Text = "";
LNameBox.Text = "";
AgeBox.Value = 0;
comboBox1.SelectedIndex = 6;
numericUpDown1.Value = 0;
numericUpDown2.Value = 0;
numericUpDown3.Value = 0;
numericUpDown4.Value = 0;
numericUpDown5.Value = 0;
numericUpDown6.Value = 0;
numericUpDown7.Value = 0;
numericUpDown8.Value = 0;
listBox1.Items.Add(c);
}
private void Menu_File_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
comboBox1.SelectedIndex = comboBox1.FindStringExact("None");
}
private void skillsToolStripMenuItem_Click(object sender, EventArgs e)
{
groupBox2.Visible = skillsToolStripMenuItem.Checked;
}
private void Menu_File_Open_Click(object sender, EventArgs e)
{
//Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
/*openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;*/
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// Insert code to read the stream here.
StreamReader read = new StreamReader(openFileDialog1.FileName);
while (!read.EndOfStream)
{
string line = read.ReadLine(), sub;
int start = 0;
Character c = new Character();
for (int x = 0; x < 12; x++)
{
int end = line.IndexOf(',', start);
sub = line.Substring(start, end-start);
switch(x)
{
case 0:
c.Name = sub;
break;
case 1:
c.LastName = sub;
break;
case 2:
c.Age = decimal.Parse(sub);
break;
case 3:
c.Race = sub;
break;
case 4:
c.Skill.Brave = decimal.Parse(sub);
break;
case 5:
c.Skill.Cheat = decimal.Parse(sub);
break;
case 6:
c.Skill.Disguise = decimal.Parse(sub);
break;
case 7:
c.Skill.Endur = decimal.Parse(sub);
break;
case 8:
c.Skill.Heal = decimal.Parse(sub);
break;
case 9:
c.Skill.Know = decimal.Parse(sub);
break;
case 10:
c.Skill.Lead = decimal.Parse(sub);
break;
case 11:
c.Skill.Steal = decimal.Parse(sub);
break;
}
start = end+1;
}
listBox1.Items.Add(c);
}
}
}
private void deselectCharactersToolStripMenuItem_Click(object sender, EventArgs e)
{
listBox1.SelectedIndex = -1;
FNameBox.Text = "";
LNameBox.Text = "";
AgeBox.Value = 0;
comboBox1.SelectedIndex = 6;
numericUpDown1.Value = 0;
numericUpDown2.Value = 0;
numericUpDown3.Value = 0;
numericUpDown4.Value = 0;
numericUpDown5.Value = 0;
numericUpDown6.Value = 0;
numericUpDown7.Value = 0;
numericUpDown8.Value = 0;
}
private void removeCharacterToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
listBox1.SelectedIndex = -1;
FNameBox.Text = "";
LNameBox.Text = "";
AgeBox.Value = 0;
comboBox1.SelectedIndex = 6;
numericUpDown1.Value = 0;
numericUpDown2.Value = 0;
numericUpDown3.Value = 0;
numericUpDown4.Value = 0;
numericUpDown5.Value = 0;
numericUpDown6.Value = 0;
numericUpDown7.Value = 0;
numericUpDown8.Value = 0;
}
private void File_Menu_Save_Click(object sender, EventArgs e)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
/*saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;*/
saveFileDialog1.AddExtension = true;
saveFileDialog1.DefaultExt = ".txt";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
StreamWriter write = new StreamWriter(myStream);
for (int x = 0; x < listBox1.Items.Count; x++)
{
Character temp = (Character)listBox1.Items[x];
string line;
line = temp.Name + ',' + temp.LastName + ',' +
temp.Age + ',' + temp.Race + ',' + temp.Skill.Brave
+ ',' + temp.Skill.Cheat + ',' + temp.Skill.Disguise
+ ',' + temp.Skill.Endur + ',' + temp.Skill.Heal
+ ',' + temp.Skill.Know + ',' + temp.Skill.Lead
+ ',' + temp.Skill.Steal+ ',';
write.WriteLine(line);
}
write.Close();
myStream.Close();
}
}
}
private void updateCharactersToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
Character c = (Character)listBox1.Items[listBox1.SelectedIndex];
c.Name = FNameBox.Text;
c.LastName = LNameBox.Text;
c.Age = AgeBox.Value;
c.Race = comboBox1.Text;
c.Skill.Brave = numericUpDown1.Value;
c.Skill.Cheat = numericUpDown2.Value;
c.Skill.Disguise = numericUpDown3.Value;
c.Skill.Endur = numericUpDown4.Value;
c.Skill.Heal = numericUpDown5.Value;
c.Skill.Know = numericUpDown6.Value;
c.Skill.Lead = numericUpDown7.Value;
c.Skill.Steal = numericUpDown8.Value;
listBox1.Items[listBox1.SelectedIndex] = c;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ECommerceApi.CustomValidators
{
public class LuhnCheck
{
public bool PassesLuhnCheck(string creditCardNumber)
{
var cleanedNumber = NormalizeString(creditCardNumber);
if (cleanedNumber.Trim() == "")
{
return false;
}
return Luhn(cleanedNumber);
}
/// <summary>
/// NormalizeString
/// </summary>
/// <param name="creditCardNumber">A non-empty string holding a potential credit card number</param>
/// <returns>That string with the spaces and dashes removed</returns>
private static string NormalizeString(string creditCardNumber)
{
return new string(creditCardNumber.Where(c => c != ' ' && c != '-')
.ToArray());
}
/// <summary>
/// Uses the Luhn (Mod 10) algorithm to check for typos in credit card numbers
/// </summary>
/// <param name="creditCardNumber">A string with a candidate credit card number</param>
/// <returns>true if the string fulfills the algorithm, false if it doesn't</returns>
/// <seealso cref="https://en.wikipedia.org/wiki/Luhn_algorithm"/>
private static bool Luhn(string creditCardNumber)
{
return creditCardNumber.All(char.IsDigit) && creditCardNumber.Reverse()
.Select(c => c - 48) // a char - 48 coerces it into a number.
.Select((thisNum, i) => i % 2 == 0 // the even index numbers
? thisNum // just used the number (it's even)
: ((thisNum *= 2) > 9 ? thisNum - 9 : thisNum) // the odd numbers if they are greater than 9, subtract nine, otherwise just that number
).Sum() % 10 == 0; // the sum of all these should be evenly divisible by 10.
// HT to https://stackoverflow.com/questions/21249670/implementing-luhn-algorithm-using-c-sharp
}
}
}
|
using System;
namespace iCopy.Model.Response
{
public class ProfilePhoto
{
public int ID { get; set; }
public string Path { get; set; }
public string FileSystemPath { get; set; }
public Int64 SizeInBytes { get; set; }
public string Name { get; set; }
public string Extension { get; set; }
public string Format { get; set; }
public string Base64Encoded { get; set; }
}
}
|
namespace SimpleTerrain
{
public class GameObject : Common.SimpleModel
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using BoardGamedia.Entities;
using Android.Graphics.Drawables;
namespace BoardGamedia.Adapters
{
public class GameListAdapter : BaseAdapter<Game>
{
private Context _context;
private List<Game> _items;
public GameListAdapter(Context context, IEnumerable<Game> items)
{
_context = context;
_items = items.ToList();
}
public override Game this[int position]
{
get { return _items[position]; }
}
public override int Count
{
get { return _items.Count(); }
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View result = convertView;
if (result == null)
{
var inflater = (LayoutInflater)_context.GetSystemService(Context.LayoutInflaterService);
result = inflater.Inflate(Resource.Layout.GameItem, parent, false);
}
var game = this[position];
result.FindViewById<ImageView>(Resource.Id.Thumbnail).SetImageBitmap(Utilities.GetImageBitmapFromUrl(game.ImageUrl));
result.FindViewById<TextView>(Resource.Id.GameName).Text = game.Name;
return result;
}
}
} |
using AutoMapper;
using ServicesLibrary.Models;
using TiendeoAPI.Models;
namespace TiendeoAPI.Helpers.Mappers
{
public class ServiceMapper : Profile
{
public ServiceMapper()
{
CreateMap<ServiceDto, ServiceModel>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using ReactRestChat.Models;
namespace ReactRestChat.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Conversation> Conversations { get; set; }
public DbSet<ConversationMessage> ConversationMessages { get; set; }
public DbSet<ConversationInstance> ConversationInstances { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<Conversation>().ToTable("Conversation");
builder.Entity<ConversationMessage>().ToTable("ConversationMessage");
builder.Entity<ConversationInstance>().ToTable("ConversationInstance");
}
}
}
|
/* ***************************************************************
* 프로그램 명 : Round3Prac.cs
* 작성자 : 최은정 (이송이, 류서현, 신은지, 최세화, 홍예지)
* 최조 작성일 : 2019년 12월 02일
* 최종 작성일 : 2019년 12월 07일
* 프로그램 설명 : Round3의 연습 단계에 알맞게 창을 구성한다.
* *************************************************************** */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Round3Prac : MonoBehaviour
{
public GameObject oven;
public GameObject fire1;
public GameObject fire2;
public GameObject correct;
public GameObject wrong;
Container situ;
public void Start()
{
situ = GameObject.Find("Situation").GetComponent<Container>();
Invoke("Round3prac", 8);
}
void Round3prac()
{
oven.SetActive(true);
Invoke("ShowShape1", 1);
}
void ShowShape1()
{
fire1.SetActive(true);
//while (true)
//{
// if(알맞은 동작 인식) {
// correct.SetActive(true);
// break;
// }
//}
Invoke("ShowShape2", 2);
}
void ShowShape2()
{
correct.SetActive(false);
fire1.SetActive(false);
fire2.SetActive(true);
//while (true)
//{
// if(알맞은 동작 인식) {
// correct.SetActive(true);
// break;
// }
//}
situ.situation = "NANIP2";
}
} |
using System;
namespace cn.bmob.io
{
/// <summary>
/// 地理位置处理类
///
/// 纬度的范围应该是在-90.0到90.0之间。经度的范围应该是在-180.0到180.0之间。
/// </summary>
public sealed class BmobGeoPoint : BmobObject
{
/// <summary>
/// 构造函数
/// </summary>
public BmobGeoPoint() { }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="latitude">纬度</param>
/// <param name="longitude">经度</param>
public BmobGeoPoint(double latitude, double longitude)
{
this.Latitude = latitude;
this.Longitude = longitude;
}
/// <summary>
/// 获取类型信息
/// </summary>
public override string _type { get { return "GeoPoint"; } }
private BmobDouble latitude;
/// <summary>
/// 纬度 [-90, 90]
/// </summary>
public BmobDouble Latitude
{
get { return this.latitude; }
set
{
this.latitude = value;
if (this.latitude.Get() < -90 || this.latitude.Get() > 90)
{
throw new InvalidOperationException();
}
}
}
private BmobDouble longitude;
/// <summary>
/// 经度 [-180, 180]
/// </summary>
public BmobDouble Longitude
{
get { return this.longitude; }
set
{
this.longitude = value;
if (this.longitude.Get() < -180 || this.longitude.Get() > 180)
{
throw new InvalidOperationException();
}
}
}
public override void readFields(BmobInput input)
{
this.latitude = input.getDouble("latitude");
this.longitude = input.getDouble("longitude");
}
public override void write(BmobOutput output, Boolean all)
{
output.Put(TYPE_NAME, this._type);
output.Put("latitude", this.latitude);
output.Put("longitude", this.longitude);
}
}
}
|
// ----------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="ViewObservableDynamicArray.cs" company="David Eiwen">
// Copyright © 2016 by David Eiwen
// </copyright>
// <author>David Eiwen</author>
// <summary>
// This file contains the ViewObservableDynamicArray{TIn, TOut} class.
// </summary>
// ----------------------------------------------------------------------------------------------------------------------------------------
namespace IndiePortable.Collections
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Formatter;
/// <summary>
/// Provides a Model-View-View Model (MVVM) compatible observable dynamic array with an input type and an output type.
/// </summary>
/// <typeparam name="TIn">
/// The type of the model items that shall be viewed.
/// </typeparam>
/// <typeparam name="TOut">
/// The view type of the items.
/// </typeparam>
/// <remarks>
/// <para>Implements <see cref="IObservableReadOnlyList{T}" />, <see cref="IDisposable" /> explicitly.</para>
/// <para>
/// Implements <see cref="IReadOnlyList{T}" />, <see cref="INotifyCollectionChanged" />
/// implicitly through <see cref="IObservableReadOnlyList{T}"/>
/// </para>
/// <para>
/// Implements <see cref="IReadOnlyCollection{T}" />, <see cref="IEnumerable{T}" />, <see cref="IEnumerable" />
/// implicitly through <see cref="IReadOnlyList{TOut}" />.
/// </para>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Naming",
"CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "Array suffix describes the functinality better than Collection suffix.")]
[ComVisible(true)]
public class ViewObservableDynamicArray<TIn, TOut>
: IObservableReadOnlyList<TOut>, INotifyCollectionChanged, IList, IDisposable
where TIn : class, IEquatable<TIn>
where TOut : IViewType<TIn>
{
/// <summary>
/// The <see cref="SemaphoreSlim" /> that synchronizes the thread access on the <see cref="ViewObservableDynamicArray{TIn, TOut}" />.
/// </summary>
private readonly SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
/// <summary>
/// The backing field for the <see cref="Source" /> property.
/// </summary>
private ObservableDynamicArray<TIn> sourceBacking;
/// <summary>
/// The <see cref="ArrayDictionary{TIn, TOut}" /> that maps between the source and the destination object.
/// </summary>
private ArrayDictionary<TIn, TOut> mapping;
/// <summary>
/// The <see cref="DynamicArray{T}" /> containing the view models.
/// </summary>
private DynamicArray<TOut> viewModels;
/// <summary>
/// The backing field for the <see cref="IsDisposed" /> property.
/// </summary>
private bool isDisposedBacking;
/// <summary>
/// Initializes a new instance of the <see cref="ViewObservableDynamicArray{TIn, TOut}" /> class.
/// </summary>
/// <param name="source">
/// The source <see cref="ObservableDynamicArray{T}" />.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if:</para>
/// <para> - <paramref name="source" /> is <c>null</c>.</para>
/// </exception>
public ViewObservableDynamicArray(ObservableDynamicArray<TIn> source)
: this(source, vm => (TOut)Activator.CreateInstance(typeof(TOut), vm))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ViewObservableDynamicArray{TIn, TOut}" /> class.
/// </summary>
/// <param name="source">
/// The source <see cref="ObservableDynamicArray{T}" />.
/// </param>
/// <param name="viewModelGenerator">
/// The method callback used for generating the view models.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if:</para>
/// <para> - <paramref name="source" /> is <c>null</c>.</para>
/// <para> - <paramref name="viewModelGenerator" /> is <c>null</c>.</para>
/// </exception>
public ViewObservableDynamicArray(ObservableDynamicArray<TIn> source, Func<TIn, TOut> viewModelGenerator)
{
this.sourceBacking = source ?? throw new ArgumentNullException(nameof(source));
this.ViewModelGeneratorCallback = viewModelGenerator ?? throw new ArgumentNullException(nameof(viewModelGenerator));
this.mapping = new ArrayDictionary<TIn, TOut>();
this.viewModels = new DynamicArray<TOut>();
this.Source.CollectionChanged += this.Source_CollectionChanged;
if (source.Count > 0)
{
this.AddItems(source);
}
}
/// <summary>
/// Finalizes an instance of the <see cref="ViewObservableDynamicArray{TIn, TOut}" /> class.
/// </summary>
~ViewObservableDynamicArray()
{
this.Dispose(false);
}
/// <summary>
/// Raised when the <see cref="ViewObservableDynamicArray{TIn, TOut}" /> has been changed.
/// </summary>
/// <remarks>
/// Implements <see cref="INotifyCollectionChanged.CollectionChanged" /> implicitly.
/// </remarks>
public event NotifyCollectionChangedEventHandler CollectionChanged;
/// <summary>
/// Gets a value indicating whether the <see cref="ViewObservableDynamicArray{TIn, TOut}" /> has been disposed.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="ViewObservableDynamicArray{TIn, TOut}" /> has been disposed; otherwise, <c>false</c>.
/// </value>
public bool IsDisposed
{
get { return this.isDisposedBacking; }
}
/// <summary>
/// Gets the number of elements in the collection.
/// </summary>
/// <value>
/// Contains the number of elements in the collection.
/// </value>
/// <remarks>
/// Implements <see cref="IReadOnlyCollection{TOut}.Count" /> implicitly.
/// </remarks>
public int Count
{
get { return this.Source.Count; }
}
/// <summary>
/// Gets the source <see cref="ObservableDynamicArray{T}" />.
/// </summary>
/// <value>
/// Contains the source <see cref="ObservableDynamicArray{T}" />.
/// </value>
public ObservableDynamicArray<TIn> Source
{
get { return this.sourceBacking; }
}
/// <summary>
/// Gets the method callback used for generating the view models.
/// </summary>
/// <value>
/// Contains the method callback used for generating the view models.
/// </value>
public Func<TIn, TOut> ViewModelGeneratorCallback { get; private set; }
bool IList.IsFixedSize { get; } = false;
bool IList.IsReadOnly { get; } = true;
int ICollection.Count
{
get { return this.Count; }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection" /> is synchronized (thread safe).
/// </summary>
/// <value>
/// Contains a value indicating whether access to the <see cref="ICollection" /> is synchronized (thread safe).
/// </value>
bool ICollection.IsSynchronized { get; } = false;
object ICollection.SyncRoot { get; } = null;
object IList.this[int index]
{
get => this[index];
set => throw new InvalidOperationException();
}
/// <summary>
/// Gets the <typeparamref name="TOut" /> at the specified index.
/// </summary>
/// <value>
/// Contains the <typeparamref name="TOut" /> at the specified index.
/// </value>
/// <param name="index">
/// The index at which the item shall be returned.
/// </param>
/// <returns>
/// Returns the <typeparamref name="TOut" /> at the specified index.
/// </returns>
/// <remarks>
/// Implements <see cref="IReadOnlyList{TOut}.this[int]" /> implicitly.
/// </remarks>
public TOut this[int index]
{
get { return this.viewModels[index]; }
}
/// <summary>
/// Gets the <typeparamref name="TOut"/> specified by a <typeparamref name="TIn" /> value.
/// </summary>
/// <value>
/// Contains the <typeparamref name="TOut"/> specified by a <typeparamref name="TIn" /> value.
/// </value>
/// <param name="input">
/// The <typeparamref name="TIn" /> value associated with the desired <typeparamref name="TOut" /> value.
/// </param>
/// <returns>
/// Returns the <typeparamref name="TOut" /> specified by <paramref name="input" />.
/// </returns>
public TOut this[TIn input]
{
get { return this.mapping[input]; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{TOut}" /> that can be used to iterate through the collection.
/// </returns>
/// <remarks>
/// Implements <see cref="IEnumerable{TOut}.GetEnumerator()" /> implicitly.
/// </remarks>
public IEnumerator<TOut> GetEnumerator() => new Enumerator(this);
/// <summary>
/// Gets an <see cref="Enumerator" /> for the <see cref="IEnumerable" />.
/// </summary>
/// <returns>
/// Returns an <see cref="IEnumerator" /> for the <see cref="IEnumerable" />.
/// </returns>
/// <remarks>
/// Implements <see cref="IEnumerable.GetEnumerator()" /> explicitly.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
#region Explicit IList & ICollection Method implementations
int IList.Add(object value)
{
throw new InvalidOperationException();
}
void IList.Clear()
{
throw new InvalidOperationException();
}
bool IList.Contains(object value)
=> value is TOut
? this.Contains((TOut)value)
: false;
void ICollection.CopyTo(Array array, int index)
=> this.mapping.Select(kv => kv.Value).ToArray().CopyTo(array, index);
int IList.IndexOf(object value)
=> value is TOut
? this.viewModels.IndexOf((TOut)value)
: -1;
void IList.Insert(int index, object value)
{
throw new InvalidOperationException();
}
void IList.Remove(object value)
{
throw new InvalidOperationException();
}
void IList.RemoveAt(int index)
{
throw new InvalidOperationException();
}
#endregion
/// <summary>
/// Releases all resources reserved by the <see cref="ViewObservableDynamicArray{TIn, TOut}" />.
/// </summary>
/// <remarks>
/// Implements <see cref="IDisposable.Dispose()" /> implicitly.
/// </remarks>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (!this.IsDisposed)
{
if (disposing)
{
}
this.mapping.Dispose();
this.viewModels.Dispose();
this.semaphore.Dispose();
this.CollectionChanged = null;
this.sourceBacking = null;
this.mapping = null;
this.viewModels = null;
this.isDisposedBacking = true;
}
}
/// <summary>
/// Raises the <see cref="CollectionChanged" /> event.
/// </summary>
/// <param name="e">
/// Contains additional information for the event handlers.
/// </param>
protected void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e) => this.CollectionChanged?.Invoke(this, e);
/// <summary>
/// Handles the <see cref="INotifyCollectionChanged.CollectionChanged" /> event of <see cref="Source" />.
/// </summary>
/// <param name="sender">
/// The sender of the event.
/// </param>
/// <param name="e">
/// Contains additional information for the event handler.
/// </param>
private void Source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.semaphore.Wait();
NotifyCollectionChangedEventArgs args;
try
{
IList<TOut> newItems = null;
IList<TOut> oldItems = null;
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
newItems = this.AddItems(e.NewItems.Cast<TIn>());
args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems, e.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Remove:
oldItems = this.RemoveItems(e.OldItems.Cast<TIn>());
args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItems, e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Replace:
var itemReplacements = from o in e.OldItems.Cast<TIn>()
from n in e.NewItems.Cast<TIn>()
select new Tuple<TIn, TIn>(o, n);
this.ReplaceItems(itemReplacements, out oldItems, out newItems);
args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, oldItems, newItems, e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Move:
var movedItems = e.OldItems.Cast<TIn>();
this.MoveItems(movedItems, out newItems);
args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, oldItems, e.OldStartingIndex, e.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Reset:
oldItems = this.RemoveItems(from i in this select i.Model);
args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
break;
default: throw new InvalidOperationException();
}
}
finally
{
// leave lock in each case
this.semaphore.Release();
}
this.RaiseCollectionChanged(args);
}
/// <summary>
/// Adds the items in the specified <see cref="IEnumerable{T}" />.
/// </summary>
/// <param name="items">
/// The items that shall be added.
/// </param>
/// <returns>
/// Returns the <typeparamref name="TOut" /> representations of the items in <paramref name="items" />.
/// </returns>
private IList<TOut> AddItems(IEnumerable<TIn> items)
{
var ret = new List<TOut>();
foreach (var item in items)
{
TOut newItem = this.ViewModelGeneratorCallback(item);
this.mapping.Add(item, newItem);
this.viewModels.Insert(this.sourceBacking.IndexOf(item), newItem);
ret.Add(newItem);
}
return ret;
}
/// <summary>
/// Removes the items in the specified <see cref="IEnumerable{T}" /> from the <see cref="ViewObservableDynamicArray{TIn, TOut}" />.
/// </summary>
/// <param name="items">
/// The items that shall be removed.
/// </param>
/// <returns>
/// Returns the <typeparamref name="TOut" /> representations of the removed items.
/// </returns>
private IList<TOut> RemoveItems(IEnumerable<TIn> items)
{
var ret = new List<TOut>();
foreach (var item in items)
{
TOut oldItem = this.mapping[item];
this.mapping.Remove(item);
this.viewModels.Remove(oldItem);
ret.Add(oldItem);
}
return ret;
}
/// <summary>
/// Replaces the specified items.
/// </summary>
/// <param name="itemReplacements">
/// The <typeparamref name="TIn" /> replacement tuples.
/// </param>
/// <param name="removedItems">
/// The list containing the removed <typeparamref name="TOut" /> values.
/// </param>
/// <param name="addedItems">
/// The list containing the added <typeparamref name="TOut" /> values.
/// </param>
private void ReplaceItems(IEnumerable<Tuple<TIn, TIn>> itemReplacements, out IList<TOut> removedItems, out IList<TOut> addedItems)
{
removedItems = new DynamicArray<TOut>();
addedItems = new DynamicArray<TOut>();
foreach (var tuple in itemReplacements)
{
var newItem = this.ViewModelGeneratorCallback(tuple.Item1);
var sourceIndex = this.sourceBacking.IndexOf(tuple.Item1);
this.viewModels[sourceIndex] = newItem;
removedItems.Add(this.mapping[tuple.Item1]);
addedItems.Add(newItem);
this.mapping[tuple.Item1] = newItem;
}
}
private void MoveItems(IEnumerable<TIn> items, out IList<TOut> movedItems)
{
movedItems = new DynamicArray<TOut>();
foreach (var item in items.ToArray())
{
var sourceIndex = this.Source.IndexOf(item);
var viewmodel = this.mapping[item];
this.viewModels.Remove(viewmodel);
this.viewModels.Insert(sourceIndex, viewmodel);
movedItems.Add(viewmodel);
}
}
/// <summary>
/// Provides an enumerator for the <see cref="ViewObservableDynamicArray{TIn, TOut}" />.
/// </summary>
/// <remarks>
/// Implements <see cref="IEnumerable{TOut}" />, <see cref="IEnumerable" />, <see cref="IDisposable" /> explicitly.
/// </remarks>
public struct Enumerator
: IEnumerator<TOut>, IEnumerator, IDisposable
{
/// <summary>
/// The <see cref="ViewObservableDynamicArray{TIn, TOut}" /> that shall be enumerated.
/// </summary>
private ViewObservableDynamicArray<TIn, TOut> enumerable;
/// <summary>
/// The current index of the <see cref="Enumerator" />.
/// </summary>
private int currentIndex;
/// <summary>
/// Initializes a new instance of the <see cref="ViewObservableDynamicArray{TIn, TOut}.Enumerator" /> struct.
/// </summary>
/// <param name="enumerable">
/// The <see cref="ViewObservableDynamicArray{TIn, TOut}" /> that shall be enumerated.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="enumerable" /> is <c>null</c>.
/// </exception>
public Enumerator(ViewObservableDynamicArray<TIn, TOut> enumerable)
{
this.enumerable = enumerable ?? throw new ArgumentNullException(nameof(enumerable));
this.currentIndex = -1;
}
/// <summary>
/// Gets the current item of the <see cref="Enumerator" />.
/// </summary>
/// <value>
/// Contains the current item of the <see cref="Enumerator" />.
/// </value>
/// <remarks>
/// Implements <see cref="IEnumerator{TOut}.Current" /> implicitly.
/// </remarks>
public TOut Current
{
get { return this.enumerable[this.currentIndex]; }
}
/// <summary>
/// Gets the current item of the <see cref="IEnumerator" />.
/// </summary>
/// <value>
/// Contains the current item of the <see cref="IEnumerator" />.
/// </value>
/// <remarks>
/// Implements <see cref="IEnumerator.Current" /> explicitly.
/// </remarks>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Releases all resources reserved by the <see cref="Enumerator" />.
/// </summary>
/// <remarks>
/// Implements <see cref="IDisposable.Dispose()" /> implicitly.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Usage",
"CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "False Positive; actually calls GC.SuppressFinalize() on itself.")]
public void Dispose()
{
// exit read lock if entered
if (this.currentIndex >= 0 && this.currentIndex < this.enumerable.Count)
{
this.enumerable.semaphore.Release();
}
this.currentIndex = 0;
this.enumerable = null;
GC.SuppressFinalize(this);
}
/// <summary>
/// Advances the <see cref="Enumerator" /> to the next item.
/// </summary>
/// <returns>
/// Returns a value indicating whether the <see cref="Enumerator" /> is inside of the <see cref="ViewObservableDynamicArray{TIn, TOut}" />.
/// </returns>
/// <remarks>
/// Implements <see cref="IEnumerator.MoveNext()" /> implicitly.
/// </remarks>
public bool MoveNext()
{
// enter read lock if not entered
if (this.currentIndex < 0)
{
this.enumerable.semaphore.Wait();
}
var ret = ++this.currentIndex < this.enumerable.Count;
if (!ret)
{
this.enumerable.semaphore.Release();
}
return ret;
}
/// <summary>
/// Resets the <see cref="IEnumerator" />.
/// </summary>
/// <remarks>
/// Implements <see cref="IEnumerator.Reset()" /> implicitly.
/// </remarks>
public void Reset()
{
// exit read lock if entered
if (this.currentIndex >= 0 && this.currentIndex < this.enumerable.Count)
{
this.enumerable.semaphore.Release();
}
this.currentIndex = -1;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace example1
{
public struct Complex
{
public double real;
public double imaginary;
public Complex(double real, double imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator +(Complex c1)
{
return c1;
}
public static Complex operator -(Complex c1)
{
return new Complex(-c1.real, -c1.imaginary);
}
public static bool operator true(Complex c1)
{
return c1.real != 0 || c1.imaginary != 0;
}
public static bool operator false(Complex c1)
{
return c1.real == 0 && c1.imaginary == 0;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
public static Complex operator -(Complex c1, Complex c2)
{
return c1 + (-c2);
}
public static Complex operator *(Complex c1, Complex c2)
{
return new Complex(c1.real * c2.real - c1.imaginary * c2.imaginary,
c1.real * c2.imaginary + c1.imaginary * c2.real);
}
public static Complex operator *(Complex c, double k)
{
return new Complex(c.real * k, c.imaginary * k);
}
public static Complex operator *(double k, Complex c)
{
return c * k;
}
public override string ToString()
{
return (System.String.Format("({0} + {1} i)", real, imaginary));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UrTLibrary.Server.Logging.Events
{
public class UnknownEvent: LogEvent
{
public string Text { get; set; }
public override string ToString()
{
return this.Text;
}
}
}
|
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace BastaDynamicBackendInterface
{
public class HttpHelper
{
internal async Task Post(object user, string method, string contentType = "application/json")
{
var uri = Resources.EndpointUri;
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = contentType;
await wc.UploadStringTaskAsync(uri, method, JsonConvert.SerializeObject(user));
}
}
internal async Task<object> Get()
{
var uri = Resources.EndpointUri;
using (var wc = new WebClient())
{
return JsonConvert.DeserializeObject<object>(await wc.DownloadStringTaskAsync(uri));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using InvoiceClient.Properties;
using Model.Schema.EIVO;
using InvoiceClient.Agent;
using Utility;
using Newtonsoft.Json;
using Model.Locale;
using InvoiceClient.MainContent;
namespace InvoiceClient.TransferManagement
{
public class JsonInvoiceTransferManagerForCBE : ITransferManager
{
private InvoiceWatcher _InvoiceWatcher;
private InvoiceWatcher _CancellationWatcher;
private InvoiceWatcher _AllowanceWatcher;
private InvoiceWatcher _AllowanceCancellationWatcher;
private JsonInvoiceTransferManagerForCBE.LocalSettings _Settings;
public JsonInvoiceTransferManagerForCBE()
{
string path = Path.Combine(Logger.LogPath, "JsonInvoiceTransferManagerForCBE.json");
if (File.Exists(path))
{
this._Settings = JsonConvert.DeserializeObject<JsonInvoiceTransferManagerForCBE.LocalSettings>(File.ReadAllText(path));
}
else
{
this._Settings = new JsonInvoiceTransferManagerForCBE.LocalSettings();
File.WriteAllText(path, JsonConvert.SerializeObject((object)this._Settings));
}
}
public void EnableAll(string fullPath)
{
this._InvoiceWatcher = (InvoiceWatcher)new ProcessRequestWatcher(Path.Combine(fullPath, this._Settings.InvoiceRequestPath))
{
ResponsibleProcessType = new Naming.InvoiceProcessType?(Naming.InvoiceProcessType.C0401_Json_CBE)
};
this._InvoiceWatcher.StartUp();
this._CancellationWatcher = (InvoiceWatcher)new ProcessRequestWatcher(Path.Combine(fullPath, this._Settings.VoidInvoiceRequestPath))
{
ResponsibleProcessType = new Naming.InvoiceProcessType?(Naming.InvoiceProcessType.C0501_Json)
};
this._CancellationWatcher.StartUp();
this._AllowanceWatcher = (InvoiceWatcher)new ProcessRequestWatcher(Path.Combine(fullPath, this._Settings.AllowanceRequestPath))
{
ResponsibleProcessType = new Naming.InvoiceProcessType?(Naming.InvoiceProcessType.D0401_Json)
};
this._AllowanceWatcher.StartUp();
this._AllowanceCancellationWatcher = (InvoiceWatcher)new ProcessRequestWatcher(Path.Combine(fullPath, this._Settings.VoidAllowanceRequestPath))
{
ResponsibleProcessType = new Naming.InvoiceProcessType?(Naming.InvoiceProcessType.D0501_Json)
};
this._AllowanceCancellationWatcher.StartUp();
}
public void PauseAll()
{
if (this._InvoiceWatcher != null)
this._InvoiceWatcher.Dispose();
if (this._CancellationWatcher != null)
this._CancellationWatcher.Dispose();
if (this._AllowanceWatcher != null)
this._AllowanceWatcher.Dispose();
if (this._AllowanceCancellationWatcher != null)
this._AllowanceCancellationWatcher.Dispose();
}
public string ReportError()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._InvoiceWatcher != null)
stringBuilder.Append(this._InvoiceWatcher.ReportError());
if (this._CancellationWatcher != null)
stringBuilder.Append(this._CancellationWatcher.ReportError());
if (this._AllowanceWatcher != null)
stringBuilder.Append(this._AllowanceWatcher.ReportError());
if (this._AllowanceCancellationWatcher != null)
stringBuilder.Append(this._AllowanceCancellationWatcher.ReportError());
return stringBuilder.ToString();
}
public void SetRetry()
{
this._InvoiceWatcher.Retry();
this._CancellationWatcher.Retry();
this._AllowanceWatcher.Retry();
this._AllowanceCancellationWatcher.Retry();
}
public Type UIConfigType
{
get
{
return typeof(JsonInvoiceCenterConfig);
}
}
private class LocalSettings
{
public string InvoiceRequestPath { get; set; } = "Invoice_Json";
public string VoidInvoiceRequestPath { get; set; } = "CancelInvoice_Json";
public string AllowanceRequestPath { get; set; } = "Allowance_Json";
public string VoidAllowanceRequestPath { get; set; } = "CancelAllowance_Json";
}
}
}
|
using CustomerManagement.Application.DTOs;
using CustomerManagement.Application.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CustomerManagement.WebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ClienteController : ControllerBase
{
private readonly IClienteService _clienteService;
public ClienteController(IClienteService clienteService)
{
_clienteService = clienteService;
}
[HttpPost]
public async Task<IActionResult> Create([FromBody] ClienteDTO.Gravar dto)
{
var retorno = await _clienteService.Criar(dto);
if (Guid.Empty.Equals(retorno.Id))
return BadRequest();
dto.Id = retorno.Id;
dto.Endereco.ClienteId = retorno.Id;
return CreatedAtRoute("", new { retorno.Id }, dto);
}
[HttpPut]
[Route("{Id}")]
public async Task<IActionResult> Update(Guid id, [FromBody] ClienteDTO.Gravar dto)
{
if (!dto.Id.Equals(id) || Guid.Empty.Equals(id))
return BadRequest();
if (!_clienteService.IsClienteExists(dto.Id))
return NotFound();
try
{
await _clienteService.Atualizar(dto);
}
catch (DbUpdateConcurrencyException)
{
throw;
}
return NoContent();
}
[HttpDelete]
[Route("{Id}")]
public async Task<IActionResult> Delete([FromRoute] ClienteDTO.Excluir dto)
{
if (!_clienteService.IsClienteExists(dto.Id))
return NotFound();
await _clienteService.Exlcuir(dto);
return NoContent();
}
//[HttpGet (Name = "Get")]
[HttpGet]
[Route("{Id}")]
public ActionResult<ClienteDTO.Retorno> Get([FromRoute] ClienteDTO.ObterPorId dto)
{
var retorno = _clienteService.GetById(dto.Id);
if (Guid.Empty.Equals(retorno.Id))
return NotFound();
return retorno;
}
[HttpGet]
public ActionResult<List<ClienteDTO.Retorno>> Get()
{
var retorno = _clienteService.GetAll();
if (retorno.Count == 0)
return NotFound();
return retorno;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;
using Webcorp.Model;
using Webcorp.Model.Quotation;
using Ninject;
namespace Webcorp.unite.tests
{
[TestClass]
public class UnitTest1
{
static IKernel container;
[AssemblyInitialize()]
public static void AssemblyInit(TestContext context)
{
Debug.WriteLine("AssemblyInit " + context.TestName);
}
[ClassInitialize()]
public static void ClassInit(TestContext context)
{
Debug.WriteLine("ClassInit " + context.TestName);
container = new StandardKernel();
container.Bind(typeof(IEntityProvider<,>)).To(typeof(EntityProvider<,>)).InSingletonScope();
container.Bind(typeof(IEntityProviderInitializable<MaterialPrice, string>)).To(typeof(MaterialPriceInitializer));
}
[TestMethod]
public void TestMethod1()
{
var l = 1 * Length.Mile;
Debug.WriteLine(l.ToString("0.00 [km]"));
Debug.WriteLine(l.ToString("0.00 [mi]"));
var l1 = l.ConvertTo(Length.Mile);
Debug.WriteLine(l1.ToString());
var l2 = Length.Parse(l.ToString("0.00 [km]"));
Debug.WriteLine(l2.ToString());
// Debug.WriteLine(UnitProvider.Default.GetDisplayUnit(l1.GetType()));
}
[TestMethod]
public void TestCurrency()
{
/*var v = 1 * Currency.Euro;
Debug.WriteLine(v.ToString());
Debug.WriteLine(v.ToString("0.00 [chf]"));
var v2 = 1 * Currency.FrancSuisse;
Debug.WriteLine(v2.ToString("0.00 [chf]"));
Debug.WriteLine(v2.ToString("0.00 [euro]"));*/
Currency.FrancSuisse.SetChange(2);
var v3 = 1 * Currency.Euro;
Debug.WriteLine(v3.ToString());
Debug.WriteLine(v3.ToString("0.00 [chf]"));
var v4 = 1 * Currency.FrancSuisse;
Debug.WriteLine(v4.ToString("0.00 [chf]"));
Debug.WriteLine(v4.ToString("0.00 [euro]"));
}
[TestMethod]
public void TestMaterialPrice()
{
var mpp = container.Get<IEntityProvider<MaterialPrice, string>>();
MaterialPrice mp = mpp.Find("1.0035");
Assert.IsNotNull(mp);
Debug.WriteLine(mp.Cout.ToString("0.00 euro/kg"));
MaterialPrice mp1 = mpp.Find("1.0036");
Debug.WriteLine( mp1.Cout.ToString("0.00 euro/kg"));
}
[TestMethod]
public void TestAreaLinear()
{
var a = AreaLinear.Parse("0.328 m2/m");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KolkoIKrzyzyk.Logic;
namespace KolkoIKrzyzyk
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private const string player1Alert = "Tura Gracza 1";
private const string player2Alert = "Tura Gracza 2";
private const string draw = "REMIS";
private const string markX = "X";
private const string markO = "O";
private Logika kolkoIKrzyzykLogika = null;
private Logika KolkoIKrzyzykLogika
{
get
{
if (kolkoIKrzyzykLogika == null) { kolkoIKrzyzykLogika = new Logika(); }
return kolkoIKrzyzykLogika;
}
}
private void ButtonClick(object sender, MouseButtonEventArgs e)
{
if (KolkoIKrzyzykLogika.GameOver)
{
return;
}
Rectangle click = e.Source as Rectangle;
int buttonUid = Convert.ToInt32(click.Uid);
if (IsValidMove(buttonUid))
{
UpdateGameUi(click);
UpdateGameLogicMap(buttonUid);
KolkoIKrzyzykLogika.AmountOfMoves++;
if (KolkoIKrzyzykLogika.AmountOfMoves >= 9)
{
CheckForGameWinner();
CheckForGameTie();
}
KolkoIKrzyzykLogika.CurrentPlayer = KolkoIKrzyzykLogika.IsPlayerOneTurn ? 1 : 2;
}
}
private void UpdateGameLabelForNextPlayer(string labelMessage, Brush color)
{
Info.Content = labelMessage;
Info.Foreground = color;
}
public MainWindow()
{
InitializeComponent();
UpdateGameLabelForNextPlayer(player1Alert, Brushes.Red);
}
/// <param name="sender"></param>
/// <param name="e"></param>
private void Btn_Reset_MouseLeftButtonDown(object sender, RoutedEventArgs e)
{
foreach (Rectangle gamePieces in Container.Children.OfType<Rectangle>())
{
gamePieces.Fill = new SolidColorBrush(Colors.Wheat);
}
KolkoIKrzyzykLogika.ResetGame();
UpdateGameLabelForNextPlayer(player1Alert, Brushes.Red);
}
private void CheckForGameWinner()
{
KolkoIKrzyzykLogika.CheckForGameWinner();
if (KolkoIKrzyzykLogika.GameOver)
{
UpdateGameLabelForNextPlayer(string.Format("Gracz {0} wygrał!", KolkoIKrzyzykLogika.CurrentPlayer), Brushes.DarkGoldenrod);
}
}
private void CheckForGameTie()
{
if (KolkoIKrzyzykLogika.AmountOfMoves >= 25 && !KolkoIKrzyzykLogika.GameOver)
{
UpdateGameLabelForNextPlayer(draw, Brushes.Black);
KolkoIKrzyzykLogika.GameOver = true;
}
}
private bool IsValidMove(int clickedRectangleIndex)
{
if (KolkoIKrzyzykLogika.PressedButtons[clickedRectangleIndex] == 0)
{
return true;
}
return false;
}
private void UpdateGameUi(Rectangle clickedButton)
{
if (KolkoIKrzyzykLogika.IsPlayerOneTurn)
{
UpdateButtonFill(clickedButton, markX, new SolidColorBrush(Colors.Red));
UpdateGameLabelForNextPlayer(player2Alert, Brushes.Blue);
}
else
{
UpdateButtonFill(clickedButton, markO, new SolidColorBrush(Colors.Blue));
UpdateGameLabelForNextPlayer(player1Alert, Brushes.Red);
}
}
private void UpdateButtonFill(Rectangle clickedButton, string playerSymbol, Brush color)
{
if (clickedButton != null)
{
TextBlock tb = new TextBlock();
tb.FontSize = 72;
tb.Background = color;
tb.Text = playerSymbol;
BitmapCacheBrush bcb = new BitmapCacheBrush(tb);
clickedButton.Fill = bcb;
}
}
private void UpdateGameLogicMap(int arrayIndex)
{
int mapValue = KolkoIKrzyzykLogika.CurrentPlayer;
KolkoIKrzyzykLogika.PressedButtons[arrayIndex] = mapValue;
}
}
}
|
using System.Linq;
namespace Student.Repository.interfaces
{
// set the common methods in repo (CRUD)
public interface IGenericRepository<T>
{
T Add(T entity);
void Edit(T entity);
T Delete(T entity);
IQueryable<T> GetAll();
T FindById(int id);
}
}
|
using Dapper;
using Reserva.Domain.Command.Input;
using Reserva.Domain.Command.Result;
using Reserva.Domain.Entities;
using Reserva.Domain.Repositories;
using Reserva.Infra.Context;
using Reserva.Infra.Transactions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reserva.Infra.Repositories
{
public class ReservaRepository : IReservaRepository
{
private readonly ReservaStoreContext _contextStore;
private readonly ReservaContext _context;
private readonly IUow _uow;
public ReservaRepository(ReservaStoreContext contextStore, IUow uow, ReservaContext context)
{
_contextStore = contextStore;
_context = context;
_uow = uow;
}
public ReservaCommadResult GetReservaId(int id)
{
var sql = @"SELECT f.Nome as Filial, u.Nome as NomeUsuario, s.NomeSala, *from Reservas r
JOIN Usuarios u WITH(nolock) on u.UsuarioId = r.UsuarioId
JOIN Sala s WITH(nolock) on s.SalaId = r.SalaId
join Filia f WITH(nolock) on f.FilialId = s.FilialId
where r.ReservaId = @ReservaId";
return _contextStore.Connection.Query<ReservaCommadResult>(
sql, new {ReservaId = id}
).FirstOrDefault();
}
public IEnumerable<ReservaCommadResult> GetReservaSala(ReservaCommandRegister commad)
{
var sql = @"select * from Reservas " +
"where SalaId = @SalaId and HoraInicio >= @HoraInicio and HoraFim <= @HoraFim";
return _contextStore.Connection.Query<ReservaCommadResult>(
sql, new { SalaId = commad.SalaId, HoraInicio = commad.HoraInicio, HoraFim = commad.HoraFim }
);
}
public IEnumerable<ReservaCommadResult> GetReservaSalaId(int salaId)
{
var sql = "select * from Reservas where SalaId = @SalaId";
return _contextStore.Connection.Query<ReservaCommadResult>(
sql, new { SalaId = salaId }
);
}
public IEnumerable<ReservaCommadResult> Listar()
{
var sql = @"SELECT f.Nome as Filial, u.Nome as NomeUsuario, s.NomeSala, *from Reservas r
JOIN Usuarios u WITH(nolock) on u.UsuarioId = r.UsuarioId
JOIN Sala s WITH(nolock) on s.SalaId = r.SalaId
join Filia f WITH(nolock) on f.FilialId = s.FilialId";
return _contextStore.Connection.Query<ReservaCommadResult>(
sql, new { }
);
}
public void removeReserva(int id)
{
var sql = "Delete from Reservas where ReservaId = @ReservaId";
_contextStore.Connection.Execute(
sql, new {ReservaId = id }
);
}
public int Salvar(Reservas reserva)
{
_context.Reservas.Add(reserva);
_uow.commit();
return reserva.ReservaId;
}
}
}
|
using Model.Locale;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.Schema.TurnKey.C0401
{
public static class C0401Extensions
{
}
public partial class Main
{
public string DataNumber;
}
public partial class Invoice
{
public String TxnCode;
}
}
|
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.CookiePolicy;
namespace jwt
{
public class Startup
{
private IConfiguration _config;
public Startup(IConfiguration configuration)
{
_config = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
// configure strongly typed settings objects
var appSettingsSection = _config.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services
.AddCors(option =>
option
.AddDefaultPolicy(builder =>
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()));
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true
};
});
services.AddScoped<UserService>()
.AddScoped<TokenService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCookiePolicy(new CookiePolicyOptions
{
HttpOnly = HttpOnlyPolicy.Always
});
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TileLight : MonoBehaviour {
GameObject squareParticle;
ParticleSystem particleLight;
tileScript ts;
public LibPdInstance pdPatch;
StringEvent r;
//public UnityEditor.DefaultAsset pdToUnityPatch;
public Light lightPrefab;
float intensityFromTile;
private void Awake()
{
//pdPatch = gameObject.GetComponent<LibPdInstance>();
//pdPatch.patch = pdToUnityPatch;
//pdPatch.pureDataEvents.Bang.AddListener(BangReceive);
//pdPatch.Bind("lampBang");
}
// Use this for initialization
void Start () {
squareParticle = GameObject.Find("SquareParticle");
particleLight = squareParticle.GetComponent<ParticleSystem>();
ts = GetComponent<tileScript>();
intensityFromTile = ts.intensityFromTile;
var lights = particleLight.lights;
lights.light = lightPrefab;
}
// Update is called once per frame
void Update () {
if (!ts.isSphereCreated)
{
intensityFromTile = ts.intensityFromTile;
lightPrefab.intensity = 1f + intensityFromTile * 0.5f;
lightPrefab.range = 3 + (intensityFromTile - 1f) * 0.5f;
var lights = particleLight.lights;
lights.light = lightPrefab;
}
else
{
intensityFromTile = ts.intensityFromTile;
lightPrefab.intensity -= 0.05f;
lightPrefab.range -= 0.05f;
if(lightPrefab.intensity < 0f)
{
lightPrefab.intensity = 0.05f;
lightPrefab.range = 0.05f;
}
var lights = particleLight.lights;
lights.light = lightPrefab;
}
pdPatch.SendFloat("f", intensityFromTile);
}
void BangReceive(string name)
{
Debug.Log(name);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ToDo.Core.Lists;
namespace ToDo.Core
{
interface IDataStore
{
int InsertList(BaseList list);
void EditList(BaseList list);
void DeleteList(int id);
int InsertTask(Task task);
int EditTask(Task task);
int DeleteTask(Task task);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using VS.Connection;
using VS.Container;
namespace VS.Logic {
public class BaseLogic {
#region State Property Definitions
protected eState state;
public eState State {
get {
return state;
}
set {
state = value;
OnStateChanged();
}
}
protected void OnStateChanged() {
StateChangedDelegate ev = this.StateChanged;
if (ev != null) ev(this, new StateChangedEventArgs(this.state));
}
public event StateChangedDelegate StateChanged;
#endregion
protected List<BaseContainer> containers;
public List<BaseContainer> Containers {
get { return this.containers; }
set { this.containers = value; }
}
protected BaseContainer container;
public BaseContainer Container {
get { return this.container; }
set { this.container = value; }
}
public BaseLogic() { }
}
public interface IStateChangedListener {
void StateChanged(BaseLogic sender, StateChangedEventArgs args);
}
public interface IStateListChangedListener {
void ListStateChanged(BaseLogic sender, StateChangedEventArgs args);
}
public class StateChangedEventArgs : System.EventArgs {
protected eState state;
public eState State {
get { return this.state; }
}
public StateChangedEventArgs() { }
public StateChangedEventArgs(eState state) {
this.state = state;
}
}
public delegate void StateChangedDelegate(BaseLogic sender, StateChangedEventArgs args);
public enum eState : int { ADDING, ADDED, CANCELING, CANCELED, DELETING, DELETED, RETRIEVING, RETRIEVED, PRESAVING, SAVING,
SAVED, RESYNCHING, RESYNCHED};
}
|
using CHSystem.Filters;
using System.Web.Mvc;
namespace CHSystem.Controllers
{
[AuthenticationFilter]
public class BaseController : Controller
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CA2
{
class Book
{
//Properties
public string Title { get; set; }
public double Price { get; set; }
public int Pages { get; set; }
//ToString method which returns the book details
public override string ToString()
{
return Title + ", " + Pages + " pages - €" + Price;
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Protocol.Core.Types;
namespace NuGet.Protocol.Core.v2
{
public class SimpleSearchResourceV2Provider : V2ResourceProvider
{
public SimpleSearchResourceV2Provider()
: base(typeof(SimpleSearchResource), "SimpleSearchResourceV2Provider", NuGetResourceProviderPositions.Last)
{
}
public override async Task<Tuple<bool, INuGetResource>> TryCreate(SourceRepository source, CancellationToken token)
{
SimpleSearchResourceV2 resource = null;
var v2repo = await GetRepository(source, token);
if (v2repo != null)
{
resource = new SimpleSearchResourceV2(v2repo);
}
return new Tuple<bool, INuGetResource>(resource != null, resource);
}
}
}
|
using AssetHub.DAL;
using AssetHub.Models;
using AssetHub.ViewModels.Loan;
using AssetHub.ViewModels.Loan.Partial;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AssetHub.Controllers
{
public class LoanController : Controller
{
AssetHubContext db = new AssetHubContext();
//GET: CreateLoan
public ActionResult CreateLoan(int id)
{
return View(new CreateLoanViewModel
{
AssetId = id,
AssetName = db.Assets.Find(id).Name,
Rooms = db.RoomDropdown(),
Hours = GenerateHours(),
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateLoan(CreateLoanViewModel vm)
{
if(vm.SelectedHourFromId < 0)
{
ModelState.AddModelError("TimeFrom", Loan.Validator.TIME_FROM_REQUIRED);
}
if(vm.SelectedHourToId < 0)
{
ModelState.AddModelError("TimeTo", Loan.Validator.TIME_TO_REQUIRED);
}
var timeFrom = vm.DateFrom.AddHours(vm.SelectedHourFromId);
var timeTo = vm.DateTo.AddHours(vm.SelectedHourToId);
var timeFromValidation = Loan.Validator.ValidateTimeTo(timeFrom);
if(timeFromValidation != null)
{
ModelState.AddModelError("TimeFrom", timeFromValidation);
}
var timeToValidation = Loan.Validator.ValidateTimeTo(timeTo);
if(timeToValidation != null)
{
ModelState.AddModelError("TimeTo", timeFromValidation);
}
var intervalValidation = Loan.Validator.ValidateTimeInterval(timeFrom, timeTo);
if(intervalValidation != null)
{
ModelState.AddModelError("TimeFrom", intervalValidation);
ModelState.AddModelError("TimeTo", intervalValidation);
}
var availableValidation = Loan.Validator.ValidateAssetAvailabilty(vm.AssetId, timeFrom, timeTo);
if(availableValidation != null)
{
ModelState.AddModelError("", availableValidation);
}
var roomValidation = Loan.Validator.ValidateRoom(vm.SelectedRoomId);
if(roomValidation != null)
{
ModelState.AddModelError("SelectedRoomId", roomValidation);
}
if(ModelState.IsValid)
{
try
{
var loan = new Loan
{
AssetId = vm.AssetId,
RoomId = vm.SelectedRoomId,
TimeFrom = timeFrom,
TimeTo = timeTo,
UserId = User.Identity.GetUserId(),
};
db.Loans.Add(loan);
db.SaveChanges();
return Json(new { Success = true, Message = Loan.SAVE_SUCCESS });
}
catch (Exception e)
{
return Json(new { Success = false, Message = Loan.SAVE_FAIL });
}
}
vm.Hours = GenerateHours();
vm.Rooms = db.RoomDropdown();
return PartialView("_CreateLoan", vm);
}
public ActionResult ViewLoan(int id)
{
return View(new ViewLoanViewModel(id));
}
public ActionResult ReturnLoan(int id)
{
var l = db.Loans.Find(id);
l.TimeTo = DateTime.Now;
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
private IEnumerable<SelectListItem> GenerateHours()
{
var list = new List<SelectListItem>();
for(var i = 0; i < 24; i++)
{
list.Add(new SelectListItem
{
Value = i.ToString(),
Text = i.ToString(),
});
}
return new SelectList(list, "Value", "Text");
}
}
} |
using System;
using SnakeGame;
using NUnit.Framework;
namespace SnakeTest
{
[TestFixture]
public class PointTest
{
//Create 2 Points at 0,0 and make sure they are both at 0,0, and that they'e not the same object
[Test]
public void TestPointEqual()
{
Point p = new Point(0, 0);
Point p2 = new Point(0, 0);
Assert.IsTrue(p.Equals(p2));
Assert.AreNotSame(p, p2);
}
//Create 4 Points at different positions and make sure they aren't in the same position
[Test]
public void TestPointNotEqual()
{
Point p = new Point(0, 0);
Point p2 = new Point(0, 1);
Point p3 = new Point(1, 0);
Point p4 = new Point(1, 1);
Assert.IsFalse(p.Equals(p2));
Assert.IsFalse(p.Equals(p3));
Assert.IsFalse(p.Equals(p4));
}
}
}
|
using SpSim.Setting;
using SpSim.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SpSim.Forms
{
public partial class GUI : Form
{
private Location location;
public GUI()
{
InitializeComponent();
}
/// <summary>
/// Quits the programm
/// </summary>
private void quit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void loadSetting_Click(object sender, EventArgs e)
{
string Path = string.Empty;
Display.Clear();
OpenFileDialog openFileDialog = new OpenFileDialog();
/*openFileDialog.Filter = "XML-File (*.xml)|*.xml |All files (*.*)|*.*";*/
openFileDialog.Filter = "All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK) {
Path = openFileDialog.FileName;
location = IOHelper.ImportFile(Path, Display);
/*
//Import testing block
location.PrintProtagonist();
location.PrintRooms();
location.PrintImplements();
location.PrintClothes();*/
}
Input.Focus();
}
/// <summary>
/// Handels the players input
/// </summary>
private void Input_KeyDown(object sender, KeyEventArgs e)
{
//Enter starts the Evaluation
if (e.KeyCode == Keys.Enter)
{
try
{
Display.AppendText(String.Format("{0}[{1}]", Environment.NewLine, Input.Text));
location.HandleSelection(Convert.ToInt32(Input.Text));
}
catch (Exception ex)
{
Display.AppendText(String.Format(
"{0}An error has okued :V{0}Either your input was invalid or something is f*cked up.{0} If it seems to be the last case, please complain (and ideally post a screenshot with the stactrace) in 4chan/d's spanking thread and/or 8chan/spank's game thread and I`ll try my best to fix it.{0}{1}{0}{2}{0}{3}{0}"
, Environment.NewLine, ex.Message, ex.TargetSite, ex.StackTrace));
location.PrintDefaultStatus();
location.EvaluateDefaultActions();
location.PrintAvailableActions();
}
Input.Text = "";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ultilities
{
public class UtilitiesMethod
{
public static String ConvertMinuteToString(int minute)
{
Int32 hour = minute / 60;
Int32 min = minute - hour * 60;
String strHour = hour.ToString().Length == 1 ? "0" + hour.ToString() : hour.ToString();
String strMin = min.ToString().Length == 1 ? "0" + min.ToString() : min.ToString();
return strHour + ":" + strMin + ":00";
}
}
}
|
/* **********************************************
* 版 权:亿水泰科(EWater)
* 创建人:JinJianping
* 日 期:2019/5/29 14:45:11
* 描 述:数据维护-测站
* *********************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EWF.Application.Web.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace EWF.Application.Web.Areas.SysManage.Controllers
{
[Authorize]
public class SiteDataManageController : EWFBaseController
{
#region 测站概况
public IActionResult Index()
{
return View();
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class SumPolinomials
{
static void Sum(int[] arr1, int[] arr2)
{
int len = Math.Max(arr1.Length, arr2.Length);
int[] sum = new int[len];
for (int i = 0; i < len; i++)
{
sum[i] = arr1[i] + arr2[i];
}
PrintArray(sum);
}
static void PrintArray(int[] arr)
{
for (int i = arr.Length - 1; i >= 0; i--)
{
if (i == 0)
{
Console.Write(arr[i]);
}
else
{
Console.Write(arr[i] + "x^" + i + " + ");
}
}
Console.WriteLine();
}
static void Main()
{
/*Write a method that adds two polynomials. */
Console.Write("Enter power of the first polinom: ");
int firstPower = int.Parse(Console.ReadLine()) + 1;
Console.Write("Enter power of the second polinom: ");
int secondPower = int.Parse(Console.ReadLine()) + 1;
int biggerPower = Math.Max(firstPower, secondPower);
int[] first = new int[biggerPower];
int[] second = new int[biggerPower];
Console.WriteLine("Enter {0} coefficients for the first polinomial starting with the free term: ", firstPower);
for (int i = 0; i < firstPower; i++)
{
first[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter {0} coefficients for the second polinomial starting with the free term: ", secondPower);
for (int i = 0; i < secondPower; i++)
{
second[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("The sum of the two polinomials is: ");
Sum(first, second);
}
}
|
using KnapsackProblem.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace KnapsackAnnealing.Solver.TryStrategies
{
public class RandomTryStrategy : ITryStrategy
{
Random random;
public RandomTryStrategy(int seed)
{
random = new Random(seed);
}
//Performs a random bit-flip
public bool Try(SimulatedAnnealingSolver solverInstance, ref KnapsackConfiguration currentConfiguration)
{
var bitToFlip = random.Next(0, solverInstance.Instance.ItemCount - 1);
var triedConfiguration = new KnapsackConfiguration(currentConfiguration);
triedConfiguration.ItemVector[bitToFlip] = !triedConfiguration.ItemVector[bitToFlip];
if (triedConfiguration.ItemVector[bitToFlip])
{
triedConfiguration.Price += solverInstance.Instance.Items[bitToFlip].Price;
triedConfiguration.Weight += solverInstance.Instance.Items[bitToFlip].Weight;
}
else
{
triedConfiguration.Price -= solverInstance.Instance.Items[bitToFlip].Price;
triedConfiguration.Weight -= solverInstance.Instance.Items[bitToFlip].Weight;
}
triedConfiguration.Cost = solverInstance.Options.ScoreStrategy.Cost(triedConfiguration, solverInstance);
if (triedConfiguration.Cost >= currentConfiguration.Cost)
{
currentConfiguration = triedConfiguration;
return true;
}
var delta = triedConfiguration.Cost - currentConfiguration.Cost;
if (random.NextDouble() < Math.Exp(delta / solverInstance.CurrentTemperature))
{
currentConfiguration = triedConfiguration;
return true;
}
return false;
}
}
}
|
using DynamicData;
using ReactiveUI;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Collections.Generic;
using System.Windows;
using TableTopCrucible.Core.Models.Sources;
using TableTopCrucible.Core.Services;
using TableTopCrucible.Core.Helper;
using TableTopCrucible.Data.Models.Views;
using TableTopCrucible.Data.Services;
using TableTopCrucible.Domain.Models.ValueTypes.IDs;
using System.Windows.Input;
using TableTopCrucible.WPF.Commands;
using TableTopCrucible.Core.WPF.Helper;
using System.Collections.Specialized;
using TableTopCrucible.Domain.Library.WPF.Views;
namespace TableTopCrucible.Domain.Library.WPF.ViewModels
{
public struct ItemClickedEventArgs
{
public ItemClickedEventArgs(ItemSelectionInfo item, MouseButtonEventArgs e)
{
Item = item;
EventArgs = e;
}
public ItemSelectionInfo Item { get; }
public MouseButtonEventArgs EventArgs { get; }
}
public interface ISelectionProvider
{
ISourceList<ItemId> SelectedItemIDs { get; }
bool Disconnected { get; }
}
public class ItemSelectionInfo : DisposableReactiveObjectBase
{
public ICommand ItemLeftMouseButtonDownCommand { get; }
private ObservableAsPropertyHelper<bool> _isSelected;
public bool IsSelected
{
get => _isSelected.Value;
//required to prevent 2-way-binging exception, use the source-list to set it}
set { }
}
public ItemEx Item { get; }
public ItemSelectionInfo(ItemEx item, ISelectionProvider selectionProvider, ICommand dragCommand)
{
this.ItemLeftMouseButtonDownCommand = dragCommand;
this.Item = item;
this._isSelected =
selectionProvider
.SelectedItemIDs
.Connect()
.Filter(id => id == item.ItemId)
.ToCollection()
.Select(lst => lst.Any())
.TakeUntil(destroy)
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, nameof(IsSelected));
}
}
public class ItemListViewModel : DisposableReactiveObjectBase, ISelectionProvider
{
private readonly IItemService _itemService;
private readonly IInjectionProviderService _injectionProviderService;
public BehaviorSubject<Func<ItemEx, bool>> FilterChanges { get; } = new BehaviorSubject<Func<ItemEx, bool>>(_ => true);
ReadOnlyObservableCollection<ItemSelectionInfo> _items;
public ReadOnlyObservableCollection<ItemSelectionInfo> Items => _items;
public IObservableList<ItemEx> Selection { get; private set; }
public ISourceList<ItemId> SelectedItemIDs { get; } = new SourceList<ItemId>();
public ICommand ItemClickedCommand { get; }
public bool Disconnected { get; private set; }
public ICommand DeselectAllCommand { get; }
public ICommand ListKeyUpCommand { get; }
public ICommand DragCommand { get; }
public ItemListViewModel(
IItemService itemService,
IInjectionProviderService injectionProviderService)
{
this._itemService = itemService ?? throw new NullReferenceException("got no itemService");
this._injectionProviderService = injectionProviderService ?? throw new NullReferenceException("got no itemservice");
this.DeselectAllCommand = new RelayCommand(
_ => this.SelectedItemIDs.Clear(),
_ => this.SelectedItemIDs.Items.Any());
this.ItemClickedCommand = new RelayCommand(onItemClicked);
this.ListKeyUpCommand = new RelayCommand(onListKeyUp);
DragCommand = new RelayCommand(sender =>
{
if (KeyboardHelper.IsKeyPressed(ModifierKeys.Alt))
{
itemDrag(sender as DependencyObject);
}
});
this._injectionProviderService.Provider.Subscribe(
(provider) =>
{
if (provider == null)
throw new InvalidOperationException("provider is null");
#region list assembly
var itemList = this._itemService
.GetExtended()
.Connect()
.Filter(FilterChanges)
.TakeUntil(destroy);
var selectionList =
itemList.Transform(item => new ItemSelectionInfo(item, this, DragCommand))
.DisposeMany();
var _selection =
SelectedItemIDs.Connect()
.AddKey(id => id)
.LeftJoin(
itemList,
item => item.ItemId,
(id, item) => new { id, item })
.RemoveKey();
Selection =
_selection
.Filter(x => x.item.HasValue)
.Transform(x => x.item.Value)
.AsObservableList();
_selection
.Filter(x => !x.item.HasValue)
.ToCollection()
.Subscribe(col =>
{
if (col.Any())
SelectedItemIDs.RemoveMany(col.Select(x => x.id));
});
selectionList
.Sort(item => item.Item.Name)
.ObserveOn(RxApp.MainThreadScheduler)
.Do(_ => this.Disconnected = true)
.Bind(out _items)
.Do(_ => this.Disconnected = false)
.Subscribe();
#endregion
});
}
void onItemClicked(object e)
{
if (e is ItemClickedEventArgs args)
onItemClicked(args);
else
throw new InvalidOperationException($"{nameof(ItemListViewModel)}.{nameof(onItemClicked)} invalid args {e}");
}
private void itemDrag(DependencyObject source)
{
var files = this.Selection.Items
.Select(item => item.LatestFile?.AbsolutePath)
.Where(x => x != null)
.ToStringCollection();
DataObject dragData = new DataObject();
dragData.SetFileDropList(files);
DragDrop.DoDragDrop(source, dragData, DragDropEffects.Move);
}
private ItemSelectionInfo previouslyClickedItem = null;
void onItemClicked(ItemClickedEventArgs args)
{
var curItem = args.Item;
var prevItem = previouslyClickedItem;
var isStrgPressed = KeyboardHelper.IsKeyPressed(ModifierKeys.Control);
var isShiftPressed = KeyboardHelper.IsKeyPressed(ModifierKeys.Shift);
var isAltPressed = KeyboardHelper.IsKeyPressed(ModifierKeys.Alt);
if (isAltPressed)
return;
if (isStrgPressed)
{
if (curItem.IsSelected)
SelectedItemIDs.Remove(curItem.Item.ItemId);
else
SelectedItemIDs.Add(curItem.Item.ItemId);
}
else if (isShiftPressed)
{
var section = this.Items.Subsection(curItem, prevItem);
if (section.All(item => item.IsSelected))
SelectedItemIDs.RemoveMany(section.Select(item => item.Item.ItemId));
else
SelectedItemIDs.AddRange(section.Select(item => item.Item.ItemId).Except(this.SelectedItemIDs.Items));
}
else
{
if (SelectedItemIDs.Count == 1 && SelectedItemIDs.Items.Contains(curItem.Item.ItemId))
return;
this.SelectedItemIDs.Clear();
SelectedItemIDs.Add(curItem.Item.ItemId);
}
previouslyClickedItem = curItem;
}
void onListKeyUp(object e)
{
if (e is KeyEventArgs args)
onListKeyUp(args);
else
throw new InvalidOperationException($"{nameof(ItemListViewModel)}.{nameof(onListKeyUp)} invalid args {e}");
}
void onListKeyUp(KeyEventArgs args)
{
if (KeyboardHelper.IsKeyPressed(ModifierKeys.Control) && args.Key == Key.A)
{
if (Selection.Items.Count() == Items.Count())
SelectedItemIDs.Clear();
else
SelectedItemIDs.AddRange(Items.Select(Items => Items.Item.ItemId));
}
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
namespace Scheduler.Models
{
public class DoctorImage
{
[ForeignKey("Doctor")]
public int Id { get; set; }
public byte[] Image { get; set; }
public virtual Doctor Doctor { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;
namespace solution1.gestion_utilisateur
{
public partial class modifier_suprimer_utilisateur : DevExpress.XtraEditors.XtraUserControl
{
//public gestion_utilisateur gestion_utilisateur = new gestion_utilisateur();
string connectionString = ConfigurationManager.ConnectionStrings["connectString1"].ConnectionString;
string requete;
public string mot;
public string log;
public modifier_suprimer_utilisateur()
{
InitializeComponent();
}
private void modifier_suprimer_utilisateur_Load(object sender, EventArgs e)
{
charger_utilisateur();
}
private void charger_utilisateur()
{
DataSet dSUtilisateur = MaConnexion.ExecuteSelect(connectionString, "select idUtilisateur,Administrateur, pseudo, motDePasse from utilisateur where etat = 'Valide'");
if (dSUtilisateur != null)
{
foreach (DataRow row in dSUtilisateur.Tables[0].Rows)
{
object[] newRow = new object[] { row[0].ToString().Trim(), row[1].ToString().Trim(), row[2].ToString().Trim(), row[3].ToString().Trim(),null,null };
dataGrid_utilisateur.Rows.Add(newRow);
}
}
}
private void dataGrid_utilisateur_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
//click sur le bouton de suppression
if (dataGrid_utilisateur.Columns[e.ColumnIndex].Name == "Supprimer")
{
if (e.RowIndex != dataGrid_utilisateur.RowCount - 1) //bouton de suppression
{
if (MessageBox.Show("Voulez vous vraiment supprimer cet utilisateur ?", "Supprimer un client", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
requete = "update Utilisateur set etat = 'Non valide' where pseudo ='" + dataGrid_utilisateur.Rows[e.RowIndex].Cells["Login"].Value + "'and motDePasse='" + dataGrid_utilisateur.Rows[e.RowIndex].Cells["Mot_pass"].Value+"'";
if (MaConnexion.ExecuteUpdate(connectionString, requete) == 1)
{
dataGrid_utilisateur.Rows.Clear();
charger_utilisateur();
}
else
MessageBox.Show("La suppression a échoué", "Erreur de suppression", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
if (dataGrid_utilisateur.Columns[e.ColumnIndex].Name == "Modifier") //click sur le bouton de modification ou d'ajout
{
if (e.RowIndex != dataGrid_utilisateur.RowCount - 1) //click sur le bouton de modification
{
log= dataGrid_utilisateur.Rows[e.RowIndex].Cells["login"].Value.ToString();
mot = dataGrid_utilisateur.Rows[e.RowIndex].Cells["mot_pass"].Value.ToString();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YzkSoftWare.Data
{
/// <summary>
/// 数字类型
/// </summary>
public enum NumberType
{
Unkown = 0,
/// <summary>
/// Int32
/// </summary>
Int = 1,
/// <summary>
/// int64
/// </summary>
Long = 2,
/// <summary>
/// byte
/// </summary>
Byte = 3,
/// <summary>
/// int16
/// </summary>
Short = 4,
/// <summary>
/// uint32
/// </summary>
UInt = 5,
/// <summary>
/// uint64
/// </summary>
ULong = 6,
/// <summary>
/// uint16
/// </summary>
UShort = 7,
/// <summary>
/// ubyte
/// </summary>
Sbyte = 8,
/// <summary>
/// decimal
/// </summary>
Decimal = 9,
/// <summary>
/// double
/// </summary>
Double = 10,
/// <summary>
/// float
/// </summary>
Float = 11
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuManager : MonoBehaviour {
public GameObject destinationPanel;
public GameObject MainViewPanel;
public GameObject VizModePanel;
public void showDestinations(){
destinationPanel.SetActive(true);
MainViewPanel.SetActive(false);
}
public void DonePressed(){
hideDestination();
NodeNavigation.instance.GetAllPaths();
}
private void hideDestination(){
destinationPanel.SetActive(false);
MainViewPanel.SetActive(true);
}
public void showVizModes(){
VizModePanel.SetActive(true);
}
public void hideVizModes()
{
VizModePanel.SetActive(false);
}
}
|
//
// Copyright 2010, 2020 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// 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;
using Carbonfrost.Commons.Core;
namespace Carbonfrost.Commons.PropertyTrees {
public class PropertyTreeReaderSettings {
private bool _allowExternals;
private bool _isReadOnly;
public bool AllowExternals {
get {
return _allowExternals;
}
set {
ThrowIfReadOnly();
_allowExternals = value;
}
}
public bool IsReadOnly {
get {
return _isReadOnly;
}
}
public PropertyTreeReaderSettings() { }
public PropertyTreeReaderSettings(PropertyTreeReaderSettings other) {
if (other != null) {
AllowExternals = other.AllowExternals;
}
}
public void MakeReadOnly() {
_isReadOnly = true;
}
public PropertyTreeReaderSettings Clone() {
return CloneCore();
}
protected virtual PropertyTreeReaderSettings CloneCore() {
return new PropertyTreeReaderSettings(this);
}
protected void ThrowIfReadOnly() {
if (IsReadOnly) {
throw Failure.ReadOnlyCollection();
}
}
}
}
|
namespace Tekstomania.Mobile.Core.Services.Interfaces
{
public interface IAlertService
{
void ShowAlert(string title, string subtitle);
}
} |
namespace FeelingGoodApp.Services.Models
{
public class ExercisePhoto
{
public int Id { get; set; }
public string highres { get; set; }
public string thumb { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace baithuchanh5
{
class bai1
{
static void Main()
{
Console.WriteLine("Nhap so nguyen n");
int n = Convert.ToInt32(Console.ReadLine());
bool kq = ktsonguyen(n);
Console.WriteLine(kq);
}
static bool ktsonguyen(int n)
{
if(n<2)
{
return false;
}
if (n % n == 0 || n % 1 == 0)
{
return true;
}
else
return false;
}
}
}
|
namespace Triton.Common
{
using log4net;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using Triton.Common.LogUtilities;
public class AssemblyLoader<T>
{
private readonly bool bool_0;
private readonly FileSystemWatcher fileSystemWatcher_0;
private readonly ILog ilog_0;
[CompilerGenerated]
private List<T> list_0;
private readonly string string_0;
[field: CompilerGenerated]
public event EventHandler Reloaded;
public AssemblyLoader(string directory, bool detectFileChanges)
{
this.ilog_0 = Logger.GetLoggerInstanceForType();
this.fileSystemWatcher_0 = new FileSystemWatcher();
this.Instances = new List<T>();
this.string_0 = directory;
this.bool_0 = detectFileChanges;
if (this.bool_0)
{
this.fileSystemWatcher_0.Path = directory;
this.fileSystemWatcher_0.Filter = "*.cs";
this.fileSystemWatcher_0.IncludeSubdirectories = true;
this.fileSystemWatcher_0.EnableRaisingEvents = true;
this.fileSystemWatcher_0.Changed += new FileSystemEventHandler(this.method_0);
this.fileSystemWatcher_0.Created += new FileSystemEventHandler(this.method_1);
this.fileSystemWatcher_0.Deleted += new FileSystemEventHandler(this.method_2);
}
this.Reload("Initializing");
}
[CompilerGenerated]
private void method_0(object sender, FileSystemEventArgs e)
{
this.Reload(e.ChangeType.ToString());
}
[CompilerGenerated]
private void method_1(object sender, FileSystemEventArgs e)
{
this.Reload(e.ChangeType.ToString());
}
[CompilerGenerated]
private void method_2(object sender, FileSystemEventArgs e)
{
this.Reload(e.ChangeType.ToString());
}
public void Reload(string reason)
{
this.ilog_0.Debug(string.Format("Reloading AssemblyLoader<{0}> - {1}", typeof(T), reason));
this.Instances = new List<T>();
if (!Directory.Exists(this.string_0))
{
this.ilog_0.Error(string.Format("Could not Reload assemblies because the path \"{0}\" does not exist.", this.string_0));
}
else
{
string[] directories = Directory.GetDirectories(this.string_0);
int index = 0;
while (true)
{
if (index >= directories.Length)
{
break;
}
string path = directories[index];
try
{
Triton.Common.CodeCompiler compiler = new Triton.Common.CodeCompiler(path);
CompilerResults results = compiler.Compile();
if (results != null)
{
if (results.Errors.HasErrors)
{
foreach (object obj2 in results.Errors)
{
this.ilog_0.Error("Compiler Error: " + obj2.ToString());
}
}
else
{
this.Instances.AddRange(new TypeLoader<T>(compiler.CompiledAssembly, null));
}
}
}
catch (Exception exception)
{
if (exception is ReflectionTypeLoadException)
{
foreach (Exception exception2 in (exception as ReflectionTypeLoadException).LoaderExceptions)
{
this.ilog_0.Error("[Reload] An exception occured.", exception2);
}
}
else
{
this.ilog_0.Error("[Reload] An exception occured.", exception);
}
}
index++;
}
using (List<T>.Enumerator enumerator2 = new TypeLoader<T>(null, null).GetEnumerator())
{
while (enumerator2.MoveNext())
{
Class226<T> class2 = new Class226<T> {
gparam_0 = enumerator2.Current
};
if (!this.Instances.Any<T>(new Func<T, bool>(class2.method_0)))
{
this.Instances.Add(class2.gparam_0);
}
}
}
if (this.eventHandler_0 != null)
{
this.eventHandler_0(this, null);
}
}
}
public List<T> Instances
{
[CompilerGenerated]
get
{
return this.list_0;
}
[CompilerGenerated]
private set
{
this.list_0 = value;
}
}
[CompilerGenerated]
private sealed class Class226
{
public T gparam_0;
internal bool method_0(T gparam_1)
{
return (gparam_1.GetType().FullName == this.gparam_0.GetType().FullName);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour, IDamageable
{
public static event EventController.ObjectHandler EnemyDead;
private float _currentHealth;
[SerializeField] private int _damage;
[SerializeField] private int _speed;
[SerializeField] public float _health;
[SerializeField] public float _armor;
private Transform _victimTransform;
private Rigidbody2D _rigidbody2D;
public float health { get { return _health; }}
public float currentHealth
{
get
{
return _currentHealth;
}
private set
{
if(value < 0)
value = 0;
_currentHealth = value;
}
}
public void GetDamage(int damage, IDamageable attacker)
{
currentHealth -= damage * (1 - _armor);
if(_currentHealth <= 0)
{
EnemyDead(this);
Destroy(this.gameObject);
}
}
public void Init(Transform victimTransform)
{
_rigidbody2D = GetComponent<Rigidbody2D>();
_victimTransform = victimTransform;
currentHealth = health;
}
private void FixedUpdate()
{
Rotate();
Move();
}
private void Move()
{
Vector2 move = transform.up * _speed * Time.deltaTime;
_rigidbody2D.MovePosition(_rigidbody2D.position + move);
}
private void Rotate()
{
Vector2 position = _victimTransform.position;
Vector2 targetDir = position - (Vector2)transform.position;
Vector2 localTarget = transform.InverseTransformPoint(position);
float angle = Mathf.Atan2(localTarget.x, localTarget.y) * Mathf.Rad2Deg;
_rigidbody2D.MoveRotation(_rigidbody2D.rotation - angle);
}
private void OnTriggerEnter2D(Collider2D collider2D)
{
IDamageable victim = collider2D.GetComponent<TankHealth>();
if(victim != null)
{
victim.GetDamage(_damage, this);
EnemyDead(this);
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CheeseSystem
{
public class MilkProductionLine : IProductionLine
{
public Production Produce()
{
return new Milk();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HeladacWeb.Models
{
public class HeladacError:Exception
{
public HeladacErrorCode errorCode { get; set;}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.