text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CustomerFinderWorkerRole.TwitterGnip.SearchApi { public class SearchApi { private const string SearchApiEndPoint = "https://search.gnip.com/accounts/pticostarica/search/prod.json"; private const string SearchApiPassword = ""; private const string SearchApiUsername = ""; private string AuthInfo { get; } = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", SearchApiUsername, SearchApiPassword))); public async Task<TwitterGnip.SearchApi.Response.SearchResponse> GetTweetFromUser(string twitterUsername) { TwitterGnip.SearchApi.Response.SearchResponse result = null; System.Net.ServicePointManager.Expect100Continue = false; using (System.Net.Http.WebRequestHandler httpHandler = new System.Net.Http.WebRequestHandler() { AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip, } ) { using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(httpHandler)) { TwitterGnip.SearchApi.Request.SearchRequest request = new Request.SearchRequest() { query = "from: [REPLACE]" }; string jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(request); System.Net.Http.StringContent strContent = new System.Net.Http.StringContent(jsonRequest); strContent.Headers.Add("Authorization", string.Format("Basic: {0}", AuthInfo)); strContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var response = await client.PostAsync(SearchApiEndPoint, strContent); if (response.IsSuccessStatusCode) { var jsonResponse = await response.Content.ReadAsStringAsync(); result = Newtonsoft.Json.JsonConvert.DeserializeObject<TwitterGnip.SearchApi.Response.SearchResponse>(jsonResponse); } else { throw new Exception(response.ReasonPhrase); } } } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.Webpack; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; namespace Team.Web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var appConfig = Configuration.GetSection(nameof(AppConfig)).Get<AppConfig>(); services .AddSingleton(Configuration) .AddOptions() .Configure<JwtConfig>(Configuration.GetSection(nameof(AppConfig)).GetSection(nameof(JwtConfig))); services .ConfigureData(Configuration.GetConnectionString("TeamSqlConnection")) .ConfigureBuilder() .ConfigureServices(); services .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = appConfig.JwtConfig.Issuer, ValidAudience = appConfig.JwtConfig.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appConfig.JwtConfig.Key)) }; }); services.AddAuthorization(options => { options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User")); }); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "DefaultApi", template: "api/{controller}/{action}" ); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DEleteFileWithGivenExtension { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string[] files = null; string folderName = null; private void button1_Click(object sender, EventArgs e) { DialogResult dialogresult = folderBrowserDialog1.ShowDialog(); //Надпись выше окна контрола folderBrowserDialog1.Description = "Поиск папки"; if (dialogresult == DialogResult.OK) { //Извлечение имени папки folderName = folderBrowserDialog1.SelectedPath; } textBox1.Text = folderName; } private void button2_Click(object sender, EventArgs e) { if (files != null && files.Length != 0) { for (int i = 0; i < files.Length; i++) treeView1.Nodes.Add(files[i]); } else MessageBox.Show("Файлов нет", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void button3_Click(object sender, EventArgs e) { if (files != null && files.Length != 0) { for (int i = 0; i < files.Length; i++) if (Path.GetExtension(files[i]) == "." + textBox2.Text) File.Delete(files[i]); } else MessageBox.Show("Файлов нет","Ошибка!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); } private void button4_Click(object sender, EventArgs e) { treeView1.Nodes.Clear(); } private void button5_Click(object sender, EventArgs e) { if(folderName != null) files = Directory.GetFiles(folderName, @"*." + textBox2.Text, SearchOption.AllDirectories); else MessageBox.Show("Выберите папку", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); if (textBox2.Text=="") MessageBox.Show("Введите расширение файлов", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
using SampleTracker.Model; using System; using System.Collections.Generic; using System.Text; namespace SampleTracker.ViewModel.Element { public class AccelerometerElement : BaseElement<AccelerometerReading> { public AccelerometerElement() { } public AccelerometerElement(AccelerometerReading model) : base(model) { this.AccelerometerX = model.AccelerometerX; this.AccelerometerY = model.AccelerometerY; this.AccelerometerZ = model.AccelerometerZ; this.Timestamp = model.Timestamp; } #region Bindable Properties public double AccelerometerX { get => _accelerometerX; set { _accelerometerX = value; NotifyPropertyChanged(); } } private double _accelerometerX; public double AccelerometerY { get => _accelerometerY; set { _accelerometerY = value; NotifyPropertyChanged(); } } private double _accelerometerY; public double AccelerometerZ { get => _accelerometerZ; set { _accelerometerZ = value; NotifyPropertyChanged(); } } private double _accelerometerZ; public string Timestamp { get => _timestamp; set { _timestamp = value; NotifyPropertyChanged(); } } private string _timestamp; #endregion } }
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using BB.Common.WinForms; using System.Drawing; using Appy.Core; using Appy.Core.Themes; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Splash")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Splash")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4a974516-3ceb-4097-8850-0ec40cb31024")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] namespace Splash { static class Start { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //-- TODO: //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); Control.CheckForIllegalCrossThreadCalls = false; App app = new App("http://localhost:9393/"); app.Text = "Splash"; ThemeManager.ApplyTheme(GetMyTheme()); Application.Run(app); } static BaseTheme GetMyTheme() { var myTheme = new AppyTheme(); //-- Uncomment lines below to see the effects! //myTheme.Units["PanelBorderWidth"] = 0; //myTheme.Colors["PanelBorder"] = Color.DarkGray; //myTheme.Colors["FormBorder"] = Color.DarkGray; //myTheme.Colors["FormBackground"] = Color.Pink; //myTheme.Colors["ButtonMouseOverForeground"] = Color.White; //myTheme.Colors["ButtonMouseOverBorder"] = Color.DeepPink; //myTheme.Colors["ButtonMouseOverBackground"] = Color.DeepPink; //myTheme.Colors["ButtonMouseDownBackground"] = Color.DeepPink; //myTheme.Colors["ButtonForeground"] = Color.DarkGray; //myTheme.Units["ButtonBorderSize"] = 2; //myTheme.Colors["ButtonBorder"] = Color.White; //myTheme.Colors["ButtonBackground"] = Color.White; //myTheme.Colors["ResizeButtonMouseOverForeground"] = Color.DeepPink; //myTheme.Colors["ResizeButtonMouseOverBorder"] = Color.DeepPink; //myTheme.Colors["ResizeButtonMouseOverBackground"] = Color.DeepPink; //myTheme.Colors["ResizeButtonMouseDownBackground"] = Color.DeepPink; //myTheme.Colors["ResizeButtonForeground"] = Color.DarkGray; //myTheme.Units["ResizeButtonBorderSize"] = 2; //myTheme.Colors["ResizeButtonBorder"] = Color.Lavender; //myTheme.Colors["ResizeButtonBackground"] = Color.Lavender; //myTheme.Colors["ToolTipBackground"] = Color.White; //myTheme.Colors["ToolTipForeground"] = Color.Black; //myTheme.Units["FormBorderWidth"] = 2; return myTheme; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Webshop.Data; using Webshop.Data.DTO; using Webshop.Data.Models; namespace Webshop.Controllers { [Route("api/[controller]")] [ApiController] public class UserFavouriteProductsController : ControllerBase { private readonly ApplicationDbContext _context; private readonly IMapper _mapper; public UserFavouriteProductsController(ApplicationDbContext context, IMapper mapper) { _context = context; _mapper = mapper; } [HttpGet("{userId}")] public async Task<IEnumerable<UsersFavouriteProductsDto>> Get(string userId) { var res = await _context.UsersFavouriteProducts.Where(x => x.UserIndex == userId).ToListAsync(); var mappelt = _mapper.Map<List<UsersFavouriteProductsDto>>(res); return mappelt; } [HttpPost] public async Task<ActionResult> Post([FromBody] UsersFavouriteProductsDto usersFavouriteProductsDto) { if (usersFavouriteProductsDto.UserIndex == null ||usersFavouriteProductsDto.ProductIndex == null) return NoContent(); var newUsersFavouriteProducts = _mapper.Map<UsersFavouriteProducts>(usersFavouriteProductsDto); var tmp = _context.UsersFavouriteProducts.Where(x => x.ProductIndex == newUsersFavouriteProducts.ProductIndex).ToListAsync(); if(tmp.Result.Count == 0) _context.UsersFavouriteProducts.Add(newUsersFavouriteProducts); await _context.SaveChangesAsync(); return Ok(); } // DELETE api/<CategoryController>/5 [HttpDelete("{id}")] public async Task<ActionResult> Delete(int id) { var dbUsersFavouriteProducts = _context.UsersFavouriteProducts.SingleOrDefault(p => p.Id == id); if (dbUsersFavouriteProducts == null) return NotFound("Couldnt find the item"); _context.UsersFavouriteProducts.Remove(dbUsersFavouriteProducts); await _context.SaveChangesAsync(); return Ok(); // a sikeres torlest 204 No } } }
using Infnet.Engesoft.SysBank.Model.Contratos; namespace Infnet.Engesoft.SysBank.Model.Dominio { public abstract class Pessoa { public int id { get; set; } public string Nome { get; set; } public IEndereco Endereco { get; set; } public Telefone Telefone { get; set; } public TipoEstadoCliente EstadoCliente { get; set; } } }
using RestSharp.Deserializers; using System.Collections.Generic; namespace GoogleDistanceMatrix.Entities { public class DistanceMatrixResponse { [DeserializeAs(Name = "destination_addresses")] public IList<string> DestinationAddresses { get; set; } [DeserializeAs(Name = "origin_addresses")] public IList<string> OriginAddresses { get; set; } [DeserializeAs(Name = "rows")] public IList<Row> Rows { get; set; } [DeserializeAs(Name = "status")] public string Status { get; set; } } }
using Espades.Domain.Entities.Base; using Espades.Domain.Repository; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Espades.Infrastructure.Base.Repositories { public class Repository : IRepository { #region Properties private EspadesContext _context { get; set; } public Repository(EspadesContext context) { _context = context; } #endregion #region Methods public async void Add<T>(T entity) where T : BaseEntity { await _context.Set<T>().AddAsync(entity); } public void Edit<T>(T entity) where T : BaseEntity { Edit(entity.Id, entity).Wait(); } public async Task Edit<T>(object id, T entity) where T : BaseEntity { var oldEntity = await Get<T>(id); _context.Entry(oldEntity).State = EntityState.Modified; _context.Entry(oldEntity).CurrentValues.SetValues(entity); } public async Task Delete<T>(int id) where T : BaseEntity { Delete(await Get<T>(id)); } public void Delete<T>(T entity) where T : BaseEntity { _context.Entry(entity).State = EntityState.Deleted; } public async Task<int> Count<T>(Expression<Func<T, bool>> expression) where T : BaseEntity { return await _context.Set<T>().Where(expression).CountAsync(); } public async Task<bool> Exists<T>(Expression<Func<T, bool>> expression) where T : BaseEntity { return await _context.Set<T>().AnyAsync(expression); } public async Task<T> First<T>(Expression<Func<T, bool>> expression) where T : BaseEntity { return await _context.Set<T>().Where(x => !x.Deleted).FirstOrDefaultAsync(expression); } public async Task<T> First<T>(Expression<Func<T, bool>> expression, bool noTracking = false) where T : BaseEntity { if (noTracking) return await _context.Set<T>().AsNoTracking().FirstOrDefaultAsync(expression); else return await _context.Set<T>().FirstOrDefaultAsync(expression); } public async Task<T> Get<T>(object id) where T : BaseEntity { return await _context.Set<T>().FindAsync(id); } public IQueryable<T> Get<T>(bool noTracking = false) where T : BaseEntity { if (noTracking) return _context.Set<T>().Where(x => !x.Deleted).AsNoTracking(); else return _context.Set<T>().Where(x => !x.Deleted); } public IQueryable<T> Get<T>(Expression<Func<T, bool>> expression, bool noTracking = false) where T : BaseEntity { if (noTracking) return _context.Set<T>().Where(expression).AsNoTracking(); else return _context.Set<T>().Where(expression); } public IQueryable<T> Get<T>(Expression<Func<T, bool>> expression, int skip, int take, params string[] includes) where T : BaseEntity { var query = _context.Set<T>().Where(x => !x.Deleted).AsQueryable(); if (includes != null) { foreach (string include in includes) { query = query.Include(include).AsQueryable(); } } return query.Where(expression).Skip(skip).Take(take); } public IQueryable<T> Get<T>(Expression<Func<T, bool>> expression, params string[] includes) where T : BaseEntity { var query = _context.Set<T>().AsQueryable(); if (includes != null) { foreach (string include in includes) { query = query.Include(include).AsQueryable(); } } return query.Where(expression); } public IQueryable<T> Get<T>(Expression<Func<T, bool>> expression, bool noTracking = false, params string[] includes) where T : BaseEntity { if (noTracking) { var query = _context.Set<T>().Where(x => !x.Deleted).AsNoTracking().AsQueryable(); query = MakeIncludes<T>(query, includes); return query.Where(expression); } else { var query = _context.Set<T>().Where(x => !x.Deleted).AsQueryable(); query = MakeIncludes<T>(query, includes); return query.Where(expression); } } public IQueryable<T> GetWithDeleteds<T>(Expression<Func<T, bool>> expression, bool noTracking = false, params string[] includes) where T : BaseEntity { if (noTracking) { var query = _context.Set<T>().AsNoTracking().AsQueryable(); query = MakeIncludes<T>(query, includes); return query.Where(expression); } else { var query = _context.Set<T>().AsQueryable(); query = MakeIncludes<T>(query, includes); return query.Where(expression); } } private IQueryable<T> MakeIncludes<T>(IQueryable<T> query, string[] includes) where T : BaseEntity { if (includes != null) { foreach (string include in includes) { query = query.Include(include).AsQueryable(); } } return query; } #endregion } }
using Quartz; using System; using System.Net; using System.IO; using System.Text; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using System.Xml.Linq; using System.Collections.Generic; using MVCApplication.Models; namespace MVCApplication.Services.Harvest { public class HarvestService { private HttpWebResponse response = null; private DateTime today = DateTime.Today; private string HARVEST_ROOT_URI = "https://yandexru.harvestapp.com"; //Get Entries public IEnumerable<Entry> GetEntries(IEnumerable<int> projectIds) { var entries = new List<Entry>(); int daysToStartDate = -5; int daysToEndDate = -1; var startDate = today.AddDays(daysToStartDate).ToString("yyyyMMdd"); var endDate = today.AddDays(daysToEndDate).ToString("yyyyMMdd"); foreach (var projectId in projectIds) { string uri = String.Format ("{0}/projects/{1}/entries?from={2}&to={3}&billable=yes&is_closed=yes", HARVEST_ROOT_URI, projectId, startDate, endDate); try { var request = RequestHelper.MakeRequest(uri); using (response = request.GetResponse() as HttpWebResponse) { if (request.HaveResponse == true && response != null) { XDocument doc = RequestHelper.CreateXDocument(response); var elements = doc.Descendants("day-entry"); foreach (var entryElement in elements) { var entry = new Entry(); entry.UserId = Int32.Parse(entryElement.Element("user-id").Value); entry.ProjectId = Int32.Parse(entryElement.Element("project-id") .Value); entry.Hours = Decimal.Parse(entryElement.Element("hours").Value); entries.Add(entry); } } } } catch (WebException wex) { RequestHelper.CatchWebException(wex); } finally { RequestHelper.CloseResponse(response); } } return entries; } // Get projects public IEnumerable<Project> GetProjects() { int daysToStartDate = -5; var startDate = today.AddDays(daysToStartDate).ToString("yyyy-MM-dd"); string uri = String.Format ("{0}/projects?updated_since={1}", HARVEST_ROOT_URI, startDate); var projects = new List<Project>(); try { var request = RequestHelper.MakeRequest(uri); using (response = request.GetResponse() as HttpWebResponse) { if (request.HaveResponse == true && response != null) { XDocument doc = RequestHelper.CreateXDocument(response); var elements = doc.Descendants("project"); foreach (var entryElement in elements) { var project = new Project(); project.ClientId = Convert.ToInt32(entryElement.Element("client-id") .Value); project.ProjectId = Convert.ToInt32(entryElement.Element("id").Value); project.Name = entryElement.Element("name").Value; projects.Add(project); } } } } catch (WebException wex) { RequestHelper.CatchWebException(wex); } finally { RequestHelper.CloseResponse(response); } return projects; } public IEnumerable<User> GetUsers(IEnumerable<int> userIds) { var users = new List<User>(); foreach (var userId in userIds) { string uri = String.Format ("{0}/people/{1}", HARVEST_ROOT_URI, userId); try { var request = RequestHelper.MakeRequest(uri); using (response = request.GetResponse() as HttpWebResponse) { if (request.HaveResponse == true && response != null) { XDocument doc = RequestHelper.CreateXDocument(response); var elements = doc.Descendants("user"); foreach (var userElement in elements) { var user = new User(); user.Id = Convert.ToInt32(userElement.Element("id").Value); user.FirstName = userElement.Element("first-name").Value; user.LastName = userElement.Element("last-name").Value; user.HourlyRate = Decimal.Parse(userElement.Element("cost-rate") .Value); users.Add(user); } } } } catch (WebException wex) { RequestHelper.CatchWebException(wex); } finally { RequestHelper.CloseResponse(response); } } return users; } //Get Clients public IEnumerable<Client> GetClients(IEnumerable<int> clientIds) { var clients = new List<Client>(); foreach (var clientId in clientIds) { string uri = String.Format ("{0}/clients/{1}", HARVEST_ROOT_URI, clientId); try { var request = RequestHelper.MakeRequest(uri); using (response = request.GetResponse() as HttpWebResponse) { if (request.HaveResponse == true && response != null) { XDocument doc = RequestHelper.CreateXDocument(response); var elements = doc.Descendants("client"); foreach (var clientElement in elements) { var client = new Client(); client.Id = Convert.ToInt32(clientElement.Element("id").Value); client.Name = clientElement.Element("name").Value; client.Currency = clientElement.Element("currency").Value; client.Details = clientElement.Element("details").Value; ; clients.Add(client); } } } } catch (WebException wex) { RequestHelper.CatchWebException(wex); } finally { RequestHelper.CloseResponse(response); } } return clients; } } }
using System; namespace NetPayroll.Guides.Contract.Taxing { public class ContractTaxing2011 : ContractTaxingPrototype { public ContractTaxing2011() : base(new GuidesTaxing2011()) { } } }
using System.Windows; using System.Windows.Controls; using MusicPlayer.ViewModels.Interfaces; namespace MusicPlayer.UserControls { public partial class PlayerControl : UserControl { public double CurrentProgress; public PlayerControl() { InitializeComponent(); this.DataContext = IocKernel.IocKernel.Get<IPlayerViewModel>(); } } }
using PDV.DAO.Atributos; using System; namespace PDV.DAO.Entidades.MDFe { public class EventoMDFE { [CampoTabela("IDEVENTOMDFE")] public decimal IDEventoMDFE { get; set; } [CampoTabela("IDMOVIMENTOFISCALMDFE")] public decimal IDMovimentoFiscalMDFe { get; set; } [CampoTabela("NSEQEVENTO")] public decimal NSeqEvento { get; set; } [CampoTabela("DHEVENTO")] public DateTime? DHEvento { get; set; } [CampoTabela("DESCEVENTO")] public string DescEvento { get; set; } [CampoTabela("NPROT")] public string NProt { get; set; } [CampoTabela("XMOTIVO")] public string XMotivo { get; set; } [CampoTabela("CSTAT")] public decimal CSTAT { get; set; } [CampoTabela("TIPOEVENTO")] public decimal TipoEvento { get; set; } public EventoMDFE() { } } }
#region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.GamerServices; #endregion namespace floodControl { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D playingPieces; Texture2D backgroundScreen; Texture2D titleScreen; GameBoard board; Vector2 gameBoardDisplayOrigin = new Vector2(70, 89); int playerScore = 0; enum gameState { TitleScreen, Playing }; gameState state = gameState.TitleScreen; Rectangle emptyPiece = new Rectangle(1, 247, 40, 40); const float minTimeSunceLastInput = 0.25f; float timeSinceLastInput = 0.0f; public Game1() : base() { graphics = new GraphicsDeviceManager (this); Content.RootDirectory = "Content"; this.graphics.PreferredBackBufferWidth = 800; this.graphics.PreferredBackBufferHeight = 600; graphics.IsFullScreen = false; this.graphics.ApplyChanges(); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here board = new GameBoard(); base.Initialize(); } private int DetermineScore(int count) { return (int)((Math.Pow(count / 5, 2) + count) * 10); } private void CheckScoring(List<Vector2> waterChain) { if (waterChain.Count <= 0) return; Vector2 lastPipe = waterChain[waterChain.Count - 1]; if (lastPipe.X == GameBoard.w - 1 && board.HasConnector((int)lastPipe.X, (int)lastPipe.Y, "Right")) { playerScore += DetermineScore(waterChain.Count); foreach (Vector2 i in waterChain) { board.AddFadingPiece((int)i.X, (int)i.Y, board.GetSquare((int)i.X, (int)i.Y)); board.SetSquare((int)i.X, (int)i.Y, "Empty"); } } } private void HandleMouseInput(MouseState state) { int x = (state.X - (int)gameBoardDisplayOrigin.X) / GamePiece.w; int y = (state.Y - (int)gameBoardDisplayOrigin.Y) / GamePiece.h; if (x < 0 || x >= GameBoard.w || y < 0 || y >= GameBoard.h) return; if (state.LeftButton == ButtonState.Pressed) { board.RotatePiece(x, y, false); timeSinceLastInput = 0.0f; board.AddRotationPiece(x, y, board.GetSquare(x, y), false); } if (state.RightButton == ButtonState.Pressed) { board.RotatePiece(x, y, true); timeSinceLastInput = 0.0f; board.AddRotationPiece(x, y, board.GetSquare(x, y), true); } } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); playingPieces = Content.Load<Texture2D>("Textures/Tile_Sheet"); backgroundScreen = Content.Load<Texture2D>("Textures/Background"); titleScreen = Content.Load<Texture2D>("Textures/TitleScreen"); // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); // TODO: Add your update logic here if (state == gameState.TitleScreen) { if (Keyboard.GetState().IsKeyDown(Keys.Space)) { board.ClearBoard(); board.Generate(false); playerScore = 0; state = gameState.Playing; } } else if (state == gameState.Playing) { timeSinceLastInput += (float)gameTime.ElapsedGameTime.TotalSeconds; if (timeSinceLastInput >= minTimeSunceLastInput) { HandleMouseInput(Mouse.GetState()); } board.ResetWater(); //playerScore = 0; for (int y = 0; y < GameBoard.h; ++y) { CheckScoring(board.GetWaterChain(y)); } board.Generate(false); board.Update(); } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); if (state == gameState.TitleScreen) { spriteBatch.Draw(titleScreen, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White); } else if (state == gameState.Playing) { spriteBatch.Draw(backgroundScreen, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White); //Debug.Write("lol"); for (int x = 0; x < GameBoard.w; ++x) { for (int y = 0; y < GameBoard.h; ++y) { int px = (int)gameBoardDisplayOrigin.X + x * GamePiece.w; int py = (int)gameBoardDisplayOrigin.Y + y * GamePiece.h; DrawEmptyPiece(px, py); bool isDw = false; string posName = x.ToString() + "_" + y.ToString(); if (board.rotating.ContainsKey(posName)) { DrawRotatingPiece(px, py, posName); isDw = true; } if (board.fading.ContainsKey(posName)) { DrawFadingPiece(px, py, posName); isDw = true; } if (board.falling.ContainsKey(posName)) { DrawFallingPiece(px, py, posName); isDw = true; } if (!isDw) { DrawStandardPiece(x, y, px, py); } Window.Title = playerScore.ToString(); } } } spriteBatch.End(); base.Draw(gameTime); } private void DrawEmptyPiece(int x, int y) { spriteBatch.Draw(playingPieces, new Rectangle(x, y, GamePiece.w, GamePiece.h), emptyPiece, Color.White); } private void DrawStandardPiece(int x, int y, int px, int py) { spriteBatch.Draw(playingPieces, new Rectangle(px, py, GamePiece.w, GamePiece.h), board.GetRect(x, y), Color.White); } private void DrawFallingPiece(int x, int y, string posName) { spriteBatch.Draw(playingPieces, new Rectangle(x, y - board.falling[posName].offset, GamePiece.w, GamePiece.h), board.falling[posName].GetRect(), Color.White); } private void DrawFadingPiece(int x, int y, string posName) { spriteBatch.Draw(playingPieces, new Rectangle(x, y, GamePiece.w, GamePiece.h), board.falling[posName].GetRect(), Color.White * board.fading[posName].alphaLevel); } private void DrawRotatingPiece(int x, int y, string posName) { spriteBatch.Draw(playingPieces, new Rectangle(x + (GamePiece.w / 2), y + (GamePiece.h / 2), GamePiece.w, GamePiece.h), board.rotating[posName].GetRect(), Color.White, board.rotating[posName].RotationAmount, new Vector2(GamePiece.w / 2, GamePiece.h / 2), SpriteEffects.None, 0.0f); } } }
using nmct.ba.cashlessproject.crypto; using nmct.ba.cashlessproject.model.ASP.NET; using nmct.ba.cashlessproject.service.DataAccess; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; using System.Threading.Tasks; namespace nmct.ba.cashlessproject.service { public partial class CheckRegisters : ServiceBase { #region Properties private CancellationTokenSource cancellationTokenSource; private Task mainTask; #endregion #region Service methods public CheckRegisters() { cancellationTokenSource = new CancellationTokenSource(); mainTask = null; } public void OnDebug() { OnStart(null); } protected override void OnStart(string[] args) { mainTask = new Task(Poll, cancellationTokenSource.Token, TaskCreationOptions.LongRunning); mainTask.Start(); } protected override void OnStop() { cancellationTokenSource.Cancel(); mainTask.Wait(); } #endregion #region Register checking methods /* * Polling task. */ private void Poll() { CancellationToken cancellation = cancellationTokenSource.Token; TimeSpan interval = TimeSpan.Zero; while(!cancellation.WaitHandle.WaitOne(interval)) { try { List<Organisation> organisations = (List<Organisation>)OrganisationDA.GetOrganisations(); foreach(Organisation organisation in organisations) { List<Register> registers = GetListOfRegisters(organisation); List<Register> newRegisters = GetListOfNewRegisters(organisation, registers); List<Register> removedRegisters = GetListOfRemovedRegisters(organisation, registers); PostNewRegistersToOrganisation(organisation, newRegisters); DeleteRemovedRegistersFromOrganisation(organisation, removedRegisters); } if (cancellation.IsCancellationRequested) break; interval = TimeSpan.FromMinutes(1); } catch (Exception ex) { Console.WriteLine(ex.Message); interval = TimeSpan.FromMinutes(1); } } } /* * Get a list of all registers of an organisation. */ private List<Register> GetListOfRegisters(Organisation organisation) { List<Organisation_Register> orgRegs = (List<Organisation_Register>)OrganisationRegisterDA.GetOrganisationRegistersByOrganisationID(organisation.ID); List<Register> registers = new List<Register>(); foreach(Organisation_Register orgReg in orgRegs) { registers.Add(RegisterDA.GetRegister(orgReg.RegisterID)); } return registers; } /* * Check if new registers are added to database. */ private List<Register> GetListOfNewRegisters(Organisation organisation, List<Register> registers) { List<Register> newRegisters = new List<Register>(); List<Register> registersOfOrganisation = RegisterDA.GetRegistersOfOrganisation(organisation); foreach(Register register in registers) { if (!IsInList(register, registersOfOrganisation)) newRegisters.Add(register); } return newRegisters; } /* * Check if registers are removed from the database. */ private List<Register> GetListOfRemovedRegisters(Organisation organisation, List<Register> registers) { List<Register> removedRegisters = new List<Register>(); List<Register> registersOfOrganisation = RegisterDA.GetRegistersOfOrganisation(organisation); foreach(Register registerOfOrganisation in registersOfOrganisation) { if (!IsInList(registerOfOrganisation, registers)) removedRegisters.Add(registerOfOrganisation); } return removedRegisters; } /* * Check if a register is in list of registers. */ private Boolean IsInList(Register register, List<Register> registers1) { foreach(Register register1 in registers1) { if (register.RegisterName == register1.RegisterName) return true; } return false; } /* * Post registers to an organisation. */ private void PostNewRegistersToOrganisation(Organisation organisation, List<Register> registers) { foreach(Register register in registers) { if(IsInactive(organisation, register)) RegisterDA.ActivateOrganisationRegister(organisation, register); else { int id = RegisterDA.PostRegisterOfOrganisation(organisation, register); } } } /* * Check if register is inactive in organisation DB. */ private Boolean IsInactive(Organisation organisation, Register register) { List<Register> registersOfOrganisation = RegisterDA.GetRegistersOfOrganisationAndInactive(organisation); foreach(Register registerOfOrganisation in registersOfOrganisation) { if (registerOfOrganisation.ID == register.ID) return true; } return false; } /* * Delete register from an organisation. */ private void DeleteRemovedRegistersFromOrganisation(Organisation organisation, List<Register> registers) { foreach(Register register in registers) { int id = RegisterDA.DeleteRegisterOfOrganisation(organisation, register); } } #endregion } }
using Ghost.Utils; using System; using UnityEngine; namespace RO { [CustomLuaClass] public sealed class CameraInputController : InputController { public float angleOneDistance = 10f; public Vector2 rotationMin; public Vector2 rotationMax; private Vector3 originalCameraRotation; private Vector3 cameraRotationMin; private Vector3 cameraRotationMax; public bool enable; public bool noClamp; public CameraController cameraController; private bool inited; public Vector3 centerPoint { get; set; } public CameraInputController(InputHelper[] ihs) : base(ihs) { } protected override bool DoAllowInterruptedBy(State other) { return other is DefaultInputController || other is CameraFieldOfViewInputController || other is CameraGyroInputController || base.DoAllowInterruptedBy(other); } protected override bool DoEnter() { if (!base.DoEnter()) { return false; } if (null == this.cameraController) { return false; } this.inited = false; return true; } protected override void DoUpdate() { base.DoUpdate(); if (0 >= base.touchingCount) { base.Exit(); } else if (!this.inited && this.enable) { this.inited = true; this.originalCameraRotation = this.cameraController.cameraRotationEuler; this.cameraRotationMin.x = this.rotationMin.x; this.cameraRotationMax.x = this.rotationMax.x; this.cameraRotationMin.y = this.originalCameraRotation.y + this.rotationMin.y; this.cameraRotationMax.y = this.originalCameraRotation.y + this.rotationMax.y; this.cameraRotationMin.z = this.originalCameraRotation.z; this.cameraRotationMax.z = this.originalCameraRotation.z; } } protected override void OnTouchBegin() { if (base.pointerID == 0) { return; } if (base.isOverUI) { return; } } protected override void OnTouchMoved() { if (base.pointerID != 0) { return; } if (!this.inited) { return; } if (null == this.cameraController) { return; } Vector3 vector = new Vector3(-(base.touchPoint.y - this.centerPoint.y) / this.angleOneDistance, (base.touchPoint.x - this.centerPoint.x) / this.angleOneDistance, 0f); Vector3 rotation = this.originalCameraRotation + vector; if (!this.noClamp) { float num = GeometryUtils.UniformAngle180(rotation.x); num = Mathf.Clamp(num, this.cameraRotationMin.x, this.cameraRotationMax.x); rotation.x = GeometryUtils.UniformAngle(num); } this.cameraController.ResetRotation(rotation); } protected override void OnTouchEnd() { if (0 < base.touchingCount) { return; } base.DelayExit(); } protected override bool allowExtra() { return 0 < base.pointerID; } } }
using System.Collections.Generic; using Escc.Umbraco.PropertyEditors.App_Plugins.Escc.Umbraco.PropertyEditors.RichTextPropertyEditor; namespace Escc.EastSussexGovUK.UmbracoDocumentTypes.RichTextPropertyEditor { /// <summary> /// A more permissive customised rich text editor data type, intended for hidden author notes /// </summary> public static class RichTextAuthorNotesDataType { /// <summary> /// The display name of the data type /// </summary> public const string DataTypeName = "Rich text: author notes"; /// <summary> /// Creates the data type. /// </summary> public static void CreateDataType() { var editorSettings = RichTextPropertyEditorEsccWebsiteSettings.CreateDefaultPreValues(); editorSettings.toolbar = new List<string>(editorSettings.toolbar) { TinyMceButtons.StyleSelect, TinyMceButtons.Table, TinyMceButtons.Blockquote, TinyMceButtons.UmbracoMediaPicker, TinyMceButtons.Hr, TinyMceButtons.Strikethrough }.ToArray(); editorSettings.stylesheets = new List<string>(editorSettings.stylesheets) { RichTextPropertyEditorEsccWebsiteSettings.StylesheetHeadings, RichTextPropertyEditorEsccWebsiteSettings.StylesheetEmbed }.ToArray(); editorSettings.validators = new Validator[0]; RichTextDataTypeService.InsertDataType(DataTypeName, editorSettings); } } }
using UnityEngine; using System.Collections; public class HumanAIAttackController : MonoBehaviour { //movement variables public float moveSpeed = 10.0f; public float rotateSpeed = 20.0f; //ranges public float minRange = 20.0f; public float attackRange = 60.0f; public float fireRate = 2.0f; public Transform bullet; private GameObject player; private PlayerPhysics playerPhysics; void Awake() { player = GameObject.FindWithTag("player"); playerPhysics = player.GetComponent<PlayerPhysics>(); } void LateUpdate () { ProcessMotion(); } void ProcessMotion() { Vector3 targetDir = player.transform.position - transform.position; float dist = Vector3.Distance(player.transform.position, transform.position); //chase if (playerPhysics.zombieStates != PlayerPhysics.ZombieState.fullHuman) { transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(targetDir), rotateSpeed); transform.rotation = Quaternion.Euler(0, transform.eulerAngles.y, 0); if (dist > minRange) { transform.position += transform.forward * moveSpeed * Time.deltaTime; } //attack if (dist < attackRange && !IsInvoking("Shoot")) { Invoke("Shoot", fireRate); } } } //shoot void Shoot() { Instantiate(bullet, transform.position, transform.rotation); } }
namespace OptGui.Services { using System; using System.Collections.ObjectModel; using System.Diagnostics; /// <summary> /// Defines the <see cref="IProblemType1918" />. /// </summary> public interface IProblemType1918 { /// <summary> /// Gets or sets the Rows. /// </summary> ObservableCollection<KnapsackRow> Rows { get; set; } /// <summary> /// Gets or sets the StageCount. /// </summary> int StageCount { set; get; } /// <summary> /// Gets or sets the DecisionObservableCollections. /// </summary> ObservableCollection<ObservableCollection<double>> DecisionObservableCollections { get; set; } /// <summary> /// Gets or sets the RecursiveReturnsObservableCollections. /// </summary> ObservableCollection<ObservableCollection<double>> RecursiveReturnsObservableCollections { get; set; } /// <summary> /// Gets the StageTable. /// </summary> ObservableCollection<ObservableCollection<double>> StageTable { get; } /// <summary> /// Gets the OptimalPolicy. /// </summary> double OptimalPolicy { get; } } /// <summary> /// Defines the <see cref="KnapsackSolver" />. /// </summary> public class KnapsackSolver : IProblemType1918 { /// <summary> /// Gets or sets the Rows. /// </summary> public ObservableCollection<KnapsackRow> Rows { get; set; } /// <summary> /// Gets or sets the StageCount. /// </summary> public int StageCount { set; get; } /// <summary> /// Gets or sets the DecisionObservableCollections. /// </summary> public ObservableCollection<ObservableCollection<double>> DecisionObservableCollections { get; set; } /// <summary> /// Gets or sets the RecursiveReturnsObservableCollections. /// </summary> public ObservableCollection<ObservableCollection<double>> RecursiveReturnsObservableCollections { get; set; } /// <summary> /// Gets the StageTable. /// </summary> public ObservableCollection<ObservableCollection<double>> StageTable { get { var table = new ObservableCollection<ObservableCollection<double>>(); for (int i = this.StageCount; i >= 0; i--) { table.Add(this.RecursiveReturnsObservableCollections[i]); table.Add(this.DecisionObservableCollections[i]); } return table; } } /// <summary> /// Gets the OptimalPolicy. /// </summary> public double OptimalPolicy { get; } /// <summary> /// Initializes a new instance of the <see cref="KnapsackSolver"/> class. /// </summary> public KnapsackSolver() { this.Rows = new ObservableCollection<KnapsackRow>(); } /// <summary> /// Adds a <see cref="KnapsackRow"/> to the ObservableCollection of data points. /// </summary> /// <param name="name">The name<see cref="string"/>.</param> /// <param name="weight">The weight<see cref="double"/>.</param> /// <param name="value">The value<see cref="double"/>.</param> public void AddRow(string name, double weight, double value) { this.Rows.Add(new KnapsackRow(name, weight, value)); } /// <summary> /// Removes a <see cref="KnapsackRow"/> from the ObservableCollection of data points by a given index. /// </summary> /// <param name="index">The index<see cref="int"/>.</param> public void RemoveRow(int index) { this.Rows.RemoveAt(index); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MySql.Data.MySqlClient; using PetaPoco; using SM.Entities.Model; using SM.Entities.OrderEnum; using SM.Entities.SearchModel; namespace SM.DAL { public class CargoTypeDAL { /// <summary> /// 获取货物类型实体 /// </summary> /// <param name="id"></param> /// <returns></returns> public CargoType GetCargoTypeById(int id) { return DatabaseProvider.SingleOrDefault<CargoType>(id); } /// <summary> /// 新增货物类型实体 /// </summary> /// <param name="item"></param> /// <returns></returns> public bool AddCargoType(CargoType item) { var obj = DatabaseProvider.Insert(item); if (obj != null) { return Convert.ToInt32(obj) > 0; } return false; } /// <summary> /// 修改货物类型实体 /// </summary> /// <param name="item"></param> /// <returns></returns> public bool UpdateCargoType(CargoType item) { var obj = DatabaseProvider.Update(item); return Convert.ToInt32(obj) > 0; } /// <summary> /// 获取货物类型列表 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="searchEntity"></param> /// <param name="orderEnums"></param> /// <param name="recordCount"></param> /// <returns></returns> public List<CargoType> GetListByPager(int pageIndex, int pageSize, SearchCargoType searchEntity, IEnumerable<CargoTypeEnum> orderEnums, out int recordCount) { string sqlStr = @"select * from cargotype t"; Sql sql = AppendSqlWhere(sqlStr, "t", searchEntity); if (orderEnums != null && orderEnums.Any()) { sql = sql.OrderByT(orderEnums); } return DatabaseProvider.GetEntitiesByPager<CargoType>(pageIndex, pageSize, sql, out recordCount); } /// <summary> /// 附加where条件 /// </summary> /// <param name="initSqlString">sql字符串</param> /// <param name="tableAlias">topic表在查询中的别名</param> /// <param name="searchEntity">查询条件实体</param> /// <returns></returns> public Sql AppendSqlWhere(string initSqlString, string tableAlias, SearchCargoType searchEntity) { Sql sql = Sql.Builder.Append(initSqlString); if (!string.IsNullOrEmpty(searchEntity.CargoNameLike)) { sql.Where(string.Format(" {0}.CargoName like '%{1}%'", tableAlias, searchEntity.CargoNameLike)); } return sql; } } }
using Logs.Data.Contracts; using Logs.Factories; using Logs.Models; using Moq; using NUnit.Framework; using System.Collections.Generic; using System.Linq; namespace Logs.Services.Tests.NutritionServiceTests { [TestFixture] public class GetUserNutritionsSortedByDateTests { [TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95")] [TestCase("99ae8dd3-1067-4141-9675-62e94bb6caaa")] public void TestGetUserNutritionsSortedByDate_ShouldCallRepositoryAll(string userId) { // Arrange var mockedNutritionRepository = new Mock<IRepository<Nutrition>>(); var mockedUnitOfWork = new Mock<IUnitOfWork>(); var mockedFactory = new Mock<INutritionFactory>(); var service = new NutritionService(mockedNutritionRepository.Object, mockedUnitOfWork.Object, mockedFactory.Object); // Act service.GetUserNutritionsSortedByDate(userId); // Assert mockedNutritionRepository.Verify(r => r.All, Times.Once); } [TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95")] [TestCase("99ae8dd3-1067-4141-9675-62e94bb6caaa")] public void TestGetUserNutritionsSortedByDate_ShouldFilterAndReturnCorrectly(string userId) { // Arrange var nutritions = new List<Nutrition> { new Nutrition {UserId=userId }, new Nutrition {UserId=userId }, new Nutrition () }.AsQueryable(); var mockedNutritionRepository = new Mock<IRepository<Nutrition>>(); mockedNutritionRepository.Setup(r => r.All).Returns(nutritions); var mockedUnitOfWork = new Mock<IUnitOfWork>(); var mockedFactory = new Mock<INutritionFactory>(); var service = new NutritionService(mockedNutritionRepository.Object, mockedUnitOfWork.Object, mockedFactory.Object); var expected = nutritions.Where(m => m.UserId == userId); // Act var result = service.GetUserNutritionsSortedByDate(userId); // Assert CollectionAssert.AreEqual(expected, result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnitedPigeonAirlines.Data.Entities.OrderAggregate; namespace UnitedPigeonAirlines.Data.Repositories { public interface IOrderRepository { List<Order> GetAllOrders(); void SaveOrder(Order order); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Aqueduct.Mail { public interface IEmail { void Send(); MailMessage CreateMessage(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Game1 { public class Canon : MoveableItem { public int frames; public Canon() { textureTest = Game1.cManager.Load<Texture2D>("themes/" + Game1.world.currentTheme + "/items/Canon"); } public Canon(ContentManager content, float x, float y, float width, float height) : base(content, x, y, width, height) { textureTest = content.Load<Texture2D>("themes/" + Game1.world.currentTheme + "/items/Canon"); } public override void Update() { if (frames % 120 == 119) { Game1.world.addItem(new CanonBall(Game1.cManager, pos.X, pos.Y, size.X, size.Y, MapTools.AngleToVector(angle - (float)Math.PI * 0.5f))); frames = 0; } frames++; base.Update(); } public override void reset() { frames = 0; base.reset(); } } }
using System; using System.Collections.Generic; using UnityEngine; namespace Action { [Serializable] public class StateMachine { List<State> states = new List<State>(); State currentState; int statesCount = 0; public void Register(State state) { states.Add(state); statesCount = states.Count; } public void Start() { var startState = GetShouldStartState(limitState:null); ChangeState(startState); } public void Update() { var shouldChangeState = GetShouldStartState(currentState); if (shouldChangeState != null) { ChangeState(shouldChangeState); } if (currentState == null) { return; } currentState.Update(); if (currentState.ShouldEnd()) { var nextState = GetShouldStartState(limitState:null); if (nextState == null) { Debug.LogError("Not found start state. There must be a state to start."); return; } ChangeState(nextState); } } public void End() { currentState?.End(); } void ChangeState(State changeState) { currentState?.End(); currentState = changeState; currentState.Start(); } State GetShouldStartState(State limitState) { var isSetLimit = (limitState != null); for (var checkIdx = 0; checkIdx < statesCount; checkIdx++) { var state = states[checkIdx]; if (isSetLimit && state == limitState) { break; } if (state.ShouldStart()) { return state; } } return null; } #if TEST public void SwapInput(UInput.InputComponet input) { foreach (var state in states) { state.SwapInput(input); } } public State GetCurrentState() { return currentState; } #endif //TEST } } // namespace Action
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet.Win32.SafeHandles; using NtApiDotNet.Win32.Security.Native; using System; using System.Security; namespace NtApiDotNet.Win32.Security.Sam { /// <summary> /// Class to represent a SAM user. /// </summary> public class SamUser : SamObject { #region Private Members private NtResult<T> Query<T, S>(UserInformationClass info_class, Func<S, T> func, bool throw_on_error) where S : struct { return SecurityNativeMethods.SamQueryInformationUser(Handle, info_class, out SafeSamMemoryBuffer buffer).CreateResult(throw_on_error, () => { using (buffer) { buffer.Initialize<S>(1); return func(buffer.Read<S>(0)); } }); } #endregion #region Internal Members internal SamUser(SafeSamHandle handle, SamUserAccessRights granted_access, string server_name, string user_name, Sid sid) : base(handle, granted_access, SamUtils.SAM_USER_NT_TYPE_NAME, user_name, server_name) { Sid = sid; Name = user_name; } #endregion #region Public Methods /// <summary> /// Get full name for the user. /// </summary> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The full name of the user.</returns> public NtResult<string> GetFullName(bool throw_on_error) { return Query(UserInformationClass.UserFullNameInformation, (USER_FULL_NAME_INFORMATION f) => f.FullName.ToString(), throw_on_error); } /// <summary> /// Get home directory for the user. /// </summary> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The home directory of the user.</returns> public NtResult<string> GetHomeDirectory(bool throw_on_error) { return Query(UserInformationClass.UserHomeInformation, (USER_HOME_INFORMATION f) => f.HomeDirectory.ToString(), throw_on_error); } /// <summary> /// Get primary group ID for the user. /// </summary> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The primary group ID of the user.</returns> public NtResult<uint> GetPrimaryGroupId(bool throw_on_error) { return Query(UserInformationClass.UserPrimaryGroupInformation, (USER_PRIMARY_GROUP_INFORMATION f) => f.PrimaryGroupId, throw_on_error); } /// <summary> /// Get user account control flags for the user. /// </summary> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The user account control flags of the user.</returns> public NtResult<UserAccountControlFlags> GetUserAccountControl(bool throw_on_error) { return Query(UserInformationClass.UserControlInformation, (USER_CONTROL_INFORMATION f) => (UserAccountControlFlags)f.UserAccountControl, throw_on_error); } /// <summary> /// Change a user's password. /// </summary> /// <param name="old_password">The old password.</param> /// <param name="new_password">The new password.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public NtStatus ChangePassword(SecureString old_password, SecureString new_password, bool throw_on_error) { using (var list = new DisposableList()) { var old_pwd_buf = list.AddResource(new SecureStringMarshalBuffer(old_password)); var new_pwd_buf = list.AddResource(new SecureStringMarshalBuffer(new_password)); return SecurityNativeMethods.SamChangePasswordUser(Handle, new UnicodeStringSecure(old_pwd_buf, old_password.Length), new UnicodeStringSecure(new_pwd_buf, new_password.Length)).ToNtException(throw_on_error); } } /// <summary> /// Change a user's password. /// </summary> /// <param name="old_password">The old password.</param> /// <param name="new_password">The new password.</param> public void ChangePassword(SecureString old_password, SecureString new_password) { ChangePassword(old_password, new_password, true); } /// <summary> /// Set a user's password. /// </summary> /// <param name="password">The password to set.</param> /// <param name="expired">Whether the password has expired.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public NtStatus SetPassword(SecureString password, bool expired, bool throw_on_error) { using (var pwd_buf = new SecureStringMarshalBuffer(password)) { var set_info = new USER_SET_PASSWORD_INFORMATION(); set_info.Password = new UnicodeStringInSecure(pwd_buf, password.Length); set_info.PasswordExpired = expired; using (var buf = set_info.ToBuffer()) { return SecurityNativeMethods.SamSetInformationUser(Handle, UserInformationClass.UserSetPasswordInformation, buf).ToNtException(throw_on_error); } } } /// <summary> /// Set a user's password. /// </summary> /// <param name="password">The password to set.</param> /// <param name="expired">Whether the password has expired.</param> public void SetPassword(SecureString password, bool expired) { SetPassword(password, expired, true); } #endregion #region Public Properties /// <summary> /// The user name. /// </summary> public string Name { get; } /// <summary> /// The SID of the user. /// </summary> public Sid Sid { get; } /// <summary> /// Get full name for the user. /// </summary> public string FullName => GetFullName(true).Result; /// <summary> /// Get home directory for the user. /// </summary> public string HomeDirectory => GetHomeDirectory(true).Result; /// <summary> /// Get user account control flags for the user. /// </summary> public UserAccountControlFlags UserAccountControl => GetUserAccountControl(true).Result; /// <summary> /// Is the account disabled? /// </summary> public bool Disabled => UserAccountControl.HasFlagSet(UserAccountControlFlags.AccountDisabled); /// <summary> /// Get the primary group SID. /// </summary> public Sid PrimaryGroup => Sid.CreateSibling(GetPrimaryGroupId(true).Result); #endregion } }
using UnityEngine; public class Grid { int width; int height; float cellSize; int[,] gridArray; public Grid(int _width, int _height, float _cellsize) { width = _width; height = _height; cellSize = _cellsize; gridArray = new int[width, height]; for (int x = 0; x < gridArray.GetLength(0); x++) { for (int y = 0; y < gridArray.GetLength(1); y++) { Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x, y + 1), Color.white, 100f); Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x + 1, y), Color.white, 100f); } } Debug.DrawLine(GetWorldPosition(width, 0), GetWorldPosition(width, height), Color.white, 100f); } private Vector3 GetWorldPosition(int x, int y) { return new Vector3(x, y) * cellSize; } private void GetXY(Vector3 worldPosition, out int x, out int y) { x = Mathf.FloorToInt(worldPosition.x / cellSize); y = Mathf.FloorToInt(worldPosition.y / cellSize); } public void SetValue(int x, int y, int value) { if (x >= 0 && y >= 0 && x <= width && y <= height) { gridArray[x, y] = value; } } public void SetValue(Vector3 worldPosition, int value) { int x, y; GetXY(worldPosition, out x, out y); SetValue(x, y, value); } public int GetValue(int x, int y) { if (x >= 0 && y >= 0 && x <= width && y <= height) { return gridArray[x, y]; } else { return 0; } } public int GetValue(Vector3 worldPosition) { int x, y; GetXY(worldPosition, out x, out y); return GetValue(x, y); } }
namespace PRGTrainer.Shared.EncryptString { /// <summary> /// Интерфейс шифровальщика. /// </summary> public interface IEncrypter { /// <summary> /// Шифрование стоки. /// </summary> /// <param name="value">Строка, которую предстоит зашифровать.</param> /// <returns>Зашифрованная строка.</returns> string Encrypt(string value); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MedicinesInStockDatabase { public class MedicineInStock : Medicine { private int _amount; private float _cost; private string _pharmacyId; public MedicineInStock(string id, string name, string manufacturer, string amount, string cost, string pharmacyId) : base(id, name, manufacturer) { _amount = int.Parse(amount); _cost = float.Parse(cost); _pharmacyId = pharmacyId; } public int Amount { get { return this._amount; } set { this._amount = value; } } public float Cost { get { return this._cost; } set { this._cost = value; } } public string PharmacyId { get { return this._pharmacyId; } set { this._pharmacyId = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DistanceFriends { class Program { static void Main(string[] args) { Console.WriteLine("Distancia entre amigos"); List<ListaDistancia> listaAmigos = new List<ListaDistancia>(); double distancia; Calculo calculo = new Calculo(); //Amigo1 distancia = calculo.CalculoDistancia(28.5418, 77.2314, -23.633773, -46.626198); listaAmigos.Add(new ListaDistancia() { Amigo = "Amigo1", Distancia = distancia }); //Amigo2 distancia = calculo.CalculoDistancia(28.5418, 77.2314, -22.783146, -50.307419); listaAmigos.Add(new ListaDistancia() { Amigo = "Amigo2", Distancia = distancia }); //Amigo3 distancia = calculo.CalculoDistancia(28.5418, 77.2314, -22.927824, -45.495572); listaAmigos.Add(new ListaDistancia() { Amigo = "Amigo3", Distancia = distancia }); //Amigo4 distancia = calculo.CalculoDistancia(28.5418, 77.2314, -27.646620, -48.670361); listaAmigos.Add(new ListaDistancia() { Amigo = "Amigo4", Distancia = distancia }); //Amigo5 distancia = calculo.CalculoDistancia(28.5418, 77.2314, -26.304516, -48.843380); listaAmigos.Add(new ListaDistancia() { Amigo = "Amigo5", Distancia = distancia }); //Amigo6 distancia = calculo.CalculoDistancia(28.5418, 77.2314, -22.240088, -42.054329); listaAmigos.Add(new ListaDistancia() { Amigo = "Amigo6", Distancia = distancia }); var resultado = (from t in listaAmigos orderby t.Distancia ascending select t).Take(3); foreach (var item in resultado) { Console.WriteLine(item.Amigo + " mais proximo. Distancia " + item.Distancia); } Console.Read(); } private class ListaDistancia { public string Amigo { get; set; } public double Distancia { get; set; } } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_GradientAlphaKey : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { float num; LuaObject.checkType(l, 2, out num); float num2; LuaObject.checkType(l, 3, out num2); GradientAlphaKey gradientAlphaKey = new GradientAlphaKey(num, num2); LuaObject.pushValue(l, true); LuaObject.pushValue(l, gradientAlphaKey); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_alpha(IntPtr l) { int result; try { GradientAlphaKey gradientAlphaKey; LuaObject.checkValueType<GradientAlphaKey>(l, 1, out gradientAlphaKey); LuaObject.pushValue(l, true); LuaObject.pushValue(l, gradientAlphaKey.alpha); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_alpha(IntPtr l) { int result; try { GradientAlphaKey gradientAlphaKey; LuaObject.checkValueType<GradientAlphaKey>(l, 1, out gradientAlphaKey); float alpha; LuaObject.checkType(l, 2, out alpha); gradientAlphaKey.alpha = alpha; LuaObject.setBack(l, gradientAlphaKey); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_time(IntPtr l) { int result; try { GradientAlphaKey gradientAlphaKey; LuaObject.checkValueType<GradientAlphaKey>(l, 1, out gradientAlphaKey); LuaObject.pushValue(l, true); LuaObject.pushValue(l, gradientAlphaKey.time); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_time(IntPtr l) { int result; try { GradientAlphaKey gradientAlphaKey; LuaObject.checkValueType<GradientAlphaKey>(l, 1, out gradientAlphaKey); float time; LuaObject.checkType(l, 2, out time); gradientAlphaKey.time = time; LuaObject.setBack(l, gradientAlphaKey); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.GradientAlphaKey"); LuaObject.addMember(l, "alpha", new LuaCSFunction(Lua_UnityEngine_GradientAlphaKey.get_alpha), new LuaCSFunction(Lua_UnityEngine_GradientAlphaKey.set_alpha), true); LuaObject.addMember(l, "time", new LuaCSFunction(Lua_UnityEngine_GradientAlphaKey.get_time), new LuaCSFunction(Lua_UnityEngine_GradientAlphaKey.set_time), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_GradientAlphaKey.constructor), typeof(GradientAlphaKey), typeof(ValueType)); } }
using System; using System.Data; using System.Text; namespace DriveMgr.Common { /// <summary> /// Easyui Datagrid/Treegrid Toolbar帮助类 /// </summary> public class ToolbarHelper { /// <summary> /// 输出操作按钮 /// </summary> /// <param name="dt">根据用户id和菜单标识码得到的用户可以操作的此菜单下的按钮集合</param> /// <param name="pageName">当前页面名称,方便拼接js函数名</param> public static string GetToolBar(DataTable dt, string pageName) { StringBuilder sb = new StringBuilder(); sb.Append("{\"toolbar\":["); for (int i = 0; i < dt.Rows.Count; i++) { switch (dt.Rows[i]["Code"].ToString()) { case "add": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_add();\"},"); break; case "edit": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_edit();\"},"); break; case "delete": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_delete();\"},"); break; case "setrole": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_role();\"},"); break; case "setdepartment": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_department();\"},"); break; case "authorize": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_authorize();\"},"); break; case "export": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_export();\"},"); break; case "setbutton": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_setbutton();\"},"); break; case "expandall": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_expandall();\"},"); break; case "collapseall": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_collapseall();\"},"); break; case "pay": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_pay();\"},"); break; case "paytuition": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_paytuition();\"},"); break; case "payExam": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_payExam();\"},"); break; case "exit": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_exit();\"},"); break; case "setupnew": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_setupnew();\"},"); break; case "preAppointment": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_preAppointment();\"},"); break; case "autoDistributeVehicle": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_autoDistributeVehicle();\"},"); break; case "autoDistributeStu": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_autoDistributeStu();\"},"); break; case "byCard": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_byCard();\"},"); break; case "printer": sb.Append("{\"text\": \"" + dt.Rows[i]["Name"] + "\",\"iconCls\":\"" + dt.Rows[i]["Icon"] + "\",\"handler\":\"" + pageName + "_printer();\"},"); break; default: //browser不是按钮 break; } } bool flag = true; //是否有浏览权限 DataRow[] row = dt.Select("code = 'browser'"); if (row.Length == 0) //没有浏览权限 { flag = false; if (dt.Rows.Count > 0) sb.Remove(sb.Length - 1, 1); } else { if (dt.Rows.Count > 1) sb.Remove(sb.Length - 1, 1); } sb.Append("],\"success\":true,"); if (flag) sb.Append("\"browser\":true}"); else sb.Append("\"browser\":false}"); return sb.ToString(); } } }
using System.Collections.Generic; using System.Linq; namespace Benchmark.Benchmarks { using System; using System.Collections.ObjectModel; using BenchmarkDotNet.Attributes; /* * TODO: Collection_FastLinq is worse - not meant to be faster alone but allows us to stay in the ICollection interface * * Method | EnumerateAfterwards | Mean | Error | StdDev | Gen 0 | Allocated | ------------------------ |-------------------- |------------:|------------:|-----------:|-------:|----------:| Enumerable_System | False | 13.8531 ns | 7.6531 ns | 0.4324 ns | 0.0171 | 72 B | Enumerable_Optimal | False | 0.8169 ns | 0.5360 ns | 0.0303 ns | - | 0 B | Enumerable_System | True | 404.1512 ns | 370.9796 ns | 20.9610 ns | 0.0401 | 168 B | Enumerable_Optimal | True | 153.9279 ns | 28.9223 ns | 1.6342 ns | 0.0226 | 96 B | Collection_System | False | 14.1781 ns | 3.7421 ns | 0.2114 ns | 0.0171 | 72 B | Collection_FastLinq | False | 28.3557 ns | 22.0482 ns | 1.2458 ns | 0.0247 | 104 B | Collection_Optimal | False | 10.3005 ns | 0.9645 ns | 0.0545 ns | - | 0 B | Collection_System | True | 489.9000 ns | 363.5197 ns | 20.5395 ns | 0.0362 | 152 B | Collection_FastLinq | True | 493.7783 ns | 145.6884 ns | 8.2317 ns | 0.0429 | 184 B | Collection_Optimal | True | 80.9507 ns | 6.1558 ns | 0.3478 ns | - | 0 B | CollectionList_System | False | 13.8261 ns | 5.8454 ns | 0.3303 ns | 0.0171 | 72 B | CollectionList_FastLinq | False | 27.1457 ns | 26.6151 ns | 1.5038 ns | 0.0247 | 104 B | CollectionList_Optimal | False | 10.4806 ns | 0.7217 ns | 0.0408 ns | - | 0 B | CollectionList_System | True | 433.2741 ns | 184.5974 ns | 10.4301 ns | 0.0362 | 152 B | CollectionList_FastLinq | True | 451.3501 ns | 290.2735 ns | 16.4010 ns | 0.0434 | 184 B | CollectionList_Optimal | True | 54.3423 ns | 17.5528 ns | 0.9918 ns | - | 0 B | ListCollection_System | False | 13.6549 ns | 8.0486 ns | 0.4548 ns | 0.0171 | 72 B | ListCollection_FastLinq | False | 28.0917 ns | 20.5107 ns | 1.1589 ns | 0.0247 | 104 B | ListCollection_Optimal | False | 9.9016 ns | 1.7115 ns | 0.0967 ns | - | 0 B | ListCollection_System | True | 422.8167 ns | 50.3091 ns | 2.8426 ns | 0.0362 | 152 B | ListCollection_FastLinq | True | 505.0638 ns | 54.8945 ns | 3.1016 ns | 0.0434 | 184 B | ListCollection_Optimal | True | 54.1247 ns | 22.5877 ns | 1.2762 ns | - | 0 B | List_System | False | 13.6497 ns | 3.8314 ns | 0.2165 ns | 0.0171 | 72 B | List_FastLinq | False | 9.7044 ns | 3.9397 ns | 0.2226 ns | 0.0076 | 32 B | List_Optimal | False | 0.6208 ns | 2.1544 ns | 0.1217 ns | - | 0 B | List_System | True | 441.1774 ns | 353.3933 ns | 19.9674 ns | 0.0362 | 152 B | List_FastLinq | True | 212.2858 ns | 83.4322 ns | 4.7141 ns | 0.0074 | 32 B | List_Optimal | True | 18.7904 ns | 8.2715 ns | 0.4674 ns | - | 0 B | IList_System | False | 14.0431 ns | 5.8969 ns | 0.3332 ns | 0.0171 | 72 B | IList_FastLinq | False | 9.3813 ns | 4.8397 ns | 0.2735 ns | 0.0076 | 32 B | IList_Optimal | False | 0.5302 ns | 0.1910 ns | 0.0108 ns | - | 0 B | IList_System | True | 409.2205 ns | 27.0639 ns | 1.5292 ns | 0.0362 | 152 B | IList_FastLinq | True | 317.3828 ns | 235.1893 ns | 13.2886 ns | 0.0072 | 32 B | IList_Optimal | True | 62.3989 ns | 23.3150 ns | 1.3173 ns | - | 0 B | Array_System | False | 13.6173 ns | 6.2241 ns | 0.3517 ns | 0.0171 | 72 B | Array_FastLinq | False | 9.2286 ns | 2.5248 ns | 0.1427 ns | 0.0076 | 32 B | Array_Optimal | False | 0.3518 ns | 1.3517 ns | 0.0764 ns | - | 0 B | Array_System | True | 400.9441 ns | 39.4488 ns | 2.2289 ns | 0.0319 | 136 B | Array_FastLinq | True | 205.7276 ns | 108.8946 ns | 6.1527 ns | 0.0074 | 32 B | Array_Optimal | True | 11.2031 ns | 1.2035 ns | 0.0680 ns | - | 0 B | */ /// <summary> /// Enumerable.Concat just uses IEnumerator, so List, Array, IEnumerable /// /// FastLinq optimizes ICollection and IList+IList /// </summary> public class ConcatBenchmark { /// <summary> /// Probably best to isolate the testing of the enumeration to the underlying class /// but since I'm here right now and thinking about the implementation of ICollection+IList, /// adding the test here /// </summary> [Params(true, false)] public bool EnumerateAfterwards; private int[] array; private List<int> list; // HashSet is ICollection, not IList, and has a struct enumerator private HashSet<int> collection; // ReadOnlyCollection is IList, but has an object enumerator private ReadOnlyCollection<int> ilist; private IEnumerable<int> enumerable; [GlobalSetup] public void Setup() { this.enumerable = Enumerable.Range(0, 10); this.array = enumerable.ToArray(); this.list = enumerable.ToList(); this.collection = new HashSet<int>(this.list); this.ilist = new ReadOnlyCollection<int>(this.list); } [Benchmark] [BenchmarkCategory("System", "Enumerable")] public void Enumerable_System() { var concat = Enumerable.Concat(this.enumerable, this.enumerable); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("System", "Collection")] public void Collection_System() { var concat = Enumerable.Concat(this.collection, this.collection); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("System", "Collection", "List")] public void CollectionList_System() { var concat = Enumerable.Concat(this.collection, this.list); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("System", "Collection", "List")] public void ListCollection_System() { var concat = Enumerable.Concat(this.list, this.collection); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("System", "List")] public void List_System() { var concat = Enumerable.Concat(this.list, this.list); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("System", "IList")] public void IList_System() { var concat = Enumerable.Concat(this.ilist, this.ilist); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("System", "Array")] public void Array_System() { var concat = Enumerable.Concat(this.array, this.array); if (EnumerateAfterwards) { foreach (var item in concat) ; } } // Not implemented for FastLinq //[Benchmark] //[BenchmarkCategory("FastLinq", "Enumerable")] //public void FastLinq_Enumerable() //{ // var concat = FastLinq.Concat(this.enumerable, this.enumerable); //} [Benchmark] [BenchmarkCategory("FastLinq", "Collection")] public void Collection_FastLinq() { var concat = FastLinq.Concat(this.collection, this.collection); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("FastLinq", "Collection", "List")] public void CollectionList_FastLinq() { var concat = FastLinq.Concat(this.collection, this.list); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("FastLinq", "Collection", "List")] public void ListCollection_FastLinq() { var concat = FastLinq.Concat(this.list, this.collection); if (EnumerateAfterwards) { foreach (var item in concat) ; } } [Benchmark] [BenchmarkCategory("FastLinq", "IList")] public void IList_FastLinq() { var concat = FastLinq.Concat(this.ilist, this.ilist); if (EnumerateAfterwards) { int concatCount = concat.Count; for (int i = 0; i < concatCount; i++) { var item = concat[i]; } } } [Benchmark] [BenchmarkCategory("FastLinq", "List")] public void List_FastLinq() { var concat = FastLinq.Concat(this.list, this.list); if (EnumerateAfterwards) { int concatCount = concat.Count; for (int i = 0; i < concatCount; i++) { var item = concat[i]; } } } [Benchmark] [BenchmarkCategory("FastLinq", "Array")] public void Array_FastLinq() { var concat = FastLinq.Concat(this.array, this.array); if (EnumerateAfterwards) { int concatCount = concat.Count; for (int i = 0; i < concatCount; i++) { var item = concat[i]; } } } [Benchmark] [BenchmarkCategory("Optimal", "Enumerable")] public void Enumerable_Optimal() { var first = this.enumerable; var second = this.enumerable; if (this.EnumerateAfterwards) { foreach (var item in first) ; foreach (var item in second) ; } } [Benchmark] [BenchmarkCategory("Optimal", "Collection")] public void Collection_Optimal() { var first = this.collection; var second = this.collection; if (this.EnumerateAfterwards) { foreach (var item in first) ; foreach (var item in second) ; } } [Benchmark] [BenchmarkCategory("Optimal", "IList")] public void IList_Optimal() { var first = this.ilist; var second = this.ilist; if (this.EnumerateAfterwards) { var firstCount = first.Count; for (int i = 0; i < firstCount; i++) { var item = first[i]; } var secondCount = second.Count; for (int i = 0; i < secondCount; i++) { var item = second[i]; } } } [Benchmark] [BenchmarkCategory("Optimal", "Collection", "List")] public void CollectionList_Optimal() { var first = this.collection; var second = this.list; if (this.EnumerateAfterwards) { foreach (var item in first) ; var secondCount = second.Count; for (int i = 0; i < secondCount; i++) { var item = second[i]; } } } [Benchmark] [BenchmarkCategory("Optimal", "Collection", "List")] public void ListCollection_Optimal() { var first = this.list; var second = this.collection; if (this.EnumerateAfterwards) { var firstCount = first.Count; for (int i = 0; i < firstCount; i++) { var item = first[i]; } foreach (var item in second) ; } } [Benchmark] [BenchmarkCategory("Optimal", "List")] public void List_Optimal() { var first = this.list; var second = this.list; if (EnumerateAfterwards) { var firstCount = first.Count; for (int i = 0; i < firstCount; i++) { var item = first[i]; } var secondCount = second.Count; for (int i = 0; i < secondCount; i++) { var item = second[i]; } } } [Benchmark] [BenchmarkCategory("Optimal", "Array")] public void Array_Optimal() { var first = this.array; var second = this.array; if (EnumerateAfterwards) { var firstCount = first.Length; for (int i = 0; i < firstCount; i++) { var item = first[i]; } var secondCount = second.Length; for (int i = 0; i < secondCount; i++) { var item = second[i]; } } } } }
using Demo.Employee.MVC.Core.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace Demo.Employee.MVC.Core.Infrastructure { public class EmployeeDbContext : DbContext { private readonly string connectionString; //public EmployeeDbContext(DbContextOptions<EmployeeDbContext> options) // : base(options) //{ //} public EmployeeDbContext(string connectionString) { this.connectionString = connectionString; } public virtual DbSet<EmployeeEntity> EmployeeEnties { get; set; } public virtual DbSet<JobProfileEntity> JobProfileEnties { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<JobProfileEntity>().HasData(new JobProfileEntity { JobProfileId = (int)JobProfileEnum.Director, JobProfileName = JobProfileEnum.Director.ToString() }, new JobProfileEntity { JobProfileId = (int)JobProfileEnum.Manager, JobProfileName = JobProfileEnum.Manager.ToString() }, new JobProfileEntity { JobProfileId = (int)JobProfileEnum.Trainee, JobProfileName = JobProfileEnum.Trainee.ToString() } ); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseMySql(connectionString); } optionsBuilder.EnableSensitiveDataLogging(); optionsBuilder.EnableDetailedErrors(); optionsBuilder.EnableServiceProviderCaching(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoordControl.Core.Domains { public class Cross : DomainObject { public string StreetName { get; set; } public ISet<CrossPlan> PlanOfCrosses { get; set; } public Route Route { get; set; } public Pass PassLeft { get; set; } public Pass PassRight { get; set; } public Pass PassTop { get; set; } public Pass PassBottom { get; set; } public Road RoadLeft { get; set; } public Road RoadRight { get; set; } public int Position { get; protected set; } public override string ToString() { return StreetName; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; [Serializable] public class BuildingFace { public enum BuildingFaceType{ REGULAR, CONNECTION, ROOF, } [SerializeField] public Vector2[] baseShape; Mesh mesh; Building building; Vector3[] vertices; Vector2[] uvs; int[] tris; public float floorHeight = 0.1f; public int floors = 10; public float startHeight = 0; public float height; float uvScale; BuildingFaceType faceType; public BuildingFaceType FaceType { set => faceType = value; get => faceType; } [HideInInspector] public float unit; public BuildingFace(Building building, Mesh mesh) { InitParam(building, mesh); } public void InitParam(Building building, Mesh mesh) { this.building = building; this.mesh = mesh; } void InitProperty() { int verticesCount = baseShape.Length * (4 + 6); vertices = new Vector3[verticesCount]; uvs = new Vector2[verticesCount]; int trisCount = baseShape.Length * (2 + 2) * 3; tris = new int[trisCount]; height = GetHeight(); uvScale = 1.0f / 32 / floorHeight; curVerticesIndex = 0; curTrisIndex = 0; } public float GetHeight() { if (faceType == BuildingFaceType.REGULAR) return floorHeight * floors; else return height; } int curVerticesIndex = 0; int curTrisIndex = 0; public void ConstructMesh() { InitProperty(); ConstructSideFaces(); ConstructTopAndBottomFaces(); ApplyDataToMesh(); } float GetTopY() { return startHeight + height; } float GetBottomY() { return startHeight; } Vector2 GetQuadUV(float bottomLineLength, float edgeDistance, int x, int y) { if (faceType == BuildingFaceType.CONNECTION) return new Vector2(0, 0); else return new Vector2(bottomLineLength + edgeDistance * x, 0 + height * y) * uvScale; } void ConstructSideFaces() { // Roof doesn't need side face if (faceType == BuildingFaceType.ROOF) return; var sideCount = baseShape.Length; // Bottom line accumulated length, used to calculate UV float bottomLineLength = 0; for (int i = 0; i < sideCount; i++) { var leftBottomPosi = new Vector3(baseShape[i].x, GetBottomY(), baseShape[i].y); var leftTopPosi = new Vector3(baseShape[i].x, GetTopY(), baseShape[i].y); var rightBottomPosi = new Vector3(baseShape.Looped(i + 1).x, GetBottomY(), baseShape.Looped(i + 1).y); var rightTopPosi = new Vector3(baseShape.Looped(i + 1).x, GetTopY(), baseShape.Looped(i + 1).y); var edgeDistance = Vector3.Distance(leftBottomPosi, rightBottomPosi); var leftBottomIndex = curVerticesIndex; uvs[curVerticesIndex] = GetQuadUV(bottomLineLength, edgeDistance, 0, 0); vertices[curVerticesIndex++] = leftBottomPosi; uvs[curVerticesIndex] = GetQuadUV(bottomLineLength, edgeDistance, 0, 1); vertices[curVerticesIndex++] = leftTopPosi; uvs[curVerticesIndex] = GetQuadUV(bottomLineLength, edgeDistance, 1, 0); vertices[curVerticesIndex++] = rightBottomPosi; uvs[curVerticesIndex] = GetQuadUV(bottomLineLength, edgeDistance, 1, 1); vertices[curVerticesIndex++] = rightTopPosi; var leftTopIndex = leftBottomIndex + 1; var rightBottomIndex = leftBottomIndex + 2; var rightTopIndex = leftBottomIndex + 3; // Tris tris[curTrisIndex++] = leftBottomIndex; tris[curTrisIndex++] = rightTopIndex; tris[curTrisIndex++] = rightBottomIndex; tris[curTrisIndex++] = leftBottomIndex; tris[curTrisIndex++] = leftTopIndex; tris[curTrisIndex++] = rightTopIndex; bottomLineLength += edgeDistance; } } public void ConstructTopAndBottomFaces() { var sideCount = baseShape.Length; var shapeCenter = GetShapeCenter(); var bottomCenterPosi = new Vector3(shapeCenter.x, GetBottomY(), shapeCenter.y); var topCenterPosi = new Vector3(shapeCenter.x, GetTopY(), shapeCenter.y); for (int i = 0; i < sideCount; i++) { var leftBottomPosi = new Vector3(baseShape[i].x, GetBottomY(), baseShape[i].y); var leftTopPosi = new Vector3(baseShape[i].x, GetTopY(), baseShape[i].y); var rightBottomPosi = new Vector3(baseShape.Looped(i + 1).x, GetBottomY(), baseShape.Looped(i + 1).y); var rightTopPosi = new Vector3(baseShape.Looped(i + 1).x, GetTopY(), baseShape.Looped(i + 1).y); if(faceType == BuildingFaceType.ROOF) { leftTopPosi = new Vector3(baseShape[i].x, GetBottomY(), baseShape[i].y); rightTopPosi = new Vector3(baseShape.Looped(i + 1).x, GetBottomY(), baseShape.Looped(i + 1).y); } // Bottom var leftBottomIndex = curVerticesIndex; uvs[curVerticesIndex] = new Vector2(0, 0); vertices[curVerticesIndex++] = leftBottomPosi; uvs[curVerticesIndex] = new Vector2(0, 0); vertices[curVerticesIndex++] = rightBottomPosi; uvs[curVerticesIndex] = new Vector2(0, 0); vertices[curVerticesIndex++] = bottomCenterPosi; var rightBottomIndex = leftBottomIndex + 1; var bottomCenterIndex = leftBottomIndex + 2; tris[curTrisIndex++] = leftBottomIndex; tris[curTrisIndex++] = rightBottomIndex; tris[curTrisIndex++] = bottomCenterIndex; // Top var leftTopIndex = leftBottomIndex + 3; var topCenterIndex = leftBottomIndex + 4; var rightTopIndex = leftBottomIndex + 5; uvs[curVerticesIndex] = new Vector2(0, 0); vertices[curVerticesIndex++] = leftTopPosi; uvs[curVerticesIndex] = new Vector2(0, 0); vertices[curVerticesIndex++] = topCenterPosi; uvs[curVerticesIndex] = new Vector2(0, 0); vertices[curVerticesIndex++] = rightTopPosi; tris[curTrisIndex++] = leftTopIndex; tris[curTrisIndex++] = topCenterIndex; tris[curTrisIndex++] = rightTopIndex; } } Vector2 GetShapeCenter() { var ret = Vector2.zero; foreach(var vec in baseShape) { ret += vec; } ret /= baseShape.Length; return ret; } void ApplyDataToMesh() { //mesh.Clear(); //mesh.vertices = vertices; //mesh.triangles = tris; //mesh.uv = uvs; //mesh.RecalculateNormals(); int vertexOffset = building.vertexList.Count; foreach(var v in vertices) { building.vertexList.Add(v); } foreach(var tri in tris) { building.triList.Add(tri + vertexOffset); } foreach(var uv in uvs) { building.uvList.Add(uv); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImportExportController.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CGI.Reflex.Core.Importers; using CGI.Reflex.Web.Areas.System.Models.ImportExport; using CGI.Reflex.Web.Infra.Controllers; using CGI.Reflex.Web.Infra.Filters; namespace CGI.Reflex.Web.Areas.System.Controllers { public class ImportExportController : BaseController { [IsAllowed("/System/ImportExport")] public ActionResult Index(ImportConfig model) { model.ImportersList = new[] { new KeyValuePair<string, string>() }.Concat(FileImporters.GetImporters()); return View(model); } [HttpPost] [IsAllowed("/System/ImportExport/Import")] public ActionResult GetTemplate(string name) { var result = FileImporters.GetTemplate(name); return File(result.Stream, result.ContentType, result.SuggestedFileName); } [HttpPost] [IsAllowed("/System/ImportExport/Export")] [NoAsyncTimeout] [CanBeSlow] public void ExportAsync(string name) { if (!string.IsNullOrEmpty(name)) AsyncTaskExecute(() => FileImporters.Export(name)); } [IsAllowed("/System/ImportExport/Export")] public ActionResult ExportCompleted(FileImporterResult result) { if (result == null) return RedirectToAction("Index"); return File(result.Stream, result.ContentType, result.SuggestedFileName); } [HttpPost] [IsAllowed("/System/ImportExport/Import")] [NoAsyncTimeout] [CanBeSlow] public void ResultAsync(string name, HttpPostedFileBase file) { if (!string.IsNullOrEmpty(name) && file != null) AsyncTaskExecute(() => FileImporters.Import(name, file.InputStream)); } [IsAllowed("/System/ImportExport/Import")] public ActionResult ResultCompleted(IEnumerable<ImportOperationLineResult> result) { if (result == null) return RedirectToAction("Index"); return View(result); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Kers.Models.Entities.KERScore { public partial class TaskOperation : IEntityBase { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string ClassName {get;set;} public string Description {get;set;} public string Arguments {get;set;} public DateTime Created {get;set;} public DateTime Updated {get;set;} } }
using Logging.Entities.Concrete; using System; using System.Collections.Generic; using System.Text; namespace Logging.Business.Abstract { public interface IStudentService { Student GetById(int userId); Student GetByStudentId(string studentId); List<Student> GetList(); void Add(Student student); void Delete(Student student); void Update(Student student); } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; using System.Collections.Generic; using UnityEngine; namespace EnhancedEditor { /// <summary> /// GUI getter / setter buffer, allowing to dynamically push and pop values. /// </summary> /// <typeparam name="T">Buffer value type.</typeparam> public class GUIBuffer<T> { #region Scope /// <summary> /// Disposable GUI helper class used to wrap your controls within a pushed-in-buffer value. /// </summary> public class GUIBufferScope : GUI.Scope { private readonly GUIBuffer<T> buffer = null; /// <param name="_buffer">Associated GUI buffer.</param> /// <param name="_value">Pushed-in-buffer value.</param> /// <inheritdoc cref="GUIBufferScope"/> public GUIBufferScope(GUIBuffer<T> _buffer, T _value) { buffer = _buffer; _buffer.Push(_value); } // ----------------------- protected override void CloseScope() { buffer.Pop(); } } #endregion #region Global Members private readonly string name = string.Empty; private readonly Func<T> getter = null; private readonly Action<T> setter = null; /// <summary> /// All pushed-in-buffer values. /// </summary> public List<T> Buffer = new List<T>(); // ----------------------- /// <param name="_getter">Associated value getter.</param> /// <param name="_setter">Associated value setter.</param> /// <param name="_name">Name of the buffer associated value (used for error logs).</param> /// <inheritdoc cref="GUIBuffer{T}"/> public GUIBuffer(Func<T> _getter, Action<T> _setter, string _name) { getter = _getter; setter = _setter; name = _name; } #endregion #region Utility /// <summary> /// Push the current associated value into the buffer and set its new value. /// </summary> /// <param name="_value">New value.</param> public void Push(T _value) { T _previous = getter(); Buffer.Add(_previous); setter(_value); } /// <summary> /// Reverts the buffer to its previous pushed-in value. /// </summary> /// <returns>Previous pushed-in-buffer value.</returns> public T Pop() { if (Buffer.Count == 0) { // Logs an error when the buffer is empty. Debug.LogError($"You are popping more {name} than you are pushing!"); return default; } int _index = Buffer.Count - 1; T _value = Buffer[_index]; setter(_value); Buffer.RemoveAt(_index); return _value; } /// <summary> /// Clears the buffer and resets its associated value. /// </summary> /// <returns>First initial pushed-in-buffer value.</returns> public T Clear() { T _value = Buffer[0]; Buffer.Clear(); return _value; } /// <summary> /// Creates a new GUI scope for this buffer. Use this with the using keyword to wrapp your GUI controls within. /// </summary> /// <param name="_value">New buffer value.</param> /// <returns>Disposable helper class to wrap your controls within.</returns> public GUIBufferScope Scope(T _value) { GUIBufferScope _scope = new GUIBufferScope(this, _value); return _scope; } #endregion } /// <typeparam name="T1">Reference object type.</typeparam> /// <typeparam name="T2">Object value type.</typeparam> /// <inheritdoc cref="GUIBuffer{T}"/> public class GUIBuffer<T1, T2> { #region Scope /// <inheritdoc cref="GUIBuffer{T}.GUIBufferScope"/> public class GUIBufferScope : GUI.Scope { private readonly GUIBuffer<T1, T2> buffer = null; private readonly T1 key = default; /// <param name="_buffer">Associated GUI buffer.</param> /// <param name="_key">Reference object to set value.</param> /// <param name="_value">Pushed-in-buffer value.</param> /// <inheritdoc cref="GUIBufferScope"/> public GUIBufferScope(GUIBuffer<T1, T2> _buffer, T1 _key, T2 _value) { buffer = _buffer; key = _key; _buffer.Push(_key, _value); } // ----------------------- protected override void CloseScope() { buffer.Pop(key); } } #endregion #region Global Members private readonly string name = string.Empty; private readonly Func<T1, T2> getter = null; private readonly Action<T1, T2> setter = null; /// <summary> /// All pushed-in-buffer values. /// <para/> /// Reference object as key, with all its pushed-in values as value. /// </summary> public Dictionary<T1, List<T2>> Buffer = new Dictionary<T1, List<T2>>(); // ----------------------- /// <param name="_getter">Associated value getter.</param> /// <param name="_setter">Associated value setter.</param> /// <param name="_name">Name of the buffer associated value (used for error logs).</param> /// <inheritdoc cref="GUIBuffer{T}"/> public GUIBuffer(Func<T1, T2> _getter, Action<T1, T2> _setter, string _name) { getter = _getter; setter = _setter; name = _name; } #endregion #region Utility /// <summary> /// Push the current value of a specific key into the buffer and set its new value. /// </summary> /// <param name="_key">Reference object to push and set value.</param> /// <param name="_value">New value.</param> public void Push(T1 _key, T2 _value) { T2 _previous = getter(_key); if (!Buffer.ContainsKey(_key)) Buffer.Add(_key, new List<T2>()); Buffer[_key].Add(_previous); setter(_key, _value); } /// <summary> /// Reverts the buffer of a specific key to its previous pushed-in value. /// </summary> /// <param name="_key">Reference object to revert value.</param> /// <returns>Previous key pushed-in-buffer value.</returns> public T2 Pop(T1 _key) { if (!Buffer.ContainsKey(_key)) { // Logs an error when the buffer is empty. Debug.LogError($"You are popping more {name} than you are pushing!"); return default; } int _index = Buffer[_key].Count - 1; T2 _value = Buffer[_key][_index]; setter(_key, _value); Buffer[_key].RemoveAt(_index); if (_index == 0) Buffer.Remove(_key); return _value; } /// <summary> /// Clears the buffer of a specific key and resets its associated value. /// </summary> /// <param name="_key">Reference object to clear and reset value.</param> public void Clear(T1 _key) { Buffer[_key].Clear(); } /// <summary> /// Creates a new GUI scope for this buffer. Use this with the using keyword to wrapp your GUI controls within. /// </summary> /// <param name="_key">Reference object to set value.</param> /// <param name="_value">New object buffer value.</param> /// <returns>Disposable helper class to wrap your controls within.</returns> public GUIBufferScope Scope(T1 _key, T2 _value) { GUIBufferScope _scope = new GUIBufferScope(this, _key, _value); return _scope; } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace TopkaE.FPLDataDownloader.Models.InputModels.LeagueDataModel { public class League { public int id { get; set; } public string name { get; set; } public DateTime created { get; set; } public bool closed { get; set; } //public object rank { get; set; } //public object max_entries { get; set; } public string league_type { get; set; } public string scoring { get; set; } public int admin_entry { get; set; } public int start_event { get; set; } public string code_privacy { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ThreadPool { class Program { static void Main(string[] args) { // den Threadpool erforschen int maxThreads; int asyncThreads; System.Threading.ThreadPool.GetMaxThreads(out maxThreads, out asyncThreads); Console.WriteLine("Max. Anzahl Threads: {0}", maxThreads); Console.WriteLine("Max. Anzahl E/A-Threads: {0}", asyncThreads); // Benachrichtigungsereignis, Zustand 'nicht signalisieren' AutoResetEvent ready = new AutoResetEvent(false); // Anforder eines threads aus dem Pool System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(Calculate), ready); Console.WriteLine("Der Hauptthread wartet ..."); // Hauptthread in den Wartezustand setzen ready.WaitOne(); Console.WriteLine("Sekundärthread ist fertig."); Thread.Sleep(5000); } public static void Calculate(object obj) { Console.WriteLine("Im Sekundärthread"); Thread.Sleep(5000); // Ereigniszustand auf 'signalisieren' festlegen ((AutoResetEvent)obj).Set(); } } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ID; using Terraria.ModLoader; using TheMinepack.Items; namespace TheMinepack.Items { public class ZephyteBar : ModItem { public override void SetDefaults() { // Item Details item.name = "Zephyte Bar"; AddTooltip("'Imbued with the power of wind'"); item.width = 10; item.height = 10; item.rare = 2; item.value = Item.sellPrice(0, 0, 50, 0); item.maxStack = 999; } public override void ModifyTooltips(List<TooltipLine> tooltips) { foreach (TooltipLine line2 in tooltips) { if (line2.mod == "Terraria" && line2.Name == "ItemName") { line2.overrideColor = new Color(25, 155, 255); } } } /*public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "ZephyteOre", 4); // 4 Zephyte Ore recipe.AddTile(TileID.Furnaces); // Solidifier recipe.SetResult(this); recipe.AddRecipe(); }*/ } }
namespace CustomerTestProject.DAL.Entity { public class CustomerEntity { public int Id { get; set; } public string Name { get; set; } public string Symbol { get; set; } public string NIP { get; set; } public string Regon { get; set; } public string PhoneNumber { get; set; } public virtual AddressEntity Address { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using System.Configuration; namespace LoginRegistration { public partial class Registration : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { try { using (SqlConnection connectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["TempConnectionString1"].ConnectionString)) { connectionString.Open(); string name, id, password,secret; name = UserNameText.Text; id = UserIDText.Text; password = PasswordText.Text; secret = SecretMessageText.Text; if (name == "" || id == "" || password == ""||secret=="") { message.Attributes.Add("class", "alert-warning"); message.Text = "Please fill all the details"; //Response.Write("<script language=javascript>alert('Please fill all the details')</script>"); } else { SqlCommand cmd = new SqlCommand(); cmd.Connection = connectionString; cmd.CommandText = "USP_InsertUserDetails"; cmd.Parameters.Add("@UserID", SqlDbType.VarChar).Value = id; cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = name; cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = password; cmd.Parameters.Add("@SecretMessage", SqlDbType.VarChar).Value = secret; cmd.CommandType = CommandType.StoredProcedure; int rd = 0; rd = cmd.ExecuteNonQuery(); if (rd > 0) { message.Attributes.Add("class", "alert-success"); message.Text = "Registration Successful"; //Response.Write("<script language=javascript>alert('Insertion Successful')</script>"); UserIDText.Text = ""; UserNameText.Text = ""; PasswordText.Text = ""; SecretMessageText.Text = ""; } else throw (new Exception()); } } } catch (Exception) { message.Attributes.Add("class", "alert-danger"); message.Text = "Registration Failed"; //Response.Write("<script language=javascript>alert('Error Occurred')</script>"); UserIDText.Text = ""; UserNameText.Text = ""; PasswordText.Text = ""; SecretMessageText.Text = ""; } } protected void Button1_Click1(object sender, EventArgs e) { Response.Redirect("Login.aspx"); } } }
using System.Collections.Generic; namespace NoScope360Engine.Core.Entites { /// <summary> /// Base class /// </summary> public abstract class GameObject { private static List<GameObject> Objects { get; set; } = new List<GameObject>(); /// <summary> /// Get game object by Id /// </summary> /// <param name="Id">Game object</param> /// <returns></returns> public static GameObject GetObject(int Id) => Objects.Find((GameObject obj) => obj.Id == Id); /// <summary> /// Get game object by name /// </summary> /// <param name="Name">Game object</param> /// <returns></returns> public static GameObject GetObject(string Name) => Objects.Find((GameObject obj) => obj.Name == Name); private int Id { get; set; } /// <summary> /// Object's name /// </summary> private string Name { get; set; } public GameObject(string name = "default") { Id = Objects.Count; Name = name; Objects.Add(this); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace MVC { public class Program { public static void Main(string[] args) { //CreateWebHostBuilder(args).Build().Run(); var host = CreateWebHostBuilder(args).Build(); Models.Company company = (Models.Company)host.Services.GetService(typeof(Services.ICompany)); try { company.FillStaff(); } catch (Exception ex) { var logger = (ILogger<Program>)host.Services.GetService(typeof(ILogger<Program>)); logger.LogError(ex, "An error occurred while filling company's staff!"); } host.Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
using AutoMapper; using CryptoInvestor.Core.Domain; using CryptoInvestor.Core.Repositories; using CryptoInvestor.Infrastructure.DTO; using CryptoInvestor.Infrastructure.Exceptions; using CryptoInvestor.Infrastructure.Services; using Moq; using Shouldly; using System; using System.Threading.Tasks; using Xunit; namespace CryptoInvestor.Tests.Services { public class FavouritesServiceTest { private readonly Mock<IFavouritesRepository> _favouritesRepository; private readonly Mock<IUserRepository> _userRepository; private readonly Mock<ICoinRepository> _coinRepository; private readonly Mock<IMapper> _mapper; public FavouritesServiceTest() { _favouritesRepository = new Mock<IFavouritesRepository>(); _userRepository = new Mock<IUserRepository>(); _coinRepository = new Mock<ICoinRepository>(); _mapper = new Mock<IMapper>(); } [Fact] public async Task GetAsync_should_invoke_GetAsync_on_repository() { var favourites = new Favourites(Guid.NewGuid()); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); await favouritesService.GetAsync(Guid.NewGuid()); _favouritesRepository.Verify(x => x.GetAsync(It.IsAny<Guid>()), Times.Once); } [Fact] public async Task GetAsync_should_update_coins_before_return() { var favourites = new Favourites(Guid.NewGuid()); var coin = new Coin("btc", "bitcoin"); favourites.AddCoin(coin); _coinRepository.Setup(x => x.GetAsync(It.IsAny<string>())).ReturnsAsync(coin); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); await favouritesService.GetAsync(Guid.NewGuid()); _coinRepository.Verify(x => x.GetAsync(It.IsAny<string>()), Times.Once); } [Fact] public async Task GetAsync_should_return_FavouritesDto() { var favourites = new Favourites(Guid.NewGuid()); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); _mapper.Setup(x => x.Map<FavouritesDto>(It.IsAny<Favourites>())).Returns(new FavouritesDto()); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); var favouritesDto = await favouritesService.GetAsync(Guid.NewGuid()); favouritesDto.ShouldBeOfType<FavouritesDto>(); } [Fact] public async Task CreateAsync_should_invoke_AddAsync_on_repository() { var user = new User("test@email.com", "test", "secret", "salt"); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync((Favourites)null); _userRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(user); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); await favouritesService.CreateAsync(Guid.NewGuid()); _favouritesRepository.Verify(x => x.AddAsync(It.IsAny<Favourites>()), Times.Once); } [Fact] public async Task Given_not_exists_user_CreateAsync_should_throw_exception() { _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync((Favourites)null); _userRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync((User)null); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); ServiceException ex = await Should.ThrowAsync<ServiceException>(async () => { await favouritesService.CreateAsync(Guid.NewGuid()); }); ex.Code.ShouldBe(ErrorCodes.UserNotFound); } [Fact] public async Task Given_user_with_favourites_collection_CreateAsync_should_throw_exception() { var favourites = new Favourites(Guid.NewGuid()); var user = new User("test@email.com", "test", "secret", "salt"); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); _userRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(user); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); ServiceException ex = await Should.ThrowAsync<ServiceException>(async () => { await favouritesService.CreateAsync(Guid.NewGuid()); }); ex.Code.ShouldBe(ErrorCodes.FavouritesAlreadyExists); } [Fact] public async Task GetCoinAsync_should_invoke_GetAsync_on_favourites_repository() { var favourites = new Favourites(Guid.NewGuid()); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); await favouritesService.GetCoinAsync(Guid.NewGuid(), "btc"); _favouritesRepository.Verify(x => x.GetAsync(It.IsAny<Guid>()), Times.Once); } [Fact] public async Task GetCoinAsync_should_return_CoinDto() { var favourites = new Favourites(Guid.NewGuid()); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); _mapper.Setup(x => x.Map<CoinDto>(It.IsAny<Coin>())).Returns(new CoinDto()); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); var coinDto = await favouritesService.GetCoinAsync(Guid.NewGuid(), "btc"); coinDto.ShouldBeOfType<CoinDto>(); } [Fact] public async Task Given_user_without_favourites_collection_GetCoinAsync_should_throw_exception() { _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync((Favourites)null); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); ServiceException ex = await Should.ThrowAsync<ServiceException>(async () => { await favouritesService.GetCoinAsync(Guid.NewGuid(), "btc"); }); ex.Code.ShouldBe(ErrorCodes.FavouritesNotFound); } [Fact] public async Task AddCoinAsync_should_invoke_UpdateAsync_on_favourites_repository() { var favourites = new Favourites(Guid.NewGuid()); var coin = new Coin("btc", "bitcoin"); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); _coinRepository.Setup(x => x.GetAsync(It.IsAny<string>())).ReturnsAsync(coin); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); await favouritesService.AddCoinAsync(Guid.NewGuid(), "btc"); _favouritesRepository.Verify(x => x.UpdateAsync(It.IsAny<Favourites>()), Times.Once); } [Fact] public async Task Given_user_without_favourites_collection_AddCoinAsync_should_throw_exception() { _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync((Favourites)null); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); ServiceException ex = await Should.ThrowAsync<ServiceException>(async () => { await favouritesService.AddCoinAsync(Guid.NewGuid(), "btc"); }); ex.Code.ShouldBe(ErrorCodes.FavouritesNotFound); } [Fact] public async Task Given_favourites_collection_without_coin_AddCoinAsync_should_throw_exception() { var favourites = new Favourites(Guid.NewGuid()); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); _coinRepository.Setup(x => x.GetAsync(It.IsAny<string>())).ReturnsAsync((Coin)null); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); ServiceException ex = await Should.ThrowAsync<ServiceException>(async () => { await favouritesService.AddCoinAsync(Guid.NewGuid(), "btc"); }); ex.Code.ShouldBe(ErrorCodes.InvalidCoin); } [Fact] public async Task DeleteCoinAsync_should_invoke_UpdateAsync_on_favourites_repository() { var favourites = new Favourites(Guid.NewGuid()); var coin = new Coin("btc", "bitcoin"); favourites.AddCoin(coin); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); _coinRepository.Setup(x => x.GetAsync(It.IsAny<string>())).ReturnsAsync(coin); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); await favouritesService.DeleteCoinAsync(Guid.NewGuid(), "btc"); _favouritesRepository.Verify(x => x.UpdateAsync(It.IsAny<Favourites>()), Times.Once); } [Fact] public async Task Given_user_without_favourites_collection_DeleteCoinAsync_should_throw_exception() { _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync((Favourites)null); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); ServiceException ex = await Should.ThrowAsync<ServiceException>(async () => { await favouritesService.DeleteCoinAsync(Guid.NewGuid(), "btc"); }); ex.Code.ShouldBe(ErrorCodes.FavouritesNotFound); } [Fact] public async Task Given_favourites_collection_without_coin_DeleteCoinAsync_should_throw_exception() { var favourites = new Favourites(Guid.NewGuid()); _favouritesRepository.Setup(x => x.GetAsync(It.IsAny<Guid>())).ReturnsAsync(favourites); _coinRepository.Setup(x => x.GetAsync(It.IsAny<string>())).ReturnsAsync((Coin)null); var favouritesService = new FavouritesService(_favouritesRepository.Object, _userRepository.Object, _coinRepository.Object, _mapper.Object); ServiceException ex = await Should.ThrowAsync<ServiceException>(async () => { await favouritesService.DeleteCoinAsync(Guid.NewGuid(), "btc"); }); ex.Code.ShouldBe(ErrorCodes.InvalidCoin); } } }
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 WFProject { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void CheckPhoneNumber(string phoneNumber) // 0700000000 is valid { if (phoneNumber.Length != 10) throw new Exception("Phone number length must contain 10 digits"); if (!(phoneNumber[0] == '0' && phoneNumber[1] == '7')) throw new Exception("Invalid phone number"); } public void CheckEMail(string email) // a@a.a is valid { string username = string.Empty; string domain = string.Empty; bool writeUsername = true; int amountOfAtSigns = 0; int amountOfDotsInDomain = 0; int indexOfDotSeparator; int minLength = 1; int maxNameLength = 64; int maxDomainLength = 188; // Verifying the email of invalid characters "(),:;<>@[\] and space if (email.Contains('\"') || email.Contains('(') || email.Contains(')') || email.Contains(',') || email.Contains(':') || email.Contains(';') || email.Contains('<') || email.Contains('>') || email.Contains('[') || email.Contains('\\') || email.Contains(']') || email.Contains(' ')) throw new Exception("Invalid Email adress"); // Email can't have more than one @ for (int i = 0; i < email.Length - 1; i++) if (email[i] == '@') amountOfAtSigns++; if (amountOfAtSigns > 1 || amountOfAtSigns == 0) throw new Exception("Invalid Email adress"); // Separating the email into the username and domain for (int i = 0; i < email.Length; i++) { if (email[i] == '@') { writeUsername = false; i++; } if (writeUsername) username += email[i]; else { if (email[i] == '.') { amountOfDotsInDomain++; if (amountOfDotsInDomain > 1) throw new Exception("Invalid Email adress"); indexOfDotSeparator = domain.Length; } domain += email[i]; } } // Verifying length of name/domain if (username.Length > maxNameLength || domain.Length > maxDomainLength || username.Length < minLength || domain.Length < minLength) throw new Exception("Invalid Email adress"); // Veryfing the domain bool isBeforeDot = true; int charsBeforeDot = 0; int charsAfterDot = 0; if (!domain.Contains('.')) throw new Exception("Invalid domain name"); for (int i = 0; i < domain.Length - 1; i++) { if (domain[i] == '.') { isBeforeDot = false; i++; } if (!char.IsLetterOrDigit(domain[i])) throw new Exception("Invalid domain name"); if (isBeforeDot) charsBeforeDot++; else charsAfterDot++; } // Domain needs at least one letter before the dot and after 'a.a' if (!(charsBeforeDot >= 1 && charsAfterDot >= 1)) throw new Exception("Invalid domain name"); } private void ApplyButton_Click(object sender, EventArgs e) { try { CheckEMail(EmailTextBox.Text); CheckPhoneNumber(PhoneNumberTextBox.Text); ValidationLabel.ForeColor = Color.Green; ValidationLabel.Text = "Success"; } catch (Exception error) { ValidationLabel.ForeColor = Color.Red; ValidationLabel.Text = error.Message; } } private void PhoneNumberTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) e.Handled = true; } } }
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 Isaac_Pill_Tracker { public partial class TransForm : Form { //Rebirth Item Lists private static Item[] beelzItems = { new Item("Jar of Flies", 1), new Item("???'s only Friend"), new Item("Angry Fly",2), new Item("BBF"), new Item("Best Bud"), new Item("Big Fan"), new Item("Distant Admiration"), new Item("Forever Alone"), new Item("Friend Zone",1), new Item("Halo of Flies"), new Item("Hive Mind"), new Item("Infestation"), new Item("Lost Fly",1), new Item("The Mulligan"), new Item("Obsessed Fan"), new Item("Papa Fly"), new Item("Skatole"), new Item("Smart Fly") }; private static Item[] guppyItems = { new Item("Guppy's Head"), new Item("Guppy's Paw"), new Item("Dead Cat"), new Item("Guppy's Collar"), new Item("Guppy's Tail"), new Item("Guppy's Hair Ball") }; //private Trans Beelz = new Trans("Beelzebub", "Flight,\nConverts small enemy flies into blue flies", beelzItems); //private Trans Guppy = new Trans("Guppy", "Flight,\nSpawns a blue fly each time a tear hits an enemy", guppyItems); //Afterbirth item Lists private Item[] bobItems = { new Item("Bob's Rotten Head"),new Item("Bob's Brain"),new Item("Bob's Curse"), new Item("Ipecac")}; private Item[] conjItems = { new Item("Brother Bobby"), new Item("Harlequin Baby"), new Item("Headless Baby"), new Item("Little Steven"), new Item("Mongo Baby"), new Item("Rotten Baby"), new Item("Sister Maggy") }; private Item[] funguyItems = { new Item("1up!"),new Item("Blue Cap"), new Item("God's Flesh"), new Item("Magic Mushroom"), new Item("Mini Mush"), new Item("Odd Mushroom (Large)"), new Item("Odd Mushroom (Thin)") }; private Item[] leviaItems = { new Item("The nail"), new Item("Abaddon"), new Item("Brimstone"), new Item("The Mark"), new Item("Maw of the Void"), new Item("The Pact"), new Item("Pentagram"), new Item("Spirit of the Night")}; private Item[] ohcrapItems = { new Item("Flush!"),new Item("The Poop"), new Item("E-Coli")}; private Item[] seraItems = { new Item("The Bible"), new Item("Dead Dove"),new Item("Guardian Angel"),new Item("The Halo"),new Item("Holy Grail"),new Item("Holy Mantle"),new Item("Mitre"),new Item("Rosary"),new Item("Sworn Protector") }; private Item[] spunItems = { new Item("Adrenaline",2), new Item("Euthanasia",2),new Item("Experimental Treatment"),new Item("Growth Hormones"),new Item("Roid Rage"),new Item("Speed Ball"),new Item("Synthoil")}; private Item[] momItems = { new Item("Mom's Bottle of Pills"),new Item("Mom's Bra"),new Item("Mom's Pad"),new Item("Mom's Shovel",2),new Item("Mom's Coin Purse"),new Item("Mom's Contacts"),new Item("Mom's Eye"),new Item("Mom's Eyeshadow"),new Item("Mom's Heels"),new Item("Mom's Key"),new Item("Mom's Knife"),new Item("Mom's Lipstick"),new Item("Mom's Pearls"),new Item("Mom's Perfume"),new Item("Mom's Purse"),new Item("Mom's Razor",2),new Item("Mom's Underwear"),new Item("Mom's Wig") }; private Item[] sbumItems = { new Item("Bum Friend"),new Item("Dark Bum"),new Item("Key Bum") }; //Afterbirth+ item Lists private Item[] bookItems = { new Item("Anarchist Cookbook"),new Item("The Bible"),new Item("The Book of Belial"),new Item("Book of Revelations"),new Item("Book of Secrets"),new Item("Book of Shadows"),new Item("The Book of Sin"),new Item("Book of the Dead"),new Item("How to Jump"),new Item("The Necronomicon"),new Item("Monster Manual"),new Item("Satanic Bible"),new Item("Telepathy for Dummies") }; private Item[] spidItems = { new Item("Box of Spiders"),new Item("Spider Butt"),new Item("Mutant Spider"),new Item("Spider Baby"),new Item("Spider Bite"),new Item("Spider Mod")}; private int rVal = -1; public TransForm() { InitializeComponent(); } public TransForm(int resetVal) { rVal = resetVal; InitializeComponent(); //display the correct table and transformations } private void TransForm_Load(object sender, EventArgs e) { Transformations.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; switch (rVal) { case 0: populateRebirth(); break; case 1: populateAfterbirth(); break; case 2: populateAfterbirthPlus(); break; default: MessageBox.Show("Error occurred trying to get the DLC"); break; } } private string filterForDLC(Item[] list) { string itemList = "\n"; if (rVal != 2) { foreach (Item i in list) if (i.getDLC() <= rVal) itemList += $" - {i.getName()}\n"; } else { foreach (Item i in list) itemList += $" - {i.getName()}\n"; } return itemList; } private void populateRebirth() { string filtered_items = ""; //beelz loop filtered_items = filterForDLC(beelzItems); Transformations.Rows.Add("Beelzebub", RebirthTrans.Images[0], "Flight,\nConverts small enemy flies into blue flies", filtered_items); //guppy loop filtered_items = filterForDLC(guppyItems); Transformations.Rows.Add("Guppy", RebirthTrans.Images[1], "Flight,\nSpawns a blue fly each time a tear hits an enemy", filtered_items); } private void populateAfterbirth() { populateRebirth(); string filtered_items = ""; //bob filtered_items = filterForDLC(bobItems); Transformations.Rows.Add("Bob", AfterbirthTrans.Images[0], "Grants a trail of poisonous green creep", filtered_items); //conjoined filtered_items = filterForDLC(conjItems); Transformations.Rows.Add("Conjoined", AfterbirthTrans.Images[1], "Grants two tumor faces that shoot tears diagonally,\n-0.3 damage,\nSlight increase to tear rate", filtered_items); //Fun Guy filtered_items = filterForDLC(funguyItems); Transformations.Rows.Add("Fun Guy", AfterbirthTrans.Images[2], "+1 Heart Container", filtered_items); //Leviathan filtered_items = filterForDLC(leviaItems); Transformations.Rows.Add("Leviathan", AfterbirthTrans.Images[3], "Flight,\n+2 Black Hearts", filtered_items); //Oh Crap filtered_items = filterForDLC(ohcrapItems); Transformations.Rows.Add("Oh Crap", AfterbirthTrans.Images[4], "Replenishes 1/2 a red heart for every poop destroyed", filtered_items); //Seraphim filtered_items = filterForDLC(seraItems); Transformations.Rows.Add("Seraphim", AfterbirthTrans.Images[5], "Flight,\n+3 Soul Hearts", filtered_items); //Spun filtered_items = filterForDLC(spunItems); Transformations.Rows.Add("Spun", AfterbirthTrans.Images[6], "+2 Damage,\n+0.15 Speed,\nSpawns a random pill", filtered_items); //Yes Mother? filtered_items = filterForDLC(momItems); Transformations.Rows.Add("Yes, Mother?", AfterbirthTrans.Images[7], "Grants a stationary knife that trails behind Isaac", filtered_items); //Super Bum filtered_items = filterForDLC(sbumItems); Transformations.Rows.Add("Super Bum", AfterbirthTrans.Images[8], "Combines all three beggar followers into one, Super Bum offers twice the rewards and can pick up coins, hearts, and keys", filtered_items); } private void populateAfterbirthPlus() { populateAfterbirth(); string filtered_items = ""; //Bookworm filtered_items = filterForDLC(bookItems); Transformations.Rows.Add("Bookworm", AbplusTrans.Images[0], "50% of the time Isaac shoots an extra tear like 20/20", filtered_items); //Spider Baby filtered_items = filterForDLC(spidItems); Transformations.Rows.Add("Spider Baby", AbplusTrans.Images[1], "Spawns a spider familiar that applies random status effects to enemies", filtered_items); //Adult Transformations.Rows.Add("Adult", AbplusTrans.Images[2], "+1 Heart Container", "\n - Puberty (Pill) x3\n"); } private void helpToolStripMenuItem_Click(object sender, EventArgs e) { string message = ""; message += "This is the transformation sheet!\n"; message += "This sheet detects which DLC you're using from the Pill Tracker form and automatically populates the grid with the appropriate transformations and items included in that DLC.\n"; message += "\nIf you find any glitches with this form please report them as I will not be testing this form as thoroughly since it has no interactivity. For contact info refer to the About tab on the main form.\nThank You!\n-Tyler"; MessageBox.Show(message); } private void TransForm_Resize(object sender, EventArgs e) { Transformations.Refresh(); } } public class Item { private int resetVal = -1; private string name; public Item() { } public Item(string n, int rVal = 0) { resetVal = rVal; name = n; } public int getDLC() { return resetVal; } public string getName() { return name; } } } /* public partial class TransForm : Form { ///=====REBIRTH===== //Item Lists private static Item[] beelzItems = { new Item(1, "Jar of Flies"), new Item(0,"???'s only Friend"), new Item(2,"Angry Fly"),new Item(0,"BBF"),new Item(0, "Best Bud"), new Item(0,"Big Fan"),new Item(0,"Distant Admiration"),new Item(0, "Forever Alone"),new Item(1,"Friend Zone"),new Item(0,"Halo of Flies"),new Item(0,"Hive Mind"),new Item(0,"Infestation"),new Item(1,"Lost Fly"),new Item(0,"The Mulligan"),new Item(1,"Obsessed Fan"),new Item(1,"Papa Fly"),new Item(0,"Skatole"),new Item(0,"Smart Fly")}; private static Item[] guppyItems = { new Item(0,"Guppy's Head"),new Item(0,"Guppy's Paw"),new Item(0,"Dead Cat"),new Item(0,"Guppy's Collar"),new Item(0,"Guppy's Tail"),new Item(0,"Guppy's Hair Ball") }; //transformation objects private Trans Beelz = new Trans("Beelzebub", "Flight,\nConverts small enemy flies into blue flies", beelzItems); private Trans Guppy = new Trans("Guppy","Flight,\nSpawns a blue fly each time a tear hits an enemy", guppyItems); //Afterbirth item trans private Item[] bobItems = { }; private Item[] conjItems = { }; private Item[] funguyItems = { }; private Item[] leviaItems = { }; private Item[] ohcrapItems = { }; private Item[] seraItems = { }; private Item[] spunItems = { }; private Item[] momItems = { }; private Item[] sbumItems = { }; //Afterbirth+ item trans private Item[] bookItems = { }; private Item[] spidItems = { }; private int rVal=-1; public TransForm() { InitializeComponent(); } public TransForm(int resetVal) { rVal = resetVal; InitializeComponent(); //display the correct table and transformations } private void TransForm_Load(object sender, EventArgs e) { Transformations.AutoGenerateColumns = false; //this allows for row collapsing switch (rVal) { case 0: populateRebirth(); break; case 1: populateAfterbirth(); break; case 2: populateAfterbirthPlus(); break; default: MessageBox.Show("Error occurred trying to get the DLC"); break; } } private void populateRebirth() { //beelz loop foreach (Item i in Beelz.getItems()) Transformations.Rows.Add(Beelz.getName(), RebirthTrans.Images[0], Beelz.getFX(), (i.getDLC() == rVal) ? i.getName() : ""); //guppy loop foreach (Item i in Guppy.getItems()) Transformations.Rows.Add(Guppy.getName(), RebirthTrans.Images[0], Guppy.getFX(), (i.getDLC() == rVal) ? i.getName() : ""); } private void populateAfterbirth() { populateRebirth(); } private void populateAfterbirthPlus() { populateAfterbirth(); } bool IsTheSameCellValue(int column, int row) { DataGridViewCell c1 = Transformations[column, row]; DataGridViewCell c2 = Transformations[column, row - 1]; if (c1.Value == null || c2.Value == null) return false; return c1.Value == c2.Value;//maybe remove toString to make it work with images? } /// <summary> /// This will allow me to "collapse" rows within a certain column /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Transformations_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { e.AdvancedBorderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.None; if (e.RowIndex < 1 || e.ColumnIndex < 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.AdvancedBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.None; } else { e.AdvancedBorderStyle.Top = Transformations.AdvancedCellBorderStyle.Top; } } private void Transformations_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.RowIndex == 0) return; if (IsTheSameCellValue(e.ColumnIndex, e.RowIndex)) { e.Value = null; e.FormattingApplied = true; } } } public class Item { private int resetVal = -1; private string name; public Item() { } public Item(int rVal, string n) { resetVal = rVal; name = n; } public int getDLC() { return resetVal; } public string getName() { return name; } } public class Trans { List<Item> items = new List<Item>(); string name, effects; public Trans() { } public Trans(string n, string fx, Item[] itemList) { name = n; effects = fx; foreach (Item i in itemList) { items.Add(i); } } public string getFX() { return effects; } public string getName() { return name; } public List<Item> getItems() { return items; } } } */
using System; using System.Text; using System.Collections.Generic; class DayFourteen{ private string currentMask = ""; private Dictionary<long, long> memory = new Dictionary<long, long>(); public void Run(){ List<string> strList = Input.GetStrings("input_files/Day14.txt"); strList.ForEach(ProcessString); long totalValue = GetTotalValue(); System.Console.WriteLine("Answer: " + totalValue); } private void ProcessString(string str){ string type = str.Split(" = ")[0]; switch(type.Substring(0, 3)){ case "mas": ProcessMask(str); break; case "mem": ProcessMem(str); break; } } private void ProcessMask(string str){ string newMask = str.Split(" = ")[1]; currentMask = newMask; } private void ProcessMem(string str){ string[] parts = str.Split(" = "); string memoryLocation = parts[0].Substring(4, parts[0].Length - 5); memoryLocation = Convert.ToString(Int32.Parse(memoryLocation), 2); string memoryValue = Convert.ToString(Int64.Parse(parts[1]), 2); memoryLocation = ParseInput(memoryLocation); memoryValue = ParseInput(memoryValue); ProcessMemWithFloatingBits(memoryLocation, memoryValue); } private void ProcessMemWithFloatingBits(string memoryLocation, string memoryValue){ string rawLocation = ApplyMaskToLocation(currentMask, memoryLocation); Queue<string> locationQueue = new Queue<string>(); locationQueue.Enqueue(rawLocation); while(locationQueue.TryDequeue(out string potentialLocation)){ if(potentialLocation.Contains('X')) AddLocationsToQueue(locationQueue, potentialLocation); else { AddToMemory(potentialLocation, memoryValue); } } //Bug is in here. //Don't place the 0/1s in the mask but in the location. } private void AddLocationsToQueue(Queue<string> maskQueue, string unreadyMask){ int indexOfX = unreadyMask.IndexOf('X'); StringBuilder builder = new StringBuilder(unreadyMask); string zero = builder.Replace(builder[indexOfX], '0', indexOfX, 1).ToString(); string one = builder.Replace(builder[indexOfX], '1', indexOfX, 1).ToString(); maskQueue.Enqueue(zero); maskQueue.Enqueue(one); } private string ApplyMaskToLocation(string mask, string memoryLocation){ StringBuilder builder = new StringBuilder(memoryLocation); for(int i = 0; i < mask.Length; i++){ if(mask[i] == '1'){ builder.Replace(memoryLocation[i], '1', i, 1); } else if(mask[i] == 'X'){ builder.Replace(memoryLocation[i], 'X', i, 1); } } return builder.ToString(); } private void AddToMemory(string memoryLocation, string memoryValue){ long key = Convert.ToInt64(memoryLocation, 2); long value = Convert.ToInt64(memoryValue, 2); memory[key] = value; } private string ParseInput(string initValue){ StringBuilder builder = new StringBuilder(); builder.Append('0', 36 - initValue.Length).Append(initValue); return builder.ToString(); } private long GetTotalValue(){ long sum = 0; foreach(KeyValuePair<long, long> entry in memory){ sum += entry.Value; } return sum; } }
using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using NetCode.Payloads; using NetCode.Util; namespace NetCode.Connection { public abstract class NetworkConnection { public ConnectionStats Stats { get; private set; } public int PacketTimeout { get; set; } = 500; public bool Compression { get; set; } = false; private List<Packet> pendingPackets = new List<Packet>(); private List<Payload> payloadQueue = new List<Payload>(); private List<uint> packetAcknowledgementQueue = new List<uint>(); public NetworkConnection() { Stats = new ConnectionStats(); } internal List<Payload> RecievePackets() { List<Payload> payloads = new List<Payload>(); List<byte[]> incomingData = RecieveData(); if (incomingData != null) { foreach (byte[] data in incomingData) { payloads.AddRange(RecievePacket(data)); } } return payloads; } internal void FlushRecievedPackets() { RecieveData(); } internal void TransmitPackets() { long timestamp = NetTime.Now(); FlushAcknowledgements(); while (payloadQueue.Count > 0) { Packet packet = ConstructPacket(); SendPacket(packet); } Stats.Update(timestamp); } internal void Enqueue(Payload payload) { payloadQueue.Add(payload); } internal bool AcknowledgePacket(uint packetID) { Packet packet = pendingPackets.Find(p => p.PacketID == packetID); if (packet != null) { pendingPackets.Remove(packet); long timestamp = NetTime.Now(); int latency = (int)(timestamp - packet.Timestamp); Stats.RecordAcknowledgement(latency, timestamp); return true; } return false; } internal List<Payload> GetTimeouts() { long timestamp = NetTime.Now(); // Assuming packets are ordered by timestamp. List<Payload> timeouts = new List<Payload>(); int culledPackets = 0; foreach (Packet packet in pendingPackets) { if (timestamp - packet.Timestamp > PacketTimeout) { culledPackets++; Stats.RecordTimeout(timestamp); timeouts.AddRange(packet.Payloads); } else { break; } } pendingPackets.RemoveRange(0, culledPackets); return timeouts; } private uint lastPacketID = 0; private uint GetNewPacketID() { return ++lastPacketID; } private Packet ConstructPacket() { uint packetID = GetNewPacketID(); Packet packet = new Packet(packetID); packet.Payloads.AddRange(payloadQueue); payloadQueue.Clear(); return packet; } private void SendPacket(Packet packet) { if (packet.RequiresAcknowledgement()) { pendingPackets.Add(packet); } long timestamp = NetTime.Now(); byte[] data = packet.Encode(timestamp); if (Compression) { data = Compress.Deflate(data); } Stats.RecordSend(data.Length, timestamp); SendData(data); } private List<Payload> RecievePacket(byte[] data) { if (Compression) { data = Compress.Enflate(data); } long timestamp = NetTime.Now(); Packet packet = Packet.Decode(data, timestamp); Stats.RecordReceive(data.Length, timestamp, packet.DecodingError); if (packet.RequiresAcknowledgement()) { packetAcknowledgementQueue.Add(packet.PacketID); } return packet.Payloads; } private void FlushAcknowledgements() { if (packetAcknowledgementQueue.Count > 0) { foreach (uint[] packetIDs in packetAcknowledgementQueue.Segment(PoolDeletionPayload.MAX_ENTITY_IDS)) { Enqueue(AcknowledgementPayload.Generate(packetIDs)); } packetAcknowledgementQueue.Clear(); } } public abstract void Destroy(); protected abstract void SendData(byte[] data); protected abstract List<byte[]> RecieveData(); public virtual NetworkClient.ConnectionClosedReason ConnectionStatus { get { return NetworkClient.ConnectionClosedReason.None; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace Assets.Level { public class Level { public int LevelWidth { get; private set; } public int LevelHeight { get; private set; } private static GameObject[,] blocks; public Level(int levelWidth, int levelHeight) { blocks = new GameObject[levelWidth, levelHeight]; LevelWidth = levelWidth; LevelHeight = levelHeight; } public void setBlockAt(int x, int y, GameObject block) { blocks[x, y] = block; } public GameObject getBlockAt(int x, int y) { return blocks[x, y]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using OlympicsWebApp.BusinessLayer; using OlympicsWebApp.Data; namespace OlympicsWebApp.Pages.Countries { public class DeleteModel : PageModel { private readonly OlympicsWebApp.Data.OlympicsDataContext _context; public DeleteModel(OlympicsWebApp.Data.OlympicsDataContext context) { _context = context; } [BindProperty] public Country Country { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Country = await _context.Countries.FirstOrDefaultAsync(m => m.Id == id); if (Country == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAsync(int? id) { if (id == null) { return NotFound(); } Country = await _context.Countries.FindAsync(id); if (Country != null) { _context.Countries.Remove(Country); await _context.SaveChangesAsync(); } return RedirectToPage("./Index"); } } }
using Proyecto_Web.Interface; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using Proyecto_Web.Modelos; using Proyecto_Web.Conection; namespace Proyecto_Web.Modelos { public class estructura { DataTable Err = new DataTable(); /// <summary> /// /// </summary> public estructura() { Err = new DataTable(); } /// <summary> /// Code Error /// </summary> /// <param name="code"></param> /// <returns></returns> public DataTable GetError(string code) { Err.Clear(); Err.Columns.Add("TIPO"); Err.Columns.Add("MENSAJE"); Object[] Para = { "1", "Error: fatal en los servicios, código de error: " + code }; Err.Rows.Add(Para); return Err; } } }
using System.Web; using System.Web.Optimization; namespace Inspinia_MVC5_SeedProject { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { // Vendor scripts bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-2.1.4.js")); // jQuery Validation bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate.min.js")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js")); bundles.Add(new StyleBundle("~/bundles/myStyles").Include( "~/Content/myStyles.css")); bundles.Add(new StyleBundle("~/bundles/tagStyles").Include( "~/Content/tagStyles.css")); // Inspinia script bundles.Add(new ScriptBundle("~/bundles/inspinia").Include( "~/Scripts/app/inspinia.js")); //categoryTree bundles.Add(new ScriptBundle("~/bundles/categoryTree").Include("~/Scripts/categoryTree.js")); // SlimScroll bundles.Add(new ScriptBundle("~/plugins/slimScroll").Include( "~/Scripts/plugins/slimScroll/jquery.slimscroll.min.js")); // jQuery plugins bundles.Add(new ScriptBundle("~/plugins/metsiMenu").Include( "~/Scripts/plugins/metisMenu/metisMenu.js")); bundles.Add(new ScriptBundle("~/plugins/pace").Include( "~/Scripts/plugins/pace/pace.min.js")); // CSS style (bootstrap/inspinia) bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.min.css", "~/Content/style.css")); // Font Awesome icons bundles.Add(new StyleBundle("~/font-awesome/css").Include( "~/fonts/font-awesome/css/font-awesome.min.css", new CssRewriteUrlTransform())); //knockout bundles.Add(new ScriptBundle("~/plugins/knockout").Include("~/Scripts/knockout-3.3.0.js")); bundles.Add(new ScriptBundle("~/plugins/toastr").Include( "~/Scripts/plugins/toastr/toastr.min.js")); bundles.Add(new StyleBundle("~/plugins/toastrStyles").Include( "~/Content/plugins/toastr/toastr.min.css")); // jsTree bundles.Add(new ScriptBundle("~/plugins/jsTree").Include( "~/Scripts/plugins/jsTree/jstree.min.js")); // jsTree styles //bundles.Add(new StyleBundle("~/Content/plugins/jsTree").Include( // "~/Content/plugins/jsTree/style.css")); // validate bundles.Add(new ScriptBundle("~/plugins/validate").Include( "~/Scripts/plugins/validate/jquery.validate.min.js")); // jQueryUI CSS bundles.Add(new ScriptBundle("~/Scripts/plugins/jquery-ui/jqueryuiStyles").Include( "~/Scripts/plugins/jquery-ui/jquery-ui.css")); // jQueryUI bundles.Add(new StyleBundle("~/bundles/jqueryui").Include( "~/Scripts/plugins/jquery-ui/jquery-ui.min.js")); // iCheck css styles bundles.Add(new StyleBundle("~/Content/plugins/iCheck/iCheckStyles").Include( "~/Content/plugins/iCheck/custom.css")); // iCheck bundles.Add(new ScriptBundle("~/plugins/iCheck").Include( "~/Scripts/plugins/iCheck/icheck.min.js")); // chosen styles bundles.Add(new StyleBundle("~/Content/plugins/chosen/chosenStyles").Include( "~/Content/plugins/chosen/chosen.css")); // chosen bundles.Add(new ScriptBundle("~/plugins/chosen").Include( "~/Scripts/plugins/chosen/chosen.jquery.js")); // image cropper bundles.Add(new ScriptBundle("~/plugins/imagecropper").Include( "~/Scripts/plugins/cropper/cropper.min.js")); // image cropper styles bundles.Add(new StyleBundle("~/plugins/imagecropperStyles").Include( "~/Content/plugins/cropper/cropper.min.css")); //autosize bundles.Add(new ScriptBundle("~/plugins/autosize").Include("~/Scripts/jquery.autosize.min.js")); //timeago bundles.Add(new ScriptBundle("~/plugins/timeago").Include("~/Scripts/jquery.timeago.js")); //selectize bundles.Add(new StyleBundle("~/scripts/selectizeStyles").Include("~/Scripts/plugins/selectize/selectize.css")); bundles.Add(new ScriptBundle("~/scripts/selectize").Include("~/Scripts/plugins/selectize/selectize.min.js")); // Slick carousel Styless bundles.Add(new StyleBundle("~/plugins/slickStyles").Include( "~/Content/plugins/slick/slick.css", new CssRewriteUrlTransform())); // Slick carousel theme Styless bundles.Add(new StyleBundle("~/plugins/slickThemeStyles").Include( "~/Content/plugins/slick/slick-theme.css", new CssRewriteUrlTransform())); // Slick carousel bundles.Add(new ScriptBundle("~/plugins/slick").Include( "~/Scripts/plugins/slick/slick.min.js")); // Sweet alert Styless bundles.Add(new StyleBundle("~/plugins/sweetAlertStyles").Include( "~/Content/plugins/sweetalert/sweetalert.css")); // Sweet alert bundles.Add(new ScriptBundle("~/plugins/sweetAlert").Include( "~/Scripts/plugins/sweetalert/sweetalert.min.js")); // dataPicker styles bundles.Add(new StyleBundle("~/plugins/dataPickerStyles").Include( "~/Content/plugins/datapicker/datepicker3.css")); // dataPicker bundles.Add(new ScriptBundle("~/plugins/dataPicker").Include( "~/Scripts/plugins/datapicker/bootstrap-datepicker.js")); // Rickshaw chart bundles.Add(new ScriptBundle("~/plugins/rickshaw").Include( "~/Scripts/plugins/rickshaw/vendor/d3.v3.js", "~/Scripts/plugins/rickshaw/rickshaw.min.js")); // dropZone styles bundles.Add(new StyleBundle("~/Content/plugins/dropzone/dropZoneStyles").Include( "~/Content/plugins/dropzone/basic.css", "~/Content/plugins/dropzone/dropzone.css")); // dropZone bundles.Add(new ScriptBundle("~/plugins/dropZone").Include( "~/Scripts/plugins/dropzone/dropzone.js")); // Lightbox gallery css styles bundles.Add(new StyleBundle("~/Content/plugins/blueimp/css/").Include( "~/Content/plugins/blueimp/css/blueimp-gallery.min.css")); // Lightbox gallery bundles.Add(new ScriptBundle("~/plugins/lightboxGallery").Include( "~/Scripts/plugins/blueimp/jquery.blueimp-gallery.min.js")); // ionRange styles bundles.Add(new StyleBundle("~/Content/plugins/ionRangeSlider/ionRangeStyles").Include( "~/Content/plugins/ionRangeSlider/ion.rangeSlider.css", "~/Content/plugins/ionRangeSlider/ion.rangeSlider.skinFlat.css")); // ionRange bundles.Add(new ScriptBundle("~/plugins/ionRange").Include( "~/Scripts/plugins/ionRangeSlider/ion.rangeSlider.min.js")); // wizardSteps styles bundles.Add(new StyleBundle("~/plugins/wizardStepsStyles").Include( "~/Content/plugins/steps/jquery.steps.css")); // wizardSteps bundles.Add(new ScriptBundle("~/plugins/wizardSteps").Include( "~/Scripts/plugins/staps/jquery.steps.min.js")); // Ladda buttons Styless bundles.Add(new StyleBundle("~/plugins/laddaStyles").Include( "~/Content/plugins/ladda/ladda-themeless.min.css")); // Ladda buttons bundles.Add(new ScriptBundle("~/plugins/ladda").Include( "~/Scripts/plugins/ladda/spin.min.js", "~/Scripts/plugins/ladda/ladda.min.js", "~/Scripts/plugins/ladda/ladda.jquery.min.js")); // Dotdotdot buttons bundles.Add(new ScriptBundle("~/plugins/truncate").Include( "~/Scripts/plugins/dotdotdot/jquery.dotdotdot.min.js")); // summernote styles bundles.Add(new StyleBundle("~/plugins/summernoteStyles").Include( "~/Content/plugins/summernote/summernote.css", "~/Content/plugins/summernote/summernote-bs3.css")); // summernote bundles.Add(new ScriptBundle("~/plugins/summernote").Include( "~/Scripts/plugins/summernote/summernote.min.js")); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TextLayoutChanger { public sealed class ConfigurationStore { public string SelectedDocument { get; } private static volatile ConfigurationStore _instance; private static readonly object syncRoot = new object(); private ConfigurationStore() { SelectedDocument = ConfigurationManager.AppSettings["DocumentPath"]; } public static ConfigurationStore Instance { get { if (_instance == null) { lock (syncRoot) { if (_instance == null) _instance = new ConfigurationStore(); } } return _instance; } } } }
using System; namespace Arch.Data.Orm { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class VersionLockAttribute : Attribute { } }
using System.Security.Principal; namespace MvcApplication.Business.Security.Principal { public class Identity : IIdentity { #region Properties public virtual string AuthenticationType { get; set; } public virtual bool IsAuthenticated { get; set; } public virtual string Name { get; set; } #endregion } }
using UnityEngine; using UnityEngine.UI; using Lowscope.Saving.Components; using UnityEngine.EventSystems; namespace Lowscope.Saving.Examples { public class ExampleSlotMenuSlot : MonoBehaviour, IPointerEnterHandler, IPointerDownHandler, IPointerExitHandler { [SerializeField] private Text slotIndicator; [SerializeField] private Text slotText; [SerializeField] private SaveScreenShotDisplayer screenshotDisplayer; [SerializeField] private Button buttonRemoveSave; [SerializeField] private ExamplePlaySoundsOnMouse playSoundsOnMouse; private ExampleSlotMenu.Mode mode; private int slotIndex = -1; private bool isSlotUsed = false; private bool isSlotValid = false; private Color initialSlotIndicatorColor; private Color initialSlotTextColor; private void Awake() { initialSlotIndicatorColor = slotIndicator.color; initialSlotTextColor = slotText.color; buttonRemoveSave.onClick.AddListener(OnClickRemove); SaveMaster.OnSlotChangeDone += OnChangedSlot; } private void OnDestroy() { SaveMaster.OnSlotChangeDone -= OnChangedSlot; } private void OnClickRemove() { if (isSlotUsed && isSlotValid) { SaveMaster.DeleteSave(slotIndex); SetIndex(slotIndex, mode); } } private void OnChangedSlot(int to, int from) { if (to != slotIndex) return; // Ensure the slot updates if anything is saved to it. if (mode == ExampleSlotMenu.Mode.Save) SetIndex(slotIndex, mode); } private void Reset() { if (slotIndicator == null) slotIndicator = GetComponent<Text>(); } public void SetIndex(int slotIndex, ExampleSlotMenu.Mode mode) { this.slotIndex = slotIndex; this.mode = mode; isSlotUsed = SaveMaster.IsSlotUsed(slotIndex); isSlotValid = SaveMaster.IsSlotValid(slotIndex); slotIndicator.text = string.Format("{0}.", (slotIndex + 1).ToString()); string lastTimeSaved; SaveMaster.GetMetaData("lastsavedtime", out lastTimeSaved, slotIndex); buttonRemoveSave.gameObject.SetActive(isSlotUsed && isSlotValid); if (isSlotValid) { playSoundsOnMouse.PlaySounds(isSlotUsed || mode == ExampleSlotMenu.Mode.Save); slotText.text = isSlotUsed ? lastTimeSaved : "Slot is empty"; } else { playSoundsOnMouse.PlaySounds(false); slotText.text = ""; slotIndicator.text = ""; } } // Called when clicking on the slot public void OnPointerDown(PointerEventData eventData) { if (mode == ExampleSlotMenu.Mode.Load) { if (slotIndex == -1 || !isSlotUsed || !isSlotValid) return; SaveMaster.SetSlot(slotIndex, true); } else { if (!isSlotValid) return; // Change the slot, keep the save data SaveMaster.SetSlot(slotIndex, false, keepActiveSaveData: true, writeToDiskAfterChange: true); } } // Called when pointer hovers over the slot public void OnPointerEnter(PointerEventData eventData) { if (slotIndex == -1) return; if (screenshotDisplayer != null) { screenshotDisplayer.LoadScreenshot(slotIndex); } if (isSlotUsed || (mode == ExampleSlotMenu.Mode.Save && isSlotValid)) { Hovering(true); } } private void Hovering(bool state) { slotIndicator.color = state ? Color.white : initialSlotIndicatorColor; slotText.color = state ? Color.white : initialSlotTextColor; } public void OnPointerExit(PointerEventData eventData) { Hovering(false); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; //2018-12-01 宋柏慧 //--------------------------------------------------------- //这个脚本的功能为 被攻击后的反应 //从而达到怪物后退 在被砍点生成粒子的效果 //--------------------------------------------------------- public class isattacked : MonoBehaviour { public GameObject blod; private int count = 0; // public Text countText; public static int TotalTime = 120;//总时间 public Text TimeText;//在UI里显示时间 public string LoadsceneName; public Image loseImage; public AudioSource damage; private int mumite;//分 private int second;//秒 void Start() { StartCoroutine(startTime()); //运行一开始就进行协程 } public IEnumerator startTime() { while (TotalTime >= 0) { //Debug.Log(TotalTime);//打印出每一秒剩余的时间 yield return new WaitForSeconds(1);//由于开始倒计时,需要经过一秒才开始减去1秒, //所以要先用yield return new WaitForSeconds(1);然后再进行TotalTime--;运算 TotalTime--; TimeText.text = "Time:" + TotalTime; if (TotalTime <= 0) { //如果倒计时剩余总时间为0时,就跳转场景 loseImage.gameObject.SetActive(true); StartCoroutine(WaitSeconds(0.5f)); } mumite = TotalTime / 60; //输出显示分 second = TotalTime % 60; //输出显示秒 string length = mumite.ToString(); if (second >= 10) { TimeText.text ="倒计时: "+ "0" + mumite + ":" + second; } //如果秒大于10的时候,就输出格式为 00:00 else TimeText.text = "倒计时: "+"0" + mumite + ":0" + second; //如果秒小于10的时候,就输出格式为 00:00 } } public virtual void OnCollisionEnter(Collision pOther) { if (pOther.gameObject.tag == "sword") { Instantblod(pOther); damage.Play(); Back(); } } private void Update() { } private void Instantblod(Collision pOther) { ContactPoint contact = pOther.contacts[0]; Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal); Vector3 pos = contact.point; //这个就是碰撞点 blod = Instantiate(blod, pos, rot); //在碰撞点产生爆炸火焰 blod.transform.parent = this.transform; } //若Rigbody不FreezePosition会产生后退 但效果不明显 会偏移 原因可能为采用的模型问题 //所以用此方法模拟后退 private void Back() { this.gameObject.transform.Translate(new Vector3(-1, 0, -1)); } IEnumerator WaitSeconds(float waitTime) { yield return new WaitForSeconds(waitTime); SceneManager.LoadScene("Final"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief テスト。 */ /** test05 マウス ジョイスティック キー */ public class test05 : main_base { /** 削除管理。 */ private NDeleter.Deleter deleter; /** 背景。 */ private NRender2D.Sprite2D sprite_bg; /** テキスト。 */ private NRender2D.Text2D text_mouse; /** テキスト。 */ private NRender2D.Text2D text_key; /** テキスト。 */ private NRender2D.Text2D text_pad_1; private NRender2D.Text2D text_pad_2; /** mouse_sprite */ private NRender2D.Sprite2D mouse_sprite; /** タッチビューID。 */ private int touchview_id; /** タッチビュー。 */ class TouchView : NInput.Touch_Phase_Key_Base { public int id; public NRender2D.Sprite2D sprite; public NRender2D.Text2D text; public NInput.Touch_Phase touch_phase; public NDeleter.Deleter deleter; /** constructor */ public TouchView(int a_id,NDeleter.Deleter a_deleter,NInput.Touch_Phase a_touch_phase) { this.id = a_id; this.deleter = a_deleter; this.touch_phase = a_touch_phase; this.sprite = new NRender2D.Sprite2D(this.deleter,null,1); { int t_size = 100; this.sprite.SetTextureRect(ref NRender2D.Render2D.TEXTURE_RECT_MAX); this.sprite.SetTexture(Texture2D.whiteTexture); this.sprite.SetColor(Random.value,Random.value,Random.value,1.0f); this.sprite.SetRect(this.touch_phase.value_x-t_size/2,this.touch_phase.value_y-t_size/2,t_size,t_size); } this.text = new NRender2D.Text2D(this.deleter,null,1); { this.text.SetRect(this.touch_phase.value_x,this.touch_phase.value_y,0,0); } } /** [Touch_Phase_Key_Base]更新。 */ public void OnUpdate() { int t_size = 100; this.sprite.SetRect(this.touch_phase.value_x-t_size/2,this.touch_phase.value_y-t_size/2,t_size,t_size); this.text.SetRect(this.touch_phase.value_x,this.touch_phase.value_y - 100,0,0); string t_text = ""; t_text += "id = " + this.id.ToString() + " "; t_text += this.touch_phase.phasetype.ToString().Substring(0,1) + " "; t_text += "rawid = " + this.touch_phase.raw_id.ToString() + " "; /* t_text += "pressure = " + this.touch_phase.pressure.ToString() + " "; t_text += "radius = " + this.touch_phase.radius.ToString() + " "; t_text += "altitude = " + this.touch_phase.angle_altitude.ToString() + " "; t_text += "azimuth = " + this.touch_phase.angle_azimuth.ToString() + " "; */ this.text.SetText(t_text); } /** [Touch_Phase_Key_Base]削除。 */ public void OnRemove() { this.deleter.UnRegister(this.sprite); this.deleter.UnRegister(this.text); this.sprite.Delete(); this.text.Delete(); this.sprite = null; this.text = null; } }; /** touch_list */ private Dictionary<TouchView,NInput.Touch_Phase> touch_list; /** Start */ private void Start() { //タスク。インスタンス作成。 NTaskW.TaskW.CreateInstance(); //パフォーマンスカウンター。インスタンス作成。 //NPerformanceCounter.Config.LOG_ENABLE = true; //NPerformanceCounter.PerformanceCounter.CreateInstance(); //2D描画。 NRender2D.Render2D.CreateInstance(); //マウス。インスタンス作成。 NInput.Mouse.CreateInstance(); //キー。インスタンス作成。 NInput.Key.CreateInstance(); //パッド。インスタンス作成。 NInput.Pad.CreateInstance(); //タッチ。 NInput.Touch.CreateInstance(); NInput.Touch.GetInstance().SetCallBack(CallBack_OnTouch); //イベントプレート。 NEventPlate.Config.LOG_ENABLE = true; NEventPlate.EventPlate.CreateInstance(); //UI。インスタンス作成。 NUi.Config.LOG_ENABLE = true; NUi.Ui.CreateInstance(); //削除管理。 this.deleter = new NDeleter.Deleter(); //戻るボタン作成。 this.CreateReturnButton(this.deleter,(NRender2D.Render2D.MAX_LAYER - 1) * NRender2D.Render2D.DRAWPRIORITY_STEP); //背景。 int t_layerindex = 0; long t_drawpriority = t_layerindex * NRender2D.Render2D.DRAWPRIORITY_STEP; this.sprite_bg = new NRender2D.Sprite2D(this.deleter,null,t_drawpriority); this.sprite_bg.SetTextureRect(ref NRender2D.Render2D.TEXTURE_RECT_MAX); this.sprite_bg.SetTexture(Texture2D.whiteTexture); this.sprite_bg.SetRect(ref NRender2D.Render2D.VIRTUAL_RECT_MAX); this.sprite_bg.SetMaterialType(NRender2D.Config.MaterialType.Alpha); this.sprite_bg.SetColor(0.0f,0.0f,0.0f,1.0f); //テキスト。 this.text_mouse = new NRender2D.Text2D(this.deleter,null,t_drawpriority); this.text_mouse.SetRect(10,100 + 50 * 0,0,0); this.text_mouse.SetFontSize(17); //テキスト。 this.text_key = new NRender2D.Text2D(this.deleter,null,t_drawpriority); this.text_key.SetRect(10,100 + 50 * 1,0,0); this.text_key.SetFontSize(20); //テキスト。 this.text_pad_1 = new NRender2D.Text2D(this.deleter,null,t_drawpriority); this.text_pad_1.SetRect(10,100 + 50 * 2,0,0); this.text_pad_1.SetFontSize(20); //テキスト。 this.text_pad_2 = new NRender2D.Text2D(this.deleter,null,t_drawpriority); this.text_pad_2.SetRect(10,100 + 50 * 3,0,0); this.text_pad_2.SetFontSize(20); //スプライト。 this.mouse_sprite = new NRender2D.Sprite2D(this.deleter,null,t_drawpriority + 1); this.mouse_sprite.SetTextureRect(ref NRender2D.Render2D.TEXTURE_RECT_MAX); this.mouse_sprite.SetTexture(Texture2D.whiteTexture); this.mouse_sprite.SetRect(0,0,10,10); this.mouse_sprite.SetColor(1.0f,1.0f,1.0f,1.0f); //touch_list this.touch_list = NInput.Touch.CreateTouchList<TouchView>(); } /** コールバック。 */ public void CallBack_OnTouch(NInput.Touch_Phase a_touch_phase) { this.touchview_id++; this.touch_list.Add(new TouchView(this.touchview_id,this.deleter,a_touch_phase),a_touch_phase); } /** FixedUpdate */ private void FixedUpdate() { //マウス。 NInput.Mouse.GetInstance().Main(NRender2D.Render2D.GetInstance()); //キー。 NInput.Key.GetInstance().Main(); //パッド。 NInput.Pad.GetInstance().Main(); //タッチ。 NInput.Touch.GetInstance().Main(NRender2D.Render2D.GetInstance()); //イベントプレート。 NEventPlate.EventPlate.GetInstance().Main(NInput.Mouse.GetInstance().pos.x,NInput.Mouse.GetInstance().pos.y); //UI。 NUi.Ui.GetInstance().Main(); //モーター。 { NInput.Pad.GetInstance().moter_low.Request(NInput.Pad.GetInstance().left_trigger2_button.value); NInput.Pad.GetInstance().moter_high.Request(NInput.Pad.GetInstance().right_trigger2_button.value); } //タッチ。 { NInput.Touch.UpdateTouchList(this.touch_list); } //マウス位置。 { string t_text = ""; if(NInput.Mouse.GetInstance().left.on == true){ t_text += "l[o]"; }else{ t_text += "l[ ]"; } if(NInput.Mouse.GetInstance().right.on == true){ t_text += "r[o]"; }else{ t_text += "r[ ]"; } if(NInput.Mouse.GetInstance().middle.on == true){ t_text += "m[o]"; }else{ t_text += "m[ ]"; } t_text += "x = " + NInput.Mouse.GetInstance().pos.x.ToString() + " "; t_text += "y = " + NInput.Mouse.GetInstance().pos.y.ToString() + " "; t_text += "m = " + NInput.Mouse.GetInstance().mouse_wheel.y.ToString() + " "; this.text_mouse.SetText(t_text); this.mouse_sprite.SetXY(NInput.Mouse.GetInstance().pos.x,NInput.Mouse.GetInstance().pos.y); } //キー。 { string t_text = ""; if(NInput.Key.GetInstance().enter.on == true){ t_text += "enter[o]"; }else{ t_text += "enter[ ]"; } if(NInput.Key.GetInstance().escape.on == true){ t_text += "escape[o]"; }else{ t_text += "escape[ ]"; } if(NInput.Key.GetInstance().sub1.on == true){ t_text += "sub1[o]"; }else{ t_text += "sub1[ ]"; } if(NInput.Key.GetInstance().sub2.on == true){ t_text += "sub2[o]"; }else{ t_text += "sub2[ ]"; } t_text += " "; if(NInput.Key.GetInstance().left.on == true){ t_text += "l[o]"; }else{ t_text += "l[ ]"; } if(NInput.Key.GetInstance().right.on == true){ t_text += "r[o]"; }else{ t_text += "r[ ]"; } if(NInput.Key.GetInstance().up.on == true){ t_text += "u[o]"; }else{ t_text += "u[ ]"; } if(NInput.Key.GetInstance().down.on == true){ t_text += "d[o]"; }else{ t_text += "d[ ]"; } t_text += " "; if(NInput.Key.GetInstance().left_menu.on == true){ t_text += "left_menu[o]"; }else{ t_text += "left_menu[ ]"; } if(NInput.Key.GetInstance().right_menu.on == true){ t_text += "right_menu[o]"; }else{ t_text += "right_menu[ ]"; } this.text_key.SetText(t_text); } //パッド。 { string t_text = ""; if(NInput.Pad.GetInstance().enter.on == true){ t_text += "enter[o]"; }else{ t_text += "enter[ ]"; } if(NInput.Pad.GetInstance().escape.on == true){ t_text += "escape[o]"; }else{ t_text += "escape[ ]"; } if(NInput.Pad.GetInstance().sub1.on == true){ t_text += "sub1[o]"; }else{ t_text += "sub1[ ]"; } if(NInput.Pad.GetInstance().sub2.on == true){ t_text += "sub2[o]"; }else{ t_text += "sub2[ ]"; } t_text += " "; if(NInput.Pad.GetInstance().left.on == true){ t_text += "l[o]"; }else{ t_text += "l[ ]"; } if(NInput.Pad.GetInstance().right.on == true){ t_text += "r[o]"; }else{ t_text += "r[ ]"; } if(NInput.Pad.GetInstance().up.on == true){ t_text += "u[o]"; }else{ t_text += "u[ ]"; } if(NInput.Pad.GetInstance().down.on == true){ t_text += "d[o]"; }else{ t_text += "d[ ]"; } t_text += " "; if(NInput.Pad.GetInstance().left_menu.on == true){ t_text += "left_menu[o]"; }else{ t_text += "left_menu[ ]"; } if(NInput.Pad.GetInstance().right_menu.on == true){ t_text += "right_menu[o]"; }else{ t_text += "right_menu[ ]"; } this.text_pad_1.SetText(t_text); } { string t_text = ""; if(NInput.Pad.GetInstance().left_stick_button.on == true){ t_text += "l_stick[o]"; }else{ t_text += "l_stick[ ]"; } if(NInput.Pad.GetInstance().right_stick_button.on == true){ t_text += "r_stick[o]"; }else{ t_text += "r_stick[ ]"; } if(NInput.Pad.GetInstance().left_trigger1_button.on == true){ t_text += "l_trigger1[o]"; }else{ t_text += "l_trigger1[ ]"; } if(NInput.Pad.GetInstance().right_trigger1_button.on == true){ t_text += "r_trigger1[o]"; }else{ t_text += "r_trigger1[ ]"; } if(NInput.Pad.GetInstance().left_trigger2_button.on == true){ t_text += "l_trigger2[o]"; }else{ t_text += "l_trigger2[ ]"; } if(NInput.Pad.GetInstance().right_trigger2_button.on == true){ t_text += "r_trigger2[o]"; }else{ t_text += "r_trigger2[ ]"; } t_text += "\n"; t_text += "l stick = " + ((int)(NInput.Pad.GetInstance().left_stick.x * 100)).ToString() + " " + ((int)(NInput.Pad.GetInstance().left_stick.y * 100)).ToString() + "\n"; t_text += "r stick = " + ((int)(NInput.Pad.GetInstance().right_stick.x * 100)).ToString() + " " + ((int)(NInput.Pad.GetInstance().right_stick.y * 100)).ToString() + "\n"; t_text += "trigger2 = "+ ((int)(NInput.Pad.GetInstance().left_trigger2_button.value * 100)).ToString() + " " + ((int)(NInput.Pad.GetInstance().right_trigger2_button.value * 100)).ToString() + "\n"; this.text_pad_2.SetText(t_text); } } /** 削除前。 */ public override bool PreDestroy(bool a_first) { return true; } /** OnDestroy */ private void OnDestroy() { this.deleter.DeleteAll(); } /** 追加。 */ #if(UNITY_EDITOR) [UnityEditor.MenuItem("Test/Test05/EditInputManager")] private static void MakeInputManager() { NInput.EditInputManager t_inputmaanger = new NInput.EditInputManager(); { List<NInput.EditInputManager_Item> t_list = t_inputmaanger.GetList(); bool t_find_left = false; bool t_find_right = false; bool t_find_up = false; bool t_find_down = false; bool t_find_enter = false; bool t_find_escape = false; bool t_find_sub1 = false; bool t_find_sub2 = false; bool t_find_left_menu = false; bool t_find_right_menu = false; bool t_left_stick_axis_x = false; bool t_left_stick_axis_y = false; bool t_right_stick_axis_x = false; bool t_right_stick_axis_y = false; bool t_left_stick_button = false; bool t_right_stick_button = false; bool t_left_trigger1_button = false; bool t_right_trigger1_button = false; bool t_left_trigger2_axis = false; bool t_right_trigger2_axis = false; for(int ii=0;ii<t_list.Count;ii++){ switch(t_list[ii].m_Name){ case NInput.EditInputManager_Item.ButtonName.LEFT: t_find_left = true; break; case NInput.EditInputManager_Item.ButtonName.RIGHT: t_find_right = true; break; case NInput.EditInputManager_Item.ButtonName.UP: t_find_up = true; break; case NInput.EditInputManager_Item.ButtonName.DOWN: t_find_down = true; break; case NInput.EditInputManager_Item.ButtonName.ENTER: t_find_enter = true; break; case NInput.EditInputManager_Item.ButtonName.ESCAPE: t_find_escape = true; break; case NInput.EditInputManager_Item.ButtonName.SUB1: t_find_sub1 = true; break; case NInput.EditInputManager_Item.ButtonName.SUB2: t_find_sub2 = true; break; case NInput.EditInputManager_Item.ButtonName.LEFT_MENU: t_find_left_menu = true; break; case NInput.EditInputManager_Item.ButtonName.RIGHT_MENU: t_find_right_menu = true; break; case NInput.EditInputManager_Item.ButtonName.LEFT_STICK_AXIS_X: t_left_stick_axis_x = true; break; case NInput.EditInputManager_Item.ButtonName.LEFT_STICK_AXIS_Y: t_left_stick_axis_y = true; break; case NInput.EditInputManager_Item.ButtonName.RIGHT_STICK_AXIS_X: t_right_stick_axis_x = true; break; case NInput.EditInputManager_Item.ButtonName.RIGHT_STICK_AXIS_Y: t_right_stick_axis_y = true; break; case NInput.EditInputManager_Item.ButtonName.LEFT_STICK_BUTTON: t_left_stick_button = true; break; case NInput.EditInputManager_Item.ButtonName.RIGHT_STICK_BUTTON: t_right_stick_button = true; break; case NInput.EditInputManager_Item.ButtonName.LEFT_TRIGGER1_BUTTON: t_left_trigger1_button = true; break; case NInput.EditInputManager_Item.ButtonName.RIGHT_TRIGGER1_BUTTON: t_right_trigger1_button = true; break; case NInput.EditInputManager_Item.ButtonName.LEFT_TRIGGER2_AXIS: t_left_trigger2_axis = true; break; case NInput.EditInputManager_Item.ButtonName.RIGHT_TRIGGER2_AXIS: t_right_trigger2_axis = true; break; } } { //デジタルボタン。上下左右。 if(t_find_left == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonLeft(); t_list.Add(t_item); } if(t_find_right == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonRight(); t_list.Add(t_item); } if(t_find_up == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonUp(); t_list.Add(t_item); } if(t_find_down == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonDown(); t_list.Add(t_item); } //デジタルボタン。 if(t_find_enter == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonEnter(); t_list.Add(t_item); } if(t_find_escape == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonEscape(); t_list.Add(t_item); } if(t_find_sub1 == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonSub1(); t_list.Add(t_item); } if(t_find_sub2 == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonSub2(); t_list.Add(t_item); } //デジタルボタン。 if(t_find_left_menu == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonLeftMenu(); t_list.Add(t_item); } if(t_find_right_menu == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateDigitalButtonRightMenu(); t_list.Add(t_item); } //スティック。方向。 if(t_left_stick_axis_x == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateLeftStickAxisX(); t_list.Add(t_item); } if(t_left_stick_axis_y == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateLeftStickAxisY(); t_list.Add(t_item); } if(t_right_stick_axis_x == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateRightStickAxisX(); t_list.Add(t_item); } if(t_right_stick_axis_y == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateRightStickAxisY(); t_list.Add(t_item); } //スティック。ボタン。 if(t_left_stick_button == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateLeftStickButton(); t_list.Add(t_item); } if(t_right_stick_button == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateRightStickButton(); t_list.Add(t_item); } //トリガー。 if(t_left_trigger1_button == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateLeftTrigger1Button(); t_list.Add(t_item); } if(t_right_trigger1_button == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateRightTrigger1Button(); t_list.Add(t_item); } if(t_left_trigger2_axis == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateLeftTrigger2Button(); t_list.Add(t_item); } if(t_right_trigger2_axis == false){ NInput.EditInputManager_Item t_item = new NInput.EditInputManager_Item(); t_item.CreateRightTrigger2Button(); t_list.Add(t_item); } } } t_inputmaanger.Save(); } #endif }
using Amazon.Runtime; using Amazon.S3.Model; using OpenTracing; namespace Epsagon.Dotnet.Instrumentation.Handlers.S3.Operations { public class PutObjectRequestHandler : IOperationHandler { public void HandleOperationAfter(IExecutionContext context, IScope scope) { var response = context.ResponseContext.Response as PutObjectResponse; scope.Span.SetTag("aws.s3.etag", response.ETag); } public void HandleOperationBefore(IExecutionContext context, IScope scope) { var request = context.RequestContext.OriginalRequest as PutObjectRequest; scope.Span.SetTag("resource.name", request.BucketName); scope.Span.SetTag("aws.s3.bucket", request.BucketName); scope.Span.SetTag("aws.s3.key", request.Key); } } }
using System; using System.Collections.Generic; namespace RestApiEcom.Models { public partial class TSonProfession { public TSonProfession() { TSonPopulation = new HashSet<TSonPopulation>(); } public int ProfId { get; set; } public string ProfLibelle { get; set; } public virtual ICollection<TSonPopulation> TSonPopulation { get; set; } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Runtime.Remoting; using RemoteServices; using System.Diagnostics; namespace pacman { class PuppetMaster { static PuppetMasterWindow form; private static Dictionary<string, string> pidUrl = new Dictionary<string, string>(); private static List<string> servers = new List<string>(); private static List<string> clients = new List<string>(); private static List<string> listPCS = new List<string>(); [STAThread] static void Main() { //var th = new Thread(consoleApp); //th.Start(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); form = new PuppetMasterWindow(); Application.Run(form); } static string[] splitInputBox(string input) { string[] result = input.Split(' '); return result; } public static void read(String input) { string[] commands = splitInputBox(input); switch (commands[0]) { case "StartClient": startClient(commands[1], commands[2], commands[3], Int32.Parse(commands[4]), Int32.Parse(commands[5])); break; case "StartServer": startServer(commands[1], commands[2], commands[3], Int32.Parse(commands[4]), Int32.Parse(commands[5])); break; case "GlobalStatus": globalStatus(); break; case "Crash": crash(commands[1]); break; case "Freeze": freeze(commands[1]); break; case "Unfreeze": unfreeze(commands[1]); break; case "InjectDelay": break; case "LocalState": break; case "Wait": wait(commands[1]); break; default: form.changeText("Command not found"); break; } } static void startClient(string pid, string pcs_url, string client_url, int msec_per_round, int num_players) { //IPCS = getPCS(pcs_url); //IPCS.create(pid, pcs_url, client_url, msec_per_round, num_players); pidUrl.Add(pid, client_url); clients.Add(client_url); string commands = client_url + " " + msec_per_round + " " + num_players; ProcessStartInfo info = new ProcessStartInfo(Client.executionPath(), commands); info.CreateNoWindow = false; Process.Start(info); } static void startServer(string pid, string pcs_url, string server_url, int msec_per_round, int num_players) {; //IPCS = getPCS(pcs_url); //IPCS.create(pid, pcs_url, server_url, msec_per_round, num_players); string commands; if (servers.Count == 0) { commands = server_url + " " + msec_per_round + " " + num_players + " " + 0; } else { commands = server_url + " " + msec_per_round + " " + num_players + " " + 1; } pidUrl.Add(pid, server_url); servers.Add(server_url); ProcessStartInfo info = new ProcessStartInfo(Server.executionPath(), commands); info.CreateNoWindow = false; Process.Start(info); } static void globalStatus() { string actives = ""; string inactives = ""; foreach(var server_url in servers) { IServer remote = RemotingServices.Connect(typeof(IServer), server_url) as IServer; if (remote.getStatus().Equals("On")) { actives += "PID: " + server_url + ", "; } else { inactives += "PID: " + server_url + ", "; } } foreach (var client_url in clients) { IClient remote = RemotingServices.Connect(typeof(IClient), client_url) as IClient; if (remote.getStatus().Equals("On")) { actives += "PID: " + client_url + ", "; } else { inactives += "PID: " + client_url + ", "; } } form.changeText("Who is alive: " + actives + "\r\n" + "Who seems to be down: " + inactives); } static void crash(string pid) { string[] words = pidUrl[pid].Split(':', '/'); int port = Int32.Parse(words[4]); if (servers.Contains(pidUrl[pid])) { IServer remote = RemotingServices.Connect(typeof(IServer), "tcp://localhost:" + port + "/" + words[5]) as IServer; try { pidUrl.Remove(pid); remote.getProcessToCrash(); } catch (Exception ex) { }; } else if(clients.Contains(pidUrl[pid])) { IClient remote = RemotingServices.Connect(typeof(IClient), "tcp://localhost:" + port + "/" + words[5]) as IClient; try { pidUrl.Remove(pid); remote.getProcessToCrash(); } catch (Exception ex) { }; } } static void freeze(string pid) { string[] words = pidUrl[pid].Split(':', '/'); int port = Int32.Parse(words[4]); if (servers.Contains(pidUrl[pid])) { IServer remote = RemotingServices.Connect(typeof(IServer), "tcp://localhost:" + port + "/" + words[5]) as IServer; try { remote.freeze(); } catch (Exception ex) { }; } else if (clients.Contains(pidUrl[pid])) { IClient remote = RemotingServices.Connect(typeof(IClient), "tcp://localhost:" + port + "/" + words[5]) as IClient; try { remote.freeze(); } catch (Exception ex) { }; } } static void unfreeze(string pid) { string[] words = pidUrl[pid].Split(':', '/'); int port = Int32.Parse(words[4]); if (servers.Contains(pidUrl[pid])) { IServer remote = RemotingServices.Connect(typeof(IServer), "tcp://localhost:" + port + "/" + words[5]) as IServer; try { remote.unfreeze(); } catch (Exception ex) { }; } else if (clients.Contains(pidUrl[pid])) { IClient remote = RemotingServices.Connect(typeof(IClient), "tcp://localhost:" + port + "/" + words[5]) as IClient; try { remote.unfreeze(); } catch (Exception ex) { }; } } static void wait(string time) { System.Threading.Thread.Sleep(Int32.Parse(time)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Globalization; using System.Linq; namespace GdNet.Common.Tests { [TestClass] public class RandomStringTests { [TestMethod] public void CanGetNextValueNumbers() { var generator = new RandomString(); var x = generator.NextValue(); Assert.AreEqual(6, x.Length); x.ToCharArray().ToList().ForEach(c => { int num; if (!int.TryParse(c.ToString(CultureInfo.InvariantCulture), out num)) { Assert.Fail("Must contain only number characters"); } }); } [TestMethod] public void CanGetNextValueAny() { var generator = new RandomString(12, RandomString.Options.Any); var x = generator.NextValue(); Assert.AreEqual(12, x.Length); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CheckMySymptoms.Utils { public struct ResourceStringNames { public const string settingNavOnlyMenuItemText = "settingNavOnlyMenuItemText"; public const string symptomCheckerResetNotificationText = "symptomCheckerResetNotificationText"; public const string voiceChangedTextFormat = "voiceChangedTextFormat"; public const string goBackVoiceCommand = "goBackVoiceCommand"; public const string notificationText01 = "notificationText01"; public const string notificationText02 = "notificationText02"; public const string notificationText03 = "notificationText03"; public const string errorGettingAddOnsFormat = "errorGettingAddOnsFormat"; public const string subscriptionToPurchaseNotFound = "subscriptionToPurchaseNotFound"; public const string adFreePurchaseSuccessful = "adFreePurchaseSuccessful"; public const string addOnNotPurchasedFormat = "addOnNotPurchasedFormat"; public const string addOnErrorDuringPurchaseFormat = "addOnErrorDuringPurchaseFormat"; public const string addOnAlreadyPurchasedFormat = "addOnAlreadyPurchasedFormat"; } public struct RoamingData { public const string SoundPlayerState = "SoundPlayerState"; public const string SpatialAudioMode = "SpatialAudioMode"; public const string SelectedVoice = "SelectedVoice"; public const string VoiceOn = "VoiceOn"; } public struct SpeechRecognitionConstants { public const string GOBACKTAG = "goBack"; public const string OPTIONSTAG = "options"; public const double InitialSilenceTimeout = 12; public const double EndSilenceTimeout = 5; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Promact.Oauth.Server.Services { public interface IHttpClientService { Task<string> GetAsync(string baseUrl, string contentUrl); } }
using AutoMapper; using esstp.Models.ViewModels; namespace esstp.Models.Helpers { public class AutoMapper : Profile { public AutoMapper() { CreateMap<User, UserViewModel>(); CreateMap<UserViewModel, User>(); CreateMap<User, SignupViewModel>(); CreateMap<SignupViewModel, User>(); CreateMap<Role, RoleViewModel>(); CreateMap<RoleViewModel, Role>(); CreateMap<Market, MarketViewModel>(); CreateMap<MarketViewModel, Market>(); CreateMap<Portfolio, PortfolioPageViewModel>(); CreateMap<PortfolioPageViewModel, Portfolio>(); CreateMap<Portfolio, PortfolioPositionViewModel>(); CreateMap<PortfolioPositionViewModel, Portfolio>(); CreateMap<Portfolio, SubjectModel>(); CreateMap<SubjectModel, Portfolio>(); CreateMap<MarketViewModel, SubjectModel>(); CreateMap<SubjectModel, MarketViewModel>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using eIDEAS.Data; using eIDEAS.Models; using Microsoft.AspNetCore.Identity; namespace eIDEAS.Controllers { public class AmendmentsController : Controller { private readonly ApplicationDbContext _context; private readonly UserManager<ApplicationUser> _userManager; public AmendmentsController(ApplicationDbContext context, UserManager<ApplicationUser> userManager) { _context = context; _userManager = userManager; } public ActionResult AmendmentsRefreshHandler() { return View(); } // POST: Amendments/Create [HttpPost] public async Task<IActionResult> Update(int ideaID, string comment) { var loggedInUserID = _userManager.GetUserId(HttpContext.User); var amendment = new Amendment(); //Create the amendment amendment.IdeaID = ideaID; amendment.Comment = comment; amendment.UserID = new Guid(loggedInUserID); amendment.DateCreated = DateTime.UtcNow; _context.Add(amendment); await _context.SaveChangesAsync(); //Give the amendment author 100 participation points var loggedInUser = _context.Users.Where(user => user.Id == loggedInUserID).FirstOrDefault(); loggedInUser.ParticipationPoints += 100; _context.Update(loggedInUser); await _context.SaveChangesAsync(); //Get and return amendments //Retrieve amendments for submitted ideas List<AmendmentPresentationViewModel> amendmentViewModel = new List<AmendmentPresentationViewModel>(); var amendments = _context.Amendment.Where(a => a.IdeaID == ideaID); foreach (Amendment amendmentVal in amendments) { ApplicationUser amendmentAuthor = _context.Users.Where(user => user.Id == amendment.UserID.ToString()).FirstOrDefault(); var amendmentPresentation = new AmendmentPresentationViewModel { AuthorFirstName = amendmentAuthor.FirstName, AuthorLastName = amendmentAuthor.LastName, Comment = amendmentVal.Comment, PostingDate = amendmentVal.DateCreated }; amendmentViewModel.Add(amendmentPresentation); } return PartialView("_AmendmentPartial", amendmentViewModel); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using SaleShop.Common.ViewModels; using SaleShop.Data.Infrastructure; using SaleShop.Model.Models; namespace SaleShop.Data.Repositories { public interface IOrderRepository: IRepository<Order> { IEnumerable<RevenueStatisticViewModel> GetRevenueStatistic(string fromDate, string toDate); } public class OrderRepository : RepositoryBase<Order>, IOrderRepository { public OrderRepository(IDbFactory dbFactory) : base(dbFactory) { } public IEnumerable<RevenueStatisticViewModel> GetRevenueStatistic(string fromDate, string toDate) { var parameters = new SqlParameter[] { new SqlParameter("@fromDate", fromDate), new SqlParameter("@toDate", toDate) }; return DbContext.Database.SqlQuery<RevenueStatisticViewModel>("GetRevenueStatistic @fromDate,@toDate",parameters); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Game : MonoBehaviour { // Use this for initialization void Start () { GameObject go1 = Instantiate(Resources.Load("Cube")) as GameObject; for (int i = 0; i > 100;i++){ GameObject go = Instantiate(go1) as GameObject; go.transform.position = new Vector3(0, i * 5, 0); } } // Update is called once per frame void Update () { } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using core.Server; using core.ServerInterface; using core.TableStoreEntities; namespace test.ServerInterface { [TestClass] public class CommHandlerTest { [TestMethod] public void CommHandlerTest_Constructor_ValidParams() { // Create objects var mockCommLayer = new Mock<ICommLayer>(); var commHandler = new CommHandler(); commHandler.CommLayer = mockCommLayer.Object; // Subscribe to CommHandler bool raised = false; commHandler.CoreListener += delegate { raised = true; }; // Raise MessageSent event in Server var msg = new ChatMessage(new DateTime(2012, 12, 18), "Llamautomatic", "This is a test message", "all"); mockCommLayer.Raise(m => m.CommHandler += null, new ChatEventArgs(msg)); // Check if CommHandler was successfully raised in response Assert.IsTrue(raised); } [TestMethod] public void CommHandlerTest_Constructor_NullParams() { // Create objects var commHandler = new CommHandler(); // Check for empty CommHandler reference in Core Assert.AreEqual(commHandler.CommLayer, null); } } }
using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Newtonsoft.Json.Linq; using XUnitMoqSampleWeb.Services; namespace XUnitMoqSampleWeb.Controllers { using System; /// <summary> /// This represents the controller entity for /home. /// </summary> public class HomeController : Controller { private readonly IGitHubApiService _service; /// <summary> /// Initializes a new instance of the <see cref="HomeController"/> class. /// </summary> /// <param name="service"><see cref="IGitHubApiService"/> instance.</param> public HomeController(IGitHubApiService service) { if (service == null) { throw new ArgumentNullException(nameof(service)); } this._service = service; } /// <summary> /// Gets the <see cref="IActionResult"/> for /home/index. /// </summary> /// <returns>Returns the <see cref="IActionResult"/>.</returns> public async Task<IActionResult> Index() { var result = await this._service.GetOrgReposAsync("devkimchi").ConfigureAwait(false); this.ViewBag.Repos = JArray.Parse(result); return this.View(); } /// <summary> /// Gets the <see cref="IActionResult"/> for /home/about. /// </summary> /// <returns>Returns the <see cref="IActionResult"/>.</returns> public IActionResult About() { this.ViewData["Message"] = "Your application description page."; return this.View(); } /// <summary> /// Gets the <see cref="IActionResult"/> for /home/contact. /// </summary> /// <returns>Returns the <see cref="IActionResult"/>.</returns> public IActionResult Contact() { this.ViewData["Message"] = "Your contact page."; return this.View(); } /// <summary> /// Gets the <see cref="IActionResult"/> for /home/error. /// </summary> /// <returns>Returns the <see cref="IActionResult"/>.</returns> public IActionResult Error() { return this.View(); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace webapi.Models { public class TransactionInfo { [JsonProperty("fullName", Required = Required.DisallowNull)] public string FullName { get; set; } [JsonProperty("creditCardNumber", Required = Required.DisallowNull)] public string CreditCardNumber { get; set; } [JsonProperty("creditCardCompeny", Required = Required.DisallowNull)] public string CreditCardCompeny { get; set; } [JsonProperty("expirationDate", Required = Required.DisallowNull)] public string ExpirationDate { get; set; } [JsonProperty("cvv", Required = Required.DisallowNull)] public string Cvv { get; set; } [JsonProperty("amount", Required = Required.DisallowNull)] public float Amount { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace SincolPDV.DAL { public class ClienteDAL { string conexao = ConfigurationManager.ConnectionStrings["context"].ConnectionString.ToString(); private SqlConnection _conn; private SqlCommand comando; private SqlDataAdapter oda; public ClienteDAL() { _conn = new SqlConnection(conexao); _conn.Open(); } public DataTable ConsultaCliente(string procedure, int campo) { DataTable i = new DataTable(); SqlParameter pfiltro; oda = new SqlDataAdapter(); oda.SelectCommand = new SqlCommand(); oda.SelectCommand.CommandText = procedure; oda.SelectCommand.Connection = _conn; oda.SelectCommand.CommandType = CommandType.StoredProcedure; pfiltro = oda.SelectCommand.Parameters.Add("@codigo", SqlDbType.Int); pfiltro.Value = campo; oda.Fill(i); return i; } public int InserirCliente(string procedure, string clie_nome, string clie_tp_pessoa, int clie_status, string clie_cpf, string clie_cnpj, string clie_telefone, string clie_endereco, string clie_sexo, DateTime clie_dt_nascimento, string clie_email, DateTime clie_dt_cadastro, DateTime clie_dt_atualizacao, decimal clie_limite_credito, int clie_qtd_dias_credito, string clie_observacao) { try { int result; comando = new SqlCommand(); comando.Connection = _conn; comando.CommandType = CommandType.StoredProcedure; comando.CommandText = procedure; SqlParameter pclie_nome = new SqlParameter("@nome", SqlDbType.Text); pclie_nome.Value = clie_nome; SqlParameter pclie_tp_pessoa = new SqlParameter("@tp_pessoa", SqlDbType.Char); pclie_tp_pessoa.Value = clie_tp_pessoa; SqlParameter pclie_cpf = new SqlParameter("@cpf", SqlDbType.Text); pclie_cpf.Value = clie_cpf; SqlParameter pclie_cnpj = new SqlParameter("@cnpj", SqlDbType.Text); pclie_cnpj.Value = clie_cnpj; SqlParameter pclie_telefone = new SqlParameter("@telefone", SqlDbType.Text); pclie_telefone.Value = clie_telefone; //SqlParameter pprod_imagem = new SqlParameter("@imagem", SqlDbType.Text); //pprod_imagem.Value = prod_imagem; SqlParameter pclie_endereco= new SqlParameter("@endereco", SqlDbType.Text); pclie_endereco.Value = clie_endereco; SqlParameter pclie_sexo = new SqlParameter("@sexo", SqlDbType.Text); pclie_sexo.Value = clie_sexo; SqlParameter pclie_dt_nascimento = new SqlParameter("@dt_nasc", SqlDbType.DateTime); pclie_dt_nascimento.Value = clie_dt_nascimento; SqlParameter pclie_email = new SqlParameter("@email", SqlDbType.Text); pclie_email.Value = clie_email; SqlParameter pclie_status= new SqlParameter("@status", SqlDbType.Int); pclie_status.Value = clie_status; SqlParameter pclie_dt_cadastro = new SqlParameter("@dt_cadastro", SqlDbType.DateTime); pclie_dt_cadastro.Value = clie_dt_cadastro; SqlParameter pclie_dt_atualizacao = new SqlParameter("@dt_atualizacao", SqlDbType.DateTime); pclie_dt_atualizacao.Value = clie_dt_atualizacao; SqlParameter pclie_limite_credito = new SqlParameter("@limite_credito", SqlDbType.Decimal); pclie_limite_credito.Value = clie_limite_credito; SqlParameter pclie_qtd_dias_credito = new SqlParameter("@qtd_dias_emprestimo", SqlDbType.Int); pclie_qtd_dias_credito.Value = clie_qtd_dias_credito; SqlParameter pclie_observacao = new SqlParameter("@observacao", SqlDbType.Text); pclie_observacao.Value = clie_observacao; comando.Parameters.Add(pclie_nome); comando.Parameters.Add(pclie_tp_pessoa); comando.Parameters.Add(pclie_cpf); comando.Parameters.Add(pclie_cnpj); comando.Parameters.Add(pclie_telefone); //comando.Parameters.Add(pprod_imagem); comando.Parameters.Add(pclie_endereco); comando.Parameters.Add(pclie_sexo); comando.Parameters.Add(pclie_dt_nascimento); comando.Parameters.Add(pclie_email); comando.Parameters.Add(pclie_status); comando.Parameters.Add(pclie_dt_cadastro); comando.Parameters.Add(pclie_dt_atualizacao); comando.Parameters.Add(pclie_limite_credito); comando.Parameters.Add(pclie_qtd_dias_credito); comando.Parameters.Add(pclie_observacao); return result = comando.ExecuteNonQuery(); } catch (SqlException ex) { throw new Exception("Erro ao inserir Cliente:" + ex.Message); } } public int AlterarCliente(string procedure, int clie_codigo, string clie_nome, string clie_tp_pessoa, int clie_status, string clie_cpf, string clie_cnpj, string clie_telefone, string clie_endereco, string clie_sexo, DateTime clie_dt_nascimento, string clie_email, DateTime clie_dt_cadastro, DateTime clie_dt_atualizacao, decimal clie_limite_credito, int clie_qtd_dias_credito, string clie_observacao) { try { comando = new SqlCommand(); comando.Connection = _conn; comando.CommandType = CommandType.StoredProcedure; comando.CommandText = procedure; SqlParameter pclie_codigo = new SqlParameter("@codigo", SqlDbType.Int); pclie_codigo.Value = clie_codigo; SqlParameter pclie_nome = new SqlParameter("@nome", SqlDbType.Text); pclie_nome.Value = clie_nome; SqlParameter pclie_tp_pessoa = new SqlParameter("@tp_pessoa", SqlDbType.Char); pclie_tp_pessoa.Value = clie_tp_pessoa; SqlParameter pclie_cpf = new SqlParameter("@cpf", SqlDbType.Text); pclie_cpf.Value = clie_cpf; SqlParameter pclie_cnpj = new SqlParameter("@cnpj", SqlDbType.Text); pclie_cnpj.Value = clie_cnpj; SqlParameter pclie_telefone = new SqlParameter("@telefone", SqlDbType.Text); pclie_telefone.Value = clie_telefone; //SqlParameter pprod_imagem = new SqlParameter("@imagem", SqlDbType.Text); //pprod_imagem.Value = prod_imagem; SqlParameter pclie_endereco = new SqlParameter("@endereco", SqlDbType.Text); pclie_endereco.Value = clie_endereco; SqlParameter pclie_sexo = new SqlParameter("@sexo", SqlDbType.Text); pclie_sexo.Value = clie_sexo; SqlParameter pclie_dt_nascimento = new SqlParameter("@dt_nasc", SqlDbType.DateTime); pclie_dt_nascimento.Value = clie_dt_nascimento; SqlParameter pclie_email = new SqlParameter("@email", SqlDbType.Text); pclie_email.Value = clie_email; SqlParameter pclie_status = new SqlParameter("@status", SqlDbType.Int); pclie_status.Value = clie_status; SqlParameter pclie_dt_cadastro = new SqlParameter("@dt_cadastro", SqlDbType.DateTime); pclie_dt_cadastro.Value = clie_dt_cadastro; SqlParameter pclie_dt_atualizacao = new SqlParameter("@dt_atualizacao", SqlDbType.DateTime); pclie_dt_atualizacao.Value = clie_dt_atualizacao; SqlParameter pclie_limite_credito = new SqlParameter("@limite_credito", SqlDbType.Decimal); pclie_limite_credito.Value = clie_limite_credito; SqlParameter pclie_qtd_dias_credito = new SqlParameter("@qtd_dias_emprestimo", SqlDbType.Int); pclie_qtd_dias_credito.Value = clie_qtd_dias_credito; SqlParameter pclie_observacao = new SqlParameter("@observacao", SqlDbType.Text); pclie_observacao.Value = clie_observacao; comando.Parameters.Add(pclie_codigo); comando.Parameters.Add(pclie_nome); comando.Parameters.Add(pclie_tp_pessoa); comando.Parameters.Add(pclie_cpf); comando.Parameters.Add(pclie_cnpj); comando.Parameters.Add(pclie_telefone); //comando.Parameters.Add(pprod_imagem); comando.Parameters.Add(pclie_endereco); comando.Parameters.Add(pclie_sexo); comando.Parameters.Add(pclie_dt_nascimento); comando.Parameters.Add(pclie_email); comando.Parameters.Add(pclie_status); comando.Parameters.Add(pclie_dt_cadastro); comando.Parameters.Add(pclie_dt_atualizacao); comando.Parameters.Add(pclie_limite_credito); comando.Parameters.Add(pclie_qtd_dias_credito); comando.Parameters.Add(pclie_observacao); return comando.ExecuteNonQuery(); } catch (SqlException ex) { throw new Exception("Erro ao Alterar Cliente:" + ex.Message); } } public int ExcluirCliente(string procedure, int clie_codigo) { try { comando = new SqlCommand(); comando.Connection = _conn; comando.CommandType = CommandType.StoredProcedure; comando.CommandText = procedure; SqlParameter pclie_codigo = new SqlParameter("@codigo", SqlDbType.Int); pclie_codigo.Value = clie_codigo; comando.Parameters.Add(pclie_codigo); return comando.ExecuteNonQuery(); } catch (SqlException ex) { throw new Exception("Erro ao Excluir Cliente:" + ex.Message); } } public DataTable ListarCliente(string procedure, int codigo, string nome, string cpf, string telefone) { DataTable i = new DataTable(); SqlParameter pfiltro; oda = new SqlDataAdapter(); oda.SelectCommand = new SqlCommand(); oda.SelectCommand.CommandText = procedure; oda.SelectCommand.Connection = _conn; oda.SelectCommand.CommandType = CommandType.StoredProcedure; pfiltro = oda.SelectCommand.Parameters.Add("@codigo", SqlDbType.Int); pfiltro.Value = codigo; pfiltro = oda.SelectCommand.Parameters.Add("@nome", SqlDbType.Text); pfiltro.Value = nome; pfiltro = oda.SelectCommand.Parameters.Add("@cpf", SqlDbType.Text); pfiltro.Value = cpf; pfiltro = oda.SelectCommand.Parameters.Add("@telefone", SqlDbType.Text); pfiltro.Value = telefone; oda.Fill(i); return i; } } }
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using Microsoft.Extensions.Options; namespace AzureBlobUpload.Pages { public class FileInfo { public string Name { get; set; } public string Base64FileData { get; set; } public string ContentType { get; set; } public string Uri { get; set; } } public class EditFileModel : PageModel { private readonly IOptions<StorageAccountInfo> _storageAccountInfOptions; public EditFileModel(IOptions<StorageAccountInfo> storageAccountInfOptions) => _storageAccountInfOptions = storageAccountInfOptions; [BindProperty] public FileInfo FileInfo { get; set; } [BindProperty] public IFormFile Upload { get; set; } public async Task OnGetAsync(string fileName) { var cloudStorageAccount = CloudStorageAccount.Parse(_storageAccountInfOptions.Value.ConnectionString); var blobClient = cloudStorageAccount.CreateCloudBlobClient(); var container = blobClient.GetContainerReference(_storageAccountInfOptions.Value.ContainerName); var file = await container.GetBlobReferenceFromServerAsync(fileName); if (await file.ExistsAsync()) { FileInfo = new FileInfo { ContentType = file.Properties.ContentType, Name = file.Name, Uri = file.Uri.AbsoluteUri }; using (var memoryStream = new MemoryStream()) { await file.DownloadToStreamAsync(memoryStream); var bytes = memoryStream.ToArray(); FileInfo.Base64FileData = Convert.ToBase64String(bytes, 0, bytes.Length); } } } public async Task OnPostAsync() { var cloudStorageAccount = CloudStorageAccount.Parse(_storageAccountInfOptions.Value.ConnectionString); var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient(); var cloudBlobContainer = cloudBlobClient.GetContainerReference(_storageAccountInfOptions.Value.ContainerName); var fileName = Upload.FileName; var fileMimeType = Upload.ContentType; var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName); cloudBlockBlob.Properties.ContentType = fileMimeType; await cloudBlockBlob.UploadFromStreamAsync(Upload.OpenReadStream()); var uri = cloudBlockBlob.Uri.AbsoluteUri; await OnGetAsync(fileName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SincolPDV.BLL; namespace Projeto.Cadastros { public partial class WebForm3 : System.Web.UI.Page { Fornecedor fornecedor = new Fornecedor(); MiniConsulta mn = new MiniConsulta(); Ferramentas.Uteis ut = new Ferramentas.Uteis(); protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { PreencherCombo(); } } private void PreencherCombo() { } protected void btnAjuda_Click(object sender, EventArgs e) { ut.ExecutaJS(this, "<script>Ajuda('../Ferramentas/HelpDinamico/HelpDinamico.aspx?Hlp=" + this + "');</script>"); } protected void btnGravar_Click(object sender, EventArgs e) { PreencherObjetos(); fornecedor.CadastrarFornecedor(); ut.LimpaCampos(this.form1); } protected void btnAlterar_Click(object sender, EventArgs e) { PreencherObjetos(); fornecedor.AlterarFornecedor(); } protected void btnExcluir_Click(object sender, EventArgs e) { if (txtCodigo.Text != "") { fornecedor.Codigo = Convert.ToInt32(txtCodigo.Text); fornecedor.ExcluirFornecedor(); ut.LimpaCampos(this.form1); } } private void PreencherObjetos() { int Status; if (checkStatus.Checked) { Status = 1; } else { Status = 0; } fornecedor.Codigo = Convert.ToInt32(txtCodigo.Text); fornecedor.Nome = txtNome.Text; fornecedor.Status = Status; fornecedor.Pessoa = dropPessoa.SelectedValue; fornecedor.Cpf = txtCPF.Text; fornecedor.Cnpj = txtCNPJ.Text; fornecedor.Telefone = txtTelefone.Text; fornecedor.Endereco = txtEndereco.Text; fornecedor.Email = txtEmail.Text; fornecedor.DadosBancarios = txtDadosBancarios.Text; fornecedor.Observacao = txtObservacao.Text; } protected void txtCodigo_TextChanged(object sender, EventArgs e) { preencher_campos(); } protected void preencher_campos() { fornecedor.Codigo = Convert.ToInt32(txtCodigo.Text); int retorno = fornecedor.Consulta(); ut.LimpaCampos(this.form1); txtCodigo.Text = fornecedor.Codigo.ToString(); if (retorno > 0) { txtCodigo.Text = fornecedor.Codigo.ToString(); txtNome.Text = fornecedor.Nome; dropPessoa.Text = fornecedor.Pessoa.ToString(); txtCPF.Text = fornecedor.Cpf; txtCNPJ.Text = fornecedor.Cnpj; txtTelefone.Text = fornecedor.Telefone.ToString(); txtEndereco.Text = fornecedor.Endereco; txtEmail.Text = fornecedor.Email; txtDadosBancarios.Text = fornecedor.DadosBancarios; txtObservacao.Text = fornecedor.Observacao; if (fornecedor.Status == 1) { checkStatus.Checked = true; } else { checkStatus.Checked = false; } btnGravar.Visible = false; } else { btnGravar.Visible = true; } } protected void btnLimpar_Click(object sender, EventArgs e) { ut.LimpaCampos(this.form1); btnGravar.Visible = true; } /* protected void btnAjuda_Click(object sender, EventArgs e) { ut.ExecutaJS(this, "<script>Ajuda('../Ferramentas/HelpDinamico/HelpDinamico.aspx?Hlp=" + this + "');</script>"); }*/ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestPartA12 { public class Computer { private List<string> parts = new List<string>(); public Computer() { } public void BuildCase(string cumputerCase) { parts.Add(cumputerCase); } public void AddingMotherboard(string motherboard) { parts.Add(motherboard); } public void AddingProcessor(string processor) { parts.Add(processor); } public void AddingGraphicCard(string graphicCard) { parts.Add(graphicCard); } public void AddingMemoryCard(string memoryCard) { parts.Add(memoryCard); } public void RunTest() { Console.WriteLine("runing test"); } } }
using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Drawing.Imaging; using System.Globalization; using System.Drawing; using System; namespace LXF { using static Math; public static unsafe class ImageCleanup { public static Bitmap RemoveEdges(this Bitmap bmp) { const int BORDER = 2; (int w, int h) = (bmp.Width, bmp.Height); (int wx, int hx) = (w + 2 * BORDER, h + 2 * BORDER); Bitmap src = new Bitmap(w, h, PixelFormat.Format32bppArgb); Bitmap dst = new Bitmap(wx, hx, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(src)) g.DrawImage(bmp, 0, 0, w, h); BitmapData dsrc = src.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); BitmapData ddst = dst.LockBits(new Rectangle(0, 0, wx, hx), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); ARGB* pdst = (ARGB*)ddst.Scan0; ARGB* psrc = (ARGB*)dsrc.Scan0; ARGB* ps, pd; float[] m1 = new float[9] { 1, 0, -1, 2, 0, -2, 1, 0, -1, }; float[] m2 = new float[9] { 1, 2, 1, 0, 0, 0, -1, -2, -1, }; float v1, v2; for (int y = 0, x, _x, _y; y < hx; ++y) for (x = 0; x < wx; ++x) if (insidebox(x, y, BORDER, BORDER, wx - BORDER, hx - BORDER)) { _x = x - BORDER; _y = y - BORDER; v1 = v2 = 0; pd = pdst + y * wx + x; for (int i = 0, j, ndx; i < 3; ++i) for (j = 0; j < 3; ++j) { ps = psrc + Min(Max(_y + i - 1, 0), h - 1) * w + Min(Max(_x + j - 1, 0), w - 1); ndx = i * 3 + j; v1 += m1[ndx] * ps->Gray; v2 += m2[ndx] * ps->Gray; } pd->A = 0xff; pd->R = pd->G = pd->B = (byte)Min(255, Max(0, Sqrt(v1 * v1 + v2 * v2))); } else pdst[y * wx + x] = 0xff000000u; byte[,] iα = new byte[wx, hx]; double diag = Sqrt(wx * wx + hx * hx) / 2; const byte α_THRESHOLD = 30; for (double θ = 0, rs = 1 / diag, θs = Atan(rs) / 3; θ < PI * 2; θ += θs) for (double r = 1; r >= 0; r -= rs) { int x = (int)(w / 2d + Sin(θ) * r * diag); int y = (int)(h / 2d + Cos(θ) * r * diag); if (insidebox(x, y, 1, 1, wx - 1, hx - 1)) { ARGB* px = pdst + y * wx + x; if (px->Gray >= α_THRESHOLD) { iα[x, y] = 0; break; } else iα[x, y] = (byte)(255f * Max(0, α_THRESHOLD - px->Gray) / α_THRESHOLD); } else if (insidebox(x, y, 0, 0, wx, hx)) // ignore 1px border iα[x, y] = 0xff; } for (int y = 0; y < hx; ++y) for (int x = 0; x < wx; ++x) { ARGB px = insidebox(x, y, BORDER, BORDER, wx - BORDER, hx - BORDER) ? psrc[(y - BORDER) * w + (x - BORDER)] : (ARGB)0x00ffffffu; px.A = (byte)(0xff - iα[x, y]); pdst[y * wx + x] = px; } dst.UnlockBits(ddst); src.UnlockBits(dsrc); return dst; bool insidebox(int px, int py, int x0, int y0, int xm, int ym) => (px >= x0) && (py >= y0) && (px < xm) && (py < ym); } } [Serializable, StructLayout(LayoutKind.Sequential, Size = 4, Pack = 1), NativeCppClass] internal unsafe struct ARGB { public byte B; public byte G; public byte R; public byte A; private float cmax => Max(R, Max(G, B)); private float cmin => Min(R, Min(G, B)); private float δ => cmax - cmin; public float this[uint ndx] { set { fixed (ARGB* ptr = &this) *((byte*)ptr + (2 - ndx) % 4) = (byte)(value * 255); } get { fixed (ARGB* ptr = &this) return *((byte*)ptr + (2 - ndx) % 4) / 255f; } } public float Gray => (R + G + B) / 3f; public float Lightness => (cmax + cmin) / 2; public float Saturation => δ == 0 ? 0 : δ / (1 - Abs(2 * Lightness - 1)); public float Deviation => Abs(Gray - R) + Abs(Gray - G) + Abs(Gray - B) / 3; public override string ToString() => $"#{A:x2}{R:x2}{G:x2}{B:x2}"; public static implicit operator string(ARGB col) => col.ToString(); public static implicit operator ARGB(string str) => uint.Parse(str.Replace("#", ""), NumberStyles.HexNumber); public static implicit operator uint(ARGB col) => (uint)(col.A << 24) | (uint)(col.R << 16) | (uint)(col.G << 8) | col.B; public static implicit operator ARGB(uint hex) => new ARGB { A = (byte)((hex >> 24) & 0xff), R = (byte)((hex >> 16) & 0xff), G = (byte)((hex >> 8) & 0xff), B = (byte)(hex & 0xff), }; public static implicit operator float[](ARGB col) => new float [] { col.R / 255f, col.G / 255f, col.B / 255f, col.A / 255f, }; public static implicit operator ARGB(float[] rgba) => new ARGB { R = (byte)(rgba[0] * 255), G = (byte)(rgba[1] * 255), B = (byte)(rgba[2] * 255), A = (byte)(rgba[3] * 255), }; } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using Microsoft.Extensions.DependencyInjection; namespace DotNetNuke.DependencyInjection { /// <summary> /// An interface for adding extension points to the DNN Startup Logic. /// </summary> public interface IDnnStartup { /// <summary> /// Configure additional services for the host or web application. /// This method will be called during the Application Startup phase /// and services will be available anywhere in the application. /// </summary> /// <param name="services"> /// Service Collection used to registering services in the container. /// </param> void ConfigureServices(IServiceCollection services); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Airfield_Simulator.Core.Simulation { public interface IFlightDirector { event AircraftLandedEventHandler AircraftLanded; } }
using System; class CheckABitAtGivenPosition { static void Main() { ////Write an expression that extracts from given integer n the value of given bit at index p. Console.Write("Enter your number: "); int number = int.Parse(Console.ReadLine()); Console.Write("Enter the number of the bit you want to check if it is equal to '1': "); int p = int.Parse(Console.ReadLine()); int bit = 1 << p; int comparedBit = number & bit; string binaryNum = Convert.ToString(number, 2); Console.WriteLine("Your number is {0}.", binaryNum); if (comparedBit == 1) { Console.WriteLine("Yes, your bit is '1'."); } else { Console.WriteLine("No, your bit is '0'."); } } }
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 MySql.Data.MySqlClient; using Dapper; namespace Haloween_Challenge { public partial class FilmDetails : Form { private string connectionStringClient = "Server=127.0.0.1;Database=sakila;Uid=client;Pwd=$3cr3t3t"; private string connectionStringStaff = "Server=127.0.0.1;Database=sakila;Uid=staff;Pwd=$up3r$3cr3t"; Films _selectedFilm; public FilmDetails(Films selectedFilm) { // ToDo: BONUS points: Don’t write any code to access the database in this class. //EXTRA BONUS points: Show actors in the film. List<Films> films = new List<Films>(); MySqlConnection con = new MySqlConnection(connectionStringClient); InitializeComponent(); _selectedFilm = selectedFilm; string sql = $"select f.title, f.description, f.length, f.rating, c.name as name, l.name as namel from sakila.film as f inner join film_category as fc on f.film_id = fc.film_id inner join category as c on c.category_id = fc.category_id inner join language as l on f.language_id = l.language_id where f.film_id = {selectedFilm.film_id}"; films = con.Query<Films>(sql).ToList(); Films film = films.FirstOrDefault(); DescriptionLabel.Text = film.description; TitleLabel.Text = film.title; CategoryLabel.Text = film.name; LanguajeLabel.Text = film.namel; RatingLabel.Text = film.rating; DurationLabel.Text = film.length; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("AnimatedLowPolyPack")] public class AnimatedLowPolyPack : MonoBehaviour { public AnimatedLowPolyPack(IntPtr address) : this(address, "AnimatedLowPolyPack") { } public AnimatedLowPolyPack(IntPtr address, string className) : base(address, className) { } public bool FlyIn(float animTime, float delay) { object[] objArray1 = new object[] { animTime, delay }; return base.method_11<bool>("FlyIn", objArray1); } public void FlyInImmediate() { base.method_8("FlyInImmediate", Array.Empty<object>()); } public bool FlyOut(float animTime, float delay) { object[] objArray1 = new object[] { animTime, delay }; return base.method_11<bool>("FlyOut", objArray1); } public void FlyOutImmediate() { base.method_8("FlyOutImmediate", Array.Empty<object>()); } public State GetState() { return base.method_11<State>("GetState", Array.Empty<object>()); } public void Hide() { base.method_8("Hide", Array.Empty<object>()); } public void Init(int column, Vector3 targetLocalPos, Vector3 offScreenOffset, bool ignoreFullscreenEffects, bool changeActivation) { object[] objArray1 = new object[] { column, targetLocalPos, offScreenOffset, ignoreFullscreenEffects, changeActivation }; base.method_8("Init", objArray1); } public void OnFlownIn() { base.method_8("OnFlownIn", Array.Empty<object>()); } public void OnHidden() { base.method_8("OnHidden", Array.Empty<object>()); } public void PositionOffScreen() { base.method_8("PositionOffScreen", Array.Empty<object>()); } public void SetFlyingLocalRotations(Vector3 flyInLocalAngles, Vector3 flyOutLocalAngles) { object[] objArray1 = new object[] { flyInLocalAngles, flyOutLocalAngles }; base.method_8("SetFlyingLocalRotations", objArray1); } public int Column { get { return base.method_11<int>("get_Column", Array.Empty<object>()); } } public bool m_changeActivation { get { return base.method_2<bool>("m_changeActivation"); } } public Vector3 m_flyInLocalAngles { get { return base.method_2<Vector3>("m_flyInLocalAngles"); } } public string m_FlyInSound { get { return base.method_4("m_FlyInSound"); } } public Vector3 m_flyOutLocalAngles { get { return base.method_2<Vector3>("m_flyOutLocalAngles"); } } public string m_FlyOutSound { get { return base.method_4("m_FlyOutSound"); } } public State m_state { get { return base.method_2<State>("m_state"); } } public Vector3 m_targetLocalPos { get { return base.method_2<Vector3>("m_targetLocalPos"); } } public Vector3 m_targetOffScreenLocalPos { get { return base.method_2<Vector3>("m_targetOffScreenLocalPos"); } } public Vector3 PUNCH_POSITION_AMOUNT { get { return base.method_2<Vector3>("PUNCH_POSITION_AMOUNT"); } } public float PUNCH_POSITION_TIME { get { return base.method_2<float>("PUNCH_POSITION_TIME"); } } public enum State { UNKNOWN, FLOWN_IN, FLYING_IN, FLYING_OUT, HIDDEN } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using System; public class Data : MonoBehaviour { public enum Specs { Orc, Beast, Ogre, Undead, Goblin, Troll, Elf, Elemental, Human, Demon, Naga, Dwarf, Dragon}; public enum Classes { Warrior, Druid, Mage, Hunter, Assassin, Mech, Shaman, Knight, DemonHunter, Warlock }; public struct Hero { public List<Specs> _specs; public Classes _class; public int price; public Sprite miniIcon; } public List<Hero> allHeroes = new List<Hero>(); public Dictionary<Specs, List<Hero>> specsDict = new Dictionary<Specs, List<Hero>> (); public Dictionary<Classes, List<Hero>> classesDict = new Dictionary<Classes, List<Hero>>(); private void Awake() { // TODO: read from JSON List<Specs> sps = Enum.GetValues(typeof(Specs)).Cast<Specs>().ToList(); List<Classes> cls = Enum.GetValues(typeof(Classes)).Cast<Classes>().ToList(); for (int i = 0; i < 40; i++) { Hero hero = new Hero(); hero._specs = new List<Specs>(); hero._specs.Add(sps[UnityEngine.Random.Range(0, sps.Count)]); hero._class = cls[UnityEngine.Random.Range(0, cls.Count)]; hero.price = 3; hero.miniIcon = null; allHeroes.Add(hero); } // foreach (Specs spec in Enum.GetValues(typeof(Specs))) { specsDict.Add(spec, new List<Hero>()); } foreach (Classes _class in Enum.GetValues(typeof(Classes))) { classesDict.Add(_class, new List<Hero>()); } foreach (Hero hero in allHeroes) { classesDict[hero._class].Add(hero); specsDict[hero._specs[0]].Add(hero); if (hero._specs.Count > 1) specsDict[hero._specs[1]].Add(hero); } // Test for (int i = 0; i < specsDict.Count; i++) { Debug.LogWarning(sps[i]); foreach (Hero hero in specsDict[sps[i]]) { Debug.Log(hero._class); } } // } }
using System; using System.Threading; using Tetris.GameEngine; using System.Timers; using SharpDX.XInput; using Tetris.GameEngine.Interfaces; namespace TetrisConsoleUI { class TetrisConsoleUI : IGameView { private static Game _game; private static ConsoleDrawing _drawer; private static System.Timers.Timer _gameTimer; private static int _timerCounter = 0; private static readonly int _timerStep = 10; private static Controller controller; private static System.Timers.Timer controllerPollTimer; private static State prevControllerState; static int Main(string[] args) { //preparing Console Console.Clear(); Console.CursorVisible = false; _drawer = new ConsoleDrawing(); ConsoleDrawing.ShowControls(); Console.ReadKey(true); Console.Clear(); _game = new Game(null); _game.Start(); _gameTimer = new System.Timers.Timer(800); _gameTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); _gameTimer.Start(); _drawer.DrawScene(_game); controller = new Controller(0); if (controller.IsConnected) { controllerPollTimer = new System.Timers.Timer(50); controllerPollTimer.Elapsed += ControllerPoll; controllerPollTimer.Start(); prevControllerState = controller.GetState(); } while (_game.Status != Game.GameStatus.Finished) { if (Console.KeyAvailable) { KeyPressedHandler(Console.ReadKey(true)); _drawer.DrawScene(_game); _gameTimer.Enabled = true; } } _gameTimer.Stop(); _drawer.ShowGameOver(_game); Console.ResetColor(); Console.CursorVisible = true; return 0; } private static void ControllerPoll(object sender, ElapsedEventArgs e) { if (_game.Status == Game.GameStatus.Finished) { controllerPollTimer.Stop(); } if (controller.IsConnected) { ControllerButtonHandler(); } } private static void ControllerButtonHandler() { State curState = controller.GetState(); if (curState.Gamepad.Buttons != prevControllerState.Gamepad.Buttons) { switch (curState.Gamepad.Buttons) { case GamepadButtonFlags.A: _game.Rotate(false); break; case GamepadButtonFlags.B: _game.Rotate(true); break; case GamepadButtonFlags.DPadUp: _game.SmashDown(); break; case GamepadButtonFlags.DPadDown: _game.MoveDown(); break; case GamepadButtonFlags.DPadLeft: _game.MoveLeft(); break; case GamepadButtonFlags.DPadRight: _game.MoveRight(); break; case GamepadButtonFlags.Start: _game.Pause(); break; case GamepadButtonFlags.X: _game.HoldPiece(); break; } _drawer.DrawScene(_game); prevControllerState = curState; } } private static void KeyPressedHandler(ConsoleKeyInfo input_key) { switch (input_key.Key) { case ConsoleKey.LeftArrow: if (_game.Status != Game.GameStatus.Paused) _game.MoveLeft(); break; case ConsoleKey.Z: if (_game.Status != Game.GameStatus.Paused) _game.MoveLeft(); break; case ConsoleKey.RightArrow: if (_game.Status != Game.GameStatus.Paused) _game.MoveRight(); break; case ConsoleKey.UpArrow: if (_game.Status != Game.GameStatus.Paused) _game.Rotate(); break; case ConsoleKey.DownArrow: if (_game.Status != Game.GameStatus.Paused) { _game.MoveDown(); _gameTimer.Enabled = false; } break; case ConsoleKey.Spacebar: if (_game.Status != Game.GameStatus.Paused) _game.SmashDown(); break; case ConsoleKey.N: _game.NextPieceMode = !_game.NextPieceMode; break; case ConsoleKey.G: _game.ShadowPieceMode = !_game.ShadowPieceMode; break; case ConsoleKey.P: _game.Pause(); break; case ConsoleKey.Escape: _game.GameOver(); break; case ConsoleKey.C: _game.HoldPiece(); break; default: break; } } private static void OnTimedEvent(object source, ElapsedEventArgs e) { #if DEBUG (source as System.Timers.Timer).Stop(); #endif if (_game.Status != Game.GameStatus.Finished) { if (_game.Status != Game.GameStatus.Paused) { _timerCounter += _timerStep; _game.MoveDown(); if (_game.Status == Game.GameStatus.Finished) { _gameTimer.Stop(); } else { _drawer.DrawScene(_game); if (_timerCounter >= (1000 - (_game.Lines * 10))) { _gameTimer.Interval -= 50; _timerCounter = 0; } } } else if (_game.CountDownNum > 0) { _drawer.DrawScene(_game); } } #if DEBUG (source as System.Timers.Timer).Start(); #endif } public void Update(IGameView G) { throw new NotImplementedException(); } } }
using Yeasca.Metier; namespace Yeasca.Requete { public interface IRechercheUtilisateurMessage : IMessageRequete, IRechercheUtilisateur { } }
namespace DxMessaging.Unity.Networking { using System; using JetBrains.Annotations; [AttributeUsage(AttributeTargets.Struct)] [MeansImplicitUse] public sealed class NetworkMessageAttribute : Attribute { } }
using System.Collections.Generic; namespace Lobster.Extensions { internal static class ICollectionExtensions { public static void AddRange<T>( this ICollection<T> source, IEnumerable<T> values) { foreach (var item in values) source.Add(item); } } }
using EDU_Rent.data_layer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EDU_Rent.business_layer { class Email { internal void SendEmail(User currentUser, string message, string subject) { Emails.SendEmail(currentUser, message, subject); } } }
using SimpleVisioModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Xceed.Wpf.Toolkit; using Microsoft.Win32; using SimpleVisioService; using Ninject; namespace SimpleVisioApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public IShapeService shapeService; WpfShapeManipulator shapeManipulator; ContextMenu shapeMenu = new ContextMenu(); string fileFilter = "Xml file (*.xml)|*.xml"; public MainWindow(IShapeService shapeService) { this.shapeService = shapeService; InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { FillShapeMenu(); MainCanvas.ContextMenu = shapeMenu; shapeManipulator = new WpfShapeManipulator(shapeService, MainCanvas); MainCanvas.MouseLeftButtonDown += new MouseButtonEventHandler(Container_MouseLeftButtonDown); MainCanvas.MouseLeftButtonUp += new MouseButtonEventHandler(DragFinishedMouseHandler); MainCanvas.MouseMove += new MouseEventHandler(Container_MouseMove); MainCanvas.MouseLeave += new MouseEventHandler(Container_MouseLeave); MainCanvas.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(Container_PreviewMouseLeftButtonDown); MainCanvas.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(DragFinishedMouseHandler); MainCanvas.MouseLeftButtonDown += new MouseButtonEventHandler(Container_MouseDown); MainCanvas.MouseUp += new MouseButtonEventHandler(Container_MouseUp); } private void FillShapeMenu() { shapeMenu.Items.Add(new MenuItem { Header = "Paste" }); foreach (MenuItem item in shapeMenu.Items) { item.Click += Item_Click; } } private void Item_Click(object sender, RoutedEventArgs e) { shapeManipulator.Paste(Mouse.GetPosition(MainCanvas)); } private void UnDo_Click(object sender, RoutedEventArgs e) { shapeManipulator.Undo(); } private void ReDo_Click(object sender, RoutedEventArgs e) { shapeManipulator.Redo(); } private void RectShape_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { shapeManipulator.StopConnecting(); shapeManipulator.AddShape(new RectangleShape { Position = new Point(300, 300) }); } private void Container_MouseLeave(object sender, MouseEventArgs e) { shapeManipulator.StopDragging(); e.Handled = true; } private void Container_MouseMove(object sender, MouseEventArgs e) { shapeManipulator.DragElement(MainCanvas, e); } private void Container_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { shapeManipulator.RemoveSelection(); } private void Container_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { shapeManipulator.SelectElement(MainCanvas, e); if (!(e.Source is Canvas)) ShapeColorPicker.SelectedColor = (e.Source as FrameworkElement).GetValue(BackgroundProperty) != null ? ((e.Source as FrameworkElement).GetValue(BackgroundProperty) as SolidColorBrush).Color : Colors.White; else ShapeColorPicker.SelectedColor = Colors.White; } private void DragFinishedMouseHandler(object sender, MouseButtonEventArgs e) { shapeManipulator.StopDragging(); e.Handled = true; shapeManipulator.HandlePosition(); } private void Container_MouseDown(object sender, MouseButtonEventArgs e) { shapeManipulator.StopConnecting(); Keyboard.ClearFocus(); } private void Container_MouseUp(object sender, MouseButtonEventArgs e) { //shapeManipulator._isDown = false; } private void Connect_Click(object sender, RoutedEventArgs e) { Keyboard.ClearFocus(); shapeManipulator.RemoveSelection(); shapeManipulator.StartConnecting(); } private void SaveFile_Click(object sender, RoutedEventArgs e) { SaveFileDialog saveDialog = new SaveFileDialog { Filter = fileFilter }; if (saveDialog.ShowDialog() == true) { shapeManipulator.Save(saveDialog.FileName); } } private void LoadFile_Click(object sender, RoutedEventArgs e) { OpenFileDialog openDialog = new OpenFileDialog { Filter = fileFilter }; if (openDialog.ShowDialog() == true) { shapeService.Clear(); shapeManipulator.Load(openDialog.FileName); shapeManipulator = new WpfShapeManipulator(shapeService, MainCanvas); } } private void ColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e) { Color selColor = (sender as ColorPicker).SelectedColor ?? Colors.White; shapeManipulator.ChangeColor(selColor); } private void RoundRectShape_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { shapeManipulator.StopConnecting(); Keyboard.ClearFocus(); shapeManipulator.AddShape(new RoundedRectangleShape { Position = new Point(300, 300) }); } private void Arrow_MouseUp(object sender, MouseButtonEventArgs e) { shapeManipulator.StopConnecting(); Keyboard.ClearFocus(); shapeManipulator.RemoveSelection(); shapeManipulator.StartConnecting(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { shapeService.Clear(); shapeManipulator = new WpfShapeManipulator(shapeService, MainCanvas); } } }
namespace Contoso.Parameters.Expressions { public class MonthOperatorParameters : IExpressionParameter { public MonthOperatorParameters() { } public MonthOperatorParameters(IExpressionParameter operand) { Operand = operand; } public IExpressionParameter Operand { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game.Mono; [Attribute38("ClassSpecificVoLine")] public class ClassSpecificVoLine : MonoClass { public ClassSpecificVoLine(IntPtr address) : this(address, "ClassSpecificVoLine") { } public ClassSpecificVoLine(IntPtr address, string className) : base(address, className) { } public SpellClassTag m_Class { get { return base.method_2<SpellClassTag>("m_Class"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OakIdeas.Volunteer.Models { public class Organization : BaseModel { private string _name; public string Name { get { return _name; } set { _name = value; } } private string _description; public string Description { get { return _description; } set { _description = value; } } private string _website; public string WebSite { get { return _website; } set { _website = value; } } private List<Location> _locations; public virtual List<Location> Locations { get { return _locations; } set { _locations = value; } } private List<Contact> _contacts; public virtual List<Contact> Contacts { get { return _contacts; } set { _contacts = value; } } private List<Project> _projects; public virtual List<Project> Projects { get { return _projects; } set { _projects = value; } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; namespace NuGet.Protocol.Core.v3.Data { public abstract class FileCacheBase { public abstract bool TryGet(Uri uri, out Stream stream); public abstract void Remove(Uri uri); public abstract void Add(Uri uri, TimeSpan lifeSpan, Stream stream); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.Support.V4.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace jumpHelper { public class AddCommentDialogFragment : DialogFragment { private static List<string> formations; public static AddCommentDialogFragment NewInstance(List<string> formationsList) { AddCommentDialogFragment fragment = new AddCommentDialogFragment(); formations = formationsList; fragment.Arguments = new Bundle(); return fragment; } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.Inflate(Resource.Layout.NewCommentLayout, container, false); Spinner spinner = view.FindViewById<Spinner>(Resource.Id.formationSelectSpinner); var adapter = new ArrayAdapter<string>(this.Activity, Android.Resource.Layout.SimpleSpinnerItem, formations); spinner.Adapter = adapter; EditText edittext = view.FindViewById<EditText>(Resource.Id.newCommentText); Button saveButton = view.FindViewById<Button>(Resource.Id.SaveButton); Button cancelButton = view.FindViewById<Button>(Resource.Id.CancelButton); saveButton.Click += async delegate { string formation = spinner.SelectedItem.ToString(); await FSNotesHandler.addComment(formation, edittext.Text); Dismiss(); }; cancelButton.Click += delegate { Dismiss(); }; return view; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class TestSceneChange : MonoBehaviour { public void OnClick() { var a = GetComponents<SceneChangeRelay>(); foreach(var aa in a) { aa.Next(); } } }
using Zillow.Core.Dto; using Microsoft.AspNetCore.Mvc; using Zillow.Core.Dto.CreateDto; using Zillow.Core.Dto.UpdateDto; using Zillow.Core.ViewModel; using Zillow.Service.Services.CustomerServices; using System.Threading.Tasks; namespace Zillow.API.Controllers { public class CustomerController : BaseController { private readonly ICustomerService _customerService; public CustomerController(ICustomerService customerService) { _customerService = customerService; } [HttpGet("{page}/{pageSize}")] public async Task<IActionResult> GetAll(int page,int pageSize) => await GetResponse( async () => new ApiResponseViewModel(true, "Get All Customers Successfully", await _customerService.GetAll(page, pageSize))); [HttpGet("{id}")] public async Task<IActionResult> Get(int id) => await GetResponse(async () => new ApiResponseViewModel(true, "Get Customer Successfully", await _customerService.Get(id))); [HttpPost] public async Task<IActionResult> Create([FromBody]CreateCustomerDto dto) => await GetResponse(async () => new ApiResponseViewModel(true, "Customer Created Successfully", await _customerService.Create(dto, UserId))); [HttpPut("{id}")] public async Task<IActionResult> Update(int id ,[FromBody]UpdateCustomerDto dto) => await GetResponse(async () => new ApiResponseViewModel(true, "Customer Updated Successfully", await _customerService.Update(id,dto, UserId))); [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) => await GetResponse(async () => new ApiResponseViewModel(true, "Customer Deleted Successfully", await _customerService.Delete(id, UserId))); } }
using System; using System.Linq; using Foundation; using UIKit; using MvvmCross.Binding.iOS.Views; using MvvmCross.Binding.BindingContext; using MvvmCross.Core.ViewModels; using EsMo.Sina.SDK.Model; using System.Diagnostics; using SDWebImage; using System.Collections.Generic; using CoreGraphics; using EsMo.MvvmCross.iOS.Support.Converter; using CoreText; namespace EsMo.iOS.WeiBo.Entity { public partial class TimelineItemView : MvxTableViewCell { public static readonly NSString Key = new NSString("TimelineItemView"); public static readonly UINib Nib; ImageCollectionSource imgSource; UIStringAttributes strAttr; static TimelineItemView() { Nib = UINib.FromName("TimelineItemView", NSBundle.MainBundle); } protected TimelineItemView(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } public override void AwakeFromNib() { base.AwakeFromNib(); strAttr = new UIStringAttributes(); //this.imgBackground.Image = UIImage.FromBundle("timeline_publish_single_normal.9"); this.viewReplyHeight.Constant = 0; this.viewReplyHeight.Active = false; this.imgSource = new ImageCollectionSource(this.listImage,this); this.BindingContext.DataContextChanged += BindingContext_DataContextChanged; this.DelayBind(() => { var set = this.CreateBindingSet<TimelineItemView, TimelineItemViewModel>(); set.Bind(this.txtName).To(v => v.Name); set.Bind(this.txtContent).To(v => v.Text); set.Bind(this.txtDesc).To(v => v.Description); set.Bind(this.txtReContent).To(v => v.RetweetContent); set.Bind(this.txtComment).To(v => v.CommentCount); set.Bind(this.txtLike).To(v => v.LikeCount); set.Bind(this.txtRepost).To(v => v.RepostCount); set.Bind(this.imgComment).To(v => v.ImageComment).WithConversion(Converter.StreamToUIImage); set.Bind(this.imgRepost).To(v => v.ImageRepost).WithConversion(Converter.StreamToUIImage); set.Bind(this.imgLike).To(v => v.ImageLike).WithConversion(Converter.StreamToUIImage); set.Bind(this.imgVerified).To(v => v.ImageVerified).WithConversion(Converter.StreamToUIImage); set.Bind(this.viewReply).For(x => x.Hidden).To("HasRetweetedStatus==false"); set.Apply(); }); this.AddBindings(new Dictionary<object, string> { {imgSource, "ItemsSource ImageModels"} }); this.listImage.Source = this.imgSource; this.listImage.ReloadData(); } private void BindingContext_DataContextChanged(object sender, EventArgs e) { var vm = this.DataContext as TimelineItemViewModel; if (vm != null) { this.imgPhoto.SetImage(new NSUrl(vm.ProfileUrl)); //this.viewReplyHeight.Active = !vm.HasRetweetedStatus; this.listImage.ViewModel = vm; this.listImage.ReloadData(); if (!string.IsNullOrEmpty(vm.RetweetedHeader)) { strAttr.ForegroundColor = Converter.ColorToUIColor.Convert(TimelineItemViewModel.RetweetColor) as UIColor; this.UpdateRetweetColor(vm.RetweetedHeader, vm.RetweetContent); } } this.SetNeedsLayout(); } public override void LayoutSubviews() { base.LayoutSubviews(); this.ContentView.SetNeedsLayout(); this.ContentView.LayoutIfNeeded(); this.txtContent.PreferredMaxLayoutWidth = this.txtContent.Frame.Width; this.txtReContent.PreferredMaxLayoutWidth = this.txtReContent.Frame.Width; } public override CGSize SystemLayoutSizeFittingSize(CGSize targetSize, float horizontalFittingPriority, float verticalFittingPriority) { CGSize size = base.SystemLayoutSizeFittingSize(targetSize, horizontalFittingPriority, verticalFittingPriority); var imgsSize = this.listImage.SystemLayoutSizeFittingSize(targetSize); return new CGSize(size.Width, size.Height + imgsSize.Height + 1); } void UpdateRetweetColor(string header, string txt) { NSMutableAttributedString attr = new NSMutableAttributedString(); attr.BeginEditing(); NSRange range = new NSRange(0, header.Length); attr.MutableString.SetString(new NSString(txt)); attr.SetAttributes(this.strAttr, range); attr.EndEditing(); this.txtReContent.AttributedText = attr; } } public class ImageCollectionSource: MvxCollectionViewSource { TimelineItemView itemView; public ImageCollectionSource(UICollectionView collectionView,TimelineItemView itemView) : base(collectionView, ImageViewCell.Key) { collectionView.RegisterNibForCell(ImageViewCell.Nib, ImageViewCell.Key); this.itemView = itemView; } protected override UICollectionViewCell GetOrCreateCellFor(UICollectionView collectionView, NSIndexPath indexPath, object item) { return collectionView.DequeueReusableCell(ImageViewCell.Key, indexPath) as UICollectionViewCell; } public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath) { (this.itemView.DataContext as TimelineItemViewModel).ImageSelected?.Execute(indexPath.Row); } } }