Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hoofdstuk_7_Facade { public class Projector { public void On() { Console.WriteLine("Projector has turned on"); } public void WideScreenMode() { Console.WriteLine("Projector set to wide screen mode"); } public void Off() { Console.WriteLine("Projector has turned off"); } } }
using System; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference of type `float`. Inherits from `AtomEventReference&lt;float, FloatVariable, FloatEvent, FloatVariableInstancer, FloatEventInstancer&gt;`. /// </summary> [Serializable] public sealed class FloatEventReference : AtomEventReference< float, FloatVariable, FloatEvent, FloatVariableInstancer, FloatEventInstancer>, IGetEvent { } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; // Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled. // If you have enabled NRTs for your project, then un-comment the following line: // #nullable disable namespace Project3.Models { public partial class TblOrderedLaptop { public int Oid { get; set; } public int? Lid { get; set; } public int? SellerId { get; set; } public int? CustomerId { get; set; } public virtual TblCustomer Customer { get; set; } public virtual AvailableLaptop L { get; set; } public virtual TblSeller Seller { get; set; } } }
namespace API.Repositories { using System.Collections.Concurrent; using System.Collections.Generic; using API.Models; public class ValueRepository : IValueRepository { private readonly ConcurrentDictionary<int, Value> store = new ConcurrentDictionary<int, Value>(); public IEnumerable<Value> Get() { return this.store.Values; } public Value Get(int id) { this.store.TryGetValue(id, out var value); return value; } public Value Upsert(Value value) { this.store.AddOrUpdate(value.Id, value, (key, oldValue) => value); return value; } public void Delete(int id) { this.store.TryRemove(id, out _); } } }
using System; using System.Collections.Generic; using System.Text; using System.Globalization; using System.Xml.Serialization; using DBDiff.Schema.Model; namespace DBDiff.Schema.Sybase.Model { public class Column : SybaseSchemaBase { private Boolean identity; private string type; private int size; private Boolean nullable; private int precision; private int scale; private Boolean hasIndexDependencies; private int position; public Column(Table parent):base(StatusEnum.ObjectTypeEnum.Column) { this.Parent = parent; } /// <summary> /// Clona el objeto Column en una nueva instancia. /// </summary> public Column Clone(Table parent) { Column col = new Column(parent); col.Id = this.Id; col.Identity = this.Identity; col.HasIndexDependencies = this.HasIndexDependencies; col.Name = this.Name; col.Nullable = this.Nullable; col.Precision = this.Precision; col.Scale = this.Scale; col.Size = this.Size; col.Status = this.Status; col.Type = this.Type; col.Position = this.Position; //col.Constraints = this.Constraints.Clone(this); return col; } public int Position { get { return position; } set { position = value; } } /// <summary> /// Cantidad de digitos que permite el campo (solo para campos Numeric). /// </summary> public int Scale { get { return scale; } set { scale = value; } } /// <summary> /// Cantidad de decimales que permite el campo (solo para campos Numeric). /// </summary> public int Precision { get { return precision; } set { precision = value; } } /// <summary> /// Indica si el campos permite valores NULL o no. /// </summary> public Boolean Nullable { get { return nullable; } set { nullable = value; } } /// <summary> /// Indica en bytes, el tamaņo del campo. /// </summary> public int Size { get { return size; } set { size = value; } } /// <summary> /// Nombre del tipo de dato del campo. /// </summary> public string Type { get { return type; } set { type = value; } } /// <summary> /// Indica si la columna es usada en un indice. /// </summary> public Boolean HasIndexDependencies { get { return hasIndexDependencies; } set { hasIndexDependencies = value; } } /// <summary> /// Indica si es campo es Identity o no. /// </summary> public Boolean Identity { get { return identity; } set { identity = value; } } /*public Constraints DependenciesConstraint(string columnName) { Table ParenTable = (Table)Parent; Constraints cons = new Constraints(ParenTable); for (int index = 0; index < ParenTable.Constraints.Count; index++) { if (ParenTable.Constraints[index].Columns.Find(columnName) != null) { cons.Add(ParenTable.Constraints[index]); } } return cons; }*/ /// <summary> /// Devuelve el schema de la columna en formato SQL. /// </summary> public string ToSQL(Boolean sqlConstraint) { string sql = ""; sql += "[" + Name + "] "; sql += Type; if (Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") || Type.Equals("nchar") || Type.Equals("nvarchar")) { if (Type.Equals("nchar") || Type.Equals("nvarchar")) sql += " (" + (Size / 2).ToString(CultureInfo.InvariantCulture) + ")"; else sql += " (" + Size.ToString(CultureInfo.InvariantCulture) + ")"; } if (Type.Equals("numeric") || Type.Equals("decimal")) sql += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," + Scale.ToString(CultureInfo.InvariantCulture) + ")"; if (Identity) sql += " IDENTITY "; if (Nullable) sql += " NULL"; else sql += " NOT NULL"; return sql; } /// <return> /// Compara dos campos y devuelve true si son iguales, false en caso contrario. /// </summary> /// <param name="destino"> /// Objeto Column con el que se desea comparar. /// </param> public StatusEnum.ObjectStatusType CompareStatus(Column destino) { if (destino != null) { StatusEnum.ObjectStatusType status = StatusEnum.ObjectStatusType.OriginalStatus; if (!Compare(this, destino)) { if (destino.Identity == this.Identity) { } } return status; } else throw new ArgumentNullException("destino"); } /// <summary> /// Compara solo las propiedades de dos campos relacionadas con los Identity. Si existen /// diferencias, devuelve falso, caso contrario, true. /// </summary> public static Boolean CompareIdentity(Column origen, Column destino) { if (destino == null) throw new ArgumentNullException("destino"); if (origen == null) throw new ArgumentNullException("origen"); if (origen.Identity != destino.identity) return false; return true; } /// <summary> /// Compara dos campos y devuelve true si son iguales, caso contrario, devuelve false. /// </summary> public static Boolean Compare(Column origen, Column destino) { if (destino == null) throw new ArgumentNullException("destino"); if (origen == null) throw new ArgumentNullException("origen"); if (origen.Nullable != destino.nullable) return false; if (origen.Precision != destino.precision) return false; if (origen.Scale != destino.scale) return false; //Si el tamaņo de un campo Text cambia, entonces por la opcion TextInRowLimit. if ((origen.Size != destino.size) && (origen.Type.Equals(destino.Type)) && (!origen.Type.Equals("text"))) return false; if (!origen.Type.Equals(destino.type)) return false; return CompareIdentity(origen, destino); } } }
using DrugMgmtSys.codes; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DrugMgmtSys { public partial class Main : Form { private int KEY; private bool canOrder=false; Order order = null; public bool CanOrder { get { return canOrder; } set { canOrder = value; } } public Main() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { ForbidSortColumn(dataGridView_K); //显示 BindAll_X(); } #region 查询按钮 /// <summary> /// 药品销售页面查询按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //查询 BindByTrim_X(); } /// <summary> /// 库存页面查询按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button6_Click(object sender, EventArgs e) { BindByTrim_K(); } #endregion #region 显示全部按钮 /// <summary> /// 销售页面显示全部按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button5_Click(object sender, EventArgs e) { BindAll_X(); } /// <summary> /// 库存页面显示全部按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button7_Click(object sender, EventArgs e) { BindAll_K(); } #endregion #region 出售按钮 private void dataGridView_X_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex != 0 || e.RowIndex == -1) { return; } if (CanOrder) { double num = getIntputNum(); //获取当前行的索引 int index = dataGridView_X.CurrentCell.RowIndex; //获取当前行对应的“编号”列的值(主键) int key = Int32.Parse(dataGridView_X.Rows[index].Cells["编号"].Value.ToString()); //更新库存 updateReserve(num, key); Drug drug = new Drug(key); //向订单添加 order.add(drug); order.setNum(num); BindAll_X(); } else { MessageBox.Show("请先点击上方“开处药方”按钮,建立新的药方再行出售!","温馨提示"); } } #endregion #region 查询所有并绑定 /// <summary> /// 销售页面查询所有并绑定 /// </summary> protected void BindAll_X() { string sql_select_drug_X = "SELECT d_id,d_name,u_name,d_spec,d_reserve,d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id"; DataSet ds = MySqlTools.GetDataSet(sql_select_drug_X); dataGridView_X.DataSource = ds.Tables[0]; } /// <summary> /// 库存页面查询所有并绑定 /// </summary> protected void BindAll_K() { string sql_select_drug_K = "SELECT d_id,d_name,u_name,d_spec,d_origin,d_lot_num,d_reserve,d_w_price,d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id"; DataSet ds = MySqlTools.GetDataSet(sql_select_drug_K); DataTable dt = ds.Tables[0]; //添加一列“tb_progit” dt.Columns.Add("tb_progit"); //为该列的每一行赋值 for (int i = 0; i < dt.Rows.Count; i++) { dt.Rows[i]["tb_progit"] = Convert.ToDouble(dt.Rows[i][8]) - Convert.ToDouble(dt.Rows[i][7]); } dataGridView_K.DataSource = dt; getSum(); } /// <summary> /// 销售记录查询 /// </summary> protected void BindAndShow() { DateTime dt = dateTimePicker1.Value; string time=dt.ToLongDateString().ToString(); string sql =string .Format("SELECT o_id,o_name,o_num,o_r_price,o_money FROM tb_order where o_time='{0}'", time); DataSet ds = MySqlTools.GetDataSet(sql); DataTable dataTable = ds.Tables[0]; dataGridView_M.DataSource=dataTable; //求和 double sum_m = 0; double sum_r = 0; for (int i = 0; i < dataGridView_M.Rows.Count; i++) { sum_m += Convert.ToDouble(dataGridView_M.Rows[i].Cells["利润"].Value); sum_r += Convert.ToDouble(dataGridView_M.Rows[i].Cells["售价"].Value); } lb_r.Text = sum_r.ToString()+"元"; lb_m.Text = sum_m.ToString() + "元"; } #endregion #region 条件查询并绑定 /// <summary> /// 销售页面按条件绑定 /// </summary> private void BindByTrim_X() { string d_name = string.Format("'%{0}%'", textBox_select_X.Text); string sql_select_by_d_name = "SELECT d_id,d_name,u_name,d_spec,d_reserve,d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id AND d_name LIKE " + d_name; DataSet ds = MySqlTools.GetDataSet(sql_select_by_d_name); dataGridView_X.DataSource = ds.Tables[0]; } /// <summary> /// 库存页面按条件绑定 /// </summary> private void BindByTrim_K() { string d_name = string.Format("'%{0}%'", textBox_select_K.Text); string sql_select_by_d_name = "SELECT d_id, d_name, u_name, d_spec, d_origin, d_lot_num, d_reserve, d_w_price, d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id AND d_name LIKE " + d_name; DataSet ds = MySqlTools.GetDataSet(sql_select_by_d_name); DataTable dt = ds.Tables[0]; //添加一列“tb_progit” dt.Columns.Add("tb_progit"); //为该列的每一行赋值 for (int i = 0; i < dt.Rows.Count; i++) { dt.Rows[i]["tb_progit"] = Convert.ToDouble(dt.Rows[i][8]) - Convert.ToDouble(dt.Rows[i][7]); } dataGridView_K.DataSource = dt; getSum(); } #endregion /// <summary> /// 计算库存合计信息 /// </summary> private void getSum() { double sum_w = 0; double sum_r = 0; double sum_money = 0; for (int i = 0; i < dataGridView_K.Rows.Count; i++) { sum_w += Convert.ToDouble(dataGridView_K.Rows[i].Cells["批发价"].Value)*Convert.ToDouble(dataGridView_K.Rows[i].Cells["库存"].Value); sum_r += Convert.ToDouble(dataGridView_K.Rows[i].Cells["零售"].Value) * Convert.ToDouble(dataGridView_K.Rows[i].Cells["库存"].Value); sum_money += Convert.ToDouble(dataGridView_K.Rows[i].Cells["利"].Value) * Convert.ToDouble(dataGridView_K.Rows[i].Cells["库存"].Value); } lb_w_sum.Text = sum_w.ToString() + "元"; lb_r_sum.Text = sum_r.ToString() + "元"; lb_money.Text = sum_money.ToString() + "元"; } #region 清空文本框 private void textBox_select_X_MouseClick(object sender, MouseEventArgs e) { textBox_select_X.Text = ""; } private void textBox_select_K_MouseClick(object sender, MouseEventArgs e) { textBox_select_K.Text = ""; } #endregion #region 获取输入 /// <summary> /// 获取用户输入数量 /// </summary> /// <returns>输入的值</returns> private double getIntputNum() { InputNumDiaLog form = new InputNumDiaLog(); form.ShowDialog(); return form.Input; } #endregion /// <summary> /// 更新库存方法 /// </summary> /// <param name="num">用户输入</param> /// <param name="key">主键</param> /// <param name="b">true为增加,false为减少</param> private void updateReserve(double num,int key) { if (num==0) { return; } string sql_SelectReserve = "SELECT d_reserve FROM tb_drug WHERE d_id=" + key; double reserve = (double)MySqlTools.ExecuteScalar(sql_SelectReserve); if (reserve - num<0) { MessageBox.Show(" 该药品剩余库存为:" + reserve + "\n 库存不足,请尽快补货!", "温馨提示"); } else { string sql_updateReserve = string.Format("UPDATE tb_drug SET d_reserve={0} WHERE d_id={1}", reserve - num, key); // sql_select_r_price = "SELECT d_r_price FROM tb_drug WHERE d_id=" + key; //double money =num*(double)MySqlTools.ExecuteScalar(sql_select_r_price); if (MySqlTools.ExecuteNonQuery(sql_updateReserve) == 1) { MessageBox.Show("出库成功!", "温馨提示"); } else { MessageBox.Show("出库失败!", "温馨提示"); } } //} } #region 库存页面删除、修改按钮 /// <summary> /// 修改药品信息按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button4_Click(object sender, EventArgs e) { if (KEY==0) { MessageBox.Show("请先选中一行数据!", "温馨提示"); return; } //创建drug,获取当前信息 Drug drug = new Drug(KEY); InfoMgmtForm infoForm = new InfoMgmtForm(KEY); //为组件赋值:当前值 infoForm.setValue(drug.Name, drug.Unit, drug.Spec, drug.Origin, drug.Lot_num, drug.Reserve, drug.W_price, drug.R_price); infoForm.asChange();//更改按钮 infoForm.ShowDialog(); BindAll_K(); } /// <summary> /// 删除按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { string caption = "温馨提示"; string message = "是否删除该条数据?"; MessageBoxButtons btn = MessageBoxButtons.YesNo; DialogResult result = new DialogResult(); result = MessageBox.Show(message, caption, btn); if (result == System.Windows.Forms.DialogResult.Yes) { string sql = "delete from tb_drug where d_id=" + KEY; if (MySqlTools.ExecuteNonQuery(sql) > 0) { MessageBox.Show("成功删除该条记录!", "温馨提示"); BindAll_K(); } } } #endregion #region 添加数据 /// <summary> /// 添加药品 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { InfoMgmtForm infoForm = new InfoMgmtForm(); infoForm.ShowDialog(); //BindAll_K(); tabControl_main.SelectedIndex = 0; tabControl_main.SelectedIndex = 1; } #endregion #region 选项卡切换处理 /// <summary> /// 更改选项卡后触发的事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tabControl_main_SelectedIndexChanged(object sender, EventArgs e) { string i = tabControl_main.SelectedTab.Text; switch (i) { case "药品销售": BindAll_X(); break; case "药品库存信息管理": BindAll_K(); break; case "销售记录": BindAndShow(); break; } } #endregion #region 处理操作 /// <summary> /// 点击单元格时,获取当前行索引 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGridView_K_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex==-1) { return; } this.dataGridView_K.Rows[e.RowIndex].Selected = true;//是否选中当前行 int index = e.RowIndex; //获取当前行对应的“编号”列的值(主键) DataTable dt =(DataTable)dataGridView_K.DataSource; KEY = (int)dt.Rows[index][0]; } /// <summary> /// 禁止DataGrideView排序 加载时调用 /// </summary> /// <param name="dgv"></param> public static void ForbidSortColumn(DataGridView dgv) { for (int i = 0; i < dgv.Columns.Count; i++) { dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable; } } /// <summary> /// 检索时间改变 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dateTimePicker1_ValueChanged(object sender, EventArgs e) { BindAndShow(); } #endregion /// <summary> /// 版权方网站 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void label14_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("https://www.llanc.cn/"); } /// <summary> /// 开处药方 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button8_Click(object sender, EventArgs e) { if (button8.Text=="开处药方") { button8.Text = "结算"; button8.ForeColor = Color.Red; CanOrder = true;//可以出售 order = new Order();//新建订单 MessageBox.Show("创建药方成功,请点击“出售”按钮添加药品", "温馨提示"); } else if (button8.Text == "结算") { button8.Text = "开处药方"; button8.ForeColor = Color.Green; CanOrder = false;//不可出售 ShowOrder showOrderForm = new ShowOrder(order.getMessage()); showOrderForm.ShowDialog(); } } #region 登录处理 /// <summary> /// 登录按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_login_Click(object sender, EventArgs e) { string pwd = tb_pwd.Text; string sql = string.Format("SELECT * FROM tb_pwd WHERE pwd='{0}'", pwd); try { if ((int)MySqlTools.ExecuteScalar(sql) == 1) { panl_Login.Visible = false; } } catch (Exception) { MessageBox.Show("您的密码输入有误,请重新输入!", "温馨提示"); } } /// <summary> /// 修改密码按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void bun_ch_Click(object sender, EventArgs e) { string sql = string.Format("UPDATE tb_pwd SET pwd='{0}' where id=1",tb_pwdCh.Text); if ((int)MySqlTools.ExecuteNonQuery(sql)==1) { MessageBox.Show("密码更改成功,请牢记!\n" + tb_pwdCh.Text, "温馨提示"); } else { MessageBox.Show("密码更改失败!", "温馨提示"); } } #endregion private void lb__Click(object sender, EventArgs e) { } #region 药品销售记录删除 private void button9_Click(object sender, EventArgs e) { string caption = "温馨提示"; string message = "是否删除该记录?"; MessageBoxButtons btn = MessageBoxButtons.YesNo; DialogResult result = new DialogResult(); result = MessageBox.Show(message, caption, btn); if (result == System.Windows.Forms.DialogResult.Yes) { DateTime dt = dateTimePicker1.Value; string time = dt.ToLongDateString().ToString(); string sql_day = string.Format("delete from tb_order where o_time='{0}'", time); if (MySqlTools.ExecuteNonQuery(sql_day) > 0) { MessageBox.Show("成功删除该记录!", "温馨提示"); BindAndShow(); } } } private void button10_Click(object sender, EventArgs e) { string caption = "温馨提示"; string message = "是否删除该记录?"; MessageBoxButtons btn = MessageBoxButtons.YesNo; DialogResult result = new DialogResult(); result = MessageBox.Show(message, caption, btn); if (result == System.Windows.Forms.DialogResult.Yes) { DateTime dt = dateTimePicker1.Value; string time = dt.ToLongDateString().ToString(); string sql ="delete from tb_order"; if (MySqlTools.ExecuteNonQuery(sql) > 0) { MessageBox.Show("成功删除该记录!", "温馨提示"); BindAndShow(); } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MethodsExercise { class Program { static void Main(string[] args) { ////Method One ClassNum Dog = new ClassNum(); //int input1 = 8; //int Results = Dog.NumMethod(input1); //Console.WriteLine(Results); //Console.ReadLine(); //Method Two float input2 = 4.25f; float Results2 = Dog.NumMethod(input2); Console.WriteLine(Results2); Console.ReadLine(); //Method Three string input3 = "20"; //int ren = Convert.ToInt32(input3); int Results3 = Dog.NumMethod(input3); Console.WriteLine(Results3); Console.ReadLine(); } } }
namespace DataLayer { using System; using System.Data; using System.Data.SqlClient; public class TravelManager { public DataSet SearchTravelDetails(string tr_no) { SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@tr_no", tr_no) }; return clsConnectionString.returnConnection.executeSelectQueryDataSet("usp_trl_travel_details", CommandType.StoredProcedure, parameterArray); } public DataTable SearchTravelQuery(string trav_name, string destination, string dateFrom, string dateTo, string capacity, string travel_type, string tr_no, string travel_mode, string is_emergency) { DateTime time = (dateFrom != "") ? Convert.ToDateTime(dateFrom) : Convert.ToDateTime("1753-01-01"); DateTime time2 = (dateTo != "") ? Convert.ToDateTime(dateTo) : DateTime.MaxValue; SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@traveller_name", trav_name.Trim()), new SqlParameter("@destination", destination.Trim()), new SqlParameter("@start_date", time), new SqlParameter("@end_date", time2), new SqlParameter("@capacity", capacity), new SqlParameter("@travel_type", travel_type), new SqlParameter("@tr_no", tr_no.Trim()), new SqlParameter("@travel_mode", travel_mode), new SqlParameter("@is_emergency", is_emergency) }; return clsConnectionString.returnConnection.executeSelectQuery("usp_trl_travel_query", CommandType.StoredProcedure, parameterArray); } public DataTable SearchTRLAsOfDate(string source_name) { SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@source_name", source_name) }; return clsConnectionString.returnConnection.executeSelectQuery("usp_upload_log_list", CommandType.StoredProcedure, parameterArray); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace FileIO { class Program { static void Main(string[] args) { string input = ""; // nuskaityk failą į input kintamąjį FindSportsmenWithLongestFullname(input); FindSportsmenWithLongestFullnameLikeAPro(input); SortSportsmenByFullnameLength(input); } public static void FindSportsmenWithLongestFullname(string input) { //sukarpyk input į string[] //surask ilgiausią vardą //išvesk į failą longestNameV1.txt } public static void FindSportsmenWithLongestFullnameLikeAPro(string input) { //sukarpyk input į List<string> //surask ilgiausią vardą //išvesk į failą longestNameV2.txt } public static void SortSportsmenByFullnameLength(string input) { //sukarpyk input į List<string> //surūšiuok pagal vardo ilgį //išvesk į failą sortedNames.txt } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AtendimentoProntoSocorro.Data; using AtendimentoProntoSocorro.Models; using AtendimentoProntoSocorro.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AtendimentoProntoSocorro.Controllers { public class DadosClinicosController : Controller { private readonly ApplicationDbContext _context; private readonly IDadosClinicosRepository dadosClinicosRepository; public DadosClinicosController(ApplicationDbContext context, IDadosClinicosRepository dadosClinicosRepository) { _context = context; this.dadosClinicosRepository = dadosClinicosRepository; } public IActionResult Atender(int idFicha) { if (ModelState.IsValid) { var dados = dadosClinicosRepository.GetDadosClinicos(idFicha); return View(dados); } return View(); } [HttpPost] public async Task<IActionResult> GravarDadosClinicos(DadoClinico dadosClinicos) { if (ModelState.IsValid) { //var _idFicha = //Ficha ficha = fichaRepository.GetFicha(_idFicha); _context.Add(dadosClinicos); await _context.SaveChangesAsync(); return RedirectToAction("Aguardando", "Ficha"); } return View(dadosClinicos); } // GET: DadosClinicos public ActionResult Index() { return View(); } } }
#if UNITY_EDITOR using System; using System.Collections; using System.Collections.Generic; using System.Linq; using BP12; using DChild.Gameplay.Objects; using DChild.Gameplay.Objects.Characters.Enemies; using Sirenix.OdinInspector; using UnityEngine; namespace DChildDebug { public class DebugMinionSpawner : SingletonBehaviour<DebugMinionSpawner> { public DebugMinionDatabase database; public Transform spawnPoint; public Transform m_target; public static TypeCache<Minion> m_minionCache; private static Dictionary<Type, Type> m_controllerCache; private static GameObject m_minionInstance; public static int m_minionIndex; public static Transform target => m_instance.m_target; public static void NextMinion() { DestroyMinion(); IterateIndex(1); SpawnMinion(); } public static void PreviousMinion() { DestroyMinion(); IterateIndex(-1); SpawnMinion(); } public static void SpawnMinion(string minionName) { DestroyMinion(); var minionType = m_minionCache.GetType(minionName); m_minionIndex = m_instance.database.GetIndexOfMinionType(minionType); SpawnMinion(); } private static void DestroyMinion() { if (m_minionInstance != null) { Destroy(m_minionInstance); Destroy(m_instance.GetComponent<MinionAttackDebugger>()); } } private static void IterateIndex(int iteration) => m_minionIndex = (int)Mathf.Repeat(m_minionIndex + iteration, m_instance.database.Count); private static void SpawnMinion() { var spawnPoint = m_instance.spawnPoint; m_minionInstance = Instantiate(m_instance.database.GetMinion(m_minionIndex), spawnPoint.position, Quaternion.identity); var minionSentience = m_minionInstance.GetComponent<ISentientBeing>(); minionSentience.EnableBrain(false); var controller = (MinionAttackDebugger)m_instance.gameObject.AddComponent(m_controllerCache[minionSentience.GetType()]); controller.Set(m_minionInstance.GetComponent<Minion>()); } protected override void Awake() { base.Awake(); m_minionCache = new TypeCache<Minion>(); InstantiateControllerCache(); } private static void InstantiateControllerCache() { var controllerGO = new GameObject("Something"); m_controllerCache = new Dictionary<Type, Type>(); var attackDebuggers = Reflection.GetDerivedClasses(typeof(MinionAttackDebugger)); for (int i = 0; i < attackDebuggers.Length; i++) { var type = attackDebuggers[i]; var controller = (MinionAttackDebugger)controllerGO.AddComponent(type); m_controllerCache.Add(controller.monsterType, type); } Destroy(controllerGO); } } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DelftTools.Controls.Swf.Test.Table.TestClasses { public class ClassWithTwoProperties { public string Property1 { get; set; } public string Property2 { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using cyrka.api.common.events; using MongoDB.Driver; using MongoDB.Driver.Linq; namespace cyrka.api.infra.stores.events { public class MongoEventStore : IEventStore, IDisposable { const string CollectionKeyName = "events"; public string NexterChannelKey => CollectionKeyName; public MongoEventStore(IMongoDatabase mongoDatabase, IEnumerable<IDbMapping> maps) { foreach (var map in maps) { map.DefineMaps(); } _eventsChannel = new Subject<Event>(); _mDb = mongoDatabase; try { _eventsCollection = _mDb.GetCollection<Event>(CollectionKeyName); } catch (Exception e) { throw e; } } public async Task<ulong> GetLastStoredId() { try { return ( await _eventsCollection.AsQueryable() .OrderByDescending(e => e.Id) .FirstOrDefaultAsync() )? .Id ?? 0; } catch (Exception e) { throw e; } } public async Task<Event[]> FindAllAfterId(ulong id) { return ( await _eventsCollection.AsQueryable() .Where(e => e.Id > id) .OrderBy(e => e.Id) .ToListAsync() ) .ToArray(); } public async Task<Event[]> FindAllOfAggregateById<TAggregate>(string aggregateId) where TAggregate : class { var aggregateName = typeof(TAggregate).Name; var query = _eventsCollection.AsQueryable() .Where(e => e.EventData.AggregateType == aggregateName && e.EventData.AggregateId == aggregateId); return (await query.OrderBy(e => e.Id).ToListAsync()).ToArray(); } public async Task<Event[]> FindLastNWithDataOf<TEventData>(int n, Expression<Func<Event, bool>> eventDataPredicate = null) where TEventData : EventData { var query = _eventsCollection.AsQueryable() .Where(e => e.EventData is TEventData); if (eventDataPredicate != null) query = query.Where(eventDataPredicate); return (await query.OrderByDescending(e => e.Id).Take(n).ToListAsync()).ToArray(); } public async Task Store(Event @event) { try { await _eventsCollection.InsertOneAsync(@event); _eventsChannel.OnNext(@event); } catch (Exception e) { throw e; } } public IObservable<Event> AsObservable(bool fromStart = false) { if (fromStart) { var storedEvents = _eventsCollection.AsQueryable() .OrderBy(e => e.Id) .ToObservable(); return storedEvents.Concat(_eventsChannel.AsObservable()); } return _eventsChannel.AsObservable(); } public void Dispose() { if (_eventsChannel != null && !_eventsChannel.IsDisposed) { _eventsChannel.OnCompleted(); _eventsChannel.Dispose(); } } private readonly IMongoDatabase _mDb; private readonly IMongoCollection<Event> _eventsCollection; private readonly Subject<Event> _eventsChannel; } }
using System; using System.Runtime.InteropServices.ComTypes; using System.Security.Cryptography.X509Certificates; namespace assign_cab301 { class Program { //Create objects of the class that we have written private static MovieCollection movieCollectionObj; private static MemberCollection memberCollectionObj; private static Member memberObj; /// <summary> /// This is the main method and is the starting point for the program /// This is the place where everything gets called. /// </summary> /// <param name="args"></param> static void Main(string[] args) { int userInputs = -1; movieCollectionObj = new MovieCollection(); memberCollectionObj = new MemberCollection(); do { Console.WriteLine( "\nWelcome to the Community Library\n" + "===========Main Menu============\n" + " 1. Staff Login\n" + " 2. Membr Login\n" + " 0. Exit\n" + "================================\n"); userInputs = getUserInputsInt(" Please make a selection (1-2, or 0 to exit): ", 0, 2); if (userInputs == 1 || userInputs == 2) { Console.Write("Enter Username: (LastnameFirstname): "); string uName = Console.ReadLine(); Console.Write("Enter Password: "); string uPass = Console.ReadLine(); if (userInputs == 1) { if (uName == "staff" && uPass == "today123") { Console.WriteLine(); menuForStaffAndItsOperation(); Console.WriteLine(); } else { Console.WriteLine("Incorrect Password or Username! Try again\n"); } } if (userInputs == 2) { memberObj = memberCollectionObj.userLoginToLibrary(uName, uPass); if (memberObj != null) { Console.WriteLine(); menuForMemberAndItsOperation(); Console.WriteLine(); } else { Console.WriteLine("Incorrect Password or Username! Try again.\n"); } } } } while (userInputs != 0); } /// <summary> /// This function is for the member's menu to allow members do the /// operation of displaying, borrowing, returning, listing, /// displaying top 10 movies and retuning to main menu. /// </summary> public static void menuForMemberAndItsOperation() { int userInputs = -1; while (userInputs != 0) { Console.WriteLine( "\n\n" + "===========Member Menu============\n" + "1. Display all movies\n" + "2. Borrow a movie DVD\n" + "3. Return a movie DVD\n" + "4. List current borrowed movie DVDs\n" + "5. Display top 10 most popular movies\n" + "0. Return to main menu\n" + "==================================\n"); userInputs = getUserInputsInt(" Please make a selection (1-5 or 0 to return to main menu): ", 0, 5); switch (userInputs) { case 0: //exit to main menu break; case 1: memberDisplayEntireAddedMovies(); break; case 2: memberBorrowingMovies(); break; case 3: memberReturnsMovieToLibrary(); break; case 4: showAListForEachMemberOfCurrentlyBorrowedMovies(); break; case 5: showTheTopTenPopularMovies(); break; } } } /// <summary> /// This function is a helper function which helps the member-menu functionality and helping in showing top ten moives /// </summary> private static void showTheTopTenPopularMovies() { movieCollectionObj.showingPopularMoviesRentedTenTimes(); } /// <summary> /// This function shows a list of movies each member have borrowed. /// </summary> private static void showAListForEachMemberOfCurrentlyBorrowedMovies() { memberObj.showMovieDVDsCurrentlyBorrowed(); } /// <summary> /// This function is also a member functionality which allow the member to return movies to the library. /// </summary> private static void memberReturnsMovieToLibrary() { Console.Write("Enter movie title: "); string userInput = Console.ReadLine(); if (memberObj.checkIsMovieBorrowed(userInput)) { memberObj.memberReturnedMovie(userInput); Console.WriteLine("You have successfully returned Movie DVD \n"); } else { Console.WriteLine("You have not borrowed movie now.\n\n"); } } /// <summary> /// This function allow the members to borrow movies which is a helper function of the member-menu functionality. /// </summary> public static void memberBorrowingMovies() { Console.Write("Enter movie title: "); string userInput = Console.ReadLine(); if (!memberObj.checkIsMovieBorrowed(userInput)) { if (movieCollectionObj.movieBorrowingProcess(userInput)){ memberObj.borrowingMovie(userInput); Console.WriteLine("You borrowed " + userInput + "\n"); } } else { Console.WriteLine("You have already borrowed movie.\n"); } } /// <summary> /// This function is a helper function for the member-menu which allow users to display all available movies. /// </summary> public static void memberDisplayEntireAddedMovies() { movieCollectionObj.showMoviesInOrder(); } /// <summary> /// This method/function is for staff menu and it's operationss, its display and its error handling. /// </summary> private static void menuForStaffAndItsOperation() { int userInputs = -1; while(userInputs != 0) { Console.WriteLine( "\n===========Staff Menu============\n" + "1. Add a new movie DVD\n" + "2. Remove a movie DVD\n" + "3. Register a new member\n" + "4. Find a registered member's phone number\n" + "0. Return to main menu\n" + "==================================\n"); userInputs = getUserInputsInt(" Please make a selection (1-4 or 0 to return to main menu): ", 0, 4); switch (userInputs) { case 0: //exit to main menu break; case 1: functionalityOfNewMovieAddition(); break; case 2: staffRemoveMovie(); break; case 3: staffRegisteringNewMembersToSystem(); break; case 4: phoneNumberLookUpForMembers(); break; } } } /// <summary> /// This function is a helper function of the staff-menu functionality, which allow the staff member to /// look up a member's phone number by typing their first and last name. /// </summary> private static void phoneNumberLookUpForMembers() { Console.Write("Enter member's first name: "); string fName = Console.ReadLine(); Console.Write("Enter member's last name: "); string lName = Console.ReadLine(); Member objMember = memberCollectionObj.membersPhoneNumberFinder(fName, lName); if (objMember != null) { Console.WriteLine(fName + " " + lName + "'s phone number is: " + objMember.UserPhoneNumber + "\n"); } else { Console.WriteLine("This member does not exist." + "\n"); } } /// <summary> /// This function is a helper function of the staff-menu functionality which allows the staff to /// register new members to the system. /// </summary> private static void staffRegisteringNewMembersToSystem() { Console.Write("Enter member's first name: "); string fName = Console.ReadLine(); Console.Write("Enter member's last name: "); string lName = Console.ReadLine(); if (!memberCollectionObj.memberIsAddedAlready(fName, lName)) { Console.Write("Enter member's address: "); string userAddr = Console.ReadLine(); Console.Write("Enter member's phone number: "); string userPhoneNo = Console.ReadLine(); string userPassword = ""; while (!inputedCorrectPass(userPassword)) { Console.Write("Enter member's password(4 digits): "); userPassword = Console.ReadLine(); } memberCollectionObj.memberAdder(new Member(fName, lName, userAddr, userPhoneNo, userPassword)); Console.WriteLine("Successfully added " + fName + " " + lName + "\n"); } else { Console.WriteLine(fName + " " + lName + " has already registered." + "\n"); } } /// <summary> /// This function is a helper function of the staff-menu. Which checks the staff members password to see its correct or not. /// </summary> /// <param name="userInputPassword"></param> /// <returns></returns> private static bool inputedCorrectPass(string userInputPassword) { if (userInputPassword.Length != 4) { return false; } for (int i = 0; i < userInputPassword.Length; i++) { if (Char.IsLetter(userInputPassword[i])) { return false; } } return true; } /// <summary> /// This function is a helper function which help staff to remove movies that they have added to the system. /// </summary> private static void staffRemoveMovie() { Console.Write("Enter movie title: "); string movieTitle = Console.ReadLine(); if (!movieCollectionObj.deleteMovie(movieTitle)) { Console.WriteLine(movieTitle + " was deleted successfully.\n"); } else { Console.WriteLine(movieTitle+ " does not exist.\n"); } } /// <summary> /// This method is for adding new movies by staff members and it is a helper function of the staff menu. /// </summary> private static void functionalityOfNewMovieAddition() { string[] movieClassificationInfo = {"General (G)", "Parental Guidance (PG)", "Mature (M15+)", "Mature Accompanied (MA15+)"}; string[] movieGenreInfo = { "Drama", "Adventure", "Family", "Action", "Sci-Fi", "Comedy", "Thriller", "Other"}; int choiceOfClassification = 0; int choiceOfGenre = 0; //These are console application notes asking the staff member on what to do. Console.Write("Enter the movie title: "); string movieTitle = Console.ReadLine(); Console.Write("Enter the starring actor(s): "); string star = Console.ReadLine(); Console.Write("Enter the director(s): "); string directorNames = Console.ReadLine(); Console.WriteLine("Select the genre: "); for (int i = 0; i < movieGenreInfo.Length; i++) { Console.WriteLine((i + 1).ToString() + ". " + movieGenreInfo[i]); } choiceOfGenre = getUserInputsInt("Make selection(1-8): ", 1, 8); Console.WriteLine("Select the classification: "); for (int i = 0; i < movieClassificationInfo.Length; i++) { Console.WriteLine((i + 1).ToString() + ". " + movieClassificationInfo[i]); } choiceOfClassification = getUserInputsInt("Make selection(l - 4): ", 1, 4); int movieDuration = getUserInputsInt("Enter the duration (minutes): ", 0, 20000); int movieReleaseDate = getUserInputsInt("Enter the release date (year): ", 1, 2030); int movieCopiesAvailable = getUserInputsInt("Enter the number of copies available: ", 0, 2000000); if (movieCollectionObj.BinarySearchAddMovie(new Movie(movieCopiesAvailable, movieDuration, 0, movieReleaseDate, movieTitle, movieClassificationInfo[choiceOfClassification - 1], movieGenreInfo[choiceOfGenre - 1], directorNames, star))){ Console.WriteLine(movieTitle + " was added." + "\n"); } else { Console.WriteLine("Movie " + movieTitle + " already exists." + "\n"); } Console.WriteLine(); } /// <summary> /// This method will get user inputs and then convert it to an integer type of data. /// Then it will check if they have entered inputs other than 0, 1, or 2 or any number of inputs /// </summary> /// <param name="mesg"></param> /// <param name="minimum"></param> /// <param name="maximum"></param> /// <returns></returns> private static int getUserInputsInt( string mesg, int minimum, int maximum) { int userInputs = -1; bool running = false; while (!running) { try { Console.Write(mesg); userInputs = int.Parse(Console.ReadLine()); if(userInputs >= minimum && userInputs <= maximum) { running = true; } } catch { } } return userInputs; } } }
using System; namespace CameraClassTest { public class Program { static void Main(string[] args) { ActionResult result; Console.WriteLine("**************************************************************************************************"); Console.WriteLine("Esercitazione Classe Base e Classe Derivata con nuove proprieta e nuovi metodi - Vargas"); Console.WriteLine("***********************************"); CameraClass myCamF = new CameraClass("Samsung", TypeCamera.FRONT, false); Console.WriteLine($"Samsung Camera Initial state: {myCamF.NameCamera} type Camera {myCamF.TypeCamera} activation state: {myCamF.IsActive.ToString()}"); result = myCamF.Activate(TypeCamera.FRONT); Console.WriteLine($"after call Activate Camera message {result.Message} and Result {result.Result}"); Console.WriteLine($"After activate: {myCamF.NameCamera} type Camera {myCamF.TypeCamera}"); Console.WriteLine("************************************"); // DEACTIVATE result = myCamF.DeActivate(TypeCamera.FRONT); Console.WriteLine($" after call DeActivate Camera message {result.Message} and Result activation state {result.Result}"); Console.WriteLine($" after disactivate: {myCamF.NameCamera} type Camera {myCamF.TypeCamera}"); Console.WriteLine("**************************************************************************************************"); // //ACTIVATE deacttivate error ? result = myCamF.DeActivate(TypeCamera.FRONT); Console.WriteLine($" after call New Deactivate Camera message {result.Message} and deactivate state Result {result.Result}"); Console.WriteLine($" after disactivate *** {myCamF.NameCamera} type Camera {myCamF.TypeCamera}"); Console.WriteLine("**************************************"); //CON LA CLASSE DERIVATA PhoneI myPhone = new PhoneI("Iphone", TypeCamera.REAR, true, 12); Console.WriteLine($"Iphone Camera Initial state {myPhone.NameCamera} camera type {myPhone.TypeCamera} camera state: {myPhone.IsActive.ToString()}"); int number = myPhone.Calcolate(12); Console.WriteLine($"was Calcolated brightnes ? {myPhone.Calcolate(12).ToString()} camera type {myPhone.TypeCamera} il suo stato è {myPhone.IsActive.ToString()}"); result = myPhone.Activate(TypeCamera.REAR); Console.WriteLine($" after call Activate Camera message {result.Message} and Result {result.Result}"); //Console.WriteLine($"After activate: {myPhone.NameCamera} tipo {myPhone.TypeCamera} il suo stato è {myPhone.IsActive.ToString()}"); result = myPhone.DeActivate(TypeCamera.REAR); Console.WriteLine($" after disactivate IPHONE. {myPhone.NameCamera} camera type {myPhone.TypeCamera} camera state: {myPhone.IsActive.ToString()}"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OcTur.Model; namespace OcTur.Control { class ControlePermissaoControl { public List<string> CarregarPapeis() { return new List<string>(); } public List<string> CarregarPermissoes() { return new List<string>(); } public bool SalvarAssociassoes (string papelSelecionado, List<string> permissoesSelecionadas) { return true; } } }
using UnityEngine; using System; using System.Collections; using GoogleMobileAds.Api; using GoogleMobileAds.Common; public class GoogleAdController : MonoBehaviour { public static GoogleAdController instance; public int instancesBetweenInterstitialAds = 3; public PhaseDelayedEventScheduler phaseDelayedEventScheduler; bool registeredForEvents; bool adsEnabled = true; BannerView bannerView; InterstitialAd interstitialAd; public string iosBannerViewAdId; public string androidBannerViewAdId; public string iosInterstitialAdId; public string androidInterstitialAdId; void Awake() { instance = this; bannerView = new BannerView (GetBannerAdUnitId(), AdSize.SmartBanner, AdPosition.Bottom); bannerView.LoadAd (MakeAdRequest()); bannerView.AdLoaded += OnBannerAdLoaded; bannerView.Hide (); PrepInterstitialAd (); } void PrepInterstitialAd() { if (Debug.isDebugBuild) { Debug.Log ("Setting up interstitialAd"); } interstitialAd = new InterstitialAd (GetInterstitialAdUnitId()); interstitialAd.AdLoaded += OnInterstitialAdLoaded; interstitialAd.AdOpened += OnInterstitialAdOpened; interstitialAd.AdClosed += OnInterstitialAdClosed; interstitialAd.AdFailedToLoad += OnInterstitialAdFailedToLoad; interstitialAd.LoadAd (MakeAdRequest ()); } AdRequest MakeAdRequest() { AdRequest.Builder builder = new AdRequest.Builder(); builder.AddKeyword("game"); builder.AddKeyword("cat"); builder.TagForChildDirectedTreatment (true); return builder.Build(); } string GetInterstitialAdUnitId() { if (Application.platform == RuntimePlatform.IPhonePlayer) { return iosInterstitialAdId; } else if (Application.platform == RuntimePlatform.Android) { return androidInterstitialAdId; } else { return "badid"; } } string GetBannerAdUnitId() { if (Application.platform == RuntimePlatform.IPhonePlayer) { return iosBannerViewAdId; } else if (Application.platform == RuntimePlatform.Android) { return androidBannerViewAdId; } else { return "badid"; } } // Use this for initialization void Start () { RegisterForEvents (); UpdateBanner (); UpdateAdsAvailability (); } void UpdateAdsAvailability() { if (StoreController.instance.IsUpgradePurchased ()) { adsEnabled = false; } } void OnDestroy() { UnregisterForEvents (); } void OnBannerAdLoaded(object sender, EventArgs args) { if (Debug.isDebugBuild) { Debug.Log ("OnBannerAdLoaded"); } } void OnInterstitialAdLoaded(object sender, EventArgs args) { if (Debug.isDebugBuild) { Debug.Log ("OnInterstitialAdLoaded"); } } void OnInterstitialAdOpened(object sender, EventArgs args) { if (Debug.isDebugBuild) { Debug.Log ("OnInterstitialAdOpened"); } // Quiet the music. SoundController.instance.SuppressSounds (); } void OnInterstitialAdFailedToLoad(object sender, EventArgs args) { if (Debug.isDebugBuild) { Debug.Log ("OnInterstitialAdFailedToLoad"); Debug.Log ("args = " + args); } } void OnInterstitialAdClosed(object sender, EventArgs args) { if (Debug.isDebugBuild) { Debug.Log ("OnInterstitialAdClosed"); } SoundController.instance.UnsuppressSounds (); // Load another one. PrepInterstitialAd (); } void RegisterForEvents() { if (registeredForEvents) { return; } registeredForEvents = true; GamePhaseState.instance.GamePhaseChanged += new GamePhaseState.GamePhaseChangedEventHandler (OnGamePhaseChanged); StoreController.instance.StoreChanged += new StoreController.StoreChangedHandler (OnStoreChanged); } void UnregisterForEvents() { if (registeredForEvents) { GamePhaseState.instance.GamePhaseChanged -= new GamePhaseState.GamePhaseChangedEventHandler (OnGamePhaseChanged); StoreController.instance.StoreChanged += new StoreController.StoreChangedHandler (OnStoreChanged); } } void OnGamePhaseChanged() { UpdateBanner (); UpdateInterstialAd (); } void OnStoreChanged() { UpdateAdsAvailability (); } void UpdateInterstialAd() { phaseDelayedEventScheduler.OnPhaseChanged (MaybeShowAd); } bool MaybeShowAd() { bool shouldShowAd = ShouldShowInterstitialAd (); if (!shouldShowAd) { return false; } PersistentStorage.instance.SetIntValue ("lastInstanceAdShown", GamePhaseState.instance.instancesFinishedThisSession); ShowInterstitialAd (); return true; } void ShowInterstitialAd() { if (!adsEnabled) { return; } if (interstitialAd.IsLoaded ()) { interstitialAd.Show (); } } bool ShouldShowInterstitialAd() { if (!adsEnabled) { return false; } if (GamePhaseState.instance.gamePhase != GamePhaseState.GamePhaseType.GAME_OVER) { return false; } int lastInstanceAdShown = PersistentStorage.instance.GetIntValue ("lastInstanceAdShown", 0); if (GamePhaseState.instance.instancesFinishedThisSession < lastInstanceAdShown + instancesBetweenInterstitialAds) { return false; } if (!interstitialAd.IsLoaded ()) { return false; } return true; } void UpdateBanner() { if (!adsEnabled) { bannerView.Hide (); return; } switch(GamePhaseState.instance.gamePhase) { case GamePhaseState.GamePhaseType.LEVEL_PLAY: case GamePhaseState.GamePhaseType.PENDING: if (!DebugConfig.instance.IsDebugFlagSet(DebugConfig.DEBUG_HIDE_ADS)) { bannerView.Show (); } break; default: bannerView.Hide (); break; } switch (GamePhaseState.instance.gamePhase) { case GamePhaseState.GamePhaseType.WELCOME: case GamePhaseState.GamePhaseType.LEVEL_END: if (Debug.isDebugBuild) { Debug.Log("Loading new banner ad"); } bannerView.LoadAd (MakeAdRequest ()); break; } } public static float GetBannerHeight() { // Logic from // https://developers.google.com/admob/android/banner#smart float longSide; float screenHeight = Screen.height; float screenWidth = Screen.width; longSide = Mathf.Max (screenHeight, screenWidth); if (longSide < 400) { return 32; } if (longSide <= 720) { return 50; } return 90; } public void DebugInterstitialAds() { ShowInterstitialAd (); } }
using UnityEngine; using System.Collections; using System; using System.Security; using System.Security.Permissions; using System.IO; using System.Runtime.Serialization; using stSaveFileInfo = CSaveAndLoadTypes.stSaveFileInfo; [System.Serializable] public sealed class _SALContainer : ISaveAndLoadContainer { #region Private fileds private static ArrayList _instances = new ArrayList(); private static _SALContainer _instance_load; #endregion #region Public Fields #endregion #region Properties public new static _SALContainer Instance_Save{ get{ return (_SALContainer)CSingleton.GetSingletonInstance( ref _instances, typeof(_SALContainer) ); } } public new static _SALContainer Instance_Load{ get{ return _instance_load; } set{ _instance_load = value; } } #endregion #region Constructors public _SALContainer() base(){ //singleton system _instances.Add(this); CSingleton.DestroyExtraInstances(_instances); } //Serializatoin counstructor. call when Deserialize function called. //Must be private and call base constructor. private _SALContainer(SerializationInfo info, StreamingContext context) : base(info, context){ } #endregion #region Public Methods //This method will call when save event happend. //All data that need to be save must store here. public override void GetObjectData (SerializationInfo info, StreamingContext context){ throw new System.NotImplementedException (); } #endregion }
using System; namespace lab2 { interface IPrint { void Print(); } abstract class GeomFigure { public abstract double Area(); } class Rectangle : GeomFigure, IPrint { public double height { get; set; } public double width { get; set; } public Rectangle(double width, double height) { this.height = height; this.width = width; } public override double Area() { return height * width; } public override string ToString() { return ("Прямоугольник:\n ширина: " + width + "\n высота: " + height + "\n площадь: " + Area()); } public void Print() { Console.WriteLine(ToString()); } } class Square : Rectangle { public double sideLength { get; set; } public Square(double sideLength) : base(sideLength, sideLength) { this.sideLength = sideLength; } public override double Area() { return sideLength * sideLength; } public override string ToString() { return ("Квадрат:\n длина стороны: " + sideLength + "\n площадь: " + Area()); } } class Circle : GeomFigure, IPrint { public double radius { get; set; } public Circle(double radius) { this.radius = radius; } public override double Area() { return radius * radius * 3.14; } public override string ToString() { return ("Круг:\n радиус: " + radius + "\n площадь: " + Area()); } public void Print() { Console.WriteLine(ToString()); } } public static class Program { public static void Main() { Rectangle r = new Rectangle(2, 3); Square s = new Square(5); Circle c = new Circle(7); r.Print(); s.Print(); c.Print(); } } }
using System; namespace twpx.Model { class SadminModel { public int id { get; set; } public string username { get; set; } public string password { get; set; } public string name { get; set; } public string phone { get; set; } } }
using UnityEngine; /// <summary> /// A GUI control for configuring the solid color shader. /// This class encapsulates the underlying GUI controls /// needed to configure the shader, allowing it to present /// a simplified interface to receive the shader's configuration. /// </summary> public class SolidColorShaderConfigGui : MaterialConfiguration { /// <summary> /// The material for the solid color shader. /// </summary> public Material SolidColorShaderMaterial = null; /// <summary> /// The selector for the solid color. /// </summary> private ColorSelector m_colorSelector = null; /// <summary> /// The example game object that gets updated with new shader /// settings configured in this GUI control. /// </summary> private PlayerExampleGameObject m_exampleGameObject = null; /// <summary> /// Initializes the configuration GUI to have /// access to the selector of the solid color /// for the shader and knowledge about the example /// game object. /// </summary> /// <param name="exampleGameObject">The example game object /// to update with new solid color settings configured /// in this control.</param> public void Initialize(GameObject exampleGameObject) { // STORE THE EXAMPLE GAME OBJECT. m_exampleGameObject = exampleGameObject.GetComponent<PlayerExampleGameObject>(); // CLONE THE ATTACHED MATERIAL SO THAT WE DON'T MODIFY THE UNDERLYING MATERIAL ASSET. SolidColorShaderMaterial = new Material(SolidColorShaderMaterial); // REGISTER WITH THE COLOR SELECTOR TO BE NOTIFIED WHEN THE COLOR CHANGES. m_colorSelector = transform.Find("ColorSelector").GetComponent<ColorSelector>(); m_colorSelector.Initialize(); m_colorSelector.AddOnColorChangedListener(UpdateDisplayedColor); // INITIALIZE THE EXAMPLE GAME OBJECT WITH THE CURRENT SELECTED COLOR. UpdateDisplayedColor(m_colorSelector.Color); } /// <summary> /// Updates the color displayed in the example object based /// the provided color. /// </summary> /// <param name="color">The new solid color for the example object.</param> public void UpdateDisplayedColor(Color color) { // UPDATE THE SOLID COLOR IN THE MATERIAL. SolidColorShaderMaterial.SetColor("_Color", color); m_exampleGameObject.SetMaterial(SolidColorShaderMaterial); } /// <summary> /// Creates a copy of the configured solid color shader material. /// </summary> /// <returns>The configured solid color shader material.</returns> public override Material CreateMaterial() { return new Material(SolidColorShaderMaterial); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using gMediaTools.Services; using gMediaTools.Services.AviSynth; using gMediaTools.Services.AviSynth.VideoSource; namespace gMediaTools.Factories { public class AviSynthSourceFactory { public IAviSynthVideoSourceService GetAviSynthSourceService(string fileContainerFormat) { string container = fileContainerFormat.Trim().ToLower(); if (container.Equals("matroska")) { // MKV => FFMS2 return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>(); } else if (container.Equals("windows media")) { // WMV => FFMS2 return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>(); } else if (container.Equals("mpeg-4")) { // MP4 or MOV => FFMS2 return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>(); } else if (container.Equals("avi")) { // AVI => AviSource return ServiceFactory.GetService<AviSynthAviSourceService>(); } else if (container.Equals("flash video")) { // FLV => FFMS2 return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>(); } else if (container.Equals("realmedia")) { // RM => FFMS2 return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>(); } else if (container.Equals("mpeg-ts")) { // TS => FFMS2 return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>(); } else { // Could not identify container/format // Let's play it safe and use DirectShowSource return ServiceFactory.GetService<AviSynthDirectShowVideoSourceService>(); } } } }
using Common.Data; using Common.Exceptions; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace Entity { /// <summary> /// Class for performing operations on the Staging table. /// </summary> public partial class Staging { #region Public Methods /// <summary> /// Adds a record to the database. /// </summary> /// <param name="connectionString">The connection string to use.</param> /// <param name="userName">The user making the request.</param> /// <param name="id">The ID to add.</param> /// <param name="instance">The current instance.</param> /// <returns>True if successful; otherwise false.</returns> public bool Add(string connectionString, string userName, int id, int instance) { bool result = false; if (Exists(connectionString, userName, id, instance)) return true; string sql = "insert into staging (id, username, instance_num) values (" + id + ", '" + userName + "', " + instance + ")"; using (Database database = new Database(connectionString)) { try { result = database.ExecuteNonQuery(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } /// <summary> /// Deletes items from the Staging table. /// </summary> /// <param name="connectionString">The connection string to use.</param> /// <param name="userName">The user making the request.</param> /// <param name="instance">The current instance.</param> /// <returns>True if successful; otherwise false.</returns> public bool ClearClipboard(string connectionString, string userName, int instance) { bool result = false; //delete from staging where username = @Username and instance_num = @Instance_Num string sql = "P_Staging_Main_Clear_Clear2"; List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@Username", userName)); parameters.Add(new SqlParameter("@Instance_Num", instance)); using (Database database = new Database(connectionString)) { try { result = database.ExecuteNonQuery(sql, parameters: parameters.ToArray()); } catch (Exception e) { throw new EntityException(sql, e); } finally { parameters.Clear(); } } return result; } /// <summary> /// Deletes a record from the database. /// </summary> /// <param name="connectionString">The connection string to use.</param> /// <param name="id">The ID to delete.</param> /// <param name="userName">The user making the request.</param> /// <param name="instance">The Clipboard instance to delete from.</param> /// <returns>True if successful; otherwise false.</returns> public bool DeleteRecord(string connectionString, int id, string userName, int instance) { //delete from staging where id = @ID and username = @Username and instance_num = @Instance_Num string sql = "P_Staging_Main_Remove_Delete2"; List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@ID", id)); parameters.Add(new SqlParameter("@Username", userName)); parameters.Add(new SqlParameter("@Instance_Num", instance)); using (Database database = new Database(connectionString)) { try { return database.ExecuteNonQuery(sql, parameters: parameters.ToArray()); } catch (Exception e) { throw new EntityException(sql, e); } finally { parameters.Clear(); } } } /// <summary> /// Gets the notes for the selected ID from the database. /// </summary> /// <param name="connectionString">The connection string to use.</param> /// <param name="id">The ID to delete.</param> /// <param name="userName">The user making the request.</param> /// <param name="instance">The current instance.</param> /// <returns>The notes text.</returns> public string GetNotes(string connectionString, int id, string userName, int instance) { string result = String.Empty; //select notes from staging where id = @ID and username = @Username and instance_num = @Instance_Num string sql = "P_Staging_GetNotes2"; List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@ID", id)); parameters.Add(new SqlParameter("@Username", userName)); parameters.Add(new SqlParameter("@Instance_Num", instance)); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectString(sql, CommandType.StoredProcedure, parameters.ToArray()); } catch (Exception e) { throw new EntityException(sql, e); } finally { parameters.Clear(); } } return result; } /// <summary> /// Gets the IDs to display in the form's grid. /// </summary> /// <param name="connectionString">The connection string to use.</param> /// <param name="userName">The user making the request.</param> /// <param name="instance">The current instance.</param> /// <returns>The IDs to load.</returns> public List<int> GetStagingIds(string connectionString, string userName, int instance) { List<int> result = new List<int>(); string sql = "Select distinct ID from Staging where username = '" + userName + "' " + "and instance_num = " + instance.ToString(); //List<SqlParameter> parameters = new List<SqlParameter>(); //parameters.Add(new SqlParameter("@Username", userName)); //parameters.Add(new SqlParameter("@Instance_Num", instance)); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectIntList(sql);//, CommandType.StoredProcedure, parameters.ToArray()); } catch (Exception e) { throw new EntityException(sql, e); } //finally //{ // parameters.Clear(); //} } return result; } /// <summary> /// Saves the current instance to the database. /// </summary> /// <param name="connectionString">The connection string to use.</param> /// <returns>True if successful; otherwise false.</returns> public bool Save(string connectionString) { bool result = false; using (Database database = new Database(connectionString)) { string sql = ""; try { Mapper<Staging> m = new Mapper<Staging>(); sql = m.MapSingleUpdate(this); result = database.ExecuteNonQuery(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public List<int> GetIds(string connectionString, string userName, int instance) { List<int> result = new List<int>(); string sql = "Select ID from Staging where username= '" + userName + "' and instance_num = " + instance.ToString(); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectIntList(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } #endregion #region Private Methods /// <summary> /// Checks to see if a record exists on the Staging table. /// </summary> /// <param name="connectionString">The connection string to use.</param> /// <param name="userName">The current user.</param> /// <param name="id">The ID to check.</param> /// <param name="instance">The current instance.</param> /// <returns>True if the record exists; otherwise false.</returns> private bool Exists(string connectionString, string userName, int id, int instance) { bool result = false; string sql = "Select count(*) from Staging where id = " + id + " and username = '" + userName + "' and " + "instance_num = " + instance; using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectInt(sql).GetValueOrDefault() > 0; } catch (Exception e) { throw new EntityException(sql, e); } } return result; } #endregion } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. using System; using System.Collections.Generic; using System.Text; namespace FiiiChain.Node { public class NodeConfig { public string Ip { get; set; } public string User { get; set; } public string Password { get; set; } public string Port { get; set; } public string WalletNotify { get; set; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; using System; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace DoodleReplacement { public static class InsertAnswer { [FunctionName("InsertAnswer")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { try { var partition = req.Query["partition"]; var service = new EntriesBL(); var config = await service.GetEntryConfig(partition); if(config == null) { return new BadRequestResult(); } string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var model = JsonConvert.DeserializeObject<AnswerAM>(requestBody); if(!model.IsValid) { return new BadRequestObjectResult("Model is invalid! Name or dates missing."); } var entity = new AnswerEntity(partition, model.Name) { Name = model.Name, AdditionalMessage = model.AdditionalMessage, SelectedDatesString = string.Join(',', model.SelectedDates.Select(sd => sd.ToString("yyyy-MM-dd"))) }; var table = await StorageService.GetStorageTableReference(); await table.ExecuteAsync(TableOperation.Insert(entity)); if(!string.IsNullOrEmpty(config.WebHookUrl)) { using (var client = new HttpClient()) { await client.PostAsync(config.WebHookUrl, null); } } return new OkObjectResult(entity); } catch(Exception ex) { log.LogError(ex.Message, ex); return new BadRequestObjectResult(ex.Message); } } } }
using System; namespace DoublePermutationMethod.Command { class HelpCommand : BaseCommand { public override string Name => "help"; public override void Execute() { Console.WriteLine("<encode> - Command to encrypt a sentence with a custom key"); Console.WriteLine("<encodeRND> - Command to encrypt a sentence with a random key"); Console.WriteLine("<decode> - Command for decrypting a sentence with a custom key"); } } }
using System; using System.Linq; using VetClinicPublic.Web.Models; namespace VetClinicPublic.Web.Interfaces { public interface ISendConfirmationEmails { void SendConfirmationEmail(AppointmentDTO appointment); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LibreriaClases { public class EjecutarQuery { static string connectionString = @"Server = YouServerName; Database=Usuarios;Trusted_Connection=True"; public static List<usuario> listaUsuarios; public static List<EstadoCivil> listaEstados; #region InsertSQL public static void insertSQL( string nombre,string apellido) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(null, connection); // Create and prepare an SQL statement. command.CommandText = "INSERT INTO usuario (nombre, apellido) VALUES (@nombre, @apellido)"; command.Parameters.AddWithValue("@nombre", nombre); command.Parameters.AddWithValue("@apellido", apellido); try { connection.Open(); Int32 rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("RowsAffected: {0}", rowsAffected); } catch (Exception ex) { Console.WriteLine(ex.Message); } connection.Close(); } } public static void insertSQL(string nombre) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(null, connection); // Create and prepare an SQL statement. command.CommandText = "INSERT INTO usuario (nombre) VALUES (@nombre)"; command.Parameters.AddWithValue("@nombre", nombre); try { connection.Open(); Int32 rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("RowsAffected: {0}", rowsAffected); } catch (Exception ex) { Console.WriteLine(ex.Message); } connection.Close(); } } #endregion InsertSQL #region SelectSQL //se obtiene 1 usuario utilizando el id public static List<usuario> selectSQL(int id) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(null, connection); DataTable dt = new DataTable(); // Create and prepare an SQL statement. command.CommandText = $"select * from usuario where id_usuario = {id}"; try { connection.Open(); var DataAdapter = new SqlDataAdapter(command); DataAdapter.Fill(dt); usuario _usuario = new usuario(); listaUsuarios = new List<usuario>(); _usuario.id_usuario = int.Parse((dt.Rows[0]["id_usuario"].ToString())); _usuario.nombre = dt.Rows[0]["nombre"].ToString(); _usuario.apellido = dt.Rows[0]["apellido"].ToString(); listaUsuarios.Add(_usuario); } catch (Exception ex) { Console.WriteLine(ex.Message); } connection.Close(); } return listaUsuarios; } //se obtienen todos los usuarios en la BD public static List<usuario> selectAllUsuariosSQL() { var dt = new DataTable(); using (SqlConnection connection = new SqlConnection(connectionString)) { //command nos prepara la query a ejecutar SqlCommand command = new SqlCommand(null, connection); command.CommandText = "select * from usuario"; connection.Open(); var DataAdapter = new SqlDataAdapter(command); DataAdapter.Fill(dt); listaUsuarios = new List<usuario>(); foreach (DataRow row in dt.Rows) { usuario usuarioTemp = new usuario(); usuarioTemp.id_usuario = int.Parse(row["id_usuario"].ToString()); usuarioTemp.nombre = row["nombre"].ToString(); usuarioTemp.apellido = row["apellido"].ToString(); listaUsuarios.Add(usuarioTemp); } } return listaUsuarios; } //se obtienen todos los usuarios en la BD public static List<EstadoCivil> selectAllEstadoCivilSQL() { var dt = new DataTable(); using (SqlConnection connection = new SqlConnection(connectionString)) { //command nos prepara la query a ejecutar SqlCommand command = new SqlCommand(null, connection); command.CommandText = "select * from EstadoCivil"; connection.Open(); var DataAdapter = new SqlDataAdapter(command); DataAdapter.Fill(dt); listaEstados = new List<EstadoCivil>(); foreach (DataRow row in dt.Rows) { EstadoCivil estadoCivil = new EstadoCivil(); estadoCivil.id_estadoCivil = int.Parse(row["IdEstadoCivil"].ToString()); estadoCivil.descripcion = row["Descripcion"].ToString(); listaEstados.Add(estadoCivil); } } return listaEstados; } #endregion SelectSQL } }
using Microsoft.AspNet.Http; using SciVacancies.WebApp.ViewModels.Base; namespace SciVacancies.WebApp.ViewModels { public class ResearcherEditPhotoViewModel: PageViewModelBase { public IFormFile PhotoFile { get; set; } public string ImageName { get; set; } public long? ImageSize { get; set; } public string ImageExtension { get; set; } private string _imageUrl; public string ImageUrl { get { return _imageUrl ?? string.Empty; } set { _imageUrl = value; } } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class PlayerHealth : MonoBehaviour { public int player1Health; public int player2Health; // Access to LastManStanding script public GameObject lastManStandingGameObj; public LastManStanding lastManStandingScript; // Display the player's health public Text player1HealthDisplay; public Text player2HealthDisplay; // Play victory sound public GameObject audioControllerObj; public AudioFileController audioControllerScript; private bool playVictorySound; // Use this for initialization void Start () { player1Health = 100; player2Health = 100; lastManStandingGameObj = GameObject.Find("GameController"); lastManStandingScript = lastManStandingGameObj.GetComponent<LastManStanding>(); //audioControllerObj = GameObject.Find("AudioController"); //audioControllerScript = audioControllerObj.GetComponent<AudioFileController>(); playVictorySound = false; } // Update is called once per frame void Update () { // Delete player one object if the health threshold gets to 0 if (player1Health <= 0 && playVictorySound == false) { player1Health = 0; lastManStandingScript.isPlayer1Alive = false; Destroy(GameObject.FindWithTag("PlayerOne")); playVictorySound = true; audioControllerScript.PlaySound(audioControllerScript.victorySound); } // Do not let the players get more than 100% health if (player1Health >= 100) { player1Health = 100; } // Do not let the players get less than 0% health if (player1Health <= 0) { player1Health = 0; } // Delete player two object if the health threshold gets to 0 if (player2Health <= 0 && playVictorySound == false) { player2Health = 0; lastManStandingScript.isPlayer2Alive = false; Destroy(GameObject.FindWithTag("PlayerTwo")); playVictorySound = true; audioControllerScript.PlaySound(audioControllerScript.victorySound); } // Do not let the players get more than 100% health if (player2Health >= 100) { player2Health = 100; } // Update the health text player1HealthDisplay.text = (player1Health.ToString("0")); player2HealthDisplay.text = (player2Health.ToString("0")); } }
using mec.Database.Presentees; using mec.Model; using mec.Model.Processes; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace mec.Cleint.Portal.Controllers { public class ProcessController : ApiController { [HttpPost] public HttpResponseMessage GetNotices(NoticeParam param) { ProcessPresenter pre = new ProcessPresenter(); var vms = pre.GetNotices(param); if (vms != null) { return Request.CreateResponse(HttpStatusCode.OK, vms); } return Request.CreateErrorResponse(HttpStatusCode.NotModified, "取得工站預警資訊錯誤!!"); } //setNotice [HttpPost] public HttpResponseMessage SetNotice(NoticeViewModel vm) { ProcessPresenter pre = new ProcessPresenter(); int eCode = pre.SetNotice(vm); if (eCode > 0) { return Request.CreateResponse(HttpStatusCode.OK, eCode); } return Request.CreateErrorResponse(HttpStatusCode.NotModified, "設定工站預警資訊錯誤!!"); } [HttpPost] public HttpResponseMessage GetTraces(TraceParam param) { ProcessPresenter pre = new ProcessPresenter(); var vms = pre.GetTraces(param); if (vms != null) { return Request.CreateResponse(HttpStatusCode.OK, vms); } return Request.CreateErrorResponse(HttpStatusCode.NotModified, "取得追溯資訊錯誤!!"); } //GetTraceOptions [HttpPost] public HttpResponseMessage GetTraceOptions() { ProcessPresenter pre = new ProcessPresenter(); var vms = pre.GetTraceOptions(); if (vms != null) { return Request.CreateResponse(HttpStatusCode.OK, vms); } return Request.CreateErrorResponse(HttpStatusCode.NotModified, "取得追溯查詢條件錯誤!!"); } } }
using MediaProtector.App_Plugins.MediaProtector.Controllers; using Umbraco.Core; using Umbraco.Core.Composing; namespace MediaProtector.App_Plugins.MediaProtector.Components { public class Composer:IUserComposer { public void Compose(Composition composition) { //Append our component to the collection of Components // It will be the last one to be run composition.Components().Append<InitializePlan>(); composition.Components().Append<EventBlocker>(); composition.Register<MediaProtectorApiController>(); } } }
*** Start programmer edit section *** (EduProgram.Number CustomAttributes) *** End programmer edit section *** (EduProgram.Number CustomAttributes) *** Start programmer edit section *** (EduProgram.Number Get) return null; *** End programmer edit section *** (EduProgram.Number Get) *** Start programmer edit section *** (EduProgram.Number Set) *** End programmer edit section *** (EduProgram.Number Set)
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace isukces.code.vssolutions { public sealed class FrameworkVersion : IComparable<FrameworkVersion>, IComparable { public FrameworkVersion(string shortName, string version, string profile) { shortName = shortName.ToLower(); FrameworkGroup = RecognizeFrameworkVersionGroup(shortName); ShortName = shortName; Version = version; Profile = profile; VersionCompare = version.Replace(".", ""); } public static bool operator >(FrameworkVersion left, FrameworkVersion right) { return Comparer<FrameworkVersion>.Default.Compare(left, right) > 0; } public static bool operator >=(FrameworkVersion left, FrameworkVersion right) { return Comparer<FrameworkVersion>.Default.Compare(left, right) >= 0; } public static bool operator <(FrameworkVersion left, FrameworkVersion right) { return Comparer<FrameworkVersion>.Default.Compare(left, right) < 0; } public static bool operator <=(FrameworkVersion left, FrameworkVersion right) { return Comparer<FrameworkVersion>.Default.Compare(left, right) <= 0; } public static FrameworkVersion[] Parse(string x) { { var portable = "portable-"; if (x.StartsWith(portable)) { var xx = x.Substring(portable.Length).Split('+'); return xx.Select(Parse1).ToArray(); } } { var portable = "portable40-"; if (x.StartsWith(portable)) { var xx = x.Substring(portable.Length).Split('+'); return xx.Select(Parse1).ToArray(); } } return new[] {Parse1(x)}; } public static FrameworkVersion Parse1(string x) { var m = VersionRegex.Match(x); if (m.Success) { var type = m.Groups[1].Value; var version = m.Groups[2].Value; var profile = m.Groups[3].Value; if (type == "v") type = "net"; return new FrameworkVersion(type, version, profile); } return null; } private static FrameworkVersionGroup RecognizeFrameworkVersionGroup(string shortName) { // https://docs.microsoft.com/pl-pl/nuget/reference/target-frameworks if (shortName.StartsWith("xamarin", StringComparison.Ordinal)) return FrameworkVersionGroup.Xamarin; switch (shortName) { case "net": return FrameworkVersionGroup.Framework; case "netcore": return FrameworkVersionGroup.NetCore; case "netcoreapp": case "aspnet": // Deprecated case "aspnetcore": // Deprecated case "dnx": // Deprecated case "dnxcore": // Deprecated return FrameworkVersionGroup.NetCoreApp; case "netstandard": case "dotnet": // Deprecated return FrameworkVersionGroup.NetStandard; case "wp": case "wpa": return FrameworkVersionGroup.WindowsPhone; case "sl": return FrameworkVersionGroup.Silverlight; case "win": case "winrt": // Deprecated return FrameworkVersionGroup.Windows; case "netmf": return FrameworkVersionGroup.MicroFramework; case "uap": return FrameworkVersionGroup.UniversalWindowsPlatform; case "tizen": return FrameworkVersionGroup.Tizen; default: return FrameworkVersionGroup.Other; } } public NugetLoadCompatibility CanLoad(FrameworkVersion nuget) { if (FrameworkGroup == nuget.FrameworkGroup) { var g = string.Compare(VersionCompare, nuget.VersionCompare, StringComparison.OrdinalIgnoreCase); return g == 0 ? NugetLoadCompatibility.Full : g > 0 ? NugetLoadCompatibility.Possible : NugetLoadCompatibility.None; } if (FrameworkGroup == FrameworkVersionGroup.UniversalWindowsPlatform) switch (nuget.FrameworkGroup) { case FrameworkVersionGroup.Windows: case FrameworkVersionGroup.WindowsPhone: return nuget.VersionCompare == "81" ? NugetLoadCompatibility.Partial : NugetLoadCompatibility.None; case FrameworkVersionGroup.NetCore: return nuget.VersionCompare == "50" ? NugetLoadCompatibility.Partial : NugetLoadCompatibility.None; } return NugetLoadCompatibility.None; } public int CompareTo(FrameworkVersion other) { if (ReferenceEquals(this, other)) return 0; if (ReferenceEquals(null, other)) return 1; var compareTypeComparison = FrameworkGroup.CompareTo(other.FrameworkGroup); if (compareTypeComparison != 0) return compareTypeComparison; return string.Compare(VersionCompare, other.VersionCompare, StringComparison.Ordinal); } public int CompareTo(object obj) { if (ReferenceEquals(null, obj)) return 1; if (ReferenceEquals(this, obj)) return 0; return obj is FrameworkVersion other ? CompareTo(other) : throw new ArgumentException($"Object must be of type {nameof(FrameworkVersion)}"); } public override string ToString() { return Name; } public FrameworkVersionGroup FrameworkGroup { get; } public string ShortName { get; } public string Version { get; } public string Profile { get; } public string VersionCompare { get; } public string Name { get { var name = ShortName + Version; if (string.IsNullOrEmpty(Profile)) return name; return name + "-" + Profile; } } private static readonly Regex VersionRegex = new Regex(VersionFilter, RegexOptions.IgnoreCase | RegexOptions.Compiled); const string VersionFilter = @"^([a-z]+)(\d+(?:\.\d+(?:\.\d+)?)?)(?:-([a-z]+))?$"; } #if OLD ^([a-z]+) (\d+(?:\.\d+(?:\.\d+)?)?) (?:-([a-z]+))?$ #endif }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using VeterinariaT1.BD; using VeterinariaT1.Modelo; namespace VeterinariaT1.Controller { class ControladorTratamiento { public List<Modelo.Tratamientos> AllTramientos() { List<Tratamientos> vjs = new List<Tratamientos>(); Tratamientos ctemp = null; Conexion conn = new Conexion(); string sqlConsulta = "sp_Tratamientos"; SqlCommand comando = new SqlCommand(sqlConsulta, conn.AbrirC()); SqlDataReader reader = comando.ExecuteReader(); while (reader.Read()) { ctemp = new Tratamientos(); ctemp.Id = reader.GetInt32(reader.GetOrdinal("Id")); ctemp.Tratamiento = reader.GetString(reader.GetOrdinal("Tratamiento")); ctemp.Telefonos = reader.GetString(reader.GetOrdinal("Sucursal")); ctemp.Tamaño = reader.GetString(reader.GetOrdinal("Tamaño")); ctemp.Precio = reader.GetInt32(reader.GetOrdinal("Precio")); ctemp.Sucursal = reader.GetString(reader.GetOrdinal("Sucursal")); ctemp.Tipo = reader.GetString(reader.GetOrdinal("Tipo")); ctemp.IdEstatus = reader.GetInt32(reader.GetOrdinal("Estatus")); vjs.Add(ctemp); } conn.CerrarC(); return vjs; } public void AgregarTratamientos(Tratamientos ani) { SqlDataReader reader = null; Conexion conn = new Conexion(); string sql1 = "sp_AgregarTratamientos"; SqlCommand comando1 = new SqlCommand(sql1, conn.AbrirC()); comando1.CommandType = System.Data.CommandType.StoredProcedure; comando1.Parameters.AddWithValue("@Precio", System.Data.SqlDbType.Float).Value = ani.Precio; comando1.Parameters.AddWithValue("@Sucursal", System.Data.SqlDbType.VarChar).Value = ani.Sucursal; comando1.Parameters.AddWithValue("@Tratamientos", System.Data.SqlDbType.VarChar).Value = ani.Tratamiento; comando1.Parameters.AddWithValue("@Telefono", System.Data.SqlDbType.VarChar).Value = ani.Telefonos; comando1.Parameters.AddWithValue("@Tamaño", System.Data.SqlDbType.VarChar).Value = ani.Tamaño; comando1.Parameters.AddWithValue("@Tipo", System.Data.SqlDbType.VarChar).Value = ani.Tipo; comando1.ExecuteNonQuery(); conn.CerrarC(); MessageBox.Show("Se agrego nuevo Servicio"); } public void ModificarTratamientos(Tratamientos ani) { SqlDataReader reader = null; Conexion conn = new Conexion(); string sql1 = "sp_ModificarTratamientos"; SqlCommand comando1 = new SqlCommand(sql1, conn.AbrirC()); comando1.CommandType = System.Data.CommandType.StoredProcedure; comando1.Parameters.AddWithValue("@Precio", System.Data.SqlDbType.Float).Value = ani.Precio; comando1.Parameters.AddWithValue("@Sucursal", System.Data.SqlDbType.VarChar).Value = ani.Sucursal; comando1.Parameters.AddWithValue("@Tratamientos", System.Data.SqlDbType.VarChar).Value = ani.Tratamiento; comando1.Parameters.AddWithValue("@Telefono", System.Data.SqlDbType.VarChar).Value = ani.Telefonos; comando1.Parameters.AddWithValue("@Tamaño", System.Data.SqlDbType.VarChar).Value = ani.Tamaño; comando1.Parameters.AddWithValue("@Tipo", System.Data.SqlDbType.VarChar).Value = ani.Tipo; comando1.Parameters.AddWithValue("@IdVal", System.Data.SqlDbType.Int).Value = ani.Id; comando1.ExecuteNonQuery(); conn.CerrarC(); MessageBox.Show("Se modifico el Tratamiento"); } public void EliminarTratamientos(Tratamientos ani) { SqlDataReader reader = null; Conexion conn = new Conexion(); string sql1 = "sp_EliminarTratamientos"; SqlCommand comando1 = new SqlCommand(sql1, conn.AbrirC()); comando1.CommandType = System.Data.CommandType.StoredProcedure; comando1.Parameters.AddWithValue("@IdVal", System.Data.SqlDbType.Int).Value = ani.Id; comando1.ExecuteNonQuery(); conn.CerrarC(); MessageBox.Show("Se elimino el Tratamientos"); } } }
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 AndroidAirHockey { /// <summary> /// This is a game component that implements IUpdateable. /// </summary> public class Puck : Microsoft.Xna.Framework.GameComponent { SpriteBatch spriteBatch; Texture2D texturePuck; Vector2 puckPosition = Vector2.Zero; Table table; int puckRadius = 16; int intMass = 1; float fltSpeedX = 2; float fltSpeedY = 2; public Puck(Game game) : base(game) { // TODO: Construct any child components here table = new Table(game); Initialize(); } /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { // TODO: Add your initialization code here spriteBatch = new SpriteBatch(Game.GraphicsDevice); //texturePuck = Game.Content.Load<Texture2D>("PuckMed"); texturePuck = Game.Content.Load<Texture2D>("PuckSmallBlack"); base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { // TODO: Add your update code here base.Update(gameTime); } public void DrawPuck() { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); spriteBatch.Draw(texturePuck, puckPosition, Color.White); spriteBatch.End(); } public void DrawPuck(string strStartingPosition) { if (strStartingPosition == "StartPosition") { puckPosition.X = 240; puckPosition.Y = 240; } else if (strStartingPosition == "PlayerAStart") { puckPosition.X = 240; puckPosition.Y = 305; } else if (strStartingPosition == "PlayerBStart") { puckPosition.X = 240; puckPosition.Y = 165; } DrawPuck(); } public void DrawPuck(int x, int y) { Vector2 vectorPoint = new Vector2(x, y); DrawPuck(vectorPoint); } public void DrawPuck(float x, float y) { Vector2 vectorPoint = new Vector2(x, y); DrawPuck(vectorPoint); } public void DrawPuck(Point point) { Vector2 vectorPoint = new Vector2(point.X, point.Y); DrawPuck(vectorPoint); } public void DrawPuck(Vector2 vectorPosition) { spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); spriteBatch.Draw(texturePuck, vectorPosition, Color.White); spriteBatch.End(); } public void Friction() { fltSpeedX = fltSpeedX * 0.9979f; fltSpeedY = fltSpeedY * 0.9979f; } public float X { get { return puckPosition.X; } set { puckPosition.X = value; } } public float Y { get { return puckPosition.Y; } set { puckPosition.Y = value; } } public float CenterX { get { return puckPosition.X + puckRadius; } set { puckPosition.X = value - puckRadius; } } public float CenterY { get { return puckPosition.Y + puckRadius; } set { puckPosition.Y = value - puckRadius; } } public int Radius { get { return puckRadius; } } public int Mass { get { return intMass; } } public float SpeedX { get { return fltSpeedX; } set { fltSpeedX = value; } } public float SpeedY { get { return fltSpeedY; } set { fltSpeedY = value; } } } }
using Niusys.WebAPI.Common.Security; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Niusys.WebAPI.Models { public class SessionObject { public string SessionKey { get; set; } public User LogonUser { get; set; } } public class User : IUser<int> { public int UserId { get; set; } public string LoginName { get; set; } public string Password { get; set; } public string DisplayName { get; set; } public bool IsActive { get; internal set; } } public class UserDevice { public int UserId { get; internal set; } public DateTime ActiveTime { get; internal set; } public DateTime ExpiredTime { get; internal set; } public DateTime CreateTime { get; internal set; } public int DeviceType { get; internal set; } public string SessionKey { get; internal set; } } }
namespace _09._UserLogs { using System; using System.Collections.Generic; public class Startup { public static void Main() { string input = Console.ReadLine(); SortedDictionary<string, Dictionary<string, int>> users = new SortedDictionary<string, Dictionary<string, int>>(); while (input != "end") { string[] inputParts = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); string[] ipParts = inputParts[0].Split('='); string[] userParts = inputParts[2].Split('='); string ip = ipParts[1]; string user = userParts[1]; if (!users.ContainsKey(user)) { users[user] = new Dictionary<string, int>(); } if (!users[user].ContainsKey(ip)) { users[user][ip] = 0; } users[user][ip]++; input = Console.ReadLine(); } foreach (KeyValuePair<string, Dictionary<string, int>> user in users) { string username = user.Key; List<string> ips = new List<string>(); foreach (KeyValuePair<string, int> kvp in user.Value) { string ip = $"{kvp.Key} => {kvp.Value}"; ips.Add(ip); } Console.WriteLine($"{username}:"); Console.WriteLine($"{string.Join(", ", ips)}."); } } } }
using PopulationFitness.Models.FastMaths; using PopulationFitness.Models.Genes.BitSet; using System; namespace PopulationFitness.Models.Genes.LocalMinima { public class AckleysGenes : NormalizingBitSetGenes { private class NormalizationRatioCalculator : IValueCalculator<Double> { public double CalculateValue(long n) { /* {f left (x right )} over {20 left (1- {e} ^ {-0.2α} right ) +e- {e} ^ {-1}} */ return 20.0 * (1.0 - Math.Exp(-0.2 * Alpha)) + Math.E - Math.Exp(-1.0); } } private static readonly ExpensiveCalculatedValues<double> NormalizationRatios = new ExpensiveCalculatedValues<double>(new NormalizationRatioCalculator()); private const double Alpha = 4.5; private const double TwentyPlusE = 20.0 + Math.E; private const double TwoPi = 2.0 * Math.PI; public AckleysGenes(Config config) : base(config, 5.0) { } protected override double CalculateNormalizationRatio(int n) { return NormalizationRatios.FindOrCalculate(n); } protected override double CalculateFitnessFromIntegers(long[] integer_values) { /* http://www.cs.unm.edu/~neal.holts/dga/benchmarkFunction/ackley.html f left (x right ) =-20 exp {left (-0.2 sqrt {{1} over {n} sum from {i=1} to {n} {{x} rsub {i} rsup {2}}} right )} - exp {left ({1} over {n} sum from {i=1} to {n} {cos {left ({2πx} rsub {i} right )}} right ) +20+ exp⁡ (1)} */ double firstSum = 0.0; double secondSum = 0.0; foreach (long integer_value in integer_values) { double x = Interpolate(integer_value); firstSum += x * x; secondSum += CosSineCache.Cos(TwoPi * x); } double n = integer_values.Length; return -20.0 * Math.Exp(-0.2 * Math.Sqrt(firstSum / n)) - Math.Exp(secondSum / n) + TwentyPlusE; } } }
public class Solution { public IList<string> FindWords(char[][] board, string[] words) { var res = new List<string>(); Trie t = new Trie(); foreach(string word in words) { t.Insert(word); } int m = board.Length, n = board[0].Length; bool[][] visited = new bool[m][]; for (int i = 0; i < m; i ++) { visited[i] = new bool[n]; } for (int i = 0; i < m; i ++) { for (int j = 0; j < n; j ++) { DFSHelper(board, i, j, t.root, res, visited); } } return res; } private void DFSHelper(char[][] board, int i, int j, TrieNode curr, IList<string> res, bool[][] visited) { if (curr.str != null) { res.Add(curr.str); curr.str = null; // this is to avoid duplicates in the result } if (i < 0 || i >= board.Length || j < 0 || j >= board[0].Length || curr.children[board[i][j] - 'a'] == null || visited[i][j]) return; TrieNode next = curr.children[board[i][j] - 'a']; visited[i][j] = true; DFSHelper(board, i+1, j, next, res, visited); DFSHelper(board, i-1, j, next, res, visited); DFSHelper(board, i, j+1, next, res, visited); DFSHelper(board, i, j-1, next, res, visited); visited[i][j] = false; } } public class TrieNode { public TrieNode[] children; public string str; public TrieNode() { children = new TrieNode[26]; } } public class Trie { public TrieNode root; public Trie() { root = new TrieNode(); } public void Insert(string word) { TrieNode curr = root; for (int i = 0; i < word.Length; i ++) { char c = word[i]; if (curr.children[c - 'a'] == null) { curr.children[c - 'a'] = new TrieNode(); } curr = curr.children[c - 'a']; } curr.str = word; } }
using System; using System.Runtime.Serialization; namespace Phenix.Business { /// <summary> /// 校验限制保存时异常 /// </summary> [Serializable] public class CheckSaveException : Exception { /// <summary> /// 校验限制保存时异常 /// </summary> public CheckSaveException() : base() { } /// <summary> /// 校验限制保存时异常 /// </summary> public CheckSaveException(string message) : base(message) { } /// <summary> /// 校验限制保存时异常 /// </summary> public CheckSaveException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// 校验限制保存时异常 /// </summary> public CheckSaveException(IBusiness business) : base(business == null ? null : String.Format(Phenix.Business.Properties.Resources.CheckSaveException, business.Caption)) { _business = business; } /// <summary> /// 校验限制保存时异常 /// </summary> public CheckSaveException(IBusiness business, string message) : base(business == null ? message : String.Format(Phenix.Business.Properties.Resources.CheckSaveException + '\n' + message, business.Caption)) { _business = business; } /// <summary> /// 校验限制保存时异常 /// </summary> public CheckSaveException(IBusiness business, Exception exception) : base(business == null ? exception.Message : String.Format(Phenix.Business.Properties.Resources.CheckSaveException + '\n' + exception.Message, business.Caption), exception) { _business = business; } #region Serialization /// <summary> /// 序列化 /// </summary> protected CheckSaveException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) throw new ArgumentNullException("info"); _business = (IBusiness)info.GetValue("_business", typeof(IBusiness)); } /// <summary> /// 反序列化 /// </summary> [System.Security.SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); base.GetObjectData(info, context); info.AddValue("_business", _business); } #endregion #region 属性 private readonly IBusiness _business; /// <summary> /// 业务对象 /// </summary> public IBusiness Business { get { return _business; } } #endregion } }
namespace SOLIDPrinciples.OCP.Example1.Good { public class CalculadoraDePrecos { private readonly ITabelaDePreco tabela; private readonly IServicoDeEntrega entrega; public CalculadoraDePrecos( ITabelaDePreco tabela, IServicoDeEntrega entrega) => (this.tabela, this.entrega) = (tabela, entrega); public double Calcular(Compra produto) { double desconto = tabela.DescontoPara(produto.Valor); double frete = entrega.Para(produto.Cidade); return produto.Valor * (1 - desconto) + frete; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using DelftTools.Functions.Filters; using DelftTools.Functions.Generic; using DelftTools.Units; using DelftTools.Utils.Aop.NotifyPropertyChange; namespace DelftTools.Functions.Conversion { /// <summary> /// Convert a certain variable within a variable (for example x(t) convert t-t') /// Here x is variable, t is sourcevariable, t' is target variable /// </summary> /// <typeparam name="TVariable">Type of resulting variable</typeparam> /// <typeparam name="TTarget">Type of converted variable</typeparam> /// <typeparam name="TSource">Type of source variable</typeparam> public class ConvertedVariable<TVariable, TTarget, TSource> : ConvertedFunction<TTarget, TSource>, IVariable<TVariable> where TTarget : IComparable where TSource : IComparable where TVariable : IComparable { public ConvertedVariable(IVariable parent,IVariable<TSource> variableToConvert, Func<TTarget, TSource> toSource, Func<TSource, TTarget> toTarget) :base(parent,variableToConvert,toSource,toTarget) { if (variableToConvert.Arguments.Count > 0) throw new NotImplementedException("Conversion of non-arguments not supported yet"); //convertedVariable = this; } public void SetValues<T>(IEnumerable<T> values, params IVariableFilter[] filters) { //convert values to parent values IEnumerable<TTarget> targetValues = (IEnumerable<TTarget>)values; Parent.SetValues(targetValues.Select(s=>toSource(s)),ConvertFilters(filters)); } public new IVariable Parent { get { return (IVariable) base.Parent; } set { base.Parent = value; } } public IMultiDimensionalArray<TVariable> GetValues(params IVariableFilter[] filters) { return GetValues<TVariable>(); } IVariable<TVariable> IVariable<TVariable>.Clone() { throw new NotImplementedException(); } //TODO: get this addvalues mess out. public void AddValues<T>(IEnumerable<T> values) { throw new NotImplementedException(); } [NoNotifyPropertyChange] public bool GenerateUniqueValueForDefaultValue { get; set; } public InterpolationType InterpolationType { get; set; } public ExtrapolationType ExtrapolationType { get; set; } public NextValueGenerator<TVariable> NextValueGenerator { get; set; } object IVariable.MaxValue { get { return MaxValue; } } public IMultiDimensionalArray<TVariable> AllValues { get { return Values; } } object IVariable.MinValue { get { return MinValue; } } public TVariable MinValue { get { if ((variableToConvert == Parent) && typeof(TVariable) == typeof(TTarget)) { //no nice cast here :( return (TVariable)(object)toTarget((TSource)Parent.MinValue); } return (TVariable)Parent.MinValue; } } public TVariable MaxValue { get { if ((variableToConvert == Parent) && typeof(TVariable) == typeof(TTarget)) { //no nice cast here :( return (TVariable)(object)toTarget((TSource)Parent.MaxValue); } return (TVariable)Parent.MaxValue; } } public void AddValues<T>(IEnumerable<TVariable> values) { IEnumerable<TTarget> targetValues = (IEnumerable<TTarget>)values; Parent.AddValues(targetValues.Select(s => toSource(s))); } public void AddValues(IEnumerable values) { //TODO redirect parent? IEnumerable<TTarget> targetValues = (IEnumerable<TTarget>)values; Parent.AddValues(targetValues.Select(s => toSource(s))); } public IMultiDimensionalArray CreateStorageArray() { return new MultiDimensionalArray<TTarget>(); } public IMultiDimensionalArray CreateStorageArray(IMultiDimensionalArray values) { return new MultiDimensionalArray<TTarget>(values.Cast<TTarget>().ToList(), values.Shape); } public bool IsAutoSorted { get { if (variableToConvert == null) { return true;//a wild guess :( } return variableToConvert.IsAutoSorted; } set { throw new NotImplementedException(); } } /* public TVariable MinValue { get { throw new NotImplementedException(); } } public TVariable MaxValue { get { throw new NotImplementedException(); } } object IVariable.MaxValue { get { return MaxValue; } } object IVariable.MinValue { get { return MinValue; } } */ public override IMultiDimensionalArray<T> GetValues<T>(params IVariableFilter[] filters) { return (IMultiDimensionalArray<T>) base.GetValues(filters); } private IVariableFilter[] ConvertFilters(IEnumerable<IVariableFilter> filters) { //rewrite variable value filter to the domain of the source. IList<IVariableFilter> filterList = new List<IVariableFilter>(); foreach (var filter in filters) { //TODO: rewrite to IEnumerable etc if (filter is IVariableValueFilter && filter.Variable == convertedVariable) { var variableValueFilter = filter as IVariableValueFilter; IList values = new List<TSource>(); foreach (TTarget obj in variableValueFilter.Values) { values.Add(toSource(obj)); } filterList.Add(variableToConvert.CreateValuesFilter(values)); } else { filterList.Add(filter); } } return filterList.ToArray(); } private IUnit unit; public virtual IUnit Unit { get { return Parent != null ? Parent.Unit : unit; } set { if (Parent == null) { unit = value; } else { throw new Exception("Can't set unit for a filtered function."); } } } public Type ValueType { get { if (variableToConvert == Parent) return typeof(TTarget); return Parent.ValueType; } set { throw new NotImplementedException(); } } public TVariable DefaultValue { get { if ((variableToConvert == Parent) && typeof(TVariable) == typeof(TTarget)) { //no nice cast here :( return (TVariable)(object)toTarget((TSource) Parent.DefaultValue); } return (TVariable) Parent.DefaultValue; } set { throw new NotImplementedException(); } } public IList<TVariable> NoDataValues { get; set; } public virtual object NoDataValue { get { return NoDataValues.Count != 0 ? (object)NoDataValues[0] : null; } set { NoDataValues.Clear(); NoDataValues.Add((TVariable)value); } } public IMultiDimensionalArray<TVariable> Values { get { return GetValues<TVariable>(); } set { SetValues(value); } } object IMeasurable.DefaultValue { get ; set; } object IMeasurable.MinValidValue { get; set; } object IMeasurable.MaxValidValue { get; set; } IMeasurable IMeasurable.Clone() { return Clone(); } IMultiDimensionalArray IVariable.Values { get { return base.GetValues(); } set { SetValues((IEnumerable<TVariable>) value); } } public object DefaultStep { get; set; } IList IVariable.NoDataValues { get; set; } public IDictionary<string, string> Attributes { get; set; } public IVariable Filter(params IVariableFilter[] filters) { return (IVariable)base.Filter(filters); } public int FixedSize { get { if (Parent != null) { return Parent.FixedSize; } return 0; } set { Parent.FixedSize = value; } } public bool IsFixedSize { get { return Parent.IsFixedSize; } } public IVariable Clone() { throw new NotImplementedException(); } #region IMeasurable Members public virtual string DisplayName { get { return string.Format("{0} [{1}]", Name, ((Unit != null) ? Unit.Symbol : "-")); } } #endregion public IVariableValueFilter CreateValueFilter(object value) { return new VariableValueFilter<TVariable>(this, new[] { (TVariable)value }); } public IVariableValueFilter CreateValuesFilter(IEnumerable values) { return new VariableValueFilter<TVariable>(this, values.Cast<TVariable>()); } public IMultiDimensionalArray CachedValues { get; set; } public bool AllowSetInterpolationType { get; set; } public bool AllowSetExtrapolationType { get; set; } public bool SkipUniqueValuesCheck { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void CopyFrom(object source) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Text; namespace CarRental.API.BL.Models.Reservations { public class CreateReservationModel { public Guid ClientId { get; set; } public Guid CarId { get; set; } public DateTime RentalStartDate { get; set; } public DateTime RentalEndDate { get; set; } public Guid PickUpLocation { get; set; } public Guid DropOffLocation { get; set; } public int TotalPrice { get; set; } } }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5