text stringlengths 13 6.01M |
|---|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GlobalDevelopment.SocialNetworks.Facebook.Models
{
public class FacebookEngagement
{
/// <summary>
/// Number of poeple who like this.
/// </summary>
public int Count { get; set; }
/// <summary>
/// Abbreviated string reprentation of count.
/// </summary>
public string CountString { get; set; }
/// <summary>
/// Abbreviated string representation of count if the viewer likes the object.
/// </summary>
public string CountStringWithLike { get; set; }
/// <summary>
/// Abbreviated string representation of count if the viewer likes the object.
/// </summary>
public string CountStringWithoutLike { get; set; }
/// <summary>
/// The text that the like button would currently display.
/// </summary>
public string SocialSentence { get; set; }
/// <summary>
/// The text that the like button would display if the viewer likes the object.
/// </summary>
public string SocialSentenceWithLike { get; set; }
/// <summary>
/// Text that the like button would display if the viewer does not like the object.
/// </summary>
public string SocialSentenceWithoutLike { get; set; }
public FacebookEngagement(JToken token)
{
JObject obj = JObject.Parse(token.ToString());
Count = int.Parse((obj["count"] ?? "0").ToString());
CountString = (obj["count_string"] ?? "NA").ToString();
CountStringWithLike = (obj["count_string_with_like"] ?? "NA").ToString();
CountStringWithoutLike = (obj["count_string_without_like"] ?? "NA").ToString();
SocialSentence = (obj["social_sentance"] ?? "NA").ToString();
SocialSentenceWithLike = (obj["social_sentance_with_like"] ?? "NA").ToString();
SocialSentenceWithoutLike = (obj["social_sentance_without_like"] ?? "NA").ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using MagicOnion.Client;
using WagahighChoices.GrpcUtils;
using WagahighChoices.Toa.Grpc.Internal;
using WagahighChoices.Toa.Imaging;
namespace WagahighChoices.Toa.Grpc
{
public class GrpcRemoteWagahighOperator : WagahighOperator
{
private readonly Channel _channel;
private readonly IToaMagicOnionService _service;
public GrpcRemoteWagahighOperator(string host, int port)
{
this._channel = new Channel(host, port, ChannelCredentials.Insecure);
this._service = MagicOnionClient.Create<IToaMagicOnionService>(this._channel, WhcFormatterResolver.Instance);
this.LogStream = Observable.Create<string>(async (observer, cancellationToken) =>
{
using (var result = await this._service.LogStream().ConfigureAwait(false))
using (cancellationToken.Register(result.Dispose))
{
var stream = result.ResponseStream;
// MoveNext に CancellationToken を指定するのは対応していない
while (true)
{
if (cancellationToken.IsCancellationRequested) return;
if (!await stream.MoveNext().ConfigureAwait(false)) break;
observer.OnNext(stream.Current);
}
}
observer.OnCompleted();
});
}
public Task ConnectAsync() => this._channel.ConnectAsync();
public override Task<Bgra32Image> CaptureContentAsync() => this._service.CaptureContent().ResponseAsync;
public override Task<Size> GetContentSizeAsync() => this._service.GetContentSize().ResponseAsync;
public override Task SetCursorPositionAsync(short x, short y) => this._service.SetCursorPosition(x, y).ResponseAsync;
public override Task MouseClickAsync() => this._service.MouseClick().ResponseAsync;
public override Task<Bgra32Image> GetCursorImageAsync() => this._service.GetCursorImage().ResponseAsync;
public override IObservable<string> LogStream { get; }
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
// TODO: もっといい手段ないの
this._channel.ShutdownAsync().Wait();
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace SeniorLibrary.Models
{
public class Entrying
{
[Key]
public int ID { get; set; }
public string SubmittorEmail {get; set;}
public string ProjectName { get; set; }
public string BookAdvisor { get; set; }
[DataType(DataType.Date)]
public DateTime SubmittedDate {get; set;}
}
} |
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Net;
namespace AtlBot.Models.Slack
{
public class SlackClient : ISlackClient
{
private const string Host = "https://slack.com/api/";
public string Invoke(string apiMethod, NameValueCollection parameters)
{
var baseUri = new Uri(Host);
var apiUri = new Uri(baseUri, apiMethod);
// crazy happens
if (ConfigurationManager.AppSettings["SafeMode"] == "On") return "safe mode";
using (var client = new WebClient())
{
var response = client.UploadValues(apiUri, parameters);
return System.Text.Encoding.UTF8.GetString(response);
}
}
}
} |
namespace GaleService.DomainLayer.Managers.Services.Fitbit.ResourceModels
{
public class FitbitSleepResource : FitbitTrackerStatsResourceBase
{
public Summary summary { get; set; }
public class Summary
{
public string TotalMinutesAsleep { get; set; }
public string TotalSleepRecords { get; set; }
public string TotalTimeInBed { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HoraireAlpha
{
public class Profil : Ressource
{
private string prenom;
private string nom;
private string email;
private string numTelephone;
private int anciennete;
private int heuresTravaillees;
private List<Poste> poste = new List<Poste>();
public Profil(Poste poste, string prenom, string nom, string email, string numTelephone, int anciennete, int heuresTravaillees)
{
setPrenom(prenom);
setNom(nom);
setEmail(email);
setNumTelephone(numTelephone);
setAnciennete(anciennete);
setHeuresTravaillees(heuresTravaillees);
this.poste.Add(poste);
}
public void setPrenom(string prenom)
{
this.prenom = prenom;
}
public void setNom(string nom)
{
this.nom = nom;
}
public void setEmail(string email)
{
this.email = email;
}
public void setNumTelephone(string numTelephone)
{
this.numTelephone = numTelephone;
}
public void setAnciennete(int anciennete)
{
this.anciennete = anciennete;
}
public void setHeuresTravaillees(int heuresTravaillees)
{
this.heuresTravaillees = heuresTravaillees;
}
public void setPoste(Poste poste)
{
this.poste.Add(poste);
}
public String getPrenom()
{
return prenom;
}
public String getNom()
{
return nom;
}
public String getEmail()
{
return email;
}
public String getNumTelephone()
{
return numTelephone;
}
public int getAnciennete()
{
return anciennete;
}
public int getHeuresTravaillees()
{
return heuresTravaillees;
}
public Poste getPoste(int num)
{
return (poste[num]);
}
public List<Poste> getPoste()
{
return poste;
}
}
}
|
using coffeeSalesManag_CompApp.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity;
using System.Data.Entity.Validation;
namespace coffeeSalesManag_CompApp
{
public partial class manageSalesForm : Form
{
public manageSalesForm()
{
InitializeComponent();
fillDataGridView();
populatecbCoffee(cbMangSale_coffName);//populating combo box with coffee names.
fillCB_FilterBy();//fiiling combo box with property names.
EnableDisablePreviousButton();//method call to disable previous button.
EnableDisableNextButton();//method call to disable next button.
}
/********************CRUD OPERATION*******************/
//ADD operation.
private void btnMangSale_Add_Click(object sender, EventArgs e)
{
try
{
Sale saleObj = new Sale();//DECLARE OBJECT OF SALE TYPE.
//POPULATING OBJECT.
saleObj.CoffeeName = cbMangSale_coffName.Text;
saleObj.Price = Convert.ToDouble(txtMangSale_Price.Text);
saleObj.Quantity = Convert.ToInt32(txtMangSale_Quantity.Text);
saleObj.Total = Convert.ToDouble(txtMangSale_Total.Text);
saleObj.Date = DateTime.Now.Date;
saleObj.Time = DateTime.Now.TimeOfDay;
saleObj.AddBy = "Manpreet";
DbCoffeeContext _db = new DbCoffeeContext();//intialise db object.
_db.Sales.Add(saleObj);//adding sale obj to db.
_db.SaveChanges();//saving changes to db.
MessageBox.Show("Sale Added.");
emptyAllControls();//method call to emptyAllControls.
fillDataGridView();//method call to fillDataGridView.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//UPDATE OPERATION.
private void btnMangSale_Edit_Click(object sender, EventArgs e)
{
try
{
//method call to get specific object.
var originalSaleObj = returnSpecificSaleObj();
Sale saleObj = new Sale();
saleObj.ID = Convert.ToInt32(txtMangSale_saleID.Text);
saleObj.CoffeeName = cbMangSale_coffName.Text.Trim();
saleObj.Price = Convert.ToDouble(txtMangSale_Price.Text);
saleObj.Quantity = Convert.ToInt32(txtMangSale_Quantity.Text);
saleObj.Total = Convert.ToDouble(txtMangSale_Total.Text);
saleObj.Date = originalSaleObj.Date;
saleObj.Time = originalSaleObj.Time;
saleObj.AddBy = originalSaleObj.AddBy;
DbCoffeeContext _db = new DbCoffeeContext();
_db.Entry(saleObj).State = EntityState.Modified;
_db.SaveChanges();
//_db.Configuration.ValidateOnSaveEnabled = false;
MessageBox.Show("Updated.");
emptyAllControls();//method call to emptyAllControls.
fillDataGridView();//method call to fillDataGridView.
}
//catch (DbEntityValidationException err)
//{
// MessageBox.Show(err.Message);
//}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//DELETE OPERATION.
private void btnMangSale_Delete_Click(object sender, EventArgs e)
{
try
{
if (MessageBox.Show("Are you sure you want to delete this sale?", "Delete Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
DbCoffeeContext _db = new DbCoffeeContext();//create context.
Sale saleObj = new Sale();//create sale obj.
saleObj.ID = Convert.ToInt32(txtMangSale_saleID.Text);//enter id of rec.
_db.Sales.Attach(saleObj);//attach sale obj to context.
_db.Sales.Remove(saleObj);//remove specific object.
_db.SaveChanges();//saving changes.
MessageBox.Show("Record Deleted");
emptyAllControls();//method call to emptyAllControls.
fillDataGridView();//method call to fillDataGridView.
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/************************** EVENTS ****************************/
//EVENT TO STOP WRITING IN COMBO FILTERBY.
private void cbMangSale_FilterBy_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
cbMangSale_FilterBy.Text = string.Empty ;//REMOVING ALL CONTENT FROM COMBO.
MessageBox.Show("You can't write here");
}
//EVENT TO FILTER ROWS IN DATA GRID VIEW UPON SELECTED INDEX CHANGE OF ORDERBY.
private void cbMangSale_FilterBy_SelectedIndexChanged(object sender, EventArgs e)
{
DbCoffeeContext _db = new DbCoffeeContext();
if (cbMangSale_FilterBy.Text == "ID")
{
var resultObjs = _db.Sales
.OrderBy(x => x.ID).ToList();
dgvMangSale.DataSource = null;
dgvMangSale.DataSource = resultObjs;
EnableDisablePreviousButton();//method call to disable previous btn.
EnableDisableNextButton();//method call to disable next btn.
}
else if (cbMangSale_FilterBy.Text == "CoffeeName")
{
var resultObjs = _db.Sales
.OrderBy(x => x.CoffeeName).ToList();
dgvMangSale.DataSource = null;
dgvMangSale.DataSource = resultObjs;
EnableDisablePreviousButton();//method call to disable previous btn.
EnableDisableNextButton();//method call to disable next btn.
}
else if (cbMangSale_FilterBy.Text == "AddBy")
{
var resultObjs = _db.Sales
.OrderBy(x => x.AddBy).ToList();
dgvMangSale.DataSource = null;
dgvMangSale.DataSource = resultObjs;
EnableDisablePreviousButton();//method call to disable previous btn.
EnableDisableNextButton();//method call to disable next btn.
}
else if (cbMangSale_FilterBy.Text == "Date")
{
var resultObjs = _db.Sales
.OrderBy(x => x.Date).ToList();
dgvMangSale.DataSource = null;
dgvMangSale.DataSource = resultObjs;
EnableDisablePreviousButton();//method call to disable previous btn.
EnableDisableNextButton();//method call to disable next btn.
}
else if (cbMangSale_FilterBy.Text == "All")
{
fillDataGridView();//calling fill data grid view.
EnableDisablePreviousButton();//method call to disable previous btn.
EnableDisableNextButton();//method call to disable next btn.
}
}
//EVENT TO CALL SHOW COFFEE PRICE METHOD.
private void cbMangSale_coffName_SelectedIndexChanged(object sender, EventArgs e)
{
//METHOD TO SHOWCOFFPRICE.
showCoffPrice(cbMangSale_coffName.Text, txtMangSale_Price);
//METHOD CALL TO CALCULATE TOTAL.
calculateTotal(txtMangSale_Price, txtMangSale_Quantity);
}
//EVENT TO CONTROL WRITING IN COFFEE COMBO BOX.
private void cbMangSale_coffName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
cbMangSale_coffName.Text = string.Empty;//removing text from coffee name combo box.
MessageBox.Show("You can't write here.");
}
//EVENT TO CONTROL INPUT OF NEW COFFEE NAME.
private void txtMangSale_NewCofName_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!char.IsLetter(ch) && ch != (char)Keys.Back)
{
e.Handled = true;
MessageBox.Show("Please enter only letters.");
}
}
//EVENT TO CNTROL INPUT IN PRICE FEILD.
private void txtMangSale_Price_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!char.IsDigit(ch) && !(ch == (char)Keys.Back) && ch != 46)
{
e.Handled = true;
MessageBox.Show("Please enter on decimal number.");
}
}
//KEYPRESS EVENT TO MAKE SURE QUANTITY IS NUMBER.
private void txtMangSale_Quantity_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!char.IsDigit(ch) && !(ch == (char)Keys.Back))
{
e.Handled = true;
MessageBox.Show("Please enter only whole number less than 500.");
}
}
//EVENT CALLED WHEN QUANTITY VALUE CHANGES AND CAN'T BE MORE THAN 500.
private void txtMangSale_Quantity_TextChanged(object sender, EventArgs e)
{
//getting value from quantity field.
string quantityFieldValue = txtMangSale_Quantity.Text.Trim();
int quantity;//declare quantity varibale.
//check if quantity has empty string.
if (quantityFieldValue == string.Empty)
{
quantity = 1;//if true -> set quantity degfault value 1.
}
else
{
//if false -> convert to value.
quantity = Convert.ToInt32(txtMangSale_Quantity.Text.Trim());
}
//check if quantity more than 500.
if (quantity > 500)
{
MessageBox.Show("Quantity can't be more than 500.");
txtMangSale_Quantity.Text = string.Empty;
}
}
//EVENT CALLED WHEN QUANTITY FIELD LEFT.
private void txtMangSale_Quantity_Leave(object sender, EventArgs e)
{
//Method call to calculate total from peice and quantity.
calculateTotal(txtMangSale_Price, txtMangSale_Quantity);
}
//EVENT TO GET NEXT FIVE RECORDS.
private void btnMangSale_Next_Click(object sender, EventArgs e)
{
int lastRowIndex = dgvMangSale.Rows.Count - 1;
//MessageBox.Show(lastRowIndex.ToString());
int lastRecId = (int)dgvMangSale.Rows[lastRowIndex].Cells[0].Value;
DbCoffeeContext _db = new DbCoffeeContext();
//fetching next five objects from data base.
var fiveNextObjs = _db.Sales
.Where(x => x.ID > lastRecId).Take(5).ToList();
dgvMangSale.DataSource = null;//clear the data grid view.
dgvMangSale.DataSource = fiveNextObjs;//setting objects in datagrid view.
EnableDisablePreviousButton();//method call to disable previous btn.
EnableDisableNextButton();//method call to disable next btn.
}
//EVENT TO GET FIVE PREVIOUS RECORDS.
private void btnMangSale_Prev_Click(object sender, EventArgs e)
{
int firstRowIndex = dgvMangSale.Rows[0].Index;//fetch first row from dgv.
//fetch id value for first record.
int firstRecId = (int)dgvMangSale.Rows[firstRowIndex].Cells[0].Value;
DbCoffeeContext _db = new DbCoffeeContext();
//fetching previous five objects from data base.
var fivePrevObjs = _db.Sales
.Where(x => x.ID < firstRecId).Take(5).ToList();
dgvMangSale.DataSource = null;//clear the data grid view.
dgvMangSale.DataSource = fivePrevObjs;//setting objects in datagrid view.
EnableDisablePreviousButton();//method call to disable previous btn.
EnableDisableNextButton();//method call to disable next btn.
}
//EVENT TO GET CURRENT ROW DATA.
private void dgvMangSale_CellClick(object sender, DataGridViewCellEventArgs e)
{
var saleObj = returnSpecificSaleObj();
txtMangSale_saleID.Text = saleObj.ID.ToString();
cbMangSale_coffName.Text = saleObj.CoffeeName;
cbMangSale_coffName.Text = saleObj.CoffeeName;
txtMangSale_Price.Text = saleObj.Price.ToString();
txtMangSale_Quantity.Text = saleObj.Quantity.ToString();
txtMangSale_Total.Text = saleObj.Total.ToString();
}
/*************************** METHODS ********************************/
//method to populate Combo Box for coffe name.
void populatecbCoffee(ComboBox cbName)
{
DbCoffeeContext _db = new DbCoffeeContext();
var coffList = _db.Coffee.ToList();//getting all record from db.
cbMangSale_coffName.Items.Clear();//clearing the cheeck box first.
//foreach for all objects.
foreach (var item in coffList)
{
//adding coffee names to check box.
cbName.Items.Add(item.CoffeeName);
}
}
//METHOD TO SHOW COFFEE PRICE USING COFFEE NAME.
void showCoffPrice(string coffeeName, TextBox txtBoxName)
{
try
{
DbCoffeeContext _db = new DbCoffeeContext();
//getting coffee obj for specific coffee name.
var resultObj = _db.Coffee
.Where(x => x.CoffeeName == coffeeName).FirstOrDefault();
//setting coffee price.
txtMangSale_Price.Text = resultObj.CoffePrice;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//METHOD TO CALCULATE TOTAL.
void calculateTotal(TextBox priceBox, TextBox quantityBox)
{
try
{
//CHECK IF BOTH PRICE AND QUANTITY ARE NOT EMPTY.
if (priceBox.Text != string.Empty && quantityBox.Text != string.Empty)
{
int quantity;//declare quantity variable.
double price = Convert.ToDouble(priceBox.Text);//convert price to double.
//if condition to check quantity is empty or not.
if (quantityBox.Text == string.Empty)
{
quantity = 1;//set to 1 if empty.
}
else
{
quantity = Convert.ToInt32(quantityBox.Text);//convert quantity to int.
}
double total = (price * quantity);//cal total.
txtMangSale_Total.Text = total.ToString();//seting total to TOTAL feild.
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//METHOD TO FILL COMBO BOX FILTERBY.
void fillCB_FilterBy()
{
Sale saleObj = new Sale();//creating object of sale.
//setting property names in combo box.
cbMangSale_FilterBy.Items.Add("All");
cbMangSale_FilterBy.Items.Add(nameof(saleObj.ID));
cbMangSale_FilterBy.Items.Add(nameof(saleObj.CoffeeName));
cbMangSale_FilterBy.Items.Add(nameof(saleObj.Date));
cbMangSale_FilterBy.Items.Add(nameof(saleObj.AddBy));
}
//Method to fill data grid view.
void fillDataGridView()
{
try
{
DbCoffeeContext _db = new DbCoffeeContext();
dgvMangSale.DataSource = _db.Sales.Take(5).ToList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//METHOD TO DISABLE PREVIOUS BUTTON IF NO RECORDS ARE THERE ON LEFT SIDE.
void EnableDisablePreviousButton()
{
int firstRowIndex = dgvMangSale.Rows[0].Index;
int firstRecId = (int)dgvMangSale.Rows[firstRowIndex].Cells[0].Value;
DbCoffeeContext _db = new DbCoffeeContext();
var resultObjs = _db.Sales
.Where(x => x.ID < firstRecId).ToList();
if (resultObjs.Count == 0)
{
btnMangSale_Prev.Enabled = false;
}
else
{
btnMangSale_Prev.Enabled = true;
}
}
//METHOD TO DISABLE NEXT BUTTON IF NO RECORDS ARE THERE ON RIGHT.
void EnableDisableNextButton()
{
int lastRowIndex = dgvMangSale.Rows.Count - 1;
int lastRecId = (int)dgvMangSale.Rows[lastRowIndex].Cells[0].Value;
DbCoffeeContext _db = new DbCoffeeContext();
var resultObj = _db.Sales
.Where(x => x.ID > lastRecId).ToList();
if (resultObj.Count == 0)
{
btnMangSale_Next.Enabled = false;
}
else
{
btnMangSale_Next.Enabled = true;
}
}
//METHOD TO EMPTY ALL CONTROLS.
void emptyAllControls()
{
txtMangSale_saleID.Text = string.Empty;
cbMangSale_coffName.Text = string.Empty;
cbMangSale_coffName.Text = string.Empty;
txtMangSale_Price.Text = string.Empty;
txtMangSale_Quantity.Text = string.Empty;
txtMangSale_Total.Text = string.Empty;
}
//RETURN SPECIFIC SALE OBJECT.
Sale returnSpecificSaleObj()
{
DataGridViewRow row = dgvMangSale.CurrentRow;
int recId = (int)row.Cells[0].Value;
//MessageBox.Show(recId.ToString());
DbCoffeeContext _db = new DbCoffeeContext();
var saleObj = _db.Sales
.Where(x => x.ID == recId).FirstOrDefault();
return saleObj;
}
}
}
|
using System;
using System.Collections.Generic;
namespace taks11_Polynomial
{
class Program
{
static void Main(string[] args)
{
//Write a method that adds two polynomials. Represent them as arrays of their coefficients as in the example below:
//x2 + 5 = 1x2 + 0x + 5 -> |5|0|1|
decimal[] poly1 = { -1, 1, 1 };
decimal[] poly2 = { 6, 3, 2 };
decimal[] poly3 = { -3, -2 };
decimal[] poly4 = { -6, 3, 2, -5 };
PrintPoly(Sum(poly1, poly2));
PrintPoly(Multiplying(poly1, poly3));
PrintPoly(Substract(poly1, poly2));
}
static decimal[] Substract(decimal[] poly1, decimal[] poly2)
{
for (int i = 0; i < poly2.Length; i++)
{
poly2[i] *= -1;
}
return Sum(poly1, poly2);
}
static decimal[] Multiplying(decimal[] poly1, decimal[] poly2)
{
decimal[] result = new decimal[poly1.Length * poly2.Length];
for (int i = 0; i < poly1.Length; i++)
{
for (int j = 0; j < poly2.Length; j++)
{
result[i + j] += poly1[i] * poly2[j];
}
}
return result;
}
static decimal[] Sum(decimal[] poly1, decimal[] poly2)
{
List<decimal> result = new List<decimal>();
int size = poly1.Length > poly2.Length ? poly1.Length : poly2.Length;
for (int i = 0; i < size; i++)
{
if (LegitIndex(poly1, i) && LegitIndex(poly2, i))
{
result.Add(poly1[i] + poly2[i]);
}
else
{
if (LegitIndex(poly1, i))
{
result.Add(poly1[i]);
}
else
{
result.Add(poly2[i]);
}
}
}
return result.ToArray();
}
static bool LegitIndex(decimal[] arr, int i)
{
if (i < 0 || i > arr.Length - 1)
{
return false;
}
return true;
}
static void PrintPoly(decimal[] poly)
{
for (int i = poly.Length - 1; i >= 0; i--)
{
if (poly[i] != 0 && i != 0)
{
if (i == 1)
{
if (poly[i - 1] >= 0)
{
Console.Write("{0}x +", poly[i]);
}
else
{
Console.Write("{0}x ", poly[i]);
}
}
else
{
if (poly[i - 1] >= 0)
{
Console.Write("{1}x^{0} +", i, poly[i]);
}
else
{
Console.Write("{1}x^{0} ", i, poly[i]);
}
}
}
else
{
if (i == 0)
{
Console.Write("{0}", poly[i]);
}
}
}
Console.WriteLine();
}
}
}
|
namespace Kit.Enums
{
public enum SqlServerVersion
{
None = 0, V2005 = 9, V2008 = 10, V2012 = 11, V2014 = 12, V2016 = 13, V2017 = 14, V2019 = 15
}
} |
using ServiceHost.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ServiceHost.Repository
{
public interface ITransactionRepository : IRepository<Transaction>
{
Task<IEnumerable<Transaction>> GetTransactionsAsync(Account account, DateTime fromDate, DateTime toDate);
Task<IEnumerable<Transaction>> GetTransactionsAsync(ApplicationUser owner, DateTime fromDate, DateTime toDate);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program0
{
public class Address
{
//Backing fields
private string _name; //Holds the name for the package destination
private string _addressOne; //Address line 1
private string _addressTwo; //Address line 2
private string _city; //Holds the city
private string _state; //Holds the state
private int _zipCode; //This will hold the destination zip code
//Validation fields for zip code
private const int MIN_ZIP = 00000; //Min zip code
private const int MAX_ZIP = 99999; //Max zip code
//Precondition: none
//Postcondition: The Address will be set with Address2 as a empty string
public Address(string name, string addressOne, string city, string state, int zipCode)
: this(name, addressOne, "", city, state, zipCode)
{ }
//Precondition: None
//Postcondition: Address will be set
public Address(string name, string addressOne, string addressTwo, string city, string state, int zipCode)
{
Name = name;
Address1 = addressOne;
Address2 = addressTwo;
City = city;
State = state;
Zip = zipCode;
}
public string Name
{
//Precondition: None
//Postcondition: Name will be returned
get { return _name; }
//Precondition: Name must not be empty
//Postcondition: Name set to specified value
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Valid name must be given.", "name");
else
_name = value;
}
}
public string Address1
{
//Precondition: None
//Postcondition: Address 1 will be returned
get { return _addressOne; }
//Precondition: Address 1 should not be empty
//Postcondition: Address 1 set to specified value
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Address should not be empty.", "address");
else
_addressOne = value;
}
}
public string Address2
{
//Precondition: None
//Postcondition: Address 2 will be returned
get { return _addressTwo; }
//Precondition: Address 2 is optional. Can either be filled in or not.
//Postcondition: Address 2 set to specified value
set
{
_addressTwo = value;
}
}
public string City
{
//Precondition: None
//Postcondition: City will be returned
get { return _city; }
//Precondition: City should not be empty
//Postcondition: City set to specified value
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("City should not be empty.", "city");
else
_city = value;
}
}
public string State
{
//Precondition: None
//Postcondition: City will be returned
get { return _state; }
//Precondition: City should not be empty
//Postcondition: City set to specified value
set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("State should not be empty.", "state");
else
_state = value;
}
}
public int Zip
{
//Precondition: None
//Postcondition: Zipcode will be returned
get { return _zipCode; }
//Precondition: MIN_ZIP <= value <= MAX_ZIP
//Postcondition: Zipcode will be set to value
set
{
if ((value < MIN_ZIP) || (value > MAX_ZIP))
throw new ArgumentOutOfRangeException("zipcode", "Please enter a valid Zip Code.");
else
_zipCode = value;
}
}
//Precondition: None
//Postcondition: Returns the formatted string of all the values entered.
// Address2 will be empty if nothing is entered.
public override string ToString() =>
$"{Name}" + Environment.NewLine +
$"{Address1}" + Environment.NewLine +
$"{(string.IsNullOrWhiteSpace(Address2) ? null : (Address2 + Environment.NewLine))}" +
$"{City}, {State} {Zip:D5}" + Environment.NewLine; //Output for ToString() : Address
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using SimpleJSON;
using System.Text;
using System.Linq;
using UnityEngine.UI;
public class HttpRequest : MonoBehaviour {
public const string EQUALS = "=";
public const string AND = "&";
public const string HEADER_AUTHORIZATION = "Authorization";
public const string HEADER_CONTENT_TYPE = "Content-Type";
public const string HEADER_CONTENT_TYPE_MULTIPART_FORM_DATA = "multipart/form-data; ";
public const string HEADER_BOUDARY = "boundary=";
public const string BODY_BOUNDARY = "------------------------aa2af2f6902e7855";
public const string BODY_TWO_HYPHENS = "--";
public const string BODY_CR_LF = "\r\n";
public const string BODY_DOUBLE_QUOTES = "\"";
public const string BODY_CONTENT_TYPE = "Content-Type: ";
public const string BODY_CONTENT_DISPOSITION = "Content-Disposition: ";
public const string BODY_FORM_DATA = "form-data; ";
public const string BODY_NAME = "name=";
public const string BODY_FILE_NAME = "filename=";
public const string BODY_SEMICOLON_SPACE = "; ";
public const string BODY_CONTENT_TYPE_IMAGE_JPEG = "image/jpeg";
public const string BODY_CONTENT_TYPE_TEXT_PLAIN = "text/plain";
public const string BODY_CONTENT_PLACEHOLDER = "aoidfngoiefoi12097445";
private byte[] imageByte;
private bool analyzing;
private bool analysisSucceeded;
private bool showDeepAnalysis;
private string foundObject;
public HttpRequest(){
}
public void initialize(byte[] imageByte){
this.imageByte = imageByte;
analyzing = true;
analysisSucceeded = false;
showDeepAnalysis = true;
foundObject = "";
}
public byte[] getImageByte (){
return imageByte;
}
public bool isAnalyzing(){
return analyzing;
}
public bool hasAnalysisSucceeded(){
return analysisSucceeded;
}
public bool shouldShowDeepAnalysis(){
return showDeepAnalysis;
}
public string getFoundObject(){
return foundObject;
}
public void setAnalyzing(bool analyzing){
this.analyzing = analyzing;
}
public void setAnalysisSucceeded(bool analysisSucceeded){
this.analysisSucceeded = analysisSucceeded;
}
public void setShowDeepAnalysis(bool showDeepAnalysis){
this.showDeepAnalysis = showDeepAnalysis;
}
public void setFoundObj(string foundObject){
this.foundObject = foundObject;
}
public virtual IEnumerator analyze(){
Debug.Log ("HttpRequest: Analyze");
yield return 0;
}
public virtual IEnumerator postAnalyze(){
Debug.Log ("HttpRequest: PostAnalyze");
yield return 0;
}
public void makeRequest(byte[] imageData){
StartCoroutine (BarGraph.getInstance ().start ());
Webcam.getInstance ().stopCamera ();
SwitchPanels.changePanelStatic ("pCameraAnalyzing:activate");
}
private void getDeepAnalysisMessageReady (){
GameObject messageTitle = StartGame.findInactive ("tDeepAnalysisMessageTitle", "pCamera")[0];
GameObject messageContent= StartGame.findInactive ("tDeepAnalysisMessageContent", "pCamera")[0];
if (foundObject == "") {
messageTitle.GetComponent<Text>().text = "Deep Analysis"+'\u2122'+" Failed!";
messageContent.GetComponent<Text>().text = "Please try analyzing another picture.";
} else {
messageTitle.GetComponent<Text>().text = "Deep Analysis"+'\u2122'+" Succeeded!";
messageContent.GetComponent<Text>().text = "Your Deep Analysis"+'\u2122'+" request has succeeded.";
}
}
/*
* Build the html post body for a post without any image data.
*/
public byte[] htmlPostBody(Dictionary<string, string> paramaters)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < paramaters.Count; i++)
{
var element = paramaters.ElementAt(i);
sb.Append(element.Key);
sb.Append(EQUALS);
sb.Append(element.Value);
if(i < paramaters.Count - 1)
{
sb.Append(AND);
}
}
return stringToBytes(sb.ToString());
}
/*
* Build a html post body for a post with text data (0..n) and image data (0..n)
*/
public byte[] htmlPostBody(HttpConfiguration[] configurations)
{
if(configurations.Length == 0)
{
return null;
}
StringBuilder sb = new StringBuilder();
// combine all UTF-8 encoded data
int contentSize = 0;
int[] placeHolderIndexes = new int[configurations.Length];
for(int i = 0; i < configurations.Length; i++)
{
HttpConfiguration config = configurations[i];
// boundary
sb.Append(BODY_TWO_HYPHENS);
sb.Append(BODY_BOUNDARY);
sb.Append(BODY_CR_LF);
// content disposition
sb.Append(BODY_CONTENT_DISPOSITION);
sb.Append(BODY_FORM_DATA);
// name
sb.Append(BODY_NAME);
sb.Append(BODY_DOUBLE_QUOTES);
sb.Append(config.getName());
sb.Append(BODY_DOUBLE_QUOTES);
sb.Append(BODY_SEMICOLON_SPACE);
// optional file name
if (config.hasFileName())
{
sb.Append(BODY_FILE_NAME);
sb.Append(BODY_DOUBLE_QUOTES);
sb.Append(config.getFileName());
sb.Append(BODY_DOUBLE_QUOTES);
}
sb.Append(BODY_CR_LF);
// content type
sb.Append(BODY_CONTENT_TYPE);
sb.Append(config.getContentType());
sb.Append(BODY_CR_LF);
sb.Append(BODY_CR_LF);
// content placeholder
placeHolderIndexes[i] = sb.ToString().Length;
sb.Append(BODY_CONTENT_PLACEHOLDER);
sb.Append(BODY_CR_LF);
contentSize += config.getContent().Length;
// end entire body
if(i == configurations.Length - 1)
{
sb.Append(BODY_TWO_HYPHENS);
sb.Append(BODY_BOUNDARY);
sb.Append(BODY_TWO_HYPHENS);
sb.Append(BODY_CR_LF);
}
}
Debug.Log("Part body: \r\n" + sb.ToString());
byte[] bodyPart = stringToBytes(sb.ToString());
int neededSize = bodyPart.Length - (BODY_CONTENT_PLACEHOLDER.Length * configurations.Length) + contentSize;
byte[] wholeBody = new byte[neededSize];
// insert content byte[] data
int currentIndexSrc = 0;
int currentIndexDest = 0;
for(int i = 0; i < configurations.Length; i++)
{
byte[] content = configurations[i].getContent();
// before placeholder
System.Buffer.BlockCopy(bodyPart, currentIndexSrc, wholeBody, currentIndexDest, placeHolderIndexes[i] - currentIndexSrc);
currentIndexDest += placeHolderIndexes[i] - currentIndexSrc;
currentIndexSrc = placeHolderIndexes[i] + BODY_CONTENT_PLACEHOLDER.Length;
// insert content instead of placeholder
System.Buffer.BlockCopy(content, 0, wholeBody, currentIndexDest, content.Length);
currentIndexDest += content.Length;
// insert rest of data if its the last configuration
if (i == configurations.Length - 1)
{
System.Buffer.BlockCopy(bodyPart, currentIndexSrc, wholeBody, currentIndexDest, bodyPart.Length - currentIndexSrc);
}
}
Debug.Log("Whole body: \r\n" + System.Text.Encoding.UTF8.GetString(wholeBody));
return wholeBody;
}
public byte[] stringToBytes(string str)
{
return System.Text.Encoding.UTF8.GetBytes(str);
}
public void checkIfFoundObjects(string[] responses, byte[] imageByte){
List<Text>[] currentObjects = ObjectList.getInstance ().getCurrentObjects ();
AcceptedTags[] acceptedTags = ObjectList.getInstance ().getAcceptedTags ();
bool foundCurrentObjects = false;
for (int i = 0; i < currentObjects.Length; i++) {
string currentObj = currentObjects [i][0].text;
for (int j = 0; j < acceptedTags.Length; j++) {
string acceptedTag = acceptedTags [j].getAcceptedTag();
string[] similarTags = acceptedTags [j].getSimilarTags ();
if (acceptedTag.CompareTo (currentObj) == 0) {
for(int k = 0; k < similarTags.Length; k++){
string similarTag = similarTags [k];
for (int l = 0; l < responses.Length; l++) {
string tagAnalyzed = responses[l];
if (tagAnalyzed.CompareTo (similarTag) == 0) {
foundCurrentObjects = true;
foundObject = currentObj;
l = responses.Length;
k = similarTags.Length;
j = acceptedTags.Length;
i = currentObjects.Length;
}
}
}
}
}
}
if (foundCurrentObjects) {
setAnalysisSucceeded (true);
saveJPG (imageByte);
} else {
analysisSucceeded = false;
}
}
private void switchToCorrectPanel(){
ObjectList.getInstance ().pickCurrentObjects ();
GameObject pCamera = GameObject.Find ("pCamera");
Webcam.getInstance ().resetCameraZoom ();
Webcam.getInstance ().stopCamera ();
pCamera.SetActive (false);
if (PlayerData.getInstance ().getCurrentNarrativeChunk () == 9) {
AugmentedRealityGyro.getInstance ().reInitializeForNarrativeChunk ();
GameObject pAugmentedReality = pCamera.transform.parent.FindChild ("pAugmentedReality").gameObject;
pAugmentedReality.SetActive (true);
AugmentedReality.getInstance ().setNewImage ();
GameObject obj = StartGame.findInactive ("bCamera", "vMenu")[0];
obj.GetComponent<Button> ().interactable = false;
}
else if (PlayerData.getInstance ().getCurrentNarrativeChunk () == 3 ||
PlayerData.getInstance ().getCurrentNarrativeChunk () > 4) {
AugmentedRealityGyro.getInstance ().reInitializeForNarrativeChunk ();
GameObject pAugmentedReality = pCamera.transform.parent.FindChild ("pAugmentedReality").gameObject;
pAugmentedReality.SetActive (true);
AugmentedReality.getInstance ().setNewImage ();
} else if (PlayerData.getInstance ().getCurrentNarrativeChunk () == 4) {
Rewards.PrepareRewards ();
SwitchPanels.changePanelStatic ("pUpdate:activate");
UpdatePanel.startUpdate ();
} else {
GameObject pRewards = pCamera.transform.parent.FindChild ("pRewardsCongrats").gameObject;
pRewards.SetActive (true);
GameObject confetti = StartGame.findInactive ("confetti", "vMenu") [0];
Animation anim = confetti.GetComponent<Animation> ();
anim.Play ();
Rewards.PrepareRewards ();
}
}
public void saveJPG(byte[] imageByte){
Debug.Log (Application.persistentDataPath);
System.IO.File.WriteAllBytes (Application.persistentDataPath +
"/image" + PlayerData.getInstance ().getCurrentNarrativeChunk () + ".jpg", imageByte);
}
public void checkWWWForError(WWW www)
{
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.text);
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
} |
namespace Application.DTOs.Product.Requests
{
public partial class CreateProductRequest
{
public string Name { get; set; }
public string Barcode { get; set; }
public string Description { get; set; }
public decimal Rate { get; set; }
}
}
|
using System.Collections.Generic;
namespace NoScope360Engine.Core.Entites.Creatures
{
/// <summary>
/// Group of creatures having the same aim
/// (status): attacking, patrolling,
/// expansing and etc.
/// </summary>
public class Squad
{
/// <summary>
/// List of creatures of this <see cref="Squad"/>
/// </summary>
public List<Creature> Creatures { get; set; }
/// <summary>
/// Aim of this <see cref="Squad"/> for now
/// </summary>
public Status Status { get; set; }
public Squad()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace homeworkCSharp2020
{
class nal9_01
{
public static void func(int treeSize)
{
//KROSNJA
for (int i = 0; i <= treeSize; i++)
{
Console.WriteLine("");
//PRESLEDKI
for (int p = treeSize; p >= i; p--)
{
Console.Write(" ");
}
//ZVEZDICE
for (int j = 0; j <= i; j++)
{
Console.Write("*");
}
//ZVEZDICE DESNA STRAN
for (int ds = 0; ds < i; ds++)
{
Console.Write("*");
}
}
Console.WriteLine("");
//DEBLO
string empty = " ";
string offset = "";
for (int offSize = 0; offSize < treeSize ; offSize++)
{
offset += empty;
}
Console.Write(offset); Console.WriteLine("***");
Console.Write(offset); Console.WriteLine("***");
}
}
}
|
using RoR2;
namespace TridevLoader.Mod.API.Character {
/// <summary>
/// Represents the Character level stats, used in place of direct CharacterBody references.
/// </summary>
public class CharacterLevelStats {
public CharacterLevelStats(CharacterBody characterBody) {
LevelMaxHealth = characterBody.levelMaxHealth;
LevelRegen = characterBody.levelRegen;
LevelMaxShield = characterBody.levelMaxShield;
LevelMoveSpeed = characterBody.levelMoveSpeed;
LevelJumpPower = characterBody.levelJumpPower;
LevelDamage = characterBody.levelDamage;
LevelAttackSpeed = characterBody.levelAttackSpeed;
LevelCrit = characterBody.levelCrit;
LevelArmor = characterBody.levelArmor;
}
public float LevelMaxHealth { get; set; }
public float LevelRegen { get; set; }
public float LevelMaxShield { get; set; }
public float LevelMoveSpeed { get; set; }
public float LevelJumpPower { get; set; }
public float LevelDamage { get; set; }
public float LevelAttackSpeed { get; set; }
public float LevelCrit { get; set; }
public float LevelArmor { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Xspace
{
class Bonus_BaseWeapon : Bonus
{
public Bonus_BaseWeapon(Texture2D texture, Vector2 position)
: base(texture, 0.30f, position, Vector2.Normalize(new Vector2(1, 0)), "baseWeapon", 1, -1, 500)
{ }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;
namespace Adjuvant.CodedUI.Test.Automation.Login
{
public class Login
{
public Login()
{
}
public void LoginUser(string user,string pass, BrowserWindow bw)
{
HtmlEdit txtUsername = new HtmlEdit(bw);
HtmlEdit txtPassword = new HtmlEdit(bw);
HtmlButton btnLogin = new HtmlButton(bw);
txtUsername.SearchProperties.Add(HtmlEdit.PropertyNames.Id, "username");
txtPassword.SearchProperties.Add(HtmlEdit.PropertyNames.Id, "password");
btnLogin.SearchProperties.Add(HtmlButton.PropertyNames.Id, "btn_login");
Keyboard.SendKeys(txtUsername, user);
Keyboard.SendKeys(txtPassword, pass);
Mouse.Click(btnLogin);
}
}
}
|
using System;
using strange.extensions.command.impl;
using syscrawl.Game.Models.Levels;
using syscrawl.Common.Extensions;
using syscrawl.Game.Views.Nodes;
using UnityEngine;
namespace syscrawl.Game.Controllers.Levels
{
public class CreateNodeConnectionCommand : Command
{
[Inject]
public CreateNodeConnection NodeConnection { get; set; }
public override void Execute()
{
var container = NodeConnection.Container;
var connection =
container.CreateSubcomponent<NodeConnectionView>(
"Connection", Vector3.zero
);
connection.Init(NodeConnection.From, NodeConnection.To);
}
}
}
|
//
// - PropertyTreeValueTests.cs -
//
// Copyright 2013 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.PropertyTrees;
using Carbonfrost.Commons.Spec;
namespace Carbonfrost.UnitTests.PropertyTrees {
public class PropertyTreeValueTests : TestBase {
[Fact]
public void test_get_string_value_nominal() {
PropertyTree p = new PropertyTree("t");
p.AppendProperty("a", "text");
Assert.Equal("text", p.GetString("a"));
}
[Fact]
public void test_get_boolean_value_implicit_conversion() {
PropertyTree p = new PropertyTree("t");
p.AppendProperty("a", "true");
Assert.True(p.GetBoolean("a"));
}
[Fact]
public void test_set_value_nominal() {
PropertyTree p = new PropertyTree("t");
p.SetValue("a", "420");
Assert.Equal(420, p.GetInt16("a"));
}
}
}
|
using System;
namespace OverloadTestApp
{
class Calculator
{
static void Main(string[] args)
{
Console.WriteLine("계산기!");
int x = Calculator.Plus(3, 4);
Console.WriteLine($"3 + 4 = {x}");
float y = Calculator.Plus(3.14f, 5.6f);
Console.WriteLine($"3.14f + 5.6f = {y}");
int z = Calculator.Plus(3, 4, 5);
Console.WriteLine($"3 + 4 + 5 = {z}");
int w = Calculator.Plus(3, 4, 5, 6, 7, 8, 9);
Console.WriteLine($"{w}");
}
// params
private static int Plus(params int []v)
{
int result = 0;
for (int i = 0; i < v.Length; i++)
result += v[i];
return result;
}
// 메소드 오버로딩
private static int Plus(int v1, int v2)
{
// throw new NotImplementedException();
return (v1 + v2);
}
private static float Plus(float v1, float v2)
{
// throw new NotImplementedException();
return (v1 + v2);
}
private static int Plus(int v1, int v2, int v3)
{
// throw new NotImplementedException();
return (v1 + v2 + v3);
}
}
}
|
using UnityEngine;
using System.Collections;
public class HabilityShrink : Hability {
[SerializeField]
float shrinkedDivider;
[SerializeField]
float shrinkDuration;
Vector3 previousScale;
void Awake()
{
cooldown = 5f;
shrinkDuration = 2f;
shrinkedDivider = 2f;
habilityName = "Shrink";
habilityTarget = PhotonTargets.All;
}
public override void ExecuteHability()
{
StartCoroutine(HabilityCoroutine());
}
IEnumerator HabilityCoroutine()
{
previousScale = transform.localScale;
transform.localScale = transform.localScale / shrinkedDivider;
yield return new WaitForSeconds(shrinkDuration);
transform.localScale = previousScale;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace BlogBack.Models
{
public class Comentario
{
[Key]
public int Id { get; set; }
[Required]
public string Texto { get; set; }
public DateTime Data { get; set; }
[Required]
public string Comentarista { get; set; }
[ForeignKey("Postagem")]
public int PostagemId { get; set; }
[JsonIgnore]
public Postagem Postagem { get; set; }
}
}
|
using System;
using System.IO;
using Exortech.NetReflector;
using ThoughtWorks.CruiseControl.Core;
using ThoughtWorks.CruiseControl.Core.State;
using ThoughtWorks.CruiseControl.Core.Util;
using ThoughtWorks.CruiseControl.Remote;
namespace AnalysisUK.BuildMachine.CCNetExtensions.State
{
[ReflectorType("webServiceState")]
public class WebServiceState : IStateManager
{
public WebServiceState()
{
}
////public WebServiceStateManager(IFileSystem fileSystem)
////{
////}
public IIntegrationResult LoadState(string project)
{
throw new NotImplementedException("");
}
public void SaveState(IIntegrationResult result)
{
throw new NotImplementedException("");
}
public bool HasPreviousState(string project)
{
throw new NotImplementedException("");
}
}
}
|
// PROJECT : PluginRetriever
// This project was developed by Marius Solend at Acando, Oslo, Norway
// GitHub: https://github.com/mariusso/XrmToolboxPlugins
using System.ComponentModel.Composition;
using XrmToolBox.Extensibility;
using XrmToolBox.Extensibility.Interfaces;
namespace Acando.Crm.XrmToolbox.Plugins.PluginRetriever
{
[Export(typeof(IXrmToolBoxPlugin)),
ExportMetadata("Name", "Plugin Retriever"),
ExportMetadata("Description", "Retrieves and lists all plugin steps defined in an organization"),
ExportMetadata("SmallImageBase64", null),
ExportMetadata("BigImageBase64", null),
ExportMetadata("BackgroundColor", "MediumBlue"),
ExportMetadata("PrimaryFontColor", "White"),
ExportMetadata("SecondaryFontColor", "LightGray")]
public class Retriever : PluginBase
{
public override IXrmToolBoxPluginControl GetControl()
{
return new RetrieverControl();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Usable Item", menuName = "Custom/Items/Usable Item", order=2)]
public class UsableItem : BasicItem {
public bool IsConsumable = false;
public List<UsableItemEffect> effects;
public virtual void Use(Player player)
{
for(int i = 0; i < effects.Count; i++)
{
effects[i].ApplyEffect(this, player);
}
}
}
|
using MCC.Utility.Binding;
using System;
using System.Reactive.Disposables;
namespace MultiCommentCollector.ViewModels
{
/// <summary>
/// ReactivePropertyを利用した、ViewModelBase
/// </summary>
internal class ViewModelBase : BindableBase, IDisposable
{
protected readonly CompositeDisposable Disposable = new();
public void Dispose()
{
Disposable.Clear();
Disposable.Dispose();
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Im.Access.GraphPortal.Repositories;
namespace Im.Access.GraphPortal.Data
{
public interface IUserStore
{
Task<PaginationResult<DbUser>> GetUsersAsync(
UserSearchCriteria criteria,
CancellationToken cancellationToken);
Task<DbUser> GetUserAsync(
string userId, CancellationToken cancellationToken);
}
} |
using System;
using NUnit.Framework;
using IOM.Internals.Readers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Tests.MetadataReaderTests
{
[TestFixture]
public class MetadataReaderTests{
//Sanity check to ensure tests are building properly.
[TestCase]
public void UnfailableTests(){
Console.WriteLine($"Running UnfailableTests");
Assert.IsTrue(true);
}
/*
So let's describe what this reader should do.
It should
[ ] Take an object, or already serialized version of an object
[ ] Understand how to read those specific formats
*/
[TestCase]
public void ObjectConstructor(){
//We should be able to generate a reader from a simple object.
//The object here should be simple enough; make sure what we serialize, we can deserialize.
MetadataReader<DateTime> reader = new MetadataReader<DateTime>(DateTime.Now);
DateTime d = JsonConvert.DeserializeObject<DateTime>(reader._InternalSerializedObject);
Assert.IsNotNull(d);
}
[TestCase]
public void StaticObjectConstructor(){
//We should also be able to generate a reader from a previously serialized object
MetadataReader<DateTime> readerFromSerializedObject = MetadataReader<DateTime>.From(JsonConvert.SerializeObject(DateTime.Now));
//Honestly, I think it's good enough to simply check that these three things are the same.
//This would be after round trip serialization.
Assert.IsTrue(readerFromSerializedObject._InternalDeserializedObject.Day == DateTime.Now.Day);
Assert.IsTrue(readerFromSerializedObject._InternalDeserializedObject.Month == DateTime.Now.Month);
Assert.IsTrue(readerFromSerializedObject._InternalDeserializedObject.Year == DateTime.Now.Year);
}
[TestCase]
public void TestSimpleRelationship(){
MetadataReader<DateTime> readerFromSerializedObject = MetadataReader<DateTime>.From(JsonConvert.SerializeObject(DateTime.Now));
MetadataReader<JObject>.GetRelationships(readerFromSerializedObject._InternalSerializedObject);
//Assert Fail for now, because this isn't even a real test.
Assert.Fail();
}
}
} |
using Nancy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nancy.TinyIoc;
using Nancy.Bootstrapper;
using Nancy.Conventions;
using Appy.Core.Nancy;
namespace Splash.Config
{
public class SplashBootstrapper : AppyBootstrapper
{
}
}
|
using Webcorp.unite;
namespace Webcorp.Model{
public class MaterialInitializer : IEntityProviderInitializable<Material, string>{
public void InitializeProvider(EntityProvider<Material, string> entityProvider)
{
entityProvider.Register(new Material(){Code="1.0035",Group=MaterialGroup.P,Density=7800*Density.KilogramPerCubicMetre, Symbol="S185",Correspondance=new string[]{"S185","A33"} });
entityProvider.Register(new Material(){Code="1.0036",Group=MaterialGroup.P,Density=7800*Density.KilogramPerCubicMetre, Symbol="S235JRG1" });
entityProvider.Register(new Material(){Code="1.0037",Group=MaterialGroup.P,Density=7800*Density.KilogramPerCubicMetre, Symbol="S235JR",Correspondance=new string[]{"S235JR","E24-2"} });
entityProvider.Register(new Material(){Code="1.0038",Group=MaterialGroup.P,Density=7800*Density.KilogramPerCubicMetre, Symbol="S235JRG2" });
entityProvider.Register(new Material(){Code="1.0044",Group=MaterialGroup.P,Density=7800*Density.KilogramPerCubicMetre, Symbol="S275JR" });
}
}
}
|
namespace Newtonsoft.Json.Linq
{
using Newtonsoft.Json;
using ns20;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
public class JProperty : JContainer
{
private readonly List<JToken> list_0;
private readonly string string_0;
public JProperty(JProperty other) : base(other)
{
this.list_0 = new List<JToken>();
this.string_0 = other.Name;
}
internal JProperty(string name)
{
this.list_0 = new List<JToken>();
Class203.smethod_2(name, "name");
this.string_0 = name;
}
public JProperty(string name, params object[] content) : this(name, content)
{
}
public JProperty(string name, object content)
{
this.list_0 = new List<JToken>();
Class203.smethod_2(name, "name");
this.string_0 = name;
this.Value = base.method_4(content) ? new JArray(content) : base.method_9(content);
}
public static JProperty Load(JsonReader reader)
{
if ((reader.JsonToken_0 == JsonToken.None) && !reader.Read())
{
throw JsonReaderException.smethod_1(reader, "Error reading JProperty from JsonReader.");
}
while (reader.JsonToken_0 == JsonToken.Comment)
{
reader.Read();
}
if (reader.JsonToken_0 != JsonToken.PropertyName)
{
throw JsonReaderException.smethod_1(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".smethod_0(CultureInfo.InvariantCulture, reader.JsonToken_0));
}
JProperty property = new JProperty((string) reader.Object_0);
property.method_0(reader as IJsonLineInfo);
property.method_10(reader);
return property;
}
void JContainer.()
{
throw new JsonException("Cannot add or remove items from {0}.".smethod_0(CultureInfo.InvariantCulture, typeof(JProperty)));
}
JToken JContainer.(int int_0)
{
if (int_0 != 0)
{
throw new ArgumentOutOfRangeException();
}
return this.Value;
}
void JContainer.(int int_0, JToken jtoken_2)
{
if (int_0 != 0)
{
throw new ArgumentOutOfRangeException();
}
if (!JContainer.smethod_6(this.Value, jtoken_2))
{
if (base.Parent != null)
{
((JObject) base.Parent).method_15(this);
}
base.Newtonsoft.Json.Linq.JContainer.(0, jtoken_2);
if (base.Parent != null)
{
((JObject) base.Parent).method_14(this);
}
}
}
bool JContainer.(JToken jtoken_2)
{
throw new JsonException("Cannot add or remove items from {0}.".smethod_0(CultureInfo.InvariantCulture, typeof(JProperty)));
}
bool JContainer.(JToken jtoken_2)
{
return (this.Value == jtoken_2);
}
void JContainer.(int int_0, JToken jtoken_2, bool bool_1)
{
if (this.Value != null)
{
throw new JsonException("{0} cannot have multiple values.".smethod_0(CultureInfo.InvariantCulture, typeof(JProperty)));
}
base.Newtonsoft.Json.Linq.JContainer.(0, jtoken_2, false);
}
void JContainer.(int int_0)
{
throw new JsonException("Cannot add or remove items from {0}.".smethod_0(CultureInfo.InvariantCulture, typeof(JProperty)));
}
int JToken.()
{
return (this.string_0.GetHashCode() ^ ((this.Value != null) ? this.Value.Newtonsoft.Json.Linq.JToken.() : 0));
}
bool JToken.(JToken jtoken_2)
{
JProperty property = jtoken_2 as JProperty;
return (((property != null) && (this.string_0 == property.Name)) && base.method_3(property));
}
JToken JToken.()
{
return new JProperty(this);
}
public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
{
writer.WritePropertyName(this.string_0);
JToken token = this.Value;
if (token != null)
{
token.WriteTo(writer, converters);
}
else
{
writer.WriteNull();
}
}
protected override IList<JToken> ChildrenTokens
{
get
{
return this.list_0;
}
}
public string Name
{
[DebuggerStepThrough]
get
{
return this.string_0;
}
}
public override JTokenType Type
{
[DebuggerStepThrough]
get
{
return JTokenType.Property;
}
}
public JToken Value
{
[DebuggerStepThrough]
get
{
if (this.list_0.Count <= 0)
{
return null;
}
return this.list_0[0];
}
set
{
base.method_2();
JToken token = value ?? new JValue(null);
if (this.list_0.Count == 0)
{
this.Newtonsoft.Json.Linq.JContainer.(0, token, false);
}
else
{
this.Newtonsoft.Json.Linq.JContainer.(0, token);
}
}
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrganizationsAreaRegistration.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Diagnostics.CodeAnalysis;
using System.Web.Mvc;
using CGI.Reflex.Core;
namespace CGI.Reflex.Web.Areas.Organizations
{
[ExcludeFromCodeCoverage]
public class OrganizationsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Organizations";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Organizations_default",
"Organizations/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional });
}
}
}
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class TriggerControl : MonoBehaviour
{
#if UNITY_EDITOR
[SerializeField]
protected bool m_IsLog;
#endif
protected ColliderObjects m_TriggerObjects;
bool m_IsInit;
Coroutine m_CheckTriggerCoroutine;
protected bool m_IgnoreTriggerEnter;
public event Action<Collider, bool> EnterToTrigger, ExitFromTrigger;
//цель, состояние, условие
public event Action<Collider, bool, bool> EventTrigger;
public int Count { get { return m_TriggerObjects.Count; } }
public Collider this[int index] { get { return m_TriggerObjects.Objs[index]; } }
protected void ImprovedStopCoroutine(Coroutine coroutine)
{
if (coroutine != null) StopCoroutine(coroutine);
coroutine = null;
}
protected virtual bool CheckConditions(Collider cld)
{
return !cld.IsNullOrDestroy();
}
protected virtual void Init()
{
if (m_IsInit) return;
m_TriggerObjects = new ColliderObjects();
m_TriggerObjects.SetConditions(CheckConditions);
m_TriggerObjects.SetTriggerControl(this);
m_IsInit = true;
}
protected class ColliderObjects : SomeTriggerObject<Collider>
{
public void SetTriggerControl(TriggerControl control)
{
m_Control = control;
}
TriggerControl m_Control;
public bool Validation()
{
for (int i = m_Objs.Count - 1; i >= 0; i--)
{
var cld = m_Objs[i];
if (cld.IsNullOrDestroy())
{
m_Objs.RemoveAt(i);
continue;
}
bool res = CheckValidation(cld);
if (!res)
{
m_Objs.RemoveAt(i);
m_Control.CallExitFromTrigger(cld, true);
}
}
return true;
}
bool CheckValidation(Collider cld)
{
return cld.enabled && cld.gameObject.activeInHierarchy;
}
}
//улучшенный ебанный костыль
IEnumerator CheckTriggerObjects()
{
while (true)
{
m_TriggerObjects.Validation();
yield return null;
}
}
void CallExitFromTrigger(Collider cld, bool cond)
{
#if UNITY_EDITOR
if (m_IsLog) Debug.LogError("CallExitFromTrigger=" + cld + " cond=" + cond);
#endif
if (cond)
{
if (m_TriggerObjects.Count <= 0) ImprovedStopCoroutine(m_CheckTriggerCoroutine);
}
OnExitFromTrigger(cld, cond);
if (ExitFromTrigger != null) ExitFromTrigger(cld, cond);
if (EventTrigger != null) EventTrigger(cld, false, cond);
}
void CallEnterToTrigger(Collider cld, bool cond)
{
#if UNITY_EDITOR
if (m_IsLog) Debug.LogError("CallEnterToTrigger=" + cld + " cond=" + cond);
#endif
if (cond)
{
if (m_CheckTriggerCoroutine == null) m_CheckTriggerCoroutine = StartCoroutine(CheckTriggerObjects());
}
OnEnterToTrigger(cld, cond);
if (EnterToTrigger != null) EnterToTrigger(cld, cond);
if (EventTrigger != null) EventTrigger(cld, true, cond);
}
protected void OnTriggerEnter(Collider cld) { if (m_IgnoreTriggerEnter) return; CallEnterToTrigger(cld, m_TriggerObjects.AddObject(cld)); }
protected void OnTriggerExit(Collider cld) { CallExitFromTrigger(cld, m_TriggerObjects.RemoveObject(cld)); }
protected virtual void OnEnterToTrigger(Collider sender, bool condition) { }
protected virtual void OnExitFromTrigger(Collider sender, bool condition) { }
protected virtual void Disable() { }
protected virtual void OnAwake() { }
protected void Clear()
{
m_TriggerObjects.Reset();
ImprovedStopCoroutine(m_CheckTriggerCoroutine);
}
private void Awake()
{
Init();
OnAwake();
}
void OnDisable()
{
Clear();
Disable();
}
//Костыли
#region Manual Funcs
public void ManualExit(Collider cld)
{
if (cld.IsNullOrDestroy()) return;
Init();
OnTriggerExit(cld);
}
public void ManualExit(GameObject go)
{
if (go == null) return;
ManualExit(go.GetComponent<Collider>());
}
public void ManualEnter(Collider cld)
{
if (cld.IsNullOrDestroy()) return;
Init();
OnTriggerEnter(cld);
}
public void ManualEnter(GameObject go)
{
if (go == null) return;
ManualEnter(go.GetComponent<Collider>());
}
#endregion
}
public abstract class TriggerObjects<T>
{
Predicate<T> m_Conditions;
public abstract void Reset();
//public abstract bool CheckConditions();
public void SetConditions(Predicate<T> cond)
{
m_Conditions = cond;
}
public bool AddObject(T obj)
{
bool res = m_Conditions == null || m_Conditions(obj);
return res && InnerAdd(obj);
}
public abstract bool RemoveObject(T obj);
protected abstract bool InnerAdd(T obj);
public TriggerObjects() { }
public TriggerObjects(Predicate<T> cond)
{
SetConditions(cond);
}
}
public class OneTriggerObject<T> : TriggerObjects<T> where T : class
{
T m_Obj;
//public T Obj { get { return m_Obj; } }
public OneTriggerObject() { }
public OneTriggerObject(Predicate<T> cond) : base(cond) { }
public override void Reset()
{
m_Obj = null;
}
protected override bool InnerAdd(T obj)
{
m_Obj = obj;
return true;
}
public override bool RemoveObject(T obj)
{
bool res = m_Obj == obj;
if (res) m_Obj = null;
return res;
}
//public override bool CheckConditions()
//{
// return m_Conditions == null || m_Conditions(m_Obj);
//}
}
public class SomeTriggerObject<T> : TriggerObjects<T> where T : class
{
protected List<T> m_Objs;
public List<T> Objs { get { return m_Objs; } }
public int Count { get { return m_Objs.Count; } }
public SomeTriggerObject() : this(10) { }
public SomeTriggerObject(int cap) { m_Objs = new List<T>(cap); }
public SomeTriggerObject(Predicate<T> cond) : this(10, cond) { }
public SomeTriggerObject(int cap, Predicate<T> cond) : base(cond)
{
m_Objs = new List<T>(cap);
}
public bool Contains(T obj)
{
return m_Objs.Contains(obj);
}
public override void Reset()
{
m_Objs.Clear();
}
protected override bool InnerAdd(T obj)
{
bool res = !m_Objs.Contains(obj);
if (res) m_Objs.Add(obj);
return res;
}
public override bool RemoveObject(T obj)
{
int index = m_Objs.IndexOf(obj);
if (index != -1) m_Objs.RemoveAt(index);
return index != -1;
}
//public override bool CheckConditions()
//{
// if (m_Conditions == null) return true;
// for (int i = m_Objs.Count - 1; i >= 0; i--)
// {
// bool res = m_Conditions(m_Objs[i]);
// if (!res) return false;
// }
// return true;
//}
}
public struct ColliderTriggerArgs
{
public Collider Object;
public bool EnterConditions;
public bool TriggerConditions;
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoalEater : Eater
{
private GameObject m_currentFocusObject;
private float m_refocusFrequency = 1;
private float m_timerRefocus;
public float m_shutdownTerrierFrequency = 6;
private float m_timerShutdown;
private bool m_isDying = false;
private bool m_focusOnTerrier = false;
// Start is called before the first frame update
void Start()
{
if (WorldGenerator.Instance.EatableCoalList.Count == 0)
{
m_currentFocusObject = FindClosestCoalBall();
m_currentFocusObject.GetComponent<CoalBall>().RegisterPredator(this);
}
}
// Update is called once per frame
void Update()
{
if ((WorldGenerator.Instance.PlayerInstance.transform.position - transform.position).sqrMagnitude > 10000)
{
Destroy(gameObject);
}
if (m_isDying)
{
return;
}
if (WorldGenerator.Instance.EatableCoalList.Count == 0 && m_currentFocusObject == null)
{
// No ball anymore? Let's make it disappear for now
Die(new Vector3(0, 0, 0));
return;
}
if (m_focusOnTerrier && (m_currentFocusObject == null || m_currentFocusObject.GetComponent<TerrierSpawner>().Status == TerrierState.SLEEPING))
{
//if (m_currentFocusObject.GetComponent<TerrierSpawner>().Status == TerrierState.SLEEPING)
//{
m_focusOnTerrier = false;
//}
}
if (!m_focusOnTerrier)
{
CoalBall cb = m_currentFocusObject == null ? null : m_currentFocusObject.GetComponent<CoalBall>();
if (m_currentFocusObject != null && cb != null && m_timerRefocus > m_refocusFrequency)
{
m_currentFocusObject.GetComponent<CoalBall>().UnregisterPredator(this);
m_currentFocusObject = null;
m_timerRefocus = 0;
} else
{
m_timerRefocus += Time.deltaTime;
}
if (m_currentFocusObject == null || cb == null)
{
m_currentFocusObject = FindClosestCoalBall();
m_currentFocusObject.GetComponent<CoalBall>().RegisterPredator(this);
}
}
if (m_timerShutdown > m_shutdownTerrierFrequency)
{
m_focusOnTerrier = true;
if (m_currentFocusObject != null)
{
var cb = m_currentFocusObject.GetComponent<CoalBall>();
if (cb != null)
{
cb.GetComponent<CoalBall>().UnregisterPredator(this);
}
}
m_currentFocusObject = FindClosestTerrier();
m_timerShutdown = 0;
} else
{
m_timerShutdown += Time.deltaTime;
}
if (m_currentFocusObject != null)
{
MoveTowardFocusObject();
}
}
private GameObject FindClosestTerrier()
{
GameObject closestTerrier = null;
float min = float.MaxValue;
foreach (var terrierObj in TerrierSpawner.AwokeTerriers)
{
var sqrDist = (terrierObj.transform.position - transform.position).sqrMagnitude;
if (closestTerrier == null || sqrDist < min)
{
closestTerrier = terrierObj.gameObject;
min = sqrDist;
}
}
return closestTerrier;
}
private void MoveTowardFocusObject()
{
var direction = Vector3.Normalize(m_currentFocusObject.transform.position - transform.position);
transform.Translate(direction * Speed * Time.deltaTime);
if (direction.x > 0)
{
MonsterSprite.flipX = false;
} else
{
MonsterSprite.flipX = true;
}
}
private GameObject FindRandomCoalBall()
{
return WorldGenerator.Instance.EatableCoalList[Random.Range(0, WorldGenerator.Instance.EatableCoalList.Count)];
}
private GameObject FindClosestCoalBall()
{
GameObject closestBall = null;
float min = float.MaxValue;
foreach (var coalObj in WorldGenerator.Instance.EatableCoalList)
{
var sqrDist = (coalObj.transform.position - transform.position).sqrMagnitude;
if (closestBall == null || sqrDist < min)
{
closestBall = coalObj;
min = sqrDist;
}
}
return closestBall;
}
public void CoalBallDisappear()
{
m_currentFocusObject = null;
}
private void OnCollisionEnter2D(Collision2D collision)
{
var cb = collision.gameObject.GetComponent<CoalBall>();
if (cb != null)
{
cb.DestroyBall();
}
var ts = collision.gameObject.GetComponent<TerrierSpawner>();
if (ts != null && ts == m_currentFocusObject.GetComponent<TerrierSpawner>())
{
ts.PutToSleep();
m_currentFocusObject = null;
}
}
public override void Die(Vector3 playerPosition)
{
base.Die(playerPosition);
m_isDying = true;
if (m_currentFocusObject != null && m_currentFocusObject.GetComponent<CoalBall>() != null)
{
m_currentFocusObject.GetComponent<CoalBall>().UnregisterPredator(this);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
public class SplashScreen : MonoBehaviour {
public Image splashImage;
public string loadLevel;
IEnumerator Start() {
splashImage.canvasRenderer.SetAlpha(0f);
splashImage.CrossFadeAlpha(1f, 1.5f, false);
yield return new WaitForSeconds(2.5f);
splashImage.CrossFadeAlpha(0f, 2.5f, false);
yield return new WaitForSeconds(2.5f);
SceneManager.LoadScene(loadLevel);
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SpaceWars;
using System.Collections.Generic;
namespace ModelTestProject
{
[TestClass]
public class TestsToPass
{
[TestMethod]
public void ProjDiesWhenLeavingWorldNorth()
{
// make world and projectile
int worldSize = 400;
World newWorld = new World(worldSize);
Projectile newProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(0, 0));
newWorld.UpdateProjectile(newProj, 0);
Assert.IsTrue(newProj.IsAlive());
// relocate projectile offscreen
newProj.SetLocation(new Vector2D(0, -400));
newWorld.Update(100);
Assert.IsFalse(newProj.IsAlive());
}
[TestMethod]
public void ProjDiesWhenLeavingWorldSouth()
{
int worldSize = 400;
World newWorld = new World(worldSize);
Projectile newProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(0, 0));
newWorld.UpdateProjectile(newProj, 0);
Assert.IsTrue(newProj.IsAlive());
// relocate projectile offscreen
newProj.SetLocation(new Vector2D(0, (worldSize) / 2));
newWorld.Update(100);
Assert.IsFalse(newProj.IsAlive());
}
[TestMethod]
public void ProjDiesWhenLeavingWorldEast()
{
int worldSize = 400;
World newWorld = new World(worldSize);
Projectile newProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(0, 0));
newWorld.UpdateProjectile(newProj, 0);
Assert.IsTrue(newProj.IsAlive());
// relocate projectile offscreen
newProj.SetLocation(new Vector2D(-400, 0));
newWorld.Update(100);
Assert.IsFalse(newProj.IsAlive());
}
[TestMethod]
public void ProjDiesWhenLeavingWorldWest()
{
int worldSize = 400;
World newWorld = new World(worldSize);
Projectile newProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(0, 0));
newWorld.UpdateProjectile(newProj, 0);
Assert.IsTrue(newProj.IsAlive());
// relocate projectile offscreen
newProj.SetLocation(new Vector2D(400, 0));
newWorld.Update(100);
Assert.IsFalse(newProj.IsAlive());
}
[TestMethod]
public void ProjDiesWhenHittingStar()
{
// make world, star, and projectile
int worldSize = 400;
int starRadius = 35;
int projSpeed = 15;
Vector2D starLocation = new Vector2D(-100, 0);
World newWorld = new World(worldSize, 0.08, projSpeed, 2, starRadius, 20, 300, 5);
Star theStar = new Star(0, 0.01, starLocation);
theStar.GetID();
Projectile newProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(0, 0));
newWorld.UpdateProjectile(newProj, 0);
newWorld.UpdateStar(theStar, 0);
Assert.IsTrue(newProj.IsAlive());
// relocate projectile
newProj.SetLocation(starLocation + new Vector2D(starRadius - projSpeed + 1, 0));
newWorld.Update(100);
Assert.IsFalse(newProj.IsAlive());
}
[TestMethod]
public void ProjCollideWithStar()
{
World theWorld = new World(750);
Star aStar = new Star(0, 0.02, new Vector2D(0, 0));
Projectile proj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(0, 0));
Projectile farProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(0, 50));
PrivateObject obj = new PrivateObject(theWorld);
Assert.AreEqual(obj.Invoke("CollidedWith", new object[] { proj, aStar}), true);
Assert.AreEqual(obj.Invoke("CollidedWith", new object[] { farProj, aStar}), false);
}
[TestMethod]
public void ShipCollideWithStar()
{
World theWorld = new World(750);
Star aStar = new Star(0, 0.02, new Vector2D(0, 0));
Ship ship = new Ship(0, "close");
ship.SetLocation(new Vector2D(0, 20));
Ship farShip = new Ship(1, "far");
farShip.SetLocation(new Vector2D(100, 0));
PrivateObject obj = new PrivateObject(theWorld);
Assert.AreEqual(obj.Invoke("CollidedWith", new object[] { aStar, ship }), true);
Assert.AreEqual(obj.Invoke("CollidedWith", new object[] { aStar, farShip }), false);
}
[TestMethod]
public void ProjDiesWhenHittingShipAndShipLosesHP()
{
// make world
int worldSize = 400;
int shipRadius = 20;
World newWorld = new World(worldSize, 0.08, 15, 2, 35, shipRadius, 300, 5);
// make ship and projectile (ship is not projectile owner)
Ship theShip = new Ship(3, "me");
theShip.SetLocation(new Vector2D(shipRadius, 0));
Projectile newProj = new Projectile(0, 0, new Vector2D(1, 0), new Vector2D(0, 0)); // starts at center, and will move right 15 units
// add the projectile and ship to the world
newWorld.UpdateProjectile(newProj, 0);
newWorld.UpdateShip(theShip, 3);
Assert.IsTrue(newProj.IsAlive());
Assert.IsTrue(theShip.GetHP() == 5);
newWorld.Update(100);
Assert.IsFalse(newProj.IsAlive());
Assert.IsTrue(theShip.GetHP() == 4);
}
[TestMethod]
public void KillShipKillProjIncreaseScore()
{
// make world
int worldSize = 400;
int shipRadius = 20;
World newWorld = new World(worldSize, 0.08, 15, 2, 35, shipRadius, 300, 5);
// make them ship
Ship themShip = new Ship(3, "them");
themShip.SetHP(1);
Vector2D themLocation = new Vector2D(100, 100);
themShip.SetLocation(themLocation);
newWorld.UpdateShip(themShip, 3);
// make us ship
Ship usShip = new Ship(0, "us");
usShip.SetLocation(new Vector2D(100, 200));
newWorld.UpdateShip(usShip, 0);
// make projectile
Projectile newProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(themLocation));
newWorld.UpdateProjectile(newProj, 0);
Assert.IsTrue(newProj.IsAlive());
Assert.IsTrue(themShip.GetHP() == 1);
Assert.IsTrue(usShip.GetScore() == 0);
// relocate projectile
newWorld.Update(100);
Assert.IsFalse(newProj.IsAlive());
Assert.IsTrue(themShip.GetHP() == 0);
Assert.IsTrue(usShip.GetScore() == 1);
}
[TestMethod]
public void NoSelfFriendlyFire()
{
// make world
int worldSize = 400;
int shipRadius = 20;
World newWorld = new World(worldSize);
// make us ship
Ship usShip = new Ship(0, "us");
usShip.SetHP(1);
newWorld.UpdateShip(usShip, 0);
// make projectile
Projectile newProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(100, 100));
newWorld.UpdateProjectile(newProj, 0);
Assert.IsTrue(newProj.IsAlive());
Assert.IsTrue(usShip.GetScore() == 0);
Assert.IsTrue(usShip.GetHP() == 1);
// relocate projectile
newProj.SetLocation(new Vector2D(shipRadius, 0));
newWorld.Update(100);
Assert.IsTrue(newProj.IsAlive());
Assert.IsTrue(usShip.GetScore() == 0);
Assert.IsTrue(usShip.GetHP() == 1);
}
[TestMethod]
public void ShipWraparoundNorth()
{
// make world
int worldSize = 400;
World newWorld = new World(worldSize);
// make us ship
Ship usShip = new Ship(0, "us");
newWorld.UpdateShip(usShip, 0);
// put ship off screen
usShip.SetLocation(new Vector2D(0, ((-worldSize) / 2) - 1));
// ship wraps around
newWorld.Update(100);
Assert.IsTrue(usShip.GetLocation().Equals(new Vector2D(0, (worldSize / 2) - 1)));
}
[TestMethod]
public void ShipWraparoundSouth()
{
// make world
int worldSize = 400;
World newWorld = new World(worldSize);
// make us ship
Ship usShip = new Ship(0, "us");
newWorld.UpdateShip(usShip, 0);
// put ship off screen
usShip.SetLocation(new Vector2D(0, ((worldSize) / 2) + 1));
// ship wraps around
newWorld.Update(100);
Assert.IsTrue(usShip.GetLocation().Equals(new Vector2D(0, ((-worldSize) / 2) + 1)));
}
[TestMethod]
public void ShipWraparoundEast()
{
// make world
int worldSize = 400;
World newWorld = new World(worldSize);
// make us ship
Ship usShip = new Ship(0, "us");
newWorld.UpdateShip(usShip, 0);
// put ship off screen
usShip.SetLocation(new Vector2D((worldSize / 2) + 1, 0));
// ship wraps around
newWorld.Update(100);
Assert.IsTrue(usShip.GetLocation().Equals(new Vector2D((-worldSize / 2) + 1, 0)));
}
[TestMethod]
public void ShipWraparoundWest()
{
// make world
int worldSize = 400;
World newWorld = new World(worldSize);
// make us ship
Ship usShip = new Ship(0, "us");
newWorld.UpdateShip(usShip, 0);
// put ship off screen
usShip.SetLocation(new Vector2D(((-worldSize) / 2) - 1, 0));
// ship wraps around
newWorld.Update(100);
Assert.IsTrue(usShip.GetLocation().Equals(new Vector2D(((worldSize) / 2) - 1, 0)));
}
[TestMethod]
public void GetNameShip()
{
Ship ship = new Ship(0, "John");
Assert.AreEqual("John", ship.GetName());
}
[TestMethod]
public void CompareToShip2IsGreater()
{
Ship ship1 = new Ship(1, "one");
ship1.IncrementScore();
Ship ship2 = new Ship(2, "two");
ship2.IncrementScore();
ship2.IncrementScore();
Assert.IsTrue(ship1.CompareTo(ship2) > 0);
}
[TestMethod]
public void CompareToShip1IsGreater()
{
Ship ship1 = new Ship(1, "one");
ship1.IncrementScore();
ship1.IncrementScore();
ship1.IncrementScore();
Ship ship2 = new Ship(2, "two");
ship2.IncrementScore();
ship2.IncrementScore();
Assert.IsTrue(ship1.CompareTo(ship2) < 0);
}
[TestMethod]
public void CompareToShipsAreEqual()
{
Ship ship1 = new Ship(1, "one");
ship1.IncrementScore();
ship1.IncrementScore();
Ship ship2 = new Ship(2, "two");
ship2.IncrementScore();
ship2.IncrementScore();
Assert.IsTrue(ship1.CompareTo(ship2) == 0);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CompareToNotShip()
{
Ship ship1 = new Ship(1, "one");
ship1.IncrementScore();
ship1.IncrementScore();
ship1.IncrementScore();
String ship2 = "fake ship";
ship1.CompareTo(ship2);
}
[TestMethod]
public void ThrustingTest()
{
Ship ship = new Ship(0, "me");
ship.ThrustOff();
Assert.IsFalse(ship.IsThrusting());
ship.ThrustOn();
Assert.IsTrue(ship.IsThrusting());
}
[TestMethod]
public void FireProjectile()
{
World myWorld = new World(750);
Ship ship = new Ship(0, "me");
ship.SetLocation(new Vector2D(0, 0));
ship.SetOrientation(new Vector2D(1, 0));
myWorld.UpdateShip(ship, 0);
Assert.AreEqual(-7, ship.TimeLastFired);
myWorld.FireProjectile(0, 0);
List<Projectile> projs = new List<Projectile>(myWorld.GetProjectiles());
Assert.IsTrue(projs.Count == 1);
Assert.AreEqual(projs[0].GetOrientation(), ship.GetOrientation());
}
[TestMethod]
public void RotateRight()
{
World myWorld = new World(750, 0.08, 15, 90, 35, 20, 300, 5);
Vector2D expectedDir = new Vector2D(1, 0);
expectedDir.Rotate(90);
Ship ship = new Ship(0, "me");
ship.SetLocation(new Vector2D(0, 0));
ship.SetOrientation(new Vector2D(1, 0));
myWorld.UpdateShip(ship, 0);
myWorld.RotateShipRight(0);
Assert.AreEqual(expectedDir, ship.GetOrientation());
}
[TestMethod]
public void RotateLeft()
{
World myWorld = new World(750, 0.08, 15, 90, 35, 20, 300, 5);
Vector2D expectedDir = new Vector2D(1, 0);
expectedDir.Rotate(-90);
Ship ship = new Ship(0, "me");
ship.SetLocation(new Vector2D(0, 0));
ship.SetOrientation(new Vector2D(1, 0));
myWorld.UpdateShip(ship, 0);
myWorld.RotateShipLeft(0);
Assert.AreEqual(expectedDir, ship.GetOrientation());
}
[TestMethod]
public void RespawnDeadShip()
{
World world = new World(750, 0.08, 15, 2, 35, 20, 300, 5);
Ship ship = new Ship(0, "me");
world.UpdateShip(ship, 0);
ship.SetHP(0);
ship.TimeOfDeath = 195;
world.Update(200);
Assert.AreEqual(0, ship.GetHP());
world.Update(500);
Assert.AreEqual(5, ship.GetHP());
}
[TestMethod]
public void KillProj()
{
World world = new World(750);
Projectile proj = new Projectile(0, 0, new Vector2D(1, 0), new Vector2D(0, 0));
world.UpdateProjectile(proj, 0);
proj.KillProj();
List<Projectile> orig = new List<Projectile>(world.GetProjectiles());
Assert.AreEqual(1, orig.Count);
world.Update(100);
List<Projectile> projs = new List<Projectile>(world.GetProjectiles());
Assert.AreEqual(0, projs.Count);
}
[TestMethod]
public void GetSize()
{
World world = new World(750);
Assert.AreEqual(750, world.GetSize());
}
[TestMethod]
public void SortedShips()
{
World world = new World(750);
Ship ship1 = new Ship(1, "bro");
Ship ship2 = new Ship(2, "bro");
Ship ship3 = new Ship(3, "bro");
world.UpdateShip(ship1, 1);
world.UpdateShip(ship2, 2);
world.UpdateShip(ship3, 3);
ship1.IncrementScore();
ship2.IncrementScore();
ship2.IncrementScore();
ship3.IncrementScore();
ship3.IncrementScore();
ship3.IncrementScore();
List<Ship> sorted = new List<Ship>(world.GetShips());
Assert.AreEqual(ship3, sorted[0]);
Assert.AreEqual(ship2, sorted[1]);
Assert.AreEqual(ship1, sorted[2]);
}
[TestMethod]
public void StarGetSizeChangeSize()
{
World theWorld = new World(750);
Star aStar = new Star(0, 0.02, new Vector2D(0, 0));
theWorld.UpdateStar(aStar, 0);
Assert.AreEqual(0.02, aStar.GetSize());
aStar.SetSize(0.2);
Assert.AreEqual(0.2, aStar.GetSize());
}
[TestMethod]
public void StarGetLocChangeLoc()
{
World theWorld = new World(750);
Star aStar = new Star(0, 0.02, new Vector2D(0, 0));
theWorld.UpdateStar(aStar, 0);
Assert.IsTrue(new Vector2D(0, 0).Equals(aStar.GetLocation()));
aStar.SetLocation(new Vector2D(300, -20));
Assert.IsTrue(new Vector2D(300, -20).Equals(aStar.GetLocation()));
}
[TestMethod]
public void NullNotEqualToVector()
{
Vector2D meVector = new Vector2D(7, 7);
Assert.IsFalse(meVector.Equals(null));
}
[TestMethod]
public void NonVectorNotEqualToVector()
{
Vector2D meVector = new Vector2D(7, 7);
Assert.IsFalse(meVector.Equals(new Ship()));
}
[TestMethod]
public void SameVectorSameHashcode()
{
Vector2D aVector = new Vector2D(7, 7);
Vector2D bVector = new Vector2D(7, 7);
Assert.IsTrue(aVector.GetHashCode().Equals(bVector.GetHashCode()));
}
[TestMethod]
public void TestPositiveClamp()
{
Vector2D aVector = new Vector2D(7, 7);
aVector.Clamp();
Assert.IsTrue(aVector.Equals(new Vector2D(1, 1)));
}
[TestMethod]
public void TestNegativeClamp()
{
Vector2D aVector = new Vector2D(-7, -7);
aVector.Clamp();
Assert.IsTrue(aVector.Equals(new Vector2D(-1, -1)));
}
[TestMethod]
public void ToAngleZeroX()
{
Vector2D meVector = new Vector2D(0, 1);
meVector.Normalize();
Assert.AreEqual(180, meVector.ToAngle());
}
[TestMethod]
public void ToAngleNegativeX()
{
Vector2D meVector = new Vector2D(-1, 0);
meVector.Normalize();
Assert.AreEqual(-90, meVector.ToAngle());
}
[TestMethod]
public void UpdateAndGetWorldStars()
{
World theWorld = new World(750);
Star aStar = new Star(0, 0.02, new Vector2D(0, 0));
theWorld.UpdateStar(aStar, 0);
theWorld.UpdateStar(aStar, 0);
HashSet<Star> starSet = new HashSet<Star>(theWorld.GetStars());
Assert.AreEqual(1, starSet.Count);
}
[TestMethod]
public void UpdateAndGetWorldShips()
{
World theWorld = new World(750);
Ship meShip = new Ship();
theWorld.UpdateShip(meShip, 0);
theWorld.UpdateShip(meShip, 0);
Ship otherShip = theWorld.GetShip(0);
Assert.AreEqual(meShip.GetID(), otherShip.GetID());
}
[TestMethod]
public void UpdateAndKillProj()
{
World theWorld = new World(750);
Projectile aProj = new Projectile(0, 0, new Vector2D(1, 1), new Vector2D(0, 0));
theWorld.UpdateProjectile(aProj, 0);
theWorld.UpdateProjectile(aProj, 0);
HashSet<Projectile> projSet = new HashSet<Projectile>(theWorld.GetProjectiles());
Assert.AreEqual(1, projSet.Count);
aProj.KillProj();
theWorld.UpdateProjectile(aProj, 0);
projSet = new HashSet<Projectile>(theWorld.GetProjectiles());
Assert.AreEqual(0, projSet.Count);
}
[TestMethod]
public void CheckGravity()
{
World theWorld = new World(750);
Ship meShip = new Ship(0, "Us");
theWorld.UpdateShip(meShip, 0);
Star aStar = new Star(0, 0.05, new Vector2D(80, 80));
theWorld.UpdateStar(aStar, 0);
Assert.IsTrue(meShip.GetLocation().Equals(new Vector2D(0, 0)));
// after updating, the ship should be in a different location, due
// to the star's gravity
theWorld.Update(1);
Assert.IsFalse(meShip.GetLocation().Equals(new Vector2D(0, 0)));
// Switch the ships thrust on
meShip.ThrustOn();
theWorld.Update(2);
}
[TestMethod]
public void CheckThrust()
{
World theWorld = new World(750);
Ship meShip = new Ship(0, "Us");
theWorld.UpdateShip(meShip, 0);
Assert.IsTrue(meShip.GetLocation().Equals(new Vector2D(0, 0)));
// after updating, the ship should be in a different location, due
// to the ship's thrust
meShip.ThrustOn();
theWorld.Update(1);
Assert.IsFalse(meShip.GetLocation().Equals(new Vector2D(0, 0)));
}
[TestMethod]
public void StarKillShip()
{
World theWorld = new World(750);
Ship meShip = new Ship(0, "Us");
theWorld.UpdateShip(meShip, 0);
Star aStar = new Star(0, 0.05, new Vector2D(80, 80));
theWorld.UpdateStar(aStar, 0);
theWorld.CheckCollisions(1);
Assert.AreEqual(-5, meShip.TimeOfDeath);
meShip.SetLocation(new Vector2D(80, 40));
theWorld.CheckCollisions(2);
Assert.AreEqual(2, meShip.TimeOfDeath);
}
[TestMethod]
public void NoCollisionIfProfAlreadyDead()
{
World theWorld = new World(750);
Projectile meProj = new Projectile(0, 0, new Vector2D(0, 1), new Vector2D(80, 80));
theWorld.UpdateProjectile(meProj, 0);
meProj.KillProj();
Star aStar = new Star(0, 0.05, new Vector2D(80, 80));
theWorld.UpdateStar(aStar, 0);
theWorld.CheckCollisions(1);
}
[TestMethod]
public void NoCollisionIfShipAlreadyDead()
{
World theWorld = new World(750);
Ship meShip = new Ship(0, "Us");
meShip.SetHP(0);
theWorld.UpdateShip(meShip, 0);
Star aStar = new Star(0, 0.05, new Vector2D(80, 80));
theWorld.UpdateStar(aStar, 0);
theWorld.CheckCollisions(1);
Assert.AreEqual(-5, meShip.TimeOfDeath);
meShip.SetLocation(new Vector2D(80, 40));
theWorld.CheckCollisions(2);
Assert.AreEqual(-5, meShip.TimeOfDeath);
}
[TestMethod]
public void GetStartingShipHP()
{
World theWorld = new World(750);
Ship meShip = new Ship(0, "Us");
theWorld.UpdateShip(meShip, 0);
Assert.AreEqual(meShip.GetHP(), theWorld.GetStartingHP());
}
[TestMethod]
public void RemoveShipFromWorld()
{
World theWorld = new World(750);
Ship meShip = new Ship(0, "Us");
theWorld.UpdateShip(meShip, 0);
HashSet<Ship> worldShips = new HashSet<Ship>(theWorld.GetShips());
Assert.AreEqual(1, worldShips.Count);
theWorld.RemoveShip(0);
Assert.AreEqual(0, meShip.GetHP());
Assert.IsFalse(meShip.Connected);
}
[TestMethod]
public void CheckShipLocation()
{
// check safeness with star
World theWorld = new World(750);
PrivateObject obj = new PrivateObject(theWorld);
Assert.AreEqual(obj.Invoke("CheckSafeness", new object[] { new Vector2D(0, 0) }), new Vector2D(0, 0));
Star theStar = new Star(0, 0.01, new Vector2D(0, 0));
theWorld.UpdateStar(theStar, 0);
Assert.AreNotEqual(obj.Invoke("CheckSafeness", new object[] { new Vector2D(0, 0) }), new Vector2D(0, 0));
}
[TestMethod]
public void SafeGameModeOnShipIsSafe()
{
World theWorld = new World(750, 0.08, 15, 2, 35, 20, 300, 5, true);
Ship theShip = new Ship(0, "Us");
theWorld.UpdateShip(theShip, 0);
theShip.TimeLastSpawned = 10;
Projectile proj = new Projectile(2, 0, new Vector2D(0, 1), new Vector2D(0, 0));
theWorld.UpdateProjectile(proj, 0);
theWorld.Update(20);
Assert.AreEqual(5, theShip.GetHP());
}
[TestMethod]
public void SafeGameModeOnShipIsNotSafe()
{
World theWorld = new World(750, 0.08, 15, 2, 35, 20, 300, 5, true);
Ship theShip = new Ship(0, "Us");
theWorld.UpdateShip(theShip, 0);
Projectile proj = new Projectile(2, 0, new Vector2D(0, 1), new Vector2D(0, 0));
theWorld.UpdateProjectile(proj, 0);
theWorld.Update(20);
Assert.AreEqual(4, theShip.GetHP());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Master.Contract;
using Master.BusinessFactory;
using LogiCon.Areas.Master.DTO;
using System.Globalization;
namespace LogiCon.Areas.Master.Controllers
{
[RoutePrefix("api/master/currencyrate")]
public class CurrencyRateController : ApiController
{
[HttpGet, Route("list/{currencyCode}")]
public IHttpActionResult List(string currencyCode)
{
try
{
var currencyList = new CurrencyRateBO().GetList(UTILITY.BRANCHID, currencyCode);
if (currencyList != null)
return Ok(new {
currencyList = currencyList,
lineChartData = ChartData(currencyList)
});
else
return NotFound();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
[HttpPost, Route("save")]
public IHttpActionResult SaveList(List<CurrencyRate> currencyRateList)
{
try
{
var result = new CurrencyRateBO().SaveCurrencyRateList<CurrencyRate>(currencyRateList);
return Ok(result ? UTILITY.SUCCESSMSG : UTILITY.FAILEDMSG);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
private List<LineChartDataDTO> ChartData(List<CurrencyRate> currencyRateList)
{
var lineChartData = new List<LineChartDataDTO>();
LineChartDataDTO lineChart;
for(var i = 0; i < currencyRateList.Count; i++)
{
lineChart = new LineChartDataDTO();
//lineChart.currencyCode = currencyRateList[i].CurrencyCode;
lineChart.exchangeRate = currencyRateList[i].ExchangeRate;
lineChart.yearMonth = currencyRateList[i].ExpiryDate.Year.ToString() + "-"
+ currencyRateList[i].ExpiryDate.Month.ToString();
lineChartData.Add(lineChart);
}
return lineChartData;
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using static AudioManager;
public class PlayerProperties : MonoBehaviour
{
public List<Card> active_cards;
// This will track health and be attached to player objects. gameObject refers to what this script is attached to.
private int unspent_pts;
public int health = 100;
//public int move_speed = 5; // Arbitrary value for now. Just created a place in memory for it
public bool isDead;
public int xp = 0, level = 1;
int xpToLevel = 2;
public int points = 0;
public int score = 0;
int castleState = 0;
Image castle;
public Sprite[] castleSprites;
TextMeshProUGUI pointsTxt, scoreTxt, levelTxt;
public bool ignoreMe;
// Start is called before the first frame update INITIALIZATION
void Start()
{
active_cards = new List<Card>();
isDead = false;
unspent_pts = 0;
}
// Update is called once per frame
void Update()
{
if (isDead == true)
{
//gameObject.SetActive(false);
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
}
if (!ignoreMe)
{
if (PlayManager.inst.handPhase)
{
if (pointsTxt == null) SetText();
else
{
pointsTxt.text = "Points: " + points;
scoreTxt.text = score + "/20";
levelTxt.text = "Level: " + level;
}
}
}
}
int award_points(int pts)
{ // Awards points to parents
unspent_pts += pts;
return unspent_pts;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Knife")
{
health -= 100; // In case we decide at some point we don't want to instantly kill player, here's a mechanism
if (health <= 0 && !isDead) // by default player will instantly die
{
isDead = true;
death(collision.GetComponent<Knife>().owner);
}
if(!collision.GetComponent<Knife>().pierce) Destroy(collision.gameObject);
}
}
public void equipCard(Card card)
{ //call for each card being activated
active_cards.Add(card);
}
public void activateCards()
{
foreach (Card a in active_cards)
{
if(!a.isActive) a.GetComponent<Card>().setCardActive(gameObject);
GetComponent<PlayerHand>().myHand.Remove(a.gameObject);
}
}
public void resetCards()
{
foreach (Card a in active_cards)
{
if(a.isActive) a.setCardUnactivate(gameObject);
Destroy(a.gameObject);
if (GetComponent<PlayerHand>().highestButtonShown < 4 && GetComponent<PlayerHand>().highestButtonShown > -1)
{
GetComponent<PlayerHand>().buttonsUI[GetComponent<PlayerHand>().highestButtonShown].SetActive(false);
GetComponent<PlayerHand>().highestButtonShown--;
}
}
active_cards = new List<Card>();
isDead = false;
health = 100;
}
public void buyXP()
{
if(points > 0)
{
xp++;
points--;
if (xp >= xpToLevel)
{
xp -= xpToLevel;
level++;
xpToLevel *= 2;
GetComponent<PlayerHand>().maxCardCount++;
GetComponent<PlayerHand>().cardsPicked.text = "Picks Left: " + (GetComponent<PlayerHand>().maxCardCount - GetComponent<PlayerHand>().activeCardCount);
// level up stat boosts
GetComponent<PlayerMove>().movementSpeed += 1F;
GetComponent<PlayerMove>().resetCD -= 0.05F;
if (level >= 5) PlayManager.inst.checkForWin(gameObject);
}
}
}
public void buyScore()
{
if(points > 0)
{
score++;
points--;
// every 2 a piece is added
if (score == 2) repair();
else if (score % 4 == 3) updateCastle();
// check for win
PlayManager.inst.checkForWin(gameObject);
}
}
public void SetText()
{
Debug.Log("setting text objects");
GameObject tempHand = GetComponent<PlayerHand>().handImg;
pointsTxt = tempHand.transform.GetChild(2).GetComponent<TextMeshProUGUI>();
scoreTxt = tempHand.transform.GetChild(3).GetComponent<TextMeshProUGUI>();
levelTxt = tempHand.transform.GetChild(4).GetComponent<TextMeshProUGUI>();
castle = tempHand.transform.GetChild(5).GetComponent<Image>();
}
public void death(int playerKill)
{
// disable player, add to death count, give point to player who killed
GetComponent<SpriteRenderer>().enabled = false;
transform.GetChild(0).gameObject.SetActive(false);
GetComponent<Animator>().SetFloat("Hor", 0);
GetComponent<Animator>().SetFloat("Vert", 0);
GetComponent<PlayerMove>().enabled = false;
//if (transform.GetChild(2) != null) transform.GetChild(2).gameObject.SetActive(false);
PlayManager.inst.playersDead.Add(gameObject);
PlayManager.inst.Players[playerKill - 1].GetComponent<PlayerProperties>().points++;
instance.PlayDeathSound();
}
void updateCastle()
{
// increase castle state, change castle sprite
castleState++;
castle.sprite = castleSprites[castleState];
}
void repair()
{
castle.transform.GetChild(0).gameObject.SetActive(false);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Webshop.Data
{
public class Status
{
public Status(int i)
{
switch (i)
{
case 1:
{
Name = "New";
break;
}
case 2:
{
Name = "Processing";
break;
}
case 3:
{
Name = "Packaged";
break;
}
case 4:
{
Name = "In transit";
break;
}
case 5:
{
Name = "Delivered";
break;
}
default:
{
Name = "Error";
break;
}
}
}
public Status() {; }
/// <summary>
/// A sztátusz egyéni azonosítója
/// </summary>
public int StatusId { get; set; }
/// <summary>
/// A sztátusz neve
/// </summary>
public string Name { get; set; }
}
}
|
namespace kelvinho_airlines.Utils.ExtensionMethods
{
public static class NullExtensions
{
public static bool IsNull(this object obj)
=> obj == null;
}
}
|
using Microsoft.JSInterop;
using System;
using System.Threading.Tasks;
namespace ServerlessCrudBlazorUI.Services.JSInteropHelpers
{
/// <summary>
/// A class to be passed as a DotNetObjectReference to IJSRuntime invoked Javascript, which can call its JSInvokable CallbackMethod and get a return value of type T.
/// </summary>
public class CallbackHelper<T>
{
/// <summary>
/// The delegate for the .NET method to be invoked by Javascript.
/// </summary>
/// <param name="args">The arguments supplied by Javascript to the .NET method.</param>
public delegate Task<T> Callback(params object[] args);
/// <summary>
/// Creates a new CallbackHelper instance.
/// </summary>
/// <param name="callbackMethod">The .NET method to be invoked by Javascript.</param>
public CallbackHelper(Callback callbackMethod)
{
CallbackMethod = callbackMethod;
}
/// <summary>
/// The .NET method to be invoked by Javascript.
/// </summary>
public Callback CallbackMethod { get; set; }
/// <summary>
/// The method invoked by Javascript, which in turn invokes the CallbackMethod supplied in the constructor, to get a return value of type T.
/// </summary>
/// <param name="args">The arguments to be passed to the CallbackMethod supplied in the constructor.</param>
[JSInvokable]
public Task<T> InvokeCallback(params object[] args)
{
return CallbackMethod(args);
}
}
}
|
using AutoMapper;
using Contoso.Common.Configuration.ExpansionDescriptors;
using LogicBuilder.Expressions.Utils.Expansions;
using LogicBuilder.Expressions.Utils.Strutures;
namespace Contoso.AutoMapperProfiles
{
public class ExpansionDescriptorToOperatorMappingProfile : Profile
{
public ExpansionDescriptorToOperatorMappingProfile()
{
CreateMap<SelectExpandDefinitionDescriptor, SelectExpandDefinition>();
CreateMap<SelectExpandItemFilterDescriptor, SelectExpandItemFilter>();
CreateMap<SelectExpandItemDescriptor, SelectExpandItem>();
CreateMap<SelectExpandItemQueryFunctionDescriptor, SelectExpandItemQueryFunction>();
CreateMap<SortCollectionDescriptor, SortCollection>()
.ForMember(dest => dest.Skip, opts => opts.MapFrom(src => src.Skip.HasValue ? src.Skip.Value : 0))
.ForMember(dest => dest.Take, opts => opts.MapFrom(src => src.Take.HasValue ? src.Take.Value : int.MaxValue));
CreateMap<SortDescriptionDescriptor, SortDescription>();
}
}
}
|
using FluentValidation;
using FluentValidation.Results;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ProjectRestaurant.Domains.ValueObjects
{
public class Address : AbstractValidator<Address>
{
public string Street { get; set; }
public string Number { get; set; }
public string City { get; set; }
public string UF { get; set; }
public string Cep { get; set; }
public Address(string street, string number, string city, string uF, string cep)
{
Street = street;
Number = number;
City = city;
UF = uF;
Cep = cep;
}
public ValidationResult ValidationResult { get; set; }
public bool Validation()
{
ValidateElements();
ValidationResult = Validate(this);
return ValidationResult.IsValid;
}
private void ValidateElements()
{
RuleFor(x => x.Street)
.NotEmpty().WithMessage("A rua não pode ser vazia.")
.MaximumLength(50).WithMessage("Rua pode ter no máximo 50 caracteres.");
RuleFor(x => x.City)
.NotEmpty().WithMessage("A cidade não pode ser vazia.")
.MaximumLength(100).WithMessage("Cidade pode ter no máximo 100 caracteres.");
RuleFor(x => x.UF)
.NotEmpty().WithMessage("UF não pode ser vazio.")
.MaximumLength(2).WithMessage("UF pode ter no máximo 2 caracteres.");
RuleFor(x => x.Cep)
.NotEmpty().WithMessage("O CEP não pode ser vazio.")
.MaximumLength(8).WithMessage("Cep pode ter no máximo 8 caracteres.");
}
//private void ValidateStreet()
//{
// RuleFor(x => x.Street)
// .NotEmpty().WithMessage("A rua não pode ser vazia.")
// .MaximumLength(50).WithMessage("Rua pode ter no máximo 50 caracteres.");
//}
//private void ValidateCity()
//{
// RuleFor(x => x.City)
// .NotEmpty().WithMessage("A cidade não pode ser vazia.")
// .MaximumLength(100).WithMessage("Cidade pode ter no máximo 100 caracteres.");
//}
//private void ValidateUf()
//{
// RuleFor(x => x.UF)
// .NotEmpty().WithMessage("UF não pode ser vazio.")
// .MaximumLength(2).WithMessage("UF pode ter no máximo 2 caracteres.");
//}
//private void ValidateCep()
//{
// RuleFor(x => x.Cep)
// .NotEmpty().WithMessage("O CEP não pode ser vazio.")
// .MaximumLength(8).WithMessage("Cep pode ter no máximo 8 caracteres.");
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace _52WeekChallenge
{
public class SavingsCompute
{
public int weekCount()
{
float deposit = 500;
float startingAmount = 1000;
float balance = 0;
float weeklyDeposit=0;
int lastDepositWeek = 51;
/* I will presume that the 52nd week is when the withdrawal will happen so there will be no need to make deposit, that is why the counter ends at 51*/
for (int week =1; week <= lastDepositWeek; week++)
{
weeklyDeposit = (week * deposit)+startingAmount;
balance = (balance + weeklyDeposit);
Console.WriteLine("Week "+week+" amount is " + weeklyDeposit+ " and balance is " +balance);
}
return 0;
}
public DateTime YearWeekDayToDateTime(int year, DayOfWeek day, int week)
{
DateTime startOfYear = new DateTime(year, 1, 1);
// The +7 and %7 stuff is to avoid negative numbers etc.
int daysToFirstCorrectDay = (((int)day - (int)startOfYear.DayOfWeek) + 7) % 7;
return startOfYear.AddDays(7 * (week - 1) + daysToFirstCorrectDay);
}
}
}
|
using System;
namespace DoE.Quota.ShoppingCart.Norms.Validations.Exceptions
{
[Serializable]
public class LearnerGuideException : Exception
{
public LearnerGuideException() {}
public LearnerGuideException(string error) : base(error){}
}
}
|
using System;
namespace OCP.Files
{
/**
* Class EmptyFileNameException
*
* @package OCP\Files
* @since 9.2.0
*/
class EmptyFileNameException : InvalidPathException
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YzkSoftWare.Components
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class ComponentMethodLockKeysAttribute : Attribute
{
public ComponentMethodLockKeysAttribute(string lockKey, bool isread) { LockKey = lockKey; IsRead = isread; }
/// <summary>
/// 锁定的键
/// </summary>
public string LockKey { get; private set; }
/// <summary>
/// 是否是读锁
/// </summary>
public bool IsRead { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using Yasl.Internal;
namespace Yasl
{
public class AbstractSerializer<T> : ISerializer
where T : class
{
public virtual void SerializeContents(T value, ISerializationWriter writer)
{
}
public virtual void DeserializeContents(T value, int version, ISerializationReader reader)
{
}
public virtual void SerializeBacklinks(T value, ISerializationWriter writer)
{
}
public virtual void DeserializeBacklinks(T value, int version, ISerializationReader reader)
{
}
public void SerializeConstructor(ref object value, ISerializationWriter writer)
{
throw Assert.CreateException(
"can't serialize constructor of abstract type '{0}'", typeof(T).Name());
}
public void DeserializeConstructor(out object value, int version, ISerializationReader reader)
{
throw Assert.CreateException(
"can't deserialize constructor of abstract type '{0}'", typeof(T).Name());
}
public void SerializeContents(ref object value, ISerializationWriter writer)
{
T typed = (T)value;
SerializeContents(typed, writer);
}
public void DeserializeContents(ref object value, int version, ISerializationReader reader)
{
T typed = (T)value;
DeserializeContents(typed, version, reader);
value = typed;
}
public void SerializeBacklinks(ref object value, ISerializationWriter writer)
{
T typed = (T)value;
SerializeBacklinks(typed, writer);
}
public void DeserializeBacklinks(ref object value, int version, ISerializationReader reader)
{
T typed = (T)value;
DeserializeBacklinks(typed, version, reader);
value = typed;
}
public virtual void DeserializationComplete(ref object value, int version)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OtelBilgiSistemi
{
class Hashİçerik
{
public int anahtar;
public Heap OtelHeap;
public Hashİçerik(string anahtar,int ints)
{
this.anahtar = StringDönüştürücü(anahtar);
this.OtelHeap = new Heap(ints);
}
private int StringDönüştürücü(string StringKey)
{
int IntAnahtar = 0;
int i = 0;
foreach (char a in StringKey)
{
IntAnahtar += StringKey[i];
i++;
}
return IntAnahtar;
}
}
}
|
using UnityEditor;
using UnityEngine;
namespace HT.Framework
{
[CustomEditor(typeof(MouseRotation))]
internal sealed class MouseRotationInspector : HTFEditor<MouseRotation>
{
protected override bool IsEnableRuntimeData
{
get
{
return false;
}
}
protected override void OnInspectorDefaultGUI()
{
base.OnInspectorDefaultGUI();
GUILayout.BeginHorizontal();
Toggle(Target.IsCanOnUGUI, out Target.IsCanOnUGUI, "Is Can Control On UGUI");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
Toggle(Target.AllowOverstepDistance, out Target.AllowOverstepDistance, "Allow Overstep Distance");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
Toggle(Target.IsLookAtTarget, out Target.IsLookAtTarget, "LookAt Target");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Speed", EditorStyles.boldLabel);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.XSpeed, out Target.XSpeed, " X");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.YSpeed, out Target.YSpeed, " Y");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.MSpeed, out Target.MSpeed, " M");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Angle Limit", EditorStyles.boldLabel);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.YMinAngleLimit, out Target.YMinAngleLimit, " Y min");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.YMaxAngleLimit, out Target.YMaxAngleLimit, " Y max");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Distance", EditorStyles.boldLabel);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.Distance, out Target.Distance, " Distance");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.MinDistance, out Target.MinDistance, " Min");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.MaxDistance, out Target.MaxDistance, " Max");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Damping", EditorStyles.boldLabel);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
Toggle(Target.NeedDamping, out Target.NeedDamping, " Need Damping");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Angle", EditorStyles.boldLabel);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.X, out Target.X, " X");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
FloatField(Target.Y, out Target.Y, " Y");
GUILayout.EndHorizontal();
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using UnityEngine;
public static class NGUITools
{
private static AudioListener mListener;
private static bool mLoaded = false;
private static float mGlobalVolume = 1f;
private static float mLastTimestamp = 0f;
private static AudioClip mLastClip;
private static Vector3[] mSides = new Vector3[4];
public static float soundVolume
{
get
{
if (!NGUITools.mLoaded)
{
NGUITools.mLoaded = true;
NGUITools.mGlobalVolume = PlayerPrefs.GetFloat("Sound", 1f);
}
return NGUITools.mGlobalVolume;
}
set
{
if (NGUITools.mGlobalVolume != value)
{
NGUITools.mLoaded = true;
NGUITools.mGlobalVolume = value;
PlayerPrefs.SetFloat("Sound", value);
}
}
}
public static bool fileAccess
{
get
{
return Application.get_platform() != 5 && Application.get_platform() != 3;
}
}
public static string clipboard
{
get
{
TextEditor textEditor = new TextEditor();
textEditor.Paste();
return textEditor.get_content().get_text();
}
set
{
TextEditor textEditor = new TextEditor();
textEditor.set_content(new GUIContent(value));
textEditor.OnFocus();
textEditor.Copy();
}
}
public static Vector2 screenSize
{
get
{
return new Vector2((float)Screen.get_width(), (float)Screen.get_height());
}
}
public static AudioSource PlaySound(AudioClip clip)
{
return NGUITools.PlaySound(clip, 1f, 1f);
}
public static AudioSource PlaySound(AudioClip clip, float volume)
{
return NGUITools.PlaySound(clip, volume, 1f);
}
public static AudioSource PlaySound(AudioClip clip, float volume, float pitch)
{
float time = Time.get_time();
if (NGUITools.mLastClip == clip && NGUITools.mLastTimestamp + 0.1f > time)
{
return null;
}
NGUITools.mLastClip = clip;
NGUITools.mLastTimestamp = time;
volume *= NGUITools.soundVolume;
if (clip != null && volume > 0.01f)
{
if (NGUITools.mListener == null || !NGUITools.GetActive(NGUITools.mListener))
{
AudioListener[] array = Object.FindObjectsOfType(typeof(AudioListener)) as AudioListener[];
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
if (NGUITools.GetActive(array[i]))
{
NGUITools.mListener = array[i];
break;
}
}
}
if (NGUITools.mListener == null)
{
Camera camera = Camera.get_main();
if (camera == null)
{
camera = (Object.FindObjectOfType(typeof(Camera)) as Camera);
}
if (camera != null)
{
NGUITools.mListener = camera.get_gameObject().AddComponent<AudioListener>();
}
}
}
if (NGUITools.mListener != null && NGUITools.mListener.get_enabled() && NGUITools.GetActive(NGUITools.mListener.get_gameObject()))
{
AudioSource audioSource = NGUITools.mListener.GetComponent<AudioSource>();
if (audioSource == null)
{
audioSource = NGUITools.mListener.get_gameObject().AddComponent<AudioSource>();
}
audioSource.set_priority(50);
audioSource.set_pitch(pitch);
audioSource.PlayOneShot(clip, volume);
return audioSource;
}
}
return null;
}
public static int RandomRange(int min, int max)
{
if (min == max)
{
return min;
}
return Random.Range(min, max + 1);
}
public static string GetHierarchy(GameObject obj)
{
if (obj == null)
{
return string.Empty;
}
string text = obj.get_name();
while (obj.get_transform().get_parent() != null)
{
obj = obj.get_transform().get_parent().get_gameObject();
text = obj.get_name() + "\\" + text;
}
return text;
}
public static T[] FindActive<T>() where T : Component
{
return Object.FindObjectsOfType(typeof(T)) as T[];
}
public static Camera FindCameraForLayer(int layer)
{
int num = 1 << layer;
Camera camera;
for (int i = 0; i < UICamera.list.size; i++)
{
camera = UICamera.list.buffer[i].cachedCamera;
if (camera && (camera.get_cullingMask() & num) != 0)
{
return camera;
}
}
camera = Camera.get_main();
if (camera && (camera.get_cullingMask() & num) != 0)
{
return camera;
}
Camera[] array = new Camera[Camera.get_allCamerasCount()];
int allCameras = Camera.GetAllCameras(array);
for (int j = 0; j < allCameras; j++)
{
camera = array[j];
if (camera && camera.get_enabled() && (camera.get_cullingMask() & num) != 0)
{
return camera;
}
}
return null;
}
public static void AddWidgetCollider(GameObject go)
{
NGUITools.AddWidgetCollider(go, false);
}
public static void AddWidgetCollider(GameObject go, bool considerInactive)
{
if (go != null)
{
Collider component = go.GetComponent<Collider>();
BoxCollider boxCollider = component as BoxCollider;
if (boxCollider != null)
{
NGUITools.UpdateWidgetCollider(boxCollider, considerInactive);
return;
}
if (component != null)
{
return;
}
BoxCollider2D boxCollider2D = go.GetComponent<BoxCollider2D>();
if (boxCollider2D != null)
{
NGUITools.UpdateWidgetCollider(boxCollider2D, considerInactive);
return;
}
UICamera uICamera = UICamera.FindCameraForLayer(go.get_layer());
if (uICamera != null && (uICamera.eventType == UICamera.EventType.World_2D || uICamera.eventType == UICamera.EventType.UI_2D))
{
boxCollider2D = go.AddComponent<BoxCollider2D>();
boxCollider2D.set_isTrigger(true);
UIWidget component2 = go.GetComponent<UIWidget>();
if (component2 != null)
{
component2.autoResizeBoxCollider = true;
}
NGUITools.UpdateWidgetCollider(boxCollider2D, considerInactive);
return;
}
boxCollider = go.AddComponent<BoxCollider>();
boxCollider.set_isTrigger(true);
UIWidget component3 = go.GetComponent<UIWidget>();
if (component3 != null)
{
component3.autoResizeBoxCollider = true;
}
NGUITools.UpdateWidgetCollider(boxCollider, considerInactive);
}
}
public static void UpdateWidgetCollider(GameObject go)
{
NGUITools.UpdateWidgetCollider(go, false);
}
public static void UpdateWidgetCollider(GameObject go, bool considerInactive)
{
if (go != null)
{
BoxCollider component = go.GetComponent<BoxCollider>();
if (component != null)
{
NGUITools.UpdateWidgetCollider(component, considerInactive);
return;
}
BoxCollider2D component2 = go.GetComponent<BoxCollider2D>();
if (component2 != null)
{
NGUITools.UpdateWidgetCollider(component2, considerInactive);
}
}
}
public static void UpdateWidgetCollider(BoxCollider box, bool considerInactive)
{
if (box != null)
{
GameObject gameObject = box.get_gameObject();
UIWidget component = gameObject.GetComponent<UIWidget>();
if (component != null)
{
Vector4 drawRegion = component.drawRegion;
if (drawRegion.x != 0f || drawRegion.y != 0f || drawRegion.z != 1f || drawRegion.w != 1f)
{
Vector4 drawingDimensions = component.drawingDimensions;
box.set_center(new Vector3((drawingDimensions.x + drawingDimensions.z) * 0.5f, (drawingDimensions.y + drawingDimensions.w) * 0.5f));
box.set_size(new Vector3(drawingDimensions.z - drawingDimensions.x, drawingDimensions.w - drawingDimensions.y));
}
else
{
Vector3[] localCorners = component.localCorners;
box.set_center(Vector3.Lerp(localCorners[0], localCorners[2], 0.5f));
box.set_size(localCorners[2] - localCorners[0]);
}
}
else
{
Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(gameObject.get_transform(), considerInactive);
box.set_center(bounds.get_center());
box.set_size(new Vector3(bounds.get_size().x, bounds.get_size().y, 0f));
}
}
}
public static void UpdateWidgetCollider(BoxCollider2D box, bool considerInactive)
{
if (box != null)
{
GameObject gameObject = box.get_gameObject();
UIWidget component = gameObject.GetComponent<UIWidget>();
if (component != null)
{
Vector3[] localCorners = component.localCorners;
box.set_offset(Vector3.Lerp(localCorners[0], localCorners[2], 0.5f));
box.set_size(localCorners[2] - localCorners[0]);
}
else
{
Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(gameObject.get_transform(), considerInactive);
box.set_offset(bounds.get_center());
box.set_size(new Vector2(bounds.get_size().x, bounds.get_size().y));
}
}
}
public static string GetTypeName<T>()
{
string text = typeof(T).ToString();
if (text.StartsWith("UI"))
{
text = text.Substring(2);
}
else if (text.StartsWith("UnityEngine."))
{
text = text.Substring(12);
}
return text;
}
public static string GetTypeName(Object obj)
{
if (obj == null)
{
return "Null";
}
string text = obj.GetType().ToString();
if (text.StartsWith("UI"))
{
text = text.Substring(2);
}
else if (text.StartsWith("UnityEngine."))
{
text = text.Substring(12);
}
return text;
}
public static void RegisterUndo(Object obj, string name)
{
}
public static void SetDirty(Object obj)
{
}
public static GameObject AddChild(GameObject parent)
{
return NGUITools.AddChild(parent, true);
}
public static GameObject AddChild(GameObject parent, bool undo)
{
GameObject gameObject = new GameObject();
if (parent != null)
{
Transform transform = gameObject.get_transform();
transform.set_parent(parent.get_transform());
transform.set_localPosition(Vector3.get_zero());
transform.set_localRotation(Quaternion.get_identity());
transform.set_localScale(Vector3.get_one());
gameObject.set_layer(parent.get_layer());
}
return gameObject;
}
public static GameObject AddChild(GameObject parent, GameObject prefab)
{
GameObject gameObject = Object.Instantiate<GameObject>(prefab);
if (gameObject != null && parent != null)
{
Transform transform = gameObject.get_transform();
transform.set_parent(parent.get_transform());
transform.set_localPosition(Vector3.get_zero());
transform.set_localRotation(Quaternion.get_identity());
transform.set_localScale(Vector3.get_one());
gameObject.set_layer(parent.get_layer());
}
return gameObject;
}
public static int CalculateRaycastDepth(GameObject go)
{
UIWidget component = go.GetComponent<UIWidget>();
if (component != null)
{
return component.raycastDepth;
}
UIWidget[] componentsInChildren = go.GetComponentsInChildren<UIWidget>();
if (componentsInChildren.Length == 0)
{
return 0;
}
int num = 2147483647;
int i = 0;
int num2 = componentsInChildren.Length;
while (i < num2)
{
if (componentsInChildren[i].get_enabled())
{
num = Mathf.Min(num, componentsInChildren[i].raycastDepth);
}
i++;
}
return num;
}
public static int CalculateNextDepth(GameObject go)
{
int num = -1;
UIWidget[] componentsInChildren = go.GetComponentsInChildren<UIWidget>();
int i = 0;
int num2 = componentsInChildren.Length;
while (i < num2)
{
num = Mathf.Max(num, componentsInChildren[i].depth);
i++;
}
return num + 1;
}
public static int CalculateNextDepth(GameObject go, bool ignoreChildrenWithColliders)
{
if (ignoreChildrenWithColliders)
{
int num = -1;
UIWidget[] componentsInChildren = go.GetComponentsInChildren<UIWidget>();
int i = 0;
int num2 = componentsInChildren.Length;
while (i < num2)
{
UIWidget uIWidget = componentsInChildren[i];
if (!(uIWidget.cachedGameObject != go) || (!(uIWidget.GetComponent<Collider>() != null) && !(uIWidget.GetComponent<Collider2D>() != null)))
{
num = Mathf.Max(num, uIWidget.depth);
}
i++;
}
return num + 1;
}
return NGUITools.CalculateNextDepth(go);
}
public static int AdjustDepth(GameObject go, int adjustment)
{
if (!(go != null))
{
return 0;
}
UIPanel uIPanel = go.GetComponent<UIPanel>();
if (uIPanel != null)
{
UIPanel[] componentsInChildren = go.GetComponentsInChildren<UIPanel>(true);
for (int i = 0; i < componentsInChildren.Length; i++)
{
UIPanel uIPanel2 = componentsInChildren[i];
uIPanel2.depth += adjustment;
}
return 1;
}
uIPanel = NGUITools.FindInParents<UIPanel>(go);
if (uIPanel == null)
{
return 0;
}
UIWidget[] componentsInChildren2 = go.GetComponentsInChildren<UIWidget>(true);
int j = 0;
int num = componentsInChildren2.Length;
while (j < num)
{
UIWidget uIWidget = componentsInChildren2[j];
if (!(uIWidget.panel != uIPanel))
{
uIWidget.depth += adjustment;
}
j++;
}
return 2;
}
public static void BringForward(GameObject go)
{
int num = NGUITools.AdjustDepth(go, 1000);
if (num == 1)
{
NGUITools.NormalizePanelDepths();
}
else if (num == 2)
{
NGUITools.NormalizeWidgetDepths();
}
}
public static void PushBack(GameObject go)
{
int num = NGUITools.AdjustDepth(go, -1000);
if (num == 1)
{
NGUITools.NormalizePanelDepths();
}
else if (num == 2)
{
NGUITools.NormalizeWidgetDepths();
}
}
public static void NormalizeDepths()
{
NGUITools.NormalizeWidgetDepths();
NGUITools.NormalizePanelDepths();
}
public static void NormalizeWidgetDepths()
{
NGUITools.NormalizeWidgetDepths(NGUITools.FindActive<UIWidget>());
}
public static void NormalizeWidgetDepths(GameObject go)
{
NGUITools.NormalizeWidgetDepths(go.GetComponentsInChildren<UIWidget>());
}
public static void NormalizeWidgetDepths(UIWidget[] list)
{
int num = list.Length;
if (num > 0)
{
Array.Sort<UIWidget>(list, new Comparison<UIWidget>(UIWidget.FullCompareFunc));
int num2 = 0;
int depth = list[0].depth;
for (int i = 0; i < num; i++)
{
UIWidget uIWidget = list[i];
if (uIWidget.depth == depth)
{
uIWidget.depth = num2;
}
else
{
depth = uIWidget.depth;
num2 = (uIWidget.depth = num2 + 1);
}
}
}
}
public static void NormalizePanelDepths()
{
UIPanel[] array = NGUITools.FindActive<UIPanel>();
int num = array.Length;
if (num > 0)
{
Array.Sort<UIPanel>(array, new Comparison<UIPanel>(UIPanel.CompareFunc));
int num2 = 0;
int depth = array[0].depth;
for (int i = 0; i < num; i++)
{
UIPanel uIPanel = array[i];
if (uIPanel.depth == depth)
{
uIPanel.depth = num2;
}
else
{
depth = uIPanel.depth;
num2 = (uIPanel.depth = num2 + 1);
}
}
}
}
public static UIPanel CreateUI(bool advanced3D)
{
return NGUITools.CreateUI(null, advanced3D, -1);
}
public static UIPanel CreateUI(bool advanced3D, int layer)
{
return NGUITools.CreateUI(null, advanced3D, layer);
}
public static UIPanel CreateUI(Transform trans, bool advanced3D, int layer)
{
UIRoot uIRoot = (!(trans != null)) ? null : NGUITools.FindInParents<UIRoot>(trans.get_gameObject());
if (uIRoot == null && UIRoot.list.get_Count() > 0)
{
using (List<UIRoot>.Enumerator enumerator = UIRoot.list.GetEnumerator())
{
while (enumerator.MoveNext())
{
UIRoot current = enumerator.get_Current();
if (current.get_gameObject().get_layer() == layer)
{
uIRoot = current;
break;
}
}
}
}
if (uIRoot == null)
{
int i = 0;
int count = UIPanel.list.get_Count();
while (i < count)
{
UIPanel uIPanel = UIPanel.list.get_Item(i);
GameObject gameObject = uIPanel.get_gameObject();
if (gameObject.get_hideFlags() == null && gameObject.get_layer() == layer)
{
trans.set_parent(uIPanel.get_transform());
trans.set_localScale(Vector3.get_one());
return uIPanel;
}
i++;
}
}
if (uIRoot != null)
{
UICamera componentInChildren = uIRoot.GetComponentInChildren<UICamera>();
if (componentInChildren != null && componentInChildren.GetComponent<Camera>().get_orthographic() == advanced3D)
{
trans = null;
uIRoot = null;
}
}
if (uIRoot == null)
{
GameObject gameObject2 = NGUITools.AddChild(null, false);
uIRoot = gameObject2.AddComponent<UIRoot>();
if (layer == -1)
{
layer = LayerMask.NameToLayer("UI");
}
if (layer == -1)
{
layer = LayerMask.NameToLayer("2D UI");
}
gameObject2.set_layer(layer);
if (advanced3D)
{
gameObject2.set_name("UI Root (3D)");
uIRoot.scalingStyle = UIRoot.Scaling.Constrained;
}
else
{
gameObject2.set_name("UI Root");
uIRoot.scalingStyle = UIRoot.Scaling.Flexible;
}
}
UIPanel uIPanel2 = uIRoot.GetComponentInChildren<UIPanel>();
if (uIPanel2 == null)
{
Camera[] array = NGUITools.FindActive<Camera>();
float num = -1f;
bool flag = false;
int num2 = 1 << uIRoot.get_gameObject().get_layer();
for (int j = 0; j < array.Length; j++)
{
Camera camera = array[j];
if (camera.get_clearFlags() == 2 || camera.get_clearFlags() == 1)
{
flag = true;
}
num = Mathf.Max(num, camera.get_depth());
camera.set_cullingMask(camera.get_cullingMask() & ~num2);
}
Camera camera2 = NGUITools.AddChild<Camera>(uIRoot.get_gameObject(), false);
camera2.get_gameObject().AddComponent<UICamera>();
camera2.set_clearFlags((!flag) ? 2 : 3);
camera2.set_backgroundColor(Color.get_grey());
camera2.set_cullingMask(num2);
camera2.set_depth(num + 1f);
if (advanced3D)
{
camera2.set_nearClipPlane(0.1f);
camera2.set_farClipPlane(4f);
camera2.get_transform().set_localPosition(new Vector3(0f, 0f, -700f));
}
else
{
camera2.set_orthographic(true);
camera2.set_orthographicSize(1f);
camera2.set_nearClipPlane(-10f);
camera2.set_farClipPlane(10f);
}
AudioListener[] array2 = NGUITools.FindActive<AudioListener>();
if (array2 == null || array2.Length == 0)
{
camera2.get_gameObject().AddComponent<AudioListener>();
}
uIPanel2 = uIRoot.get_gameObject().AddComponent<UIPanel>();
}
if (trans != null)
{
while (trans.get_parent() != null)
{
trans = trans.get_parent();
}
if (NGUITools.IsChild(trans, uIPanel2.get_transform()))
{
uIPanel2 = trans.get_gameObject().AddComponent<UIPanel>();
}
else
{
trans.set_parent(uIPanel2.get_transform());
trans.set_localScale(Vector3.get_one());
trans.set_localPosition(Vector3.get_zero());
NGUITools.SetChildLayer(uIPanel2.cachedTransform, uIPanel2.cachedGameObject.get_layer());
}
}
return uIPanel2;
}
public static void SetChildLayer(Transform t, int layer)
{
for (int i = 0; i < t.get_childCount(); i++)
{
Transform child = t.GetChild(i);
child.get_gameObject().set_layer(layer);
NGUITools.SetChildLayer(child, layer);
}
}
public static T AddChild<T>(GameObject parent) where T : Component
{
GameObject gameObject = NGUITools.AddChild(parent);
gameObject.set_name(NGUITools.GetTypeName<T>());
return gameObject.AddComponent<T>();
}
public static T AddChild<T>(GameObject parent, bool undo) where T : Component
{
GameObject gameObject = NGUITools.AddChild(parent, undo);
gameObject.set_name(NGUITools.GetTypeName<T>());
return gameObject.AddComponent<T>();
}
public static T AddWidget<T>(GameObject go) where T : UIWidget
{
int depth = NGUITools.CalculateNextDepth(go);
T result = NGUITools.AddChild<T>(go);
result.width = 100;
result.height = 100;
result.depth = depth;
return result;
}
public static T AddWidget<T>(GameObject go, int depth) where T : UIWidget
{
T result = NGUITools.AddChild<T>(go);
result.width = 100;
result.height = 100;
result.depth = depth;
return result;
}
public static UISprite AddSprite(GameObject go, UIAtlas atlas, string spriteName)
{
UISpriteData uISpriteData = (!(atlas != null)) ? null : atlas.GetSprite(spriteName);
UISprite uISprite = NGUITools.AddWidget<UISprite>(go);
uISprite.type = ((uISpriteData != null && uISpriteData.hasBorder) ? UIBasicSprite.Type.Sliced : UIBasicSprite.Type.Simple);
uISprite.atlas = atlas;
uISprite.spriteName = spriteName;
return uISprite;
}
public static GameObject GetRoot(GameObject go)
{
Transform transform = go.get_transform();
while (true)
{
Transform parent = transform.get_parent();
if (parent == null)
{
break;
}
transform = parent;
}
return transform.get_gameObject();
}
public static T FindInParents<T>(GameObject go) where T : Component
{
if (go == null)
{
return (T)((object)null);
}
T component = go.GetComponent<T>();
if (component == null)
{
Transform parent = go.get_transform().get_parent();
while (parent != null && component == null)
{
component = parent.get_gameObject().GetComponent<T>();
parent = parent.get_parent();
}
}
return component;
}
public static T FindInParents<T>(Transform trans) where T : Component
{
if (trans == null)
{
return (T)((object)null);
}
return trans.GetComponentInParent<T>();
}
public static void Destroy(Object obj)
{
if (obj != null)
{
if (obj is Transform)
{
obj = (obj as Transform).get_gameObject();
}
if (Application.get_isPlaying())
{
if (obj is GameObject)
{
GameObject gameObject = obj as GameObject;
gameObject.get_transform().set_parent(null);
}
Object.Destroy(obj);
}
else
{
Object.DestroyImmediate(obj);
}
}
}
public static void DestroyImmediate(Object obj)
{
if (obj != null)
{
if (Application.get_isEditor())
{
Object.DestroyImmediate(obj);
}
else
{
Object.Destroy(obj);
}
}
}
public static void Broadcast(string funcName)
{
GameObject[] array = Object.FindObjectsOfType(typeof(GameObject)) as GameObject[];
int i = 0;
int num = array.Length;
while (i < num)
{
array[i].SendMessage(funcName, 1);
i++;
}
}
public static void Broadcast(string funcName, object param)
{
GameObject[] array = Object.FindObjectsOfType(typeof(GameObject)) as GameObject[];
int i = 0;
int num = array.Length;
while (i < num)
{
array[i].SendMessage(funcName, param, 1);
i++;
}
}
public static bool IsChild(Transform parent, Transform child)
{
if (parent == null || child == null)
{
return false;
}
while (child != null)
{
if (child == parent)
{
return true;
}
child = child.get_parent();
}
return false;
}
private static void Activate(Transform t)
{
NGUITools.Activate(t, false);
}
private static void Activate(Transform t, bool compatibilityMode)
{
NGUITools.SetActiveSelf(t.get_gameObject(), true);
if (compatibilityMode)
{
int i = 0;
int childCount = t.get_childCount();
while (i < childCount)
{
Transform child = t.GetChild(i);
if (child.get_gameObject().get_activeSelf())
{
return;
}
i++;
}
int j = 0;
int childCount2 = t.get_childCount();
while (j < childCount2)
{
Transform child2 = t.GetChild(j);
NGUITools.Activate(child2, true);
j++;
}
}
}
private static void Deactivate(Transform t)
{
NGUITools.SetActiveSelf(t.get_gameObject(), false);
}
public static void SetActive(GameObject go, bool state)
{
NGUITools.SetActive(go, state, true);
}
public static void SetActive(GameObject go, bool state, bool compatibilityMode)
{
if (go)
{
if (state)
{
NGUITools.Activate(go.get_transform(), compatibilityMode);
NGUITools.CallCreatePanel(go.get_transform());
}
else
{
NGUITools.Deactivate(go.get_transform());
}
}
}
[DebuggerHidden, DebuggerStepThrough]
private static void CallCreatePanel(Transform t)
{
UIWidget component = t.GetComponent<UIWidget>();
if (component != null)
{
component.CreatePanel();
}
int i = 0;
int childCount = t.get_childCount();
while (i < childCount)
{
NGUITools.CallCreatePanel(t.GetChild(i));
i++;
}
}
public static void SetActiveChildren(GameObject go, bool state)
{
Transform transform = go.get_transform();
if (state)
{
int i = 0;
int childCount = transform.get_childCount();
while (i < childCount)
{
Transform child = transform.GetChild(i);
NGUITools.Activate(child);
i++;
}
}
else
{
int j = 0;
int childCount2 = transform.get_childCount();
while (j < childCount2)
{
Transform child2 = transform.GetChild(j);
NGUITools.Deactivate(child2);
j++;
}
}
}
[Obsolete("Use NGUITools.GetActive instead")]
public static bool IsActive(Behaviour mb)
{
return mb != null && mb.get_enabled() && mb.get_gameObject().get_activeInHierarchy();
}
[DebuggerHidden, DebuggerStepThrough]
public static bool GetActive(Behaviour mb)
{
return mb && mb.get_enabled() && mb.get_gameObject().get_activeInHierarchy();
}
[DebuggerHidden, DebuggerStepThrough]
public static bool GetActive(GameObject go)
{
return go && go.get_activeInHierarchy();
}
[DebuggerHidden, DebuggerStepThrough]
public static void SetActiveSelf(GameObject go, bool state)
{
go.SetActive(state);
}
public static void SetLayer(GameObject go, int layer)
{
go.set_layer(layer);
Transform transform = go.get_transform();
int i = 0;
int childCount = transform.get_childCount();
while (i < childCount)
{
Transform child = transform.GetChild(i);
NGUITools.SetLayer(child.get_gameObject(), layer);
i++;
}
}
public static Vector3 Round(Vector3 v)
{
v.x = Mathf.Round(v.x);
v.y = Mathf.Round(v.y);
v.z = Mathf.Round(v.z);
return v;
}
public static void MakePixelPerfect(Transform t)
{
UIWidget component = t.GetComponent<UIWidget>();
if (component != null)
{
component.MakePixelPerfect();
}
if (t.GetComponent<UIAnchor>() == null && t.GetComponent<UIRoot>() == null)
{
t.set_localPosition(NGUITools.Round(t.get_localPosition()));
t.set_localScale(NGUITools.Round(t.get_localScale()));
}
int i = 0;
int childCount = t.get_childCount();
while (i < childCount)
{
NGUITools.MakePixelPerfect(t.GetChild(i));
i++;
}
}
public static bool Save(string fileName, byte[] bytes)
{
if (!NGUITools.fileAccess)
{
return false;
}
string text = Application.get_persistentDataPath() + "/" + fileName;
if (bytes == null)
{
if (File.Exists(text))
{
File.Delete(text);
}
return true;
}
FileStream fileStream = null;
try
{
fileStream = File.Create(text);
}
catch (Exception ex)
{
Debug.LogError(ex.get_Message());
return false;
}
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();
return true;
}
public static byte[] Load(string fileName)
{
if (!NGUITools.fileAccess)
{
return null;
}
string text = Application.get_persistentDataPath() + "/" + fileName;
if (File.Exists(text))
{
return File.ReadAllBytes(text);
}
return null;
}
public static Color ApplyPMA(Color c)
{
if (c.a != 1f)
{
c.r *= c.a;
c.g *= c.a;
c.b *= c.a;
}
return c;
}
public static void MarkParentAsChanged(GameObject go)
{
UIRect[] componentsInChildren = go.GetComponentsInChildren<UIRect>();
int i = 0;
int num = componentsInChildren.Length;
while (i < num)
{
componentsInChildren[i].ParentHasChanged();
i++;
}
}
[Obsolete("Use NGUIText.EncodeColor instead")]
public static string EncodeColor(Color c)
{
return NGUIText.EncodeColor24(c);
}
[Obsolete("Use NGUIText.ParseColor instead")]
public static Color ParseColor(string text, int offset)
{
return NGUIText.ParseColor24(text, offset);
}
[Obsolete("Use NGUIText.StripSymbols instead")]
public static string StripSymbols(string text)
{
return NGUIText.StripSymbols(text);
}
public static T AddMissingComponent<T>(this GameObject go) where T : Component
{
T t = go.GetComponent<T>();
if (t == null)
{
t = go.AddComponent<T>();
}
return t;
}
public static Vector3[] GetSides(this Camera cam)
{
return cam.GetSides(Mathf.Lerp(cam.get_nearClipPlane(), cam.get_farClipPlane(), 0.5f), null);
}
public static Vector3[] GetSides(this Camera cam, float depth)
{
return cam.GetSides(depth, null);
}
public static Vector3[] GetSides(this Camera cam, Transform relativeTo)
{
return cam.GetSides(Mathf.Lerp(cam.get_nearClipPlane(), cam.get_farClipPlane(), 0.5f), relativeTo);
}
public static Vector3[] GetSides(this Camera cam, float depth, Transform relativeTo)
{
if (cam.get_orthographic())
{
float orthographicSize = cam.get_orthographicSize();
float num = -orthographicSize;
float num2 = orthographicSize;
float num3 = -orthographicSize;
float num4 = orthographicSize;
Rect rect = cam.get_rect();
Vector2 screenSize = NGUITools.screenSize;
float num5 = screenSize.x / screenSize.y;
num5 *= rect.get_width() / rect.get_height();
num *= num5;
num2 *= num5;
Transform transform = cam.get_transform();
Quaternion rotation = transform.get_rotation();
Vector3 position = transform.get_position();
int num6 = Mathf.RoundToInt(screenSize.x);
int num7 = Mathf.RoundToInt(screenSize.y);
if ((num6 & 1) == 1)
{
position.x -= 1f / screenSize.x;
}
if ((num7 & 1) == 1)
{
position.y += 1f / screenSize.y;
}
NGUITools.mSides[0] = rotation * new Vector3(num, 0f, depth) + position;
NGUITools.mSides[1] = rotation * new Vector3(0f, num4, depth) + position;
NGUITools.mSides[2] = rotation * new Vector3(num2, 0f, depth) + position;
NGUITools.mSides[3] = rotation * new Vector3(0f, num3, depth) + position;
}
else
{
NGUITools.mSides[0] = cam.ViewportToWorldPoint(new Vector3(0f, 0.5f, depth));
NGUITools.mSides[1] = cam.ViewportToWorldPoint(new Vector3(0.5f, 1f, depth));
NGUITools.mSides[2] = cam.ViewportToWorldPoint(new Vector3(1f, 0.5f, depth));
NGUITools.mSides[3] = cam.ViewportToWorldPoint(new Vector3(0.5f, 0f, depth));
}
if (relativeTo != null)
{
for (int i = 0; i < 4; i++)
{
NGUITools.mSides[i] = relativeTo.InverseTransformPoint(NGUITools.mSides[i]);
}
}
return NGUITools.mSides;
}
public static Vector3[] GetWorldCorners(this Camera cam)
{
float depth = Mathf.Lerp(cam.get_nearClipPlane(), cam.get_farClipPlane(), 0.5f);
return cam.GetWorldCorners(depth, null);
}
public static Vector3[] GetWorldCorners(this Camera cam, float depth)
{
return cam.GetWorldCorners(depth, null);
}
public static Vector3[] GetWorldCorners(this Camera cam, Transform relativeTo)
{
return cam.GetWorldCorners(Mathf.Lerp(cam.get_nearClipPlane(), cam.get_farClipPlane(), 0.5f), relativeTo);
}
public static Vector3[] GetWorldCorners(this Camera cam, float depth, Transform relativeTo)
{
if (cam.get_orthographic())
{
float orthographicSize = cam.get_orthographicSize();
float num = -orthographicSize;
float num2 = orthographicSize;
float num3 = -orthographicSize;
float num4 = orthographicSize;
Rect rect = cam.get_rect();
Vector2 screenSize = NGUITools.screenSize;
float num5 = screenSize.x / screenSize.y;
num5 *= rect.get_width() / rect.get_height();
num *= num5;
num2 *= num5;
Transform transform = cam.get_transform();
Quaternion rotation = transform.get_rotation();
Vector3 position = transform.get_position();
NGUITools.mSides[0] = rotation * new Vector3(num, num3, depth) + position;
NGUITools.mSides[1] = rotation * new Vector3(num, num4, depth) + position;
NGUITools.mSides[2] = rotation * new Vector3(num2, num4, depth) + position;
NGUITools.mSides[3] = rotation * new Vector3(num2, num3, depth) + position;
}
else
{
NGUITools.mSides[0] = cam.ViewportToWorldPoint(new Vector3(0f, 0f, depth));
NGUITools.mSides[1] = cam.ViewportToWorldPoint(new Vector3(0f, 1f, depth));
NGUITools.mSides[2] = cam.ViewportToWorldPoint(new Vector3(1f, 1f, depth));
NGUITools.mSides[3] = cam.ViewportToWorldPoint(new Vector3(1f, 0f, depth));
}
if (relativeTo != null)
{
for (int i = 0; i < 4; i++)
{
NGUITools.mSides[i] = relativeTo.InverseTransformPoint(NGUITools.mSides[i]);
}
}
return NGUITools.mSides;
}
public static string GetFuncName(object obj, string method)
{
if (obj == null)
{
return "<null>";
}
string text = obj.GetType().ToString();
int num = text.LastIndexOf('/');
if (num > 0)
{
text = text.Substring(num + 1);
}
return (!string.IsNullOrEmpty(method)) ? (text + "/" + method) : text;
}
public static void Execute<T>(GameObject go, string funcName) where T : Component
{
T[] components = go.GetComponents<T>();
T[] array = components;
for (int i = 0; i < array.Length; i++)
{
T t = array[i];
MethodInfo method = t.GetType().GetMethod(funcName, 52);
if (method != null)
{
method.Invoke(t, null);
}
}
}
public static void ExecuteAll<T>(GameObject root, string funcName) where T : Component
{
NGUITools.Execute<T>(root, funcName);
Transform transform = root.get_transform();
int i = 0;
int childCount = transform.get_childCount();
while (i < childCount)
{
NGUITools.ExecuteAll<T>(transform.GetChild(i).get_gameObject(), funcName);
i++;
}
}
public static void ImmediatelyCreateDrawCalls(GameObject root)
{
NGUITools.ExecuteAll<UIWidget>(root, "Start");
NGUITools.ExecuteAll<UIPanel>(root, "Start");
NGUITools.ExecuteAll<UIWidget>(root, "Update");
NGUITools.ExecuteAll<UIPanel>(root, "Update");
NGUITools.ExecuteAll<UIPanel>(root, "LateUpdate");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using Ninject;
using Dao.Mercadeo;
namespace Blo.Mercadeo
{
public class EstadoProductoBlo : GenericBlo<InvEstadoProducto>, IEstadoProductoBlo
{
private IEstadoProductoDao _estadoProductoDao;
public EstadoProductoBlo(IEstadoProductoDao estadoProductoDao)
: base(estadoProductoDao)
{
_estadoProductoDao =estadoProductoDao;
}
}
}
|
using System;
using System.Threading.Tasks;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Epsagon.Dotnet.Core;
using OpenTracing;
using OpenTracing.Util;
using Serilog;
namespace Epsagon.Dotnet.Instrumentation.Handlers {
public abstract class BaseServiceHandler : PipelineHandler, IServiceHandler {
public abstract void HandleAfter(IExecutionContext executionContext, IScope scope);
public abstract void HandleBefore(IExecutionContext executionContext, IScope scope);
protected ITracer tracer = GlobalTracer.Instance;
public override void InvokeSync(IExecutionContext executionContext) {
var name = executionContext.RequestContext.RequestName;
Utils.DebugLogIfEnabled("AWSSDK request invoked, {name}", name);
using (var scope = tracer.BuildSpan(name).StartActive(finishSpanOnDispose: true)) {
BuildSpan(executionContext, scope.Span);
try { HandleBefore(executionContext, scope); } catch (Exception e) { scope.Span.AddException(e); }
base.InvokeSync(executionContext);
try {
HandleAfter(executionContext, scope);
scope.Span.SetTag("event.id", executionContext.ResponseContext.Response.ResponseMetadata.RequestId);
} catch (Exception e) {
scope.Span.SetTag("event.id", executionContext.ResponseContext.Response.ResponseMetadata.RequestId);
scope.Span.AddException(e);
}
}
}
public override Task<T> InvokeAsync<T>(IExecutionContext executionContext) {
var name = executionContext.RequestContext.RequestName;
Utils.DebugLogIfEnabled("AWSSDK request invoked, {name}", name);
using (var scope = tracer.BuildSpan(name).StartActive(finishSpanOnDispose: true)) {
BuildSpan(executionContext, scope.Span);
try { HandleBefore(executionContext, scope); } catch (Exception e) { scope.Span.AddException(e); }
var result = base.InvokeAsync<T>(executionContext).Result;
try {
HandleAfter(executionContext, scope);
scope.Span.SetTag("event.id", executionContext.ResponseContext.Response.ResponseMetadata.RequestId);
} catch (Exception e) {
scope.Span.SetTag("event.id", executionContext.ResponseContext.Response.ResponseMetadata.RequestId);
scope.Span.AddException(e);
}
return Task.FromResult(result);
}
}
private void BuildSpan(IExecutionContext context, ISpan span) {
var resoureType = context?.RequestContext?.ServiceMetaData.ServiceId;
var serviceName = context?.RequestContext?.ServiceMetaData.ServiceId;
var operationName = context?.RequestContext?.RequestName;
var endpoint = context?.RequestContext?.Request?.Endpoint?.ToString();
var region = context?.RequestContext?.ClientConfig?.RegionEndpoint?.SystemName;
var envRegion = Environment.GetEnvironmentVariable("AWS_REGION");
span.SetTag("resource.type", resoureType?.ToLower());
span.SetTag("event.origin", "aws-sdk");
span.SetTag("event.error_code", 0); // OK
span.SetTag("aws.service", serviceName);
span.SetTag("resource.operation", operationName);
span.SetTag("resource.name", serviceName);
span.SetTag("aws.endpoint", endpoint);
span.SetTag("aws.region", envRegion ?? region);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
namespace SDMClasses
{
public class ScoreManager
{
// Caminho para o arquivo: C:/Users/(Nome do usuário)/%appdata%/Roaming
private string _appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Instancia do jogador
private Player _jogador;
// Caminho do arquivo dos placares
private string _filePath;
// Lista de todos os perfis contidos no placar
private List<Player> _jogadores;
// Variavel usada para habilitar os registros no placar
private bool _registrar;
// Getters e setters
public string AppDataPath
{
get { return this._appDataPath; }
}
public Player Jogador
{
get { return this._jogador; }
set { this._jogador = value; }
}
public string FilePath
{
get { return this._filePath; }
}
public List<Player> Jogadores
{
get { return this._jogadores; }
}
public bool Registrar
{
get { return this._registrar; }
set { this._registrar = value; }
}
public ScoreManager(Player P, string FileName)
{
this.Jogador = P;
if (FileName != null)
{
_jogadores = new List<Player>();
Registrar = true;
this._filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Combinando o caminho do roaming com uma pasta SDM, ficaria assim: C:/Users/(Nome do usuário)/%appdata%/roaming/SDM
string aux = Path.Combine(FilePath, "SDM");
// Se o diretório acima não existir, crie um novo
if (!Directory.Exists(aux))
Directory.CreateDirectory(aux);
// Prepara o arquivo: C:/Users/(Nome do usuário)/%appdata%/roaming/SDM/(Nome do arquivo).ssdm para ser lido ou criado"
this._filePath = aux + "/" + FileName + ".ssdm";
this.CreateScoreFile();
}
else
{
throw new ArgumentNullException();
}
}
/// <summary>
/// Cria o arquivo de placares inicial caso o mesmo não exista
/// </summary>
/// <param name="FilePath"></param>
private void CreateScoreFile()
{
// Se o arquivo não existe, cria-lo, caso contrário, leia-o em busca de perfis
if(!File.Exists(FilePath))
{
using(StreamWriter st = File.CreateText(FilePath))
{
st.WriteLine("[Placares]");
}
}
else
{
string Dado = "";
using(StreamReader sr = new StreamReader(File.OpenRead(FilePath)))
{
Dado = sr.ReadLine();
while(Dado != null)
{
Dado = sr.ReadLine();
if(Dado != null && !Dado.Equals("[Placares]"))
{
string[] Split = Dado.Split('=');
try
{
Jogadores.Add(new Player(Split[0], Double.Parse(Split[1])));
}catch(FormatException e)
{
if((MessageBox.Show("Foram encontrados alguns dados corrompidos no placar! Deseja chamar o Liminha para reparar o placar? Se escolher \"não\" o placar não irá funcionar!")) == DialogResult.Yes)
{
RepararArquivoDePlacar();
break;
}
else
{
MessageBox.Show("Placar desativado pelo motivo de haver dados corrompidos!");
Registrar = false;
}
}
}
}
}
}
}
/// <summary>
/// Tenta recuperar o arquivo de placar, reparando ou deletando dados corrompidos
/// </summary>
private void RepararArquivoDePlacar()
{
if (!File.Exists(FilePath))
{
var Dado = "";
var Pontos = 0.0;
var DadosCorrompidos = 0;
// Limpa a lista e começa do zero
Jogadores.Clear();
// Lê todos os dados do arquivo
using (StreamReader sr = new StreamReader(File.OpenRead(FilePath)))
{
Dado = sr.ReadLine();
var DadoCorrompido = false;
while (Dado != null)
{
// Tenta checar por pontuações corrompidas
try
{
Pontos = Double.Parse(Dado.Split('=')[1]);
}
catch (FormatException e)
{
// Tenta corrigir pontuações corrompidas
try
{
Pontos = RemoveLetras(Dado.Split('=')[1]);
}catch(FormatException e2 )
{
// Caso não dê para corrigir, trata-o como dado corrompido
DadoCorrompido = true;
DadosCorrompidos++;
}
}
// Se o dado não estiver mais corrompido adiciona-o a lista
if(!DadoCorrompido)
{
Jogadores.Add(new Player(Dado.Split('=')[0], Pontos));
}
}
}
// Recria o arquivo de placar
using (StreamWriter st = File.AppendText(FilePath))
{
st.WriteLine("[Placares]");
// Testa se há algum dado salvo
if(Jogadores.Count > 0)
{
// Reescreve os dados salvos
foreach(var Jogador in Jogadores)
{
st.WriteLine(Jogador.Nome + "=" + Jogador.Pontuacao);
}
MessageBox.Show("Placar recuperado com êxito! Dados Perdidos: " + DadosCorrompidos + "!", "Placar Recuperado!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// Erro exibido quando todos os dados foram perdidos
MessageBox.Show("Falha ao recuperar os dados! Todos os dados estavam corrompidos, portanto o arquivo de placar foi resetado!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
/// <summary>
/// Tenta remover letras de um número
/// </summary>
/// <returns>O número limpo, sem letras</returns>
public double RemoveLetras(string Numero)
{
var Caracteres = new string[] { "A", "B", "C", "D", "E", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Ç", "~", "´", "-", "_", "!", "?", "`", "{", "[", "}", "]", "(", ")", ":", ";", "$", "*", "'", "\"", "&", "#" };
var NumeroNovo = Numero.ToLower();
foreach(string Caractere in Caracteres)
{
NumeroNovo = NumeroNovo.Replace(Caractere.ToLower(), "");
}
return double.Parse(NumeroNovo);
}
/// <summary>
/// Salva a pontuação do jogador no arquivo de placar
/// </summary>
public void SalvarPontuacao()
{
if (Registrar)
{
string Aux = File.ReadAllText(FilePath);
File.WriteAllText(FilePath, Aux);
using (StreamWriter st = File.AppendText(FilePath))
{
st.WriteLine(Jogador.Nome + "=" + Jogador.Pontuacao);
}
Jogadores.Add(new Player(Jogador.Nome, Jogador.Pontuacao));
}
}
public double AdicionarPontos(double Pontos)
{
if (Registrar)
{
if (!TemJogador())
{
throw new NullReferenceException("Sem jogador adicionado");
}
if (Pontos > 0)
{
Jogador.Pontuacao += Pontos;
return Jogador.Pontuacao;
}
}
return 0;
}
private bool TemJogador()
{
return this.Jogador != null;
}
[Obsolete("Usar metódo GetPlacarOrdenado")]
public string GetAllScores()
{
if(!File.Exists(FilePath))
{
throw new NullReferenceException("Nenhum arquivo de placar encontrado");
}
return File.ReadAllText(FilePath);
}
/// <summary>
/// Retorna um placar ordenado no formato de lista
/// </summary>
/// <returns></returns>
public List<Player> GetPlacarOrdenado()
{
if(!File.Exists(FilePath))
{
throw new NullReferenceException("Nenhum arquivo de placar encontrado");
}
return this.OrdenarPlacar();
}
private List<Player> OrdenarPlacar()
{
return (Jogadores.Count > 1) ? Jogadores.OrderByDescending(o => o.Pontuacao).ToList() : Jogadores;
}
[Obsolete("Não necessário mais")]
/// <summary>
/// Remove os números bugados do placar
/// </summary>
/// <param name="Text"></param>
/// <returns></returns>
public string RemoveNumeros(string Text)
{
return Text.Replace("0", "").Replace("1", "").Replace("2", "").Replace("3", "").Replace("4", "").Replace("5", "").Replace("6", "").Replace("7", "").Replace("8", "").Replace("9", "").Replace(".", ""); ;
}
[Obsolete("Contém bugs que não podem ser corrigidos")]
/// <summary>
/// Retorna um dicionario ordenado do placar, em ordem decrescente
/// </summary>
/// <param name="placar"></param>
/// <returns></returns>
private Dictionary<string, string> OrdenarPlacar(string[] placar)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
int Contador = 1;
// Pega todo conteudo do placar e adiciona no dicionario
foreach(string Line in placar)
{
// Menos essa linha
if(!Line.Equals("[Placares]", StringComparison.OrdinalIgnoreCase))
{
string[] Temp = Line.Split('=');
dictionary.Add(Contador+"."+Temp[0], Temp[1].Replace(" ", ""));
Contador++;
}
}
// Converte o dicionario em uma lista
var List = dictionary.ToList();
// Aranja a lista para ficar em ordem decrescente
List.Sort((value1, value2) => value2.Value.CompareTo(value1.Value));
// Converte de volta em um dicionario
dictionary = List.ToDictionary(pair => pair.Key, pair => pair.Value);
return dictionary;
}
}
}
|
using System;
using UIKit;
using Xamarin.Forms;
using App1.iOS.Interface;
using App1.Interface;
[assembly: Dependency(typeof(CLaunch))]
namespace App1.iOS.Interface
{
public class CLaunch : ILaunch
{
public CLaunch()
{
}
public bool IsInstalled(string sPackageName)
{
return UIApplication.SharedApplication.CanOpenUrl(new Foundation.NSUrl(sPackageName));
}
public void LaunchApp(string sPackageName)
{
UIApplication.SharedApplication.OpenUrl(new Foundation.NSUrl(sPackageName));
}
}
} |
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
public GameObject controlWindow;
public GameObject creditMenu;
public void Start ()
{
Time.timeScale = 1f;
}
public void LoadGame ()
{
SceneManager.LoadScene("Player Selection");
}
public void doControlsMenu()
{
controlWindow.SetActive(true);
}
public void closeControlsMenu()
{
controlWindow.SetActive(false);
}
public void doCreditMenu()
{
creditMenu.SetActive(true);
}
public void closeCreditMenu()
{
creditMenu.SetActive(false);
}
public void ExitGame()
{
Application.Quit();
}
}
|
using RoyT.AStar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Threading;
namespace aoc
{
public class D17
{
const int North = 1;
const int South = 2;
const int West = 3;
const int East = 4;
private Dictionary<int, Vector2> HeadingToVector = new Dictionary<int, Vector2>
{
{ North, (0, -1) },
{ South, (0, 1) },
{ West, (-1, 0) },
{ East, (1, 0) },
};
public object Answer()
{
var code = File.ReadAllText("17.in").Split(',').Select(s => BigInteger.Parse(s)).ToArray();
code[0] = 2;
var computer = new IntCodeSync(code);
int rows = 1;
while (rows < 36)
{
var val = (char)computer.Run().Value;
Console.Write(val);
if (val == '\n') rows++;
}
try
{
// hand-made
var main = "A,A,B,C,B,C,B,C,C,A\n";
var a = "R,8,L,4,R,4,R,10,R,8\n";
var b = "L,12,L,12,R,8,R,8\n";
var c = "R,10,R,4,R,4\n";
foreach (var ch in main.ToCharArray())
{
var res = computer.Run(ch);
}
var o = computer.Run();
while (o != null)
{
Console.Write((char)o);
o = computer.Run();
}
foreach (var ch in a.ToCharArray())
{
computer.Run(ch);
}
o = computer.Run();
while (o != null)
{
Console.Write((char)o);
o = computer.Run();
}
foreach (var ch in b.ToCharArray())
{
computer.Run(ch);
}
o = computer.Run();
while (o != null)
{
Console.Write((char)o);
o = computer.Run();
}
o = computer.Run();
while (o != null)
{
Console.Write((char)o);
o = computer.Run();
}
foreach (var ch in c.ToCharArray())
{
computer.Run(ch);
}
o = computer.Run();
while (o != null)
{
Console.Write((char)o);
o = computer.Run();
}
computer.Run('n');
computer.Run('\n');
Console.Clear();
Console.SetCursorPosition(0, 0);
computer.Run();
rows = 1;
while (true)
{
var val = (long?)computer.Run().GetValueOrDefault(0);
if (val > 0xff) return val;
if (val == '\n')
rows++;
Console.Write((char)val);
if (rows % 34 == 0)
{
Console.ReadLine();
Console.Clear();
Console.SetCursorPosition(0, 0);
val = (int?)computer.Run();
if (val > 0xFF) return val;
rows = 1;
}
}
}
catch (ComputerHaltedException)
{
}
return "error";
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ZiZhuJY.Web.UI.Utility;
namespace ZiZhuJY.Web.UI.UnitTest.Specs
{
[TestClass]
public class ResourceHelperSpec
{
[TestMethod]
public void EscapeTheUnescapedChar()
{
Assert.AreEqual(@"test no c", ResourceHelper.EscapeTheUnescapedChar(@"test no c", '\''));
Assert.AreEqual(@"test unsafe \'", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe '", '\''));
Assert.AreEqual(@"test safe \'", ResourceHelper.EscapeTheUnescapedChar(@"test safe \'", '\''));
Assert.AreEqual(@"test unsafe \\\'", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\'", '\''));
Assert.AreEqual(@"test safe \\\'", ResourceHelper.EscapeTheUnescapedChar(@"test safe \\\'", '\''));
Assert.AreEqual(@"test unsafe \\\\\'", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\'", '\''));
Assert.AreEqual(@"test safe \\\\\'", ResourceHelper.EscapeTheUnescapedChar(@"test safe \\\\\'", '\''));
Assert.AreEqual(@"test unsafe \\\\\\\'", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\\\'", '\''));
Assert.AreEqual(@"test unsafe \\\\\\\' 2nd unsafe \\\' 3rd unsafe \' 4th safe \'", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\\\' 2nd unsafe \\' 3rd unsafe ' 4th safe \'", '\''));
Assert.AreEqual(@"\'", ResourceHelper.EscapeTheUnescapedChar(@"'", '\''));
Assert.AreEqual(@"\'", ResourceHelper.EscapeTheUnescapedChar(@"\'", '\''));
Assert.AreEqual(@"\' more content", ResourceHelper.EscapeTheUnescapedChar(@"\' more content", '\''));
Assert.AreEqual(@"\' more content", ResourceHelper.EscapeTheUnescapedChar(@"' more content", '\''));
}
[TestMethod]
public void EscapeTheUnescapedUnicodeChars()
{
Assert.AreEqual(@"test no c", ResourceHelper.EscapeTheUnescapedChar(@"test no c", @"\u0027"));
Assert.AreEqual(@"test unsafe \\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \u0027", @"\u0027"));
Assert.AreEqual(@"test safe \\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test safe \\u0027", @"\u0027"));
Assert.AreEqual(@"test unsafe \\\\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\u0027", @"\u0027"));
Assert.AreEqual(@"test safe \\\\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test safe \\\\u0027", @"\u0027"));
Assert.AreEqual(@"test unsafe \\\\\\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\\u0027", @"\u0027"));
Assert.AreEqual(@"test safe \\\\\\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test safe \\\\\\u0027", @"\u0027"));
Assert.AreEqual(@"test unsafe \\\\\\\\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\\\\u0027", @"\u0027"));
Assert.AreEqual(@"test unsafe \\\\\\\\u0027 2nd unsafe \\\\u0027 3rd unsafe \\u0027 4th safe \\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\\\\u0027 2nd unsafe \\\u0027 3rd unsafe \u0027 4th safe \\u0027", @"\u0027"));
Assert.AreEqual(@"\\u0027", ResourceHelper.EscapeTheUnescapedChar(@"\u0027", @"\u0027"));
Assert.AreEqual(@"\\u0027", ResourceHelper.EscapeTheUnescapedChar(@"\\u0027", @"\u0027"));
Assert.AreEqual(@"\\u0027 more content", ResourceHelper.EscapeTheUnescapedChar(@"\\u0027 more content", @"\u0027"));
Assert.AreEqual(@"\\u0027 more content", ResourceHelper.EscapeTheUnescapedChar(@"\u0027 more content", @"\u0027"));
Assert.AreEqual(
@"test unsafe \\\\\\\\u0027 2nd unsafe \\\\u0027 3rd unsafe \\u0027 4th safe \\u0027test unsafe \\\\\\\' 2nd unsafe \\\' 3rd unsafe \' 4th safe \'",
ResourceHelper.EscapeTheUnescapedChar(
@"test unsafe \\\\\\\u0027 2nd unsafe \\\u0027 3rd unsafe \u0027 4th safe \\u0027test unsafe \\\\\\\' 2nd unsafe \\\' 3rd unsafe \' 4th safe \'",
@"\u0027"));
}
[TestMethod]
public void EscapeTheUnescapedCharAndUnicodeChars()
{
//Assert.AreEqual(@"test unsafe \\\\\\\\u0027 2nd unsafe \\\\u0027 3rd unsafe \\u0027 4th safe \\u0027test unsafe \\\\\\\' 2nd unsafe \\\' 3rd unsafe \' 4th safe \'", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\\\\u0027 2nd unsafe \\\u0027 3rd unsafe \u0027 4th safe \\u0027test unsafe \\\\\\' 2nd unsafe \\' 3rd unsafe ' 4th safe \'", '\''));
//Assert.AreEqual(@"test unsafe \\\\\\\' 2nd unsafe \\\' 3rd unsafe \' 4th safe \'test unsafe \\\\\\\\u0027 2nd unsafe \\\\u0027 3rd unsafe \\u0027 4th safe \\u0027", ResourceHelper.EscapeTheUnescapedChar(@"test unsafe \\\\\\' 2nd unsafe \\' 3rd unsafe ' 4th safe \'test unsafe \\\\\\\u0027 2nd unsafe \\\u0027 3rd unsafe \u0027 4th safe \\u0027", '\''));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic.Categories;
using NopSolutions.NopCommerce.BusinessLogic.Colors;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Products;
namespace NopSolutions.NopCommerce.Web.Modules
{
public partial class ColorsFilterControl : BaseNopUserControl
{
public List<ColorItem> Colors { get; set; }
public string CategoryName { get; set; }
protected string UrlToRedirect
{
get
{
string currentUrl = CommonHelper.GetThisPageURL(false);
bool first = true;
for (int i = 0; i < Request.QueryString.Keys.Count; i++)
{
string key = Request.QueryString.Keys[i];
if (key != null && key != "Цвет" && key != "CategoryID")
{
currentUrl = String.Format("{0}{1}{2}={3}", currentUrl, first ? "?" : "&",
key, CommonHelper.QueryStringInt(key));
first = false;
}
}
return currentUrl;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (!String.IsNullOrEmpty(CategoryName))
{
BindData();
}
else
{
this.Visible = false;
}
}
protected void onclick(object sender, EventArgs e)
{
Response.Redirect(this.UrlToRedirect);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BindData()
{
if (Colors != null && Colors.Count > 0)
{
rptColors.DataSource = Colors;
rptColors.DataBind();
}
else
{
this.Visible = false;
}
}
}
} |
using MaybeSharp;
using MaybeSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Maybe.Sharp.Tests
{
public class MaybeLinqExtensionsTests
{
[Fact]
public void Maybe_Where_ConditionOnEmptyIsFalse()
{
var maybeName = Maybe<string>.Nothing;
var result = from n in maybeName
where n.StartsWith("slippery", StringComparison.OrdinalIgnoreCase)
select n;
Assert.True(result.IsEmpty);
}
[Fact]
public void Maybe_Where_ConditionOnNonEmptyIsEvaluated()
{
var maybeName = (Maybe<string>)"Slippery Jim DiGriz";
var result = from n in maybeName
where n.StartsWith("slippery", StringComparison.OrdinalIgnoreCase)
select n;
Assert.False(result.IsEmpty);
Assert.Equal(maybeName.Value, result.Value);
maybeName = (Maybe<string>)"Slippery Jim DiGriz";
result = from n in maybeName
where n.StartsWith("Dr", StringComparison.OrdinalIgnoreCase)
select n;
Assert.True(result.IsEmpty);
}
[Fact]
public void Maybe_Where_ThrowsOnNullPredicate()
{
var maybeName = (Maybe<string>)"Slippery Jim DiGriz";
Assert.Throws<ArgumentNullException>("predicate", () => maybeName.Where(null));
}
[Fact]
public void Maybe_Select_NonEmptySelectsValue()
{
var maybeName = (Maybe<string>)"Sippery Jim DiGriz";
var result = from name in maybeName
select name;
Assert.False(result.IsEmpty);
Assert.Equal(maybeName.Value, result);
}
[Fact]
public void Maybe_Select_EmptyReturnsEmptyMaybe()
{
var maybeName = Maybe<string>.Nothing;
var result = from name in maybeName
select name;
Assert.True(result.IsEmpty);
}
[Fact]
public void Maybe_Select_ThrowsOnNullMaybePredicate()
{
var maybeName = Maybe<string>.Nothing;
Func<string, Maybe<string>> predicate = null;
Assert.Throws<ArgumentNullException>("predicate", () => maybeName.Select(predicate));
}
[Fact]
public void Maybe_Select_ThrowsOnNullTPredicate()
{
var maybeName = Maybe<string>.Nothing;
Func<string, string> predicate = null;
Assert.Throws<ArgumentNullException>("predicate", () => maybeName.Select(predicate));
}
[Fact]
public void IEnumerableOfMaybe_Select_ConvertsToEnumerableOfMaybeTResult()
{
var values = new Maybe<int>[] { 1, 2, Maybe<int>.Nothing, 4, Maybe<int>.Nothing, Maybe<int>.Nothing, 7 };
List<Maybe<int>> results = System.Linq.Enumerable.ToList(values.Select<int, int>((mi) => mi + 2));
Assert.NotNull(results);
Assert.Equal(7, results.Count);
Assert.Equal(3, results[0].Value);
Assert.Equal(4, results[1].Value);
Assert.True(results[2].IsEmpty);
Assert.Equal(6, results[3].Value);
Assert.True(results[4].IsEmpty);
Assert.True(results[5].IsEmpty);
Assert.Equal(9, results[6].Value);
}
[Fact]
public void IEnumerableOfMaybe_Select_ReturnsEmptySetWhenSourceNull()
{
Maybe<int>[] values = null;
List<Maybe<int>> results = System.Linq.Enumerable.ToList(values.Select<int, int>((mi) => mi + 2));
Assert.NotNull(results);
Assert.Empty(results);
}
[Fact]
public void IEnumerableOfMaybe_Select_ThrowsWhenPredicateNull()
{
var values = new Maybe<int>[] { 1, 2, Maybe<int>.Nothing, 4, Maybe<int>.Nothing, Maybe<int>.Nothing, 7 };
Assert.Throws<ArgumentNullException>
(
"predicate",
() => { List<Maybe<int>> results = System.Linq.Enumerable.ToList(values.Select<int, int>(null)); }
);
}
[Fact]
public void Maybe_SelectMany_WithConcatEmptyIsEmpty()
{
var maybeFirstName = (Maybe<string>)"Jim";
var maybeSurname = Maybe<string>.Nothing;
var fullName = from firstName in maybeFirstName
from surname in maybeSurname
select firstName + " " + surname;
Assert.True(fullName.IsEmpty);
}
[Fact]
public void Maybe_SelectMany_WithConcatNonEmptiesProducesResult()
{
var maybeFirstName = (Maybe<string>)"Jim";
var maybeSurname = (Maybe<string>)"DiGriz";
var fullName = from firstName in maybeFirstName
from surname in maybeSurname
select firstName + " " + surname;
Assert.Equal(maybeFirstName.Value + " " + maybeSurname.Value, fullName);
}
[Fact]
public void Maybe_SelectMany_ThrowsWithNullConverterFunc()
{
var maybeFirstName = (Maybe<string>)"Jim";
var maybeSurname = (Maybe<string>)"DiGriz";
Func<string, Maybe<string>> converter = null;
Func<string, string, string> combiner = (s1, s2) => s1 + s2;
Assert.Throws<ArgumentNullException>("converter", () => maybeFirstName.SelectMany(converter, combiner));
}
[Fact]
public void Maybe_SelectMany_ThrowsWithNullCombinerFunc()
{
var maybeFirstName = (Maybe<string>)"Jim";
var maybeSurname = (Maybe<string>)"DiGriz";
Func<string, Maybe<string>> converter = (s1) => s1;
Func<string, string, string> combiner = null;
Assert.Throws<ArgumentNullException>("combiner", () => maybeFirstName.SelectMany(converter, combiner));
}
[Fact]
public void Maybe_SelectNonEmpty_SkipsEmptyResults()
{
var items = new List<Maybe<int>>();
for (int cnt = 0; cnt < 100; cnt++)
{
if (cnt % 2 == 0)
items.Add(new Maybe<int>(cnt));
else
items.Add(Maybe<int>.Nothing);
}
var results = items.SelectNonempty<int, int>((m) => m % 5 == 0 ? Maybe<int>.Nothing : m);
Assert.Equal(40, System.Linq.Enumerable.Count(results));
foreach (var r in results)
{
Assert.False(r.IsEmpty);
Assert.False(r.Value % 2 != 0);
Assert.False(r.Value % 5 == 0);
}
}
[Fact]
public void Maybe_SelectNonEmpty_ReturnsEmptySetWhenSourceNull()
{
List<Maybe<int>> items = null;
var results = items.SelectNonempty<int, int>((m) => m % 5 == 0 ? Maybe<int>.Nothing : m);
Assert.False(System.Linq.Enumerable.Any(results));
}
[Fact]
public void Maybe_SelectNonEmpty_ThrowsWhenPredicateNull()
{
var items = new List<Maybe<int>>();
for (int cnt = 0; cnt < 100; cnt++)
{
if (cnt % 2 == 0)
items.Add(new Maybe<int>(cnt));
else
items.Add(Maybe<int>.Nothing);
}
Assert.Throws<ArgumentNullException>(
"predicate",
() =>
{
var results = items.SelectNonempty<int, int>(null);
}
);
}
}
} |
namespace L7.Domain
{
public interface IShopingCartRepository : IReadRepository<ShoppingCart>, IWriteRepository<ShoppingCart>
{
}
} |
namespace Employee
{
abstract class Employee
{
// Private Parameters
protected string firstName = "not given", lastName = "Not given";
protected char gender = 'U';
protected int dependents = 0;
protected double annualSalary = 20000;
protected static int numEmployees = 0;
protected string employeeType;
// Constants
private const double MIN_SALARY = 20000;
private const double MAX_SALARY = 100000;
private const string DEFAULT_NAME = "Not given";
private const char DEFAULT_GENDER = 'U';
private const int MIN_DEPENDENTS = 0;
private const int MAX_DEPENDENTS = 10;
private const string DEFAULT_EMPLOYEE = "Generic Employee";
// Here is a call to the Benefit class so the output can be added to the ToString public override
protected Benefit benefits;
#region Constructors
public Employee()
{
EmployeeType = DEFAULT_EMPLOYEE;
benefits = new Benefit(); //Instantiates the Benefit class
numEmployees++;
}
public Employee(string firstName, string lastName, char gender, int dependents, double annualSalary, string employeeType, Benefit benefits)
{
FirstName = firstName; //Here we setup the overloaded constructor
LastName = lastName;
Gender = gender;
Dependents = dependents;
AnnualSalary = annualSalary;
Benefits = benefits; //Adding the Benefits argument
numEmployees++;
}
public Employee(string employeeType) : this()
{
EmployeeType = employeeType;
}
// Here is our abstract method CalculateNetPay
public abstract double CalculateNetPay();
#endregion
#region Properties
public string EmployeeName
{
get
{
return FirstName + "" + LastName;
}
}
public string EmployeeType
{
get
{
return employeeType;
}
set
{
if (string.IsNullOrEmpty(value))
employeeType = DEFAULT_EMPLOYEE;
else
employeeType = value;
}
}
public virtual double CalculateWeeklyPay()
{
return AnnualSalary / 52.0;
}
public double CalculateWeeklyPay(double employeeSalary)
{
AnnualSalary = employeeSalary;
return CalculateWeeklyPay();
}
public static int NumEmployees
{
get { return numEmployees; }
}
public string FirstName
{
get { return firstName; }
set
{
if (string.IsNullOrEmpty(value))
firstName = DEFAULT_NAME;
else
firstName = value;
}
}
public string LastName
{
get { return lastName; }
set
{
if (string.IsNullOrEmpty(value))
lastName = DEFAULT_NAME;
else
lastName = value;
}
}
public char Gender
{
get { return gender; }
set
{
if (value == 'f' || value == 'F' || value == 'm' || value == 'M')
gender = value;
else
gender = DEFAULT_GENDER;
}
}
public int Dependents
{
get { return dependents; }
set
{
if (value >= MIN_DEPENDENTS && value <= MAX_DEPENDENTS)
dependents = value;
else if (value < MIN_DEPENDENTS)
dependents = MIN_DEPENDENTS;
else
dependents = MAX_DEPENDENTS;
}
}
public double AnnualSalary
{
get { return annualSalary; }
set
{
if (value >= MIN_SALARY && value <= MAX_SALARY)
annualSalary = value;
else if (value < MIN_SALARY)
annualSalary = MIN_SALARY;
else
annualSalary = MAX_SALARY;
}
}
public Benefit Benefits
{
get { return benefits; }
set
{
if (value == null)
benefits = new Benefit();
else
benefits = value;
}
}
#endregion
public override string ToString()
{
string output;
output = "============ Employee Information ============\n";
output += "\n\t Type:\t" + EmployeeType;
output += "\n\t Name:\t" + firstName + " " + lastName;
output += "\n\t Gender:\t" + gender;
output += "\n\t Dependents:\t" + Dependents;
output += "\n\t Annual Salary:\t" + AnnualSalary.ToString("C2");
output += "\n\t Weekly Pay:\t" + CalculateWeeklyPay().ToString("C2");
output += "\n\t Net Pay:\t" + CalculateNetPay().ToString("C2");
output += Benefits.ToString();
return output;
}
}
}
|
using System;
namespace LTP4C2.Models
{
public abstract class BaseModel
{
public BaseModel()
{
Id = new Guid();
}
public Guid Id{ get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class MovementPath1 : MonoBehaviour
{
//public enum PathTypes
//{
// linear,
// loop
// }
//public PathTypes PathType;
public int movementDirection = 1;
public int movingTo = 0;
public Transform[] PathSequence;
List<GameObject> Seq;
public GameObject[] Rooms;
public GameObject[] Doors;
public void Start()
{
//string sentence = "J#K";
string sentence = PlayerPrefs.GetString ("path_seq");
char[] letters = sentence.ToCharArray();
int x = 0;
PathSequence = new Transform[letters.Length];
for(var i = 0; i < letters.Length; i++)
{
x = (int)letters[i] - 65;
//Debug.Log(x);
if(i%2 == 0)
{
PathSequence[i] = Rooms[x].GetComponent<Transform>();
}
else
{
if((letters[i-1] == 'A' && letters[i+1] == 'C') || (letters[i-1] == 'C' && letters[i+1] == 'A'))
PathSequence[i] = Doors[0].GetComponent<Transform>();
else if((letters[i-1] == 'A' && letters[i+1] == 'E') || (letters[i-1] == 'E' && letters[i+1] == 'A'))
PathSequence[i] = Doors[1].GetComponent<Transform>();
else if((letters[i-1] == 'B' && letters[i+1] == 'C') || (letters[i-1] == 'C' && letters[i+1] == 'B'))
PathSequence[i] = Doors[2].GetComponent<Transform>();
else if((letters[i-1] == 'C' && letters[i+1] == 'H') || (letters[i-1] == 'H' && letters[i+1] == 'C'))
PathSequence[i] = Doors[3].GetComponent<Transform>();
else if((letters[i-1] == 'G' && letters[i+1] == 'H') || (letters[i-1] == 'H' && letters[i+1] == 'G'))
PathSequence[i] = Doors[4].GetComponent<Transform>();
else if((letters[i-1] == 'F' && letters[i+1] == 'G') || (letters[i-1] == 'G' && letters[i+1] == 'F'))
PathSequence[i] = Doors[5].GetComponent<Transform>();
else if((letters[i-1] == 'H' && letters[i+1] == 'I') || (letters[i-1] == 'I' && letters[i+1] == 'H'))
PathSequence[i] = Doors[6].GetComponent<Transform>();
else if((letters[i-1] == 'I' && letters[i+1] == 'J') || (letters[i-1] == 'J' && letters[i+1] == 'I'))
PathSequence[i] = Doors[7].GetComponent<Transform>();
else if((letters[i-1] == 'E' && letters[i+1] == 'J') || (letters[i-1] == 'J' && letters[i+1] == 'E'))
PathSequence[i] = Doors[8].GetComponent<Transform>();
else if((letters[i-1] == 'J' && letters[i+1] == 'K') || (letters[i-1] == 'K' && letters[i+1] == 'J'))
PathSequence[i] = Doors[9].GetComponent<Transform>();
else if((letters[i-1] == 'G' && letters[i+1] == 'K') || (letters[i-1] == 'K' && letters[i+1] == 'G'))
PathSequence[i] = Doors[10].GetComponent<Transform>();
}
}
}
public void OnDrawGizmos()
{
if(PathSequence == null || PathSequence.Length <2)
{
return; //no points
}
for(var i = 1; i < PathSequence.Length; i++)
{
Gizmos.DrawLine(PathSequence[i-1].position, PathSequence[i].position);
}
}
public IEnumerator<Transform> GetNextPathPoint()
{
if(PathSequence == null || PathSequence.Length <1)
{
yield break;
}
while(true)
{
yield return PathSequence[movingTo];
if(PathSequence.Length == 1)
{
continue;
}
if(movingTo <= 0)
{
movementDirection = 1;
}
else if(movingTo >= PathSequence.Length - 1)
{
movementDirection = 0;
Time.timeScale = 0;
}
movingTo = movingTo + movementDirection;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace VAOCA_DIARS.Models
{
public class Curso
{
public int Id { get; set; }
public string Codigo { get; set; }
public string Nombre { get; set; }
public int Precio { get; set; }
public string Horas { get; set; }
public int IdProfesor { get; set; }
public Profesor profesor { get; set; }
public List<DMatricula> dMatriculas { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.IO;
using System.Configuration;
using System.Collections.Specialized;
namespace poiLoader
{
public partial class ItemParseMain : Form
{
//char has to be gobal for this form
List<Character> mychars = new List<Character>();
string path = "";
bool onlyclearonce = false;
string localpath = "";
public ItemParseMain()
{
InitializeComponent();
}
private void ItemParseMain_Load(object sender, EventArgs e)
{
localpath = Directory.GetCurrentDirectory();
localpath += @"\config.txt";
rname.Checked = true;
if (!File.Exists(localpath))
{
using (StreamWriter sw = File.CreateText(localpath)) { }
MessageBox.Show("please enter mabinogi path");
}
else
{
path = File.ReadLines(localpath).First();
Console.WriteLine(localpath);
}
;
}
private void tsearchbox_Click(object sender, EventArgs e)
{
if (!onlyclearonce)
{
tsearchbox.Clear();
onlyclearonce = true;
}
}
private void bsearch_Click(object sender, EventArgs e)
{
if (mychars.Count != 0)
{
mychars.Clear();
}
foreach (string file in Directory.EnumerateFiles(path, "*.txt"))
{
Readitemfile.readitemfile(mychars, file);
}
string search = tsearchbox.Text.ToLower();
titemlist.Text = "";
List<Character> charwithitem = new List<Character>();
if (rname.Checked) {
for (int i = 0; i < mychars.Count; i++)
{
if (mychars[i].hasitem(search))
{
charwithitem.Add(mychars[i]);
}
}
foreach (Character chara in charwithitem)
{
Console.WriteLine(chara.Charname);
titemlist.Text += chara.Charname;
if (!chara.Charname.Contains("Bank"))
{
titemlist.Text += "\t(summon command, only works on pets) \t\t summon " + chara.Charname + "!";
}
titemlist.Text += "\r\n";
titemlist.Text += "=========================================================================\r\n\r\n";
foreach (var item in chara.MyList)
{
string name = item.name.ToLower();
if (item.name.Contains(search))
{
titemlist.Text += "Item name: " + item.name;
titemlist.Text += "\r\n";
titemlist.Text += "Class id: " + item.classid.ToString();
titemlist.Text += "\r\n";
titemlist.Text += "item coords = x:" + item.xpos + " y:" + item.ypos;
titemlist.Text += "\r\n\r\n\r\n";
}
}
}
}
if (rreforge.Checked)
{
for (int i = 0; i < mychars.Count; i++)
{
if (mychars[i].hasreforge(search))
{
charwithitem.Add(mychars[i]);
}
}
foreach (Character chara in charwithitem)
{
Console.WriteLine(chara.Charname);
titemlist.Text += chara.Charname;
if (!chara.Charname.Contains("Bank"))
{
titemlist.Text += "\t(summon command, only works on pets) \t\t summon " + chara.Charname + "!";
}
titemlist.Text += "\r\n";
titemlist.Text += "=========================================================================\r\n\r\n";
foreach (var item in chara.MyList)
{
if (item.hasreforge(search))
{
titemlist.Text += "Item name: " + item.name;
titemlist.Text += "\r\n";
titemlist.Text += "Class id: " + item.classid.ToString();
titemlist.Text += "\r\n";
titemlist.Text += "item coords = x:" + item.xpos + " y:" + item.ypos;
titemlist.Text += "\r\n";
titemlist.Text += "item reforges = \r\n";
foreach (string reforge in item.reforges)
{
titemlist.Text += "\t" + reforge + "\r\n";
}
titemlist.Text += "\r\n\r\n\r\n";
}
}
}
}
}
private void Close_Click(object sender, EventArgs e)
{
}
private void bsave_Click(object sender, EventArgs e)
{
FolderBrowserDialog diag = new FolderBrowserDialog();
if (diag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string folder = diag.SelectedPath; //selected folder path
path = folder;
path += @"\SavedItems\";
File.WriteAllText(localpath, path);
foreach (string file in Directory.EnumerateFiles(path, "*.txt"))
{
Console.WriteLine(file);
Readitemfile.readitemfile(mychars, file);
}
}
path = File.ReadLines(localpath).First();
Console.WriteLine(localpath);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Tsettings_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true) {
}
}
private void ssavetofile_Click(object sender, EventArgs e)
{
string savefile = Directory.GetCurrentDirectory();
savefile += @"/output.txt";
File.WriteAllText(savefile, titemlist.Text);
MessageBox.Show("saved output to (output.txt) opening file in text editor");
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
FileName = savefile,
UseShellExecute = true,
Verb = "open"
});
}
}
}
|
using System;
namespace ReadyGamerOne.Rougelike.Person
{
[AttributeUsage(AttributeTargets.Class)]
public class UsePersonControllerAttribute:System.Attribute
{
public Type controllerType;
public UsePersonControllerAttribute(Type controllerType)
{
this.controllerType = controllerType;
}
}
} |
/*
* Created: 2.2.2016
* Authors: Albert Kuusjärvi
*
*Tehtävä 1 - Tiedostoon kirjoittaminen ja lukeminen
*Tee ohjelma, joka kirjoittaa käyttäjän antamat merkkijonot tiedostoon (lopetusehdon voit päättää itse) ja sulje tiedosto.
*Avaa tämän jälkeen tiedosto lukemista varten ja tulosta näyttölaitteelle tiedoston sisältö riveittäin.
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace T1
{
class Program
{
static void Main(string[] args)
{
string line = null;
StreamWriter outputFile = new StreamWriter(@"d:\K2021\Olio\Demo07\text.txt");
//käyttäjältä kysytään rivejä
do
{
Console.Write("Give a text line (enter stops) : ");
line = Console.ReadLine();
outputFile.WriteLine(line); //kirjoitetaan levylle!
} while (line.Length!=0);
//suljetaan tiedosto
outputFile.Close();
try{
//avaa tiedosto
string[] lines = File.ReadAllLines(@"d:\K2021\Olio\Demo07\text.txt");
//näytä sisältö
foreach (string line2 in lines)
{
Console.WriteLine(line2);
}
}catch (FileNotFoundException)
{
Console.WriteLine("File not found!");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace cancerTIC
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D test;
Vector2 spritePos = Vector2.Zero;
PhysicsObject obj1, obj2;
PhysicsObject[] obj;
GamePadInput input = new GamePadInput(PlayerIndex.One);
KeyboardInput kinput = new KeyboardInput();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
test = Content.Load<Texture2D>("stickperson");
AnimatedSprite sprite1 = new AnimatedSprite(test, 30, 140, 3, true, 33);
sprite1.Position = new Vector2(200, 0);
obj1 = new PhysicsObject(sprite1, true, true, 0);
AnimatedSprite sprite2 = new AnimatedSprite(test, 500, 40, 1);
sprite2.Position = new Vector2(150, 250);
obj2 = new PhysicsObject(sprite2, false, false, 1);
obj = new PhysicsObject[2] { obj1, obj2 };
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
input.Update();
kinput.Update();
GamePadButtonEvent[] events = input.EventsInLastUpdate();
if (events[(int)ButtonID.A].Event == ButtonEvent.Pressed)
Exit();
if (kinput.KeyDown(Keys.A))
obj1.Velocity = new Vector2(-50, obj1.Velocity.Y);
else if (kinput.KeyDown(Keys.D))
obj1.Velocity = new Vector2(50, obj1.Velocity.Y);
else
obj1.Velocity = new Vector2(0, obj1.Velocity.Y);
if (kinput.GetKeyEvent(Keys.Space) == ButtonEvent.Pressed)
obj1.Velocity += new Vector2(0, -100);
obj1.Update(gameTime, obj);
obj2.Update(gameTime, obj);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue); //Cleans screen, turns it blue
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
spriteBatch.Draw(obj1.Sprite.Texture, obj1.Sprite.Position, obj1.Sprite.SourceRect, Color.White);
spriteBatch.Draw(obj2.Sprite.Texture, obj2.Sprite.Position, obj2.Sprite.SourceRect, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
|
using System;
namespace NumberGame
{
class Program
{
static void StartSequence()
{
int length, product;
decimal quotient;
int[] array;
//Prompt user for input
Console.WriteLine("Welcome to NumberGame! Let's crunch some numbers!");
Console.Write("Please enter a number greater than zero: ");
string input = Console.ReadLine();
//Convert user input to int
try
{
length = Convert.ToInt32(input);
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Continuing with default value 5");
length = 5;
}
//Create new int array that is the size the user inputted
try
{
array = new int[length];
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Continuing with default value 5");
array = new int[5];
}
//Call populate using the array
try
{
array = Populate(array);
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Populating array with random values...");
Random rng = new Random();
for (int i = 0; i < array.Length; i++)
{
if (array[i] == 0) array[i] = rng.Next(20, 100);
}
}
//Get the sum with the GetSum method using the populated array
int sum = GetSum(array);
//Get the product with the GetProduct method using the populated array and the sum
try
{
product = GetProduct(array, sum);
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Using first array element for product...");
product = sum * array[0];
}
//Get the quotient using the GetQuotient method using the product
try
{
quotient = GetQuotient(product);
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Using first array element as divisor...");
quotient = Decimal.Divide(product, array[0]);
}
//Display the results to the console
Console.WriteLine($"Your array size: {length}");
Console.WriteLine($"Your array: {string.Join(", ", array)}");
Console.WriteLine($"The sum of these numbers is {sum}");
Console.WriteLine($"{sum} * {product / sum} = {product}");
if (quotient != 0M) Console.WriteLine($"{product} / {product / quotient} = {quotient}");
else Console.WriteLine($"{product} / 0 = infinity");
}
static int[] Populate(int[] array)
{
string input;
//Iterate through the array, prompting the user for input each time
for (int i = 0; i < array.Length; i++)
{
Console.Write($"Please enter a number ({i + 1} of {array.Length}): ");
//Convert user input to an integer (store the response into a string first)
input = Console.ReadLine();
//Add the number to the array
array[i] = Convert.ToInt32(input);
}
//Return the populated array
return array;
}
static int GetSum(int[] array)
{
//declare an int variable named sum
int sum = 0;
//iterate through the array, adding each number to the sum
foreach (int num in array)
{
sum += num;
}
//if the sum is less than 20, throw an exception
if (sum < 20) throw new Exception($"Value of {sum} is too low");
//return sum
return sum;
}
static int GetProduct(int[] array, int sum)
{
string input;
int index, product;
//prompt the user for numeric input between 1 and the arrays length
Console.Write($"Pick a number between 1 and {array.Length}: ");
input = Console.ReadLine();
index = Convert.ToInt32(input) - 1;
//multiply sum by number at given index in array
if (index < 0 || index >= array.Length) throw new IndexOutOfRangeException($"{index + 1} is not a number between 1 and {array.Length}!");
else product = sum * array[index];
//return product
return product;
}
static decimal GetQuotient(int product)
{
string input;
int divisor;
decimal quotient;
//prompt the user to enter a number to divide the product by (display the product)
Console.Write($"Enter a number to divide {product} by: ");
//retrieve input and convert
input = Console.ReadLine();
divisor = Convert.ToInt32(input);
//divide the product by the inputted number
try
{
quotient = Decimal.Divide(product, divisor);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
quotient = 0M;
}
//return the quotient
return quotient;
}
static void Main(string[] args)
{
try
{
StartSequence();
}
catch (Exception ex)
{
Console.WriteLine("Oops! Something went wrong!");
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Thank you for playing!");
}
}
}
}
|
using System;
namespace Koek
{
/// <summary>
/// A generic validation exception.
/// </summary>
/// <remarks>
/// The exception only carries one message about a validation failure. In theory, you might have an object with
/// multiple invalid fields but reporting all such fields on an object is almost never necessary. Therefore,
/// carrying multiple failures is not supported by this exception, for simplicity.
/// </remarks>
public class ValidationException : Exception
{
public ValidationException()
{
}
public ValidationException(string message) : base(message)
{
}
public ValidationException(string message, Exception inner) : base(message, inner)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BusinessLogic.Common;
using BusinessLogic;
using DataAccess;
using MediathekClient.Common;
using BusinessLogic.Exceptions;
namespace MediathekClient.Forms
{
public partial class FrmCustomerManager : FrmDlgBase
{
#region Fields
/// <summary>
/// The current session
/// </summary>
private SessionInfo session = null;
/// <summary>
/// Bussines logic handler class
/// </summary>
private BusinessLogicHandler bl = new BusinessLogicHandler();
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public FrmCustomerManager()
{
InitializeComponent();
}
/// <summary>
/// Constructor with session initalization
/// </summary>
/// <param name="session">The current session</param>
public FrmCustomerManager(SessionInfo session)
: this()
{
this.session = session;
}
#endregion
#region Methods
/// <summary>
/// Fill the listbox with all users that are not deleted
/// </summary>
private void FillCustomerList()
{
// cleanup
lbCustomers.Items.Clear();
// get new items
IList<User> customerList =
bl.GetUsersNotDeleted();
foreach (User customer in customerList)
{
lbCustomers.Items.Add(customer.UserId);
}
}
/// <summary>
/// Displays the data for the currently selected customer
/// </summary>
private void DisplaySelectedCustomer()
{
// clear old data
ClearCustomerData();
// load new data by selected ID
if (lbCustomers.SelectedItems.Count == 1)
{
int customerId = (int)this.lbCustomers.SelectedItem;
try
{
User customer =
bl.GetUserByIdIncludeTitle(customerId);
// select correct title
foreach (GenericIntStringItem item in this.cbTitles.Items)
{
if (customer.Title != null &&
item.IntVal == customer.Title.TitleId)
{
this.cbTitles.SelectedItem = item;
break;
}
}
// fill properties
this.txtCity.Text = customer.City;
this.txtCountry.Text = customer.CountryIso;
this.txtEmail.Text = customer.Email;
this.txtFirstname.Text = customer.Firstname;
this.txtPassword.Text = customer.Password;
this.txtStreet.Text = customer.Street;
this.txtSurname.Text = customer.Surname;
this.txtZip.Text = customer.Zip;
}
catch
{
// user couldn't be loaded
Tools.ShowMessageBox(MessageBoxType.Error,
Localization.MsgCommonErrorNoDataFound,
this);
}
}
}
/// <summary>
/// Creates a new customer account with the data that is currently
/// displayed in the data section.
/// </summary>
private void CreateCustomer()
{
try
{
int? titleId = ((GenericIntStringItem)cbTitles.SelectedItem).IntVal;
if (titleId <= 0)
{
titleId = null;
}
// save to DB
int userId = bl.CreateUser(this.txtFirstname.Text,
this.txtSurname.Text,
this.txtStreet.Text,
this.txtZip.Text,
this.txtCity.Text,
this.txtCountry.Text,
this.txtEmail.Text,
this.txtPassword.Text,
titleId);
// update customer list
FillCustomerList();
// select the newly created customer
this.lbCustomers.Text = userId.ToString();
this.cbTitles.Select();
}
catch (Exception ex)
{
Tools.ShowMessageBoxException(ex, this);
}
}
/// <summary>
/// Updates the data of the currently selected customer
/// account to the database.
/// </summary>
private void SaveCustomer()
{
if (lbCustomers.SelectedItems.Count == 1)
{
try
{
int customerId = (int)lbCustomers.SelectedItem;
int? titleId = ((GenericIntStringItem)cbTitles.SelectedItem).IntVal;
if (titleId <= 0)
{
titleId = null;
}
// save changes
bl.UpdateUser(customerId,
this.txtFirstname.Text,
this.txtSurname.Text,
this.txtStreet.Text,
this.txtZip.Text,
this.txtCity.Text,
this.txtCountry.Text,
this.txtEmail.Text,
this.txtPassword.Text,
titleId);
// info on success
Tools.ShowMessageBox(MessageBoxType.Info,
Localization.MsgCommonInfoSaveSuccess,
this);
}
catch (Exception)
{
// save failed
Tools.ShowMessageBox(MessageBoxType.Error,
Localization.MsgCommonErrorSaveFailed,
this);
}
}
else
{
// nothing selected
Tools.ShowMessageBox(MessageBoxType.Error,
Localization.MsgCommonErrorNothingSelected,
this);
}
}
/// <summary>
/// Deletes the selected customer
/// </summary>
private void DeleteCustomer()
{
if (lbCustomers.SelectedItems.Count == 1)
{
try
{
// mark as deleted
bl.DeleteUser((int)lbCustomers.SelectedItem);
ClearCustomerData();
// reload admin list
FillCustomerList();
// inform about success
Tools.ShowMessageBox(MessageBoxType.Info,
Localization.MsgCommonInfoDeletionSuccess,
this);
}
catch (ConditionException ex)
{
Tools.ShowMessageBoxException(ex, this);
}
catch
{
Tools.ShowMessageBox(MessageBoxType.Error,
Localization.MsgCommonErrorDeletionFailed,
this);
}
}
else
{
// nothing selected
Tools.ShowMessageBox(MessageBoxType.Error,
Localization.MsgCommonErrorNothingSelected,
this);
}
}
/// <summary>
/// Clears all customer related data from the view
/// </summary>
private void ClearCustomerData()
{
this.cbTitles.Text = Constants.ComboBoxDefaultItemText;
this.txtCity.Clear();
this.txtCountry.Clear();
this.txtEmail.Clear();
this.txtFirstname.Clear();
this.txtPassword.Clear();
this.txtStreet.Clear();
this.txtSurname.Clear();
this.txtZip.Clear();
}
/// <summary>
/// Fill title combobox with titles
/// </summary>
private void FillTitles()
{
// cleanup
this.cbTitles.Items.Clear();
foreach (GenericIntStringItem item in bl.GetTitleListForComboBox())
{
this.cbTitles.Items.Add(item);
}
// select default entry
if (this.cbTitles.Items.Count > 0)
{
this.cbTitles.Text = Constants.ComboBoxDefaultItemText;
}
}
/// <summary>
/// Open the customer search
/// </summary>
private void OpenCustomerSearch()
{
using (FrmSearchCustomer frmCstmSearch = new FrmSearchCustomer(this.session))
{
frmCstmSearch.Owner = this;
frmCstmSearch.CustomerSelected += CustomerSearch_CustomerSelected;
// show
frmCstmSearch.ShowDialog(this);
frmCstmSearch.CustomerSelected -= CustomerSearch_CustomerSelected;
}
}
#endregion
#region Event handlers
/// <summary>
/// On form load
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event args</param>
private void FrmCustomerManager_Load(object sender, EventArgs e)
{
FillTitles();
FillCustomerList();
}
/// <summary>
/// Listbox "customers", selected index changed
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event args</param>
private void lbCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
DisplaySelectedCustomer();
}
/// <summary>
/// Button "new" clicked
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event args</param>
private void butNew_Click(object sender, EventArgs e)
{
CreateCustomer();
}
/// <summary>
/// Button "save" clicked
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event args</param>
private void butSave_Click(object sender, EventArgs e)
{
SaveCustomer();
}
/// <summary>
/// Button "delete" clicked
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="e">Event args</param>
private void butDelete_Click(object sender, EventArgs e)
{
DeleteCustomer();
}
/// <summary>
/// Button "search customer" clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButSearchCustomer_Click(object sender, EventArgs e)
{
OpenCustomerSearch();
}
/// <summary>
/// On customer selection in customer search
/// </summary>
/// <param name="sender"></param>
/// <param name="customerId"></param>
private void CustomerSearch_CustomerSelected(object sender, int customerId)
{
this.lbCustomers.Text = customerId.ToString();
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
namespace Yasl
{
public class LinkedListSerializer<T> : ISerializer
{
public void SerializeConstructor(ref object value, ISerializationWriter writer)
{
}
public void SerializeContents(ref object value, ISerializationWriter writer)
{
writer.WriteSet<T>(SerializationConstants.DefaultValueItemName, (LinkedList<T>)value);
}
public void SerializeBacklinks(ref object value, ISerializationWriter writer)
{
}
public void DeserializeConstructor(out object value, int version, ISerializationReader reader)
{
value = new LinkedList<T>();
}
public void DeserializeContents(ref object value, int version, ISerializationReader reader)
{
LinkedList<T> list = (LinkedList<T>)value;
var items = reader.ReadSet<T>(SerializationConstants.DefaultValueItemName);
foreach (var cur in items)
{
list.AddLast((T)cur);
}
}
public void DeserializeBacklinks(ref object value, int version, ISerializationReader reader)
{
}
public void DeserializationComplete(ref object value, int version)
{
}
}
}
|
using Microsoft.Bot.Builder;
using Microsoft.Bot.Configuration;
using System.Threading;
using System.Threading.Tasks;
namespace BotWorkshop.Bots
{
//The IBot interface is provided by the Microsoft.Bot.Builder package.
//It lets us define behavior that happens on each "turn" of a bot.
//Step 1) Have the EchoBot class implement IBot from Microsoft.Bot.Builder
public class EchoBot
{
}
}
|
using UnityEngine;
using System.Collections;
public class Fallskjerm : MonoBehaviour {
/* Dette skripet tar for seg falskjerm funksjonen til sauen
* og er basert på Unity tourtorialen om raycasting med noe modifikasjoner
*/
public GameObject fallskjerm; //Modellen av fallskjermen legges inn i Inspector
public float fallskjermEffekt; //Hvor stor effekt fallskjermen skal ha (drag)
public float utloserHoyde; //Hvilken høyde falskjermen skal utløses i
public float underBrettet; //finne ut om sauen er under brettet
private bool deployed = true; //Setter deployed til true, fordi alle sauene starter på bakken, Dette hindrer da at Raycasten kjører konstant før det er nødvendig.
private Rigidbody rb; //Lager en variabel for å hente ut og manipulerere komponenten rigidbody
void Start(){
rb = GetComponent<Rigidbody> (); //får tak i komponentet - Dette trenger vi bare å gjøre en gang, og er derfor plassert i Start()
}
void Update(){
RaycastHit hit; //Lager en variabel som skal holde på informasjon fra raycasten
//Lager en FailSafe (dykkeryuttrykk) Dersom vi har en sau som starter oppe i skyene kan den utløsefallskjerm på vei ned
if (transform.position.y > 900) {
deployed = false;
}
//Lager en ny Raycast
Ray landingRay = new Ray (transform.position, Vector3.down);
//Dersom fallskjermen ikke er utløst ber vi den skyte en ray ned og måle avstanden til bakken(Til en colider med taggen "Landskapsobjekter" Dette inkluderer alt, steiner vann, trær, bakke osv..
if (!deployed) {
//Dersom Raycasten vår "landingRay sin verdi (avstand til bakken) i hit tilsvarer utløserhøyden...
if (Physics.Raycast (landingRay, out hit, utloserHoyde)) {
//...Og denne høyden er målt utifra et landskapsobjekt...
if (hit.collider.tag == "LandskapsObjekter") {
//.. UtløsFallskjerm
UtlosFallskjerm ();
}
}
}
//Gjør en spørring på om Sauen har falt over kanten og "fallskjermen må pakkes"..
if (transform.position.y <= underBrettet) {
deployed = false;
}
}
//Funskjon som utløser fallskjermen
void UtlosFallskjerm(){
deployed = true;//Setter deployed til True
rb.drag = 1f; //Reduserer farten på fallet
fallskjerm.SetActive(true); //Gjør fallskjermen synlig for spilleren
}
//Funksjon for å oppdage når man lander. Det gjøres ved at når Collider Meshen til sauen treffer en annen mesh(bakken ect) kjøres denne funksjonen
void OnCollisionEnter(){
rb.drag = 0.0001f; //setter Rigidbody dragen tilbake til
fallskjerm.SetActive(false); //Lukker fallskjermen (gjør den ikke lenger synlig for spilleren)
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using dk.via.ftc.businesslayer.Models;
using Newtonsoft.Json;
namespace dk.via.ftc.businesslayer.Data.Services
{
public class DispensaryService : IDispensaryService
{
private string uri = "https://localhost:44332/db/Dispensary";
private readonly HttpClient client;
public DispensaryService()
{
client = new HttpClient();
}
public async Task<IList<Dispensary>> GetDispensariesAsync()
{
Task<string> stringAsync = client.GetStringAsync(uri + "/Dispensary/All");
string message = await stringAsync;
IList<Dispensary> obj = JsonConvert.DeserializeObject<IList<Dispensary>>(message);
return obj;
}
public async Task<DispensaryAdmin> GetDispensaryByUsername(string username)
{
Task<string> stringAsync = client.GetStringAsync(uri + "/Dispensary/"+username);
string message = await stringAsync;
DispensaryAdmin obj = JsonConvert.DeserializeObject<DispensaryAdmin>(message);
obj.Pass = FTCEncrypt.DecryptString(obj.Pass);
return obj;
}
public async Task<bool> ValidateDispensaryAdmin(string username, string password)
{
DispensaryAdmin da = await GetDispensaryByUsername(username);
if (da == null)
{
return false;
}
if (da.Pass.Equals(password))
{
return true;
}
return false;
}
public async Task AddDispensaryAsync(Dispensary dispensary)
{
string dispensaryAsJson = JsonConvert.SerializeObject(dispensary);
HttpContent content = new StringContent(dispensaryAsJson,
Encoding.UTF8,
"application/json");
await client.PutAsync(uri + "/Dispensary", content);
}
public async Task AddDispensaryAdminAsync(DispensaryAdmin dispensaryAdmin)
{
dispensaryAdmin.Pass = FTCEncrypt.EncryptString(dispensaryAdmin.Pass);
string dispensaryAdminAsJson = JsonConvert.SerializeObject(dispensaryAdmin);
HttpContent content = new StringContent(dispensaryAdminAsJson,
Encoding.UTF8,
"application/json");
Console.WriteLine(dispensaryAdminAsJson);
await client.PutAsync(uri + "/DispensaryAdmin", content);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Beamore.DAL.Contents.Models
{
[Table("UserTable")]
public class User : BaseModel
{
public User()
{
this.Events = new HashSet<Event>();
this.Locations = new HashSet<Location>();
this.EventSubcribers = new HashSet<EventSubcriber>();
this.UserMobileDevices = new HashSet<UserMobileDevice>();
this.Beacons = new HashSet<Beacon>();
this.BeaconChats = new HashSet<BeaconChat>();
}
[Required]
public string Username { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string PasswordSalt { get; set; }
[Required]
public string Role { get; set; }
public virtual ICollection<Event> Events { get; set; }
public virtual ICollection<Location> Locations { get; set; }
public virtual ICollection<EventSubcriber> EventSubcribers { get; set; }
public virtual ICollection<UserMobileDevice> UserMobileDevices { get; set; }
public virtual ICollection<Beacon> Beacons { get; set; }
public virtual ICollection<BeaconChat> BeaconChats { get; set; }
}
}
|
using CMS_Database.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CMS_Database.Interfaces
{
public interface ICTKhuyenMai :IGenericRepository<CTKhuyenmai>
{
IQueryable<CTKhuyenmai> GetById(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SudokuSolverAI
{
class Cube
{
#region fields
public int TotalCount { get; set; }
public int[] RowCount { get; set; }
public int[] ColumnCount { get; set; }
Box[,] Boxes;
#endregion
public Cube()
{
TotalCount = 0;
RowCount = new int[] { 0, 0, 0 };
ColumnCount = new int[] { 0, 0, 0 };
Boxes = new Box[3,3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{ Boxes[i, j] = new Box(); }
}
}
public void setBoxValue(int value, int row, int column)
{
Boxes[row % 3, column % 3].Value = value;
Boxes[row % 3, column % 3].RowID = row;
Boxes[row % 3, column % 3].ColumnID = column;
if (value != 0)
{
TotalCount++;
RowCount[row % 3]++;
ColumnCount[column % 3]++;
}
}
public bool isInCube(int num)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (Boxes[i,j].Value == num)
{
return true;
}
}
}
return false;
}
public bool isInRow(int num, int row)
{
for (int i = 0; i < 3; i++)
{
if (Boxes[row, i].Value == num)
{
return true;
}
}
return false;
}
public bool isInColumn(int num, int column)
{
for (int i = 0; i < 3; i++)
{
if (Boxes[i, column].Value == num)
{
return true;
}
}
return false;
}
public bool isFilled(int row, int column)
{
if (Boxes[row, column].Value == 0)
{ return false; }
return true;
}
public Box[] getColumn(int column)
{ return new Box[] { Boxes[0, column], Boxes[1, column], Boxes[2, column] }; }
public Box[] getRow(int row)
{ return new Box[] { Boxes[row, 0], Boxes[row, 1], Boxes[row, 2] }; }
/// <summary>
///
/// </summary>
/// <param name="lastRow">The last row that this function found an emptybox or no more boxes</param>
/// <param name="lastColumn">The last column that this function found an emptybox or no more boxes</param>
/// <returns>The location of the empty box within the cube. The values + 1 serve as the next last positions. If no empty boxes found, returns -1s</returns>
public int[] getEmptyBoxLocation(int lastRow, int lastColumn)
{
for (int i = lastRow; i < 3; i++)
{
for (int j = lastColumn; j < 3; j++)
{
if (Boxes[i, j].Value == 0)
{
return new int[] { i, j };
}
}
lastColumn = 0;
}
return new int[] { -1, -1 };
}
public void print()
{
StringBuilder temp = new StringBuilder();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{ temp.Append(Boxes[i, j].Value + ","); }
Console.WriteLine(temp);
temp.Clear();
}
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class UIManager : MonoBehaviour {
public static UIManager ui_manager;
public Text dialogue_text_panel;
public Text speaker_text_panel;
public GameObject choice_panel;
public Image background; // Background image
public Image foreground;
// Use this for initialization
void Start () {
ui_manager = this;
}
// Update is called once per frame
void Update () {
}
}
|
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
using DataStore.Dal.Pager;
using DataStore.Entity;
using DataStore.Pager;
namespace DataStore.Dal
{
public partial interface ILoginUserService
{
PageDataView<LoginUser> GetList(string name, string status, int page, int pageSize = 10);
}
} |
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using GitlabManager.Framework;
using GitlabManager.Model;
using GitlabManager.Services.Resources;
using GitlabManager.Theme;
using static GitlabManager.Model.ConnectionState;
using Brushes = AdonisUI.Brushes;
namespace GitlabManager.ViewModels
{
/// <summary>
/// ViewModel for the entire ConnectionWindow that is opened by the "Test"-Button
/// in the Accounts Page of the Main window
/// </summary>
public class WindowConnectionViewModel : AppViewModel
{
#region Dependencies
private readonly WindowConnectionModel _model;
private readonly IResources _resources;
#endregion
#region Private Helper properties
private ConnectionState ConnectionState => _model.ConnectionState;
#endregion
#region Public Properties for View
public int CurrentProgressBarValue => ConnectionState.BarProgress;
public string StateText => GenerateFancyStateText(ConnectionState);
public string ErrorText => ConnectionState.ErrorMessage;
public SolidColorBrush StateTextColor => GenerateFancyStateTextColor(ConnectionState);
public Visibility ProgressbarVisibility => GenerateProgressVisibility(ConnectionState);
#endregion
/// <summary>
/// Constructor
/// </summary>
/// <param name="model">Windows Model</param>
/// <param name="resources">Resources Loader</param>
public WindowConnectionViewModel(WindowConnectionModel model, IResources resources)
{
_model = model;
_model.PropertyChanged += ConnectionModelPropertyChangedHandler;
_resources = resources;
}
/// <summary>
/// Init before window opens
/// </summary>
/// <param name="hostUrl">HostURL of gitlab instance</param>
/// <param name="authenticationToken">privat authentication token</param>
public void Init(string hostUrl, string authenticationToken)
{
_model.Init(hostUrl, authenticationToken);
}
#region Private Utility Methods
/// <summary>
/// Handle model property changes
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void ConnectionModelPropertyChangedHandler(object sender, PropertyChangedEventArgs eventArgs)
{
switch (eventArgs.PropertyName)
{
case nameof(WindowConnectionModel.ConnectionState):
RaisePropertyChanged(nameof(CurrentProgressBarValue));
RaisePropertyChanged(nameof(StateText));
RaisePropertyChanged(nameof(ErrorText));
RaisePropertyChanged(nameof(StateTextColor));
RaisePropertyChanged(nameof(ProgressbarVisibility));
break;
}
}
/// <summary>
/// Generate the text that is shown for a specific connection state
/// </summary>
/// <param name="state">connection state</param>
/// <returns>fancy message</returns>
private static string GenerateFancyStateText(ConnectionState state)
{
return state.Type switch {
StateType.Success => "Connection established successfully!",
StateType.Loading => "Trying to connect...",
StateType.Error => "Error while testing connection!",
_ => ""
};
}
/// <summary>
/// Generate the text color for a specific connection state
/// </summary>
/// <param name="state">connection state</param>
/// <returns></returns>
private SolidColorBrush GenerateFancyStateTextColor(ConnectionState state)
{
return state.Type switch
{
StateType.Success => _resources.GetBrush(ThemeConstants.SuccessBrush),
StateType.Error => _resources.GetBrush(ThemeConstants.ErrorLightBrush),
_ => _resources.GetBrush(Brushes.ForegroundBrush)
};
}
/// <summary>
/// generate visibility of progressbar by connection state
/// </summary>
/// <param name="state">connection state</param>
/// <returns></returns>
private static Visibility GenerateProgressVisibility(ConnectionState state)
{
return state.Type == StateType.Loading
? Visibility.Visible
: Visibility.Collapsed;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
namespace OCP.FullTextSearch.Model
{
/**
* Interface IIndex
*
* Index are generated by FullTextSearch to manage the status of a document
* regarding the date of the last index and the date of the last modification
* of the original document.
*
* The uniqueness of an IIndexDocument is made by the Id of the Content Provider
* and the Id of the original document within the Content Provider.
*
* We will call original document the source from which the IIndexDocument is
* generated. As an example, an original document can be a file, a mail, ...
*
* @since 15.0.0
*
* @package OCP\FullTextSearch\Model
*/
public interface IIndex
{
//const INDEX_OK = 1;
//const INDEX_IGNORE = 2;
//const INDEX_META = 4;
//const INDEX_CONTENT = 8;
//const INDEX_PARTS = 16;
//const INDEX_FULL = 28;
//const INDEX_REMOVE = 32;
//const INDEX_DONE = 64;
//const INDEX_FAILED = 128;
//const ERROR_FAILED = 1;
//const ERROR_FAILED2 = 2;
//const ERROR_FAILED3 = 4;
//const ERROR_SEV_1 = 1;
//const ERROR_SEV_2 = 2;
//const ERROR_SEV_3 = 3;
//const ERROR_SEV_4 = 4;
/**
* Get the Id of the Content Provider.
*
* @since 15.0.0
*
* @return string
*/
string getProviderId() ;
/**
* Get the Id of the original document.
*
* @since 15.0.0
*
* @return string
*/
string getDocumentId();
/**
* Set the source of the original document.
*
* @since 15.0.0
*
* @param string source
*
* @return IIndex
*/
IIndex setSource(string source);
/**
* Get the source of the original document.
*
* @since 15.0.0
*
* @return string
*/
string getSource();
/**
* Set the owner of the original document.
*
* @since 15.0.0
*
* @param string ownerId
*
* @return IIndex
*/
IIndex setOwnerId(string ownerId);
/**
* Get the owner of the original document.
*
* @since 15.0.0
*
* @return string
*/
string getOwnerId();
/**
* Set the current index status (bit flag) of the original document.
* If reset is true, the status is reset to the defined value.
*
* @since 15.0.0
*
* @param int status
* @param bool reset
*
* @return IIndex
*/
IIndex setStatus(int status, bool reset = false);
/**
* Get the current index status of the original document.
*
* @since 15.0.0
*
* @return int
*/
int getStatus();
/**
* Check if the document fit a specific status.
*
* @since 15.0.0
*
* @param int status
*
* @return bool
*/
bool isStatus(int status);
/**
* Remove a status.
*
* @since 15.0.0
*
* @param int status
*
* @return IIndex
*/
IIndex unsetStatus(int status);
/**
* Add an option related to the original document (as string).
*
* @since 15.0.0
*
* @param string option
* @param string|int value
*
* @return IIndex
*/
IIndex addOption(string option, string value);
/**
* Add an option related to the original document (as integer).
*
* @since 15.0.0
*
* @param string option
* @param int value
*
* @return IIndex
*/
IIndex addOptionInt(string option, int value);
/**
* Get the option related to the original document (as string).
*
* @since 15.0.0
*
* @param string option
* @param string default
*
* @return string
*/
string getOption(string option, string @default = "");
/**
* Get the option related to the original document (as integer).
*
* @since 15.0.0
*
* @param string option
* @param int default
*
* @return int
*/
int getOptionInt(string option, int @default = 0);
/**
* Get all options related to the original document.
*
* @since 15.0.0
*
* @return array
*/
IList<string> getOptions();
/**
* Add an error log related to the Index.
*
* @since 15.0.0
*
* @param string message
* @param string exception
* @param int sev
*
* @return IIndex
*/
//IIndex addError(string message, string exception = "", int sev = self::ERROR_SEV_3): ;
IIndex addError(string message, string exception = "", int sev = 3);
/**
* Returns the number of known errors related to the Index.
*
* @since 15.0.0
*
* @return int
*/
int getErrorCount();
/**
* Reset all error logs related to the Index.
*
* @since 15.0.0
*/
IIndex resetErrors();
/**
* Set the date of the last index.
*
* @since 15.0.0
*
* @param int lastIndex
*
* @return IIndex
*/
IIndex setLastIndex(int lastIndex = -1);
/**
* Get the date of the last index.
*
* @since 15.0.0
*
* @return int
*/
int getLastIndex();
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ProjectIris.Models;
namespace ProjectIris.Controllers
{
[Authorize(Roles = "Admin,EmployeeManager")]
public class employees_logController : Controller
{
private Entities db = new Entities();
// GET: employees_log
public async Task<ActionResult> Index()
{
return View(await db.employees_log.OrderByDescending(s => s.id).ToListAsync());
}
// GET: employees_log/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
employees_log employees_log = await db.employees_log.FindAsync(id);
if (employees_log == null)
{
return HttpNotFound();
}
return View(employees_log);
}
// GET: employees_log/Create
public ActionResult Create()
{
return View();
}
// POST: employees_log/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "id,datecreated,employeeid,message")] employees_log employees_log)
{
if (ModelState.IsValid)
{
db.employees_log.Add(employees_log);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(employees_log);
}
// GET: employees_log/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
employees_log employees_log = await db.employees_log.FindAsync(id);
if (employees_log == null)
{
return HttpNotFound();
}
return View(employees_log);
}
// POST: employees_log/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "id,datecreated,employeeid,message")] employees_log employees_log)
{
if (ModelState.IsValid)
{
db.Entry(employees_log).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(employees_log);
}
// GET: employees_log/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
employees_log employees_log = await db.employees_log.FindAsync(id);
if (employees_log == null)
{
return HttpNotFound();
}
return View(employees_log);
}
// POST: employees_log/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
employees_log employees_log = await db.employees_log.FindAsync(id);
db.employees_log.Remove(employees_log);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief ブラー。カメラ。
*/
/** NBlur
*/
namespace NBlur
{
/** MonoBehaviour_Camera
*/
public class MonoBehaviour_Camera : MonoBehaviour
{
/** mycamera
*/
public Camera mycamera;
/** material_blur_x
*/
private Material material_blur_x;
/** material_blur_y
*/
private Material material_blur_y;
/** work_rendertexture
*/
private RenderTexture work_rendertexture;
/** 初期化。
*/
public void Initialize()
{
//カメラ取得。
this.mycamera = this.GetComponent<Camera>();
//マテリアル読み込み。
this.material_blur_x = Resources.Load<Material>(Config.MATERIAL_NAME_BLURX);
this.material_blur_y = Resources.Load<Material>(Config.MATERIAL_NAME_BLURY);
//レンダーテクスチャー。
this.work_rendertexture = null;
#if(UNITY_EDITOR)
{
float[] t_table = new float[8];
float t_total = 0.0f;
float t_dispersion = 4.0f;
for(int ii=0;ii<t_table.Length;ii++){
t_table[ii] = Mathf.Exp(-0.5f * ((float)(ii*ii)) / t_dispersion);
t_total += t_table[ii] * 2;
}
for(int ii=0;ii<t_table.Length;ii++){
t_table[ii] /= t_total;
Tool.Log("MonoBehaviour_Camera","param = " + t_table[ii].ToString());
}
}
#endif
}
/** 削除。
*/
public void Delete()
{
}
/** カメラデプス。設定。
*/
public void SetCameraDepth(float a_depth)
{
this.mycamera.depth = a_depth;
}
/** OnRenderImage
*/
private void OnRenderImage(RenderTexture a_source,RenderTexture a_dest)
{
//レンダリングテクスチャー作成。
this.work_rendertexture = RenderTexture.GetTemporary(a_source.width/2,a_source.height/2,0,a_source.format,RenderTextureReadWrite.Default);
try{
UnityEngine.Graphics.Blit(a_source,this.work_rendertexture,this.material_blur_x);
UnityEngine.Graphics.Blit(this.work_rendertexture,a_dest,this.material_blur_y);
}catch(System.Exception t_exception){
Tool.LogError(t_exception);
}
//レンダーテクスチャー解放。
if(this.work_rendertexture != null){
RenderTexture.ReleaseTemporary(this.work_rendertexture);
this.work_rendertexture = null;
}
}
}
}
|
namespace EvnTonThat.ResourceAccess.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("V_TT_DBTT_L")]
public partial class V_TT_DBTT_L
{
// public int OBJECTID { get; set; }
[Key]
public long ID_BCAO { get; set; }
public string MA_DVIQLY { get; set; }
public string MA_LANBC { get; set; }
public short? STT { get; set; }
public string MA_PTDIEN { get; set; }
public string TEN_LO { get; set; }
public string LOAI_LO { get; set; }
public string MA_CAPDA { get; set; }
public string TEN_CAPDA { get; set; }
public string MA_NHOM { get; set; }
public string TEN_NHOM { get; set; }
public long? DN_NHANKV { get; set; }
public long? DN_NHAN { get; set; }
public long? DN_GIAO { get; set; }
public long? DN_GIAO_HSK { get; set; }
public long? TP_TONG { get; set; }
public long? TP_TPLE { get; set; }
public long? TP_BANTONG { get; set; }
public long? TP_BANLE { get; set; }
public long? TT_KW { get; set; }
public decimal? TT_PT { get; set; }
public decimal? TT_KH { get; set; }
public decimal? SO_SANH { get; set; }
public short? NAM { get; set; }
public byte? THANG { get; set; }
public string MA_VUNG { get; set; }
public string TEN_VUNG { get; set; }
public string GHICHU { get; set; }
public byte? INBAOCAO { get; set; }
public string DINH_DANH { get; set; }
public long? TP_CDTTHE { get; set; }
public long? TP_CDHTHE { get; set; }
public long? DN_NHAN_KPT { get; set; }
public long? DN_GIAO_KPT { get; set; }
}
public partial class V_TT_DBTT_L_TinhGop
{
public V_TT_DBTT_L tuyenDayData { get; set; }
public decimal TT_PT_TinhGop { get; set; }
public decimal total_TT_KW { get; set; }
public decimal total_DN_NHAN { get; set; }
public decimal total_dn_giao { get; set; }
public decimal total_tt_banle { get; set; }
public decimal total_tt_bantong { get; set; }
public decimal total_tt_tong { get; set; }
}
public partial class V_TT_DBTT_L_TinhGop_Query
{
public decimal total_TT_KW { get; set; }
public decimal total_DN_NHAN { get; set; }
public decimal total_dn_giao { get; set; }
public decimal total_tt_banle { get; set; }
public decimal total_tt_bantong { get; set; }
public decimal total_tt_tong { get; set; }
}
public partial class V_TT_DBTT_L_forHtml
{
public V_TT_DBTT_L_TinhGop tuyenDayDataGop { get; set; }
public string htmlGop { get; set; }
}
}
|
namespace Singleton.Library
{
public class Singleton
{
private static Singleton _uniqueInstanceSingleton;
private Singleton(){}
public static Singleton getInstance()
{
if (_uniqueInstanceSingleton == null)
{
_uniqueInstanceSingleton = new Singleton();
}
return _uniqueInstanceSingleton;
//Other useful methods go here
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProyectoArqui.Logica
{
class Nucleo
{
public Shared shared;
public Instruccion IR { get; set; }
public int PC { get; set; }
public int[] Registros { get; set; }
public int IdNucleo;
public int IdProce;
/// <summary>
/// 5 ya que el ultimo es la etiqueta.
/// </summary>
//public Instruccion[,] CacheInstrucciones = new Instruccion[5, 4];
public CacheInstrucciones cacheI = new CacheInstrucciones();
/// <summary>
/// 6 ya que el 5 es la
/// etiqueta y el 6 es el estado.
/// </summary>
public int[,] cacheDatos = new int[6, 4];
public Nucleo(int idn, int idp)
{
IdNucleo = idn;
IdProce = idp;
//se inicializan los registros en 0
Registros = new int[32];
for (int i = 0; i < 32; i++)
{
Registros[i] = 0;
}
//se inicializa la cache en 0, con todos los bloques inválidos
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
cacheDatos[i, j] = 0;
}
}
for (int i = 0; i < 4; i++)
{
cacheDatos[5, i] = -1;
}
}
public Nucleo(int idn, int idp, Controladora controladora)
{
IdNucleo = idn;
IdProce = idp;
shared = controladora.shared;
//se inicializan los registros en 0
Registros = new int[32];
for (int i = 0; i < 32; i++)
{
Registros[i] = 0;
}
//se inicializa la cache en 0, con todos los bloques inválidos
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
cacheDatos[i, j] = 0;
}
}
for (int i = 0; i < 4; i++)
{
cacheDatos[5, i] = -1;
}
}
//Ejecuta instrucciones del ALU
public bool ejecutarInstruccion(Instruccion instruccion)
{
/*
sumar cuatro al pc , cada vez que tiene una nueva lectura de instruccion.
*/
bool result = false;
switch (instruccion.CodigoOp)
{
case 8:
//DADDI: Rx <-- (Ry) + n
Registros[instruccion.RF2_RD] = Registros[instruccion.RF1] + instruccion.RD_IMM;
break;
case 32:
//DADD: Rx <-- (Ry) + (Rz)
Registros[instruccion.RD_IMM] = Registros[instruccion.RF1] + Registros[instruccion.RF2_RD];
break;
case 34:
//DSUB: Rx <-- (Ry) - (Rz)
Registros[instruccion.RD_IMM] = Registros[instruccion.RF1] - Registros[instruccion.RF2_RD];
break;
case 12:
//DMUL: Rx <-- (Ry) * (Rz)
Registros[instruccion.RD_IMM] = Registros[instruccion.RF1] * Registros[instruccion.RF2_RD];
break;
case 14:
//DDIV: Rx <-- (Ry) / (Rz)
Registros[instruccion.RD_IMM] = Registros[instruccion.RF1] / Registros[instruccion.RF2_RD];
break;
case 4:
//BEQZ: Si Rx == 0 hace un salto de n*4 (tamaño de instruccion)
if (Registros[instruccion.RF1] == 0)
{
PC = PC + (instruccion.RD_IMM * 4); //cambio el PC a la etiqueta
}
break;
case 5:
//BNEZ: Si Rx != 0 hace un salto de n*4 (tamaño de instruccion)
if (Registros[instruccion.RF1] != 0)
{
PC = PC + (instruccion.RD_IMM * 4); //cambio el PC a la etiqueta
}
break;
case 3:
//JAL: R31 <-- PC, PC <-- PC + n
Registros[31] = PC;
PC = PC + instruccion.RD_IMM;
break;
case 2:
//JR: PC <-- (RX)
PC = Registros[instruccion.RF1];
break;
case 63:
//FIN
result = true;
break;
case 35:
EjecutarLW(instruccion, shared.cachesDatos.ElementAt(IdNucleo));
break;
case 43:
EjecutarSW(instruccion, shared.cachesDatos.ElementAt(IdNucleo));
break;
default:
//si hay un mal codigo deberia de tirar error
break;
}
return result;
}
//Hay que definir lo de los estados, en este caso estoy proponiendo que: -1 = I, 0 = C, 1 = M para la cache
//para el directorio sería -1 = U, 0 = C, 1 = M
public bool EjecutarLW(Instruccion instruccion, int[,] CacheDatos)
{
bool result = false;
//se obtiene direccion de memoria
int direccion = instruccion.RF1 + instruccion.RD_IMM;
//se convierte a bloque y palabra posicion en cache
int bloque = direccion / 16;
int palabra = (direccion % 16) / 4;
int posCache = bloque % 4;
//Asigna un valor Para el directorio y la memoria
int procesador;
if (bloque < 16) //significa que son del directorio 0 y la memoria 0
{
procesador = 0;
}
else //memoria y directorio 1
{
procesador = 1;
}
int accesoDirMem;
if (bloque < 16) //significa que son del directorio 0 y la memoria 0
{
accesoDirMem = bloque;
}
else //memoria y directorio 1
{
accesoDirMem = bloque - 16;
}
//Se trata de bloquear la cache
lock (CacheDatos)
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//si esta el bloque en mi cache y esta válido (hit)
if (CacheDatos[4, posCache] == bloque && CacheDatos[5, posCache] != -1)
{
//cargar el valor al registro correspondiente
Registros[instruccion.RF2_RD] = CacheDatos[palabra, posCache];
//restar quantum
//quantum.Valor--; LO COMENTE PARA QUE NO DIERA ERRORES
result = true;
//Controladora.barreraReloj.SignalAndWait();
}
else //fallo de cache
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se obtienen los datos del bloque victima
int bloqueVictima = CacheDatos[4, posCache];
//Asigna un valor Para el directorio y la memoria del bloque victima
int procesadorVictima;
if (bloqueVictima < 16) //significa que son del directorio 0 y la memoria 0
{
procesadorVictima = 0;
}
else //memoria y directorio 1
{
procesadorVictima = 1;
}
int accesoDirMemVictima;
if (bloqueVictima < 16) //significa que son del directorio 0 y la memoria 0
{
accesoDirMemVictima = bloqueVictima;
}
else //memoria y directorio 1
{
accesoDirMemVictima = bloqueVictima - 16;
}
//se debe de revisar el estado del bloque para saber si esta modificado
if (CacheDatos[5, posCache] == 1)
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//bloquear el bus de data
lock (Program.BusDatos[procesadorVictima])
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//bloquear el directorio casa del bloque victima
lock (Program.BusDirectorios[procesadorVictima])
{
//se bloquea la memoria
lock (Program.BusMemorias[procesadorVictima])
{
//se actualiza el valor en memoria del bloque victima
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesadorVictima)[((accesoDirMemVictima * 16) / 4) + i] = CacheDatos[i, posCache];
}
//se actualiza el directorio casa con 0´s y una U en el estado del bloque victima
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 0] = -1;
for (int i = 1; i < 4; i++)
{
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, i] = 0;
}
//se invalida el estado de la cache del bloque victima
CacheDatos[5, posCache] = -1;
}
}
}
}
else if (CacheDatos[5, posCache] == 0) //Compartido
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
lock (Program.BusDirectorios[procesadorVictima])
{
//pone un 0 en el directorio casa del bloque victima
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, IdNucleo] = 0;
CacheDatos[5, posCache] = -1;
//se debe de actualizar el valor del directorio por si todo esta en 0
if (shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 1] == 0 &&
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 2] == 0 &&
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 3] == 0)
{
//Si entra aqui es porque el bloque esta uncached y se debe actualizar el estado con un -1
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 0] = -1;
}
}
}
//Ya termino de analizar el bloque victima, si es invalido se le puede caer encima sin problema
//se bloquea el bus
lock (Program.BusDatos[procesador])
{
//se bloquea el directorio casa del bloque fuente
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
lock (Program.BusDirectorios[procesador])
{
//se debe de bloquear la memoria para escribir en ella
lock (Program.BusMemorias[procesador])
{
//se debe de mandar a escribir a memoria
//se debe de preguntar en el directorio si el bloque fuente está modificado en alguna otra caché
if (shared.directorios.ElementAt(procesador)[accesoDirMem, 0] == 1)
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se debe de preguntar en cual caché está modificado, además se debe de bloquear esa caché
if (shared.directorios.ElementAt(procesador)[accesoDirMem, 1] == 1) //Nucleo0
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//Bloquea la cache
lock (Program.BusCaches[0])
{
//se actualiza el valor en memoria del bloque
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i] = shared.cachesDatos.ElementAt(0)[i, posCache];
}
//Se actualiza el estado del bloque a compartido
shared.cachesDatos.ElementAt(0)[5, posCache] = 0;
//Se actualiza el estado del directorio como compartido
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = 0;
//se deja el 1 que ya estaba en el directorio
}
}
else if (shared.directorios.ElementAt(procesador)[accesoDirMem, 2] == 1) //Nucleo 1
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//Bloquea la cache
lock (Program.BusCaches[1])
{
//se actualiza el valor en memoria del bloque
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i] = shared.cachesDatos.ElementAt(1)[i, posCache];
}
//Se actualiza el estado del bloque a compartido
shared.cachesDatos.ElementAt(1)[5, posCache] = 0;
//Se actualiza el estado del directorio como compartido
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = 0;
//se deja el 1 que ya estaba en el directorio
}
}
else //Nucleo2
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//Bloquea la cache
lock (Program.BusCaches[1])
{
//se actualiza el valor en memoria del bloque
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i] = shared.cachesDatos.ElementAt(2)[i, posCache];
}
//Se actualiza el estado del bloque a compartido
shared.cachesDatos.ElementAt(2)[5, posCache] = 0;
//Se actualiza el estado del directorio como compartido
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = 0;
//se deja el 1 que ya estaba en el directorio
}
}
}
//si no es porque está compartido o invalido y se le puede caer sin problema
//Ahora que no hay conflictos con los estados se puede finalmente escribir en la cache para la lectura
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//subo el bloque a cache
for (int i = 0; i < 4; i++)
{
CacheDatos[i, posCache] = shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i];
Console.Write("CacheDatos: {0}\n", CacheDatos[i, posCache]);
}
//actualizo el valor del bloque y el del estado
CacheDatos[4, posCache] = bloque;
CacheDatos[5, posCache] = 0; //0 por estar compartido
//actualizo el directorio casa
//pongo un 0 en estado, que significa que esta compartido
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = 0;
shared.directorios.ElementAt(procesador)[accesoDirMem, IdNucleo] = 1;
}
}
//finalmente puedo leer
//agrego al registro lo que hay en caché
Registros[instruccion.RF2_RD] = CacheDatos[palabra, posCache];
//restar quantum
//quantum.Valor--;
//ExitoAnterior = true
result = true;
//4(1 + 5 +1) cargando bloque de memoria a cache.
//IncrementarReloj(28);
}
}
}
return result;
}
//Hay que definir lo de los estados, en este caso estoy proponiendo que: -1 = I, 0 = C, 1 = M para la cache
//para el directorio sería -1 = U, 0 = C, 1 = M
public bool EjecutarSW(Instruccion instruccion, int[,] CacheDatos)
{
bool result = false;
//se obtiene direccion de memoria
int direccion = Registros[instruccion.RF1] + instruccion.RD_IMM;
//se convierte a bloque y palabra posicion en cache
int bloque = direccion / 16;
int palabra = (direccion % 16) / 4;
int posCache = bloque % 4;
//Asigna un valor Para el directorio y la memoria
int procesador;
if (bloque < 16) //significa que son del directorio 0 y la memoria 0
{
procesador = 0;
}
else //memoria y directorio 1
{
procesador = 1;
}
int accesoDirMem;
if (bloque < 16) //significa que son del directorio 0 y la memoria 0
{
accesoDirMem = bloque;
}
else //memoria y directorio 1
{
accesoDirMem = bloque - 16;
}
//se trata de bloquear el caché
lock (CacheDatos)
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//si esta el bloque en mi cache y esta válido (hit)
if (CacheDatos[4, posCache] == bloque && CacheDatos[5, posCache] != -1)
{
//Se debe de preguntar si el estado del bloque es modificado
if (CacheDatos[5, posCache] == 1)
{
//se modifica el dato en la cache actual
CacheDatos[palabra, posCache] = Registros[instruccion.RF2_RD];
result = true;
//no se actualiza directorio ni estado de la cache pues ya estaba modificado
//se desbloquea todo
}
else //el bloque es compartido
{
//se debe de bloquear el directorio casa del bloque
lock (Program.BusDirectorios[procesador])
{
//se debe de preguntar si se encuentra compartido en otra cache (como es compartido puede estar en las 3, pero minimo en una, la actual)
if (shared.directorios.ElementAt(procesador)[accesoDirMem, 1] == 1)//Nucleo0
{
//se bloquea la cache donde esta el bloque
lock (Program.BusCaches[0])
{
//invalida el bloque de la cache y el directorio
shared.cachesDatos.ElementAt(0)[5, posCache] = -1;
shared.directorios.ElementAt(procesador)[accesoDirMem, 1] = 0;
}
}
if (shared.directorios.ElementAt(procesador)[accesoDirMem, 2] == 1)//Nucleo1
{
//se bloquea la cache donde esta el bloque
lock (Program.BusCaches[1])
{
//invalida el bloque de la cache y el directorio
shared.cachesDatos.ElementAt(1)[5, posCache] = -1;
shared.directorios.ElementAt(procesador)[accesoDirMem, 1] = 0;
}
}
if (shared.directorios.ElementAt(procesador)[accesoDirMem, 3] == 1)//Nucleo2
{
//se bloquea la cache donde esta el bloque
lock (Program.BusCaches[2])
{
//invalida el bloque de la cache y el directorio
shared.cachesDatos.ElementAt(2)[5, posCache] = -1;
shared.directorios.ElementAt(procesador)[accesoDirMem, 1] = 0;
}
}
//Cuando llega aquí ya invalidó todos los posibles bloques compartidos y ya puede se modificar
//se modifica el dato en la cache actual
CacheDatos[palabra, posCache] = Registros[instruccion.RF2_RD];
//actualiza su estado en cache
CacheDatos[5, posCache] = 1;
result = true;
//se actualiza el directorio
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = 1;
shared.directorios.ElementAt(procesador)[accesoDirMem, IdNucleo+1] = 1;
}
}
}
else //fallo
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se obtienen los datos del bloque victima
int bloqueVictima = CacheDatos[4, posCache];
//Asigna un valor Para el directorio y la memoria del bloque victima
int procesadorVictima;
if (bloqueVictima < 16) //significa que son del directorio 0 y la memoria 0
{
procesadorVictima = 0;
}
else //memoria y directorio 1
{
procesadorVictima = 1;
}
int accesoDirMemVictima;
if (bloqueVictima < 16) //significa que son del directorio 0 y la memoria 0
{
accesoDirMemVictima = bloqueVictima;
}
else //memoria y directorio 1
{
accesoDirMemVictima = bloqueVictima - 16;
}
//se debe de revisar el estado del bloque para saber si esta modificado
if (CacheDatos[5, posCache] == 1)
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//bloquear el bus de data del procesador del bloque victima
lock (Program.BusDatos[procesadorVictima])
{
//bloquear el directorio casa del bloque victima
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//bloqueo del directorio casa del bloque victima
lock (Program.BusDirectorios[procesadorVictima])
{
//se debe de bloquear la memoria para escribir en ella
lock (Program.BusMemorias[procesadorVictima])
{
//se actualiza el valor en memoria del bloque victima
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesadorVictima)[((accesoDirMemVictima * 16) / 4) + i] = CacheDatos[i, posCache];
}
//se actualiza el directorio casa con 0´s y una U en el estado del bloque victima
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 0] = -1;
for (int i = 1; i < 4; i++)
{
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, i] = 0;
}
//se invalida el estado de la cache del bloque victima
CacheDatos[5, posCache] = -1;
}
}
}
}
else if (CacheDatos[5, posCache] == 0) //Compartido
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//Bloquea el directorio casa del bloque victima
lock (Program.BusDirectorios[procesadorVictima])
{
//pone un 0 en el directorio casa del bloque victima
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, IdNucleo+1] = 0;
CacheDatos[5, posCache] = -1;
//se debe de actualizar el valor del directorio por si todo esta en 0
if (shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 1] == 0 &&
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 2] == 0 &&
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 3] == 0)
{
//Si entra aqui es porque el bloque esta uncached y se debe actualizar el estado con un -1
shared.directorios.ElementAt(procesadorVictima)[accesoDirMemVictima, 0] = -1;
}
}
}
//Ya termino de analizar el bloque victima, si es invalido se le puede caer encima sin problema
//se bloquea el bus
lock (Program.BusDatos[procesador])
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se bloquea el directorio casa del bloque fuente
lock (Program.BusDirectorios[procesador])
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se debe de mandar a escribir a memoria
//se debe de bloquear la memoria para escribir en ella
lock (Program.BusMemorias[procesador])
{
//se debe de preguntar en el directorio si el bloque fuente está modificado en alguna otra caché
if (shared.directorios.ElementAt(procesador)[accesoDirMem, 0] == 1)
{
if (shared.directorios.ElementAt(procesador)[accesoDirMem, 1] == 1) //Nucleo0
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se bloquea la cache
lock (Program.BusCaches[0])
{
//se actualiza el valor en memoria del bloque
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i] = shared.cachesDatos.ElementAt(0)[i, posCache];
}
//Se invalida el bloque
shared.cachesDatos.ElementAt(0)[5, posCache] = -1;
//Se pone 0 en el nucleo invalidado
shared.directorios.ElementAt(procesador)[accesoDirMem, 1] = 0;
//Pongo como uncached
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = -1;
}
}
else if (shared.directorios.ElementAt(procesador)[accesoDirMem, 2] == 1) //Nucleo 1
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se bloquea la cache
lock (Program.BusCaches[1])
{
//se actualiza el valor en memoria del bloque
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i] = shared.cachesDatos.ElementAt(1)[i, posCache];
}
//Se invalida el bloque
shared.cachesDatos.ElementAt(1)[5, posCache] = -1;
//Se pone 0 en el nucleo invalidado
shared.directorios.ElementAt(procesador)[accesoDirMem, 2] = 0;
//Pongo como uncached
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = -1;
}
}
else //Nucleo2
{
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//se bloquea la cache
lock (Program.BusCaches[2])
{
//se actualiza el valor en memoria del bloque
for (int i = 0; i < 4; i++)
{
shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i] = shared.cachesDatos.ElementAt(2)[i, posCache];
}
//Se invalida el bloque
shared.cachesDatos.ElementAt(2)[5, posCache] = -1;
//Se pone 0 en el nucleo invalidado
shared.directorios.ElementAt(procesador)[accesoDirMem, 3] = 0;
//Pongo como uncached
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = -1;
}
}
}
//si no es porque está compartido o invalido y se le puede caer sin problema
//Ahora que no hay conflictos con los estados se puede finalmente escribir en la cache para la lectura
//tick de reloj
//Controladora.barreraReloj.SignalAndWait();
//subo el bloque a cache
for (int i = 0; i < 4; i++)
{
CacheDatos[i, posCache] = shared.memoriasCompartida.ElementAt(procesador)[((accesoDirMem * 16) / 4) + i];
Console.Write("CacheDatos: {0}\n", CacheDatos[i, posCache]);
}
//actualizo el valor del bloque y el del estado
CacheDatos[4, posCache] = bloque;
//finalmente puedo escribir
//agrego al caché lo que hay en registro
CacheDatos[palabra, posCache] = Registros[instruccion.RF2_RD];
//restar quantum
//quantum.Valor--;
//ExitoAnterior = true
result = true;
//4(1 + 5 +1) cargando bloque de memoria a cache.
//IncrementarReloj(28);
CacheDatos[5, posCache] = 1; //1 por estar modificado
//actualizo el directorio casa
//pongo un 1 en estado, que significa que esta modificado
shared.directorios.ElementAt(procesador)[accesoDirMem, 0] = 1;
shared.directorios.ElementAt(procesador)[accesoDirMem, IdNucleo+1] = 1;
}
}
}
// int a = 0; // para efectos de depurar y poner BP
//se libera todo
}
}
return result;
}
private void IncrementarReloj(int limiteSuperior)
{
for (int i = 0; i < limiteSuperior; i++)
Controladora.barreraReloj.SignalAndWait();
}
public void fetch()
{
//pregunta en la cache si esta en el bloque i,
//si si está entonces, busca y carga la instruccion al IR,
//sino esta lo traigo de la memoria de instrucciones (el bloque).
}
//devuelve true si finalizo el Hilillo
public void ejecutar(object o)
{
//carga los datos compartidos
shared = (Shared)o;
//hilillo que se va a ejecutar en el nucleo
ContextoHilillo proximo;
//Probar bloqueo de hilos finalizados
int hfin;
lock (Program.BusFinalizados)
{
hfin = shared.hilosFinalizados.ElementAt(IdProce).Count();
}
while (shared.hilosTotales[IdProce] != hfin)
{
proximo = null;
//bloquea la cola de contextos del Procesador donde esta el nucleo
lock (Program.BusContextos)
{
//carga el hilo de la cola de hilos pendientes
if (shared.colasContextos.ElementAt(IdProce).Count() > 0)
proximo = shared.colasContextos.ElementAt(IdProce).Dequeue();
}
if (proximo != null)
{
/*
do
{
//bloquea la cola de contextos del Procesador donde esta el nucleo
lock (Program.BusContextos)
{
//carga el hilo de la cola de hilos pendientes
proximo = shared.colasContextos.ElementAt(IdProce).Dequeue();
}
if (proximo.Finalizado)
{
//lock (shared.hilosFinalizados.ElementAt(IdProce))
{
//si el hilo esta finalizado, lo guarda en la lista de hilos finalizados
shared.hilosFinalizados.ElementAt(IdProce).Add(proximo);
}
}
} while (proximo.Finalizado);
*/
//REVISAR EL CASO EN QUE TODOS LOS HILOS ESTEN FINALIZADOS Y QUEDE VACIA LA COLA PORQUE SE PUEDE ENCLICLAR
//inicializa registros y pc del contexto
int numInst;
//lock (shared)
{
numInst = shared.quantum; // Trae el quantum definido para ejecutar
}
PC = proximo.PC;
Registros = proximo.Registros;
proximo.horaInicio = DateTime.Now;
while (numInst > 0 && !proximo.Finalizado)
{
//saca palabra y bloque del PC
int bloque = PC / 16;
int palabra = (PC % 16) / 4;
bool hit = false;
//comienza fetch
if (cacheI.etiquetas[bloque % 4] == bloque)
{
hit = true;
}
if (!hit)
{
//no hubo hit y va a memoria a cargar bloque
for (int j = 0; j < 4; ++j)
{
Instruccion nueva = new Instruccion();
lock (Program.BusInstrucciones[IdProce])
{
nueva.CodigoOp = shared.memoriaInstrucciones.ElementAt(IdProce)[(bloque * 16) + (j * 4)];
nueva.RF1 = shared.memoriaInstrucciones.ElementAt(IdProce)[(bloque * 16) + (j * 4) + 1];
nueva.RF2_RD = shared.memoriaInstrucciones.ElementAt(IdProce)[(bloque * 16) + (j * 4) + 2];
nueva.RD_IMM = shared.memoriaInstrucciones.ElementAt(IdProce)[(bloque * 16) + (j * 4) + 3];
}
cacheI.bloqueInstruccion[bloque % 4, j] = nueva;
}
//Guarda la etiqueta del bloque subido
cacheI.etiquetas[bloque % 4] = bloque;
}
//Carga instruccion al IR de la cache
IR = cacheI.bloqueInstruccion[bloque % 4, palabra];
PC += 4; //COMPROBAR SI EL INCREMENTO ESTA BIEN
//ejecuta instruccion
if (ejecutarInstruccion(IR))
{
proximo.Finalizado = true;
proximo.horaFin = DateTime.Now;
}
numInst--;
}
if (proximo.Finalizado)
{
lock (Program.BusFinalizados)
{
shared.hilosFinalizados.ElementAt(IdProce).Add(proximo);
}
}
else
{
lock (Program.BusContextos)
{
proximo.IR = IR;
proximo.PC = PC;
shared.colasContextos.ElementAt(IdProce).Enqueue(proximo);
}
}
}
lock (Program.BusFinalizados)
{
hfin = shared.hilosFinalizados.ElementAt(IdProce).Count();
}
}
}
}
}
|
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace PIT_Server
{
public class Server
{
#region Vars
IPEndPoint EPoint;
#endregion
public Server( int port)
{
EPoint = new IPEndPoint(IPAddress.Any,port);
}
public void Start()
{
Task.Factory.StartNew(() => _start()).Wait();
}
void _start()
{
using (Socket Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Logger.LogIt(typeof(Server), "Server Listening ...");
Listener.Bind(EPoint);
Listener.Listen(1000);
ClientAccept(Listener);
}
}
void ClientAccept(Socket Listener)
{
while (true)
{
try
{
VisitorBase.NewVisitor(Listener.Accept());
}
catch(Exception e)
{
Logger.LogIt(typeof(Server), "Client accept error:" + e.Message);
break;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace Plugin.HttpTransferTasks
{
public interface IHttpTransferTasks
{
// TODO: when bad response or security challenge, need a way to set new token on header
IReadOnlyList<IHttpTask> CurrentTasks { get; }
event EventHandler<TaskListEventArgs> CurrentTasksChanged;
IHttpTask Upload(string uri, string localFilePath = null, bool useMeteredConnection = false);
IHttpTask Upload(TaskConfiguration config);
IHttpTask Download(string uri, bool useMeteredConnection = false);
//IHttpTask Download(string uri, string localFilePathWhereToSave = null, bool useMeteredConnection = false);
IHttpTask Download(TaskConfiguration config);
void CancelAll();
}
}
|
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 FrbaCommerce.Modelo;
using FrbaCommerce.ABM_Rol;
using FrbaCommerce.DAO;
namespace FrbaCommerce.Abm_Rol
{
public partial class ABMRol : Form
{
public ABMRol()
{
InitializeComponent();
}
public static void comboBoxFuncionalidades(ComboBox cmbFuncionalidad)
{
List<Funcionalidad> lista = DaoFuncionalidad.getAllFuncionalidades();
cmbFuncionalidad.DataSource = lista;
cmbFuncionalidad.DisplayMember = "funcionalidad";
cmbFuncionalidad.ValueMember = "id";
}
private void ABMRol_Load(object sender, EventArgs e)
{
}
private void bBuscar_Click(object sender, EventArgs e)
{
String rol = Convert.ToString(l_rol.Text);
SQLUtils.SQLUtils.cargarTabla(this.tb_roles, DaoRol.getRoles(rol));
}
private void bModificacion_Click(object sender, EventArgs e)
{
Rol rol = new Rol();
foreach (DataGridViewRow row in this.tb_roles.SelectedRows)
{
rol = row.DataBoundItem as Rol;
}
if (rol.idRol == 0)
{
MessageBox.Show("Por favor seleccione un Rol.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AltaRol ventana = new AltaRol();
ventana.setearRol(rol);
ventana.ShowDialog();
this.bBuscar_Click(sender, e);
}
private void bAlta_Click(object sender, EventArgs e)
{
AltaRol ventana = new AltaRol();
ventana.ShowDialog();
this.bBuscar_Click(sender, e);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
[AddComponentMenu("Hitman GO/Map/Map")]
public class Map : MonoBehaviour
{
Dictionary<Vector2Int, Waypoint> waypointsInMap = new Dictionary<Vector2Int, Waypoint>();
void Awake()
{
UpdateCoordinates();
}
#region private API
void UpdateCoordinates()
{
//find every waypoint in scene
Waypoint[] waypointsInScene = FindObjectsOfType<Waypoint>();
//order on x and y
Waypoint[] waypointsByOrder = waypointsInScene.OrderBy(zAxis => Mathf.RoundToInt(zAxis.transform.position.z)).ThenBy(xAxis => Mathf.RoundToInt(xAxis.transform.position.x)).ToArray();
//reset map
waypointsInMap.Clear();
int currentZ = Mathf.RoundToInt(waypointsByOrder[0].transform.position.z);
int x = 0;
int y = 0;
for (int i = 0; i < waypointsByOrder.Length; i++)
{
Waypoint currentWaypoint = waypointsByOrder[i];
//if go to next row, reset x and increase y
if (Mathf.RoundToInt(currentWaypoint.transform.position.z) > currentZ)
{
x = 0;
y++;
currentZ = Mathf.RoundToInt(currentWaypoint.transform.position.z);
}
//put in the dictionary and set coordinates
waypointsInMap.Add(new Vector2Int(x, y), currentWaypoint);
currentWaypoint.SetCoordinates(x, y);
x++;
}
}
#endregion
#region public API
public Waypoint GetWaypointInDirection(Waypoint currentWaypoint, Vector2Int direction)
{
//get coordinates
int x = currentWaypoint.X + direction.x;
int y = currentWaypoint.Y + direction.y;
//if there is a waypoint in these coordinates, return it
if (waypointsInMap.ContainsKey(new Vector2Int(x, y)))
return waypointsInMap[new Vector2Int(x, y)];
return null;
}
public Waypoint[] GetWaypointsInArea(Waypoint currentWaypoint, int area)
{
List<Waypoint> waypoints = new List<Waypoint>();
//foreach waypoint in the area
for(int x = currentWaypoint.X - area; x <= currentWaypoint.X + area; x++)
{
for(int y = currentWaypoint.Y - area; y <= currentWaypoint.Y + area; y++)
{
//don't add if is current waypoint
if (x == currentWaypoint.X && y == currentWaypoint.Y)
continue;
//if there is this waypoint, add to the list
if (waypointsInMap.ContainsKey(new Vector2Int(x, y)))
waypoints.Add(waypointsInMap[new Vector2Int(x, y)]);
}
}
return waypoints.ToArray();
}
#endregion
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace LinkKeeper.Entities
{
public class Link
{
[Key]
public int LinkId { get; set; }
[Required]
[MaxLength(2047)]
public string Url { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Required]
[MaxLength(100)]
public string Category { get; set; }
public bool IsFavorite { get; set; }
public string ApplicationUserId { get; set; }
[ForeignKey("ApplicationUserId")]
public ApplicationUser ApplicationUser { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform _CamLookAtTarget;
List<Transform> _TransformsToKeepInFocus = new List<Transform>();
public float _Smoothing = 4;
// Start is called before the first frame update
void Start()
{
PlayerController[] players = FindObjectsOfType<PlayerController>();
EchidnaController echidna = FindObjectOfType<EchidnaController>();
_TransformsToKeepInFocus.Add(echidna.transform);
_TransformsToKeepInFocus.Add(players[0].transform);
_TransformsToKeepInFocus.Add(players[1].transform);
}
// Update is called once per frame
void Update()
{
Vector3 average = Vector3.zero;
for (int i = 0; i < _TransformsToKeepInFocus.Count; i++)
{
average += _TransformsToKeepInFocus[i].position;
}
average /= _TransformsToKeepInFocus.Count;
_CamLookAtTarget.position = Vector3.Lerp(_CamLookAtTarget.position, average, Time.deltaTime * _Smoothing);
}
}
|
using Client.Helpers;
using Domen;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client.UIControllers
{
public class DeleteGrupaController
{
BindingList<GrupaLekova> grupe = new BindingList<GrupaLekova>();
internal void SetComboBox(ComboBox cbCriteria)
{
cbCriteria.DataSource = new List<string>() { "None", "ID", "Naziv" };
cbCriteria.SelectedIndex = -1;
}
internal void ShowGrupeWhere(TextBox txtValue, ComboBox cbCriteria, DataGridView dgvGrupe, Button btnDelete)
{
if (cbCriteria.SelectedItem != null && cbCriteria.SelectedItem.ToString() == "None")
{
txtValue.Enabled = false;
grupe = new BindingList<GrupaLekova>(Communication.Communication.Instance.GetGrupe(new GrupaLekova()));
}
else
{
if (cbCriteria.SelectedItem == null | FormHelper.EmptyFieldValidation(txtValue))
{
MessageBox.Show("Odaberite kriterijum i unesite njegovu vrednost.");
return;
}
if (cbCriteria.SelectedItem.ToString() == "ID" && !int.TryParse(txtValue.Text, out _))
{
MessageBox.Show("ID mora biti broj.");
return;
}
GrupaLekova grupaLekova = CreateGrupa(cbCriteria.SelectedItem.ToString(), txtValue.Text);
grupe = new BindingList<GrupaLekova>(Communication.Communication.Instance.GetGrupe(grupaLekova));
}
dgvGrupe.DataSource = grupe;
dgvGrupe.Columns["GrupaLekovaId"].HeaderText = "ID";
dgvGrupe.Columns["NazivGrupe"].HeaderText = "Naziv";
if (dgvGrupe.RowCount > 0)
{
MessageBox.Show("Sistem je pronašao grupe lekova po zadatoj vrednosti.");
btnDelete.Enabled = true;
}
else
{
MessageBox.Show("Sistem ne može da pronađe grupe lekova po zadatoj vrednosti.");
btnDelete.Enabled = false;
}
}
internal void GetAllGrupe(DataGridView dgvGrupe)
{
try
{
dgvGrupe.DataSource = Communication.Communication.Instance.GetGrupe(new GrupaLekova());
dgvGrupe.Columns["GrupaLekovaId"].HeaderText = "ID";
dgvGrupe.Columns["NazivGrupe"].HeaderText = "Naziv";
}
catch (Exception)
{
MessageBox.Show("Sistem ne može da učita grupe lekova.");
}
}
internal void DeleteGrupa(DataGridView dgvGrupe, ComboBox cbCriteria)
{
if (dgvGrupe.SelectedRows.Count != 1)
{
MessageBox.Show("Izaberite jednu grupu koji želite da obrišete.");
return;
}
if (grupe.Count == 0 | (cbCriteria.SelectedItem != null && cbCriteria.SelectedItem.ToString() == "None"))
{
grupe = new BindingList<GrupaLekova>(Communication.Communication.Instance.GetGrupe(new GrupaLekova()));
}
GrupaLekova grupaDelete = (GrupaLekova)dgvGrupe.SelectedRows[0].DataBoundItem;
grupaDelete.SelectWhere = $"where grupaid={grupaDelete.GrupaLekovaId}";
if (Communication.Communication.Instance.DeleteGrupa(grupaDelete))
{
GrupaLekova grupaLekova = grupe.First(g => g.GrupaLekovaId == grupaDelete.GrupaLekovaId);
grupe.Remove(grupaLekova);
dgvGrupe.DataSource = null;
dgvGrupe.DataSource = grupe;
MessageBox.Show("Sistem je obrisao grupu lekova.");
}
else
{
MessageBox.Show("Sistem ne može da obriše grupu lekova.");
}
}
private GrupaLekova CreateGrupa(string criteria, string value)
{
GrupaLekova grupaLekova = new GrupaLekova();
if (criteria == "ID")
{
grupaLekova.SelectWhere = $"where grupaid={int.Parse(value)}";
}
else
{
grupaLekova.SelectWhere = $"where nazivgrupe like '%{value}%'";
}
return grupaLekova;
}
}
}
|
using System.Collections.Generic;
using System.Windows;
namespace AreaCalculatorDesktop
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Polygon convex = new Convex(new List<Point>() { new Point(0, -10), new Point(0, 10), new Point(20, 10), new Point(20, -10) });
var line1 = new LinearObject(1, 5, 5, -7); // 5x\ +\ 5y\ -\ 7\ =0
var line2 = new LinearObject(2, 2, 5, -6); // 2x\ +\ 5y\ -\ 6\ =0
var line3 = new LinearObject(1, -7, 1, 30); // -7x\ +\ y\ + \ 30\ =0
var linearObjects = new List<LinearObject> { line1, line2, line3 };
//Polygon convex = new Convex(new List<Point>() { new Point(0, 0), new Point(0, 10), new Point(10, 10), new Point(10, 0) });
//var line1 = new LinearObject(1, 0, 1, -5);
//var line2 = new LinearObject(1, 1, 0, -5);
//var linearObjects = new List<LinearObject> { line1, line2 };
var areaCalculator = new AreaCalculator(convex, linearObjects);
// For a more accurate meaning, change second parametr rounding of Round()
var resultSquare = areaCalculator.SquareLinesInPolygon();
}
}
} |
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 BaseDeDonnees;
namespace MaisonDesLigues
{
public partial class FormAjoutVacation : Form
{
private BaseDeDonnees.Bdd UneConnexion = new Bdd("mdl", "mdl");
public FormAjoutVacation()
{
InitializeComponent();
}
private void BtnAnuler_Click(object sender, EventArgs e)
{
try
{
(new FrmPrincipale()).Show(this);
this.Hide();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void FormAjoutVacation_Load(object sender, EventArgs e)
{
if (UneConnexion.ObtenirDonnesOracle("atelier").Rows.Count > 0)
{
comboAtelier.DataSource = UneConnexion.ObtenirDonnesOracle("ATELIER");
comboAtelier.DisplayMember = "LIBELLEATELIER";
comboAtelier.ValueMember = "ID";
comboAtelier.SelectedValue = "ID";
comboAtelier.Enabled = true;
}
else
{
MessageBox.Show("Il existe aucun atelier");
FrmPrincipale form = new FrmPrincipale();
form.Show();
this.Hide();
}
}
private void BtnAjoutVacation_Click(object sender, EventArgs e)
{
/**Lors du clique bouton, les date et heure de vacation sont convertis en chaîne de caractères afins de les passer en paramètres
* de la méthode ajoutvacation**/
DateTime dateHeureDebut; ;
DateTime dateHeureFin;
dateHeureDebut = new DateTime(this.dateTimeJour.Value.Year, this.dateTimeJour.Value.Month, this.dateTimeJour.Value.Day, Convert.ToInt32(this.heureDeb.Value), Convert.ToInt32(this.minDeb.Value),00);
dateHeureFin = new DateTime(this.dateTimeJour.Value.Year, this.dateTimeJour.Value.Month, this.dateTimeJour.Value.Day, Convert.ToInt32(this.heureFin.Value), Convert.ToInt32(this.minFin.Value), 00);
if (this.dateTimeJour.Value != null && this.comboAtelier.SelectedValue != null && this.choixNumero.Value != 0)
{
string dDebut = Convert.ToString(dateHeureDebut.Day) + "/" + Convert.ToString(dateHeureDebut.Month) + "/" +
Convert.ToString(dateHeureDebut.Year) + " " + Convert.ToString(dateHeureDebut.Hour) + ":" +
Convert.ToString(dateHeureDebut.Minute) + ":00";
string dFin = Convert.ToString(dateHeureFin.Day) + "/" + Convert.ToString(dateHeureFin.Month) + "/" +
Convert.ToString(dateHeureFin.Year) + " " + Convert.ToString(dateHeureFin.Hour) + ":" +
Convert.ToString(dateHeureFin.Minute) + ":00";
UneConnexion.ajoutVacation(Convert.ToInt32(this.comboAtelier.SelectedValue), Convert.ToInt32(this.choixNumero.Value), dDebut, dFin);
}
else
{
MessageBox.Show("Merci de renseigner tout les champs");
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickScript : MonoBehaviour {
public Transform prefab;
public float forceMultiplier = 1;
public Vector3 offset = new Vector3(0 , 0 , 10f);
public LineRenderer lineRenderer;
private Vector3 startPoint;
private Vector3 endPoint;
private bool mouseIsDown = false;
void Update () {
if (Input.GetMouseButtonDown(0))
{
if (!mouseIsDown)
{
startPoint = Input.mousePosition;
startPoint.z = 0f;
}
mouseIsDown = true;
}
if (Input.GetMouseButtonUp(0))
{
endPoint = Input.mousePosition;
endPoint.z = 0f;
createMoon(startPoint , endPoint);
mouseIsDown = false;
lineRenderer.SetPosition(0 ,new Vector3(0, 0, 0));
lineRenderer.SetPosition(1 ,new Vector3(0, 0, 0));
}
if (mouseIsDown)
{
Vector3 startPos = Camera.main.ScreenToWorldPoint(startPoint);
Vector3 toPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
drawLine(startPos, toPos);
}
}
private void drawLine(Vector3 startPos, Vector3 toPos)
{
lineRenderer.SetPosition(0, startPos + offset);
lineRenderer.SetPosition(1, toPos + offset);
}
void createMoon(Vector3 startPoint, Vector3 endPoint) {
Vector3 direction = startPoint - endPoint;
direction = direction * forceMultiplier;
Vector3 position = Camera.main.ScreenToWorldPoint(startPoint);
position = position + offset;
Transform moon = Instantiate(prefab, position , transform.rotation);
Rigidbody2D rb = moon.GetComponent<Rigidbody2D>();
rb.AddForce(direction);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
namespace Combination
{
public partial class 温控报表 : Form
{
public 温控报表()
{
InitializeComponent();
}
Sql sql = new Sql();
private void Load_Data()
{
//this.dataGridView1.Rows.Clear();
string showTable = "Select b.area,a.checktime,b.temperature,a.temperature, " +
"case when ABS(cast(b.temperature as float)-cast(a.temperature as float) ) > cast(b.temperaturechange as float) then '1' else '0'end as 溫度檢測, case when ABS(cast(b.wet as float)-cast(a.wet as float)) > cast(b.wetchange as float) then '1' else '0'end as 濕度檢測,b.wet,a.wet FROM [chengyifbsscctest].[dbo].[temperature] a,[chengyifbsscctest].[dbo].[temperatureinfo] b where a.Machineno = b.Machineno " +
"and convert(varchar(10),a.checktime,120) = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "' order by checktime";
DataSet dsMainTable;
SqlServer sql = new SqlServer();
sql.Connect("ChengyiYuntech");
dsMainTable = sql.SqlCmd(showTable);
dataGridView1.DataSource = dsMainTable.Tables[0];
dataGridView1.Columns[0].HeaderText = "监控区域";
dataGridView1.Columns[1].HeaderText = "日期";
dataGridView1.Columns[2].HeaderText = "标准温度";
dataGridView1.Columns[3].HeaderText = "检测温度";
dataGridView1.Columns[6].HeaderText = "标准湿度";
dataGridView1.Columns[7].HeaderText = "检测湿度";
int tem;
int wet;
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
tem = int.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString());
wet = int.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());
if (tem == 1)
dataGridView1.Rows[i].Cells[3].Style.BackColor = Color.LightGoldenrodYellow;
if (wet == 1)
dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.LightGoldenrodYellow;
}
dataGridView1.Columns[4].Visible = false;
dataGridView1.Columns[5].Visible = false;
}
private void btnSeek_Click(object sender, EventArgs e)
{
Load_Data();
}
private void btnSetting_Click(object sender, EventArgs e)
{
tempBasicSetting tbsc = new tempBasicSetting();
tbsc.Show();
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
Export_Data();
}
catch (Exception)
{
MessageBox.Show("请将先前导出关闭");
}
}
private void Export_Data()
{
if (dataGridView1.Rows.Count != 0)
{
Excel.Application excelApp;
Excel._Workbook wBook;
Excel._Worksheet wSheet;
Excel.Range wRange;
string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string inputPath = System.Environment.CurrentDirectory;
string exportPath = path + @"\温控报表导出";
string filePath = inputPath + @"\温控报表";
// 開啟一個新的應用程式
excelApp = new Excel.Application();
// 讓Excel文件可見
excelApp.Visible = false;
// 停用警告訊息
excelApp.DisplayAlerts = false;
// 加入新的活頁簿
excelApp.Workbooks.Add(Type.Missing);
wBook = excelApp.Workbooks.Open(filePath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
// 設定活頁簿焦點
wBook.Activate();
wSheet = (Excel._Worksheet)wBook.Worksheets[1];
wSheet.Name = "温控报表";
wSheet.Cells[1, 2] = dateTimePicker1.Value.ToString("yyyy/MM/dd");
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
wSheet.Cells[i + 7, 1] = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
wSheet.Cells[i + 7, 2] = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
wSheet.Cells[i + 7, 3] = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
wSheet.Cells[i + 7, 4] = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
wSheet.Cells[i + 7, 5] = Convert.ToString(dataGridView1.Rows[i].Cells[6].Value);
wSheet.Cells[i + 7, 6] = Convert.ToString(dataGridView1.Rows[i].Cells[7].Value);
}
Excel.Range last = wSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range allRange = wSheet.get_Range("A7", last);
allRange.Font.Size = "14";
allRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous; //格線
allRange.Columns.AutoFit();
//Save Excel
wBook.SaveAs(exportPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
wBook = null;
wSheet = null;
wRange = null;
excelApp = null;
GC.Collect();
MessageBox.Show("导出成功");
}
else
{
MessageBox.Show("请确认是否有资料");
}
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex > -1)
{
string execute = Convert.ToString(this.dataGridView1.Rows[e.RowIndex].Cells["Column5"].Value);
if (Convert.ToString(execute) == "异常")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
}
string execute2 = Convert.ToString(this.dataGridView1.Rows[e.RowIndex].Cells["Column8"].Value);
if (Convert.ToString(execute2) == "异常")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.