text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Trettim.Settings
{
public static class UAC
{
#region [ Properties ]
public static int UserID
{
get
{
if (HttpContext.Current.Session["UAC"] != null)
return ((UACDetails)HttpContext.Current.Session["UAC"]).UserID;
else
return 0;
}
set
{
UACDetails details = (UACDetails)HttpContext.Current.Session["UAC"];
if (details == null)
details = new UACDetails();
details.UserID = value;
HttpContext.Current.Session["UAC"] = details;
}
}
public static string Login
{
get
{
if (HttpContext.Current.Session["UAC"] != null)
return ((UACDetails)HttpContext.Current.Session["UAC"]).Login;
else
return null;
}
set
{
UACDetails details = (UACDetails)HttpContext.Current.Session["UAC"];
if (details == null)
details = new UACDetails();
details.Login = value;
HttpContext.Current.Session["UAC"] = details;
}
}
public static string Name
{
get
{
if (HttpContext.Current.Session["UAC"] != null)
return ((UACDetails)HttpContext.Current.Session["UAC"]).Name;
else
return null;
}
set
{
UACDetails details = (UACDetails)HttpContext.Current.Session["UAC"];
if (details == null) details = new UACDetails();
details.Name = value;
HttpContext.Current.Session["UAC"] = details;
}
}
public static string ProjectName
{
get
{
if (HttpContext.Current.Session["UAC"] != null)
return ((UACDetails)HttpContext.Current.Session["UAC"]).ProjectName;
else
return null;
}
set
{
UACDetails details = (UACDetails)HttpContext.Current.Session["UAC"];
if (details == null)
details = new UACDetails();
details.ProjectName = value;
HttpContext.Current.Session["UAC"] = details;
}
}
#endregion
#region [ Methods ]
public static void Clear()
{
HttpContext.Current.Session["UAC"] = null;
}
public static bool Logged
{
get
{
return (HttpContext.Current.Session["UAC"] != null);
}
}
#endregion
}
}
|
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 lab5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
x.Select();
}
private void calculate_Click(object sender, EventArgs e)
{
int parsedResult;
int.TryParse(x.Text, out parsedResult);
if (parsedResult == 0)
{
MessageBox.Show("Введіть коректне ціле число.", "Помилка");
x.Text = "";
return;
}
int n = Convert.ToInt32(x.Text);
double root1 = (25 * n + Math.Exp(n + 1)) / 2 * Math.Cos(8*n);
root1 = root1 * Math.Exp(n + 5) + Math.Exp(n) * (2 * Math.Cos(3 * n));
root1 = 2*Math.Log(Math.Sqrt(root1));
double root2 = Math.Sqrt(Math.Exp(n + 1) * Math.Sin(n));
double res = root1 / root2 + Math.Abs(10 * n + Math.Pow(n, n));
if(Double.IsNaN(res))
{
MessageBox.Show("Результат виразу не коректний.");
result.Text = "0";
}
else
result.Text = res.ToString("N3");
}
}}
|
using UnityEngine;
using System.Collections;
public class DestructorEnemigo : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D objeto)
{
//Si se encuentra un objeto con el tag enemigo enemigo la nave se destruira
if(objeto.transform.tag == "enemigo")
{
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EPATEC.Models
{
public class Sucursal
{
/// Propiedad de id
public long id { get; set; }
}
} |
using AutoMapper;
using Prj.BusinessLogic.Models;
using Prj.Respositories.Entity;
using Prj.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prj.BusinessLogic.MapperConfig
{
public class AutoMapperConfig
{
public static void ConfigureMapper()
{
ConfigureMapping();
}
private static void ConfigureMapping()
{
Mapper.Initialize(cfg => {
cfg.CreateMap<MessageEntity, MessageModel>();
cfg.CreateMap<MessageModel, MessageEntity>();
// Mapper Account
cfg.CreateMap<AccountEntity, AccountModel>();
cfg.CreateMap<AccountModel, AccountEntity>()
.ForMember(dest => dest.Password, opt => opt.MapFrom(src => Globals.GetMD5FromString(src.UserName + src.Password).ToLower()));
cfg.CreateMap<AccountListEntity, AccountListModel>();
cfg.CreateMap<AccountListModel, AccountListEntity>();
cfg.CreateMap<AccountChangePassEntity, AccountChangePassModel>();
cfg.CreateMap<AccountChangePassModel, AccountChangePassEntity>()
.ForMember(dest => dest.PassOld, opt => opt.MapFrom(src => Globals.GetMD5FromString(src.UserName + src.PassOld).ToLower()))
.ForMember(dest => dest.PassNew, opt => opt.MapFrom(src => Globals.GetMD5FromString(src.UserName + src.PassNew).ToLower()));
// Permission
cfg.CreateMap<PermissionEntity, PermissionModel>();
cfg.CreateMap<PermissionModel, PermissionEntity>();
// Mapper Branch
cfg.CreateMap<BranchEntity, BranchModel>();
cfg.CreateMap<BranchModel, BranchEntity>();
cfg.CreateMap<BranchListEntity, BranchListModel>();
cfg.CreateMap<BranchListModel, BranchListEntity>();
// Mapper Department
cfg.CreateMap<DepartmentEntity, DepartmentModel>();
cfg.CreateMap<DepartmentModel, DepartmentEntity>();
// Mapper Application
cfg.CreateMap<ApplicationEntity, ApplicationModel>();
cfg.CreateMap<ApplicationModel, ApplicationEntity>();
// Mapper Feature
cfg.CreateMap<FeatureEntity, FeatureModel>();
cfg.CreateMap<FeatureModel, FeatureEntity>();
// Mapper Department
cfg.CreateMap<GroupPageEntity, GroupPageModel>();
cfg.CreateMap<GroupPageModel, GroupPageEntity>();
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
using Euclid7.Models;
using System.Web.Mail;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Text;
using umbraco.NodeFactory;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using System.Xml.Linq;
using umbraco.presentation.nodeFactory;
using System.Data;
namespace Euclid7.Controllers
{
public class LocatorSurfaceController : SurfaceController
{
private static string connStr = ConfigurationManager.ConnectionStrings["euclidOASConn"].ConnectionString;
private static SqlConnection conn = new SqlConnection(connStr);
public umbraco.NodeFactory.Node CurrentPage = umbraco.NodeFactory.Node.GetCurrent();
[ActionName("LoadDistributor")]
public ActionResult LoadDistributor()
{
DistributorParameters dp = new DistributorParameters();
conn.Open();
string selectString = "Select distinct state from [euclidOAS].[dbo].[distributor] where type = 1";
SqlCommand cmd = new SqlCommand(selectString, conn);
SqlDataReader reader = cmd.ExecuteReader();
try
{
if (reader != null && reader.HasRows)
{
dp.States = new List<SelectListItem>();
while (reader.Read())
{
dp.States.Add(new SelectListItem()
{
Text = reader[0].ToString().Replace(' ', '-'),
Value = reader[0].ToString()
});
}
}
}
catch (Exception eo)
{
throw eo;
}
reader.Close();
conn.Close();
return PartialView("DistributorLocator", dp);
}
[ActionName("LoadSalesRep")]
public ActionResult LoadSalesRep()
{
DistributorParameters dp = new DistributorParameters();
conn.Open();
string selectString = "Select distinct state from [euclidOAS].[dbo].[distributor] where type = 0";
SqlCommand cmd = new SqlCommand(selectString, conn);
SqlDataReader reader = cmd.ExecuteReader();
try
{
if (reader != null && reader.HasRows)
{
dp.States = new List<SelectListItem>();
while (reader.Read())
{
dp.States.Add(new SelectListItem()
{
Text = reader[0].ToString().Replace(' ', '-'),
Value = reader[0].ToString()
});
}
}
}
catch (Exception eo)
{
throw eo;
}
reader.Close();
conn.Close();
return PartialView("SalesRepLocator", dp);
}
[ActionName("GetDistributorResults")]
public ActionResult GetDistributorResults(DistributorParameters dp, FormCollection form)
{
int stateZoom = Convert.ToInt32(CurrentPage.GetProperty("stateSearchMapZoom").ToString());
int zipZoom = Convert.ToInt32(CurrentPage.GetProperty("zipSearchMapZoom").ToString());
Session["distributors"] = null;
string whereClause = "WHERE";
string resultsFor = "";
bool isZipSearch = false;
if (string.IsNullOrWhiteSpace(dp.City) && string.IsNullOrWhiteSpace(dp.State) && string.IsNullOrWhiteSpace(dp.ZipCode))
{
//Display Error when no selections have been made
TempData["error"] = CurrentPage.GetProperty("requiredValidationText") != null ? CurrentPage.GetProperty("requiredValidationText").ToString() : "Please indicate State or Zip.";
}
else if (!string.IsNullOrWhiteSpace(dp.ZipCode))
{
//Zip takes priority over City/State
isZipSearch = true;
string selectedZip = dp.ZipCode;
if (ModelState.IsValid)
{
whereClause = whereClause + " a.postal_code = '" + selectedZip + "'";
resultsFor = "'" + selectedZip + "'";
}
}
else
{
if (!string.IsNullOrWhiteSpace(dp.City) && string.IsNullOrWhiteSpace(dp.State))
{
//search by City only if no State is selected
string selectedCity = dp.City;
whereClause = whereClause + " a.city LIKE '%" + selectedCity + "%'";
resultsFor = "'" + selectedCity.ToUpper() + "'";
}
else if (string.IsNullOrWhiteSpace(dp.City) && !string.IsNullOrWhiteSpace(dp.State))
{
//search by State only if no City is selected
string selectedState = dp.State;
whereClause = whereClause + " a.state = '" + selectedState + "'";
resultsFor = "'" + selectedState.ToUpper() + "'";
}
else
{
//search by State and City
string selectedCity = dp.City;
string selectedState = dp.State;
whereClause = whereClause + " a.city LIKE '%" + selectedCity + "%' AND a.state = '" + selectedState + "'";
resultsFor = "'" + selectedCity.ToUpper() + ", " + selectedState.ToUpper() + "'";
}
}
if (whereClause != "WHERE")
{
TempData["resultsFor"] = (CurrentPage.GetProperty("resultsForTextOverride") != null ? CurrentPage.GetProperty("resultsForTextOverride").ToString() : "RESULTS FOR") + " " + resultsFor;
TempData["resultsFlag"] = true;
DistributorResultSet drs = new DistributorResultSet();
if (!isZipSearch)
{
TempData["mapZoom"] = stateZoom;
DataSet ds = new DataSet();
List<Distributor> distributors = new List<Distributor>();
using (SqlConnection con = new SqlConnection(connStr))
{
string sql = "SELECT a.[name],a.[address1],a.[city],a.[state],a.[postal_code],a.[phone],a.[fax],a.[website], b.lat, b.long FROM [dbo].[distributor] a LEFT JOIN [dbo].[zips] b on a.postal_code = b.zip " + whereClause + " AND[type] = 1 ORDER BY a.[name]";
using (SqlCommand sqlcmd = new SqlCommand(sql))
{
sqlcmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(sqlcmd))
{
sda.Fill(ds);
}
}
}
int markerId = 1;
foreach (DataRow row in ds.Tables[0].Rows)
{
Distributor distributor = new Distributor();
distributor.Name = Convert.ToString(row["name"]);
distributor.Address = Convert.ToString(row["address1"]);
distributor.City = Convert.ToString(row["city"]).Replace(' ', '-');
distributor.StateValue = Convert.ToString(row["state"]).Replace(' ', '-');
distributor.State = Convert.ToString(row["state"]);
distributor.Zip = Convert.ToString(row["postal_code"]);
distributor.Phone = Convert.ToString(row["phone"]);
distributor.Fax = Convert.ToString(row["fax"]);
distributor.Website = Convert.ToString(row["website"]);
if (row["lat"] != DBNull.Value && row["long"] != DBNull.Value)
{
distributor.Lat = Convert.ToString(row["lat"]);
distributor.Long = "-" + Convert.ToString(row["long"]);
distributor.MarkerId = markerId;
markerId++;
}
else
{
distributor.Lat = "";
distributor.Long = "";
distributor.MarkerId = 0;
}
distributor.Distance = "undefined";
distributors.Add(distributor);
}
foreach (Distributor dis in distributors)
{
if (dis.Website.Length > 4 && !(dis.Website.Substring(0, 4) == "http"))
{
dis.Website = "http://" + dis.Website;
}
}
//foreach (Distributor dis in distributors)
//{
// using (WebClient wc = new WebClient())
// {
// var json = wc.DownloadString("https://maps.googleapis.com/maps/api/geocode/json?address=" + dis.Address + " " + dis.City + ", " + dis.State + " " + dis.Zip + "&key=AIzaSyCShc6ISfXBfzjitikfWY6pJIaQpw4dpxs");
// GoogleMapJSON googleMapJSON = JsonConvert.DeserializeObject<GoogleMapJSON>(json);
// dis.Lat = googleMapJSON.results[0].geometry.location.lat;
// dis.Long = googleMapJSON.results[0].geometry.location.lng;
// }
//}
drs.Distributors = distributors;
}
else
{
TempData["mapZoom"] = zipZoom;
TempData["resultsFor"] = (CurrentPage.GetProperty("resultsForTextOverride") != null ? CurrentPage.GetProperty("resultsForTextOverride").ToString() : "RESULTS FOR") + " " + resultsFor;
TempData["resultsFlag"] = true;
drs.Distributors = GetDistributorsByZip(dp.ZipCode, 50);
}
if (drs.Distributors.Count > 0)
{
Session["distributors"] = drs;
}
else
{
TempData["resultsFor"] = (CurrentPage.GetProperty("noResultsForTextOverride") != null ? CurrentPage.GetProperty("noResultsForTextOverride").ToString() : "NO RESULTS FOR") + " " + resultsFor;
}
}
return CurrentUmbracoPage();
}
[ActionName("GetSalesRepResults")]
public ActionResult GetSalesRepResults(DistributorParameters dp, FormCollection form)
{
Session["distributors"] = null;
string whereClause = "WHERE";
string resultsFor = "";
bool isZipSearch = false;
if (string.IsNullOrWhiteSpace(dp.City) && string.IsNullOrWhiteSpace(dp.State) && string.IsNullOrWhiteSpace(dp.ZipCode))
{
//Display Error when no selections have been made
TempData["error"] = CurrentPage.GetProperty("requiredValidationText") != null ? CurrentPage.GetProperty("requiredValidationText").ToString() : "Please indicate State";
}
else if (!string.IsNullOrWhiteSpace(dp.ZipCode))
{
//Zip takes priority over City/State
isZipSearch = true;
string selectedZip = dp.ZipCode;
if (ModelState.IsValid)
{
whereClause = whereClause + " a.postal_code = '" + selectedZip + "'";
resultsFor = "'" + selectedZip + "'";
}
}
else
{
if (!string.IsNullOrWhiteSpace(dp.City) && string.IsNullOrWhiteSpace(dp.State))
{
//search by City only if no State is selected
string selectedCity = dp.City;
whereClause = whereClause + " a.city LIKE '%" + selectedCity + "%'";
resultsFor = "'" + selectedCity.ToUpper() + "'";
}
else if (string.IsNullOrWhiteSpace(dp.City) && !string.IsNullOrWhiteSpace(dp.State))
{
//search by State only if no City is selected
string selectedState = dp.State;
whereClause = whereClause + " a.state = '" + selectedState + "'";
resultsFor = "'" + selectedState.ToUpper() + "'";
}
else
{
//search by State and City
string selectedCity = dp.City;
string selectedState = dp.State;
whereClause = whereClause + " a.city LIKE '%" + selectedCity + "%' AND a.state = '" + selectedState + "'";
resultsFor = "'" + selectedCity.ToUpper() + ", " + selectedState.ToUpper() + "'";
}
}
if (whereClause != "WHERE")
{
TempData["resultsFor"] = (CurrentPage.GetProperty("resultsForTextOverride") != null ? CurrentPage.GetProperty("resultsForTextOverride").ToString() : "RESULTS FOR") + " " + resultsFor;
TempData["resultsFlag"] = true;
DistributorResultSet drs = new DistributorResultSet();
if (!isZipSearch)
{
DataSet ds = new DataSet();
List<Distributor> distributors = new List<Distributor>();
using (SqlConnection con = new SqlConnection(connStr))
{
string sql = "SELECT a.[name],a.[address1],a.[city],a.[state],a.[postal_code],a.[email],a.[phone],a.[fax],a.[website] FROM[euclidOAS].[dbo].[distributor] a " + whereClause + "AND [type] = 0";
using (SqlCommand sqlcmd = new SqlCommand(sql))
{
sqlcmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(sqlcmd))
{
sda.Fill(ds);
}
}
}
foreach (DataRow row in ds.Tables[0].Rows)
{
Distributor distributor = new Distributor();
distributor.Name = Convert.ToString(row["name"]);
distributor.Address = Convert.ToString(row["address1"]);
distributor.City = Convert.ToString(row["city"]).Replace(' ', '-');
distributor.StateValue = Convert.ToString(row["state"]).Replace(' ', '-');
distributor.State = Convert.ToString(row["state"]);
distributor.Zip = Convert.ToString(row["postal_code"]);
distributor.Email = Convert.ToString(row["email"]);
distributor.Phone = Convert.ToString(row["phone"]);
distributor.Fax = Convert.ToString(row["fax"]);
distributor.Website = Convert.ToString(row["website"]);
distributor.Distance = "undefined";
distributors.Add(distributor);
}
drs.Distributors = distributors;
}
else
{
TempData["resultsFor"] = (CurrentPage.GetProperty("resultsForTextOverride") != null ? CurrentPage.GetProperty("resultsForTextOverride").ToString() : "RESULTS FOR") + " " + resultsFor;
TempData["resultsFlag"] = true;
drs.Distributors = GetDistributorsByZip(dp.ZipCode, 25);
}
if (drs.Distributors.Count > 0)
{
Session["distributors"] = drs;
}
else
{
TempData["resultsFor"] = (CurrentPage.GetProperty("noResultsForTextOverride") != null ? CurrentPage.GetProperty("noResultsForTextOverride").ToString() : "NO RESULTS FOR") + " " + resultsFor;
}
}
return CurrentUmbracoPage();
}
public List<Distributor> GetDistributorsByZip(string zipcode, int radius)
{
DataSet ds = new DataSet();
List<Distributor> distributors = new List<Distributor>();
using (SqlConnection con = new SqlConnection(connStr))
{
string proc = "usp_distributor_zip_search";
using (SqlCommand cmd = new SqlCommand(proc))
{
cmd.Parameters.Add("@zip", SqlDbType.VarChar).Value = zipcode;
cmd.Parameters.Add("@iRadius", SqlDbType.Int).Value = radius;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
}
}
}
int markerId = 1;
foreach (DataRow row in ds.Tables[0].Rows)
{
Distributor distributor = new Distributor();
distributor.Name = Convert.ToString(row["name"]);
distributor.Address = Convert.ToString(row["address1"]);
distributor.City = Convert.ToString(row["city"]).Replace(' ', '-');
distributor.StateValue = Convert.ToString(row["state"]).Replace(' ', '-');
distributor.State = Convert.ToString(row["state"]);
distributor.Zip = Convert.ToString(row["postal_code"]);
distributor.Phone = Convert.ToString(row["phone"]);
distributor.Fax = Convert.ToString(row["fax"]);
distributor.Website = Convert.ToString(row["website"]);
distributor.Lat = Convert.ToString(row["lat"]);
distributor.Long = "-" + Convert.ToString(row["long"]);
distributor.Distance = Math.Round(Convert.ToDecimal(row["distance"]), 2).ToString();
distributor.MarkerId = markerId;
distributors.Add(distributor);
markerId++;
}
foreach (Distributor dis in distributors)
{
if (dis.Website.Length > 4 && !(dis.Website.Substring(0, 4) == "http"))
{
dis.Website = "http://" + dis.Website;
}
}
return distributors;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fornax.Net.Analysis.Filters
{
interface IStemFilter
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.RobinsonCrusoe_Game.Cards.IslandCards
{
public interface IIslandCard
{
RessourceType[] GetRessourcesOnIsland();
void GatherRessources(RessourceType ressource);
bool IsNaturalCamp();
int GetMaterialNumber();
int GetNumberOfDiscoveryTokens();
TerrainType GetTerrain();
int GetNumberOfAnimals();
void EndOfSource(RessourceType collectRessource);
}
public enum RessourceType
{
Fish,
Parrot,
Wood,
}
public enum TerrainType
{
Beach,
Plain,
Mountain,
River,
Hill,
Volcano
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Requestrr.WebApi.Controllers.DownloadClients.Ombi
{
public class SaveOmbiMoviesSettingsModel : OmbiSettingsModel
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace E_Learning.Controllers
{
public class ResursiController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Kombinatorika_1()
{
return View();
}
public IActionResult Kombinatorika_2()
{
return View();
}
public IActionResult Polinomi_1()
{
return View();
}
public IActionResult Polinomi_2()
{
return View();
}
public IActionResult Brojni_Sistemi_1()
{
return View();
}
public IActionResult Brojni_Sistemi_2()
{
return View();
}
public IActionResult Pravopis_1()
{
return View();
}
public IActionResult Pravopis_2()
{
return View();
}
public IActionResult Gramatika_1()
{
return View();
}
public IActionResult Gramatika_2()
{
return View();
}
public IActionResult Književnost_1()
{
return View();
}
public IActionResult Književnost_2()
{
return View();
}
}
} |
namespace Enrollment.Common.Configuration.ExpressionDescriptors
{
public class SingleOrDefaultOperatorDescriptor : FilterMethodOperatorDescriptorBase
{
}
} |
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 KuzProject
{
public partial class OrderMenu : Form
{
public OrderMenu()
{
InitializeComponent();
}
private void Back_Click(object sender, EventArgs e)
{
this.Hide();
Form1 MM = new Form1();
MM.Show();
}
private void toolStripContainer1_ContentPanel_Load(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace CompanyDatabaseProcessing.Models
{
//Комментарии: Была выбрана подобная модель представления для того чтобы работа с 3 сущностями в коде обьединялась в вид
//Имя, Фамилия, Отчество, Отдел, Должность (для создания стого-типизированного представления) без какой-либо информации об id.
/// <summary>
/// Класс для представления элементов из таблицы Person (создание таблицы описано в SQL-запросе при создание БД) в виде: Имя, Фамилия, Отчество, Отдел, Должность
/// </summary>
public class PersonView
{
[Required(ErrorMessage = "Пожалуйста, введите имя")]
public string first_name { get; set; }
[Required(ErrorMessage = "Пожалуйста, введите фамилию")]
public string second_name { get; set; }
[Required(ErrorMessage = "Пожалуйста, введите отчество")]
public string last_name { get; set; }
[Required(ErrorMessage = "Пожалуйста, введите отдел")]
public string dep { get; set; }
[Required(ErrorMessage = "Пожалуйста, введите пост")]
public string post { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.Interfaces
{
public interface IBaseRepository<T> where T:class
{
Task<IQueryable<T>> GetAllAsync();
Task<T> GetByIdAsync(int id);
Task AddAsync(T item);
Task<bool> DeleteAsync(int id);
Task<bool> UpdateAsync(T item);
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using DatingApp.API.Models;
using udemy_datingapp.api.Helpers;
using udemy_datingapp.api.Models;
namespace udemy_datingapp.api.Data {
public interface IDatingRepository {
void Add<T> (T entity) where T : class;
void Delete<T> (T entity) where T : class;
Task<bool> SaveAll ();
Task<PagedList<User>> GetUsers (UserParam userParam);
Task<User> GetUser (int id, bool isCurrentUser);
Task<Photo> GetPhoto (int id);
Task<Photo> GetMainPhotoForUser (int userId);
Task<Like> GetLikes (int userId, int recipientId);
Task<Message> GetMessage (int id);
Task<PagedList<Message>> GetMessagesForUser(MessageParams messageParams);
Task<IEnumerable<Message>> GetMessageThread(int userId, int recipientId);
}
} |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using MediaManager.API.Controllers;
using MediaManager.API.Helpers;
using MediaManager.API.Models;
using MediaManager.API.Repository;
using MediaManager.API.Services;
using MediaManager.DAL.DBEntities;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using IdentityServer4.AccessTokenValidation;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.Extensions.PlatformAbstractions;
namespace MediaManager.API
{
/// <summary>
/// Class containing code to be executed first time
/// </summary>
public class Startup
{
IConfiguration configuration;
/// <summary>
/// Constructor
/// </summary>
/// <param name="environment">environemt to get the configuration file</param>
public Startup(IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder().SetBasePath(environment.ContentRootPath).AddJsonFile("appsettings.json");
configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
/// <summary>
/// the method is called at runtime
/// </summary>
/// <param name="services">container containg services</param>
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(typeof(ExceptionHandler));
var serviceBuilder = services.BuildServiceProvider();
var service = serviceBuilder.GetService<IHostingEnvironment>();
var connectionString = "Data Source = " + Path.Combine(service.ContentRootPath, "MediaManager.db");
services.AddDbContext<DatabaseContext>(option => option.UseSqlite(connectionString));
services.AddMvc(setup =>
{
setup.Filters.Add(new RequireHttpsAttribute());
setup.ReturnHttpNotAcceptable = true;
setup.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
setup.InputFormatters.Add(new XmlDataContractSerializerInputFormatter());
var jsonOutputFormatter = setup.OutputFormatters.OfType<JsonOutputFormatter>().FirstOrDefault();
if (jsonOutputFormatter != null)
{
jsonOutputFormatter.SupportedMediaTypes.Add("application/vnd.ak.hateoas+json");
}
}).AddJsonOptions(options =>
{
options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
services.AddResponseCaching();
services.AddHttpCacheHeaders(
(expirationModelOptions) =>
{
expirationModelOptions.MaxAge = 60;
},
(validationModelOptions) =>
{
validationModelOptions.AddMustRevalidate = true;
});
services.AddSingleton<MetadataStore>();
services.AddScoped<ParticipantRepository, ParticipantRepository>();
services.AddScoped<VideoRepository, VideoRepository>();
services.AddScoped<UserRepository, UserRepository>();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<TagRepository, TagRepository>();
services.AddScoped<IUrlHelper, UrlHelper>(implementationFactory =>
{
var actionContext = implementationFactory.GetService<IActionContextAccessor>().ActionContext;
return new UrlHelper(actionContext);
});
services.AddTransient<IPropertyMappingService, PropertyMappingService>();
services.AddTransient<ITypeHelperService, TypeHelperService>();
services.AddCors(cfg =>
{
cfg.AddPolicy("default", bldr =>
{
bldr.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://wildermuth.com");
});
cfg.AddPolicy("AnyGET", bldr =>
{
bldr.AllowAnyHeader().WithMethods("GET").AllowAnyOrigin();
});
});
// services.AddMvcCore().AddApiExplorer();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Title = "MediaManager API",
Contact = new Contact { Name = "Akansha Raman", Email = "akansha.raman23@gmail.com", Url = "akansharman.github.io" },
Description = "An API to manage your offline activities.",
Version = "1"
});
var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "MediaManager.API.xml");
c.IncludeXmlComments(filePath);
//Define OAuth2.0 scheme that is in use
//c.AddSecurityDefinition("oauth2", new OAuth2Scheme
//{
// Type = "oauth2",
// Flow = "Hybridand ClientCredential",
// AuthorizationUrl = "http://localhost:55470/",
// Scopes = new Dictionary<string, string>
// {
// { "Reader", "Access Read operation" },
// {"Writer", "Access Write Operation" },
// {"Admin", "Access update user operation" }
// }
//});
//c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
//{
// {"oauth2", new[] {"Reader", "Writer"} }
//});
});
#region jwt auth
/*
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>();
services.ConfigureApplicationCookie(options =>
{
options.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = (ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 401;
}
return Task.CompletedTask;
}),
OnRedirectToAccessDenied = (ctx) =>
{
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = 401;
}
return Task.CompletedTask;
}
};
}
);
services.AddTransient<UserIdentityInitializer>();
services.AddAuthentication().AddJwtBearer(jwt =>
{
jwt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("verylongkeyvaluethatissecured")),
ValidAudience = "audience",
ValidIssuer = "issuer",
ValidateLifetime = true,
};
});
services.AddAuthorization(auth =>
{
//auth.DefaultPolicy =
// new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
auth.AddPolicy("SuperUser", p =>
{
p.RequireClaim("SuperUser", "True");
p.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
});
auth.AddPolicy("Reader", p =>
{
p.RequireClaim("Reader", "True");
p.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
});
auth.AddPolicy("Writer", p =>
{
p.RequireClaim("Writer", "True");
p.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
});
});*/
#endregion
#region OAuthImplementation
/* services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
}).AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://identityserverakansha.azurewebsites.net/";
options.RequireHttpsMetadata = false;
options.ClientId = "reactapp";
options.SaveTokens = true;
options.Events.OnMessageReceived = async ctx =>
{
Debug.Write(ctx.Principal);
};
});*/
#endregion
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:55470/";
options.RequireHttpsMetadata = false;
options.ApiName = "api";
//options.ApiSecret = "secret";
});
services.AddAuthorization(auth =>
{
auth.AddPolicy("Reader", x =>
{
x.RequireClaim(ClaimTypes.Role, "Read");
x.AddAuthenticationSchemes(IdentityServerAuthenticationDefaults.AuthenticationScheme);
});
auth.AddPolicy("Writer", x =>
{
x.RequireClaim(ClaimTypes.Role, "Read");
x.AddAuthenticationSchemes(IdentityServerAuthenticationDefaults.AuthenticationScheme);
});
auth.AddPolicy("SuperUser", x =>
{
x.RequireClaim(ClaimTypes.Role, "Admin");
x.AddAuthenticationSchemes(IdentityServerAuthenticationDefaults.AuthenticationScheme);
});
auth.DefaultPolicy = new AuthorizationPolicyBuilder(auth.GetPolicy("Reader")).Build();
});
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">ApplicationBuilder</param>
/// <param name="env">HostingEnvironment</param>
/// <param name="context">Database context</param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, DatabaseContext context)
{
if (env.IsDevelopment())
{
app.UseMiddleware<ExceptionHandler>();
}
app.UseHttpCacheHeaders(); // should be before mvc
app.UseAuthentication();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId("tes");
c.OAuthClientSecret("tes");
c.SwaggerEndpoint("../swagger/v1/swagger.json", "MediaManager API");
});
//app.UseJwtBearerAuthentication(new JwtBearerOptions()
//{
// AutomaticAuthenticate = true,
// AutomaticChallenge = true,
//});
// context.Database.EnsureCreatedAsync().Wait();
// initializer.Seed().Wait();
app.UseMvc();
MetadataStore.LoadEntities(context);
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Participant, ParticipantVideoDisplayDTO>().ForMember(x => x.ParticipantName, opt => opt.MapFrom(src => src.ParticipantName));
cfg.CreateMap<VideoParticipant, ParticipantVideoDisplayDTO>().ForMember(x => x.ParticipantName, opt => opt.MapFrom(x => x.Participant.ParticipantName));
cfg.CreateMap<Video, VideoForDisplayDTO>()
.ForMember(dest => dest.Duration, opt => opt.MapFrom(src => TimeSpan.FromSeconds(src.Duration)))
.ForMember(dest => dest.WatchOffset, opt => opt.MapFrom(src => TimeSpan.FromSeconds(src.WatchOffset)));
cfg.CreateMap<VideoForCreationDTO, Video>().ForMember(x => x.Author, opt => opt.Ignore())
.ForMember(x => x.AuthorId, opt => opt.Ignore())
.ForMember(x => x.Domain, opt => opt.Ignore())
.ForMember(x => x.DomainId, opt => opt.Ignore())
.ForMember(x => x.VideoId, opt => opt.Ignore())
.ForMember(x => x.VideoParticipants, opt => opt.Ignore());
cfg.CreateMap<VideoForUpdateDTO, Video>()
.ForMember(x => x.Author, opt => opt.Ignore())
.ForMember(x => x.AuthorId, opt => opt.Ignore())
.ForMember(x => x.Domain, opt => opt.Ignore())
.ForMember(x => x.DomainId, opt => opt.Ignore())
.ForMember(x => x.VideoParticipants, opt => opt.Ignore());
cfg.CreateMap<VideoParticipant, string>().ConvertUsing(x => x.Participant.ParticipantName);
cfg.CreateMap<UserForCreationDTO, User>()
.ForMember(x => x.RegistrationDate, opt => opt.Ignore());
cfg.CreateMap<User, UserForDisplayDTO>();
cfg.CreateMap<UserForUpdateDTO, User>().ForMember(x => x.Email, opt => opt.MapFrom(src => src.Email))
.ForMember(x => x.Username, opt => opt.Ignore())
.ForMember(x => x.RegistrationDate, opt => opt.Ignore())
.ForMember(x => x.Name, opt => opt.Ignore());
}
);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NexusController : ShootingSystem
{
// Public game objects
public GameObject minion;
public GameObject minionsParent;
public GameObject champion;
public GameObject championsParent;
public GameObject mainCamera;
public Transform spawnPoint;
public Transform[] whiteTargets;
public Transform[] blackTargets;
public GameObject minionHealthBar;
public GameObject championHealthBar;
public float minionSpawnRate = 20f;
private float minionSpawnTimer = 0f;
protected override void Start()
{
base.Start();
if (isWhite)
{
ChampionSpawn();
}
}
protected override void Update()
{
base.Update();
minionSpawnTimer += Time.deltaTime;
if (minionSpawnTimer >= minionSpawnRate)
{
for (int i = 0; i < 3; i++)
{
MinionsSpawn();
}
minionSpawnTimer = 0f;
}
}
private void MinionsSpawn()
{
GameObject newMinion = Instantiate(minion, spawnPoint.position,
Quaternion.Euler(spawnPoint.transform.forward)) as GameObject;
newMinion.transform.SetParent(minionsParent.transform);
if (isWhite) // for white minions
{
newMinion.GetComponent<SpriteRenderer>().color = Color.white;
newMinion.GetComponent<CharactersController>().isWhite = true;
MinionController setNew = newMinion.GetComponent<MinionController>();
setNew.iconMap = whiteTargets;
setNew.healthBar = Instantiate(minionHealthBar, newMinion.transform);
}
else // for black minions
{
Vector3 tempScale = new Vector3(-newMinion.transform.localScale.x,
newMinion.transform.localScale.y, newMinion.transform.localScale.z);
newMinion.transform.localScale = tempScale;
newMinion.GetComponent<SpriteRenderer>().color = Color.black;
newMinion.GetComponent<CharactersController>().isWhite = false;
MinionController setNew = newMinion.GetComponent<MinionController>();
setNew.iconMap = blackTargets;
setNew.healthBar = Instantiate(minionHealthBar, newMinion.transform);
}
}
public void ChampionSpawn()
{
GameObject newChampion = Instantiate(champion, spawnPoint.position,
Quaternion.Euler(spawnPoint.transform.forward)) as GameObject;
//Debug.Log(Quaternion.Euler(spawnPoint.transform.forward));
newChampion.transform.SetParent(championsParent.transform);
if (isWhite) // for white champions
{
newChampion.GetComponent<SpriteRenderer>().color = Color.white;
newChampion.GetComponent<CharactersController>().isWhite = true;
ChampionController setNew = newChampion.GetComponent<ChampionController>();
setNew.healthBar = Instantiate(championHealthBar, newChampion.transform);
setNew.home = this;
CameraController main = mainCamera.GetComponent<CameraController>();
main.champion = newChampion;
}
else // for black champions
{
Vector3 tempScale = new Vector3(-newChampion.transform.localScale.x,
newChampion.transform.localScale.y, newChampion.transform.localScale.z);
newChampion.transform.localScale = tempScale;
newChampion.GetComponent<SpriteRenderer>().color = Color.black;
newChampion.GetComponent<CharactersController>().isWhite = false;
ChampionController setNew = newChampion.GetComponent<ChampionController>();
setNew.healthBar = Instantiate(championHealthBar, newChampion.transform);
}
}
}
|
using System.IO;
namespace PhysicalCache.Items
{
public interface ICacheItem
{
/// <summary>
/// The key the CacheItem should be addressed with
/// </summary>
public string Key { get; set; }
/// <summary>
/// The File to be cached
/// </summary>
public FileInfo File { get; set; }
/// <summary>
/// The Raw bytes that should represent the file
/// </summary>
public byte[] RawBytes { get; set; }
}
} |
using Godot;
using System;
using static Lib;
public class NecromancerArrow : Arrow
{
public override void _Ready()
{
base._Ready();
damage = NECROMANCER_ARROW_DAMAGE;
wizard = NECROMANCER_WIZARD;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CursoLinq
{
class Program
{
static void Main(string[] args)
{
int[] numeros = { 1, 5, 7, 3, 5, 9, 8, 12 };
IEnumerable<int> valores = from n in numeros where n > 3 && n < 8 select n;
// mostrar los resultados
foreach (int num in valores)
Console.WriteLine(num);
Console.ReadLine();
Console.WriteLine("-------------------------------");
string[] postres = { "pay de manzana", "pastel de chocolate", "manzana caramelizada", "fresas con crema" };
IEnumerable<string> encontrados = from p in postres
where p.Contains("manzana")
orderby p
select p;
foreach (string postre in encontrados)
Console.WriteLine(postre);
Console.ReadLine();
Console.WriteLine("---------------------------------");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PICSimulator.Model
{
class ProgramCounter
{
uint programmCounter = 0;
void inkrement()
{
programmCounter++;
}
void PCgoto(uint _addr)
{
programmCounter = _addr;
}
void PCcall(uint _addr)
{
// Addr auf Stack
programmCounter = _addr;
}
void PCreturn()
{
// Addr. von Stack
}
void reset()
{
programmCounter = 0;
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
namespace dojodachi.Controllers
{
public class HomeController : Controller
{
[HttpGet]
[Route("")]
public IActionResult Index()
{
TempData["gameStatus"] = "Playing";
int? happiness = HttpContext.Session.GetInt32("happiness");
if(happiness == null)
{
HttpContext.Session.SetInt32("happiness", 20);
TempData["message"] = "Hello, meet your Dojonachi";
}
int? fullness = HttpContext.Session.GetInt32("fullness");
if(fullness == null)
{
HttpContext.Session.SetInt32("fullness", 20);
}
int? energy = HttpContext.Session.GetInt32("energy");
if(energy == null)
{
HttpContext.Session.SetInt32("energy", 50);
}
int? meals = HttpContext.Session.GetInt32("meals");
if(meals == null)
{
HttpContext.Session.SetInt32("meals", 3);
}
if(fullness <= 0 || happiness <= 0)
{
TempData["message"] = "Oh, your Dojodachi is dead, try new game";
TempData["gameStatus"] = "over";
}
if(energy >= 100 && fullness >= 100 && happiness >= 100)
{
TempData["message"] = "Your Dojodachi is the happiest dojodachi in the world. You WON";
TempData["gameStatus"] = "over";
}
TempData["happiness"] = HttpContext.Session.GetInt32("happiness");
TempData["fullness"] = HttpContext.Session.GetInt32("fullness");
TempData["energy"] = HttpContext.Session.GetInt32("energy");
TempData["meals"] = HttpContext.Session.GetInt32("meals");
return View();
}
[HttpGet]
[Route("/feed")]
public IActionResult Feed()
{
if(HttpContext.Session.GetInt32("meals") > 0)
{
int? meals = HttpContext.Session.GetInt32("meals") - 1;
HttpContext.Session.SetInt32("meals", (int)meals);
Random rand1 = new Random();
int? gained = rand1.Next(5,11);
if(gained == 1)
{
TempData["message"] = "Your Dojodachi doesn't like this meal!";
}
else
{
Random rand2 = new Random();
int wellGained = rand2.Next(5,11);
int? fullness = HttpContext.Session.GetInt32("fullness") + wellGained;
HttpContext.Session.SetInt32("fullness", (int)wellGained);
TempData["message"] = $"Your Dojodachi like this meal! Your fullness increased by {wellGained} points";
}
}
else
{
TempData["message"] = "You don't have any meals!";
}
return RedirectToAction("Index");
}
[HttpGet]
[Route("/play")]
public IActionResult Play()
{
if(HttpContext.Session.GetInt32("energy") >= 5)
{
int? energy = HttpContext.Session.GetInt32("energy") - 5;
HttpContext.Session.SetInt32("energy", (int)energy);
Random rand3 = new Random();
int? gained = rand3.Next(5,11);
if(gained == 1)
{
TempData["message"] = "Your Dojodachi doesn't like this meal!";
}
else
{
Random rand4 = new Random();
int? happiness = HttpContext.Session.GetInt32("happiness") + rand4.Next(5,11);
HttpContext.Session.SetInt32("happiness", (int)happiness);
TempData["message"] = $"You played with your Dojodachi and increased happiness by {rand4.Next(5,11)}";
}
}
else
{
TempData["message"] = "You don't have enough energy!";
}
return RedirectToAction("Index");
}
[HttpGet]
[Route("/work")]
public IActionResult Work()
{
if(HttpContext.Session.GetInt32("energy") >= 5)
{
int? energy = HttpContext.Session.GetInt32("energy") - 5;
HttpContext.Session.SetInt32("energy", (int)energy);
Random rand = new Random();
int gained = rand.Next(1,4);
int? meals = HttpContext.Session.GetInt32("meals") + gained;
HttpContext.Session.SetInt32("meals", (int)meals);
TempData["message"] = $"Your Dojodachi worked and earned {gained} meals";
}
else
{
TempData["message"] = "You don't have enough energy!";
}
return RedirectToAction("Index");
}
[HttpGet]
[Route("/sleep")]
public IActionResult Sleep()
{
// if((HttpContext.Session.GetInt32("happiness")) >= 5 && (HttpContext.Session.GetInt32("fullness") >= 5))
// {
// TempData["message"] = "You don't have enough fullness and happiness!";
// }
// else if((HttpContext.Session.GetInt32("happiness")) >= 5 || (HttpContext.Session.GetInt32("fullness") >= 5))
// {
// TempData["message"] = "You don't have enough fullness or happiness!";
// }
// else
// {
int? happiness = HttpContext.Session.GetInt32("happiness");
HttpContext.Session.SetInt32("happiness", (int)happiness - 5);
int? fullness = HttpContext.Session.GetInt32("fullness");
HttpContext.Session.SetInt32("fullness", (int)fullness -5);
int? energy = HttpContext.Session.GetInt32("energy");
HttpContext.Session.SetInt32("energy", (int)energy +15);
TempData["message"] = "Your energy gained 15, but you lost 5 happiness and fullness!";
// }
return RedirectToAction("Index");
}
[HttpGet]
[Route("/reset")]
public IActionResult Reset()
{
HttpContext.Session.Clear();
return RedirectToAction("Index");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SideBoosterDemo : MonoBehaviour {
public Slider slider;
public float odczepienie;
public GameObject showEndOfFuel;
float timeEngineStart = 20f;
public Rigidbody rb;
float ciag = 0.05005679f;
public float ilosc = 120f;
public ParticleSystem PS;
public ConfigurableJoint CFJ;
bool odczepione = true;
bool leci;
// Update is called once per frame
void Update () {
Odczepienie();
}
void FixedUpdate()
{
Leci();
}
void Leci()
{
timeEngineStart -= Time.deltaTime;
if (timeEngineStart <= 0)
{
leci = true;
}
if (leci && ilosc > 0)
{
rb.AddRelativeForce(Vector3.forward * ciag * Time.deltaTime);
ilosc -= Time.deltaTime;
slider.value = ilosc;
PS.Play();
}
else if(ilosc <= 0)
{
PS.Stop();
leci = false;
}
}
void Odczepienie()
{
if(ilosc <=0 && odczepione)
{
CFJ.breakForce = 0;
StartCoroutine(Moc());
odczepione = false;
}
}
IEnumerator Moc()
{
yield return new WaitForSeconds(.1f);
rb.AddRelativeForce(odczepienie, 0, -0.008f, ForceMode.Impulse);
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Business.Abstract;
using Business.BusinessAspects.Autofac;
using Business.Constants;
using Core.Aspects.Autofac.Logging;
using Core.CrossCuttingConcerns.Logging.Log4Net.Loggers;
using Core.Utilities.Results;
using DataAccess.Abstract;
using Entities.Concrete;
namespace Business.Concrete
{
public class OrderManager:IOrderService
{
private IOrderDal _orderDal;
public OrderManager(IOrderDal orderDal)
{
_orderDal = orderDal;
}
public async Task<IDataResult<List<Order>>> GetAll()
{
return new SuccessDataResult<List<Order>>(await _orderDal.GetAllAsync());
}
[SecuredOperation("admin,user")]
public async Task<IDataResult<long>> GetByIdAdd(Order orders)
{
await _orderDal.AddAsync(orders);
return new SuccessDataResult<long>(orders.Id, Messages.AddedOrder);
}
[LogAspect(typeof(FileLogger))]
[SecuredOperation("admin,user")]
public async Task<IResult> Delete(Order order)
{
await _orderDal.DeleteAsync(order);
return new SuccessResult(Messages.DeletedOrder);
}
[LogAspect(typeof(FileLogger))]
[SecuredOperation("admin,user")]
public async Task<IResult> Update(Order order)
{
await _orderDal.UpdateAsync(order);
return new SuccessResult(Messages.UpdatedOrder);
}
[LogAspect(typeof(FileLogger))]
[SecuredOperation("admin,user")]
public async Task<IResult> Add(Order order)
{
await _orderDal.AddAsync(order);
return new SuccessResult();
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using vmware.samples.common.authentication;
using vmware.samples.common;
using vmware.vapi.bindings;
using vmware.vcenter;
using System.IO;
using System.Web.UI;
namespace Deployer2._0.Models
{
public class VirtualMachineListModel : Page
{
public VirtualMachineListModel()
{
//VirtualMachineRetrieval VMR = new VirtualMachineRetrieval(serverName: "10.0.88.11", userName: "administrator@vsphere.local", password: "Nu140859246");
}
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ViewWeaponCount : MonoBehaviour
{
private LoadWeaponCount _weaponCount = new LoadWeaponCount();
[SerializeField]
private GameObject _attackPanel;
public GameObject AttackPanel { set => _attackPanel = gameObject; get => _attackPanel; }
[SerializeField]
private Text _countFirstWeapon;
[SerializeField]
private Text _countSecondWeapon;
[SerializeField]
private Text _countThreeWeapon;
[SerializeField]
private Text _countFourWeapon;
[SerializeField]
private Text _countFiveWeapon;
private void Start()
{
Load();
_countFirstWeapon.text = PlayerPrefs.GetString("Weapon" + 0);
_countSecondWeapon.text = PlayerPrefs.GetString("Weapon" + 1);
_countThreeWeapon.text= PlayerPrefs.GetString("Weapon" + 2);
_countFourWeapon.text = PlayerPrefs.GetString("Weapon" + 3);
_countFiveWeapon.text = PlayerPrefs.GetString("Weapon" + 4);
}
private void Load()
{
StartCoroutine(_weaponCount.LoadData(PlayerPrefs.GetString("UserLogin"), "Weapon"));
}
//TODO Вынести последующий код в новый класс
[SerializeField]
private Text _hp;
public Text Hp { get => _hp; }
[SerializeField]
private Image _bossImage;
[SerializeField]
private Text _bossName;
[SerializeField]
private Text _rewardExpText;
[SerializeField]
private Text _rewardGoldTooth;
[SerializeField]
private Text _rewardGoldCoin;
private int _rewardTooth;
private int _rewardCoin;
private int _rewardExp;
public int RewardCoin { get => _rewardCoin; }
public delegate void FightEvent();
public event FightEvent YouWin;
public event FightEvent StartFight;
public void LoadImage(LoadBossGameData loadBoss)
{
_bossImage.sprite = loadBoss.BossImage();
_hp.text = loadBoss.Hp;
_bossName.text = loadBoss.BossName.text;
_attackPanel.SetActive(true);
StartFight?.Invoke();
_rewardExpText.text = loadBoss.Exp.ToString();
_rewardGoldTooth.text = loadBoss.GoldTooth.ToString();
_rewardGoldCoin.text = loadBoss.GoldCoin.ToString();
_rewardTooth = loadBoss.GoldCoin;
_rewardExp = Convert.ToInt32(loadBoss.Hp);
}
public void Punch(int damage)
{
int Hp = Convert.ToInt32(_hp.text);
_hp.text = (Hp - damage).ToString();
if (Hp <= 0)
{
YouWin?.Invoke();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using UnityEngine.SceneManagement;
public class StartGame : MonoBehaviour
{
//Holds reference to first frame image
GameObject firstFrame;
//Holds if cutscene has started
public static bool startCutscene = false;
//Component Reference
private VideoPlayer vp;
private void Start()
{
GameObject videoPlayer = GameObject.Find("Video Player");
vp = videoPlayer.GetComponent<VideoPlayer>();
if (Application.platform == RuntimePlatform.WebGLPlayer) {
vp.url = System.IO.Path.Combine(Application.streamingAssetsPath, "StartCutscene.mp4");
}
firstFrame = GameObject.Find("FirstFrame");
}
//If button is clicked
public void startClick()
{
//set StartCutscene to true
startCutscene = true;
//Start coroutine
StartCoroutine(startVideoCor());
}
IEnumerator startVideoCor()
{
yield return new WaitForSeconds(1f);
//Start videoplayer
vp.Play();
yield return new WaitForSeconds(0.6f);
//Turns off first frame image
firstFrame.SetActive(false);
//Waits for video to end
while (vp.isPlaying)
{
yield return new WaitForSeconds(0.1f);
}
//Resets varible
startCutscene = false;
//Loads Level Scene
SceneManager.LoadScene("MainLevel");
}
}
|
using K4AdotNet.BodyTracking;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace K4AdotNet.Samples.Unity
{
using Quaternion = UnityEngine.Quaternion;
public class CharacterAnimator : MonoBehaviour
{
private GameObject _skin;
private void Awake()
{
CreateBones();
_skin = GetComponentInChildren<SkinnedMeshRenderer>()?.gameObject;
}
#region Joints
private IReadOnlyDictionary<JointType, JointData> _joints;
private class JointData
{
public JointData(JointType jointType, Transform transform, Quaternion tposeOrientation, Quaternion kinectTPoseOrientationInverse)
{
Transform = transform;
TPoseOrientation = tposeOrientation;
KinectTPoseOrientationInverse = kinectTPoseOrientationInverse;
}
/// <summary>
/// Joint's transform.
/// </summary>
public Transform Transform { get; }
/// <summary>
/// Joint orientation in T-pose, in coordinate space of a character
/// </summary>
public Quaternion TPoseOrientation { get; }
/// <summary>
/// Inverse quaternion to orientation of Kinect joint in T-pose, in coordinate space of a character
/// </summary>
public Quaternion KinectTPoseOrientationInverse { get; }
}
private void CreateBones()
{
var animator = GetComponent<Animator>();
var bones = JointTypes.All
.ToDictionary(jt => jt, jt => GetJointData(jt, animator));
_joints = bones;
}
private static JointData GetJointData(JointType jointType, Animator animator)
{
var hbb = MapKinectJoint(jointType);
if (hbb == HumanBodyBones.LastBone)
return null;
var transform = animator.GetBoneTransform(hbb);
if (transform == null)
return null;
var rootName = animator.GetBoneTransform(HumanBodyBones.Hips).name;
var tposeOrientation = GetSkeletonBoneRotation(animator, transform.name);
var t = transform;
while (t.name != rootName)
{
t = t.parent;
tposeOrientation = GetSkeletonBoneRotation(animator, t.name) * tposeOrientation;
}
var kinectTPoseOrientationInverse = GetKinectTPoseOrientationInverse(jointType);
return new JointData(jointType, transform, tposeOrientation, kinectTPoseOrientationInverse);
}
private static Quaternion GetSkeletonBoneRotation(Animator animator, string boneName)
=> animator.avatar.humanDescription.skeleton.First(sb => sb.name == boneName).rotation;
private static HumanBodyBones MapKinectJoint(JointType joint)
{
// https://docs.microsoft.com/en-us/azure/Kinect-dk/body-joints
switch (joint)
{
case JointType.Pelvis: return HumanBodyBones.Hips;
case JointType.SpineNaval: return HumanBodyBones.Spine;
case JointType.SpineChest: return HumanBodyBones.Chest;
case JointType.Neck: return HumanBodyBones.Neck;
case JointType.Head: return HumanBodyBones.Head;
case JointType.HipLeft: return HumanBodyBones.LeftUpperLeg;
case JointType.KneeLeft: return HumanBodyBones.LeftLowerLeg;
case JointType.AnkleLeft: return HumanBodyBones.LeftFoot;
case JointType.FootLeft: return HumanBodyBones.LeftToes;
case JointType.HipRight: return HumanBodyBones.RightUpperLeg;
case JointType.KneeRight: return HumanBodyBones.RightLowerLeg;
case JointType.AnkleRight: return HumanBodyBones.RightFoot;
case JointType.FootRight: return HumanBodyBones.RightToes;
case JointType.ClavicleLeft: return HumanBodyBones.LeftShoulder;
case JointType.ShoulderLeft: return HumanBodyBones.LeftUpperArm;
case JointType.ElbowLeft: return HumanBodyBones.LeftLowerArm;
case JointType.WristLeft: return HumanBodyBones.LeftHand;
case JointType.ClavicleRight: return HumanBodyBones.RightShoulder;
case JointType.ShoulderRight: return HumanBodyBones.RightUpperArm;
case JointType.ElbowRight: return HumanBodyBones.RightLowerArm;
case JointType.WristRight: return HumanBodyBones.RightHand;
default: return HumanBodyBones.LastBone;
}
}
private static Quaternion GetKinectTPoseOrientationInverse(JointType jointType)
{
switch (jointType)
{
case JointType.Pelvis:
case JointType.SpineNaval:
case JointType.SpineChest:
case JointType.Neck:
case JointType.Head:
case JointType.HipLeft:
case JointType.KneeLeft:
case JointType.AnkleLeft:
return Quaternion.AngleAxis(-90, Vector3.forward) * Quaternion.AngleAxis(90, Vector3.up);
case JointType.FootLeft:
return Quaternion.AngleAxis(-90, Vector3.forward) * Quaternion.AngleAxis(90, Vector3.up) * Quaternion.AngleAxis(-90, Vector3.right);
case JointType.HipRight:
case JointType.KneeRight:
case JointType.AnkleRight:
return Quaternion.AngleAxis(90, Vector3.forward) * Quaternion.AngleAxis(90, Vector3.up);
case JointType.FootRight:
return Quaternion.AngleAxis(90, Vector3.forward) * Quaternion.AngleAxis(90, Vector3.up) * Quaternion.AngleAxis(-90, Vector3.right);
case JointType.ClavicleLeft:
case JointType.ShoulderLeft:
case JointType.ElbowLeft:
return Quaternion.AngleAxis(180, Vector3.up) * Quaternion.AngleAxis(90, Vector3.right);
case JointType.WristLeft:
return Quaternion.AngleAxis(180, Vector3.up) * Quaternion.AngleAxis(180, Vector3.right);
case JointType.ClavicleRight:
case JointType.ShoulderRight:
case JointType.ElbowRight:
return Quaternion.AngleAxis(180, Vector3.up) * Quaternion.AngleAxis(-90, Vector3.right);
case JointType.WristRight:
return Quaternion.AngleAxis(180, Vector3.up);
default:
return Quaternion.identity;
}
}
#endregion
private void OnEnable()
{
var skeletonProvider = FindObjectOfType<SkeletonProvider>();
if (skeletonProvider != null)
{
skeletonProvider.SkeletonUpdated += SkeletonProvider_SkeletonUpdated;
}
}
private void OnDisable()
{
var skeletonProvider = FindObjectOfType<SkeletonProvider>();
if (skeletonProvider != null)
{
skeletonProvider.SkeletonUpdated -= SkeletonProvider_SkeletonUpdated;
}
}
private void SkeletonProvider_SkeletonUpdated(object sender, SkeletonEventArgs e)
{
if (e.Skeleton != null)
{
ApplySkeleton(e.Skeleton.Value);
_skin?.SetActive(true);
}
else
{
_skin?.SetActive(false);
}
}
private void ApplySkeleton(Skeleton skeleton)
{
var joints = JointTypes.All;
var characterPos = ConvertKinectPos(skeleton.Pelvis.PositionMm);
transform.localPosition = characterPos;
foreach (var joint in joints)
{
var data = _joints[joint];
if (data != null)
{
var orientation = ConvertKinectQ(skeleton[joint].Orientation);
data.Transform.rotation = transform.rotation * orientation * data.KinectTPoseOrientationInverse * data.TPoseOrientation;
}
}
}
private static Vector3 ConvertKinectPos(Float3 pos)
{
// Kinect Y axis points down, so negate Y coordinate
// Scale to convert millimeters to meters
// https://docs.microsoft.com/en-us/azure/Kinect-dk/coordinate-systems
// Other transforms (positioning of the skeleton in the scene, mirroring)
// are handled by properties of ascendant GameObject's
return 0.001f * new Vector3(pos.X, -pos.Y, pos.Z);
}
private static Quaternion ConvertKinectQ(K4AdotNet.Quaternion q)
{
// Convert to Unity coordinates (right-handed Y down to left-handed Y up)
// https://docs.microsoft.com/en-us/azure/Kinect-dk/coordinate-systems
// https://gamedev.stackexchange.com/questions/157946/converting-a-quaternion-in-a-right-to-left-handed-coordinate-system
return new Quaternion(-q.X, q.Y, -q.Z, q.W);
}
}
} |
namespace Tindero.Models
{
public enum SwipeStatus
{
None,
Like,
SuperLike,
Nope,
}
}
|
using System;
using System.Threading.Tasks;
namespace IMDB.Api.Services.Interfaces
{
public interface IMovieService : IEntityService<Entities.Movie>
{
}
}
|
//
// Copyright (c) 2016, MindFusion LLC - Bulgaria.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xamarin.Forms;
using MindFusion.Charting;
using MindFusion.Drawing;
namespace BubbleChart
{
public partial class TestPage : ContentPage
{
public TestPage()
{
InitializeComponent();
// create sample data
bubbleChart.Series = GetSeriesCollection();
// axis titles and ranges
bubbleChart.XAxis.Title = "Average relative annual growth (%)";
bubbleChart.XAxis.MinValue = -1;
bubbleChart.XAxis.MaxValue = 1;
bubbleChart.YAxis.Title = "July 1, 2015 projection";
bubbleChart.YAxis.MinValue = 0;
bubbleChart.YAxis.MaxValue = 100;
// background appearance
bubbleChart.ShowZoomWidgets = true;
bubbleChart.GridType = GridType.Vertical;
bubbleChart.BackgroundColor = Color.Black;
bubbleChart.Theme.GridColor1 = Color.FromRgba(0, 0, 0, 100);
bubbleChart.Theme.GridColor2 = Color.FromRgba(0, 0, 0, 200);
bubbleChart.Theme.LegendBackground = new SolidBrush(Color.Black);
// series colors
bubbleChart.Theme.CommonSeriesFills = new List<Brush>
{
new LinearGradientBrush(Color.Transparent, Colors.Orange, 90),
new LinearGradientBrush(Color.Transparent, Colors.SkyBlue, 90)
};
bubbleChart.Theme.UniformSeriesStroke = bubbleChart.Theme.HighlightStroke =
bubbleChart.Theme.DataLabelsBrush = bubbleChart.Theme.LegendTitleBrush =
bubbleChart.Theme.LegendBorderStroke = bubbleChart.Theme.AxisLabelsBrush =
bubbleChart.Theme.AxisTitleBrush = bubbleChart.Theme.AxisStroke = Brushes.White;
bubbleChart.Theme.HighlightStrokeDashStyle = DashStyle.Dot;
SetupControls();
}
void SetupControls()
{
cbShowScatter.IsToggled = bubbleChart.ShowScatter;
cbShowLabels.IsToggled = true;
cbLegend.IsToggled = true;
}
ObservableCollection<Series> GetSeriesCollection()
{
// bubble chart requires three dimensional data;
// two dimensions for position and one for size
var series3D1 = new PointSeries3D(
new List<Point3D>
{
new Point3D(0.32, 81, 95),
new Point3D(0.39, 66, 78),
new Point3D(0.75, 65, 76),
new Point3D(0.49, 60, 71)
},
new List<string> { "Germany", "France", "UK", "Italy" });
series3D1.Title = ">50 000 000";
var series3D2 = new PointSeries3D(
new List<Point3D>
{
new Point3D(-0.28, 46, 54),
new Point3D(-0.32, 42, 50),
new Point3D(0.05, 38, 45),
new Point3D(-0.4, 19, 23)
},
new List<string> { "Spain", "Ukraine", "Poland", "Romania" });
series3D2.Title = "<50 000 000";
var data = new ObservableCollection<Series>();
data.Add(series3D1);
data.Add(series3D2);
return data;
}
void cbShowScatter_Toggled(object sender, ToggledEventArgs e)
{
bubbleChart.ShowScatter = cbShowScatter.IsToggled;
}
void cbShowLabels_Toggled(object sender, ToggledEventArgs e)
{
if (cbShowLabels.IsToggled)
bubbleChart.ShowDataLabels |= LabelKinds.InnerLabel;
else
bubbleChart.ShowDataLabels ^= LabelKinds.InnerLabel;
bubbleChart.Invalidate();
}
void cbLegend_Toggled(object sender, ToggledEventArgs e)
{
bubbleChart.ShowLegend = cbLegend.IsToggled;
}
}
} |
using Requestrr.WebApi.RequestrrBot;
namespace Requestrr.WebApi.Controllers.Authentication
{
public static class AuthenticationSettingsRepository
{
public static void UpdateAdminAccount(string username, string password)
{
SettingsFile.Write(settings =>
{
settings.Authentication.Username = username;
settings.Authentication.Password = password;
});
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace T6
{
class Program
{
static void Main(string[] args)
{
Nettipoksi pokis = new Nettipoksi("Paskana",5);
Console.WriteLine(pokis.ToString());
Kaiutin kaiutin = new Kaiutin("Hyvä", 3, "Musta");
Console.WriteLine(kaiutin.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Patterns.Factory
{
class CheesePizza : Pizza
{
public CheesePizza() { }
public override void Bake()
{
Console.WriteLine("Поджарка");
}
public override void Box()
{
Console.WriteLine("Упаковка");
}
public override void Cut()
{
Console.WriteLine("Разрезка");
}
public override void Prepare()
{
Console.WriteLine("Готовка");
}
}
}
|
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Runtime.InteropServices;
using Tizen.NUI;
using Tizen.NUI.Components;
using Tizen.NUI.BaseComponents;
using Tizen.NUI.Constants;
namespace Tizen.NUI.MediaHub
{
/// <summary>
/// A shape of PushButton
/// </summary>
public class CustomButton
{
private Button _pushbutton;
private string normalImagePath = CommonResource.GetLocalReosurceURL() + "/Button/btn_bg_25_25_25_95.9.png";
private string focusImagePath = CommonResource.GetLocalReosurceURL() + "/Button/btn_bg_255_255_255_200.9.png";
private string pressImagePath = CommonResource.GetLocalReosurceURL() + "/Button/btn_bg_0_129_198_100.9.png";
/// <summary>
/// Constructor to create new PushButtonSample
/// </summary>
public CustomButton()
{
OnIntialize();
}
/// <summary>
/// PushButton initialisation.
/// </summary>
private void OnIntialize()
{
_pushbutton = new Button();
_pushbutton.Focusable = true;
_pushbutton.ParentOrigin = ParentOrigin.TopLeft;
_pushbutton.PivotPoint = PivotPoint.TopLeft;
_pushbutton.PointSize = DeviceCheck.PointSize8;
_pushbutton.FontFamily = "SamsungOneUI_400";
_pushbutton.TextAlignment = HorizontalAlignment.Center;
if (_pushbutton.HasFocus())
{
_pushbutton.BackgroundImage = focusImagePath;
_pushbutton.TextColor = Color.Black;
}
else
{
_pushbutton.BackgroundImage = normalImagePath;
_pushbutton.TextColor = Color.White;
}
// Change backgroudVisul and Label when focus gained.
_pushbutton.FocusGained += (obj, e) =>
{
_pushbutton.BackgroundImage = focusImagePath;
_pushbutton.TextColor = Color.Black;
};
// Change backgroudVisul and Label when focus lost.
_pushbutton.FocusLost += (obj, e) =>
{
_pushbutton.BackgroundImage = normalImagePath;
_pushbutton.TextColor = Color.White;
};
// Change backgroudVisul when pressed.
_pushbutton.KeyEvent += (obj, ee) =>
{
if ("Return" == ee.Key.KeyPressedName)
{
if (Key.StateType.Down == ee.Key.State)
{
_pushbutton.BackgroundImage = pressImagePath;
Tizen.Log.Fatal("NUI", "Press in pushButton sample!!!!!!!!!!!!!!!!");
}
else if (Key.StateType.Up == ee.Key.State)
{
_pushbutton.BackgroundImage = focusImagePath;
Tizen.Log.Fatal("NUI", "Release in pushButton sample!!!!!!!!!!!!!!!!");
}
}
return false;
};
}
/// <summary>
/// Set the text on the button
/// </summary>
/// <param name="text">the text value of the button</param>
public void SetText(string text)
{
_pushbutton.Text = text;
if (_pushbutton.HasFocus())
{
_pushbutton.BackgroundImage = focusImagePath;
_pushbutton.TextColor = Color.Black;
}
else
{
_pushbutton.BackgroundImage = normalImagePath;
_pushbutton.TextColor = Color.White;
}
}
/// <summary>
/// Get the initialised pushButton
/// </summary>
/// <returns>
/// The pushButton which be create in this class
/// </returns>
public Button GetPushButton()
{
return _pushbutton;
}
/// <summary>
/// Get/Set the text value on the button
/// </summary>
public string Text
{
get
{
return buttonTextLabel;
}
set
{
buttonTextLabel = value;
SetText(buttonTextLabel);
}
}
private string buttonTextLabel;
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace YuME.GM
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class CommandDescriptionAttribute : Attribute
{
public string name;
public string description;
public CommandDescriptionAttribute(string inName, string inDescription)
{
name = inName;
description = inDescription;
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class ArgumentDescriptionAttribute : Attribute
{
public int index;
public Type argumentType;
public string name;
public string description;
public string defaultValue;
public bool isOptional;
public ArgumentDescriptionAttribute(int inIndex, Type inArgumentType, string inName = "",
string inDescription = "", string inDefaultValue = "", bool inIsOptional = false)
{
index = inIndex;
argumentType = inArgumentType;
name = inName;
description = inDescription;
defaultValue = inDefaultValue;
isOptional = inIsOptional;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.AssetImporters;
using UnityEngine;
using UnityEngine.UIElements;
public class Player : MonoBehaviour
{
[SerializeField]
private float speed = 8.0F;
[SerializeField]
private int lives = 3;
[SerializeField]
private float firerate = 0.3F;
private float nextfire = 0.0F;
[SerializeField]
private float powerdown = 5.0f;
[SerializeField]
private float speedRate = 2.0f;
public bool tripleShot = false;
public bool shield = false;
[SerializeField]
private GameObject playerExplosionAnimation;
[SerializeField]
private GameObject playerShield;
private AudioSource laserSound;
[SerializeField]
private GameObject[] engines;
private int hitCount = 0;
public GameObject laserSpawn;
private UIManager uIManager;
private GameManager gameManager;
// Start is called before the first frame update
void Start()
{
//Debug.Log(transform.position.x);
transform.position = new Vector3(0,0,0);
uIManager = GameObject.Find("Canvas").GetComponent<UIManager>();
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
if (uIManager) {
uIManager.updateLives(lives);
}
laserSound = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
Movement();
Shoot();
}
private void Shoot() {
if (tripleShot)
{
if ((Input.GetKeyDown(KeyCode.Space)) || (Input.GetMouseButtonDown(0)))
{
if (Time.time > nextfire)
{
laserSound.Play();
Vector3 laser = new Vector3(transform.position.x, transform.position.y + 0.58f, 0);
Vector3 laserleft = new Vector3(transform.position.x - 0.59f, transform.position.y -0.07f + 0.58f, 0);
Vector3 laserright = new Vector3(transform.position.x + 0.59f, transform.position.y -0.07f + 0.58f, 0);
//Shot Laser Spawn Laser
Instantiate(laserSpawn, laser, Quaternion.identity);
Instantiate(laserSpawn, laserleft, Quaternion.identity);
Instantiate(laserSpawn, laserright, Quaternion.identity);
nextfire = Time.time + firerate;
}
}
}
else {
if ((Input.GetKeyDown(KeyCode.Space)) || (Input.GetMouseButtonDown(0)))
{
if (Time.time > nextfire)
{
laserSound.Play();
Vector3 laser = new Vector3(transform.position.x, transform.position.y + 0.58f, 0);
//Shot Laser Spawn Laser
Instantiate(laserSpawn, laser, Quaternion.identity);
nextfire = Time.time + firerate;
}
}
}
}
public void Damage() {
hitCount++;
lives--;
if (shield) {
lives++;
hitCount--;
shield = false;
playerShield.SetActive(false);
}
uIManager.updateLives(lives);
if (lives < 1) {
Instantiate(playerExplosionAnimation, transform.position, Quaternion.identity);
Destroy(this.gameObject);
hitCount = 0;
gameManager.showTitleScreen();
}
if (hitCount == 1)
{
engines[0].SetActive(true);
}
if (hitCount == 2)
{
engines[1].SetActive(true);
}
}
private void Movement() {
float horizontalInput = Input.GetAxis("Horizontal");
float virticalInput = Input.GetAxis("Vertical");
if (transform.position.x < -8.6f)
{
transform.position = new Vector3(8.5f, transform.position.y, 0);
}
else if (transform.position.x > 8.6f)
{
transform.position = new Vector3(-8.5f, transform.position.y, 0);
}
transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);
if (transform.position.y < -5.1f)
{
transform.position = new Vector3(transform.position.x, 5.0f, 0);
}
else if (transform.position.y > 5.1f)
{
transform.position = new Vector3(transform.position.x, -5.0f, 0);
}
transform.Translate(Vector3.up * Time.deltaTime * speed * virticalInput);
}
public void TripleShotPowerUpOn() {
tripleShot = true;
StartCoroutine(TripleShotPowerDown());
}
public IEnumerator TripleShotPowerDown() {
yield return new WaitForSeconds(powerdown);
tripleShot = false;
}
public void ShieldPowerUp()
{
shield = true;
playerShield.SetActive(true);
}
public void SpeedPowerUpOn()
{
speed = speed * speedRate;
firerate = firerate / speedRate;
StartCoroutine(SpeedPowerDown());
}
public IEnumerator SpeedPowerDown()
{
yield return new WaitForSeconds(powerdown);
speed = speed / speedRate;
firerate = firerate * speedRate;
}
}
|
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Sample.NetCore.Autofac
{
public class ConfigHelper
{
public static T Read<T>(string configKey)
{
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configFile = configurationBuilder.Build();
return configFile.GetSection(configKey).Get<T>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using UnityEngine;
[CreateAssetMenu(menuName = "Pipe/Pipe_Object", fileName = "Pipe_Object")]
public class Single_Pipe_Object : PipeObject
{
//private PipeEntrance A, B;
public bool FlowsThroughAB;
public override bool IsConnected()
{
if (A.isConnected && B.isConnected)
{
FlowsThroughAB = true;
}
else
{
FlowsThroughAB = false;
}
return FlowsThroughAB;
}
public override void AssignPipeNum(int num)
{
A = PipeEntrance.CreateInstance<PipeEntrance>();
B = PipeEntrance.CreateInstance<PipeEntrance>();
A.pipeConnectionNum = -1;
B.pipeConnectionNum = -1;
pipeNum = num;
A.pipenum = num;
B.pipenum = num;
}
public override int IsConnectedTo(int Connection)
{
if (IsConnected())
{
if (Connection == A.pipeConnectionNum)
{
Connection = B.pipeConnectionNum;
}
else
{
Connection = A.pipeConnectionNum;
}
return Connection;
}
return -1;
}
}
|
using SQLite.Net.Async;
namespace AnimeViewer.Services
{
/// <summary>
/// Handles platform specific database connection
/// </summary>
public interface IDatabaseService
{
/// <summary>
/// Gets a connection to the database
/// </summary>
/// <returns></returns>
SQLiteAsyncConnection GetConnection();
/// <summary>
/// Gets the filepath of the database, where its stored
/// </summary>
/// <returns></returns>
string GetDatabaseFilePath();
}
} |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace iied_json_test
{
[DataContract, KnownType(typeof(ProfileStatus)), KnownType(typeof(Status)), KnownType(typeof(List<ProfileStatus>))]
public class Profile
: BaseModel
{
[DataMember]
public string PhoneNumber { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string Status { get; set; }
[DataMember]
public string Role { get; set; }
[DataMember]
public DateTime? HireDate { get; set; }
[DataMember]
public DateTime? BirthDate { get; set; }
[DataMember]
public string Location { get; set; }
[DataMember]
public string Twitter { get; set; }
[DataMember]
public virtual List<ProfileStatus> Statuses { get; set; }
public List<ProfileStatus> RecentStatuses
{
get { return (Statuses == null) ? null : Statuses.OrderByDescending(s => s.SetOn).Take(3).ToList(); }
private set { ;}
}
}
}
|
using DatabaseConnection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace EPATEC.Controllers
{
[RoutePrefix("Categoria")]
public class CategoriaController : ApiController
{
[Route("{id}")]
[HttpGet]
public IHttpActionResult getCategoria(string id)
{
var product = Connection.Instance.get_Categoria(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[Route("~/getAllCategories")]
[HttpGet]
public IHttpActionResult getAllCategories()
{
var products = Connection.Instance.get_AllCategoria();
return Ok(products);
}
[Route("{id}/{campo}/{newValue}")]
[HttpPut]
public IHttpActionResult PutCategoria(string id, string campo, string newValue)
{
System.Diagnostics.Debug.WriteLine(id);
System.Diagnostics.Debug.WriteLine(campo);
System.Diagnostics.Debug.WriteLine(newValue);
if (campo == "Descripción")
{
Connection.Instance.update_Categoria_Descripcion(id, newValue);
}
return Ok();
}
[HttpPost]
[Route("")]
public IHttpActionResult postCategoria([FromBody]Models.Categoria categoria)
{
Connection.Instance.crear_Categoria(categoria);
return Ok();
}
[Route("{id}")]
[HttpDelete]
public IHttpActionResult deleteCategoria(string id)
{
Connection.Instance.eliminar_Categoria(id);
return Ok();
}
}
}
|
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
using Whale.Shared.Models.GroupMessage;
using Whale.Shared.Models.DirectMessage;
namespace Whale.SignalR.Hubs
{
public sealed class ChatHub : Hub
{
[HubMethodName("JoinGroup")]
public async Task JoinAsync(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("JoinedGroup", Context.ConnectionId);
}
[HubMethodName("LeaveGroup")]
public async Task LeaveAsync(string groupName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("LeftGroup", Context.ConnectionId);
}
[HubMethodName("NewMessageReceived")]
public async Task SendMessageAsync(DirectMessageDTO directMessageDTO)
{
await Clients.Group(directMessageDTO.ContactId.ToString()).SendAsync("NewMessageReceived", directMessageDTO);
}
[HubMethodName("NewGroupMessageReceived")]
public async Task SendGroupMessageAsync(GroupMessageDTO groupMessageDTO)
{
await Clients.Group(groupMessageDTO.GroupId.ToString()).SendAsync("NewGroupMessageReceived", groupMessageDTO);
}
public async Task DisconnectAsync(string groupName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync(Context.ConnectionId + " jeft groupS");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class CannonCylinder : MonoBehaviour
{
private float length = 1f;
public void CannonCylinderPosition(float theta, float phi, float h){ //
gameObject.transform.position = new Vector3(length * (float)Math.Sin(theta * (float)Math.PI/180) * (float)Math.Cos(phi * (float)Math.PI/180), h + length * (float)Math.Cos(theta * (float)Math.PI/180), length * (float)Math.Sin(theta * (float)Math.PI/180) * (float)Math.Sin(phi * (float)Math.PI/180));
}
public void CannonCylinderOrientation(float theta, float phi){ //
gameObject.transform.eulerAngles = new Vector3(0, -phi, -theta);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CinematicEffects;
using UnityStandardAssets.ImageEffects;
public class Graficas : MonoBehaviour {
public string antiAliasing;
public string ambientOclusion;
public int motionBlur;
public int bloom;
public int dephOfFlied;
public int globalFog;
public int volumetricImage;
public string sunShaft;
// Use this for initialization
void Start ()
{
antiAliasing = PlayerPrefs.GetString("antiAliasing");
ambientOclusion = PlayerPrefs.GetString("ambientOclusion");
motionBlur = PlayerPrefs.GetInt("motionBlur");
bloom = PlayerPrefs.GetInt("bloom");
dephOfFlied = PlayerPrefs.GetInt("dephOfFlied");
globalFog = PlayerPrefs.GetInt("globalFog");
volumetricImage = PlayerPrefs.GetInt("volumetricImage");
sunShaft = PlayerPrefs.GetString("sunShaft");
if(motionBlur == 1)
{
GetComponent<UnityStandardAssets.CinematicEffects.MotionBlur>().enabled = true;
}else
{
GetComponent<UnityStandardAssets.CinematicEffects.MotionBlur>().enabled = false;
}
if(bloom == 1)
{
GetComponent<UnityStandardAssets.CinematicEffects.Bloom>().enabled = true;
}else
{
GetComponent<UnityStandardAssets.CinematicEffects.Bloom>().enabled = false;
}
if(dephOfFlied == 1)
{
GetComponent<UnityStandardAssets.CinematicEffects.DepthOfField>().enabled = true;
}else
{
GetComponent<UnityStandardAssets.CinematicEffects.DepthOfField>().enabled = false;
}
if(globalFog == 1)
{
GetComponent<GlobalFog>().enabled = true;
}else
{
GetComponent<GlobalFog>().enabled = false;
}
if(volumetricImage == 1)
{
GetComponent<HxVolumetricCamera>().enabled = true;
}else
{
GetComponent<HxVolumetricCamera>().enabled = false;
}
/*if(sunShaft == "LOW")
{
GetComponent<SunShafts>().SunShaftsResolution.Low;
}else if(sunShaft == "NORMAL")
{
GetComponent<SunShafts>().SunShaftsResolution.Normal;
}else if(sunShaft == "HIGH")
{
GetComponent<SunShafts>().SunShaftsResolution.High;
}*/
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace bt.Admin
{
public partial class CTsp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getCloai();
getCncc();
}
}
protected void btnLuu_Click(object sender, EventArgs e)
{
banhang2Entities db = new banhang2Entities();
sanpham obj = new sanpham();
obj.tensp = txtTen.Text;
obj.mota = txtmota.Text;
obj.chitiet = txtct.Text;
obj.giaban = float.Parse(txtgb.Text);
obj.giakm = float.Parse(txtgiakm.Text);
obj.maloai = Convert.ToInt32( cmbloai.SelectedValue);
obj.mancc = Convert.ToInt32(cmbncc.SelectedValue);
db.sanpham.Add(obj);
db.SaveChanges();
Response.Redirect("Sanpham.aspx");
}
public void getCloai()
{
banhang2Entities db = new banhang2Entities();
List<loaisp> list = db.loaisp.ToList();
cmbloai.DataSource = list;
cmbloai.DataValueField = "maloai";
cmbloai.DataTextField = "tenloai";
cmbloai.DataBind();
}
public void getCncc()
{
banhang2Entities db = new banhang2Entities();
List<ncc> obj = db.ncc.ToList();
cmbncc.DataSource = obj;
cmbncc.DataValueField = "mancc";
cmbncc.DataTextField = "tenncc";
cmbncc.DataBind();
}
}
} |
using UnityEngine;
public class PlayerJumpState : State<PlayerControl>
{
private static PlayerJumpState _instance;
public static PlayerJumpState Instance
{
get
{
if (_instance == null)
_instance = new PlayerJumpState();
return _instance;
}
}
private PlayerJumpState()
{
}
public override void Enter()
{
owner.ctrl.audioManager.Play(owner.ctrl.audioManager.jump, owner.audioSource);
owner.rgd2D.AddForce(owner.playerInfo.jumpForce * Vector2.up);
owner.isJump = true;
owner.isGrounded = false;
}
public override void Execute()
{
#region check Grounded
owner.CheckGrounded();
owner.CheckLadderTopForLadder();
if(owner.isGrounded)
{
owner.StateMachine.ChangeState(PlayerIdleState.Instance);
}
#endregion
#region check ladder
owner.CheckLadderTriggleForJumpState();
if(owner.isClimb)
{
owner.StateMachine.ChangeState(PlayerClimbState.Instance);
}
#endregion
}
public override void Exit()
{
//Clear the rest of force
owner.rgd2D.Sleep();
owner.isJump = false;
}
}
|
using Terraria;
using Terraria.GameInput;
using Terraria.ModLoader;
namespace MechScope
{
internal class ControlPlayer : ModPlayer
{
public override void ProcessTriggers(TriggersSet triggersSet)
{
if (Main.netMode == 0)
{
if (MechScope.keyStep.JustPressed)
SuspendableWireManager.Resume();
if (MechScope.keyToggle.JustPressed)
SuspendableWireManager.Active = !SuspendableWireManager.Active;
if (MechScope.keyAutoStep.JustPressed)
AutoStepWorld.Active = !AutoStepWorld.Active;
if (MechScope.keySettings.JustPressed)
MechScope.settingsUI.Visible = !MechScope.settingsUI.Visible;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation.Results;
namespace DDDSouthWest.Website.Features.Admin.Account.ManageEvents
{
public class ManageEventsViewModel
{
public ManageEventsViewModel()
{
Errors = new List<ValidationFailure>();
}
public int Id { get; set; }
public string EventName { get; set; }
public string EventFilename { get; set; }
public DateTime EventDate { get; set; }
public IList<ValidationFailure> Errors { get; set; }
public bool HasErrors => Errors.Any();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.MaximumElement
{
class MaximumElement
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
Stack<int> numbers = new Stack<int>();
Stack<int> maxNumbers = new Stack<int>();
int maxValues = int.MinValue;
for (int i = 0; i < n; i++)
{
int[] queries = Console.ReadLine().Split().Select(int.Parse).ToArray();
if (queries[0] == 1)
{
numbers.Push(queries[1]);
if (maxValues < queries[1])
{
maxValues = queries[1];
maxNumbers.Push(queries[1]);
}
}
else if (queries[0] == 2)
{
if (numbers.Pop() == maxValues)
{
maxNumbers.Pop();
if (maxNumbers.Count != 0)
{
maxValues = maxNumbers.Peek();
}
else
{
maxValues = int.MinValue;
}
}
}
else
{
Console.WriteLine(maxValues);
}
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Configuration;
using Microsoft.Bot.Connector.Authentication;
namespace Microsoft.Bot.Configuration
{
/// <summary>
/// A <see cref="ICredentialProvider">credential provider</see> which provides credentials
/// based on an <see cref="EndpointService">endpoint</see> from a <c>.bot</c> configuration file.
/// </summary>
/// <seealso cref="BotConfiguration"/>
public sealed class BotConfigurationEndpointServiceCredentialProvider : ICredentialProvider
{
public static readonly string DefaultEndpointName = "development";
private readonly EndpointService _endpointService;
/// <summary>
/// Initializes a new instance of the <see cref="BotConfigurationEndpointServiceCredentialProvider"/> class
/// which exposes the credentials from the given <paramref name="endpointService">endpoint</paramref>.
/// </summary>
/// <param name="endpointService">The <see cref="EndpointService"/> instance containing the credentials that should be used.</param>
public BotConfigurationEndpointServiceCredentialProvider(EndpointService endpointService)
{
_endpointService = endpointService ?? throw new ArgumentNullException(nameof(endpointService));
}
/// <summary>
/// Given an existing <see cref="BotConfiguration"/> instance, finds the endpoint service that corresponds to the
/// <paramref name="endpointName">given environment</paramref>.
/// </summary>
/// <param name="botConfiguration">
/// An <see cref="BotConfiguration"/> instance containing one or more <see cref="EndpointService">endpoint services</see>.</param>
/// <param name="endpointName">
/// Optional environment name that should be used to locate the correct <see cref="EndpointService">endpoint</see>
/// from the configuration file based on its <c>name</c>.
/// </param>
/// <returns>
/// An instance of a <see cref="BotConfigurationEndpointServiceCredentialProvider"/> loaded from the
/// <paramref name="botConfiguration">specified <see cref="BotConfiguration"/></paramref> populated
/// with the <see cref="EndpointService">endpoint</see> resolved based on the <paramref name="endpointName"/>.
/// </returns>
public static BotConfigurationEndpointServiceCredentialProvider FromConfiguration(BotConfiguration botConfiguration, string endpointName = null)
{
if (botConfiguration == null)
{
throw new ArgumentNullException(nameof(botConfiguration));
}
return new BotConfigurationEndpointServiceCredentialProvider(FindEndpointServiceForEnvironment(botConfiguration, endpointName ?? DefaultEndpointName));
}
/// <summary>
/// Attempts to load and create an <see cref="BotConfigurationEndpointServiceCredentialProvider"/>
/// by searching the <paramref name="botFileDirectory">specified directory</see> for a <c>.bot</c> configuration file.
/// </summary>
/// <param name="botFileDirectory">
/// The directory to load the .bot file from
/// </param>
/// <param name="botFileSecretKey">
/// Optional key that should be used to decrypt secrets inside the configuration file.
/// </param>
/// <param name="endpointName">
/// Optional environment name that should be used to locate the correct <see cref="EndpointService">endpoint</see>
/// from the configuration file based on its <c>name</c>.
/// </param>
/// <remarks>
/// If no value is provided for <paramref name="botFileSecretKey"/>, it is assumed that the contents of
/// the configuration file are not encrypted.
///
/// If no value is provided for <paramref name="endpointName"/>, it will use
/// <see cref="DefaultEndpointName">the default environment</see>.
/// </remarks>
/// <returns>
/// An instance of a <see cref="BotConfigurationEndpointServiceCredentialProvider"/> populated with the
/// <see cref="EndpointService">endpoint</see> resolved based on the <paramref name="endpointName"/>.
/// </returns>
/// <seealso cref="BotConfiguration"/>
public static BotConfigurationEndpointServiceCredentialProvider LoadFromFolder(string botFileDirectory, string botFileSecretKey = null, string endpointName = null) =>
LoadBotConfiguration(() => BotConfiguration.LoadFromFolder(botFileDirectory, botFileSecretKey), endpointName);
/// <summary>
/// Attempts to load and create an <see cref="BotConfigurationEndpointServiceCredentialProvider"/> from the
/// <paramref name="botConfigurationFilePath">specified <c>.bot</c> configuration file</paramref>.
/// </summary>
/// <param name="botConfigurationFilePath">
/// A path to the .bot configuration file that should be loaded.
/// </param>
/// <param name="botFileSecretKey">
/// Optional key that should be used to decrypt secrets inside the configuration file.
/// </param>
/// <param name="endpointName">
/// Optional environment name that should be used to locate the correct <see cref="EndpointService">endpoint</see>
/// from the configuration file based on its <c>name</c>.
/// </param>
/// <remarks>
/// If no value is provided for <paramref name="botFileSecretKey"/>, it is assumed that the contents of
/// the configuration file are not encrypted.
///
/// If no value is provided for <paramref name="endpointName"/>, it will use
/// <see cref="DefaultEndpointName">the default environment</see>.
/// </remarks>
/// <returns>
/// An instance of a <see cref="BotConfigurationEndpointServiceCredentialProvider"/> loaded from the
/// <paramref name="botConfigurationFilePath">specified <c>.bot</c> configuration file</paramref> populated
/// with the <see cref="EndpointService">endpoint</see> resolved based on the <paramref name="endpointName"/>.
/// </returns>
/// <seealso cref="BotConfiguration"/>
public static BotConfigurationEndpointServiceCredentialProvider Load(string botConfigurationFilePath, string botFileSecretKey = null, string endpointName = null)
{
if (string.IsNullOrEmpty(botConfigurationFilePath))
{
throw new ArgumentException("Expected a non-null/empty value.", nameof(botConfigurationFilePath));
}
return LoadBotConfiguration(() => BotConfiguration.Load(botConfigurationFilePath, botFileSecretKey), endpointName);
}
/// <inheritdoc />
public Task<string> GetAppPasswordAsync(string appId)
{
if (appId != _endpointService.AppId)
{
return Task.FromResult(default(string));
}
return Task.FromResult(_endpointService.AppPassword);
}
/// <inheritdoc />
public Task<bool> IsAuthenticationDisabledAsync() =>
Task.FromResult(
string.IsNullOrWhiteSpace(_endpointService.AppId)
&&
_endpointService.Name?.Equals("development", StringComparison.InvariantCultureIgnoreCase) == true);
/// <inheritdoc />
public Task<bool> IsValidAppIdAsync(string appId) => Task.FromResult(appId == _endpointService.AppId);
private static BotConfigurationEndpointServiceCredentialProvider LoadBotConfiguration(Func<BotConfiguration> loader, string endpointName)
{
var botConfiguration = default(BotConfiguration);
try
{
botConfiguration = loader();
}
catch (Exception exception)
{
throw new Exception(
@"Error reading .bot file; check inner exception for more details. Please ensure you have valid botFilePath and botFileSecret set for your environment.
- You can find the botFilePath and botFileSecret in the Azure App Service application settings.
- If you are running this bot locally, consider adding a appsettings.json file with botFilePath and botFileSecret.
- See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.
",
exception);
}
return new BotConfigurationEndpointServiceCredentialProvider(FindEndpointServiceForEnvironment(botConfiguration, endpointName));
}
private static EndpointService FindEndpointServiceForEnvironment(BotConfiguration botConfiguration, string endpointName)
{
endpointName = endpointName ?? DefaultEndpointName;
var endpointServiceForEnvironment = botConfiguration.Services.OfType<EndpointService>().FirstOrDefault(s => s.Name.Equals(endpointName, StringComparison.InvariantCultureIgnoreCase));
if (endpointServiceForEnvironment == null)
{
throw new InvalidOperationException($"The .bot file does not appear to contain an endpoint service with the name \"{endpointName}\".");
}
return endpointServiceForEnvironment;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Booster : MonoBehaviour {
public Rigidbody ziemia;
public Rigidbody booster;
public FixedJoint FJ;
public Vector3 miejsceWybuchu;
[SerializeField]
private float thrust = 5000f;
public float force = 100.0f;
public float radius = 5.0f;
public float upwardModifier = 0.0f;
public ForceMode forceMode;
public bool odczepione = true;
public ParticleSystem PS;
public ParticleSystem dym;
// Use this for initialization
void Start () {
booster.drag = 0.1f;
odczepione = true;
PS.Stop();
}
// Update is called once per frame
void Update () {
Ogien();
ZwiekszanieSieAtmosfery();
}
void FixedUpdate()
{
Odczepienie();
}
private void Ogien()
{
//if (nieOdczepione)
// {
if (Input.GetKey(KeyCode.X)&&(odczepione))
{
booster.AddRelativeForce(Vector3.forward * thrust * Time.deltaTime);
PS.Play();
}
else
{
PS.Stop();
}
//}
}
void Odczepienie() //dzieki temu prostemu kodowi boostery sie odczepiaja
{
if (Input.GetKey(KeyCode.K)&&(odczepione))
{
// rb.AddExplosionForce(10.0f, miejsceWybuchu, 5 .0f, 2.0f );
FJ.breakForce = 0;
odczepione = false;
//// foreach(Collider col in Physics.OverlapSphere(transform.position, radius))
// // {
// if(GameObject.FindWithTag("Rakieta"))
// {
// booster.AddExplosionForce(force, transform.position, radius, upwardModifier, forceMode);
// }
// // }
}
}
void ZwiekszanieSieAtmosfery()
{
float wysokosc = Vector3.Distance(booster.transform.position, ziemia.transform.position) - 12720;
// Debug.Log("wysokosc boostera" + wysokosc);
if (wysokosc <= 1500) booster.drag = 0.1f;
else if ((wysokosc >1500) && (wysokosc < 2000)) booster.drag = 0.05f;
else booster.drag = 0f;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp3
{
public class Kisi
{
public string Isim { get; set; }
public string Adres { get; set; }
public int Tel { get; set; }
public string ePosta { get; set; }
public string Uyruk { get; set; }
public string DYeri { get; set; }
public string DTarihi { get; set; }
public string MDurumu { get; set; }
public string IlgiAlanı { get; set; }
public Liste Egtim_Staj { get; set; }
public Egitim egt { get; set; }
public Staj stj { get; set; }
}
}
|
namespace WebApplication.Models.Enums
{
public enum AuditingState
{
Wait = 10,
Allow = 20,
Reject = 30
}
} |
using System;
namespace LAB_2_1
{
class Program
{
static void Main(string[] args)
{
string tmp;
tmp = Console.ReadLine();
Int64 a = 0, b = 0;
for(int i = 0; i < tmp.Length; i++)
{
if(tmp[i] == ' ')
{
a = Convert.ToInt64(tmp.Substring(0,i));
b = Convert.ToInt64(tmp.Substring(i));
}
}
int ans = 0;
for(Int64 i = a; i <= b; i++)
{
Int64 T = i;
while (T % 2 == 0) {
T /= 2;
ans++;
}
}
Console.WriteLine(ans);
}
}
}
|
using System;
using Microsoft.Pex.Framework;
using QuickGraph;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickGraphTest.Factories
{
public static partial class BinaryHeapFactory
{
/*[PexFactoryMethod(typeof(QuickGraph.BinaryHeap<int, int>))]
public static BinaryHeap<int, int> CreateBinaryHeapGeneral(int capacity, int[] priorities, int[] values)
{
PexAssume.IsTrue( priorities.Length == values.Length);
var bh = new BinaryHeap<int, int>(capacity, Comparer<int>.Default.Compare);
for (int i = 0; i < priorities.Length; i++)
{
bh.Add(priorities[i], values[i]);
}
return bh;
}*/
/*[PexFactoryMethod(typeof(QuickGraph.BinaryHeap<int, int>))]
public static BinaryHeap<int, int> CreateBinaryHeapKeyValPair([PexAssumeNotNull]KeyValuePair<int,int>[] pairs, int capacity)
{
PexAssume.IsTrue(capacity < 11 && capacity > 0 && pairs.Length <= capacity);
//PexAssume.TrueForAll(0, pairs.Length, _i => pairs[_i].Key > -11 && pairs[_i].Key < 11 && pairs[_i].Value > -11 && pairs[_i].Value < 11);
PexAssume.TrueForAll(0, pairs.Length, _i => pairs[_i].Key > -101 && pairs[_i].Key < 101);
var bh = new BinaryHeap<int, int>(capacity, Comparer<int>.Default.Compare);
foreach (var pair in pairs)
{
bh.Add(pair.Key, pair.Value);
}
return bh;
}*/
[PexFactoryMethod(typeof(Tuple<BinaryHeap<int, int>, BinaryHeap<int, int>>))]
public static Tuple<BinaryHeap<int, int>, BinaryHeap<int, int>> CreateBinaryHeapKeyValPair([PexAssumeNotNull]KeyValuePair<int, int>[] pairs, int capacity)
{
PexAssume.IsTrue(capacity < 11 && capacity > 0);
PexAssume.TrueForAll(0, pairs.Length, _i => pairs[_i].Key > -11 && pairs[_i].Key < 11);
var bh1 = new BinaryHeap<int, int>(capacity, Comparer<int>.Default.Compare);
var bh2 = new BinaryHeap<int, int>(capacity, Comparer<int>.Default.Compare);
foreach (var pair in pairs)
{
bh1.Add(pair.Key, pair.Value);
bh2.Add(pair.Key, pair.Value);
}
var ret = new Tuple<BinaryHeap<int, int>, BinaryHeap<int, int>>(bh1, bh2);
return ret;
}
}
}
|
using System.Net.Http;
namespace MCCForms
{
public partial class HttpHelper
{
static HttpHelper _instance;
HttpClient _httpClient;
private HttpHelper(){
_httpClient = new HttpClient (new ModernHttpClient.NativeMessageHandler(false, AppConfigConstants.IsCertificatePinningEnabled));
}
public static HttpHelper Instance {
get {
if (_instance == null) {
_instance = new HttpHelper ();
}
return _instance;
}
}
//TODO: For OpenID Connect Application requests you have to add the access token to the request
//httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Bearer", accessToken);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchedulerTask
{
public interface IOperation
{
TimeSpan GetDuration();
void SetOperationInPlan(DateTime real_start_time, DateTime real_end_time, SingleEquipment real_equipment_id);
bool IsEnd(DateTime time_);
bool IsEnabled();
bool PreviousOperationIsEnd(DateTime time_);
IEquipment GetEquipment();
Party GetParty();
Decision GetDecision();
}
/// <summary>
/// операция
/// </summary>
public class Operation : IOperation
{
private int id;//id операции
private string name;//name операции
private TimeSpan duration;//длительность операции
private List<IOperation> PreviousOperations;//список предыдущих операций
private bool enable;//поставлена ли оперция в расписание
private IEquipment equipment;//обордование или группа оборудований, на котором может выполняться операция
private Decision decision = null;//решение,создается,когда операция ставится в расписание
private Party parent_party;//ссылка на партию,в которой состоит данная операция
public Operation(int id_,string name_,TimeSpan duration_, List<IOperation> Prev,IEquipment equipment_,Party party)
{
id = id_;
name = name_;
duration = duration_;
PreviousOperations = new List<IOperation>();
foreach (IOperation prev in Prev)
{
PreviousOperations.Add(prev);
}
enable = false;
equipment = equipment_;
parent_party = party;
}
/// <summary>
/// получить id операции
/// </summary>
public int GetID()
{
return id;
}
/// <summary>
/// получить имя операции
/// </summary>
public string GetName()
{
return name;
}
/// <summary>
/// получить длительность операции
/// </summary>
public TimeSpan GetDuration()
{
return duration;
}
/// <summary>
/// поставить операцию в расписание и создать решение
/// </summary>
public void SetOperationInPlan(DateTime real_start_time, DateTime real_end_time, SingleEquipment real_equipment_id)
{
enable = true;
decision= new Decision (real_start_time, real_end_time, real_equipment_id, this);
}
/// <summary>
/// поставлена ли операция в расписание
/// </summary>
public bool IsEnabled()
{
return enable;
}
/// <summary>
/// выполнилась ли операция к тому времени,которое подано на вход
/// </summary>
public bool IsEnd(DateTime time_)
{
bool end = false;
if (this.IsEnabled())
{
if (time_>= decision.GetEndTime())
{
end = true;
}
}
return end;
}
/// <summary>
/// выполнены ли предыдущие операции
/// </summary>
public bool PreviousOperationIsEnd(DateTime time_)
{
bool flag = true;
foreach (IOperation prev in PreviousOperations)
{
if (prev.IsEnd(time_) == false)
{
flag = false;
break;
}
}
return flag;
}
/// <summary>
/// получить оборудование или группу оборудований, на котором может выполняться операция
/// </summary>
public IEquipment GetEquipment()
{
return equipment;
}
/// <summary>
/// получить ссылку на партию,в которой состоит данная операция
/// </summary>
public Party GetParty()
{
return parent_party;
}
/// <summary>
/// получить ссылку решение для данной операции
/// </summary>
public Decision GetDecision()
{
return decision;
}
}
}
|
// <copyright file="NetXteaTest.cs" company="Microsoft">Copyright © Microsoft 2010</copyright>
using System;
using Lidgren.Network;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lidgren.Network
{
[PexClass(typeof(NetXtea))]
[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[TestClass]
public partial class NetXteaTest
{
[PexMethod]
public int BlockSizeGet([PexAssumeUnderTest]NetXtea target)
{
int result = target.BlockSize;
return result;
}
[PexMethod]
public NetXtea Constructor(byte[] key, int rounds)
{
NetXtea target = new NetXtea(key, rounds);
return target;
}
[PexMethod]
public NetXtea Constructor01(byte[] key)
{
NetXtea target = new NetXtea(key);
return target;
}
[PexMethod]
public NetXtea Constructor02(string key)
{
NetXtea target = new NetXtea(key);
return target;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using CsvHelper;
using ImageMagick;
namespace ImageLibTest
{
class Program
{
static void Main(string[] args)
{
var summaries = new List<Summary>();
var testers = new List<LibTester>
{
new ManagedCudaLibTester(),
new ImageMagickLibTester(false),
new ImageMagickLibTester(true),
//new GraphicsMagickLibTester(),
//new GdiLibTester(),
//new ImageProcessorLibTester(),
//new ImageResizerLibTester(),
//new EmguLibTester(),
};
foreach (var t in testers)
{
var summary = t.DoTests(@"C:\temp\apod\");
summaries.Add(summary);
}
using (var sw = new StreamWriter("summary.csv"))
using (var csv = new CsvWriter(sw))
{
csv.WriteRecords(summaries);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Constructor_Example
{
public class Student
{
private string lastname, firstname, middlename;
private int age;
private int yearLevel;
private string course;
public Student()
{
}
//Constructor Overloading
public Student(string lastname, string firstname, string middlename, int age, int yearLevel, string course)
{
this.lastname = lastname;
this.firstname = firstname;
this.middlename = middlename;
this.age = age;
this.yearLevel = yearLevel;
this.course = course;
}
~Student()
{
Console.WriteLine("The object of Student is destroyed.");
}
public string Lastname { get => lastname; set => lastname = value; }
public string Firstname { get => firstname; set => firstname = value; }
public string Middlename { get => middlename; set => middlename = value; }
public int Age { get => age; set => age = value; }
public int YearLevel { get => yearLevel; set => yearLevel = value; }
public string Course { get => course; set => course = value; }
}
}
|
using BiPolarTowerDefence.Entities;
using BiPolarTowerDefence.Utilities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace BiPolarTowerDefence.Screens
{
public class GameplayScreen : BaseScreen
{
private Level level;
public bool PauseGame { get; private set; } = false;
public override void Load()
{
level = new Level(Game1.Game,"Level1",Game1.BOARD_HEIGHT, Game1.BOARD_WIDHT);
}
public override void Update(GameTime gameTime)
{
if (Input.Instance().PressedKey(Keys.Escape))
{
PauseGame = !PauseGame;
}
if (!PauseGame)
{
level.Update(gameTime);
}
}
public override void Draw(GameTime gameTime)
{
level.Draw(gameTime);
if (PauseGame)
{
//TODO draw overlay
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Zbor
{
//Klasa od internet za polnenje na keliite so bukvi vo gridot i kreiranje mapa na boi od RGB
public class FadeLabel : Label
{
private Color _fadeFromBackColor = DefaultBackColor;
public Color FadeFromBackColor
{
get { return _fadeFromBackColor; }
set
{
_fadeFromBackColor = value;
BackColor = value;
}
}
private Color _fadeFromForeColor = DefaultForeColor;
public Color FadeFromForeColor
{
get { return _fadeFromForeColor; }
set
{
_fadeFromForeColor = value;
ForeColor = value;
}
}
private Color _fadeToForeColor = DefaultForeColor;
public Color FadeToForeColor
{
get { return _fadeToForeColor; }
set
{
_fadeToForeColor = value;
}
}
private Color _fadeToBackColor = DefaultBackColor;
public Color FadeToBackColor
{
get { return _fadeToBackColor; }
set
{
_fadeToBackColor = value;
}
}
private int _fadeDuration = 2000;
public int FadeDuration
{
get { return _fadeDuration; }
set
{
_fadeDuration = value;
}
}
private int _maxTransitions = 64;
public int MaxTransitions
{
get { return _maxTransitions; }
set
{
_maxTransitions = value;
}
}
private int FadeTimerInterval
{
get
{
int interval = (int)((float)FadeDuration / (float)MaxTransitions);
return interval == 0 ? 1 : interval;
}
}
private Timer FadeTimer = new Timer();
private int CurrentTransition = 0;
private delegate void PerformActivityCallback();
private Color[] BackColorMap;
private Color[] ForeColorMap;
public FadeLabel()
: base()
{
FadeFromBackColor = Label.DefaultBackColor;
ForeColor = Label.DefaultBackColor;
FadeTimer.Tick += new EventHandler(fadeTimer_Tick);
}
void fadeTimer_Tick(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
PerformActivityCallback d = new PerformActivityCallback(FadeControl);
this.Invoke(d);
}
else
{
FadeControl();
}
}
private void FadeControl()
{
BackColor = BackColorMap[CurrentTransition];
ForeColor = ForeColorMap[CurrentTransition];
CurrentTransition++;
if (CurrentTransition == MaxTransitions)
{
FadeTimer.Stop();
}
}
public void Fade()
{
CreateColorMaps();
CurrentTransition = 0;
FadeTimer.Interval = FadeTimerInterval;
FadeTimer.Start();
}
public void StopFading()
{
FadeTimer.Stop();
}
public void Reset()
{
ForeColor = FadeFromForeColor;
BackColor = FadeFromBackColor;
}
private void CreateColorMaps()
{
float aDelta, rDelta, gDelta, bDelta;
int a, r, g, b;
BackColorMap = new Color[MaxTransitions];
ForeColorMap = new Color[MaxTransitions];
aDelta = (FadeToBackColor.A - FadeFromBackColor.A) / (float)MaxTransitions;
rDelta = (FadeToBackColor.R - FadeFromBackColor.R) / (float)MaxTransitions;
gDelta = (FadeToBackColor.G - FadeFromBackColor.G) / (float)MaxTransitions;
bDelta = (FadeToBackColor.B - FadeFromBackColor.B) / (float)MaxTransitions;
BackColorMap[0] = FadeFromBackColor;
for (int i = 1; i < MaxTransitions; i++)
{
a = (int)(BackColorMap[i - 1].A + aDelta);
r = (int)(BackColorMap[i - 1].R + rDelta);
g = (int)(BackColorMap[i - 1].G + gDelta);
b = (int)(BackColorMap[i - 1].B + bDelta);
if (a < 0 || a > 255) a = FadeToBackColor.A;
if (r < 0 || r > 255) r = FadeToBackColor.R;
if (g < 0 || g > 255) g = FadeToBackColor.G;
if (b < 0 || b > 255) b = FadeToBackColor.B;
BackColorMap[i] = Color.FromArgb(a, r, g, b);
}
aDelta = (FadeToForeColor.A - FadeFromForeColor.A) / (float)MaxTransitions;
rDelta = (FadeToForeColor.R - FadeFromForeColor.R) / (float)MaxTransitions;
gDelta = (FadeToForeColor.G - FadeFromForeColor.G) / (float)MaxTransitions;
bDelta = (FadeToForeColor.B - FadeFromForeColor.B) / (float)MaxTransitions;
ForeColorMap[0] = FadeFromForeColor;
for (int i = 1; i < MaxTransitions; i++)
{
a = (int)(ForeColorMap[i - 1].A + aDelta);
r = (int)(ForeColorMap[i - 1].R + rDelta);
g = (int)(ForeColorMap[i - 1].G + gDelta);
b = (int)(ForeColorMap[i - 1].B + bDelta);
if (a < 0 || a > 255) a = FadeToForeColor.A;
if (r < 0 || r > 255) r = FadeToForeColor.R;
if (g < 0 || g > 255) g = FadeToForeColor.G;
if (b < 0 || b > 255) b = FadeToForeColor.B;
ForeColorMap[i] = Color.FromArgb(a, r, g, b);
}
}
}
}
|
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Text.RegularExpressions;
using Ayende.NHibernateQueryAnalyzer.Core.Model;
using Ayende.NHibernateQueryAnalyzer.UserInterface.Commands;
using Ayende.NHibernateQueryAnalyzer.UserInterface.Interfaces;
using Ayende.NHibernateQueryAnalyzer.Utilities;
using NHibernate;
using NHibernate.Cfg;
namespace Ayende.NHibernateQueryAnalyzer.UserInterface.Presenters
{
/// <summary>
/// Summary description for QueryPresenter.
/// </summary>
public class QueryPresenter : IQueryPresenter
{
private readonly IMainPresenter mainPresenter;
private readonly IQueryView view;
private Query query;
public const string DefaultName = "New Query";
public QueryPresenter(IMainPresenter mainPresenter):this(mainPresenter, new Query(DefaultName,string.Empty))
{}
public QueryPresenter(IMainPresenter mainPresenter, Query query)
{
this.mainPresenter = mainPresenter;
this.query = query;
this.view = CreateView();
}
private static readonly Regex parameters = new Regex(@"(?<=:)\w+", RegexOptions.Compiled);
//public virtual void PopulateEntitiesInEntityExplorer()
//{
// mainPresenter.CurrentProject.
//}
public Configuration NHibernateConfiguration
{
get { return mainPresenter.CurrentProject.NHibernateConfiguration; }
}
public virtual SortedList MappingFiles
{
get { return mainPresenter.CurrentProject.MappingFiles; }
}
public virtual string TranslateHql()
{
try
{
if (QueryCanBeTranslated())
{
string[] sql = mainPresenter.CurrentProject.HqlToSql(view.HqlQueryText, view.Parameters);
string result = string.Join("; ", sql);
view.SqlQueryText = result;
return result;
}
else
{
string result = "Some parameters were not set, cannot translate query.";
view.SqlQueryText = result;
return result;
}
}
//Notice, this should usually be QueryException, but it can be other things, so we'll
// just handle every exception as an error from the query.
catch (Exception ex)
{
view.AddException(ex);
return ex.Message;
}
}
public virtual void ExecuteQuery()
{
if (QueryCanBeTranslated())
{
TypedParameter[] typedParameters = ConvertDictionaryToTypedParameterArray(view.Parameters);
ICommand execQuery = new ExecuteQueryCommand(view, mainPresenter.CurrentProject, view.HqlQueryText, typedParameters);
mainPresenter.EnqueueCommand(execQuery);
view.StartWait("Executing query", 100, 1000);
}
else
{
view.ShowError("Can't execute query before all parameters are set");
}
}
public bool QueryCanBeTranslated()
{
return HasParameters(view.HqlQueryText) == false || AllParametersSet();
}
private static TypedParameter[] ConvertDictionaryToTypedParameterArray(IDictionary parameters)
{
if (parameters == null)
return new TypedParameter[0];
TypedParameter[] typedParameters = new TypedParameter[parameters.Count];
int i = 0;
foreach (DictionaryEntry entry in parameters)
{
typedParameters[i] = ((TypedParameter) entry.Value);
i++;
}
return typedParameters;
}
public virtual bool HasParameters(string queryText)
{
return parameters.IsMatch(queryText);
}
public virtual bool AllParametersSet()
{
foreach (Match match in parameters.Matches(view.HqlQueryText))
{
TypedParameter parameter = (TypedParameter) view.Parameters[match.Value];
if (parameter == null || parameter.Value == null || parameter.Type == null)
return false;
}
return true;
}
public virtual bool ReplaceException(Exception newException, Exception lastException)
{
if (newException.GetType() == lastException.GetType())
{
if (newException.GetType() == typeof (QueryException))
return true;
if (newException.Message == lastException.Message)
return true;
}
return false;
}
public IQueryView View
{
get
{
return view;
}
}
public virtual void AnalyzeParameters()
{
Hashtable visibleParameters = new Hashtable(view.Parameters);
MatchCollection matches = parameters.Matches(view.HqlQueryText);
foreach (Match match in matches)
{
if (visibleParameters.Contains(match.Value))
//remove previous mark of missing
view.SetParameterMissing(match.Value, false);
else
view.SuggestParameter(match.Value);
visibleParameters.Remove(match.Value);
}
//mark those not found as missing
foreach (TypedParameter parameter in visibleParameters.Values)
{
view.SetParameterMissing(parameter.Name, true);
}
}
public bool SaveQueryAs()
{
string name = view.Title;
string newName = view.Ask("Rename query to:", name);
if (newName != null)
{
Query oldQuery = mainPresenter.CurrentProject.GetQueryWithName(newName);
if (oldQuery != null)
{
if(view.AskYesNo("A query with thename '" + newName + "' already exists, are you sure you want to overwrite it?", "Overwrite query?"))
mainPresenter.CurrentProject.RemoveQuery(oldQuery);
else
return false;
}
if(Query.OwnerProject==null)
mainPresenter.CurrentProject.AddQuery(Query);
Query.Name = newName;
view.Title = newName;
mainPresenter.Repository.SaveQuery(Query);
view.HasChanges = false;
return true;
}
return false;
}
public bool SaveQuery()
{
if (Query.Name == DefaultName)
return SaveQueryAs();
mainPresenter.Repository.SaveQuery(Query);
view.HasChanges = false;
return true;
}
protected virtual IQueryView CreateView()
{
return new QueryForm(this, mainPresenter.View);
}
public Query Query
{
get { return query; }
set { query = value; }
}
//public NHibernate.Cfg.Configuration NHibernateConfiguration
//{
// get { return mainPresenter.CurrentProject.NHibernateConfiguration; }
// set { nHibernateConfiguration = value; }
//}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Powerup : MonoBehaviour
{
Player player;
[SerializeField] private float _speed = 0;
[SerializeField] private int _powerupID;
[SerializeField] private AudioClip _audioClip;
[SerializeField] private Transform target;
private int _ammoRefill = 15;
private bool _isBeingAttractedToPlayer = false;
private int _commonPointValue = 10;
private int _uncommonPointValue = 20;
private int _rarePointValue = 40;
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
target = player.transform;
}
void Update()
{
if (!_isBeingAttractedToPlayer)
{
transform.Translate(Vector3.down * _speed * Time.deltaTime);
if (transform.position.y < -4.5f)
{
Destroy(this.gameObject);
}
}
else
{
if (target != null)
{
transform.Translate(Vector3.right * (_speed * 2) * Time.deltaTime);
transform.right = target.position - transform.position;
}
}
}
public void AttractPowerup()
{
_isBeingAttractedToPlayer = true;
}
public void StopAttractingPowerup()
{
_isBeingAttractedToPlayer = false;
transform.localEulerAngles = new Vector3(0, 0, 0);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Player player = other.transform.GetComponent<Player>();
AudioSource.PlayClipAtPoint(_audioClip, transform.position);
if (player != null)
{
switch(_powerupID)
{
case 0:
player.TripleShotActive(); //Common Spawn
player.AddScore(_commonPointValue);
break;
case 1:
player.SpeedBoostActive(); //Common Spawn
player.AddScore(_commonPointValue);
break;
case 2:
player.RefillAmmo(_ammoRefill); //Common Spawn
player.AddScore(_commonPointValue);
break;
/////////////////////////////////////////////////////////////////////////
case 3:
player.ShieldActive(); //Uncommon Spawn
player.AddScore(_uncommonPointValue);
break;
case 4:
player.RestoreHealth(); //Uncommon Spawn
player.AddScore(_uncommonPointValue);
break;
case 5:
player.NegaShroomActive(); //Uncommon Spawn
player.AddScore(_uncommonPointValue);
break;
///////////////////////////////////////////////////////////////////////
case 6:
player.SuperBeamActive(); //Rare Spawn
player.AddScore(_rarePointValue);
break;
case 7:
player.SuperMissileActive(); //Rare Spawn
player.AddScore(_rarePointValue);
break;
default:
Debug.Log("Default Value");
break;
}
}
Destroy(this.gameObject);
}
}
}
|
/* 11. Write an expression that extracts from a given integer i the value of a given bit number b.
* Example: i=5; b=2 -> value=1. */
using System;
class ExtractBit
{
static void Main()
{
Console.Write("Please enter your number: ");
int number, bit;
int.TryParse(Console.ReadLine(), out number);
Console.Write("Please enter the bit you want extracted: ");
int.TryParse(Console.ReadLine(), out bit);
int result = (number >> bit) & 1;
Console.WriteLine(result);
}
} |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace NMoSql.Helpers
{
public class Having : Helper, IQueryHelper
{
private readonly ConditionBuilder _conditionBuilder;
public Having(ConditionBuilder conditionBuilder)
{
_conditionBuilder = conditionBuilder ?? throw new ArgumentNullException(nameof(conditionBuilder));
}
public string Fn(JToken having, IList<object> values, Query query) => ((IQueryHelper)this).Fn(having, values, query);
string IQueryHelper.Fn(JToken value, IList<object> values, Query query)
{
if (value.Type != JTokenType.Object)
throw new InvalidOperationException($"Invalid type '{value?.Type ?? JTokenType.Undefined}' for query helper 'having'. Expects '{JTokenType.Object}'");
var output = _conditionBuilder.Build((JObject)value, query.__defaultTable, values, query.__tableAliases);
if (output.Length > 0)
output = "having " + output;
return output;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Admin_ADDCatagory : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindBrandsRptr();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (ImgFile.HasFile)
{
string SavePath = Server.MapPath("../Images/Categories/");
if (!Directory.Exists(SavePath))
{
Directory.CreateDirectory(SavePath);
}
string Extention = Path.GetExtension(ImgFile.PostedFile.FileName);
ImgFile.SaveAs(SavePath + "\\" + txtCatName.Text + Extention);
BussinessLogic.setProductType(txtCatName.Text, txtCatName.Text + Extention);
lblMsg.Text = "Category Inserted Successfully !!!";
BindBrandsRptr();
}
}
private void BindBrandsRptr()
{
DataTable dtBrands;
dtBrands = BussinessLogic.getCategories();
rptrCategory.DataSource = dtBrands;
rptrCategory.DataBind();
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace OneLayerNeuronNetwork
{
public partial class Form1 : Form
{
Bitmap image;
//mvp
network network = new network();
neuron neuro = new neuron();
// List<double> input = neuro.input; // Лист входов
public Form1()
{
InitializeComponent();
}
public Bitmap toWb()
{
System.IO.StreamWriter sourceMtrx = new System.IO.StreamWriter(@"D:\proj\sourceMtrx.txt");
Int32 x, y;
int c, summRGB;
int P = 127;
Bitmap result = new Bitmap(image.Width, image.Height);
network.input.Clear();
for (x = 0; x < image.Width; x++)
{
for (y = 0; y < image.Height; y++)
{
Color color = image.GetPixel(x, y);
int alpha = color.A;
summRGB = color.R + color.G + color.B;
c = (summRGB) / 3;
// cAwg = Color.FromArgb(c);
//image.SetPixel(x, y, cAwg);
result.SetPixel(x, y, (c <= P ? Color.FromArgb(255, 0, 0, 0) : Color.FromArgb(255, 255, 255, 255)));
// input.Add(result.GetPixel(x, y));
sourceMtrx.Write(summRGB.ToString() + " ");
// network.input.Add(summRGB);
if(c == 255)
network.input.Add(0);
else
network.input.Add(1);
}
sourceMtrx.WriteLine();
}
//pictureBox1.Image = result;
sourceMtrx.Close();
return result;
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open_dialog = new OpenFileDialog();
open_dialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG";
if (open_dialog.ShowDialog() == DialogResult.OK) //если в окне была нажата кнопка "ОК"
{
try
{
//MessageBox.Show(open_dialog.FileName);
image = new Bitmap(Image.FromFile(open_dialog.FileName /*@"C:\Users\Вадим\Desktop\img.jpg"*/), 64, 64); // Изменение размера картинки
pictureBox1.Image = toWb();
network.rasp();
pictureBox1.Invalidate();
}
catch
{
DialogResult rezult = MessageBox.Show("Невозможно открыть выбранный файл",
"Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string yhat;
try
{
yhat = textBox2.Text;
network.learnNetwork(yhat);
// network.altReLearn(yhat);
/*
for (int i= 0; i < network.net.Count(); i++)
{
textBox1.Text += "number neuron " + i + " " + network.net[i].output.ToString() +"\r\n";
}*/
label7.Text = network.errorNet.ToString();
}
catch (Exception)
{
MessageBox.Show("Введите значение");
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
network.getOutputText();
if (File.Exists(network.path)){
// neuro.
network.getNeuron();
label5.Text = "Данные загружены";
// label5.Text += tmpNetwork.net[0].weight.Count;
labelCountNeuron.Text = network.net.Count().ToString();
}
else
{
// network.newNeuron();
label5.Text = "Random weight add.";
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void buttonNewChar_Click(object sender, EventArgs e)
{
network.newNeuron();
labelCountNeuron.Text = network.net.Count().ToString();
}
private void labelCountNeuron_Click(object sender, EventArgs e)
{
}
private void buttonSaveWeight_Click(object sender, EventArgs e)
{
network.saveAllWeight();
network.saveOutput();
}
private void button4_Click(object sender, EventArgs e)
{
try
{
string output = textBox2.Text;
network.newNeuron(output);
labelCountNeuron.Text = network.net.Count().ToString();
}
catch (Exception)
{
MessageBox.Show("Введите значение");
}
}
private void button5_Click(object sender, EventArgs e)
{
network.rasp();
}
private void label6_Click(object sender, EventArgs e)
{
}
private void button6_Click(object sender, EventArgs e)
{
string path = @"C:\Users\Вадим\Desktop\numbers\training\Обучающая выборка";
int countFiles = 0;
//Bitmap image;
string[] pathFiles;
string[] yhatStr;
string yhat;
foreach (var item in Directory.GetDirectories(path))
{
Console.WriteLine(item);
countFiles = Directory.GetFiles(item).Length;
pathFiles = Directory.GetFiles(item);
yhatStr = item.Split('\\');
yhat = yhatStr[yhatStr.Length - 1];
network.newNeuron(yhat);
labelCountNeuron.Text = network.net.Count().ToString();
foreach (var file in pathFiles)
{
string[] end = file.Split('\\');
if (end[end.Length-1] != "Thumbs.db")
{
using (image = new Bitmap(Image.FromFile(file), 64, 64))
{
toWb();
network.learnNetwork(yhat);
// label7.Text = network.errorNet.ToString();
}
}
}
Console.WriteLine(countFiles.ToString());
}
network.saveAllWeight();
network.saveOutput();
//MessageBox.Show(countFolder.ToString());
}
private void button7_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ERP_MODEL;
namespace ERP_DAL
{
public class DepartmentDal
{
DBContent content = new DBContent();
/// <summary>
/// 添加部门
/// </summary>
/// <returns></returns>
public int AddDepart(DepartmentModel department)
{
content.departments.Add(department);
return content.SaveChanges();
}
/// <summary>
/// 删除部门
/// </summary>
/// <returns></returns>
public int DelDepart(int Departid)
{
var id = content.departments.Where(a => a.DepartmentId == Departid).FirstOrDefault();
content.Entry(id).State = EntityState.Deleted;
content.departments.Remove(id);
return content.SaveChanges();
}
/// <summary>
/// 反填部门
/// </summary>
/// <returns></returns>
public DepartmentModel FanTian(int departid)
{
return content.departments.Where(a => a.DepartmentId == departid).FirstOrDefault();
}
/// <summary>
/// 修改部门
/// </summary>
/// <param name="Roleid"></param>
/// <returns></returns>
public int UpdRole(DepartmentModel department)
{
content.Entry(department).State = EntityState.Modified;
return content.SaveChanges();
}
/// <summary>
/// 显示部门
/// </summary>
/// <returns></returns>
public List<DepartmentModel> ShowRole()
{
return content.departments.ToList();
}
}
}
|
using System.Collections.Generic;
using AnimeViewer.Models;
using MvvmHelpers;
namespace AnimeViewer.ViewModels
{
internal class AnimeCollectionPageViewModel : BaseViewModel
{
public IEnumerable<Anime> Animes { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;
namespace unid
{
public static class Download
{
public static void ParseDownload(string[] args)
{
Download.DownloadFile(args[2], args[3]);
}
public static void DownloadFile(string inurl, string outpath)
{
Console.WriteLine("Downloading from " + inurl + " to " + outpath);
try
{
WebClient downloadapi = new WebClient();
downloadapi.DownloadFile(inurl, outpath);
Console.ResetColor();
Console.WriteLine("File downloaded to " + outpath);
Process.Start("explorer.exe", outpath);
}
catch (Exception er)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(er.Message);
Console.ResetColor();
}
}
}
public static class Upload
{
public static void ParseUpload(string[] args)
{
Upload.UploadFile(args[2], args[3]);
}
public static void UploadFile(string outurl, string inpath)
{
Console.WriteLine("Uploading from " + inpath + " to " + outurl);
try
{
WebClient downloadapi = new WebClient();
downloadapi.UploadFile(outurl, inpath);
Console.ResetColor();
Console.WriteLine("File uploaded to " + outurl);
}
catch (Exception er)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(er.Message);
Console.ResetColor();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace console
{
public class _028_FindKthElement
{
/// <summary>
/// Find the Kth element of an un sorted integer array.
/// </summary>
/// <param name="input">the array</param>
/// <returns>the kth element</returns>
public int FindKthElement(int[] input, int k)
{
if (input == null ||input.Length < k) return -1;
return FindKthElement(input, 0, input.Length-1,k);
}
/// <summary>
/// Worker method of find keht element.
/// </summary>
/// <param name="input"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public int FindKthElement(int[] input, int start, int end, int k)
{
int tmp = start;
int left = start;
int right = end;
while (start < end)
{
while (start < end && input[start] <= input[tmp]) start++;
while (start < end && input[end] >= input[tmp]) end--;
Swap(input, start, end);
start++;
end--;
}
if (end+1 == k) return input[tmp];
else
{
Swap(input, tmp, end);
if (end > k)
{
return FindKthElement(input, left, end-1, k);
}
else
{
return FindKthElement(input, end + 1, right, k);
}
}
}
/// <summary>
/// swap 2 elements in a int array.
/// </summary>
/// <param name="input"></param>
/// <param name="index1"></param>
/// <param name="index2"></param>
public void Swap(int[] input, int index1, int index2)
{
int tmp = input[index1];
input[index1] = input[index2];
input[index2] = tmp;
}
}
}
|
//=======================================================================
// ClassName : CtrlLog
// 概要 : ログ画面コントローラー
//
// LiplisLive2DSystem
// Copyright(c) 2017-2018 sachin. All Rights Reserved.
//=======================================================================
using Assets.Scripts.Controller;
using Assets.Scripts.Data;
using Assets.Scripts.Define;
using Assets.Scripts.LiplisSystem.Com;
using Assets.Scripts.LiplisSystem.Model;
using Assets.Scripts.LiplisSystem.Msg;
using Assets.Scripts.LiplisSystem.Web;
using Assets.Scripts.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class CtrlLog : MonoBehaviour {
///=============================
// レンダリングUIキャッシュ
public GameObject UiRenderingBack;
public GameObject UiRenderingFront;
public GameObject UiLog;
///=============================
/// UI
public GameObject Content;
public GameObject ContentChild;
public Button BtnReTalk;
RectTransform ContentRect;
RectTransform ContentChildRect;
///=============================
///プレファブ
private GameObject PrefabLogNewsContent;
private GameObject PrefabLogWindowL1;
private GameObject PrefabLogWindowR1;
///=============================
///パネルリスト
private List<GameObject> PanelList;
private List<GameObject> PanelChildList;
///=============================
/// モデルコントローラー
public CtrlModelController modelController;
///=============================
///選択キー
private MsgTalkLog selectedLog;
///=============================
///コンテンツ
private Texture empty;
//====================================================================
//
// 初期化処理
//
//====================================================================
#region 初期化処理
/// <summary>
/// スタート処理
/// </summary>
void Start()
{
ClearChild();
}
/// <summary>
/// 画面有効化時
/// </summary>
private void OnEnable()
{
}
/// <summary>
/// クラスの初期化
/// </summary>
private void InitClass()
{
InitPrefab();
InitRect();
InitPanelList();
}
/// <summary>
/// プレファブを初期化する
/// </summary>
private void InitPrefab()
{
if (this.PrefabLogNewsContent == null)
{
this.PrefabLogNewsContent = (GameObject)Resources.Load(PREFAB_NAMES.WINDOW_LOG_NEWS);
this.PrefabLogWindowL1 = (GameObject)Resources.Load(PREFAB_NAMES.WINDOW_LOG_CHAR_L1);
this.PrefabLogWindowR1 = (GameObject)Resources.Load(PREFAB_NAMES.WINDOW_LOG_CHAR_R1);
}
}
/// <summary>
/// レクトを初期化する
/// </summary>
private void InitRect()
{
if (this.ContentRect == null)
{
this.ContentRect = Content.GetComponent<RectTransform>();
this.ContentChildRect = ContentChild.GetComponent<RectTransform>();
}
}
/// <summary>
/// パネルリストを初期化する
/// </summary>
private void InitPanelList()
{
if (this.PanelList == null)
{
this.PanelList = new List<GameObject>();
this.PanelChildList = new List<GameObject>();
}
}
/// <summary>
/// 子要素のクリア
/// </summary>
public void Clear()
{
foreach (Transform n in Content.transform)
{
GameObject.Destroy(n.gameObject);
}
}
public void ClearChild()
{
//この話題おしゃべり非表示
BtnReTalk.gameObject.SetActive(false);
foreach (Transform n in ContentChild.transform)
{
GameObject.Destroy(n.gameObject);
}
}
/// <summary>
/// エンプティを生成する
/// </summary>
public void CreateEmpty()
{
if (empty == null)
{
empty = new Texture2D(0, 0);
}
}
#endregion
//====================================================================
//
// イベントハンドラ
//
//====================================================================
#region イベントハンドラ
/// <summary>
/// クリックイベント
/// </summary>
public void OpneDescription(MsgTalkLog log, GameObject panel)
{
//色替え
panel.GetComponent<Image>().color = Color.blue;
//現在選択中ログ取得
this.selectedLog = log;
//会話ログ表示
StartCoroutine(OpenDescription(log.TalkSentenceList));
}
/// <summary>
/// ブラウザを開くボタン押下
/// </summary>
/// <param name="url"></param>
public void OpneWeb(string url)
{
Browser.Open(url);
}
/// <summary>
/// この話題をもう一度おしゃべり
/// </summary>
public void Btn_BtnReTalk_Click()
{
//おしゃべり
if (this.selectedLog != null)
{
//閉じるボタン実行
Btn_Log_Close_Click();
//おしゃべり実行
CtrlTalk.Instance.SetTopicTalkFromLastNewsList(selectedLog.DATAKEY, ContentCategolyText.GetContentCategoly(selectedLog.DATA_TYPE));
}
}
/// <summary>
/// 設定クリック
/// </summary>
public void Btn_Log_Click()
{
//フロント画面が非アクティブのときは何もしない
if (!UiRenderingFront.gameObject.activeSelf)
{
return;
}
//ペンディング設定
LiplisStatus.Instance.EnvironmentInfo.SetPendingOn();
UiRenderingBack.gameObject.SetActive(false);
UiRenderingFront.gameObject.SetActive(false);
UiLog.gameObject.SetActive(true);
}
/// <summary>
/// 設定を閉じる
/// </summary>
public void Btn_Log_Close_Click()
{
//ペンディング設定ON
LiplisStatus.Instance.EnvironmentInfo.SetPendingOff();
UiRenderingBack.gameObject.SetActive(true);
UiRenderingFront.gameObject.SetActive(true);
UiLog.gameObject.SetActive(false);
}
#endregion
//====================================================================
//
// コンテント操作
//
//====================================================================
#region コンテント操作
/// <summary>
/// 更新処理
/// </summary>
void Update()
{
}
/// <summary>
/// ログを追加する
/// </summary>
/// <param name="topic"></param>
/// <returns></returns>
public IEnumerator AddLog(MsgTopic topic)
{
//クラスの初期化チェック
InitClass();
//ログメッセージ生成
MsgTalkLog log = new MsgTalkLog();
//データ生成
log.CREATE_TIME = topic.CreateTime;
log.DATA_TYPE = topic.TopicClassification;
log.DATAKEY = topic.DataKey;
log.TITLE = topic.Title;
log.URL = topic.Url;
log.THUMBNAIL_URL = topic.ThumbnailUrl;
log.PANEL_KEY = log.DATAKEY + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
log.TalkSentenceList = topic.TalkSentenceList;
if (log.TalkSentenceList.Count < 1)
{
Debug.Log("明細0件!");
}
//スクロール
MoveAndClean();
yield return null;
//UI生成
IEnumerator Async = CreateLogUi(log);
//待ち
yield return Async;
//パネル生成
GameObject panel = (GameObject)Async.Current;
//親パネルにセット
panel.transform.SetParent(Content.transform, false);
panel.transform.SetAsFirstSibling();
//パネルリストに追加
this.PanelList.Add(panel);
}
/// <summary>
/// UIを生成する
/// </summary>
/// <param name="log"></param>
/// <returns></returns>
public IEnumerator CreateLogUi(MsgTalkLog log)
{
//ウインドウのプレハブからインスタンス生成
GameObject panel = Instantiate(this.PrefabLogNewsContent) as GameObject;
//ウインドウ名設定
panel.name = "LiplisLog" + log.DATAKEY;
//要素取得
Text TxtTitle = panel.transform.Find("TxtTitle").GetComponent<Text>();
Text TxtCat = panel.transform.Find("TxtCat").GetComponent<Text>();
Text TxtTime = panel.transform.Find("TxtTime").GetComponent<Text>();
Text TxtDataKey = panel.transform.Find("TxtDataKey").GetComponent<Text>();
Text TxtPanelKey = panel.transform.Find("TxtPanelKey").GetComponent<Text>();
Button BtnWeb = panel.transform.Find("BtnWeb").GetComponent<Button>();
RawImage ImgThumbnail = panel.transform.Find("ImgThumbnail").GetComponent<RawImage>();
//内容設定
TxtTitle.text = log.TITLE;
TxtCat.text = ContentCategolyText.GetContentText(log.DATA_TYPE);
TxtTime.text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
TxtDataKey.text = log.DATAKEY;
TxtPanelKey.text = log.PANEL_KEY + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
//ポインターダウンイベントトリガー生成
RegisterEventOpenDescription(log, ImgThumbnail.gameObject, panel);
BtnWeb.GetComponent<Button>().onClick.AddListener(() => OpneWeb(log.URL));
//イメージのロード
CreateEmpty();
GlobalCoroutine.GoWWW(ImgThumbnail, empty, log.THUMBNAIL_URL);
yield return panel;
}
/// <summary>
/// イベント登録
/// </summary>
/// <param name="log"></param>
/// <param name="imageObject"></param>
public void RegisterEventOpenDescription(MsgTalkLog log, GameObject imageObject, GameObject panel)
{
EventTrigger trigger = imageObject.AddComponent<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.PointerDown;
entry.callback.AddListener((eventData) => { OpneDescription(log, panel); });
trigger.triggers.Add(entry);
}
/// <summary>
/// 移動とクリーン
/// </summary>
private void MoveAndClean()
{
//100個以下になるまでデストロイする
while (PanelList.Count > 9)
{
//パネル取得
GameObject panel = PanelList.Dequeue();
//パネルキー取得
Text TxtPanelKey = panel.transform.Find("TxtPanelKey").GetComponent<Text>();
//パネルキーが一致したら、子を初期化する
if (selectedLog != null)
{
if (selectedLog.PANEL_KEY == TxtPanelKey.text)
{
ClearChild();
}
}
//子オブジェクトをすべて削除
foreach (Transform child in panel.transform)
{
Destroy(child.gameObject);
}
//パネルを削除
Destroy(panel);
}
int idx = 1;
//移動
foreach (var panel in PanelList)
{
Vector3 txtPos = panel.transform.position;
panel.transform.position = new Vector3(txtPos.x, txtPos.y - 90, txtPos.z);
idx++;
}
//サイズ変更
ContentRect.sizeDelta = new Vector2(ContentRect.sizeDelta.x, 600);
}
/// <summary>
/// サムネイルを更新する
/// </summary>
/// <returns></returns>
public IEnumerator UpdateThumbnail(RawImage ImgThumbnail, string thumbnailUrl)
{
//登録されていない場合は、ダウンロード
using (WWW www = new WWW(ThumbnailUrl.CreateListThumbnailUrl(thumbnailUrl)))
{
// 画像ダウンロード完了を待機
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
CreateEmpty();
ImgThumbnail.texture = empty;
}
yield return new WaitForSeconds(0.5f);
try
{
ImgThumbnail.texture = www.texture;
}
catch
{
CreateEmpty();
ImgThumbnail.texture = empty;
}
}
yield return new WaitForSeconds(0.1f);
}
/// <summary>
/// ディスクリプションを開く
/// </summary>
/// <param name="topic"></param>
/// <returns></returns>
public IEnumerator OpenDescription(List<MsgSentence> SentenceList)
{
//一旦クリアする
CleanPanelChildList();
ClearChild();
//管理ID
int prvAllocationId = -1;
bool rlBit = true;
int idx = 0;
//センテンスリストを回し、チャットを生成する
foreach (MsgSentence sentence in SentenceList)
{
CreateLogTalkUi(sentence, rlBit, idx);
//反転
if (prvAllocationId != sentence.AllocationId)
{
rlBit = !rlBit;
}
//アロケーションID取得
prvAllocationId = sentence.AllocationId;
//インデックスインクリメント
idx++;
}
//高さ設定
ContentChildRect.sizeDelta = new Vector2(ContentRect.sizeDelta.x, (idx) * 40);
//この話題おしゃべり表示
BtnReTalk.gameObject.SetActive(true);
//終了
yield return null;
}
/// <summary>
/// クリーン
/// </summary>
private void CleanPanelChildList()
{
//100個以下になるまでデストロイする
while (PanelChildList.Count > 0)
{
//パネル取得
GameObject panel = PanelChildList.Dequeue();
//子オブジェクトをすべて削除
foreach (Transform child in panel.transform)
{
Destroy(child.gameObject);
}
//パネルを削除
Destroy(panel);
}
//クリア
PanelChildList.Clear();
}
/// <summary>
/// トークUIを生成する
/// </summary>
/// <param name="sentence"></param>
/// <param name="rlBit"></param>
/// <param name="idx"></param>
public void CreateLogTalkUi(MsgSentence sentence, bool rlBit, int idx)
{
//ウインドウのプレハブからインスタンス生成
GameObject panel = CreateCharPanel(sentence.AllocationId, rlBit);
//ウインドウ名設定
panel.name = "LiplisTalkLog" + idx;
//要素取得
Text TxtMessage = panel.transform.Find("ImgText").GetComponent<Image>().transform.Find("Text").GetComponent<Text>();
//内容設定
TxtMessage.text = sentence.TalkSentence;
Vector3 txtPos = panel.transform.position;
panel.transform.position = new Vector3(txtPos.x, -idx * 40, txtPos.z);
//親パネルにセット
PanelChildList.Add(panel);
panel.transform.SetParent(ContentChild.transform, false);
}
/// <summary>
/// キャラクターのパネルを生成する
/// </summary>
/// <param name="AllocationId"></param>
/// <param name="rlBit"></param>
/// <returns></returns>
private GameObject CreateCharPanel(int AllocationId, bool rlBit)
{
//モデル取得
LiplisModel model = modelController.TableModelId[AllocationId];
//パネル
GameObject panel;
//
if (rlBit)
{
panel = Instantiate(this.PrefabLogWindowL1) as GameObject;
}
else
{
panel = Instantiate(this.PrefabLogWindowR1) as GameObject;
}
//背景画像設定
panel.transform.Find("ImgText").GetComponent<Image>().sprite = model.SpriteLogWindow;
//キャラクターアイコン設定
panel.transform.Find("ImgChar").GetComponent<Image>().sprite = model.SpriteCharIcon;
return panel;
}
#endregion
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameHandler : MonoBehaviour {
[SerializeField]
protected BoatHandler boatHandlerPrefab;
[SerializeField]
protected Transform boatParent;
[SerializeField]
protected DemonHandler demonHandler;
public delegate void EndGame();
public static event EndGame OnWinGame;
// Waves
protected int waveCount = 0;
protected BoatHandler currentWave;
protected float waveIntervalTimer = 0;
protected bool waveIntervalStart;
// Wave Data
protected List<List<BoatWaveData>> waveData = new List<List<BoatWaveData>> () {
new List<BoatWaveData> () {
new BoatWaveData (0, 2, 0)
},
new List<BoatWaveData> () {
new BoatWaveData (0, 1, 0),
new BoatWaveData (0, 3, 2)
},
new List <BoatWaveData> () {
new BoatWaveData (0, 4, 0),
new BoatWaveData (1, 1, 2)
},
new List <BoatWaveData> () {
new BoatWaveData (0, 0, 0),
new BoatWaveData (1, 3, 2)
},
new List <BoatWaveData> () {
new BoatWaveData (0, 1, 0),
new BoatWaveData (0, 3, 0),
new BoatWaveData (1, 2, 3)
},
new List <BoatWaveData> () {
new BoatWaveData (1, 0, 0),
new BoatWaveData (1, 4, 0),
new BoatWaveData (0, 2, 4),
new BoatWaveData (1, 1, 4),
new BoatWaveData (1, 3, 0)
},
new List <BoatWaveData> () {
new BoatWaveData (0, 4, 0),
new BoatWaveData (0, 3, 1),
new BoatWaveData (0, 2, 1),
new BoatWaveData (0, 1, 1),
new BoatWaveData (0, 0, 1)
},
new List <BoatWaveData> () {
new BoatWaveData (2, 2, 0)
},
new List <BoatWaveData> () {
new BoatWaveData (0, 1, 0),
new BoatWaveData (0, 3, 0),
new BoatWaveData (1, 2, 3),
new BoatWaveData (1, 0, 0),
new BoatWaveData (1, 4, 0)
},
new List <BoatWaveData> () {
new BoatWaveData (0, 0, 0),
new BoatWaveData (1, 4, 0),
new BoatWaveData (2, 2, 0)
},
new List <BoatWaveData> () {
new BoatWaveData (1, 0, 0),
new BoatWaveData (1, 1, 1),
new BoatWaveData (1, 2, 1),
new BoatWaveData (1, 3, 1),
new BoatWaveData (1, 4, 1)
},
new List <BoatWaveData> () {
new BoatWaveData (2, 0, 0),
new BoatWaveData (2, 4, 0),
new BoatWaveData (1, 1, 0),
new BoatWaveData (1, 3, 0),
new BoatWaveData (0, 2, 0)
}
};
// wave effects
protected float demonSpeedMod;
protected float demonHealthMod;
// Instance
public static GameHandler Instance;
// Use this for initialization
void Start () {
if (Instance != null) {
Destroy (gameObject);
}
Instance = this;
Reset ();
}
// Update is called once per frame
void Update () {
if (waveIntervalStart) {
waveIntervalTimer -= Time.deltaTime;
if (waveIntervalTimer <= 0.0F) {
StartWave ();
}
}
}
public void StartWave () {
Debug.Log ("Starting Wave " + waveCount);
// remove the current wave
if (currentWave != null) {
currentWave.isCurrentWave = false;
}
// start a new boat wave
currentWave = null;
currentWave = Instantiate (boatHandlerPrefab);
currentWave.transform.SetParent (transform);
currentWave.isCurrentWave = true;
// Start a new Wave
if (waveCount < waveData.Count) {
currentWave.StartWave (boatParent, waveData [waveCount]);
}
// demon waves
demonHandler.StartWave (demonHealthMod, demonSpeedMod);
// // increment wave stats
demonSpeedMod += 0.125F;
// // set the wave interval
waveIntervalTimer = 2.0F;
waveIntervalStart = false;
// increment the wave
waveCount++;
}
public void FinishedWave () {
// Check if the game is finished
if (waveCount >= waveData.Count) {
OnWinGame ();
return;
}
waveIntervalStart = true;
}
public void SpawnDemon (Transform startPosition, BoatHandler handler) {
demonHandler.SpawnDemon (startPosition, handler);
}
public void Reset () {
// wave stats
waveCount = 0;
demonSpeedMod = 1.0F;
demonHealthMod = 1.0F;
// destroy all current wave objects
foreach (Transform child in boatParent) {
Destroy (child.gameObject);
}
foreach (Transform child in transform) {
Destroy (child.gameObject);
}
// start the wave
StartWave ();
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace HT.Framework
{
[CustomEditor(typeof(FSM))]
[GiteeURL("https://gitee.com/SaiTingHu/HTFramework")]
[GithubURL("https://github.com/SaiTingHu/HTFramework")]
[CSDNBlogURL("https://wanderer.blog.csdn.net/article/details/86073351")]
internal sealed class FSMInspector : HTFEditor<FSM>
{
private Dictionary<string, Type> _stateInstances;
private string _currentStateName = "<None>";
protected override void OnRuntimeEnable()
{
base.OnRuntimeEnable();
Dictionary<Type, FiniteStateBase> states = Target.GetType().GetField("_stateInstances", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(Target) as Dictionary<Type, FiniteStateBase>;
_stateInstances = new Dictionary<string, Type>();
foreach (var state in states)
{
FiniteStateNameAttribute attribute = state.Key.GetCustomAttribute<FiniteStateNameAttribute>();
_stateInstances.Add(attribute != null ? attribute.Name : state.Key.Name, state.Key);
}
if (Target.CurrentState != null)
{
FiniteStateNameAttribute nameAttribute = Target.CurrentState.GetType().GetCustomAttribute<FiniteStateNameAttribute>();
_currentStateName = nameAttribute != null ? nameAttribute.Name : Target.CurrentState.GetType().Name;
}
}
protected override void OnInspectorDefaultGUI()
{
base.OnInspectorDefaultGUI();
GUILayout.BeginHorizontal();
EditorGUILayout.HelpBox("Finite state machine!", MessageType.Info);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
Toggle(Target.IsAutoRegister, out Target.IsAutoRegister, "Auto Register");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
TextField(Target.Name, out Target.Name, "Name");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
TextField(Target.Group, out Target.Group, "Group");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.color = Target.Data == "<None>" ? Color.gray : Color.white;
GUILayout.Label("Data", GUILayout.Width(60));
if (GUILayout.Button(Target.Data, EditorGlobalTools.Styles.MiniPopup))
{
GenericMenu gm = new GenericMenu();
gm.AddItem(new GUIContent("<None>"), Target.Data == "<None>", () =>
{
Undo.RecordObject(target, "Set FSM Data Class");
Target.Data = "<None>";
HasChanged();
});
List<Type> types = ReflectionToolkit.GetTypesInRunTimeAssemblies(type =>
{
return type.IsSubclassOf(typeof(FSMDataBase)) && !type.IsAbstract;
});
for (int i = 0; i < types.Count; i++)
{
int j = i;
gm.AddItem(new GUIContent(types[j].FullName), Target.Data == types[j].FullName, () =>
{
Undo.RecordObject(target, "Set FSM Data Class");
Target.Data = types[j].FullName;
HasChanged();
});
}
gm.ShowAsContext();
}
GUI.color = Color.white;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.enabled = Target.DefaultStateName != "";
GUILayout.Label("Default: " + Target.DefaultStateName);
GUI.enabled = true;
GUILayout.FlexibleSpace();
GUI.enabled = Target.StateNames.Count > 0;
if (GUILayout.Button("Set Default", EditorGlobalTools.Styles.MiniPopup))
{
GenericMenu gm = new GenericMenu();
for (int i = 0; i < Target.StateNames.Count; i++)
{
int j = i;
gm.AddItem(new GUIContent(Target.StateNames[j]), Target.DefaultStateName == Target.StateNames[j], () =>
{
Undo.RecordObject(target, "Set FSM Default State");
Target.DefaultState = Target.States[j];
Target.DefaultStateName = Target.StateNames[j];
HasChanged();
});
}
gm.ShowAsContext();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.enabled = Target.FinalStateName != "";
GUILayout.Label("Final: " + Target.FinalStateName);
GUI.enabled = true;
GUILayout.FlexibleSpace();
GUI.enabled = Target.StateNames.Count > 0;
if (GUILayout.Button("Set Final", EditorGlobalTools.Styles.MiniPopup))
{
GenericMenu gm = new GenericMenu();
for (int i = 0; i < Target.StateNames.Count; i++)
{
int j = i;
gm.AddItem(new GUIContent(Target.StateNames[j]), Target.FinalStateName == Target.StateNames[j], () =>
{
Undo.RecordObject(target, "Set FSM Final State");
Target.FinalState = Target.States[j];
Target.FinalStateName = Target.StateNames[j];
HasChanged();
});
}
gm.ShowAsContext();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
GUILayout.BeginVertical(EditorGlobalTools.Styles.Box);
GUILayout.BeginHorizontal();
GUILayout.Label("Enabled State:");
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
for (int i = 0; i < Target.StateNames.Count; i++)
{
GUILayout.BeginHorizontal();
GUILayout.Label(string.Format("{0}.{1}", i + 1, Target.StateNames[i]));
GUILayout.FlexibleSpace();
if (GUILayout.Button("Edit", EditorStyles.miniButtonLeft))
{
MonoScriptToolkit.OpenMonoScript(Target.States[i]);
}
if (GUILayout.Button("Delete", EditorStyles.miniButtonRight))
{
Undo.RecordObject(target, "Delete FSM State");
if (Target.DefaultStateName == Target.StateNames[i])
{
Target.DefaultState = "";
Target.DefaultStateName = "";
}
if (Target.FinalStateName == Target.StateNames[i])
{
Target.FinalState = "";
Target.FinalStateName = "";
}
Target.States.RemoveAt(i);
Target.StateNames.RemoveAt(i);
if (Target.DefaultStateName == "" && Target.StateNames.Count > 0)
{
Target.DefaultState = Target.States[0];
Target.DefaultStateName = Target.StateNames[0];
}
if (Target.FinalStateName == "" && Target.StateNames.Count > 0)
{
Target.FinalState = Target.States[0];
Target.FinalStateName = Target.StateNames[0];
}
HasChanged();
}
GUILayout.EndHorizontal();
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Add State", EditorGlobalTools.Styles.MiniPopup))
{
GenericMenu gm = new GenericMenu();
List<Type> types = ReflectionToolkit.GetTypesInRunTimeAssemblies(type =>
{
return type.IsSubclassOf(typeof(FiniteStateBase)) && !type.IsAbstract;
});
for (int i = 0; i < types.Count; i++)
{
int j = i;
string stateName = types[j].FullName;
FiniteStateNameAttribute fsmAtt = types[j].GetCustomAttribute<FiniteStateNameAttribute>();
if (fsmAtt != null)
{
stateName = fsmAtt.Name;
}
if (Target.States.Contains(types[j].FullName))
{
gm.AddDisabledItem(new GUIContent(stateName));
}
else
{
gm.AddItem(new GUIContent(stateName), false, () =>
{
Undo.RecordObject(target, "Add FSM State");
Target.States.Add(types[j].FullName);
Target.StateNames.Add(stateName);
if (Target.DefaultStateName == "")
{
Target.DefaultState = Target.States[0];
Target.DefaultStateName = Target.StateNames[0];
}
if (Target.FinalStateName == "")
{
Target.FinalState = Target.States[0];
Target.FinalStateName = Target.StateNames[0];
}
HasChanged();
});
}
}
gm.ShowAsContext();
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
protected override void OnInspectorRuntimeGUI()
{
base.OnInspectorRuntimeGUI();
GUILayout.BeginHorizontal();
GUILayout.Label("Current State: " + _currentStateName);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("States: " + _stateInstances.Count);
GUILayout.EndHorizontal();
foreach (var state in _stateInstances)
{
GUILayout.BeginHorizontal();
GUILayout.Space(20);
GUILayout.Label(state.Key);
GUILayout.FlexibleSpace();
GUI.enabled = _currentStateName != state.Key;
if (GUILayout.Button("Switch", EditorStyles.miniButton))
{
Target.SwitchState(state.Value);
FiniteStateNameAttribute nameAttribute = Target.CurrentState.GetType().GetCustomAttribute<FiniteStateNameAttribute>();
_currentStateName = nameAttribute != null ? nameAttribute.Name : Target.CurrentState.GetType().Name;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
GUILayout.BeginHorizontal();
if (GUILayout.Button("Renewal", EditorStyles.miniButtonLeft))
{
Target.Renewal();
FiniteStateNameAttribute nameAttribute = Target.CurrentState.GetType().GetCustomAttribute<FiniteStateNameAttribute>();
_currentStateName = nameAttribute != null ? nameAttribute.Name : Target.CurrentState.GetType().Name;
}
if (GUILayout.Button("Final", EditorStyles.miniButtonRight))
{
Target.Final();
FiniteStateNameAttribute nameAttribute = Target.CurrentState.GetType().GetCustomAttribute<FiniteStateNameAttribute>();
_currentStateName = nameAttribute != null ? nameAttribute.Name : Target.CurrentState.GetType().Name;
}
GUILayout.EndHorizontal();
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Web;
using VAOCA_DIARS.Models;
namespace VAOCA_DIARS.DB.Maps
{
public class CursoMap : EntityTypeConfiguration<Curso>
{
public CursoMap()
{
ToTable("Curso");
HasKey(o => o.Id);
HasRequired(o => o.profesor).WithMany(o => o.curso).HasForeignKey(o => o.IdProfesor);
}
}
} |
using Yasl;
using UnityEngine;
namespace Yasl
{
public class KeyframeSerializer : StructSerializer<Keyframe>
{
public KeyframeSerializer()
{
}
public override void SerializeConstructor(ref Keyframe value, ISerializationWriter writer)
{
writer.Write<float>("Time", value.time);
writer.Write<float>("Value", value.value);
writer.Write<float>("InTangent", value.inTangent);
writer.Write<float>("OutTangent", value.outTangent);
}
public override void DeserializeConstructor(out Keyframe keyFrame, int version, ISerializationReader reader)
{
var time = reader.Read<float>("Time");
var value = reader.Read<float>("Value");
var inTangent = reader.Read<float>("InTangent");
var outTangent = reader.Read<float>("OutTangent");
keyFrame = new Keyframe(time, value, inTangent, outTangent);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace Assignent1_PrivateSchoolStructure
{
public class School
{
public List<Course> Courses { get; set; }
public List<Student> Students { get; set; }
public List<Trainer> Trainers { get; set; }
public School()
{
Courses = new List<Course>();
Students = new List<Student>();
Trainers = new List<Trainer>();
}
// Course Methods
public void CreateCourseFromUserInput(string courseInfo, Random random)
{
var courseTitle = String.Empty;
StreamType courseStream;
CourseType courseType;
DateTime courseStartDate = DateTime.MinValue;
if (String.IsNullOrWhiteSpace(courseInfo))
throw new InvalidOperationException("You must enter course Title, Stream type , Type and Start date separated by komma.");
string[] courseProps = courseInfo.Split(',');
if (courseProps.Length != 4)
throw new InvalidOperationException("You must enter course Title, Stream type , Type and Start date separated by komma.");
if (String.IsNullOrWhiteSpace(courseProps[0]))
throw new InvalidOperationException("Course title cannot be empty.");
courseTitle = courseProps[0];
if (!Enum.TryParse<StreamType>(courseProps[1], true, out courseStream))
throw new InvalidOperationException("You entered a not valid course stream type.");
if (!Enum.TryParse<CourseType>(courseProps[2], true, out courseType))
throw new InvalidOperationException("You entered a not valid course type.");
if (!DateTime.TryParse(courseProps[3], out courseStartDate))
throw new InvalidOperationException("You entered a not valid course Start date.");
AddCourse(courseTitle, courseStream, courseType, courseStartDate, random);
}
public void AddCourse(string title, StreamType stream, CourseType type, DateTime startDate, Random random)
{
int id = GetRandomUniqueCourseId(random);
var course = new Course(id, title, stream, type, startDate);
Courses.Add(course);
Console.WriteLine($"Created course {course}");
}
public void AddRandomCourses(List<string> courseTitles, int numberOfCourses, Random random)
{
Course randomCourse = null;
for (int i = 0; i < numberOfCourses; i++)
{
if (Courses.Count == 200)
throw new InvalidOperationException("Max number of courses: 200");
randomCourse = GetRandomUniqueCourse(courseTitles, random);
Courses.Add(randomCourse);
Console.WriteLine($"Created course {randomCourse}");
}
}
public Course GetRandomUniqueCourse(List<string> courseTitles, Random random)
{
int randomId = GetRandomUniqueCourseId(random);
return Course.GetRandomCourse(randomId, courseTitles, random);
}
// Students Methods
public void CreateStudent(string firstName, string lastName, DateTime dateOfBirth, Random random)
{
int id = GetRandomUniqueStudentId(random);
var student = new Student(id, firstName, lastName, dateOfBirth);
Students.Add(student);
Console.WriteLine($"Student registered: {student}");
}
public void CreateStudentFromUserInput(string studentInfo, Random random)
{
var studentFirstName = String.Empty;
var studentLastName = String.Empty;
var studentBirthDate = DateTime.MinValue;
if (String.IsNullOrWhiteSpace(studentInfo))
throw new InvalidOperationException("You must enter student FirstName, LastName and BirthDate separated by komma.");
var studentProps = studentInfo.Split(',');
if (studentProps.Length != 3)
throw new InvalidOperationException("You must enter student FirstName, LastName and BirthDate separated by komma.");
if (String.IsNullOrWhiteSpace(studentProps[0]) || String.IsNullOrWhiteSpace(studentProps[1]))
throw new InvalidOperationException("Both FirstName and LastName cannot be empty.");
studentFirstName = studentProps[0];
studentLastName = studentProps[1];
if (!DateTime.TryParse(studentProps[2], out studentBirthDate))
throw new InvalidOperationException("You must enter a valid date.");
CreateStudent(studentFirstName, studentLastName, studentBirthDate, random);
}
public void AssignStudentToACourse(int studentId, int courseId)
{
var student = GetStudent(studentId);
var course = GetCourse(courseId);
if (course.Students.Contains(student))
throw new InvalidOperationException($"Student[{student.Id}] is already assigned to course[{course.Id} {course.Title}]");
course.Students.Add(student);
student.Courses.Add(course);
Console.WriteLine($"[{student.Id}]{student.FullName} enrolled in course[{course.Id}]{course.Title}");
course.CreatePersonalAssigmentsForStudent(student);
}
public Student GetRandomUniqueStudent(List<string> firstNames, List<string> lastNames, Random random)
{
int randomId = GetRandomUniqueStudentId(random);
return Student.GetRandomStudent(randomId, firstNames, lastNames, random);
}
public void AddRandomStudents(List<string> firstNames, List<string> lastNames, int numberOfStudents, Random random)
{
Student randomStudent = null;
for (int i = 0; i < numberOfStudents; i++)
{
if (Students.Count == 200)
throw new InvalidOperationException("Max number of students: 200");
randomStudent = GetRandomUniqueStudent(firstNames, lastNames, random);
Students.Add(randomStudent);
Console.WriteLine($"Student registered: {randomStudent}");
}
}
public void RandomlyAssignStudentsToAllCourses(Random random)
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
foreach (var course in Courses)
{
AssignRandomNumberOfStudentsToACourse(course.Id, random);
}
}
public void AssignRandomNumberOfStudentsToARandomCourse(Random random)
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
Course randomCourse = Courses[random.Next(Courses.Count)];
AssignRandomNumberOfStudentsToACourse(randomCourse.Id, random);
//List<Student> studentsThatAreNotAssignedToRandomCourse = Students.FindAll(x => !x.Courses.Contains(randomCourse));
//if (studentsThatAreNotAssignedToRandomCourse.Count == 0)
// throw new InvalidOperationException($"All registered students have applied to course [{randomCourse.Id}]{randomCourse.Title}");
//int numberOfStudentsToAssign = random.Next(1, studentsThatAreNotAssignedToRandomCourse.Count + 1);
//for (int i = 0; i < numberOfStudentsToAssign; i++)
//{
// var studentToAssign = studentsThatAreNotAssignedToRandomCourse[random.Next(studentsThatAreNotAssignedToRandomCourse.Count)];
// randomCourse.Students.Add(studentToAssign);
// randomCourse.CreatePersonalAssigmentsForStudent(studentToAssign);
// studentToAssign.Courses.Add(randomCourse);
// studentsThatAreNotAssignedToRandomCourse.Remove(studentToAssign);
//}
//Console.WriteLine($"Added {numberOfStudentsToAssign} students to course {randomCourse}");
}
public void AssignRandomNumberOfStudentsToACourse(int courseId, Random random)
{
var course = GetCourse(courseId);
if (Students.Count == 0)
throw new InvalidOperationException("There are no registered students.");
List<Student> studentsThatAreNotAssignedToCourse = Students.FindAll(x => !x.Courses.Contains(course));
if (studentsThatAreNotAssignedToCourse.Count == 0)
throw new InvalidOperationException($"All registered students have applied to course [{course.Id}]{course.Title}");
int numberOfStudentsToAssign = random.Next(1, studentsThatAreNotAssignedToCourse.Count + 1);
for (int i = 0; i < numberOfStudentsToAssign; i++)
{
var studentToAssign = studentsThatAreNotAssignedToCourse[random.Next(studentsThatAreNotAssignedToCourse.Count)];
course.Students.Add(studentToAssign);
course.CreatePersonalAssigmentsForStudent(studentToAssign);
studentToAssign.Courses.Add(course);
studentsThatAreNotAssignedToCourse.Remove(studentToAssign);
}
Console.WriteLine($"Added {numberOfStudentsToAssign} students to course {course}");
}
public List<Student> GetStudentsPerCourse(int courseId)
{
var course = GetCourse(courseId);
if (course.Students.Count == 0)
throw new InvalidOperationException($"There are no registered students in course wit id {courseId}.");
return course.Students;
}
private bool StudentBelongsToMoreThanOneCourse(Student student)
{
if (student == null || student.Courses.Count <= 1)
return false;
return true;
}
// Trainer methods
public void CreateTrainerFromUserInput(string trainerInfo, Random random)
{
var trainerFirstname = String.Empty;
var trainerLastName = String.Empty;
var trainerSubject = String.Empty;
if (String.IsNullOrWhiteSpace(trainerInfo))
throw new InvalidOperationException("You must enter trainer's FirstName, LastName and Subject separated by komma.");
var trainerProps = trainerInfo.Split(',');
if (trainerProps.Length != 3)
throw new InvalidOperationException("You must enter trainer's FirstName, LastName and Subject separated by komma.");
if (String.IsNullOrWhiteSpace(trainerProps[0]) || String.IsNullOrWhiteSpace(trainerProps[1]) || String.IsNullOrWhiteSpace(trainerProps[2]))
throw new InvalidOperationException("FirstName,LastName and Subject cannot be empty.");
trainerFirstname = trainerProps[0];
trainerLastName = trainerProps[1];
trainerSubject = trainerProps[2];
AddTrainer(trainerFirstname, trainerLastName, trainerSubject, random);
}
public void AddTrainer(string firstName, string lastName, string subject, Random random)
{
int id = GetRandomUniqueTrainerId(random);
var trainer = new Trainer(id, firstName, lastName, subject);
Trainers.Add(trainer);
Console.WriteLine($"Registered trainer: {trainer}");
}
public Trainer GetRandomUniqueTrainer(List<string> firstNames, List<string> lastNames, List<string> trainerSubjects, Random random)
{
int randomId = GetRandomUniqueTrainerId(random);
return Trainer.GetRandomTrainer(randomId, firstNames, lastNames, trainerSubjects, random);
}
public void AddRandomTrainers(List<string> firstNames, List<string> lastNames, List<string> trainerSubjects, int numberOfTrainers, Random random)
{
Trainer randomTrainer = null;
for (int i = 0; i < numberOfTrainers; i++)
{
if (Trainers.Count == 200)
throw new InvalidOperationException("Max number of trainers: 200");
randomTrainer = GetRandomUniqueTrainer(firstNames, lastNames, trainerSubjects, random);
Trainers.Add(randomTrainer);
Console.WriteLine($"Trainer registered: {randomTrainer}");
}
}
public void AssignTrainerToCourse(int trainerId, int courseId)
{
var trainer = GetTrainer(trainerId);
var course = GetCourse(courseId);
if (course.Trainers.Contains(trainer))
throw new InvalidOperationException($"{trainer} is already assigned to {course}");
foreach (var trainerCourse in trainer.Courses)
{
if (!Course.NonOverlappingIntervalBetweenTwoCoursesIsMoreThanOneMonth(trainerCourse, course))
throw new InvalidOperationException($"Non overlapping interval between course[{courseId}] and course[{trainerCourse.Id}] is lower or equal to a month.");
}
course.Trainers.Add(trainer);
trainer.Courses.Add(course);
Console.WriteLine($"Trainer[{trainer.Id}] {trainer.FullName} assigned to course[{courseId}] {course.Title}");
}
public void RandomlyAssignTrainersToAllCourses(Random random)
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
foreach (var course in Courses)
{
AssignRandomNumberOfTrainersToACourse(course.Id, random);
}
}
public void AssignRandomNumberOfTrainersToACourse(int courseId, Random random)
{
var course = GetCourse(courseId);
if (Trainers.Count == 0)
throw new InvalidOperationException("There are no registered trainers.");
var trainersThatAreNotAssignedToRandomCourse = Trainers.FindAll(x => !x.Courses.Contains(course));
if (trainersThatAreNotAssignedToRandomCourse.Count == 0)
throw new InvalidOperationException($"All trainers are assigned to: {course}");
int numberOfTrainersToAssign = random.Next(1, trainersThatAreNotAssignedToRandomCourse.Count + 1);
for (int i = 0; i < numberOfTrainersToAssign; i++)
{
var randomTrainer = trainersThatAreNotAssignedToRandomCourse[random.Next(trainersThatAreNotAssignedToRandomCourse.Count)];
course.Trainers.Add(randomTrainer);
randomTrainer.Courses.Add(course);
trainersThatAreNotAssignedToRandomCourse.Remove(randomTrainer);
}
Console.WriteLine($"Assigned {numberOfTrainersToAssign} trainers to course {course}");
}
public void AssignRandomNumberOfTrainersToARandomCourse(Random random)
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
var randomCourse = Courses[random.Next(Courses.Count)];
AssignRandomNumberOfTrainersToACourse(randomCourse.Id, random);
}
// Assignments methods
public List<Assignment> GetAssignmentsPerCourse(int courseId)
{
var course = GetCourse(courseId);
if (course.Assignments.Count == 0)
throw new InvalidOperationException($"Course[{courseId}] has no assignments.");
return course.Assignments;
}
public List<StudentAssignment> GetAllStudentAssignmentsForACourse(int courseId)
{
var course = GetCourse(courseId);
var listOfAllStudentAssignments = new List<StudentAssignment>();
if (course.Assignments.Count == 0)
throw new InvalidOperationException($"Course[{course.Id}] has no assignments.");
if (course.Students.Count == 0)
throw new InvalidOperationException($"Course[{course.Id} has no students.");
foreach (var student in course.Students)
{
listOfAllStudentAssignments.AddRange(student.PersonalAssignments.FindAll(x => x.Course.Equals(course)));
}
return listOfAllStudentAssignments;
}
public List<StudentAssignment> GetAllAssignmentsPerStudent(int studentId)
{
var student = GetStudent(studentId);
if (student.PersonalAssignments.Count == 0)
throw new InvalidOperationException($"Student with id[{studentId}] has no assignments.");
return student.PersonalAssignments;
}
public void SetRandomTotalMarkToAllStudentsAssignments(Random random)
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
foreach (var course in Courses)
{
StudentAssignment.SetTotalMarkOfAssignmentsToRandomValues(GetAllStudentAssignmentsForACourse(course.Id), random);
}
}
public void SetRandomMarkToAllStudentsAssignmetsOfACourse(int courseId, Random random)
{
StudentAssignment.SetTotalMarkOfAssignmentsToRandomValues(GetAllStudentAssignmentsForACourse(courseId), random);
}
public void AddRandomAssignmentsToACourse(int courseId, int numberOfAssignments, List<string> assignmentDescriptions, Random random)
{
if (numberOfAssignments < 0)
throw new InvalidOperationException("Number of assignments must greater or equal to zero.");
for (int i = 0; i < numberOfAssignments; i++)
{
CreateRandomAssignment(courseId, assignmentDescriptions, random);
}
}
public void AddRandomNumberOfAssignmetsToAllCourses(int maxNumberOfAssignments, List<string> assignmentDescriptions, Random random)
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
foreach (var course in Courses)
{
AddRandomAssignmentsToACourse(course.Id, random.Next(1, maxNumberOfAssignments + 1), assignmentDescriptions, random);
}
}
public void CreateRandomAssignment(int courseId, List<string> assignmentDescriptions, Random random)
{
var course = GetCourse(courseId);
var assignmentTitle = $"Assignment{course.Assignments.Count + 1}";
var assignmentDescription = assignmentDescriptions[random.Next(assignmentDescriptions.Count)];
var assignmentSubmissionDateAndTime = Randomizer.GenerateDateExcludingWeekends(course.StartDate, (course.EndDate - course.StartDate).Days, random);
var courseAssignment = new Assignment(assignmentTitle, assignmentDescription, assignmentSubmissionDateAndTime, course);
course.Assignments.Add(courseAssignment);
course.CreatePersonalAssignmentsForAllStudentsAppliedToCourse(courseAssignment);
Console.WriteLine($"Created {courseAssignment}");
}
public void CreateAssignmentFromUserInput(string assignmnetInfo, int courseId)
{
var course = GetCourse(courseId);
if (String.IsNullOrWhiteSpace(assignmnetInfo))
throw new InvalidOperationException("You must enter Description and Submission DateAndTime separated by komma");
var assignmenProps = assignmnetInfo.Split(',');
if (assignmenProps.Length != 2)
throw new InvalidOperationException("You must enter Description and Submission DateAndTime separated by komma");
var description = assignmenProps[0];
var submissionDateAndTime = DateTime.MinValue;
if (!DateTime.TryParse(assignmenProps[1], out submissionDateAndTime))
throw new InvalidOperationException("You must enter a valid date and time");
var title = $"Assignment{course.Assignments.Count + 1}";
var assignment = new Assignment(title, description, submissionDateAndTime, course);
course.Assignments.Add(assignment);
course.CreatePersonalAssignmentsForAllStudentsAppliedToCourse(assignment);
Console.WriteLine($"Created: {assignment}");
}
// Printing Methods
public void PrintStudentsThatNeedToSubmitAssigmentsInTheSpecifiedWeek(DateTime date, CultureInfo myCI)
{
var monday = FirstDateOfWeek(date, myCI);
var friday = monday.AddDays(4);
Console.WriteLine($"===== Students that need to submit assignments from {monday.ToString("yyyy/MM/dd")} to {friday.ToString("yyyy/MM/dd")}");
foreach (var student in Students)
{
if (student.PersonalAssignments.Count > 0 && student.PersonalAssignments.Exists(x => (x.SubmissionDateAndTime >= monday && x.SubmissionDateAndTime <= friday)))
Console.WriteLine(student);
}
}
public void PrintStudentsThatBelongToMoreThanOneCourse()
{
Console.WriteLine("===== Students tha belong to more than one course =====");
if (Students.Count == 0)
Console.WriteLine("There are no registered students.");
else
{
var students = new List<Student>();
foreach (var student in Students)
{
if (StudentBelongsToMoreThanOneCourse(student))
Console.WriteLine(student);
}
}
}
public void PrintAssignmentsPerStudent(int studentId)
{
var student = GetStudent(studentId);
student.PrintStudentAssignments();
}
public void PrintAllAssignmentsPerStudent()
{
if (Students.Count == 0)
Console.WriteLine("There are no registered students.");
else
{
Console.WriteLine("===== All assignments per student =====\n");
foreach (var student in Students)
{
Console.WriteLine($"=====[{student.Id}] {student.FullName} assignments");
if (student.PersonalAssignments.Count == 0)
{
Console.WriteLine($"Student[{student.Id}] has no assignments.");
Console.WriteLine();
}
else
{
foreach (var studentAssignment in student.PersonalAssignments)
{
Console.WriteLine(studentAssignment);
}
Console.WriteLine();
}
}
}
}
private void PrintAllStudentAssignmentsOfACourse(Course course)
{
if (course == null)
throw new NullReferenceException("course");
Console.WriteLine($"===== Student Assignments of Course[{course.Id}] {course.Title} =====\n");
if (course.Assignments.Count == 0)
Console.WriteLine($"Course[{course.Id}] has no assignments.");
else if (course.Students.Count == 0)
{
Console.WriteLine($"Course[{course.Id} has no students.");
}
else
{
foreach (var student in course.Students)
{
student.PrintStudentAssignmentsRelatedToACourse(course);
Console.WriteLine();
}
}
Console.WriteLine();
}
public void PrintAllStudentAssignmentsForAllCourses()
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
foreach (var course in Courses)
{
try
{
PrintAllStudentAssignmentsOfACourse(course);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
public void PrintAssignmentsForAllCourses()
{
if (Courses.Count == 0)
throw new InvalidOperationException("There are no registered courses.");
foreach (var course in Courses)
{
course.PrintAssignments();
}
}
public void PrintStudentsForAllCourses()
{
Console.WriteLine("===== Students per course =====\n");
if (Courses.Count == 0)
Console.WriteLine("There are no registered courses.");
else
{
foreach (var course in Courses)
{
course.PrintStudents();
Console.WriteLine();
}
}
Console.WriteLine();
}
public void PrintTrainersForAllCourses()
{
Console.WriteLine("===== Trainers per course =====\n");
if (Courses.Count == 0)
Console.WriteLine("There are no registered courses.");
else
{
foreach (var course in Courses)
{
course.PrintTrainers();
}
}
Console.WriteLine();
}
public void PrintAllCourses()
{
Console.WriteLine("===== Courses =====");
if (Courses.Count == 0)
Console.WriteLine("There are no registered courses.");
else
{
foreach (var course in Courses)
{
Console.WriteLine(course);
}
Console.WriteLine($"Total courses: {Courses.Count}");
}
Console.WriteLine();
}
public void PrintAllCoursesLite()
{
Console.WriteLine("===== Courses =====");
if (Courses.Count == 0)
Console.WriteLine("There are no registered courses.");
else
foreach (var course in Courses)
{
Console.WriteLine($"[{course.Id}] {course.Title}");
}
Console.WriteLine();
}
public void PrintAllStudents()
{
Console.WriteLine("===== Students =====");
if (Students.Count == 0)
Console.WriteLine("There are no registered students.");
else
{
foreach (var student in Students)
{
Console.WriteLine(student);
}
Console.WriteLine($"Total students: {Students.Count}");
}
Console.WriteLine();
}
public void PrintAllStudentsLite()
{
Console.WriteLine("===== Students =====");
if (Students.Count == 0)
Console.WriteLine("There are no registered students.");
else
foreach (var student in Students)
{
Console.WriteLine($"[{student.Id}] {student.FullName}");
}
Console.WriteLine();
}
public void PrintAllTrainers()
{
Console.WriteLine("===== Trainers =====");
if (Trainers.Count == 0)
Console.WriteLine("There are no registered trainers.");
else
{
foreach (var trainer in Trainers)
{
Console.WriteLine(trainer);
}
Console.WriteLine($"Total trainers: {Trainers.Count}");
}
Console.WriteLine();
}
public Trainer GetTrainer(int trainerId)
{
var trainer = Trainers.Find(x => x.Id == trainerId);
if (trainer == null)
throw new InvalidOperationException($"Trainer with id {trainerId} could not be found.");
return trainer;
}
public Course GetCourse(int courseId)
{
var course = Courses.Find(x => x.Id == courseId);
if (course == null)
throw new InvalidOperationException($"Course with id {courseId} could not be found.");
return course;
}
public Student GetStudent(int studentId)
{
var student = Students.Find(x => x.Id == studentId);
if (student == null)
throw new InvalidOperationException($"Student with id {studentId} could not be found.");
return student;
}
public int GetRandomUniqueCourseId(Random random)
{
int randomId = 0;
do
{
randomId = random.Next(1, 201);
} while (Courses.Exists(x => x.Id == randomId));
return randomId;
}
public int GetRandomUniqueStudentId(Random random)
{
int randomId = 0;
do
{
randomId = random.Next(1, 201);
} while (Students.Exists(x => x.Id == randomId));
return randomId;
}
public int GetRandomUniqueTrainerId(Random random)
{
int randomId = 0;
do
{
randomId = random.Next(1, 201);
} while (Trainers.Exists(x => x.Id == randomId));
return randomId;
}
// Special Methods
public static DateTime FirstDateOfWeek(DateTime date, CultureInfo myCI)
{
Calendar myCal = myCI.Calendar;
DateTime jan1 = new DateTime(2019, 1, 1);
int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;
DateTime firstThursday = jan1.AddDays(daysOffset);
int firstWeek = myCal.GetWeekOfYear(firstThursday, myCI.DateTimeFormat.CalendarWeekRule, myCI.DateTimeFormat.FirstDayOfWeek);
var weekNum = myCal.GetWeekOfYear(date, myCI.DateTimeFormat.CalendarWeekRule, myCI.DateTimeFormat.FirstDayOfWeek);
if (firstWeek == 1)
weekNum -= 1;
var result = firstThursday.AddDays(weekNum * 7);
return result.AddDays(-3);
}
//public void AddRandomCourses(List<string> courseTitles, int numberOfCourses, Random random)
//{
// Course randomCourse = null;
// for (int i = 0; i < numberOfCourses; i++)
// {
// do
// {
// randomCourse = GetRandomUniqueCourse(courseTitles, random);
// } while (!TryAddCourse(randomCourse));
// }
//}
//public void AssignRandomNumberOfStudentsToARandomCourse(Random random)
//{
// if (Courses.Count == 0 && Students.Count == 0)
// throw new InvalidOperationException("Can not proceed. There are no registered students or courses.");
// if (Courses.Count == 0)
// throw new InvalidOperationException("There is no course to assign students to.");
// if (Students.Count == 0)
// throw new InvalidOperationException("There is no student to be assigned to a course.");
// Course randomCourse = null;
// int numberOfStudentsToAssign = random.Next(1, Students.Count + 1);
// int counter = 0;
// Student student = null;
// randomCourse = Courses[random.Next(Courses.Count)];
// var randomCourseStudents = randomCourse.Students;
// while ((randomCourseStudents.Count < Students.Count) && (counter < numberOfStudentsToAssign))
// {
// student = Students[random.Next(Students.Count)];
// if (!randomCourseStudents.Contains(student))
// {
// randomCourseStudents.Add(student);
// student.Courses.Add(randomCourse);
// //Console.WriteLine($"Added: {student}\nto\n{randomCourse}");
// counter++;
// }
// //else
// //Console.WriteLine($"Student id: {student.Id} - {student.FullName} is already assigned to\n{randomCourse}");
// }
// Console.WriteLine($"Added {counter} students to course [{randomCourse.Id}]{randomCourse.Title} - Students: {randomCourse.Students.Count}\n");
//}
// We assume we cannot add a course with the same title,stream and type
//private bool TryAddCourse(Course course)
//{
// if (course == null)
// throw new ArgumentNullException("course");
// if (!Courses.Contains(course))
// {
// Courses.Add(course);
// Console.WriteLine($"Course added:\n{course}\n");
// return true;
// }
// //Console.WriteLine($"A course with the same Title({course.Title})/Stream({course.Stream})/Type({course.Type}) has already been added");
// return false;
//}
//public void AddAssignmentToCourse(Assignment assignment, int courseId)
//{
// var course = Courses.Find(x => x.Id == courseId);
// if (course == null)
// throw new InvalidOperationException($"Not found course with id {courseId}");
// course.Assignments.Add(assignment);
//}
//public void AddRandomAssignmentsToARandomCourse(int maxNumberOfAssignments, List<string> assignmentDescriptions, Random random)
//{
// if (Courses.Count == 0)
// throw new InvalidOperationException("There are no registered courses.");
// var course = Courses[random.Next(Courses.Count)];
// var numberOfAssignments = random.Next(1, maxNumberOfAssignments + 1);
// AddRandomAssignmentsToACourse(course.Id, numberOfAssignments, assignmentDescriptions, random);
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YoctoScheduler.Core.ExecutionTasks.WaitTask
{
public struct Configuration
{
public int SleepSeconds;
}
}
|
using Plus.HabboHotel.Items;
namespace Plus.Communication.Packets.Outgoing.Rooms.Furni
{
internal class OpenGiftComposer : MessageComposer
{
public ItemData Data { get; }
public string Text { get; }
public Item Item { get; }
public bool ItemIsInRoom { get; }
public OpenGiftComposer(ItemData data, string text, Item item, bool itemIsInRoom)
: base(ServerPacketHeader.OpenGiftMessageComposer)
{
Data = data;
Text = text;
Item = item;
ItemIsInRoom = itemIsInRoom;
}
public override void Compose(ServerPacket packet)
{
packet.WriteString(Data.Type.ToString());
packet.WriteInteger(Data.SpriteId);
packet.WriteString(Data.ItemName);
packet.WriteInteger(Item.Id);
packet.WriteString(Data.Type.ToString());
packet.WriteBoolean(ItemIsInRoom); //Is it in the room?
packet.WriteString(Text);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using ExampleCode.Models;
using ExampleCode.DataAccess;
namespace ExampleCode.Tasks
{
public class PersonTasks
{
PersonContext context = new PersonContext();
public IEnumerable<Person> GetAllPersons()
{
return context.Person.Where(p=>p.Active == true);
}
public Person getPerson(int id)
{
var person = context.Person.Where(p => p.Id == id).FirstOrDefault();
return person;
}
public Person AddPerson(Person p)
{
p.Active = true;
context.Person.Add(p);
context.SaveChanges();
return p;
}
public Person EditPerson(Person p)
{
var editedPerson = context.Person.Where(person => person.Id == p.Id).FirstOrDefault();
editedPerson.FirstName = p.FirstName;
editedPerson.LastName = p.LastName;
editedPerson.Address = p.Address;
editedPerson.City = p.City;
editedPerson.State = p.State;
editedPerson.Zip = p.Zip;
editedPerson.Phone = p.Phone;
editedPerson.Email = p.Email;
context.SaveChanges();
return editedPerson;
}
public Person DeletePerson(Person p)
{
var editedPerson = context.Person.Where(person => person.Id == p.Id).FirstOrDefault();
editedPerson.Active = p.Active;
context.SaveChanges();
return p;
}
}
} |
using System;
using System.Collections.Generic;
namespace RestApiEcom.Models
{
public partial class TResTaxeactiviteDefaut
{
public int TaxactId { get; set; }
public int? TaxactActId { get; set; }
public int? TaxactTaxId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ENTITY;
using OpenMiracle.DAL;
using System.Data;
using System.Windows.Forms;
using OpenMiracle.BLL;
namespace OpenMiracle.BLL
{
public class AttendanceBll
{
DailyAttendanceDetailsInfo infoDailyAttendanceDetails = new DailyAttendanceDetailsInfo();
DailyAttendanceDetailsSP SpDailyAttendanceDetails = new DailyAttendanceDetailsSP();
DailyAttendanceMasterInfo infoDailyAttendanceMaster = new DailyAttendanceMasterInfo();
DailyAttendanceMasterSP SpDailyAttendanceMaster = new DailyAttendanceMasterSP();
public List<DataTable> DailyAttendanceDetailsSearchGridFill(string strDate)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SpDailyAttendanceDetails.DailyAttendanceDetailsSearchGridFill(strDate);
}
catch (Exception ex)
{
MessageBox.Show("A1" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
public void DailyAttendanceDetailsAddUsingMasterId(DailyAttendanceDetailsInfo dailyattendancedetailsinfo)
{
try
{
SpDailyAttendanceDetails.DailyAttendanceDetailsAddUsingMasterId(dailyattendancedetailsinfo);
}
catch (Exception ex)
{
MessageBox.Show("A2" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public void DailyAttendanceDetailsEditUsingMasterId(DailyAttendanceDetailsInfo dailyattendancedetailsinfo)
{
try
{
SpDailyAttendanceDetails.DailyAttendanceDetailsEditUsingMasterId(dailyattendancedetailsinfo);
}
catch (Exception ex)
{
MessageBox.Show("A3" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public void DailyAttendanceDetailsDeleteAll(decimal decdailyAttendanceMasterId)
{
try
{
SpDailyAttendanceDetails.DailyAttendanceDetailsDeleteAll(decdailyAttendanceMasterId);
}
catch (Exception ex)
{
MessageBox.Show("A4" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public bool DailyAttendanceMasterMasterIdSearch(string strDate)
{
bool isEdit = false;
try
{
isEdit = SpDailyAttendanceMaster.DailyAttendanceMasterMasterIdSearch(strDate);
}
catch (Exception ex)
{
MessageBox.Show("A5" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return isEdit;
}
public List<DataTable> MonthlyAttendanceReportFill(DateTime dtMonth, decimal decEmployeeId)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SpDailyAttendanceMaster.MonthlyAttendanceReportFill(dtMonth, decEmployeeId);
}
catch (Exception ex)
{
MessageBox.Show("A6" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
public List<DataTable> DailyAttendanceViewForDailyAttendanceReport(string strDate, string strStatus, string strEmployeeCode, string strDesignation)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SpDailyAttendanceMaster.DailyAttendanceViewForDailyAttendanceReport(strDate, strStatus, strEmployeeCode, strDesignation);
}
catch (Exception ex)
{
MessageBox.Show("A7" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
public decimal DailyAttendanceAddToMaster(DailyAttendanceMasterInfo dailyattendancemasterinfo)
{
decimal incount = 0;
try
{
incount = SpDailyAttendanceMaster.DailyAttendanceAddToMaster(dailyattendancemasterinfo);
}
catch (Exception ex)
{
MessageBox.Show("A8" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return incount;
}
public void DailyAttendanceEditMaster(DailyAttendanceMasterInfo dailyattendancemasterinfo)
{
try
{
SpDailyAttendanceMaster.DailyAttendanceEditMaster(dailyattendancemasterinfo);
}
catch(Exception ex)
{
MessageBox.Show("A9" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Sbidu.Controllers
{
public class ReferralsController : Controller
{
[Route("referrals")]
public IActionResult Index()
{
return View();
}
}
}
|
using System;
using Acme.Collections;
namespace basic3 {
class Program {
static void Main (string[] args) {
Stack s = new Stack ();
s.Push (1);
s.Push (10);
s.Push (100);
Console.WriteLine (s.Pop ());
Console.WriteLine (s.Pop ());
// Console.WriteLine (s.Pop ());
Console.WriteLine (s);
}
}
} |
using ProManager.Entities.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace ProManager.DataTransferObjects.Base
{
public class LanguagesDTO : BaseDTO<Languages>
{
public String Code { get; set; }
public String GlyphUrl { get; set; }
public String Description { get; set; }
public override Languages ToModel()
{
// Create Model
Languages model = base.ToModel();
Code = this.Code;
GlyphUrl = this.GlyphUrl;
Description = this.Description;
Id = this.Id;
ModifiedDate = this.ModifiedDate;
CreatedDate = this.CreatedDate;
IsDeleted = this.IsDeleted.Value;
ApplicationUserId = this.ApplicationUserId;
RowVersion = this.RowVersion;
return model;
}
public override void UpdateModel(Languages model)
{
model.Code = Code;
model.GlyphUrl = GlyphUrl;
model.Description = Description;
model.Id = Id;
model.ModifiedDate = ModifiedDate;
model.IsDeleted = IsDeleted ?? false;
model.ApplicationUserId = ApplicationUserId;
}
}
}
|
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace Highway.Data
{
/// <summary>
/// A Entity Framework Specific repository implementation that uses Specification pattern to execute Queries in a
/// controlled fashion.
/// </summary>
public class Repository : IRepository
{
private readonly IDataContext _context;
/// <summary>
/// Creates a Repository that uses the context provided
/// </summary>
/// <param name="context">The data context that this repository uses</param>
public Repository(IDataContext context)
{
_context = context;
}
/// <summary>
/// Reference to the DataContext the repository is using
/// </summary>
public IUnitOfWork Context
{
get { return _context; }
}
/// <summary>
/// Executes a prebuilt <see cref="ICommand" />
/// </summary>
/// <param name="command">The prebuilt command object</param>
public virtual void Execute(ICommand command)
{
command.Execute(_context);
}
/// <summary>
/// Executes a prebuilt <see cref="IScalar{T}" /> and returns a single instance of <typeparamref name="T" />
/// </summary>
/// <typeparam name="T">The Entity being queried</typeparam>
/// <param name="query">The prebuilt Query Object</param>
/// <returns>The instance of <typeparamref name="T" /> returned from the query</returns>
public virtual T Find<T>(IScalar<T> query)
{
return query.Execute(_context);
}
/// <summary>
/// Executes a prebuilt <see cref="IQuery{T}" /> and returns an <see cref="IEnumerable{T}" />
/// </summary>
/// <typeparam name="T">The Entity being queried</typeparam>
/// <param name="query">The prebuilt Query Object</param>
/// <returns>The <see cref="IEnumerable{T}" /> returned from the query</returns>
public virtual IEnumerable<T> Find<T>(IQuery<T> query)
{
return query.Execute(_context);
}
/// <summary>
/// Executes a prebuilt <see cref="IQuery{T}" /> and returns an <see cref="IEnumerable{T}" />
/// </summary>
/// <typeparam name="T">The Entity being queried</typeparam>
/// <param name="query">The prebuilt Query Object</param>
/// <returns>The <see cref="IEnumerable{T}" /> returned from the query</returns>
public virtual IEnumerable<IProjection> Find<TSelection, IProjection>(IQuery<TSelection, IProjection> query)
where TSelection : class
{
return query.Execute(_context);
}
/// <summary>
/// Executes a prebuilt <see cref="ICommand" /> asynchronously
/// </summary>
/// <param name="command">The prebuilt command object</param>
public virtual Task ExecuteAsync(ICommand command)
{
var task = new Task(() => command.Execute(_context));
task.Start();
return task;
}
/// <summary>
/// Executes a prebuilt <see cref="IScalar{T}" /> and returns a single instance of <typeparamref name="T" />
/// </summary>
/// <typeparam name="T">The Entity being queried</typeparam>
/// <param name="query">The prebuilt Query Object</param>
/// <returns>The task that will return an instance of <typeparamref name="T" /> from the query</returns>
public virtual Task<T> FindAsync<T>(IScalar<T> query)
{
var task = new Task<T>(() => query.Execute(_context));
task.Start();
return task;
}
/// <summary>
/// Executes a prebuilt <see cref="IQuery{T}" /> and returns an <see cref="IEnumerable{T}" />
/// </summary>
/// <typeparam name="T">The Entity being queried</typeparam>
/// <param name="query">The prebuilt Query Object</param>
/// <returns>The task that will return <see cref="IEnumerable{T}" /> from the query</returns>
public virtual Task<IEnumerable<T>> FindAsync<T>(IQuery<T> query)
{
var task = new Task<IEnumerable<T>>(() => query.Execute(_context));
task.Start();
return task;
}
/// <summary>
/// Executes a prebuilt <see cref="IQuery{T}" /> and returns an <see cref="IEnumerable{T}" />
/// </summary>
/// <typeparam name="T">The Entity being queried</typeparam>
/// <param name="query">The prebuilt Query Object</param>
/// <returns>The task that will return <see cref="IEnumerable{T}" /> from the query</returns>
public virtual Task<IEnumerable<IProjection>> FindAsync<TSelection, IProjection>(IQuery<TSelection, IProjection> query)
where TSelection : class
{
var task = new Task<IEnumerable<IProjection>>(() => query.Execute(_context));
task.Start();
return task;
}
}
} |
namespace Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class EditProduct : DbMigration
{
public override void Up()
{
AlterColumn("dbo.Products", "Name", c => c.String(maxLength: 100));
AlterColumn("dbo.Products", "Description", c => c.String(maxLength: 500));
AlterColumn("dbo.Products", "Price", c => c.Decimal(nullable: false, precision: 16, scale: 2));
AlterColumn("dbo.Products", "Category", c => c.String(maxLength: 50));
}
public override void Down()
{
AlterColumn("dbo.Products", "Category", c => c.String());
AlterColumn("dbo.Products", "Price", c => c.Decimal(nullable: false, precision: 18, scale: 2));
AlterColumn("dbo.Products", "Description", c => c.String());
AlterColumn("dbo.Products", "Name", c => c.String());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MonoEngine.Gameplay;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MonoEngine.SceneManagement
{
class Scene
{
private List<Behaviour> behaviours;
private Vector2 origin;
public Scene()
{
behaviours = new List<Behaviour>();
}
public void Initialize()
{
}
public SceneReturn Update(float _deltaTime)
{
foreach (Behaviour item in behaviours)
{
item.Update(_deltaTime);
}
return SceneReturn.None;
}
public void Draw (SpriteBatch _spriteBatch)
{
_spriteBatch.Begin();
foreach (Behaviour item in behaviours)
{
_spriteBatch.Draw(item.Texture, item.Position, null, item.Colour, item.Rotation, item.Origin, item.Scale, item.SpriteEffects, item.LayerDepth);
}
}
}
}
|
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Web;
namespace graph_tutorial.Helpers
{
public static class GroupHelper
{
public static async Task<string> GetGroupIdAsync(string groupName)
{
var graphClient = GraphHelper.GetAuthenticatedClient();
var groups = await graphClient.Groups
.Request()
.Filter($"displayname eq '{groupName}'")
.GetAsync();
if (groups.Count == 0)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.ItemNotFound.ToString(),
Message = $"Group named: '{groupName}' is not found"
});
}
return groups.CurrentPage[0].Id;
}
public static async Task<IList<Conversation>> GetGroupConversationsAsync(string groupID)
{
var graphClient = GraphHelper.GetAuthenticatedClient();
//https://graph.microsoft.com/v1.0/groups/{id}/conversations
var conversations = await graphClient.Groups[groupID]
.Conversations
.Request()
.GetAsync();
return conversations.CurrentPage;
}
public static async Task<Conversation> GetGroupConversation(string groupId, string conversationId)
{
var graphClient = GraphHelper.GetAuthenticatedClient();
Conversation conversation = await graphClient.Groups[groupId]
.Conversations[conversationId]
.Request()
.Expand("threads")
.GetAsync();
return conversation;
}
public static async Task<string> CreateProject(GraphServiceClient graphClient, string groupId, string conversationId)
{
User me = await graphClient.Me.Request().GetAsync();
Conversation conversation = await GetGroupConversation(groupId, conversationId);
PlannerTask task = await CreatePlanner(graphClient, groupId, conversation, me);
DriveItem copiedFile = await DuplicateCostSpreadsheet(graphClient, groupId, $"{task.Title}.xlsx");
string fileurl = copiedFile.WebUrl;
var myEtag = task.AdditionalData["@odata.etag"].ToString();
//await UpdateTaskDetails(graphClient, groupId, task, copiedFile);
//Cannot for hte life of me get ETag Patch to work.
//await UpdateTaskDetailsV2(graphClient, groupId, task, fileurl, copiedFile, myEtag);
await ReplyToCustomer(graphClient, groupId, conversation, me);
return task.Title;
}
private static async Task<PlannerTask> CreatePlanner(GraphServiceClient graphClient, string groupId, Conversation conversation, User me)
{
string taskTitle = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}-{conversation.Topic}";
PlannerPlan plan = await GetPlannerPlanAsync(graphClient, groupId, "visitor intake");
string bucketId = await GetBucketIdAsync(graphClient, plan, "LobbyIntake");
var newTask = new PlannerTask()
{
PlanId = plan.Id,
ConversationThreadId = conversation.Id,
BucketId = bucketId,
Title = taskTitle
};
newTask.Assignments = new PlannerAssignments();
newTask.Assignments.AddAssignee(me.Id); //Assign the current logged in user
var createdTask = await graphClient.Planner.Tasks.Request().AddAsync(newTask);
return createdTask;
}
private static async Task<PlannerPlan> GetPlannerPlanAsync(GraphServiceClient graphClient, string groupId, string planName)
{
var plans = await graphClient.Groups[groupId]
.Planner
.Plans
.Request()
.Filter($"title eq '{planName}'")
.GetAsync();
if (plans.Count == 0)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.ItemNotFound.ToString(),
Message = $"Plan: {planName} was not found"
});
}
return plans[0];
}
private static async Task<string> GetBucketIdAsync(GraphServiceClient graphClient, PlannerPlan plan, string bucketName)
{
//Note: Buckets does not support $filter, so need to use linq
var planBuckets = await graphClient.Planner
.Plans[plan.Id]
.Buckets
.Request()
.GetAsync();
return planBuckets.FirstOrDefault(bucket => bucket.Name == bucketName).Id;
}
private static async Task UpdateTaskDetails(GraphServiceClient graphClient, string groupId, PlannerTask task, DriveItem attachFile)
{
PlannerTaskDetails taskDetails = await GetPlannerTaskDetailsAsync(graphClient, task);
taskDetails.References = new PlannerExternalReferences();
taskDetails.References.AddReference(attachFile.WebUrl, attachFile.Name);
taskDetails.Checklist = new PlannerChecklistItems();
taskDetails.Checklist.AddChecklistItem("Meet Visitor in Lobby");
//not useing anymore
// .Header("Prefer", "return=represendation")
PlannerTaskDetails updatedTask = await graphClient.Planner.Tasks[task.Id].Details.Request()
.Header("If-Match", taskDetails.GetEtag())
.Header("Prefer", "return=represendation")
.UpdateAsync(taskDetails);
}
private static async Task UpdateTaskDetailsV2(GraphServiceClient graphClient, string groupId, PlannerTask task, string newFileName, DriveItem attachFile, string myEtag)
{
PlannerTaskDetails taskDetails = new PlannerTaskDetails();
taskDetails = await GetPlannerTaskDetailsAsync(graphClient, task);
taskDetails.AdditionalData =
new Dictionary<string, object>()
{
{newFileName, attachFile.Name}
};
await graphClient.Planner.Tasks[task.Id].Details
.Request()
.Header("If-Match", myEtag)
.UpdateAsync(taskDetails);
}
private static async Task<PlannerTaskDetails> GetPlannerTaskDetailsAsync(GraphServiceClient graphClient, PlannerTask task)
{
int cnt = 0;
PlannerTaskDetails taskDetails = null;
while (taskDetails == null)
{
//Sometimes takes a little time to create the task, so wait until the item is created
cnt++;
try
{
taskDetails = await graphClient.Planner.Tasks[task.Id].Details.Request().GetAsync();
}
catch (ServiceException se)
{
}
}
return taskDetails;
}
private static async Task<DriveItem> DuplicateCostSpreadsheet(GraphServiceClient graphClient, string groupId, string newName)
{
string projectFolderId = await GroupHelper.GetDriveFolderIdAsync(graphClient, groupId, "VisitorProtocols");
string covid19TemplateName = "Covid19Survey.xlsx";
DriveItem covid19Template = await GroupHelper.GetDriveFileAsync(graphClient, groupId, projectFolderId, covid19TemplateName);
await graphClient.Groups[groupId]
.Drive
.Items[covid19Template.Id]
.Copy(newName)
.Request()
.PostAsync();
//Note: While the PostAsync says that it returns a DriveItem, it is currently returning null
// So to retrieve the copied file requires querying for it
DriveItem copiedItem = await GetDriveFileAsync(graphClient, groupId, projectFolderId, newName);
return copiedItem;
}
private static async Task<string> GetDriveFolderIdAsync(GraphServiceClient graphClient, string groupId, string folderName)
{
var options = new[]
{
new QueryOption("$filter", $"name eq '{folderName}'")
};
var groupDrive = await graphClient.Groups[groupId].Drive.Root.Children.Request(options).GetAsync();
if (groupDrive.Count == 0)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.ItemNotFound.ToString(),
Message = "Drive folder was not found: " + folderName + "."
});
}
return groupDrive.CurrentPage[0].Id;
}
private static async Task<DriveItem> GetDriveFileAsync(GraphServiceClient graphClient, string groupId, string projectFolderId, string budgetTemplateName)
{
var options = new[]
{
new QueryOption("$filter", $"name eq '{budgetTemplateName}'")
};
var driveItems = await graphClient.Groups[groupId].Drive.Items[projectFolderId].Children.Request(options).GetAsync();
if (driveItems.Count == 0)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.ItemNotFound.ToString(),
Message = $"Covid19 Visitor Template: {budgetTemplateName} was not found"
});
}
return driveItems[0];
}
private static async Task ReplyToCustomer(GraphServiceClient graphClient, string groupId, Conversation conversation, User me)
{
var firstSender = conversation.UniqueSenders.FirstOrDefault();
string replyMessage = $@"
Hello {firstSender},
Thank you registering with our Visitor Intake Utility.
We wanted to let you know that {me.DisplayName} has been assigned to your entry and a COVID-19 Protocol screening
has been authroized for you to complete
Thank you,
Secuirty Team
";
var post = new Post() { Body = new ItemBody() { Content = replyMessage, ContentType = BodyType.Text } }; //TODO Improve body text
var thread = conversation.Threads.FirstOrDefault();
await graphClient.Groups[groupId].Threads[thread.Id].Reply(post).Request().PostAsync();
}
}
} |
using MessageContract;
using NServiceBus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SSOSubscriber
{
public class SSOSubscriberEndpoint : IWantToRunWhenBusStartsAndStops
{
public IBus Bus { get; set; }
public void Start()
{
Bus.Subscribe<IPersonMessage>();
}
public void Stop()
{
Bus.Unsubscribe<IPersonMessage>();
}
}
}
|
using System;
namespace ElementChaos
{
class EvilElement : ElementBase
{
public int Hp {get;set;}
public EvilElement(int v, int h, int rt = -1, string name = "Evil", int Hp = 60) : base(v, h, rt)
{
this.name = name;
this.type = GameDef.GameObj.Mud;
this.Hp = Hp;
}
public override void beHitByBullet(Bullet b)
{
this.Hp -= b.damage;
// remian 设置为0, 交由元素管理器进行销毁
this.remain_time = 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace Utils {
public class DataValidation {
public static bool ValidField(string pattern, string text, ref bool flagOK) {
Regex regex;
Match match;
regex = new Regex(pattern);
match = regex.Match(text);
if (!match.Success) flagOK = match.Success;
return match.Success;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PlayerPlusPlus.Core
{
public partial class FullScreen : Form
{
UCPlayer UCPlayer1;
Control ParentContainer;
public FullScreen(UCPlayer uCPlayer, Control parentContainer)
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
FormBorderStyle = FormBorderStyle.None;
//TopMost = true;
this.Controls.Add(uCPlayer);
UCPlayer1 = uCPlayer;
UCPlayer1.ShowControls = false;
UCPlayer1.Dock = DockStyle.Fill;
Text = System.IO.Path.GetFileNameWithoutExtension(uCPlayer.FilePath);
ParentContainer = parentContainer;
}
void ExitFullScreen()
{
UCPlayer1.OnFullScreen = false;
UCPlayer1.ShowControls = true;
ParentContainer.Controls.Add(UCPlayer1);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
Close();
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void FullScreen_FormClosing(object sender, FormClosingEventArgs e)
{
ExitFullScreen();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class swordSpin : MonoBehaviour
{
public string nameSearch;
public GameObject caster;
public float rotationSpeed;
private GameObject knight;
// Start is called before the first frame update
void Start()
{
knight = GameObject.Find(nameSearch).transform.GetChild(0).gameObject;
}
// Update is called once per frame
void Update()
{
transform.Rotate(0f, rotationSpeed, 0f);
transform.position = new Vector3 (knight.transform.position.x, knight.transform.position.y +0.5f,knight.transform.position.z);
}
}
|
using System.Collections.Generic;
using CL.FormulaHelper.Attributes;
using MeasureFormulas.Generated_Formula_Base_Classes;
using MeasureFormula.Common_Code;
namespace CustomerFormulaCode
{
[Formula]
public class ElectricDistributionReliabilityLikelihood : ElectricDistributionReliabilityLikelihoodBase
{
public override double?[] GetLikelihoodValues(int startFiscalYear, int months,
TimeInvariantInputDTO timeInvariantData, IReadOnlyList<TimeVariantInputDTO> timeVariantData)
{
return PopulateOutputWithValue(months, 1 / CommonConstants.MonthsInYear);
}
}
}
|
using FPPG_ClassLibrary.TextConverter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FPPG_ClassLibrary
{
public class TextConnector : IDataConnector
{
private const string PeopleFile = "CustomersFile.csv";
private const string ConnectionsFile = "Connections.csv";
private const string TaskCategoryFile = "TaskCategory.csv";
private const string TaskListFile = "TaskList.csv";
public PersonModel CreatePerson(PersonModel person)
{
List<PersonModel> people = PeopleFile.FullFilePath().LoadFile().ConvertToPersonModels();
people.Add(person);
people.SaveToPersonFile(PeopleFile);
return person;
}
public List<PersonModel> GetPerson_All()
{
List<PersonModel> people = PeopleFile.FullFilePath().LoadFile().ConvertToPersonModels();
return people;
}
public List<ConnectionsModel> GetConnctionsByPerson( PersonModel person)
{
List<PersonModel> models = PeopleFile.FullFilePath().LoadFile().ConvertToPersonModels();
List<ConnectionsModel> connections = ConnectionsFile.FullFilePath().LoadFile().ConvertToConnections(models);
List<ConnectionsModel> connectionByPerson = new List<ConnectionsModel>();
int personId = person.Id;
foreach (ConnectionsModel conect in connections)
{
if (conect.FirstConnectedPerson.Id == personId || conect.SecondPersonModel.Id == personId)
{
connectionByPerson.Add(conect);
}
}
return connectionByPerson;
}
public ConnectionsModel CreateConnection(ConnectionsModel connection)
{
List<PersonModel> models = PeopleFile.FullFilePath().LoadFile().ConvertToPersonModels();
List<ConnectionsModel> connections = ConnectionsFile.FullFilePath().LoadFile().ConvertToConnections(models);
int currentId = 1;
if (connections.Count >0)
{
currentId = connections.OrderByDescending(x => x.Id).First().Id + 1;
}
connection.Id = currentId;
connections.Add(connection);
connections.SaveConnection(ConnectionsFile);
return connection;
}
public int GetNewCustommerId()
{
List<PersonModel> people = PeopleFile.FullFilePath().LoadFile().ConvertToPersonModels();
int currentId = 1;
if (people.Count > 0)
{
currentId = people.OrderByDescending(x => x.Id).First().Id + 1;
}
return currentId;
}
public List<string> GetTaskCategory()
{
List<string> category = TaskCategoryFile.FullFilePath().LoadFile();
return category;
}
public TaskModel CreateTask(TaskModel task)
{
List<TaskModel> tasks = TaskListFile.FullFilePath().LoadFile().ConvertToTaskModels(PeopleFile);
int currentId = 1;
if (tasks.Count > 0)
{
currentId = tasks.OrderByDescending(x => x.Id).First().Id + 1;
}
task.Id = currentId;
tasks.Add(task);
tasks.SaveToTaskFile(TaskListFile);
return task;
}
public List<TaskModel> GetAllTasks()
{
return TaskListFile.FullFilePath().LoadFile().ConvertToTaskModels(PeopleFile);
}
public void TaskDelay(TaskModel task)
{
List<TaskModel> tasks = TaskListFile.FullFilePath().LoadFile().ConvertToTaskModels(PeopleFile);
foreach (TaskModel t in tasks)
{
if (t.Id == task.Id)
{
t.TaskDate = t.TaskDate.AddDays(1);
}
}
tasks.SaveToTaskFile(TaskListFile);
}
public void TaskDone(TaskModel task)
{
List<TaskModel> tasks = TaskListFile.FullFilePath().LoadFile().ConvertToTaskModels(PeopleFile);
foreach (TaskModel t in tasks)
{
if(t.Id == task.Id)
{
t.Status = true;
}
tasks.SaveToTaskFile(TaskListFile);
}
}
public List<TaskModel> GetActiveTasks()
{
return TaskListFile.FullFilePath().LoadFile().GetActiveTasks(PeopleFile);
}
public TaskModel RemoveTask(TaskModel task)
{
List<TaskModel> tasks = TaskListFile.FullFilePath().LoadFile().ConvertToTaskModels(PeopleFile);
var taskToRemove = tasks.Single(x => x.Id == task.Id);
tasks.Remove(taskToRemove);
tasks.SaveToTaskFile(TaskListFile);
return task;
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace Alfheim.GUI.Services
{
public class ComboBoxPropertyEditor : PropertyEditor
{
private Dictionary<string, object> mValues;
public ComboBoxPropertyEditor(Dictionary<string, object> values)
{
mValues = values;
}
public ComboBoxPropertyEditor(string targetPropertyName, Dictionary<string, object> values) : this(values)
{
TargetPropertyName = targetPropertyName;
}
public override UIElement[] GenerateUIElements()
{
return new UIElement[]
{
TextBlockGenerator.GeneratePropertyTextBlock(TargetPropertyName) ,
GeneratePropertyComboBox()
};
}
public override event PropertyChangedEventHandler PropertyChanged;
#region private methods
private ComboBox GeneratePropertyComboBox()
{
ComboBox comboBox = new ComboBox();
comboBox.Style = Application.Current.FindResource("ComboBoxFlatStyle") as Style;
comboBox.DisplayMemberPath = "Key";
foreach (var value in mValues)
comboBox.Items.Add(value);
foreach (var item in comboBox.Items)
if (((KeyValuePair<string, object>)item).Value.GetType() == TargetProperty.GetType())
{
comboBox.SelectedItem = item;
break;
}
comboBox.SelectionChanged += OnPropertyChanged;
return comboBox;
}
#region Handlers
private void OnPropertyChanged(object sender, SelectionChangedEventArgs e)
{
var comboBox = (sender as ComboBox);
if (comboBox == null)
return;
TargetProperty = ((KeyValuePair<string, object>)comboBox.SelectedItem).Value;
PropertyChanged(Target, new PropertyChangedEventArgs(TargetPropertyName));
}
#endregion
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Controller;
using ModelCantina;
namespace GUICantina
{
public partial class FormConta : Form
{
private ControllerCliente controleCliente;
private ControllerConta controleConta;
private AutoCompleteStringCollection listaNomesClientes;
private List<Cliente> listaClientes;
private Conta contaAtual;
public FormConta()
{
InitializeComponent();
controleCliente = new ControllerCliente();
controleConta = new ControllerConta();
}
private void autocomplete()
{
listaClientes = controleCliente.ListarClientes();
listaNomesClientes = new AutoCompleteStringCollection();
foreach (Cliente cliente in listaClientes)
{
listaNomesClientes.Add(cliente.Nome);
}
textBoxCliente.AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxCliente.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxCliente.AutoCompleteCustomSource = listaNomesClientes;
}
private void buttonAtualizar_Click(object sender, EventArgs e)
{
if (listaNomesClientes.IndexOf(textBoxCliente.Text) == -1)
{
MessageBox.Show("Selecione um cliente");
return;
}
contaAtual.Limite = Convert.ToDouble(textBoxLimite.Text);
if (controleConta.GravarConta(contaAtual))
{
MessageBox.Show("Conta Atualizada com Sucesso");
textBoxCliente.Text = "";
textBoxLimite.Text = "0";
}
}
private void FormConta_Load(object sender, EventArgs e)
{
autocomplete();
}
private void textBoxCliente_TextChanged(object sender, EventArgs e)
{
int index = listaNomesClientes.IndexOf(textBoxCliente.Text);
if (index == -1)
{
contaAtual = null;
textBoxLimite.Text = "";
return;
}
Cliente cliente=listaClientes[index];
contaAtual = controleConta.LocalizarContaPorCliente(cliente.IDCliente);
textBoxLimite.Text = contaAtual.Limite.ToString();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.