content
stringlengths
23
1.05M
using books.api.Services; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace books.api.Models { /// <summary> /// Database Context used for the API. Receives database settings interface. /// </summary> public class AppDbContext { private readonly IMongoDatabase _db; public AppDbContext(IDatabaseSettings settings) { var setting = settings ?? throw new ArgumentNullException("Settings"); var client = new MongoClient(setting.ConnectionString); _db = client.GetDatabase(setting.DatabaseName); } public IMongoDatabase DB() { return _db; } } }
using Rabotora.CLI.SDK; using System; using System.Globalization; using System.Reflection; using static Rabotora.CLI.MultiLang; namespace Rabotora.CLI { public class Program { static void Main(string[] args) { switch (args.Length) { case 0: Console.WriteLine(GetRes<string>("CLI.BaseHelp")); break; case 1: if (args[0].Trim().StartsWith('-')) { string option = args[0].Trim().ToLower()[1..]; switch (option) { case "ver": case "-version": Console.WriteLine(string.Format(GetRes<string>("CLI.Version")!, Assembly.GetExecutingAssembly()!.GetName().Version!.ToString(), Assembly.GetEntryAssembly()!.GetName().Version!.ToString())); break; case "?": Console.WriteLine(GetRes<string>("CLI.Help")); break; default: Console.WriteLine(GetRes<string>("CLI.Help")); break; } } else if (args[0].Trim().ToLower().EndsWith(".rexe")) { Console.WriteLine("Rabotora Runtime is still developing, please wait for patience..."); } else { Entry.HandleMain(args); } break; default: Entry.HandleMain(args); break; } } } }
using GeneticSharp.Domain.Chromosomes; using GeneticSharp.Domain.Populations; using System; using System.Collections.Generic; using System.Linq; namespace GenericNEAT.Populations { public class SpeciedPopulation : Population, ISpeciedPopulation { #region Properties public IList<Specie> Species { get; set; } private int _minSpecieSize; public int MinSpecieSize { get => _minSpecieSize; set { _minSpecieSize = value; for (int i = 0; i < Species.Count; i++) Species[i].MinSize = _minSpecieSize; } } /// <summary> /// Method for dividing up individuals into species. /// </summary> public ISpeciationStrategy SpeciationStrategy { get; set; } /// <summary> /// ID that will be used when creating a new specie. /// </summary> protected uint NextSpecieID { get; set; } #endregion #region Constructors /// <summary> /// Creates a new specied population. /// </summary> public SpeciedPopulation(int minSize, int maxSize, IChromosome adamChromosome, ISpeciationStrategy speciationStrategy, int minSpecieSize) : base(minSize, maxSize, adamChromosome) { if (speciationStrategy is null) throw new ArgumentNullException(nameof(speciationStrategy)); if (minSpecieSize < 0) throw new ArgumentOutOfRangeException(nameof(minSpecieSize)); SpeciationStrategy = speciationStrategy; _minSpecieSize = minSpecieSize; Species = new List<Specie>(); } #endregion #region Methods public override void CreateInitialGeneration() { // Reset the species list Species.Clear(); var specie = new Specie(MinSpecieSize, MinSize, 0u, AdamChromosome); specie.CreateInitialGeneration(); Species.Add(specie); NextSpecieID = 1u; // Reset the base generations list Generations.Clear(); GenerationsNumber = 0; base.CreateNewGeneration(specie.CurrentGeneration.Chromosomes); } public override void CreateNewGeneration(IList<IChromosome> chromosomes) { base.CreateNewGeneration(chromosomes); // Organize chromosomes by species var lookup = chromosomes.ToLookup(c => GetFirstSpecie(c)); foreach (var group in lookup) { // Add em to the correct specie group.Key.CreateNewGeneration(group.ToList()); } // Remove empty species for (int i = 0; i < Species.Count; i++) { if (Species[i].CurrentGeneration.Chromosomes.Count == 0) { Species.RemoveAt(i); i--; } } } public override void EndCurrentGeneration() { base.EndCurrentGeneration(); for (int i = 0; i < Species.Count; i++) Species[i].EndCurrentGeneration(); } /// <summary> /// Returns the first specie to which <paramref name="chromosome"/> /// fits, according too <see cref="SpeciationStrategy"/>. /// </summary> protected Specie GetFirstSpecie(IChromosome chromosome) { for (int i = 0; i < Species.Count; i++) { var curSpecie = Species[i]; if (SpeciationStrategy.AreSameSpecies(chromosome, curSpecie.Centroid)) return curSpecie; } // Create a new specie var specie = new Specie(MinSpecieSize, MaxSize, NextSpecieID++, chromosome); Species.Add(specie); NextSpecieID++; return specie; } #endregion } }
using UnityEngine; //Esse script vai em todos os objetos que iniciam um diálogo public class ObjectDialogueTrigger : MonoBehaviour { public DialogueController dialogueController; private CurrentDialogueController activeDialogue; public void OnEnable() { activeDialogue = GameObject.FindGameObjectWithTag("CoreScripts").GetComponent<CurrentDialogueController>(); } //Atualiza o Dialogue Controller desse objeto. O Dialogue Controller é o script que contém o Json public void SetDialogueController(DialogueController newDialogueController) { dialogueController = newDialogueController; } //Define o diálogo atual e inicia as falas public void StartDialogue() { activeDialogue.SetActiveDialogue(dialogueController); dialogueController.DialogueTrigger(); } }
using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Altairis.ReP.Data; using Altairis.ValidationToolkit; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Altairis.ReP.Web.Pages.Admin.Resources { public class CreateModel : PageModel { private readonly RepDbContext dc; public CreateModel(RepDbContext dc) { this.dc = dc ?? throw new ArgumentNullException(nameof(dc)); } [BindProperty] public InputModel Input { get; set; } = new InputModel(); public class InputModel { [Required, MaxLength(50)] public string Name { get; set; } public string Description { get; set; } [Required, Range(0, 1440)] public int MaximumReservationTime { get; set; } [Required, Color] public string ForegroundColor { get; set; } = "#000000"; [Required, Color] public string BackgroundColor { get; set; } = "#ffffff"; public bool ResourceEnabled { get; set; } = true; } public async Task<IActionResult> OnPostAsync() { if (!this.ModelState.IsValid) return this.Page(); var newResource = new Resource { Description = this.Input.Description, Enabled = this.Input.ResourceEnabled, MaximumReservationTime = this.Input.MaximumReservationTime, Name = this.Input.Name, ForegroundColor = this.Input.ForegroundColor, BackgroundColor = this.Input.BackgroundColor }; this.dc.Resources.Add(newResource); await this.dc.SaveChangesAsync(); return this.RedirectToPage("Index", null, "created"); } } }
namespace Cake.AzureDevOps.Pipelines { /// <summary> /// Possible results of a build. /// </summary> public enum AzureDevOpsBuildResult : byte { /// <summary> /// Result is not set. /// </summary> None = 0, /// <summary> /// The build completed successfully. /// </summary> Succeeded = 2, /// <summary> /// The build completed compilation successfully but had other errors. /// </summary> PartiallySucceeded = 4, /// <summary> /// The build completed unsuccessfully. /// </summary> Failed = 8, /// <summary> /// The build was canceled before starting. /// </summary> Canceled = 32, } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace BizwebSharp.ConsoleTests.Web { public class WebServer { public static string HostUrl { get; private set; } public WebServer(string hostUrl) { HostUrl = hostUrl; } public Task Run() { return Task.Run(() => { var builder = new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .UseUrls(HostUrl); ; var host = builder.Build(); host.Run(); }); } } }
 using BlamanticUI.Abstractions; using Microsoft.AspNetCore.Components; using YoiBlazor; namespace BlamanticUI { /// <summary> /// Represents a container to display <see cref="Image"/> in other component. /// </summary> /// <seealso cref="BlamanticUI.Abstractions.BlamanticChildContentComponentBase" /> /// <seealso cref="BlamanticUI.Abstractions.IHasUIComponent" /> /// <seealso cref="BlamanticUI.Abstractions.IHasFluid" /> [HtmlTag] public class ImageContent : BlamanticChildContentComponentBase, IHasUIComponent,IHasFluid { /// <summary> /// Initializes a new instance of the <see cref="ImageContent"/> class. /// </summary> public ImageContent() { Fluid = true; } /// <summary> /// Gets or sets a value indicating whether this is fluid. /// </summary> /// <value> /// <c>true</c> if fluid; otherwise, <c>false</c>. /// </value> [Parameter]public bool Fluid { get; set; } /// <summary> /// Override to create the CSS class that component need. /// </summary> /// <param name="css">The instance of <see cref="T:YoiBlazor.Css" /> class.</param> protected override void CreateComponentCssClass(Css css) { css.Add("image"); } } }
using eDriven.Gui.Components; namespace eDriven.Gui.States { /// <summary> /// State override /// </summary> public interface IOverride { /// <summary> /// Initializes the override /// </summary> void Initialize(); /// <summary> /// Applies the override /// </summary> /// <param name="parent"></param> void Apply(Component parent); /// <summary> /// Removes the override /// </summary> /// <param name="parent"></param> void Remove(Component parent); } }
// 메서드 구문(Method Syntax)과 쿼리 구문(Query Syntax) 비교 using System; using System.Collections.Generic; using System.Linq; class LinqQuerySyntax { static void Main() { int[] numbers = { 3, 2, 1, 4, 5 }; //[1] 메서드 구문 IEnumerable<int> methodSyntax = numbers.Where(n => n % 2 == 1).OrderBy(n => n); foreach (var n in methodSyntax) { Console.WriteLine(n); } //[2] 쿼리 구문 IEnumerable<int> querySyntax = from num in numbers where num % 2 == 1 orderby num select num; foreach (var n in querySyntax) { Console.WriteLine(n); } } }
namespace M5x.DEC.Schema.Common; public static class IsoDimensions { public static Measurement Time() { return new Measurement(decimal.Zero, 0, IsoUnits.Second); } public static Measurement Length() { return Measurement.New(decimal.Zero, 0, IsoUnits.Meter); } public static Measurement Mass() { return Measurement.New(decimal.Zero, 0, IsoUnits.KiloGram); } public static Measurement Displacement() { return Measurement.New(decimal.Zero, 0, IsoUnits.MetricTon); } }
using System; using System.Collections.Generic; namespace AT3_UC05.Models { public class ItemAgendamento { public string Nome { get; set; } public double NumTelefone { get; set; } public DateTime Data { get; set; } public string Animal { get; set; } public string Nescessidade { get; set; } } }
using Nager.Date.Contract; using Nager.Date.Model; using System.Collections.Generic; using System.Linq; namespace Nager.Date.PublicHolidays { /// <summary> /// Ecuador /// </summary> public class EcuadorProvider : IPublicHolidayProvider { private readonly ICatholicProvider _catholicProvider; /// <summary> /// EcuadorProvider /// </summary> /// <param name="catholicProvider"></param> public EcuadorProvider(ICatholicProvider catholicProvider) { this._catholicProvider = catholicProvider; } ///<inheritdoc/> public IEnumerable<PublicHoliday> Get(int year) { var countryCode = CountryCode.EC; var easterSunday = this._catholicProvider.EasterSunday(year); var items = new List<PublicHoliday>(); items.Add(new PublicHoliday(year, 1, 1, "Año Nuevo", "New Year's Day", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(-48), "Carnaval", "Carnival", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(-47), "Carnaval", "Carnival", countryCode)); items.Add(this._catholicProvider.GoodFriday("Good Friday", year, countryCode)); items.Add(new PublicHoliday(year, 5, 1, "International Workers' Day", "International Workers' Day", countryCode)); items.Add(new PublicHoliday(year, 5, 24, "Batalla de Pichincha", "The Battle of Pichincha", countryCode)); items.Add(new PublicHoliday(year, 8, 10, "Primer Grito de Independencia", "Declaration of Independence of Quito", countryCode)); items.Add(new PublicHoliday(year, 10, 9, "Independencia de Guayaquil", "Independence of Guayaquil", countryCode)); items.Add(new PublicHoliday(year, 11, 2, "Día de los Difuntos, Día de Muertos", "All Souls' Day", countryCode)); items.Add(new PublicHoliday(year, 11, 3, "Independencia de Cuenca", "Independence of Cuenca", countryCode)); items.Add(new PublicHoliday(year, 12, 25, "Día de Navidad", "Christmas Day", countryCode)); return items.OrderBy(o => o.Date); } ///<inheritdoc/> public IEnumerable<string> GetSources() { return new string[] { "https://en.wikipedia.org/wiki/Public_holidays_in_Ecuador", }; } } }
using System; using LanguageExt.Attributes; namespace LanguageExt.Interfaces { public interface ConsoleIO { ConsoleKeyInfo ReadKey(); Unit Clear(); int Read(); string ReadLine(); Unit WriteLine(); Unit WriteLine(string value); Unit Write(string value); Unit SetBgColor(ConsoleColor color); Unit SetColor(ConsoleColor color); ConsoleColor BgColor { get; } ConsoleColor Color { get; } } /// <summary> /// Type-class giving a struct the trait of supporting Console IO /// </summary> /// <typeparam name="RT">Runtime</typeparam> [Typeclass("*")] public interface HasConsole<RT> : HasCancel<RT> where RT : struct, HasCancel<RT> { /// <summary> /// Access the console asynchronous effect environment /// </summary> /// <returns>Console asynchronous effect environment</returns> Aff<RT, ConsoleIO> ConsoleAff { get; } /// <summary> /// Access the console synchronous effect environment /// </summary> /// <returns>Console synchronous effect environment</returns> Eff<RT, ConsoleIO> ConsoleEff { get; } } }
namespace CAS.Core.Models { public class PaginationDetails { public long CurrentPage { get; set; } public long CurrentPageQty { get; set; } public long PageSize { get; set; } public long LastPage { get; set; } public long TotalResults { get; set; } public string ItemType { get; set; } } }
using System; using SparkyCLI; public class Sandbox { public static void Main(string[] args) { Window window = new Window("Test", 960, 540); while (!window.Closed()) { Vector2 mouse = window.GetMousePosition(); Console.WriteLine("{0}, {1}", mouse.x, mouse.y); window.Update(); } } }
using System; using System.Linq; using System.Collections.Generic; namespace RPS { public enum gameResult { player1Won, player2Won, draw, notFinished } public static class GameFinished { public static gameResult GameResult(List<wonDrawLost> history) { var groupedRes = history.GroupBy(roundRes => roundRes).ToList(); var maybeFoundTwoTheSameMoves = groupedRes.Find(eachGroup => (eachGroup.Count() == 2)); if (maybeFoundTwoTheSameMoves != null) { switch (maybeFoundTwoTheSameMoves.Key) { case wonDrawLost.won: return gameResult.player1Won; case wonDrawLost.lost: return gameResult.player2Won; //if the result is won, draw, draw or lost, draw, draw, the result will be as below case wonDrawLost.draw: return gameResult.draw; default://compiler limitation return gameResult.draw; } } // else if aaa is null, there should be either draw or notFinished else { if (history.Count == 3) { return gameResult.draw; } else { return gameResult.notFinished; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Options; using SimpleOptions.Models; namespace NamedOptions.Pages { public class IndexModel : PageModel { private readonly MyOptions _named_options_1; private readonly MyOptions _named_options_2; public IndexModel(IOptionsSnapshot<MyOptions> namedOptionsAccessor) { // 用 Get(xxx) 取得命名的選項 _named_options_1 = namedOptionsAccessor.Get("named_options_1"); _named_options_2 = namedOptionsAccessor.Get("named_options_2"); } public string NamedOptions1 { get; private set; } public string NamedOptions2 { get; private set; } public void OnGet() { var named_options_1 = $"named_options_1: option1 = {_named_options_1.Option1}, " + $"option2 = {_named_options_1.Option2}"; var named_options_2 = $"named_options_2: option1 = {_named_options_2.Option1}, " + $"option2 = {_named_options_2.Option2}"; NamedOptions1 = named_options_1; NamedOptions2 = named_options_2; } } }
using NUnit.Framework; using TechTalk.SpecFlow; namespace Specs.Steps { [Binding] public class RegistrationBindings { private readonly ScenarioContext _scenarioContext; private string _name; private string _email; private string _errorMessage = ""; public RegistrationBindings(ScenarioContext scenarioContext) { _scenarioContext = scenarioContext; } [Given(@"a visitor registering as ""(.*)"" with email (.*)")] public void GivenAVisitorRegisteringAsWithEmail(string name, string email) { this._email = email; this._name = name; } [When(@"the registration completes")] public void WhenTheRegistrationCompletes() { //Simulate some email validation if (!_email.Contains("@")) { _email = null; _errorMessage = "Invalid Email"; } } [Then(@"the account system should record (.*) related to user ""(.*)""")] public void ThenTheAccountSystemShouldRecordEmailToUser(string email, string name) { Assert.AreEqual(name, _name); Assert.AreEqual(email, _email); } [Then(@"the account system should not record (.*)")] public void ThenTheAccountSystemShouldNotRecord(string p0) { Assert.IsNull(_email); } [Then(@"the error response should be ""(.*)""")] public void ThenTheErrorResponseShouldBe(string expectedErrorMessage) { Assert.AreEqual(expectedErrorMessage, _errorMessage); } } }
using System; using System.Collections.Generic; namespace _1._Reverse_Strings { class Program { static void Main(string[] args) { string text = Console.ReadLine(); Stack<string> reverseText = new Stack<string>(); foreach (var ch in text) { reverseText.Push(ch.ToString()); } Console.WriteLine(string.Join("", reverseText)); } } }
using Microsoft.AspNetCore.Http; using SchoolDiary.Models; using SchoolDiary.Services.Categories.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace SchoolDiary.Services.Contracts { public interface ICategoryService { Task<bool> Create(CreateCategoryInputViewModel model, string imageUploadResult); IEnumerable<CategoryViewModel> GetAll(); IEnumerable<Category> GetAllCategoriesPlainCollection(); void AddCourse(Course course); void DeleteCategory(string id); EditCategoryViewModel GetAllCategoryById(string id); void EditCategory(EditCategoryViewModel model, string imageUploadResult); } }
using System; using System.Threading.Tasks; using EShopOnAbp.BasketService; using EShopOnAbp.Shared.Hosting.AspNetCore; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Volo.Abp.DependencyInjection; using Volo.Abp.Users; namespace EShopOnAbp.PublicWeb.ServiceProviders { public class UserBasketProvider : ITransientDependency { private HttpContext HttpContext => _httpContextAccessor.HttpContext; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ILogger<UserBasketProvider> _logger; private readonly IBasketAppService _basketAppService; public UserBasketProvider( IHttpContextAccessor httpContextAccessor, ILogger<UserBasketProvider> logger, IBasketAppService basketAppService) { _httpContextAccessor = httpContextAccessor; _logger = logger; _basketAppService = basketAppService; } public virtual async Task<BasketDto> GetBasketAsync() { try { // Get anonymous user id from cookie HttpContext.Request.Cookies.TryGetValue(EShopConstants.AnonymousUserClaimName, out string anonymousUserId); return await _basketAppService.GetAsync(Guid.Parse(anonymousUserId)); } catch (Exception ex) { _logger.LogError(ex, ex.Message); return null; } } } }
using System; using System.Threading.Tasks; using System.Collections.Generic; using TechTalk.DataModels; namespace TechTalk.Interfaces { public interface IGalleryService { Task<IList<Picture>> LoadImagesAsync(); } }
using Newtonsoft.Json; namespace BackendAPI.Data { public class MetaSenseCo2Readings { [JsonProperty("CO2")] public double Co2; } }
using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class Image { public string Url { get; set; } } }
namespace VeilleConcurrentielle.EventOrchestrator.ConsoleApp { public class WorkerConfigOptions { public const string WorkerConfig = "WorkerConfig"; public int GetNextWaitInSeconds { get; set; } = 5; public bool InfiniteRun { get; set; } = false; public int DispatchRetryCountBeforeForcingConsume { get; set; } = 1; public int RetryWaitInSeconds { get; set; } = 5; } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using SlackRedditBot.Web.Processors; namespace SlackRedditBot.Web.Services { public class RedditService : BackgroundService { private readonly IServiceProvider _serviceProvider; private readonly Channel<JObject> _requestChannel; private readonly ILogger<RedditService> _logger; public RedditService(IServiceProvider serviceProvider, Channel<JObject> requestChannel, ILogger<RedditService> logger) { _serviceProvider = serviceProvider; _requestChannel = requestChannel; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var tasks = new List<Task>(); while (!stoppingToken.IsCancellationRequested) { var requestObj = await _requestChannel.Reader.ReadAsync(stoppingToken); tasks.Add(ProcessEvent(requestObj, stoppingToken)); tasks.RemoveAll(t => t.IsCompleted); } await Task.WhenAll(tasks); } private async Task ProcessEvent(JObject requestObj, CancellationToken stoppingToken) { try { using var scope = _serviceProvider.CreateScope(); await scope.ServiceProvider.GetRequiredService<RedditProcessor>() .ProcessRequest(requestObj, stoppingToken); } catch (OperationCanceledException) { } catch (Exception e) { _logger.LogError(e.ToString()); } } } }
using GameWork.Core.States.Tick.Input; using PlayGen.ITAlert.Unity.Utilities; namespace PlayGen.ITAlert.Unity.States.Game.Room.Initializing { public class InitializingStateInput : TickStateInput { protected override void OnInitialize() { GameObjectUtilities.FindGameObject("Game/Canvas/Graph"); } } }
using System; namespace MultiScreenSample.Views { public enum CustomWindowStates { Normal, Minimized, Maximized, FullScreen } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; using System.IO; using DiscordRPC; using DiscordRPC.Logging; using DiscordRPC.Events; namespace MarsClientLauncher { public partial class Form1 : Form { [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")] private static extern IntPtr CreateRoundRectRgn ( int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse); public static string username; public static string password; private void Form1_Load(object sender, EventArgs e) { FormBorderStyle = FormBorderStyle.None; SetBorderCurve(10); DoubleBuffered = true; mainLauncher1.SendToBack(); if (!Directory.Exists("mars_client")) { DirectoryInfo di = Directory.CreateDirectory("mars_client"); di.Attributes = FileAttributes.Hidden; } DiscordRpcClient cli; cli = new DiscordRpcClient("620414963902709760"); //cli.RegisterUriScheme(null, null); //cli.OnJoinRequested += Cli_OnJoinRequested; cli.Initialize(); Data.rpccli = cli; Data.hook = new KeyboardHooking(); if (!File.Exists("mars_client\\bindings.ser")) Data.keybinds = new KeybindManager(); else { Data.keybinds = KeybindManager.Deserialize( File.ReadAllText("mars_client\\bindings.ser")); } } public Form1() { InitializeComponent(); OutputManager.ShowConsoleWindow(false); Opacity = 0; } public static int Lerp(int a, int b, double t) { return (int)Math.Round((a * (1.0f - t)) + (b * t)); } public void SetBorderCurve(int radius) { Region r = Region; if(r != null) { r.Dispose(); } IntPtr toBeDestroyed = CreateRoundRectRgn(0, 0, Width, Height, radius, radius); Region = Region.FromHrgn(toBeDestroyed); MainLauncher.DeleteObject(toBeDestroyed); } public static void SetBorderCurve(int radius, Control ctrl) { Region r = ctrl.Region; if (r != null) { r.Dispose(); } IntPtr toBeDestroyed = CreateRoundRectRgn(0, 0, ctrl.Width, ctrl.Height, radius, radius); r = Region.FromHrgn(toBeDestroyed); ctrl.Region = r; MainLauncher.DeleteObject(toBeDestroyed); return; } public int Round(float f) { return (int)Math.Round(f); } private void Exitbutton_Click(object sender, EventArgs e) { Close(); } private void Minimizebutton_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern bool ReleaseCapture(); private void MainLauncher1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { File.WriteAllText("mars_client\\bindings.ser", Data.keybinds.Serialize()); if (Data.player != null) File.WriteAllText("mars_client\\hypixelself.ser", Data.player.Serialize()); Data.rpccli.Dispose(); Data.hook.Dispose(); if(MainLauncher.mcThread != null) MainLauncher.mcThread.Abort(); Data.mcProcess?.Dispose(); Data.hud?.Close(); Data.hud?.Dispose(); } private void Timer1_Tick(object sender, EventArgs e) { Point orig = Location; Point n = orig; Opacity = 0.05; n.Y = orig.Y + 30; Location = n; Task.Delay(16).Wait(); Opacity = 0.2; n.Y = orig.Y + 25; Location = n; Task.Delay(16).Wait(); Opacity = 0.4; n.Y = orig.Y + 20; Location = n; Task.Delay(16).Wait(); Opacity = 0.5; n.Y = orig.Y + 17; Location = n; Task.Delay(16).Wait(); Opacity = 0.55; n.Y = orig.Y + 15; Location = n; Task.Delay(16).Wait(); Opacity = 0.60; n.Y = orig.Y + 13; Location = n; Task.Delay(16).Wait(); Opacity = 0.65; n.Y = orig.Y + 11; Location = n; Task.Delay(16).Wait(); Opacity = 0.68; n.Y = orig.Y + 9; Location = n; Task.Delay(16).Wait(); Opacity = 0.72; n.Y = orig.Y + 8; Location = n; Task.Delay(16).Wait(); Opacity = 0.75; n.Y = orig.Y + 7; Location = n; Task.Delay(16).Wait(); Opacity = 0.75; n.Y = orig.Y + 6; Location = n; Task.Delay(16).Wait(); Opacity = 0.75; n.Y = orig.Y + 5; Location = n; Task.Delay(16).Wait(); Opacity = 0.79; n.Y = orig.Y + 4; Location = n; Task.Delay(16).Wait(); Opacity = 0.82; n.Y = orig.Y + 3; Location = n; Task.Delay(16).Wait(); Opacity = 0.85; n.Y = orig.Y + 3; Location = n; Task.Delay(16).Wait(); Opacity = 0.87; n.Y = orig.Y + 2; Location = n; Task.Delay(16).Wait(); Opacity = 0.9; n.Y = orig.Y + 2; Location = n; Task.Delay(16).Wait(); Opacity = 0.92; n.Y = orig.Y + 1; Location = n; Task.Delay(16).Wait(); Opacity = 0.94; n.Y = orig.Y + 1; Location = n; Task.Delay(16).Wait(); Opacity = 0.95; n.Y = orig.Y + 1; Location = n; Task.Delay(16).Wait(); Opacity = 0.96; n.Y = orig.Y + 0; Location = n; Task.Delay(16).Wait(); Opacity = 0.97; n.Y = orig.Y + 0; Location = n; Task.Delay(16).Wait(); Opacity = 0.98; n.Y = orig.Y + 0; Location = n; Task.Delay(16).Wait(); Opacity = 0.99; n.Y = orig.Y + 0; Location = n; Task.Delay(16).Wait(); Opacity = 1.0; n.Y = orig.Y + 0; Location = n; animator.Stop(); } private void ClosingTimer_Tick(object sender, EventArgs e) { if (mainLauncher1.minecraftClosed) { closingTimer.Stop(); Close(); } } } }
using System; namespace SampleAppError { class Program { static void Main(string[] args) { throw new Exception("What is dead may never die."); } } }
using System; using System.IO; using TradeAdvisor.Utils; namespace TradeAdvisor { public static class KnownPaths { public static DirectoryPath SolutionRoot => solutionRoot.Value; static readonly Lazy<DirectoryPath> solutionRoot = new Lazy<DirectoryPath>(FindSolutionRoot); static DirectoryPath FindSolutionRoot() { var current = DirectoryPath.CurrentWorkingDirectory; for (; ; ) { if (current == null) throw new Exception(); if (current.GetFile("TradeAdvisor.sln").Exists) return current; current = current.Parent; } } } }
using System.Threading.Tasks; using System.Windows; using Caliburn.Micro; using MahApps.Metro.Controls; namespace MahApps.Integration.Caliburn.Micro.Dialogs.Base { /// <summary> /// Base class for coroutines that display a dialog. /// </summary> public abstract class DialogBase : ResultBase { /// <summary> /// Gets a value indicating whether the dialog must be closed manually. /// </summary> protected virtual bool RequiresManualClose { get { return false; } } /// <summary> /// Gets the metro window for the current coroutine execution context. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The <see cref="MetroWindow"/> if found; otherwise, <c>null</c>. /// </returns> protected static MetroWindow GetWindow(CoroutineExecutionContext context) { var view = context.Source as DependencyObject; if (view != null) { return Window.GetWindow(view) as MetroWindow; } return null; } /// <inheritdoc /> public sealed async override void Execute(CoroutineExecutionContext context) { var window = GetWindow(context); if (window != null) { await ShowWindow(window, context); } if (!RequiresManualClose) { OnCompleted(); } } /// <summary> /// Shows the window. /// </summary> /// <param name="window">The window.</param> /// <param name="context">The context.</param> /// <returns>The task displaying the window.</returns> protected abstract Task ShowWindow(MetroWindow window, CoroutineExecutionContext context); } }
using System; using System.Runtime.InteropServices; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; namespace Snap.Installer.Windows; internal class CustomChromeWindow : Window { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { var thisHandle = PlatformImpl.Handle.Handle; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { NativeMethodsWindows.FocusThisWindow(thisHandle); } base.OnApplyTemplate(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { BeginMoveDrag(e); base.OnPointerPressed(e); } protected override void HandleWindowStateChanged(WindowState state) { WindowState = WindowState.Normal; } protected static class NativeMethodsWindows { [DllImport("user32", SetLastError = true, EntryPoint = "SetActiveWindow")] static extern IntPtr SetActiveWindow(IntPtr hWnd); [DllImport("user32", SetLastError = true, EntryPoint = "SetForegroundWindow")] static extern bool SetForegroundWindow(IntPtr hWnd); public static void FocusThisWindow(IntPtr hWnd) { SetActiveWindow(hWnd); SetForegroundWindow(hWnd); } } }
namespace Amazon.DynamoDb { public sealed class Conflict : DynamoDbException { public Conflict(string message) : base(message) { Type = "ConditionalCheckFailedException"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using MaterialDesignColors; using MaterialDesignThemes.Wpf; namespace Imbentaryo { /// <summary> /// Interaction logic for SellReport.xaml /// </summary> public partial class SellReport { #region Declarations Inventory inventory = new Inventory(); UtilityHelper utilityHelper = new UtilityHelper(); private List<Inventory> inventoryList = null; #endregion #region Methods public SellReport() { InitializeComponent(); LoadItemsToDgd(); } private void InitializeMaterialDesign() { // Create dummy objects to force the MaterialDesign assemblies to be loaded // from this assembly, which causes the MaterialDesign assemblies to be searched // relative to this assembly's path. Otherwise, the MaterialDesign assemblies // are searched relative to Eclipse's path, so they're not found. var card = new Card(); var hue = new Hue("Dummy", Colors.Black, Colors.White); } private void LoadItemsToDgd() { inventoryList = utilityHelper.LoadSellerReport(); dgdSellReport.ItemsSource = inventoryList; } #endregion #region Buttons private void btnGo_Click(object sender, RoutedEventArgs e) { if (cmbSearch.Text == "Show All") { LoadItemsToDgd(); } if (cmbSearch.Text == "Total Amount") { inventory.TotalAmount = Convert.ToDecimal(txtSearch.Text); dgdSellReport.ItemsSource = utilityHelper.FindItem("TotalAmount", txtSearch.Text); } if (cmbSearch.Text == "Item Stock") { inventory.ItemStock = Convert.ToUInt32(txtSearch.Text); dgdSellReport.ItemsSource = utilityHelper.FindItem("ItemStock", txtSearch.Text); } if (cmbSearch.Text == "Date") { inventory.Date = txtSearch.Text; dgdSellReport.ItemsSource = utilityHelper.FindItem("Date", txtSearch.Text); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CandyFramework.ConfigurationEditor.Entites { public class Product { public string ProductName { get; set; } public string InstanceName { get; set; } public string ConnectionString { get; set; } public override string ToString() { return $"{this.ProductName} -> {this.InstanceName}"; } public Product():this(string.Empty) { } public Product(string productName) : this(productName, string.Empty) { } public Product(string productName, string instanceName) : this(productName, instanceName, string.Empty) { } public Product(string productName, string instanceName, string connectionString) { this.ProductName = productName; this.InstanceName = instanceName; this.ConnectionString = connectionString; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Aspose.SVG.Live.Demos.UI.Services.SVG.Applications { public class MatchResult<T> : MatchResult { public MatchResult(bool value, T data) : base(value) { this.Data = data; } public T Data { get; } } public class MatchResult : IEquatable<MatchResult> { public static readonly MatchResult True = new MatchResult(true); public static readonly MatchResult False = new MatchResult(false); private bool value; protected MatchResult(bool value) : this(value, 0) { } MatchResult(bool value, int errorCode) { this.value = value; this.ErrorCode = errorCode; } public static MatchResult Error(int errorCode) { return new MatchResult(false, errorCode); } public static MatchResult Result<T>(T data) { return new MatchResult<T>(true, data); } public int ErrorCode { get; } public static bool operator ==(MatchResult a, MatchResult b) { if (ReferenceEquals(a, b)) return true; if (ReferenceEquals(a, null)) return false; return a.Equals(b); } public static bool operator !=(MatchResult a, MatchResult b) { return !(a == b); } public bool Equals(MatchResult other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return this.value.Equals(other.value); } public override bool Equals(object obj) { return obj is MatchResult other && Equals(other); } public override string ToString() { return value.ToString(); } } }
using System; using BenchmarkDotNetAnalyser.Instrumentation; using FluentAssertions; using FsCheck.Xunit; using Xunit; namespace BenchmarkDotNetAnalyser.Tests.Unit.Instrumentation { public class ColourExtensionsTests { [Fact] public void Colourise_NullValue_ReturnsNull() { string value = null; var r = value.Colourise(ConsoleColor.Blue); r.Should().BeNullOrEmpty(); } [Property(Verbose = true, Arbitrary = new[] {typeof(AlphanumericStringArbitrary)})] public bool Colourise_ReturnsAnnotatedValue(string value, ConsoleColor colour) { var result = value.Colourise(colour); return result.Contains(value) && result.Length > value.Length; } } }
using UnityEngine; using UnityEngine.InputSystem; public class Controller : MonoBehaviour { public Rigidbody rb; [Space] [Range(0, 1)] public float throttle = 1f; [Space] public float speed = 150f; public float rollSpeed = 50f; public float turnSpeed = 0.1f; public float fuel = 100f; public int angularDrag = 1; [Space] public bool cursorLocked = true; public bool invertY = false; public bool sas = true; private void Start() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } private void Update() { Sas(); if (fuel <= 0) { fuel = 0; throttle = 0; sas = false; } else { Dash(); Throttle(); rb.AddRelativeForce(Force(), ForceMode.VelocityChange); rb.AddRelativeTorque(Torque(), ForceMode.VelocityChange); if (cursorLocked == true) { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } } } private Vector3 Force() { var force = new Vector3(); if (Keyboard.current.wKey.isPressed) { rb.AddRelativeForce(Vector3.forward * speed * throttle * Time.deltaTime); fuel = fuel - 0.01f * throttle; } if (Keyboard.current.sKey.isPressed) { rb.AddRelativeForce(Vector3.back * speed * throttle * Time.deltaTime); fuel = fuel - 0.01f * throttle; } if (Keyboard.current.aKey.isPressed) { rb.AddRelativeForce(Vector3.left * speed * throttle * Time.deltaTime); fuel = fuel - 0.01f * throttle; } if (Keyboard.current.dKey.isPressed) { rb.AddRelativeForce(Vector3.right * speed * throttle * Time.deltaTime); fuel = fuel - 0.01f * throttle; } if (Keyboard.current.rKey.isPressed) { rb.AddRelativeForce(Vector3.up * speed * throttle * Time.deltaTime); fuel = fuel - 0.01f * throttle; } if (Keyboard.current.fKey.isPressed) { rb.AddRelativeForce(Vector3.down * speed * throttle * Time.deltaTime); fuel = fuel - 0.01f * throttle; } return force; } private Vector3 Torque() { float yaw = Input.GetAxis("Mouse X"); //rb.AddRelativeTorque(transform.up * turnSpeed * yaw); float pitch = Input.GetAxis("Mouse Y") * (invertY ? 1 : -1); //rb.AddRelativeTorque(transform.up * turnSpeed * pitch); if (Keyboard.current.qKey.isPressed) { rb.AddRelativeTorque(Vector3.forward * rollSpeed * Time.deltaTime); fuel = fuel - 0.01f * throttle; } if (Keyboard.current.eKey.isPressed) { rb.AddRelativeTorque(Vector3.back * rollSpeed * Time.deltaTime); fuel = fuel - 0.01f * throttle; } return new Vector3(pitch, yaw) * turnSpeed; } private void Throttle() { throttle += Input.GetAxis("Mouse ScrollWheel"); throttle = Mathf.Clamp(throttle, 0f, 1f); } private void Sas() { if (sas == true) { rb.angularDrag = angularDrag; } else { rb.angularDrag = 0f; } } private void Dash() { // timer if (Mouse.current.rightButton.isPressed) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Part1.Common { public interface IDeviceMonitor<TDeviceData> : IDisposable { void Start(); void Stop(); event EventHandler<DataReceivedEventArgs<TDeviceData>> DataReceived; event EventHandler<MonitorStatusEventArgs> MonitorStatusChanged; } public class DataReceivedEventArgs<TTDeviceData> : EventArgs { public TTDeviceData Data { get; set; } } public class MonitorStatusEventArgs : EventArgs { public MonitorStatus Status { get; set; } } public enum MonitorStatus { STARTED, STOPPED } }
using System; namespace Pattern { class MainClass { public static string DrawFigure(int n, char u, char r, char d, char l) { if(n == 0) { return ""; } return DrawFigure(n - 1, r, u, l, d) + u + DrawFigure(n - 1, u, r, d, l) + r + DrawFigure(n - 1, u, r, d, l) + d + DrawFigure(n - 1, l, d, r, u); } public static void Main() { int n = int.Parse(Console.ReadLine()); string figure = DrawFigure(n, 'u', 'r', 'd', 'l'); Console.WriteLine(figure); // comment before submitting Svg.WriteToFile("output.svg", figure); } } }
namespace EmailCore.Results { public class BaseSenderResult : ISenderResult { public bool Successful { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Kaiyuanshe.OpenHackathon.Server.Models { /// <summary> /// Administrator of a hackathon /// </summary> public class HackathonAdmin : ModelBase { /// <summary> /// name of hackathon /// </summary> /// <example>foo</example> public string hackathonName { get; internal set; } /// <summary> /// user id of admin /// </summary> /// <example>1</example> public string userId { get; internal set; } /// <summary> /// detailed user info of the admin. /// </summary> public UserInfo user { get; internal set; } } public class HackathonAdminList : ResourceList<HackathonAdmin> { /// <summary> /// a list of admins /// </summary> public override HackathonAdmin[] value { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DropdownMenu : MonoBehaviour { public GameObject[] prefabs; GameObject player; int prefabid; public void PlayerSwitch() { Dropdown dpmenu = GetComponent<Dropdown>(); prefabid = dpmenu.value; Destroy(GameObject.FindGameObjectWithTag("Player")); Instantiate(prefabs[prefabid], new Vector3(0, 2.41f, 0), Quaternion.identity); } }
using System; using System.Collections.Generic; using System.Text; namespace LiveCoin.Net.Objects.SocketObjects { /// <summary> /// Pong response /// </summary> [global::ProtoBuf.ProtoContract()] public class PongResponse { /// <summary> /// time of received ping /// </summary> public DateTime PingTime { get; set; } [global::ProtoBuf.ProtoMember(1)] private long PingTimeImpl { get => PingTime.ToUnixMilliseconds(); set => PingTime = value.ToUnixMilliseconds(); } } }
// <copyright file="ExportMessageQueueContent.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Apps.CompanyCommunicator.Prep.Func.Export.Model { /// <summary> /// Azure service bus export queue message content class. /// </summary> public class ExportMessageQueueContent { /// <summary> /// Gets or sets the notification id value. /// </summary> public string NotificationId { get; set; } /// <summary> /// Gets or sets the user id value. /// </summary> public string UserId { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ControllerPlayer : MonoBehaviour, ITakeDamage, IHealer { // Use this for initialization private Vector3 direction; private Quaternion newRotation; public LayerMask floorMask; public GameObject textGameOver; public bool isLife = true; private Rigidbody rigidbodyPlayer; private Animator animatorPlayer; public ControllerInterface scriptControllerInterface; public AudioClip songDamage; public StatusChar status; private MovementPlayer movement; private AnimationChar animator; /// Start is called on the frame when a script is enabled just before /// any of the Update methods is called the first time. void Start(){ Time.timeScale = 1; rigidbodyPlayer = GetComponent<Rigidbody>(); animatorPlayer = GetComponent<Animator>(); status = GetComponent<StatusChar>(); movement = GetComponent<MovementPlayer>(); animator = GetComponent<AnimationChar>(); status = GetComponent<StatusChar>(); } // Update is called once per frame void Update () { float axisX = Input.GetAxis(Tags.directionHorizontal); float axisZ = Input.GetAxis(Tags.directionVertical); direction = new Vector3(axisX, 0, axisZ); animator.MoveAnimator(direction); } /// This function is called every fixed framerate frame, if the MonoBehaviour is enabled. void FixedUpdate(){ movement.Movement(direction,status.velocity); movement.RotationPlayer(floorMask); } public void TakeDamage(int damage){ status.life -=damage; scriptControllerInterface.UpdateSliderLifePlayer(); ControllerAudio.instance.PlayOneShot(songDamage); if (status.life <=0){ Die(); } } public void Die(){ scriptControllerInterface.GameOver(); } public void HealLife(int qtdLife){ status.life +=qtdLife; if (status.life > status.initialLife){ status.life = status.initialLife; } scriptControllerInterface.UpdateSliderLifePlayer(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering.Universal; public class DisableFarAway : MonoBehaviour { public float maxDistance = 30f; private float nextActionTime = 0.0f; public float period = 0.5f; // Update is called once per frame private Light2D l; private Collider2D c; private void Start() { l = GetComponent<Light2D>(); c = GetComponent<Collider2D>(); } void Update() { if (Time.time > nextActionTime) { nextActionTime += period; CheckIfEnableNeeded(); } } private void SetLightAndColliderActive(bool isActive) { if (l) { l.enabled = isActive; } if (c) { c.enabled = isActive; } } private void SetChildrenActive(bool isActive) { for (int i = 0; i < this.transform.childCount; i++) { var child = this.transform.GetChild(i).gameObject; if (child != null) child.SetActive(isActive); } } private void CheckIfEnableNeeded() { float distanceToPlayer = Vector3.Distance(Player.Instance.transform.position, transform.position); if (distanceToPlayer > maxDistance) { SetChildrenActive(false); SetLightAndColliderActive(false); } else { SetChildrenActive(true); SetLightAndColliderActive(true); } } }
using UnityEngine; using System.Collections; using UnityEngine.Audio; public class AudioManager : MonoBehaviour { public static AudioManager instance = null; public AudioMixer audioMixer; public AudioMixerSnapshot unPaused; public AudioMixerSnapshot paused; public AudioSource mainMusic = null; public AudioSource alert = null; public AudioSource waterDrop = null; public AudioSource waterDrop2 = null; public AudioSource waterDrop3 = null; public AudioSource victory = null; public AudioSource wind = null; public AudioSource quake = null; public AudioSource water = null; public AudioSource space = null; // Use this for initialization void Awake () { instance = this; } // Update is called once per frame void Update () { } public void Instanciate(AudioSource audioSource) { audioSource.PlayOneShot(audioSource.clip); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Serilog; namespace DiscordOgerBot.Controller { public static class TimeManagement { private static readonly Dictionary<ulong, ActiveUserStruct> ActiveUsers = new(); private static readonly TimeSpan CoolOfTime = TimeSpan.FromMinutes(1); public static void Measure(ulong userId) { try { if (ActiveUsers.TryGetValue(userId, out var activeUserStruct)) { activeUserStruct.CancellationTokenSource.Cancel(); } else { var newActiveUserStruct = new ActiveUserStruct { ActiveTime = new TimeSpan(), CancellationTokenSource = new CancellationTokenSource() }; ActiveUsers.Add(userId, newActiveUserStruct); Task.Factory.StartNew(() => { MeasureActiveTime(userId, newActiveUserStruct.CancellationTokenSource.Token); }, newActiveUserStruct.CancellationTokenSource.Token); } } catch (Exception ex) { Log.Error(ex, $"Could not measure time of user {userId}"); } } private static void MeasureActiveTime(ulong userId, CancellationToken cancellationToken) { try { var stopWatch = new Stopwatch(); stopWatch.Start(); if (cancellationToken.WaitHandle.WaitOne(CoolOfTime)) { stopWatch.Stop(); var user = ActiveUsers[userId]; user.ActiveTime += stopWatch.Elapsed; user.CancellationTokenSource.Dispose(); user.CancellationTokenSource = new CancellationTokenSource(); ActiveUsers[userId] = user; Task.Factory.StartNew(() => { MeasureActiveTime(userId, user.CancellationTokenSource.Token); }, user.CancellationTokenSource.Token); } else { stopWatch.Stop(); var user = ActiveUsers[userId]; user.ActiveTime += stopWatch.Elapsed; DataBase.IncreaseTimeSpendWorking(userId, user.ActiveTime); ActiveUsers.Remove(userId); user.CancellationTokenSource.Cancel(); user.CancellationTokenSource.Dispose(); } } catch (Exception ex) { Log.Error(ex, $"Could not measure time of user {userId}"); } } } internal struct ActiveUserStruct { internal CancellationTokenSource CancellationTokenSource { get; set; } internal TimeSpan ActiveTime { get; set; } } }
using NUnit.Framework; using Qowaiv.TestTools; using Qowaiv.Validation.Abstractions; namespace Validation_message_specs { public class None { [Test] public void Has_an_empty_string_representation() { var message = ValidationMessage.None; Assert.AreEqual("", message.ToString()); } } public class Serialization { [Test] public void On_an_info_message_keeps_all_data() { var message = ValidationMessage.Info("Can be serialized", "Prop"); var actual = SerializationTest.SerializeDeserialize(message); Assert.AreEqual(message.Severity, actual.Severity); Assert.AreEqual(message.Message, actual.Message); Assert.AreEqual(message.PropertyName, actual.PropertyName); Assert.AreEqual("INF: Property: Prop, Can be serialized", message.ToString()); } [Test] public void On_a_warning_message_keeps_all_data() { var message = ValidationMessage.Warn("Can be serialized", "Prop"); var actual = SerializationTest.SerializeDeserialize(message); Assert.AreEqual(message.Severity, actual.Severity); Assert.AreEqual(message.Message, actual.Message); Assert.AreEqual(message.PropertyName, actual.PropertyName); Assert.AreEqual("WRN: Property: Prop, Can be serialized", message.ToString()); } [Test] public void On_an_error_message_keeps_all_data() { var message = ValidationMessage.Error("Can be serialized", "Prop"); var actual = SerializationTest.SerializeDeserialize(message); Assert.AreEqual(message.Severity, actual.Severity); Assert.AreEqual(message.Message, actual.Message); Assert.AreEqual(message.PropertyName, actual.PropertyName); Assert.AreEqual("ERR: Property: Prop, Can be serialized", message.ToString()); } } }
namespace craft { public class PalindromeTester { public bool Test(string strInput) { strReplace = strInput.Replace("", ""); strReversed = new string (strReplace.Reverse().ToArray()); return strReversed.Equals(strReversed); } public bool Check(string input) { input = input.Replace("", ""); var reversed = new string(input.Reverse().ToArray()); return reversed.Equals(input); } public bool IsPalindrome(string input) { var forwards = input.Reverse(" ", ""); var backwards = new string(forwards.Reverse().ToArray()); return backwards.Equals(forwards); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Support.mbed { using System.Runtime.InteropServices; //--// public class UsTicker { [DllImport("C")] public static extern uint us_ticker_read(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AjaxControlToolkit.Reference.Core { class EnhancementsBuilder : IssueBuilder { public EnhancementsBuilder(IEnumerable<GitHubIssue> validIssues) : base(validIssues) { issueKindName = "enhancement"; } internal override string GetHeader() { return "Features and improvements:"; } } }
namespace Vba.Grammars { partial class VbaParser { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameOverScript : MonoBehaviour { public GameController gameController; // Start is called before the first frame update public void Menu() { gameController.lastCheckpoint.x = 0; SceneManager.LoadScene("MenuJairo"); } void Start() { gameController = GameController.getInstance(); } // Update is called once per frame public void Retry() { gameController.Retry(); } }
using Cory.TowerGame.Enemies; using Cory.TowerGame.Targeting; using Cory.TowerGame.Towers; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Cory.TowerGame.Combat { public class LaserAttack : MonoBehaviour { [Header("Laser Settings")] [SerializeField] private float fireRate = 0.5f; [SerializeField] private TowerData towerData = null; [SerializeField] private Transform spawnPoint = null; [SerializeField] private LineRenderer lineRenderer = null; private float timer; private TargetingSystem targetingSystem; private void Start() { targetingSystem = GetComponent<TargetingSystem>(); } private void Update() { Enemy target = targetingSystem.Target; if (target != null) { lineRenderer.positionCount = 2; lineRenderer.SetPositions(new Vector3[] { spawnPoint.position, target.transform.position }); } else { lineRenderer.positionCount = 0; } timer -= Time.deltaTime; if (timer > 0f) { return; } timer = fireRate; if (target != null) { target.DealDamage(Mathf.CeilToInt(towerData.Dps * fireRate)); } } } }
using System; namespace Shiny.Beacons { public enum BeaconRegisterEventType { Add, Update, Remove, Clear } public class BeaconRegisterEvent { public BeaconRegisterEvent(BeaconRegisterEventType eventType, BeaconRegion region = null) { this.Type = eventType; this.Region = region; } public BeaconRegisterEventType Type { get; } public BeaconRegion Region { get; } } }
using System; using System.Windows.Controls; using Internationalization.GUITranslator; namespace Example_Excel.View { /// <summary> /// Interaction logic for ExampleView.xaml /// </summary> public partial class ExampleView : UserControl { public ExampleView() { InitializeComponent(); Loaded += TranslateMe; } private void TranslateMe(object sender, EventArgs eventArgs) { GuiTranslator.TranslateGui(this); } } }
using System; using System.Collections.Generic; using System.Linq; namespace api.Backend.Data.SQL.AutoSQL { /// <summary> /// Represents a link between a Table Obj and a DB Table /// </summary> public class Binding { #region Fields private readonly Type ObjType; private readonly Redis.CacheTable table; public static List<Binding> bindings = new List<Binding>(); #endregion Fields #region Constructors /// <summary> /// Link the Obj to the Table /// </summary> /// <param name="Obj"> </param> /// <param name="Table"> </param> public Binding(Type Obj, string Table) { this.ObjType = Obj; this.table = (Redis.CacheTable)Instance.tables.First(x => x.Name.ToLower() == Table.ToLower()); } #endregion Constructors #region Methods /// <summary> /// Create a link between T and Table /// </summary> /// <typeparam name="T"> </typeparam> /// <param name="Table"> </param> public static void Add<T>(string Table) where T : Obj.Object, new() { bindings.Add(new Binding(typeof(T), Table)); } public static void Add<T>() where T : Obj.Object, new() { bindings.Add(new Binding(typeof(T), new T().GetType().Name)); } /// <summary> /// Create a link between objType and Table /// </summary> /// <param name="objType"> </param> /// <param name="Table"> </param> public static void Add(Type objType, string Table) { bindings.Add(new Binding(objType, Table)); } /// <summary> /// Get the table that is bound to type T /// </summary> /// <typeparam name="T"> </typeparam> /// <returns> </returns> public static Redis.CacheTable GetTable<T>() { return bindings.First(x => x.ObjType == typeof(T))?.table; } /// <summary> /// Get the table that is bound to type objType /// </summary> /// <param name="objType"> </param> /// <returns> </returns> public static Redis.CacheTable GetTable(Type objType) { return bindings.First(x => x.ObjType == objType)?.table; } #endregion Methods } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using UnityEngine.UI; public class AttackDroneController : MonoBehaviour { //::::: POWERUP ::::: public bool tutorialWait; [Header("SliderSkillConfig")] public Color initFillColor; public Color endFillColor; public float cooldown; [Header("Missile")] public ParticleSystem missileFXNotSpawnable; public GameObject explosionFX; public GameObject bulletSpawn; [Header("Bar")] //Slider slider; //public Image fillSlider; [Header("Circle")] public Image backgroundCircle; public Image fillCircle; public GameObject skillIcon; public GameObject keyR; [Header("LightSkill")] Light lightDrone; private float initLightIntensity; public float freqLightDrone; private float timeToChangeLight; public GameObject bulbLightGreen; public GameObject bulbLightYellow; //::::: NAVIGATION ::::: GameObject player; NavMeshAgent navMeshAgent; public GameObject explosionMarkNotSpawneable; //objectTest.transform.position = laserSightHit.point; IEnumerator LerpSlider(float endValue, float duration) { float time = 0; float startValue; //startValue = slider.value; startValue = fillCircle.fillAmount; while (time < duration) { //slider.value = Mathf.Lerp(startValue, endValue, time / duration); fillCircle.fillAmount = Mathf.Lerp(startValue, endValue, time / duration); //fillSlider.color = Color.Lerp(initFillColor, endFillColor, slider.value); fillCircle.color = Color.Lerp(initFillColor, endFillColor, fillCircle.fillAmount); time += Time.deltaTime; yield return null; } //slider.value = endValue; fillCircle.fillAmount = endValue; } public void ShowExplosionMark(bool visible) { explosionMarkNotSpawneable.SetActive(visible); } public void PlaceExplosionMark(Vector3 newPosition) { if(fillCircle.fillAmount == 1) { ShowExplosionMark(true); } Vector3 pos = 0.5f*Vector3.up + newPosition; explosionMarkNotSpawneable.transform.position = pos; } private void LoadingSkillLightFX() { lightDrone.color = Color.yellow; bulbLightYellow.SetActive(true); bulbLightGreen.SetActive(false); timeToChangeLight += Time.deltaTime; if (timeToChangeLight >= freqLightDrone) { timeToChangeLight = 0; if (lightDrone.intensity == initLightIntensity) { lightDrone.intensity = 0; } else { lightDrone.intensity = initLightIntensity; } } } public void StateOfCanvasSkill(bool newState) { backgroundCircle.enabled = newState; fillCircle.enabled = newState; keyR.SetActive(newState); } private void Start() { player = GameObject.FindGameObjectWithTag("Player"); navMeshAgent = GetComponent<NavMeshAgent>(); ShowExplosionMark(false); rocketReadyPlayed = false; //slider = GetComponentInChildren<Slider>(); lightDrone = GetComponentInChildren<Light>(); initLightIntensity = lightDrone.intensity; if (tutorialWait) { StateOfCanvasSkill(false); } } void DoMovement() { navMeshAgent.destination = player.transform.position; transform.rotation.SetLookRotation(player.transform.forward, player.transform.up); } bool rocketReadyPlayed; private void Update() { DoMovement(); if(tutorialWait) { return; } if (fillCircle.fillAmount == 1) { lightDrone.color = Color.cyan; fillCircle.color = Color.green; lightDrone.intensity = initLightIntensity; bulbLightYellow.SetActive(false); bulbLightGreen.SetActive(true); if(!rocketReadyPlayed) { rocketReadyPlayed = true; SoundManager.Instance.PlaySfx("RocketReady"); } skillIcon.SetActive(false); keyR.SetActive(true); } //Reload skill if (fillCircle.fillAmount == 0) { skillIcon.SetActive(true); keyR.SetActive(false); StartCoroutine(LerpSlider(1, cooldown)); } if(fillCircle.fillAmount != 1) { LoadingSkillLightFX(); } //Disparar skill if (Input.GetKeyDown(KeyCode.R) && explosionMarkNotSpawneable.activeSelf) { //Puede disparar if (fillCircle.fillAmount == 1) { //Reset cooldown fillCircle.fillAmount = 0; rocketReadyPlayed = false; //Lanzamos skill missileFXNotSpawnable.transform.position = bulletSpawn.transform.position; missileFXNotSpawnable.transform.LookAt(explosionMarkNotSpawneable.transform); missileFXNotSpawnable.Play(); SoundManager.Instance.PlaySfx("Trail01"); } else { //No puede lanzar skill } } } }
namespace DataBoss.DataPackage { public enum ConstraintsBehavior { Check, Ignore, Drop, } }
using System.Runtime.InteropServices; using static RekordboxDatabaseReader.Internal.ParserHelper; namespace RekordboxDatabaseReader.Internal { [StructLayout(LayoutKind.Sequential)] public readonly struct SeekTableEntry { private readonly int entry; public int Entry => ToHostOrder(entry); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Serialization; namespace SavePaper { //classe statica per la gestione dei file per la lettura e la scrittura delle liste di scontrini public static class FileManager { public static string startpath; //path totale basato sulla posizione dell'eseguibile public static string path = Assembly.GetExecutingAssembly().Location + "/../spese/"; //estensione dei file public static string extension = ".sp"; //metodo per il controlle dell'esistenza e crazione dei file e directory public static void filecheck(string fileName) { fileName += extension; if (!Directory.Exists(path)) Directory.CreateDirectory(path); if (!File.Exists(path + fileName)) File.Create(path + fileName).Close(); } public static void filecheck() { if (!Directory.Exists(path)) Directory.CreateDirectory(path); } //metodo per serializzare e salvare su file le lista di scontrini public static void salvaScontrini(GruppoSpese scontrini, string fileName) { fileName += extension; XmlSerializer serializer = new XmlSerializer(typeof(GruppoSpese)); TextWriter writer = new StreamWriter(path + fileName); serializer.Serialize(writer, scontrini); writer.Close(); } //metodo per de serializzare e ritornare la lista di scontrini caricata su una lista public static GruppoSpese loadScontrini(string fileName) { GruppoSpese temp = new GruppoSpese(new List<Scontrino>()); temp.current_path = fileName; if (File.ReadAllBytes(fileName).Length == 0) return temp; XmlSerializer serializer = new XmlSerializer(typeof(GruppoSpese)); using (Stream reader = new FileStream(fileName, FileMode.Open)) { // Call the Deserialize method to restore the object's state. temp = (GruppoSpese)serializer.Deserialize(reader); temp.current_path = fileName; } return temp; } //metedo per caricare la lista di file (gruppi di scontrini) public static string[] getPapersList() { List<string> files = Directory.GetFiles(path).ToList(); List<string> returner = new List<string>(); foreach (var item in files) { if (item.Contains(extension)) returner.Add(Path.GetFileName(item).Split('.')[0]); } return returner.ToArray(); } //metodo per la cancellazione del file contenente il gruppo di scontrini public static void deleteFile(string filePath) { if (File.Exists(filePath)) File.Delete(filePath); //da fixare //ExcelManager.deleteFile(path + filePath); } //metodo per il salvataggio del file excel (useless) public static void writeExcel(List<Scontrino> scontrini, string fileName) { ExcelManager.saveExcel(scontrini, path, fileName); } public static void ExportSp(string filePath) { GruppoSpese tmp = loadScontrini(filePath); using (var fbs = new FolderBrowserDialog()) { DialogResult result = fbs.ShowDialog(); if(result == DialogResult.OK) { string fileName = Path.GetFileName(filePath); string ExportFile = fbs.SelectedPath + "\\" + fileName; ExportGroup(tmp, ExportFile); } } } public static void ExportGroup(GruppoSpese scontrini, string filepath) { XmlSerializer serializer = new XmlSerializer(typeof(GruppoSpese)); TextWriter writer = new StreamWriter(filepath); serializer.Serialize(writer, scontrini); writer.Close(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Autofac; using Castle.MicroKernel.Registration; using Castle.Windsor; using ExampleLib; using Ninject; using Tapeti; using Tapeti.Autofac; using Tapeti.CastleWindsor; using Tapeti.DataAnnotations; using Tapeti.Default; using Tapeti.Ninject; using Tapeti.SimpleInjector; using Tapeti.UnityContainer; using Unity; using Container = SimpleInjector.Container; // ReSharper disable UnusedMember.Global namespace _01_PublishSubscribe { public class Program { public static void Main(string[] args) { var dependencyResolver = GetSimpleInjectorDependencyResolver(); // or use your IoC container of choice: //var dependencyResolver = GetAutofacDependencyResolver(); //var dependencyResolver = GetCastleWindsorDependencyResolver(); //var dependencyResolver = GetUnityDependencyResolver(); //var dependencyResolver = GetNinjectDependencyResolver(); // This helper is used because this example is not run as a service. You do not // need it in your own applications. var helper = new ExampleConsoleApp(dependencyResolver); helper.Run(MainAsync); } internal static async Task MainAsync(IDependencyResolver dependencyResolver, Func<Task> waitForDone) { var config = new TapetiConfig(dependencyResolver) .WithDataAnnotations() .RegisterAllControllers() .Build(); using (var connection = new TapetiConnection(config) { // Params is optional if you want to use the defaults, but we'll set it // explicitly for this example Params = new TapetiConnectionParams { HostName = "localhost", Username = "guest", Password = "guest", // These properties allow you to identify the connection in the RabbitMQ Management interface ClientProperties = new Dictionary<string, string> { { "example", "01 - Publish Subscribe" } } } }) { // IoC containers that separate the builder from the resolver (Autofac) must be built after // creating a TapetConnection, as it modifies the container by injecting IPublisher. (dependencyResolver as AutofacDependencyResolver)?.Build(); // Create the queues and start consuming immediately. // If you need to do some processing before processing messages, but after the // queues have initialized, pass false as the startConsuming parameter and store // the returned ISubscriber. Then call Resume on it later. await connection.Subscribe(); // We could get an IPublisher from the container directly, but since you'll usually use // it as an injected constructor parameter this shows await dependencyResolver.Resolve<ExamplePublisher>().SendTestMessage(); // Wait for the controller to signal that the message has been received await waitForDone(); } } internal static IDependencyContainer GetSimpleInjectorDependencyResolver() { var container = new Container(); container.Register<ILogger, ConsoleLogger>(); container.Register<ExamplePublisher>(); return new SimpleInjectorDependencyResolver(container); } internal static IDependencyContainer GetAutofacDependencyResolver() { var containerBuilder = new ContainerBuilder(); containerBuilder .RegisterType<ConsoleLogger>() .As<ILogger>(); containerBuilder .RegisterType<ExamplePublisher>() .AsSelf(); return new AutofacDependencyResolver(containerBuilder); } internal static IDependencyContainer GetCastleWindsorDependencyResolver() { var container = new WindsorContainer(); // This exact combination is registered by TapetiConfig when running in a console, // and Windsor will throw an exception for that. This is specific to the WindsorDependencyResolver as it // relies on the "first one wins" behaviour of Windsor and does not check the registrations. // // You can of course register another ILogger instead, like DevNullLogger. //container.Register(Component.For<ILogger>().ImplementedBy<ConsoleLogger>()); container.Register(Component.For<ExamplePublisher>()); return new WindsorDependencyResolver(container); } internal static IDependencyContainer GetUnityDependencyResolver() { var container = new UnityContainer(); container.RegisterType<ILogger, ConsoleLogger>(); container.RegisterType<ExamplePublisher>(); return new UnityDependencyResolver(container); } internal static IDependencyContainer GetNinjectDependencyResolver() { var kernel = new StandardKernel(); kernel.Bind<ILogger>().To<ConsoleLogger>(); kernel.Bind<ExamplePublisher>().ToSelf(); return new NinjectDependencyResolver(kernel); } } }
using System; using System.Collections.Generic; using XF.Material.Themer.Models.Themes; namespace XF.Material.Themer.Factories { public class ThemeColorsFactory : IThemeColorsFactory { private readonly IDictionary<Theme, Lazy<IThemeColors>> _registry = new Dictionary<Theme, Lazy<IThemeColors>> { {Theme.Light, new Lazy<IThemeColors>(() => new LightThemeColors())}, {Theme.Dark, new Lazy<IThemeColors>(() => new DarkThemeColors())} }; public IThemeColors GetThemeColors(Theme theme) { return _registry[theme].Value; } } }
using System; namespace SaCodeWhite.Shared.Models { public interface IAlertable { public int PatientTotal { get; } public int Capacity { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using CSPostComplexJsonASPNETCore.Models; namespace CSPostComplexJsonASPNETCore.Controllers { public class HomeController : Controller { private static List<ItemGroup> _datas = new List<ItemGroup>(); public IActionResult Index() { return View(_datas); } [HttpPost] public JsonResult PostJson([FromBody] ItemGroup data) { if (data != null) { _datas.Add(data); } return Json(new { state = 0, msg = string.Empty }); } } }
using Amphisbaena.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Linq; using System.Threading.Tasks; namespace Amphisbaena.Tests.Linq { //------------------------------------------------------------------------------------------------------------------- // /// <summary> /// Factory Tests /// </summary> // //------------------------------------------------------------------------------------------------------------------- [TestCategory("Linq.AllAndAny")] [TestClass()] public sealed class AllAndAnyTest { [TestMethod("All On Empty")] public async Task AllEmpty() { bool actual = await (Array.Empty<int>() .ToChannelReader() .All(x => true)); Assert.IsTrue(actual); } [TestMethod("All Even in Array")] public async Task AllEven() { bool actual = await (new int[] { 2, 124, 8 } .ToChannelReader() .All(x => x % 2 == 0)); Assert.IsTrue(actual); } [TestMethod("Not All Even in Array")] public async Task AllNotEven() { bool actual = await (new int[] { 2, 124, 7, 8 } .ToChannelReader() .All(x => x % 2 == 0)); Assert.IsFalse(actual); } [TestMethod("Any On Empty")] public async Task AnyEmpty() { bool actual = await (Array.Empty<int>() .ToChannelReader() .Any()); Assert.IsFalse(actual); } [TestMethod("Not Any Even on Array")] public async Task NotAnyEven() { bool actual = await (new int[] { 3, 5, 137, 9 } .ToChannelReader() .Any(x => x % 2 == 0)); Assert.IsFalse(actual); } [TestMethod("Any Even on Array")] public async Task AnyEven() { bool actual = await (new int[] { 3, 5, 12, 137, 9 } .ToChannelReader() .Any(x => x % 2 == 0)); Assert.IsTrue(actual); } [TestMethod("Default on Empty")] public async Task Empty() { int[] data = Array.Empty<int>(); int[] result = await data .ToChannelReader() .DefaultIfEmpty(77) .ToArrayAsync(); Assert.IsTrue(result.Length == 1 && result[0] == 77); } [TestMethod("Default on Not Empty")] public async Task NotEmpty() { int[] data = new int[] { 88, 93 }; int[] result = await data .ToChannelReader() .DefaultIfEmpty(77) .ToArrayAsync(); Assert.IsTrue(result.Length == data.Length && result.SequenceEqual(result)); } } }
using NUnit.Framework; namespace MarginTrading.AccountsManagement.IntegrationalTests.WorkflowTests { /// <summary> /// Runs before and after all tests in this namespace /// </summary> [SetUpFixture] public class Setup { [OneTimeSetUp] public void RunBeforeAnyTests() { // ... } [OneTimeTearDown] public void RunAfterAnyTests() { // ... } } }
 namespace Our.Umbraco.CacheRefresher.Tests.Common; public interface ITestCache<T> where T : class { T? GetValue(string key); Task<T?> GetValueAsync(string key); void SetValue(string key, T value); Task SetValueAsync(string key, T value); void Remove(string key); Task RemoveAsync(string key); } internal sealed class TestCache<T> : ITestCache<T> where T : class { private readonly IMemoryCache _memoryCache; private readonly Lazy<string> CACHE_PREFIX = new(() => typeof(T).GUID.ToString("N")); private string CacheKey(string key) => $"{CACHE_PREFIX.Value}_{key}"; public TestCache(IMemoryCache memoryCache) { _memoryCache = memoryCache; } public T? GetValue(string key) => _memoryCache.Get<T>(CacheKey(key)); public Task<T?> GetValueAsync(string key) => Task.FromResult<T?>(_memoryCache.Get<T>(CacheKey(key))); public void SetValue(string key, T value) => _memoryCache.Set(CacheKey(key), value); public Task SetValueAsync(string key, T value) { _memoryCache.Set(CacheKey(key), value); return Task.CompletedTask; } public void Remove(string key) => _memoryCache.Remove(CacheKey(key)); public Task RemoveAsync(string key) { _memoryCache.Remove(CacheKey(key)); return Task.CompletedTask; } }
namespace TOTPAuthenticationProvider.QRCodeGenerator { public enum QRMaskPattern : int { PATTERN000 = 0, PATTERN001 = 1, PATTERN010 = 2, PATTERN011 = 3, PATTERN100 = 4, PATTERN101 = 5, PATTERN110 = 6, PATTERN111 = 7 } }
using System; public class Jogador{ public int energia; public bool vivo; public Jogador(){ energia = 100; vivo = true; } } class Basinha{ static void Main(){ Jogador j1 = new Jogador(); Jogador j2 = new Jogador(); Jogador j3 = new Jogador(); Console.WriteLine("Energia do jogador 1: {0}",j1.energia); Console.WriteLine("Energia do jogador 2: {0}", j2.energia); Console.WriteLine("Energia do jogador 3: {0}", j3.energia); } }
using System; using Bytewizer.TinyCLR.Http.Features; using Bytewizer.TinyCLR.Http.WebSockets; namespace Bytewizer.TinyCLR.Http { /// <summary> /// Extension methods for <see cref="HttpContext"/> related to websockets. /// </summary> public static class HttpContextExtensions { /// <summary> /// Extension method for getting the <see cref="WebSocket"/> for the current request. /// </summary> /// <param name="context">The <see cref="HttpContext"/> context.</param> public static WebSocket GetWebSocket(this HttpContext context) { return GetWebSocket(context, null); } /// <summary> /// Extension method for getting the <see cref="WebSocket"/> for the current request. /// </summary> /// <param name="context">The <see cref="HttpContext"/> context.</param> public static WebSocket GetWebSocket(this HttpContext context, string[] subProtocols) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var endpointFeature = (HttpWebSocketFeature)context.Features.Get(typeof(IHttpWebSocketFeature)); return endpointFeature?.Accept(subProtocols); } } }
using System; using System.Threading.Tasks; using HttPlaceholder.Application.StubExecution.RequestStubGeneration.Implementations; using HttPlaceholder.Domain; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace HttPlaceholder.Application.Tests.StubExecution.RequestStubGeneration { [TestClass] public class MethodHandlerFacts { private readonly MethodHandler _handler = new MethodHandler(); [TestMethod] public async Task MethodHandler_HandleStubGenerationAsync_MethodNotSet_ShouldThrowInvalidOperationException() { // Arrange var request = new RequestResultModel { RequestParameters = new RequestParametersModel {Method = string.Empty} }; var stub = new StubModel(); // Act / Assert await Assert.ThrowsExceptionAsync<InvalidOperationException>(() => _handler.HandleStubGenerationAsync(request, stub)); } [TestMethod] public async Task MethodHandler_HandleStubGenerationAsync_HappyFlow() { // Arrange const string method = "GET"; var request = new RequestResultModel { RequestParameters = new RequestParametersModel {Method = method} }; var stub = new StubModel(); // Act var result = await _handler.HandleStubGenerationAsync(request, stub); // Assert Assert.IsTrue(result); Assert.AreEqual(method, stub.Conditions.Method); } } }
using System; using System.Collections.Generic; using parking365.domain; namespace parking365.dao.iface { public interface ClienteDao { List<Cliente> listar(string documento); Int64 insertar(Cliente usuario); bool actualizar(Cliente usuario); bool eliminar(Int64 idcliente,int idusuariocre); } }
using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using ProjetoT.Security.Domain.Entities.OAuth; namespace ProjetoT.Security.Infra.Data.Mappings { public class RateLimitMap : IEntityTypeConfiguration<RateLimit> { public void Configure(EntityTypeBuilder<RateLimit> builder) { #region Common mappings var tableSchema = typeof(RateLimit).Namespace.Split('.').Last().ToLower(); var tableName = typeof(RateLimit).Name; builder.ToTable(tableName, tableSchema); builder.HasKey(x => x.Id) .HasName($"PK_{tableSchema}_{tableName}_Id"); builder.Property(x => x.Id) .HasColumnName("Id"); #endregion Common mappings /* RWhen a Rate Limit is deleted, delete any Tokens that use this rate limit */ builder.HasOne(x => x.Token) .WithOne(x => x.RateLimit) .OnDelete(DeleteBehavior.Restrict); } } }
using System; namespace Majestics.Models.Post { public class PostViewModel { public int Id { get; set; } public string Data { get; set; } public string CreatorName { get; set; } public string LastChangedName { get; set; } public DateTime CreationTime { get; set; } } }
//------------------------------------------------------------------------------ // <copyright file="ZeroOpNode.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.Collections.Generic; using System.Diagnostics; internal sealed class ZeroOpNode : ExpressionNode { internal readonly int op; internal const int zop_True = 1; internal const int zop_False = 0; internal const int zop_Null = -1; internal ZeroOpNode(int op) : base((DataTable)null) { this.op = op; Debug.Assert(op == Operators.True || op == Operators.False || op == Operators.Null, "Invalid zero-op"); } internal override void Bind(DataTable table, List<DataColumn> list) { } internal override object Eval() { switch (op) { case Operators.True: return true; case Operators.False: return false; case Operators.Null: return DBNull.Value; default: Debug.Assert(op == Operators.True || op == Operators.False || op == Operators.Null, "Invalid zero-op"); return DBNull.Value; } } internal override object Eval(DataRow row, DataRowVersion version) { return Eval(); } internal override object Eval(int[] recordNos) { return Eval(); } internal override bool IsConstant() { return true; } internal override bool IsTableConstant() { return true; } internal override bool HasLocalAggregate() { return false; } internal override bool HasRemoteAggregate() { return false; } internal override ExpressionNode Optimize() { return this; } } }
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using RedBadger.Xpf; using RedBadger.Xpf.Adapters.Xna.Graphics; using RedBadger.Xpf.Controls; using RedBadger.Xpf.Media; using RedBadger.Xpf.Media.Imaging; namespace NekoCake.Crimson.Xpf { public class NinePatch : Grid { private ContentManager content; private SpriteFontAdapter font; private Canvas canvas; private IElement element; private bool isHeaderClicked, isReasizeClicked; public IElement Content { get { return this.element; } set { this.Children.Remove(element); this.element = value; Grid.SetColumn(element, 1); Grid.SetRow(element, 1); } } public NinePatch(ContentManager content, Canvas canvas, string name, SpriteFontAdapter font) { this.RowDefinitions.Add(new RowDefinition { Height = new GridLength(16)}); this.RowDefinitions.Add(new RowDefinition()); this.RowDefinitions.Add(new RowDefinition {Height = new GridLength(16)}); this.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(16)}); this.ColumnDefinitions.Add(new ColumnDefinition()); this.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(6)}); this.content = content; this.canvas = canvas; this.font = font; BuildNinePatch(name); } public void Update() { var mouse = Mouse.GetState(); if (isHeaderClicked) { Canvas.SetLeft(this, Canvas.GetLeft(this) + (mouse.X - oldMouse.X)); Canvas.SetTop(this, Canvas.GetTop(this) + (mouse.Y - oldMouse.Y)); } if (isReasizeClicked) { this.Width += (mouse.X - oldMouse.X); this.Height += (mouse.Y - oldMouse.Y); } if (isHeaderClicked || isReasizeClicked) { if (Canvas.GetLeft(this) < 0) { Canvas.SetLeft(this, 0); } if (Canvas.GetTop(this) < 0) { Canvas.SetTop(this, 0); } if (Canvas.GetLeft(this) + this.ActualWidth > canvas.RenderSize.Width) { Canvas.SetLeft(this, canvas.RenderSize.Width - this.Width); } if (Canvas.GetTop(this) + this.ActualHeight > canvas.RenderSize.Height) { Canvas.SetTop(this, canvas.RenderSize.Height - this.Height); } } if (mouse.RightButton == ButtonState.Pressed) { this.isHeaderClicked = this.isReasizeClicked = false; } oldMouse = mouse; } private MouseState oldMouse; private void BuildNinePatch(string name) { var c1 = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/c1"))), Stretch = Stretch.Fill }; Grid.SetColumn(c1, 0); Grid.SetRow(c1, 0); this.Children.Add(c1); var c2 = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/c2"))), Stretch = Stretch.Fill }; Grid.SetColumn(c2, 2); Grid.SetRow(c2, 0); this.Children.Add(c2); var c3 = new Button() { Content = new Grid() { } }; c3.Content = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/c3"))), Stretch = Stretch.Fill }; c3.Click += (sender, args) => { this.isReasizeClicked = !this.isReasizeClicked; }; Grid.SetColumn(c3, 2); Grid.SetRow(c3, 2); this.Children.Add(c3); var c4 = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/c4"))), Stretch = Stretch.Fill }; Grid.SetColumn(c4, 0); Grid.SetRow(c4, 2); this.Children.Add(c4); var e1 = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/e1"))), Stretch = Stretch.Fill }; Grid.SetColumn(e1, 0); Grid.SetRow(e1, 1); this.Children.Add(e1); var e2 = new Button() { Content = new Grid() {} }; ((Grid)e2.Content).Children.Add(new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/e2"))), Stretch = Stretch.Fill }); ((Grid)e2.Content).Children.Add(new TextBlock(font) { Text = "[" + name + "]", Foreground = new SolidColorBrush(Colors.White), Margin = new Thickness(0,2), HorizontalAlignment = HorizontalAlignment.Center }); e2.Click += (sender, args) => { this.isHeaderClicked = !this.isHeaderClicked; }; Grid.SetColumn(e2, 1); Grid.SetRow(e2, 0); this.Children.Add(e2); var e3 = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/e3"))), Stretch = Stretch.Fill }; Grid.SetColumn(e3, 2); Grid.SetRow(e3, 1); this.Children.Add(e3); var e4 = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/e4"))), Stretch = Stretch.Fill }; Grid.SetColumn(e4, 1); Grid.SetRow(e4, 2); this.Children.Add(e4); var m = new Image { Source = new TextureImage(new Texture2DAdapter(content.Load<Texture2D>(@"UI/m"))), Stretch = Stretch.Fill }; Grid.SetColumn(m, 1); Grid.SetRow(m, 1); this.Children.Add(m); } } }
using System; using System.Collections.Generic; namespace TT.Abp.Shops.Application.Dtos { public class ShopSyncRequestDto { public List<Guid> ShopIds { get; set; } } }
using System; using Microsoft.Win32; namespace Steam_Update_Creator { internal class RegReader { public static string ReadValue(string path, string name) { string result = string.Empty; try { using (var key = Registry.LocalMachine.OpenSubKey(path)) { if (key != null) { result = key.GetValue(name).ToString(); } } } catch (Exception e) { Console.WriteLine(e); } return result; } } }
using RimWorld; using System; using System.Collections.Generic; using Verse; namespace LAS { public class CompProperties_DoorLock : CompProperties { public float progressBarOffset = -0.5f - 0.12f; public List<ThingDef> defaultLocks = new List<ThingDef>(); public CompProperties_DoorLock() { compClass = typeof(DoorLockComp); } public CompProperties_DoorLock(Type compClass) : base(compClass) { } public override IEnumerable<StatDrawEntry> SpecialDisplayStats(StatRequest req) { if (req.HasThing) return null; return null; } } }
using Elan.Common.Contracts; namespace Elan.Common.Services { public class QueryValidationService: IQueryValidationService { public bool IsValidQuery(string query) { if (string.IsNullOrWhiteSpace(query)) { return false; } if (query.Length < 3) { return false; } return true; } } }
using System; namespace WebApiReferenceImpl.Core.Numerics { public sealed class RandomNumberGenerator { private static readonly object _lockObject = new object(); private static Random _random; private RandomNumberGenerator() { _random = new Random(); } public int GetRandomNumberBetween(int min, int max) { return _random.Next(min, max); } public static RandomNumberGenerator Instance { get { // Use nested class so its instantiated only once (slight performance gain over repeated lock) return Nested.instance; } set { lock (_lockObject) { Nested.instance = value; } } } private static class Nested { static Nested() { } internal static RandomNumberGenerator instance = new RandomNumberGenerator(); } } }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace UnitTest.Rollbar { internal static class RollbarUnitTestSettings { public const string AccessToken = "17965fa5041749b6bf7095a190001ded"; public const string Environment = "unit-tests"; public const string DeploymentsReadAccessToken = "8c2982e875544037b51870d558f51ed3"; } }
using Q42.HueApi.Models.Groups; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Q42.HueApi.Interfaces { public interface IHueClient_Groups { /// <summary> /// Send command to a group /// </summary> /// <param name="command"></param> /// <param name="group"></param> /// <returns></returns> Task<HueResults> SendGroupCommandAsync(ICommandBody command, string group = "0"); /// <summary> /// Create a group for a list of lights /// </summary> /// <param name="lights">List of lights in the group</param> /// <param name="name">Optional name</param> /// <param name="roomClass">for room creation the room class has to be passed, without class it will get the default: "Other" class.</param> /// <param name="groupType">GroupType</param> /// <returns></returns> Task<string?> CreateGroupAsync(IEnumerable<string> lights, string? name = null, RoomClass? roomClass = null, GroupType groupType = GroupType.Room); /// <summary> /// Deletes a single group /// </summary> /// <param name="groupId"></param> /// <returns></returns> Task<IReadOnlyCollection<DeleteDefaultHueResult>> DeleteGroupAsync(string groupId); /// <summary> /// Get all groups /// </summary> /// <returns></returns> Task<IReadOnlyCollection<Group>> GetGroupsAsync(); /// <summary> /// Get the state of a single group /// </summary> /// <param name="id"></param> /// <returns></returns> Task<Group?> GetGroupAsync(string id); /// <summary> /// Returns the entertainment group /// </summary> /// <returns></returns> Task<IReadOnlyList<Group>> GetEntertainmentGroups(); /// <summary> /// Update a group /// </summary> /// <param name="id">Group ID</param> /// <param name="lights">List of light IDs</param> /// <param name="name">Group Name (optional)</param> /// <param name="roomClass">for room creation the room class has to be passed, without class it will get the default: "Other" class.</param> /// <returns></returns> Task<HueResults> UpdateGroupAsync(string id, IEnumerable<string> lights, string? name = null, RoomClass? roomClass = null); Task<HueResults> UpdateGroupLocationsAsync(string id, Dictionary<string, LightLocation> locations); } }
using Sharpen; namespace android.app.@internal { [Sharpen.NakedStub] public abstract class AlertActivity { } }
using System; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using Sbz.Application.Common.Interfaces; namespace Sbz.Infrastructure.Services { public class EmailService : IEmailService { public bool SendEmail(string to, string subject, string body) { try { var settingEmail = new Setting() { Smtp = "domain.com", DisplayName = "Sajad Bagherzadeh", EmailAddress= "no-reply@domain.com", EmailPassword = "password", SmtpPort = 25,// 587 - 25; EnableSsl = false }; SmtpClient smtp = new SmtpClient(settingEmail.Smtp); MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress(settingEmail.EmailAddress, settingEmail.DisplayName); mailMessage.To.Add(to); mailMessage.Subject = subject; mailMessage.Body = body; mailMessage.IsBodyHtml = true; smtp.Port = settingEmail.SmtpPort; smtp.Credentials = new NetworkCredential(settingEmail.EmailAddress, settingEmail.EmailPassword); smtp.EnableSsl = settingEmail.EnableSsl; smtp.Send(mailMessage); return true; } catch (Exception e) { return false; } } private class Setting { public string Smtp { get; set; } public string EmailAddress { get; set; } public string DisplayName { get; set; } public int SmtpPort { get; set; } public string EmailPassword { get; set; } public bool EnableSsl { get; set; } } } }
using System; public class X { public static void HogeMethod(bool isFuga = false) { Console.WriteLine("a"); } public static void HogeMethod(params string[] fugas) { Console.WriteLine("b"); } }
using System.Xml.Linq; namespace DNTProfiler.Common.Controls.Highlighter { /// <summary> /// A line start definition and its RuleOptions. /// </summary> public class HighlightLineRule { public string LineStart { get; private set; } public RuleOptions Options { get; private set; } public HighlightLineRule(XElement rule) { LineStart = rule.Element("LineStart").Value.Trim(); Options = new RuleOptions(rule); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MessageBox : MonoBehaviour { public string[] Messages; private bool MouseDown; private void Update() { if (Input.GetMouseButtonDown(0)) MouseDown = true; } IEnumerator StartMessage() { AudioManager.Instance.PlaySound("Collect"); UIManager.Instance.ShowDialog(); GameManager.Instance.GameVideo(); PlayerManager.Instance.m_rb.velocity = Vector2.zero; yield return new WaitForSeconds(0.6f); StartCoroutine(Statics.Flash(GetComponentInChildren<SpriteRenderer>(), Color.white, Color.clear, 0.7f)); foreach (var item in Messages) { UIManager.Instance.ShowText(item); MouseDown = false; while (!MouseDown) yield return new WaitForEndOfFrame(); } //MouseDown = false; while (!MouseDown) yield return new WaitForEndOfFrame(); UIManager.Instance.HideDialogAndText(); GameManager.Instance.GameRestart(); GetComponentInChildren<Collider2D>().enabled = false; Destroy(gameObject); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "PlayerHeart") { StartCoroutine(StartMessage()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SimpleProcessorPipelines { public class CountOddNumbersCommand { public int? Result { get; private set; } public int ListLength { get; private set; } public List<int> List { get; private set; } public CountOddNumbersCommand(int numbers) { this.ListLength = numbers; } public void SetResult(int result) { this.Result = result; } public void SetList(List<int> list) { this.List = list; } } }
using System; using System.Data; using System.IO; using System.Text; using Caliburn.Micro; using JetBrains.Annotations; using JirkaDb.Views; using Syncfusion.Windows.Controls.Grid; using Syncfusion.Windows.Controls.Grid.Converter; using Syncfusion.XlsIO; namespace JirkaDb.ViewModels { public class GridViewModel : Screen { private GridControl m_grid; private readonly DataTable m_table; public GridViewModel([NotNull] DataTable table) { m_table = table ?? throw new ArgumentNullException(nameof(table)); } public DataTable Table => m_table; public void ExportToXls(string folder) { // TODO: Export více listů GetGrid().Model.ExportToExcel($"{folder}\\{m_table.TableName}.xlsx", ExcelVersion.Excel2016); } public void ExportToCsv(string folder) { CopyTextToBuffer(GetGrid().Model, out string buffer); File.WriteAllText($"{folder}\\{m_table.TableName}.csv", buffer); } protected override void OnViewLoaded(object view) { m_grid = ((GridView) view).GridControl; SetupGrid(m_grid); } private GridControl GetGrid() { if (m_grid != null) return m_grid; var result = new GridControl(); SetupGrid(result); return result; } private void SetupGrid(GridControl gridControl) { gridControl.QueryCellInfo += GridOnQueryCellInfo; gridControl.Model.RowCount = m_table.Rows.Count; gridControl.Model.ColumnCount = m_table.Columns.Count; gridControl.Model.InvalidateVisual(); } private void GridOnQueryCellInfo(object sender, GridQueryCellInfoEventArgs e) { e.Style.IsEditable = false; if (e.Cell.RowIndex == 0) { if (e.Cell.ColumnIndex == 0) { //e.Style.CellValue = m_table.TableName; return; } e.Style.CellValue = m_table.Columns[e.Cell.ColumnIndex - 1].ColumnName; return; } if (e.Cell.ColumnIndex == 0) { e.Style.CellValue = e.Cell.RowIndex; return; } e.Style.CellValue = m_table.Rows[e.Cell.RowIndex - 1][e.Cell.ColumnIndex - 1]; } /// <summary> /// Převzato od Syncfusionů, abych mohl změnit str1 a přidat názvy sloupců. /// </summary> /// <param name="gridModel"></param> /// <param name="buffer"></param> /// <returns></returns> private bool CopyTextToBuffer(GridModel gridModel, out string buffer) { StringBuilder stringBuilder = new StringBuilder(); string str1 = ";"; for (int top = 0; top <= gridModel.RowCount; ++top) { bool flag = true; for (int left = 0; left <= gridModel.ColumnCount; ++left) { if (!flag) stringBuilder.Append(str1); GridStyleInfo gridStyleInfo = gridModel[top, left]; string str2 = new StringBuilder(gridStyleInfo.GetFormattedText(gridStyleInfo.CellValue, 1)) .Replace(Environment.NewLine, " ").Replace("\r", " ").Replace("\n", " ").ToString().Trim(); stringBuilder.Append("\"" + str2 + "\""); flag = false; } stringBuilder.Append(Environment.NewLine); } buffer = stringBuilder.ToString(); return true; } } }
using System.Threading.Tasks; using Excalibur.Cross.Business; namespace Excalibur.Tests.Encrypted.Cross.Core.Business.Interfaces { public interface ILoggedInUser : ISingleBusiness<Domain.LoggedInUser> { void StoreForSaveAfterPin(Domain.LoggedInUser user); Task Store(); } }
using System.IO; using System.Threading.Tasks; namespace B2Emulator.Services { /// <summary> /// A service that facilitates storage and retrieval of file binary data. /// </summary> public interface IFileStorageProvider { Task<Dtos.File> RetrieveFileAsync(string fileId); Task<bool> StoreFileAsync(Dtos.File file); } }
#nullable enable using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.Metadata.Ecma335; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Uno.Extensions; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Uno.UI.SourceGenerators.XamlGenerator.Utils { internal static partial class XBindExpressionParser { private const string XBindSubstitute = "↔↔"; private static readonly Regex NamedParam = new Regex(@"^(\w*)=(.*?)"); /// <summary> /// Rewrites all x:Bind expression Path property to be compatible with the System.Xaml parser. /// </summary> /// <param name="markup">The original markup</param> /// <returns>The adjusted markup</returns> /// <remarks> /// The System.Xaml parser does not support having extended expressions, with /// quotes or commads inside an unquoted property value. The point of this method is /// to encode the whole Path property as Base64 to that its content does not interfere /// with the default rules of the parser. The expression is then restored using <see cref="RestoreSinglePath"/>. /// </remarks> internal static string RewriteDocumentPaths(string markup) { var result = Regex.Replace( markup, "\"{x:Bind\\s(.*?)}\"", e => $"\"{{x:Bind {RewriteParameters(e.Groups[1].Value.Trim())}}}\"", RegexOptions.Singleline ); return result; } /// <summary> /// Restores an x:Bind path encoded with <see cref="RewriteDocumentPaths"/>. /// </summary> internal static string? RestoreSinglePath(string? path) { if (!string.IsNullOrEmpty(path)) { var bytes = Convert.FromBase64String(path!.Replace("_", "=")); var rawPath = Encoding.Unicode.GetString(bytes); return rawPath .Replace('\'', '\"') .Replace(XBindExpressionParser.XBindSubstitute, "\\\'"); } return path; } private static string RewriteParameters(string value) { var parts = value.Split(',').SelectToArray(v => v.Replace("^'" , XBindSubstitute)); if (parts.Length != 0) { if (NamedParam.Match(parts[0]).Success) { // No unnamed parameter at first position, look for named Path parameter var pathIndex = parts.IndexOf( "Path", (s, item) => item.Split('=').FirstOrDefault()?.Trim().Contains(s) ?? false); if (pathIndex != -1) { var adjustedParts = parts.Select(p => p.Trim().TrimStart("Path=")).ToArray(); GetEncodedPath(adjustedParts, pathIndex, out var endIndex, out var encodedPath); var finalParts = adjustedParts .Take(pathIndex) .Concat("Path=" + encodedPath) .Concat(parts.Skip(endIndex)); return string.Join(",", finalParts); } else { return value; } } else { // First parameter is unnamed, it's the path. GetEncodedPath(parts, 0, out var endIndex, out var encodedPath); var remainder = string.Join(",", parts.Skip(endIndex)) switch { var r when r.Length > 0 => "," + r, _ => "" }; return encodedPath + remainder; } } else { return value; } } private static void GetEncodedPath(string[] parts, int startIndex, out int end, out string encodedPath) { end = GetFunctionRange(parts, startIndex) + 1; var sourceString = string.Join(",", parts.Skip(startIndex).Take(end)); var pathBytes = Encoding.Unicode.GetBytes(sourceString); encodedPath = Convert.ToBase64String(pathBytes).Replace("=", "_"); } private static int GetFunctionRange(string[] parts, int startIndex) { var parenthesisCount = 0; int i = startIndex; for (; i < parts.Length; i++) { parenthesisCount += parts[i].Count(c => c == '('); parenthesisCount -= parts[i].Count(c => c == ')'); if(parenthesisCount == 0) { break; } } return i; } } }
using UnityEngine; [CreateAssetMenu(menuName = "Weapons/Info/Range Weapon (Raycast)", fileName = "Range Raycast Weapon")] public class RangeRaycastWeaponInfoAsset : RangeWeaponInfoAsset { public float damage; public GameObject hitEffectPrefab; public float hitEffectDuration; }
using System; using System.Collections.Generic; using System.Dynamic; using System.Text; using Newtonsoft.Json.Linq; using WorkflowCore.Models; namespace Conductor.Domain.Models { public class Step { public string StepType { get; set; } public string Id { get; set; } public string Name { get; set; } public string CancelCondition { get; set; } public bool ProceedOnCancel { get; set; } = false; public WorkflowErrorHandling? ErrorBehavior { get; set; } public TimeSpan? RetryInterval { get; set; } public List<List<Step>> Do { get; set; } = new List<List<Step>>(); public List<Step> CompensateWith { get; set; } = new List<Step>(); public bool Saga { get; set; } = false; public string NextStepId { get; set; } public ExpandoObject Inputs { get; set; } = new ExpandoObject(); public Dictionary<string, string> Outputs { get; set; } = new Dictionary<string, string>(); public Dictionary<string, string> SelectNextStep { get; set; } = new Dictionary<string, string>(); } }