content
stringlengths
23
1.05M
//============================================================================= // Copyright Matthew King. All rights reserved. //============================================================================= using System; using System.IO; using System.Linq; using System.Text; using Tekly.Webster.Utility; namespace Tekly.Webster.Routes.Disk { public class DirectoryResponse : IToJson { public string PersistentDataPath; public DirectorySummary Directory; public void ToJson(StringBuilder sb) { sb.Append("{"); sb.Write("PersistentDataPath", PersistentDataPath, true); sb.Write("Directory", Directory, false); sb.Append("}"); } } public class DiskEntry { public string Name; public string Path; public string Type; } public class DirectorySummary : DiskEntry, IToJson { public DirectorySummary[] Directories; public FileSummary[] Files; public DirectorySummary() { Type = "Directory"; } public void ToJson(StringBuilder sb) { sb.Append("{"); sb.Write("Name", Name, true); sb.Write("Path", Path, true); sb.Write("Directories", Directories, true); sb.Write("Files", Files, true); sb.Write("Type", Type, false); sb.Append("}"); } } public class FileSummary : DiskEntry, IToJson { public DateTime CreationTime; public DateTime LastWriteTime; public long Size; public FileSummary() { Type = "File"; } public void ToJson(StringBuilder sb) { sb.Append("{"); sb.Write("Name", Name, true); sb.Write("Path", Path, true); sb.Write("Size", Size, true); sb.Write("CreationTime", CreationTime, true); sb.Write("LastWriteTime", LastWriteTime, true); sb.Write("Type", Type, false); sb.Append("}"); } } public static class DirectorySummarizer { public static DirectorySummary Summarize(string path, string rootDirectory) { var di = new DirectoryInfo(path); return Summarize(di, rootDirectory); } public static DirectorySummary Summarize(DirectoryInfo directoryInfo, string rootDirectory) { var directorySummary = new DirectorySummary(); directorySummary.Name = directoryInfo.Name; directorySummary.Path = directoryInfo.FullName.Replace("\\", "/").Replace(rootDirectory, ""); var directoryInfos = directoryInfo.GetDirectories("*", SearchOption.TopDirectoryOnly); directorySummary.Directories = directoryInfos.Select(x => Summarize(x, rootDirectory)).ToArray(); var fileInfos = directoryInfo.GetFiles("*", SearchOption.TopDirectoryOnly); directorySummary.Files = fileInfos.Select(fi => { var path = fi.FullName.Replace("\\", "/").Replace(rootDirectory, ""); return new FileSummary { Name = fi.Name, Size = fi.Length, CreationTime = fi.CreationTime, LastWriteTime = fi.LastWriteTime, Path = path }; }).ToArray(); return directorySummary; } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using GcpBlog.Application.Dtos; using GcpBlog.Application.Handlers.Command; using GcpBlog.Application.Handlers.Query; using GcpBlog.Application.Requests; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal; namespace GcpBlog.Api.Controllers { [Route("[controller]")] public class PostController : Controller { private readonly IMediator _mediator; public PostController(IMediator mediator) { _mediator = mediator; } [HttpGet] public async Task<ActionResult<List<PostDto>>> Index() { var response = await _mediator.Send(new GetPosts.Query(), CancellationToken.None); return Ok(response); } [Route("{slug}")] [HttpGet] public async Task<ActionResult<List<PostDto>>> GetPost(string slug) { var response = await _mediator.Send(new GetPost.Query(slug), CancellationToken.None); return Ok(response); } [HttpPost] public async Task<ActionResult<PostDto>> CreatePost([FromBody] CreatePostRequest postDto) { await _mediator.Send(new CreatePost.Command(postDto), CancellationToken.None); return Ok(); } [Route("{slug}")] [HttpDelete] public async Task<ActionResult> DeletePost(string slug) { await _mediator.Send(new DeletePost.Command(slug), CancellationToken.None); return Ok(); } } }
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2016 Dominik Reichl <dominik.reichl@t-online.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using KeePass.Forms; using KeePass.Resources; using KeePass.UI; using KeePass.Util; using KeePassLib; using KeePassLib.Interfaces; using KeePassLib.Resources; using KeePassLib.Security; using KeePassLib.Utility; namespace KeePass.DataExchange.Formats { // Originally written on 2007-03-28, updated on 2012-04-15 internal sealed class Spamex20070328 : FileFormatProvider { public override bool SupportsImport { get { return true; } } public override bool SupportsExport { get { return false; } } public override string FormatName { get { return "Spamex.com"; } } public override string ApplicationGroup { get { return KPRes.WebSites; } } public override bool ImportAppendsToRootGroupOnly { get { return true; } } public override bool RequiresFile { get { return false; } } public override Image SmallIcon { get { return KeePass.Properties.Resources.B16x16_WWW; } } private const string UrlDomain = "www.spamex.com"; private const string UrlBase = "https://www.spamex.com"; private const string UrlLoginPage = "https://www.spamex.com/tool/"; private const string UrlIndexPage = "https://www.spamex.com/tool/listaliases.cfm"; private const string UrlIndexAliasLink = "<a href=\"/tool/aliasinfo.cfm?v="; private const string UrlAccountPage = "https://www.spamex.com/tool/aliasinfo.cfm?v="; private const string StrTabLinksStart = "<A HREF=\""; private const string StrTabLinksEnd = "\" class=sheadLink>"; private const string StrTabLinkUrl = "/tool/listaliases.cfm"; public override void Import(PwDatabase pwStorage, Stream sInput, IStatusLogger slLogger) { slLogger.SetText("> Spamex.com...", LogStatusType.Info); SingleLineEditForm dlgUser = new SingleLineEditForm(); dlgUser.InitEx("Spamex.com", KPRes.WebSiteLogin + " - " + KPRes.UserName, KPRes.UserNamePrompt, KeePass.Properties.Resources.B48x48_WWW, string.Empty, null); if(UIUtil.ShowDialogNotValue(dlgUser, DialogResult.OK)) return; string strUser = dlgUser.ResultString; UIUtil.DestroyForm(dlgUser); SingleLineEditForm dlgPassword = new SingleLineEditForm(); dlgPassword.InitEx("Spamex.com", KPRes.WebSiteLogin + " - " + KPRes.Password, KPRes.PasswordPrompt, KeePass.Properties.Resources.B48x48_WWW, string.Empty, null); if(UIUtil.ShowDialogNotValue(dlgPassword, DialogResult.OK)) return; string strPassword = dlgPassword.ResultString; UIUtil.DestroyForm(dlgPassword); RemoteCertificateValidationCallback pPrevCertCb = ServicePointManager.ServerCertificateValidationCallback; ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; try { slLogger.SetText(KPRes.ImportingStatusMsg, LogStatusType.Info); string strPostData = @"toollogin=&MetaDomain=&LoginEmail=" + strUser + @"&LoginPassword=" + strPassword + @"&Remember=1"; List<KeyValuePair<string, string>> vCookies; string strMain = NetUtil.WebPageLogin(new Uri(UrlLoginPage), strPostData, out vCookies); if(strMain.IndexOf("Welcome <b>" + strUser + "</b>") < 0) { MessageService.ShowWarning(KPRes.InvalidUserPassword); return; } string strIndexPage = NetUtil.WebPageGetWithCookies(new Uri(UrlIndexPage), vCookies, UrlDomain); ImportIndex(pwStorage, strIndexPage, vCookies, slLogger); int nOffset = 0; List<string> vSubPages = new List<string>(); while(true) { string strLink = StrUtil.GetStringBetween(strIndexPage, nOffset, StrTabLinksStart, StrTabLinksEnd, out nOffset); ++nOffset; if(strLink.Length == 0) break; if(!strLink.StartsWith(StrTabLinkUrl)) continue; if(vSubPages.IndexOf(strLink) >= 0) continue; vSubPages.Add(strLink); string strSubPage = NetUtil.WebPageGetWithCookies(new Uri( UrlBase + strLink), vCookies, UrlDomain); ImportIndex(pwStorage, strSubPage, vCookies, slLogger); } } finally { ServicePointManager.ServerCertificateValidationCallback = pPrevCertCb; } } private static void ImportIndex(PwDatabase pwStorage, string strIndexPage, List<KeyValuePair<string, string>> vCookies, IStatusLogger slf) { int nOffset = 0; while(true) { int nStart = strIndexPage.IndexOf(UrlIndexAliasLink, nOffset); if(nStart < 0) break; nStart += UrlIndexAliasLink.Length; StringBuilder sbCode = new StringBuilder(); while(true) { if(strIndexPage[nStart] == '\"') break; sbCode.Append(strIndexPage[nStart]); ++nStart; } ImportAccount(pwStorage, sbCode.ToString(), vCookies, slf); nOffset = nStart + 1; } } private static void ImportAccount(PwDatabase pwStorage, string strID, List<KeyValuePair<string, string>> vCookies, IStatusLogger slf) { string strPage = NetUtil.WebPageGetWithCookies(new Uri( UrlAccountPage + strID), vCookies, UrlDomain); PwEntry pe = new PwEntry(true, true); pwStorage.RootGroup.AddEntry(pe, true); string str; string strTitle = StrUtil.GetStringBetween(strPage, 0, "Subject : <b>", "</b>"); if(strTitle.StartsWith("<b>")) strTitle = strTitle.Substring(3, strTitle.Length - 3); pe.Strings.Set(PwDefs.TitleField, new ProtectedString( pwStorage.MemoryProtection.ProtectTitle, strTitle)); string strUser = StrUtil.GetStringBetween(strPage, 0, "Site Username : <b>", "</b>"); if(strUser.StartsWith("<b>")) strUser = strUser.Substring(3, strUser.Length - 3); pe.Strings.Set(PwDefs.UserNameField, new ProtectedString( pwStorage.MemoryProtection.ProtectUserName, strUser)); str = StrUtil.GetStringBetween(strPage, 0, "Site Password : <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set(PwDefs.PasswordField, new ProtectedString( pwStorage.MemoryProtection.ProtectPassword, str)); str = StrUtil.GetStringBetween(strPage, 0, "Site Domain : <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set(PwDefs.UrlField, new ProtectedString( pwStorage.MemoryProtection.ProtectUrl, str)); str = StrUtil.GetStringBetween(strPage, 0, "Notes : <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set(PwDefs.NotesField, new ProtectedString( pwStorage.MemoryProtection.ProtectNotes, str)); str = StrUtil.GetStringBetween(strPage, 0, "Address:&nbsp;</td><td><font class=\"midHD\">", "</font></td>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set("Address", new ProtectedString(false, str)); str = StrUtil.GetStringBetween(strPage, 0, "Forwards to: <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set("Forward To", new ProtectedString(false, str)); str = StrUtil.GetStringBetween(strPage, 0, "Reply-To Messages: <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set("Reply-To Messages", new ProtectedString(false, str)); str = StrUtil.GetStringBetween(strPage, 0, "Allow Reply From: <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set("Allow Reply From", new ProtectedString(false, str)); str = StrUtil.GetStringBetween(strPage, 0, "Filter Mode: <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set("Filter Mode", new ProtectedString(false, str)); str = StrUtil.GetStringBetween(strPage, 0, "Created: <b>", "</b>"); if(str.StartsWith("<b>")) str = str.Substring(3, str.Length - 3); pe.Strings.Set("Created", new ProtectedString(false, str)); slf.SetText(strTitle + " - " + strUser + " (" + strID + ")", LogStatusType.Info); if(!slf.ContinueWork()) throw new InvalidOperationException(string.Empty); } } }
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Sitko.Core.Storage.Metadata; namespace Sitko.Core.Storage.Cache { public class InMemoryStorageCache<TStorageOptions> : BaseStorageCache<TStorageOptions, InMemoryStorageCacheOptions, InMemoryStorageCacheRecord> where TStorageOptions : StorageOptions { public InMemoryStorageCache(IOptionsMonitor<InMemoryStorageCacheOptions> options, ILogger<InMemoryStorageCache<TStorageOptions>> logger) : base( options, logger) { } protected override void DisposeItem(InMemoryStorageCacheRecord deletedRecord) { } internal override async Task<InMemoryStorageCacheRecord> GetEntryAsync(StorageItemDownloadInfo item, Stream stream, CancellationToken cancellationToken = default) { await using var memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream, cancellationToken); return new InMemoryStorageCacheRecord(item.Metadata, item.FileSize, item.Date, memoryStream.ToArray()); } public override ValueTask DisposeAsync() => new(); } public class InMemoryStorageCacheOptions : StorageCacheOptions { } public class InMemoryStorageCacheRecord : IStorageCacheRecord { private byte[] Data { get; } public StorageItemMetadata? Metadata { get; } public long FileSize { get; } public DateTimeOffset Date { get; } public InMemoryStorageCacheRecord(StorageItemMetadata? metadata, long fileSize, DateTimeOffset date, byte[] data) { Metadata = metadata; FileSize = fileSize; Data = data; Date = date; } public Stream OpenRead() => new MemoryStream(Data); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Rocket_Elevators_Foundation_API.Models; namespace Rocket_Elevators_Foundation_API.Controllers { [Route("api/[controller]")] [ApiController] public class ColumnsController : ControllerBase { private readonly MySqlConnectionContext _context; public ColumnsController(MySqlConnectionContext context) { _context = context; } // GET: api/Columns [HttpGet] public async Task<ActionResult<IEnumerable<Column>>> GetColumn() { return await _context.columns.ToListAsync(); } // GET: api/Columns/5 [HttpGet("{id}")] public async Task<ActionResult<Column>> GetColumn(long id) { var column = await _context.columns.FindAsync(id); if (column == null) { return NotFound(); } return column; } // PUT: api/Columns/5 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPut("{id}")] public async Task<IActionResult> ChangeColumnStatus(long id) { var columns = await _context.columns.FindAsync(id); if (columns == null) { return NotFound(); } if (columns.status == "active") { columns.status = "offline"; _context.columns.Update(columns); } else if (columns.status == "offline") { columns.status = "active"; _context.columns.Update(columns); } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ColumnExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Columns // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPost] public async Task<ActionResult<Column>> PostColumn(Column column) { _context.columns.Add(column); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetColumn), new { id = column.id }, column); } // DELETE: api/Columns/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteColumn(long id) { var column = await _context.columns.FindAsync(id); if (column == null) { return NotFound(); } _context.columns.Remove(column); await _context.SaveChangesAsync(); return NoContent(); } private bool ColumnExists(long id) { return _context.columns.Any(e => e.id == id); } } }
namespace EA.Iws.Requests.NotificationMovements { public enum MovementNumberStatus { Valid, OutOfRange, NotNew, DoesNotExist } }
using MailKit.Net.Smtp; using MimeKit; using SistemaCenagas.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SistemaCenagas { public static class ServicioEmail { public static string EMAIL_ADDRESS { get; set; } public static string EMAIL_PASSWORD { get; set; } public static string EMAIL_SERVER { get; set; } public static string SendEmailResetPassword(Usuarios user, string action, string subject, string bodyText) { string url = $"{EMAIL_SERVER}/Home/{action}?email={user.Email}"; string emailText = bodyText + $"<a href='{url}'>Clic aquí</a>"; string fromAddress = EMAIL_ADDRESS; string password = EMAIL_PASSWORD; string toAddress = user.Email; try { using (var client = new SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("smtp.gmail.com", 465, MailKit.Security.SecureSocketOptions.Auto); client.Authenticate(fromAddress, password); var body = new BodyBuilder { HtmlBody = emailText//$"<p>Body test</p>", //TextBody = emailText }; var message = new MimeMessage { Body = body.ToMessageBody() }; message.From.Add(new MailboxAddress("Administración de CENAGAS", fromAddress)); message.To.Add(new MailboxAddress("", toAddress)); message.Subject = subject; client.Send(message); client.Disconnect(true); } return "Envio exitoso! :)"; } catch (Exception e) { return e.Message; } } public static string SendEmailNotification(Usuarios user, string subject, string bodyText) { string fromAddress = EMAIL_ADDRESS; string password = EMAIL_PASSWORD; string toAddress = user.Email; try { using (var client = new SmtpClient()) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("smtp.gmail.com", 465, MailKit.Security.SecureSocketOptions.Auto); client.Authenticate(fromAddress, password); var body = new BodyBuilder { HtmlBody = bodyText//$"<p>Body test</p>", //TextBody = emailText }; var message = new MimeMessage { Body = body.ToMessageBody() }; message.From.Add(new MailboxAddress("Administración de CENAGAS", fromAddress)); message.To.Add(new MailboxAddress("", toAddress)); message.Subject = subject; client.Send(message); client.Disconnect(true); } return "Envio exitoso! :)"; } catch (Exception e) { return e.Message; } } } }
using System.Collections.Generic; using System.Management.Automation; using System.Xml; using Sitecore.Configuration; using Sitecore.Data.Items; using Spe.Commands.Interactive.Messages; using Spe.Core.Validation; namespace Spe.Commands.Interactive { [Cmdlet(VerbsLifecycle.Invoke, "ShellCommand")] [OutputType(typeof (Item))] public class InvokeShellCommandCommand : BaseItemCommand { [Parameter(Position = 0, Mandatory = true)] [AutocompleteSet(nameof(CommandNames))] public string Name { get; set; } public static string[] CommandNames = GetAllCommands(); private static string[] GetAllCommands() { var commands = Factory.GetConfigNodes("commands/command"); var commandNames = new List<string>(); foreach (XmlElement command in commands) { try { commandNames.Add(command.Attributes["name"].Value); } catch { // not really relevant to report this problem here ... } } return commandNames.ToArray(); } protected override void ProcessItem(Item item) { LogErrors(() => { if (CheckSessionCanDoInteractiveAction()) { PutMessage(new ShellCommandInItemContextMessage(item, Name)); if (item != null) { WriteItem(item); } } }); } } }
using System; using uTinyRipper.Classes.Misc; using uTinyRipper.Converters; using uTinyRipper.YAML; namespace uTinyRipper.Classes.AnimatorControllers { /// <summary> /// HumanLayerConstant in previous versions /// </summary> public struct LayerConstant : IAssetReadable, IYAMLExportable { /// <summary> /// 4.2.0 and greater /// </summary> public static bool HasDefaultWeight(Version version) => version.IsGreaterEqual(4, 2); /// <summary> /// 4.2.0 and greater /// </summary> public static bool HasSyncedLayerAffectsTiming(Version version) => version.IsGreaterEqual(4, 2); public void Read(AssetReader reader) { StateMachineIndex = (int)reader.ReadUInt32(); StateMachineMotionSetIndex = (int)reader.ReadUInt32(); BodyMask.Read(reader); SkeletonMask.Read(reader); Binding = reader.ReadUInt32(); LayerBlendingMode = (AnimatorLayerBlendingMode)reader.ReadInt32(); if (HasDefaultWeight(reader.Version)) { DefaultWeight = reader.ReadSingle(); } IKPass = reader.ReadBoolean(); if (HasSyncedLayerAffectsTiming(reader.Version)) { SyncedLayerAffectsTiming = reader.ReadBoolean(); } reader.AlignStream(); } public YAMLNode ExportYAML(IExportContainer container) { throw new NotSupportedException(); } public int StateMachineIndex { get; set; } public int StateMachineMotionSetIndex { get; set; } public uint Binding { get; set; } public AnimatorLayerBlendingMode LayerBlendingMode { get; set; } public float DefaultWeight { get; set; } public bool IKPass { get; set; } public bool SyncedLayerAffectsTiming { get; set; } public HumanPoseMask BodyMask; public OffsetPtr<SkeletonMask> SkeletonMask; } }
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Hub.Http { using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Text; public class MethodRequest { const int DeviceMethodDefaultResponseTimeoutInSeconds = 30; byte[] payloadBytes; public MethodRequest() { this.ResponseTimeoutInSeconds = DeviceMethodDefaultResponseTimeoutInSeconds; } [JsonProperty("methodName", Required = Required.Always)] public string MethodName { get; set; } [JsonProperty("payload")] public JRaw Payload { get; set; } [JsonProperty("responseTimeoutInSeconds")] internal int ResponseTimeoutInSeconds { get; set; } [JsonProperty("connectTimeoutInSeconds")] internal int ConnectTimeoutInSeconds { get; set; } [JsonIgnore] public TimeSpan ResponseTimeout => TimeSpan.FromSeconds(this.ResponseTimeoutInSeconds); [JsonIgnore] public TimeSpan ConnectTimeout => TimeSpan.FromSeconds(this.ConnectTimeoutInSeconds); [JsonIgnore] public byte[] PayloadBytes { get { if (this.payloadBytes == null && this.Payload != null) { // TODO - Should we allow only UTF8 or other encodings as well? Need to check what IoTHub does. this.payloadBytes = Encoding.UTF8.GetBytes((string)this.Payload); } return this.payloadBytes; } } } }
using System; using System.Collections.Generic; using System.Text; namespace Sensate.Views { public class RecognitionResults { public List<RecognitionResult> results { get; set; } = new List<RecognitionResult>(); } public class RecognitionResult { public string fname { get; set; } public string generalLabel { get; set; } public List<Result> results { get; set; } = new List<Result>(); } public class Result { public string desc { get; set; } public double score { get; set; } } }
using System.Threading.Tasks; using Abp.BackgroundJobs; using Shouldly; using Xunit; namespace Abp.Tests.BackgroundJobs { public class InMemoryBackgroundJobStore_Tests { private readonly InMemoryBackgroundJobStore _store; public InMemoryBackgroundJobStore_Tests() { _store = new InMemoryBackgroundJobStore(); } [Fact] public async Task Test_All() { var jobInfo = new BackgroundJobInfo { JobType = "TestType", JobArgs = "{}" }; await _store.InsertAsync(jobInfo); (await _store.GetWaitingJobsAsync(1000)).Count.ShouldBe(1); var jobInfoFromStore = await _store.GetAsync(1); jobInfoFromStore.ShouldNotBeNull(); jobInfoFromStore.JobType.ShouldBeSameAs(jobInfo.JobType); jobInfoFromStore.JobArgs.ShouldBeSameAs(jobInfo.JobArgs); await _store.DeleteAsync(jobInfo); (await _store.GetWaitingJobsAsync(1000)).Count.ShouldBe(0); } } }
// In Package Manager, run: // Install-Package Twilio.Mvc -DependencyVersion HighestMinor using System.Web.Mvc; using Twilio.Mvc; using Twilio.TwiML; using Twilio.TwiML.Mvc; public class MmsHelloMonkey : TwilioController { [HttpPost] public ActionResult Index(SmsRequest request) { var response = new TwilioResponse(); response.Message("Hello, Mobile Monkey", new [] { "https://demo.twilio.com/owl.png" }, null); return TwiML(response); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form; namespace Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.Demo.Pages.Components { public class FormElementsModel : PageModel { [BindProperty] public SampleModel MyModel { get; set; } public List<SelectListItem> CityList { get; set; } = new List<SelectListItem> { new SelectListItem { Value = "NY", Text = "New York"}, new SelectListItem { Value = "LDN", Text = "London"}, new SelectListItem { Value = "IST", Text = "Istanbul"}, new SelectListItem { Value = "MOS", Text = "Moscow"} }; public void OnGet() { MyModel = new SampleModel(); MyModel.SampleInput0 = "This is a disabled input."; MyModel.SampleInput1 = "This is a readonly input."; MyModel.CityRadio = "IST"; } public class SampleModel { public string Name { get; set; } public string SampleInput0 { get; set; } public string SampleInput1 { get; set; } public string SampleInput2 { get; set; } public string LargeInput { get; set; } public string SmallInput { get; set; } [TextArea] public string Description { get; set; } public string EmailAddress { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } public bool CheckMeOut { get; set; } public bool DefaultCheckbox { get; set; } public bool DisabledCheckbox { get; set; } public CarType CarType { get; set; } public string City { get; set; } [Display(Name="City")] public string CityRadio { get; set; } public List<string> Cities { get; set; } } public enum CarType { Sedan, Hatchback, StationWagon, Coupe } } }
using CompanyStores.DAL.Interfaces.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CompanyStores.DAL.Models; using CompanyStores.DAL.EntityFramework6.Infrastructure; using System.Data.Entity; namespace CompanyStores.DAL.EntityFramework6.Repositories { public class CompanyRepository : BaseRepository<Company, Guid>, ICompanyRepository { public CompanyRepository(CompanyStoresContext context) : base(context) { } public async Task<IList<Company>> GetByNameAsync(string name) { return await DbSet.Where(x => x.Name.Contains(name)).ToListAsync(); } } }
namespace Xeora.Web.Service.Context.Response { public class HttpResponseStatus : Basics.Context.Response.IHttpResponseStatus { private short _Code; public HttpResponseStatus() => this.Code = 200; public short Code { get => this._Code; set { this._Code = value; this.Message = HttpResponseStatusCodes.StatusCodes.GetMessage(this._Code); } } public string Message { get; private set; } } }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading.Tasks; using TodoApplication.Data; using TodoApplication.Models; using TodoApplication.Services; using TodoApplication.Utilities.Loggers; namespace TodoApplication.Controllers { public class TodoController : Controller { private readonly ITodoItemService _service; private readonly IKodluyoruzLogger _logger; public TodoController(ITodoItemService service, IKodluyoruzLogger logger) //constructor based dependency injection (constructor injection) { _service = service; _logger = logger; } [HttpGet] public async Task<IActionResult> Index() { IEnumerable<TodoItem> items = await _service.GetIncompleteItemsAsync(); // Gelen değerleri yeni modele koy TodoViewModel vm = new TodoViewModel {Items = items}; //design decision ViewBag.Title = "Yapılacaklar Listesini Yönet"; return View(vm); } [HttpPost] public async Task<IActionResult> AddItem(TodoItem newItem) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var result = await _service.AddItemAsync(newItem); if (!result) { return BadRequest(new {error = "Could not add item"}); } return Ok(); } [HttpPost] public async Task<IActionResult> MarkDone(Guid id) { if (id == Guid.Empty) return BadRequest(); var successfull = await _service.MarkDoneAsync(id); if (!successfull) return BadRequest(); return Ok(); } } }
using System; using System.Linq; using System.Text; namespace BrawlLib.Internal { public static class StringExtension { public static bool Contains(this string source, char value) { return source.IndexOf(value) >= 0; } public static bool Contains(this string source, char value, StringComparison comp) { return source.IndexOf(value.ToString(), comp) >= 0; } public static bool Contains(this string source, string value, StringComparison comp) { return source.IndexOf(value, comp) >= 0; } public static unsafe string TruncateAndFill(this string s, int length, char fillChar) { char* buffer = stackalloc char[length]; int i; int min = Math.Min(s.Length, length); for (i = 0; i < min; i++) { buffer[i] = s[i]; } while (i < length) { buffer[i++] = fillChar; } return new string(buffer, 0, length); } public static unsafe int IndexOfOccurance(this string s, char c, int index) { int len = s.Length; fixed (char* cPtr = s) { for (int i = 0, count = 0; i < len; i++) { if (cPtr[i] == c && count++ == index) { return i; } } } return -1; } //internal static Encoding encoder = Encoding.GetEncoding(932); public static unsafe void Write(this string s, sbyte* ptr) { //var b = encoder.GetBytes(s); for (int i = 0; i < s.Length; i++) { ptr[i] = (sbyte) s[i]; } } public static unsafe void Write(this string s, ref sbyte* ptr) { //var b = encoder.GetBytes(s); for (int i = 0; i < s.Length; i++) { *ptr++ = (sbyte) s[i]; } *ptr++ = 0; //Null terminator } public static unsafe string Read(this string s, byte* ptr) { //List<byte> vals = new List<byte>(); //byte val; //while ((val = *ptr++) != 0) // vals.Add(val); //return encoder.GetString(vals.ToArray()); return new string((sbyte*) ptr); } public static string ToBinaryArray(this string s) { //string value = ""; //for (int i = 0; i < s.Length; i++) //{ // byte c = (byte)s[i]; // for (int x = 0; x < 8; x++) // value += ((c >> (7 - x)) & 1); //} //return value; string result = string.Empty; foreach (char ch in s) { result += Convert.ToString(ch, 2); } return result.PadLeft(result.Length.Align(8), '0'); } public static int CompareBits(this string t1, string t2) { int bit = 0; bool found = false; int min = Math.Min(t1.Length, t2.Length); for (int i = 0; i < min; i++) { byte c1 = (byte) t1[i]; byte c2 = (byte) t2[i]; for (int x = 0; x < 8; x++) { if (c1 >> (7 - x) != c2 >> (7 - x)) { bit = i * 8 + x; found = true; break; } } if (bit != 0) { break; } } if (!found) { bit = min * 8 + 1; } return bit; } public static bool AtBit(this string s, int bitIndex) { int bit = bitIndex % 8; int byteIndex = (bitIndex - bit) / 8; return ((s[byteIndex] >> (7 - bit)) & 1) != 0; } public static string RemoveInvalidCharacters(this string s, string valid) { string m = ""; char[] t = s.ToCharArray().Where(x => valid.Contains(x)).ToArray(); foreach (char c in t) { m += c; } return m; } public static int UTF8Length(this string s) { return Encoding.UTF8.GetByteCount(s); } } }
using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Collector.AspnetCore.Proxy { public interface IProxyClient { Task<HttpResponseMessage> SendAsync(string uri, HttpRequest message, CancellationToken token = default); } }
using System.Collections.Generic; using System.IO; using DiscUtils.Streams.Util; namespace DiscUtils.Streams { /// <summary> /// Base class for streams that wrap another stream. /// </summary> /// <remarks> /// Provides the default implementation of methods &amp; properties, so /// wrapping streams need only override the methods they need to intercept. /// </remarks> public class WrappingStream : SparseStream { private readonly Ownership _ownership; private SparseStream _wrapped; public WrappingStream(SparseStream toWrap, Ownership ownership) { _wrapped = toWrap; _ownership = ownership; } public override bool CanRead => _wrapped.CanRead; public override bool CanSeek => _wrapped.CanSeek; public override bool CanWrite => _wrapped.CanWrite; public override IEnumerable<StreamExtent> Extents => _wrapped.Extents; public override long Length => _wrapped.Length; public override long Position { get => _wrapped.Position; set => _wrapped.Position = value; } public override void Flush() { _wrapped.Flush(); } public override int Read(byte[] buffer, int offset, int count) { return _wrapped.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return _wrapped.Seek(offset, origin); } public override void SetLength(long value) { _wrapped.SetLength(value); } public override void Clear(int count) { _wrapped.Clear(count); } public override void Write(byte[] buffer, int offset, int count) { _wrapped.Write(buffer, offset, count); } protected override void Dispose(bool disposing) { try { if (disposing) { if (_wrapped != null && _ownership == Ownership.Dispose) { _wrapped.Dispose(); } _wrapped = null; } } finally { base.Dispose(disposing); } } } }
using System.Collections.Generic; using Primus.Toolbox.Beacon; namespace PrimusSamples.BeaconEditor.Beacon { public class Red : BaseBeacon<TypeBcn> { private List<Green> _childrenGreen; protected override void Awake() { base.Awake(); BiblionTitle = TypeBcn.RED; _childrenGreen = new List<Green>(); } } }
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0.llvm { using System; using static core; public sealed class LlvmNm : ToolService<LlvmNm> { public override ToolId Id => LlvmToolNames.llvm_nm; public ReadOnlySpan<ObjSymRecord> Read(FS.FilePath path) { var result = Outcome.Success; var count = FS.linecount(path).Lines; var buffer = span<ObjSymRecord>(count); var counter = 0u; using var reader = path.Utf8LineReader(); while(reader.Next(out var line)) { if(parse(line, out var sym)) seek(buffer,counter++) = sym; } return slice(buffer, 0,counter); } static Outcome parse(TextLine src, out ObjSymRecord dst) { var result = Outcome.Success; var content = src.Content; dst = default; var j = text.index(content, Chars.Colon); if(j > 0) { var k = text.index(content, j + 1, Chars.Colon); if(k > 0) { dst.Source = FS.path(text.left(content,k)); var digits = text.slice(text.right(content,k),1,8).Trim(); var hex = Hex32.Max; if(nonempty(digits)) DataParser.parse(digits, out hex); dst.Offset = hex; var pos = k + 1 + 8 + 2; dst.Kind = content[pos]; dst.Name = text.right(content, pos + 1).Trim(); } } return result; } public ReadOnlySpan<ObjSymRecord> Collect(ReadOnlySpan<FS.FilePath> src, FS.FilePath outpath) { var result = Outcome.Success; var count = src.Length; var formatter = Tables.formatter<ObjSymRecord>(ObjSymRecord.RenderWidths); var buffer = list<ObjSymRecord>(); for(var i=0; i<count; i++) { ref readonly var path = ref skip(src,i); using var reader = path.Utf8LineReader(); while(reader.Next(out var line)) { if(parse(line, out var sym)) buffer.Add(sym); } } var records = buffer.ViewDeposited(); TableEmit(records, ObjSymRecord.RenderWidths, outpath); return records; } } }
namespace LpgExample.Ast { /** * is always implemented by <b>ASTNodeToken</b>. It is also implemented by: *<b> *<ul> *<li>name0 *<li>name1 *<li>name2 *<li>name3 *<li>name4 *<li>name5 *</ul> *</b> */ public interface Iname : IASTNodeToken {} }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AdaptiveCards.Test { [TestClass] public class AdaptiveSchemaVersionTests { [TestMethod] public void OperatorTests() { var v10 = new AdaptiveSchemaVersion(1, 0); var v11 = new AdaptiveSchemaVersion(1, 1); Assert.IsFalse(v10 == v11); Assert.IsFalse(v10.Equals(v11)); Assert.IsTrue(v11 > v10); Assert.IsTrue(v10 < v11); Assert.IsTrue(v11 >= v10); } [TestMethod] public void TestVersionParsing() { var json = @"{ ""type"": ""AdaptiveCard"", ""version"": ""1.2"" }"; var result = AdaptiveCard.FromJson(json); Assert.AreEqual(new AdaptiveSchemaVersion(1, 2), result.Card.Version); } [TestMethod] public void Test_InvalidVersionStringFailsParsing() { var json = @"{ ""type"": ""AdaptiveCard"", ""version"": ""invalid"", ""body"": [ { ""type"": ""TextBlock"", ""text"": ""Hello"" } ] }"; Assert.ThrowsException<AdaptiveSerializationException>(() => { AdaptiveCard.FromJson(json); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DNA { List<int> genes = new List<int>(); int DNALength = 0; int MaxValues = 0; /// <summary> /// Constructor for the class, sets basic values /// </summary> /// <param name="len"></param> /// <param name="val"></param> public DNA(int len, int val) { DNALength = len; MaxValues = val; SetRandom(); } /// <summary> /// Sets the gene sequence randomly based on <see cref="maxValues"/> and <see cref="DNALength"/> /// </summary> void SetRandom() { genes.Clear(); for (int i = 0; i < DNALength; i++) { genes.Add(Random.Range(0, MaxValues)); } } /// <summary> /// To hard code certain gene sequence if needed /// </summary> /// <param name="pos"></param> /// <param name="value"></param> public void SetInt(int pos, int val) { genes[pos] = val; } /// <summary> /// Splits the gene of the parent and combines them back together into a single DNA /// </summary> /// <param name="parent1"></param> /// <param name="parent2"></param> public void Combine(DNA parent1, DNA parent2) { for (int i = 0; i < DNALength; i++) { if (i < DNALength / 2) { int c = parent1.genes[i]; genes[i] = c; } else { int c = parent2.genes[i]; genes[i] = c; } } } /// <summary> /// Mutates/ changes the particular value of the gene sequence based on Random range /// from <see cref="maxValues"/> and <see cref="DNALength"/> /// </summary> public void Mutate() { genes[Random.Range(0, DNALength)] = Random.Range(0, MaxValues); } /// <summary> /// Gets the Gene at the position /// </summary> /// <param name="pos"></param> /// <returns></returns> public int GetGene(int pos) { return genes[pos]; } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WithoutHaste.Drawing.Colors; namespace WithoutHaste.Windows.GUI { internal class SaturationValuePanel : Panel { public const int UNIT = 101; private const int TRACKBAR_HEIGHT = 45; private TrackBar saturationTrackBar; private TrackBar valueTrackBar; private SaturationValueGradientPanel gradientPanel; public event EventHandler ColorChanged; public int Saturation { get { return saturationTrackBar.Value; } set { saturationTrackBar.Value = value; } } public int Value { get { return valueTrackBar.Value; } set { valueTrackBar.Value = value; } } public Color Color { set { HSV hsv = ConvertColors.ToHSV(value); Saturation = (int)(hsv.Saturation * 100); Value = (int)(hsv.Value * 100); } } private int hue; public int Hue { get { return hue; } set { hue = value; gradientPanel.Hue = hue; } } public SaturationValuePanel(Color? startColor = null) { int totalColorHeight = UNIT * 3; this.Height = TRACKBAR_HEIGHT + totalColorHeight; this.Width = TRACKBAR_HEIGHT + totalColorHeight; this.BorderStyle = BorderStyle.Fixed3D; saturationTrackBar = new TrackBar(); saturationTrackBar.Location = new Point(TRACKBAR_HEIGHT, 0); saturationTrackBar.Size = new Size(totalColorHeight, TRACKBAR_HEIGHT); saturationTrackBar.Minimum = 0; saturationTrackBar.Maximum = 100; saturationTrackBar.ValueChanged += new EventHandler(Saturation_OnValueChanged); this.Controls.Add(saturationTrackBar); valueTrackBar = new TrackBar(); valueTrackBar.Location = new Point(0, TRACKBAR_HEIGHT); valueTrackBar.Size = new Size(TRACKBAR_HEIGHT, totalColorHeight); valueTrackBar.Minimum = 0; valueTrackBar.Maximum = 100; valueTrackBar.Orientation = Orientation.Vertical; valueTrackBar.ValueChanged += new EventHandler(Value_OnValueChanged); this.Controls.Add(valueTrackBar); gradientPanel = new SaturationValueGradientPanel(totalColorHeight); gradientPanel.Location = new Point(TRACKBAR_HEIGHT, TRACKBAR_HEIGHT); gradientPanel.ColorChanged += new EventHandler(Gradient_OnColorChange); this.Controls.Add(gradientPanel); if(startColor.HasValue) { HSV hsv = ConvertColors.ToHSV(startColor.Value); Hue = (int)hsv.Hue; Saturation = (int)(hsv.Saturation * 100); Value = (int)(hsv.Value * 100); } } private void Gradient_OnColorChange(object sender, EventArgs e) { Saturation = gradientPanel.Saturation; Value = gradientPanel.Value; } private void Saturation_OnValueChanged(object sender, EventArgs e) { if(ColorChanged != null) { ColorChanged(this, new EventArgs()); } } private void Value_OnValueChanged(object sender, EventArgs e) { if(ColorChanged != null) { ColorChanged(this, new EventArgs()); } } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Media; using System.Media; using System.Timers; using System.Runtime.InteropServices; //using Un4seen.Bass; //using Un4seen.Bass.AddOn; //using Un4seen.Bass.AddOn.Tags; namespace Yuri.PlatformCore.Audio { /// <summary> /// <para>音乐管理器类:负责游戏所有声效的维护和处理</para> /// <para>她是一个单例类,只有唯一实例</para> /// </summary> internal class MusicianBass { /// <summary> /// 根据音频状态描述子重演绎前端的音频 /// </summary> /// <param name="mdescriptor">音频状态描述子</param> public void RePerform(MusicianDescriptor mdescriptor) { throw new NotSupportedException(); } /// <summary> /// <para>播放背景音乐:从文件读入资源</para> /// <para>背景音乐在同一时刻只能播放一个资源</para> /// </summary> /// <param name="resourceName">资源名</param> /// <param name="filename">文件路径</param> /// <param name="vol">音量(1-1000)</param> public void PlayBGM(string resourceName, string filename, float vol) { throw new NotSupportedException(); } /// <summary> /// <para>播放背景音乐:从内存读入资源</para> /// <para>背景音乐在同一时刻只能播放一个资源</para> /// </summary> /// <param name="resourceName">资源名</param> /// <param name="gch">托管的内存句柄</param> /// <param name="len">句柄指向内存长度</param> /// <param name="vol">音量(1-1000)</param> public void PlayBGM(string resourceName, GCHandle? gch, long len, float vol) { throw new NotSupportedException(); } /// <summary> /// 暂停背景音乐 /// </summary> public void PauseBGM() { throw new NotSupportedException(); } /// <summary> /// 继续播放背景音乐 /// </summary> public void ResumeBGM() { throw new NotSupportedException(); } /// <summary> /// 停止BGM并释放资源 /// </summary> public void StopAndReleaseBGM() { throw new NotSupportedException(); } /// <summary> /// <para>播放背景音效:从文件读入资源</para> /// <para>背景声效可以多个声音资源同时播放,并且可以与BGM同存</para> /// </summary> /// <param name="filename">文件路径</param> /// <param name="vol">音量(1-1000)</param> /// <param name="track">播放的轨道</param> public void PlayBGS(string filename, float vol, int track = 0) { throw new NotSupportedException(); } /// <summary> /// <para>播放背景音效:从内存读入资源</para> /// <para>背景声效可以多个声音资源同时播放,并且可以与BGM同存</para> /// </summary> /// <param name="gch">托管的内存句柄</param> /// <param name="len">句柄指向内存长度</param> /// <param name="vol">音量(1-1000)</param> /// <param name="track">播放的轨道</param> public void PlayBGS(GCHandle? gch, long len, float vol, int track = 0) { throw new NotSupportedException(); } /// <summary> /// 停止BGS并释放资源 /// </summary> /// <param name="track">要停止的BGS轨道,缺省值-1表示全部停止</param> public void StopBGS(int track = -1) { throw new NotSupportedException(); } /// <summary> /// 变更BGM的音量 /// </summary> /// <param name="vol"></param> public void SetBGMVolume(float vol) { throw new NotSupportedException(); } /// <summary> /// 变更指定轨道的BGS音量 /// </summary> /// <param name="vol">音量</param> /// <param name="track">轨道(-1为全部变更)</param> public void SetBGSVolume(int vol, int track = 0) { throw new NotSupportedException(); } /// <summary> /// 设置BGM声道 /// </summary> /// <param name="offset">声道偏移(-1到1,从左向右偏移,0为立体声)</param> public void SetBGMStereo(float offset) { throw new NotSupportedException(); } /// <summary> /// <para>播放声效:从文件读入资源</para> /// <para>声效可以多个声音资源同时播放</para> /// </summary> /// <param name="filename">文件路径</param> /// <param name="vol">音量(1-1000)</param> public void PlaySE(string filename, float vol) { throw new NotSupportedException(); } /// <summary> /// <para>播放声效:从内存读入资源</para> /// <para>声效可以多个声音资源同时播放</para> /// </summary> /// <param name="gch">托管的内存句柄</param> /// <param name="len">句柄指向内存长度</param> /// <param name="vol">音量(1-1000)</param> public void PlaySE(GCHandle? gch, long len, float vol) { throw new NotSupportedException(); } /// <summary> /// <para>播放语音:从文件读入资源</para> /// <para>语音在同一时刻只能播放一个资源,但可以与BGM和BGS共存</para> /// </summary> /// <param name="filename">文件路径</param> /// <param name="vol">音量(1-1000)</param> public void PlayVocal(string filename, float vol) { throw new NotSupportedException(); } /// <summary> /// <para>播放语音:从内存读入资源</para> /// <para>语音在同一时刻只能播放一个资源,但可以与BGM和BGS共存</para> /// </summary> /// <param name="gch">托管的内存句柄</param> /// <param name="len">句柄指向内存长度</param> /// <param name="vol">音量(1-1000)</param> public void PlayVocal(GCHandle? gch, long len, float vol) { throw new NotSupportedException(); } /// <summary> /// 停止语音并释放资源 /// </summary> public void StopAndReleaseVocal() { throw new NotSupportedException(); } /// <summary> /// 复位音乐管理器 /// </summary> public void Reset() { throw new NotSupportedException(); } /// <summary> /// 更新函数:消息循环定期调用的更新方法 /// </summary> private void musicianTimer_Elapsed(object sender, ElapsedEventArgs e) { throw new NotSupportedException(); } /// <summary> /// 工厂方法:获得音乐管理器类的唯一实例 /// </summary> /// <returns>音乐管理器</returns> public static MusicianBass GetInstance() { return synObject == null ? synObject = new MusicianBass() : synObject; } /// <summary> /// 获取或设置BGM音量 /// </summary> public float BGMVolume { get { return this.bgmVolume; } set { this.bgmVolume = Math.Max(0, Math.Min(value, 1000)); //this.BassEngine.SetVolume(this.BgmHandleContainer.Value, this.bgmVolume); } } /// <summary> /// 获取或设置BGS默认音量 /// </summary> public float BGSDefaultVolume { get { return this.bgsVolume; } set { this.bgsVolume = Math.Max(0, Math.Min(value, 1000)); } } /// <summary> /// 获取或设置SE默认音量 /// </summary> public float SEDefaultVolume { get { return this.seVolume; } set { this.seVolume = Math.Max(0, Math.Min(value, 1000)); } } /// <summary> /// 获取或设置Vocal默认音量 /// </summary> public float VocalDefaultVolume { get { return this.vocalVolume; } set { this.vocalVolume = Math.Max(0, Math.Min(value, 1000)); } } /// <summary> /// 获取BGM是否正在播放 /// </summary> public bool isBGMPlaying { get; private set; } /// <summary> /// 获取BGM是否已经加载 /// </summary> public bool isBGMLoaded { get; private set; } /// <summary> /// 获取BGM是否已经暂停 /// </summary> public bool isBGMPaused { get; private set; } /// <summary> /// 获取当前BGM名字 /// </summary> public string currentBGM { get { return this.BgmHandleContainer.Key; } } /// <summary> /// 获取是否有BGS在播放 /// </summary> public bool isAnyBGS { get { return this.BgsHandleContainer.TrueForAll((x) => x.Key == 0) == false; } } /// <summary> /// 获取或设置是否静音 /// </summary> public bool isMute { get; set; } /// <summary> /// 当前语音句柄 /// </summary> private int vocalHandle { get; set; } /// <summary> /// BGM音量值 /// </summary> private float bgmVolume = GlobalConfigContext.GAME_SOUND_BGMVOL; /// <summary> /// BGS音量值 /// </summary> private float bgsVolume = GlobalConfigContext.GAME_SOUND_BGSVOL; /// <summary> /// SE音量值 /// </summary> private float seVolume = GlobalConfigContext.GAME_SOUND_SEVOL; /// <summary> /// Vocal音量值 /// </summary> private float vocalVolume = GlobalConfigContext.GAME_SOUND_VOCALVOL; /// <summary> /// 唯一实例 /// </summary> private static MusicianBass synObject = null; /// <summary> /// BGM句柄容器 /// </summary> private KeyValuePair<string, int> BgmHandleContainer; /// <summary> /// 音乐管理器定时器 /// </summary> private Timer musicianTimer; /// <summary> /// 背景声效容器 /// </summary> private List<KeyValuePair<int, float>> BgsHandleContainer; /// <summary> /// 音频引擎实例 /// </summary> private BassPlayer BassEngine; /// <summary> /// 私有的构造器 /// </summary> private MusicianBass() { this.BassEngine = BassPlayer.GetInstance(); this.musicianTimer = new Timer(1000); this.musicianTimer.Elapsed += musicianTimer_Elapsed; this.BGSDefaultVolume = 800; this.bgmVolume = 800; this.VocalDefaultVolume = 1000; this.seVolume = 1000; this.Reset(); } } /// <summary> /// Bass播放器 /// </summary> internal class BassPlayer : IDisposable { public static BassPlayer GetInstance() { throw new NotSupportedException(); } public void Dispose() { throw new NotSupportedException(); } } }
using System; using System.Linq; using static System.Console; namespace Alphabet { class Program { static void Main(string[] args) { char[] alphabet = "qwertyuiopasdfghjklzxcvbnm".ToCharArray(); string[] input = { "aas", "aasta", "year", "jahr", "god" }; string[] inputCopy = input.ToArray(); SortByAlphabet(input, alphabet); WriteLine(alphabet); for (int i = 0; i < input.Length; i++) Write($"{inputCopy[i]}\t\t\t{input[i]}\n"); ReadKey(); } private static void SortByAlphabet(string[] input, char[] alphabet) { Array.Sort(input, (x, y) => { if (x.Length == 0 && y.Length == 0) return 0; // We dont sort empty strings. if (x.Length == 0) return -1; // Empty string is before non-empty string. if (y.Length == 0) return +1; // -.- for (int i = 0; i < x.Length; i++) { if (i > y.Length - 1) return +1; // Shorter string comes first. int a = Array.IndexOf(alphabet, x[i]); int b = Array.IndexOf(alphabet, y[i]); if (a < b) return -1; if (b < a) return +1; } if (x.Length == y.Length) return 0; // We dont sort equal strings. return -1; // Shorter string comes first. }); } } }
using System; using System.Collections.Generic; using Mersy.Common.Entities; using Mersy.Common.Models; namespace Mersy.Web.Models { public class PlayViewModel { public List<LotterySaleItemView> Items { get; set; } public LotterySale Sale { get; set; } public string Lottery { get; set; } public string Number { get; set; } public string Mode { get; set; } } }
using Simplicity.DataContracts.Dtos; using Simplicity.Entities; using Simplicity.Repositories.RepositoryInterfaces; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Simplicity.Repositories.Repositories { public class TicketsRepository : BaseRepository<Ticket>, ITicketsRepository { public TicketsRepository(SimplicityContext context) : base(context) { } public List<TaskDto> GetAllTaskDtos(Expression<Func<Ticket, bool>> filter) { var result = dbSet.Where(filter).Select(u => new TaskDto { ID = u.ID, Name = u.Name, Description = u.Description, Assignee = new NameAndIDDto { ID = u.AssigneeID, Name = u.Assignee.Name }, Creator = new NameAndIDDto { ID = u.CreatorID, Name = u.Creator.Name }, Project = new NameAndIDDto { ID = u.ProjectID, Name = u.Project.Name }, DueDate = u.DueDate, Status = u.Status, OldStatus = u.Status, IsExpiring = (u.DueDate - DateTime.Now).TotalDays < 4 && DateTime.Now < u.DueDate, IsExpired = DateTime.Now > u.DueDate }).ToList(); return result; } } }
using Backend.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Backend.DAL { public interface IExtrasDAL { EXTRA obtenerExtra(int id_extra); void agregarExtra(EXTRA extra); void actualizarExtra(EXTRA extra); void eliminarExtra(int id_extra); List<EXTRA> obtenerExtras(); } }
using System; using System.Collections.Generic; using System.Globalization; using DiscordSupportBot.Models.BaseModels; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /* { "Error": null, "Tickers": [ { "PairId": 422, "PairName": "BTC_IPS", "Last": 0.000004000000000, "LowPrice": 0.000002910000000, "HighPrice": 0.000011500000000, "PercentChange": -60.0400, "BaseVolume": 0.3147625627072927079200000000, "QuoteVolume": 36001.842157842158000, "VolumeInBtc": 0.3147625627072927079200000000, "VolumeInUsd": 2208.3720251439295531455135796 } ] } */ namespace DiscordSupportBot.Models.Exchanges.Crex { public partial class Crex { [JsonProperty("Error")] public object Error { get; set; } [JsonProperty("Tickers")] public Ticker[] Tickers { get; set; } } public class Ticker { [JsonProperty("PairId")] public int CrexPairId { get; set; } [JsonProperty("PairName")] public string CrexPairName { get; set; } [JsonProperty("Last")] public string CrexLast { get; set; } [JsonProperty("LowPrice")] public string CrexLowPrice { get; set; } [JsonProperty("HighPrice")] public string CrexHighPrice { get; set; } [JsonProperty("PercentChange")] public string CrexPercentChange { get; set; } [JsonProperty("BaseVolume")] public string CrexBaseVolume { get; set; } [JsonProperty("QuoteVolume")] public string CrexQuoteVolume { get; set; } [JsonProperty("VolumeInBtc")] public string CrexVolumeInBtc { get; set; } [JsonProperty("VolumeInUsd")] public string CrexVolumeInUsd { get; set; } } }
using JiemyuDll.Entities; using JiemyuDll.Entities.Jiemyu; using JiemyuDll.Map; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Jiemyu { class JiemyuAlphaInitializer { Dictionary<String, Texture2D> entityTextures = new Dictionary<String, Texture2D>(); /// <summary> /// Initial entity layout for the roughest version of Jiemyu /// </summary> /// <param name="name"></param> /// <param name="texture"></param> public void AddEntityTexture(String name, Texture2D texture) { entityTextures.Add(name, texture); } public List<Entity> InitializeJiemyuAlpha1Layout() { List<Entity> entityList = new List<Entity>(); //Soldier A, what a badass entityList.Add(GenerateEntity<SoldierA>(gridPoint(6,4), entityTextures["Tree"])); //Pansy C, the fastest pansy alive entityList.Add(GenerateEntity<PansyC>(gridPoint(7, 9), entityTextures["Princess"])); return entityList; } /// <summary> /// Initial teams for the roughest version of Jiemyu /// </summary> /// <returns></returns> public List<Team> InitializeJiemyuAlpha1Teams() { List<Team> teamList = new List<Team>(); //Team 1 (Top) Team top = new Team(); top.Name = "top"; top.Color = Color.Black; teamList.Add(top); //Team 2 (Bottom) Team bot = new Team(); bot.Name = "bottom"; bot.Color = Color.White; teamList.Add(bot); return teamList; } /// <summary> /// Generates the template entity with the given position and texture /// </summary> /// <typeparam name="T"></typeparam> /// <param name="position"></param> /// <param name="texture"></param> /// <returns></returns> private Entity GenerateEntity<T>(Point position, Texture2D texture) where T : Entity, new() { Entity entity = new T(); entity.EntityTexture = texture; entity.Position = position; return entity; } /// <summary> /// Takes in coordinates on the level grid and transforms them into a Point. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> private Point gridPoint(int x, int y){ int yPadding = 50, panelWidth = 96, panelHeight = 84; //0 Index for maths x--; y--; return new Point((x * panelWidth) + (panelWidth/2) , (y * panelHeight) + (panelHeight/2) + yPadding); } /// <summary> /// Loads all of the entity textures. /// </summary> /// <param name="Content"></param> public void LoadContent(Microsoft.Xna.Framework.Content.ContentManager Content) { AddEntityTexture("Cat Girl", Content.Load<Texture2D>("Character Cat Girl")); AddEntityTexture("Tree", Content.Load<Texture2D>("Tree Tall")); AddEntityTexture("Princess", Content.Load<Texture2D>("Character Princess Girl")); AddEntityTexture("Bug", Content.Load<Texture2D>("Enemy Bug")); } } }
using System; using System.Linq; using System.Threading.Tasks; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; namespace DucksBot.Commands { /// <summary> /// This command is responsible for showing information about the specified user. /// Nickname, Username (with discriminator), ID, Join Date, Creation Date, Roles /// </summary> public class Whois : BaseCommandModule { [Command("whois")] [Aliases("userinfo", "userinformation")] [Description("Get information about a specific user.")] public async Task WhoisCommand(CommandContext ctx, [Description("The user to get information about")] DiscordMember member) { await GetUserInfo(ctx, member); } [Command("whoami")] [Description("Get information about yourself (your own user account).")] public async Task WhoAmICommand(CommandContext ctx) { await GetUserInfo(ctx, ctx.Member); } private async Task GetUserInfo(CommandContext ctx, DiscordMember member) { string title = $"Information about {member.DisplayName}#{member.Discriminator}"; DateTimeOffset joinDate = member.JoinedAt; DateTimeOffset createDate = member.CreationTimestamp; var embed = Utilities.BuildEmbed(title, null, DiscordColor.Black, member.AvatarUrl); if (member.Nickname != null) embed.AddField("NickName", member.Nickname, true); embed.AddField("Username", $"{member.Username}#{member.Discriminator}", true); embed.AddField("ID", member.Id.ToString(), true); embed.AddField("Join Date", joinDate.ToString("G"), true); embed.AddField("Creation Date", createDate.ToString("G"), true); embed.AddField("Roles", string.Join(',', member.Roles.Select(x => x.Mention))); await Utilities.LogEmbed(embed, ctx.Channel); } } }
namespace StrumskaSlava.Middlewares { using Microsoft.AspNetCore.Builder; using StrumskaSlava.Web.Middlewares; public static class SeedAdminUserMiddlewareExtensions { public static IApplicationBuilder UseSeedAdminUserMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<SeedAdminUserMiddleware>(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace DerConverter.Asn { public class DefaultDerAsnEncoder : IDerAsnEncoder { public virtual void Dispose() { } public virtual IEnumerable<byte> Encode(DerAsnType asnType) { if (asnType == null) throw new ArgumentNullException(nameof(asnType)); foreach (var data in asnType.Identifier.Encode()) yield return data; var valueData = asnType.Encode(this).ToArray(); foreach (var data in new DerAsnLength(valueData.Length).Encode()) yield return data; foreach (var data in valueData) yield return data; } } }
namespace Dadata.Model { public class FindAffiliatedRequest : SuggestRequest { public FindAffiliatedScope[] scope { get; set; } public FindAffiliatedRequest(string query, int count = 10) : base(query, count) { } } public enum FindAffiliatedScope { MANAGERS, FOUNDERS, } }
using System; namespace Mozu.Api.Events { public class Topics { public const string APPLICATIONDISABLED = "application.disabled"; public const string APPLICATIONENABLED = "application.enabled"; public const string APPLICATIONINSTALLED = "application.installed"; public const string APPLICATIONUNINSTALLED = "application.uninstalled"; public const string APPLICATIONUPGRADED = "application.upgraded"; public const string ATTRIBUTECREATED = "attribute.created"; public const string ATTRIBUTEDELETED = "attribute.deleted"; public const string ATTRIBUTEUPDATED = "attribute.updated"; public const string CARTCREATED = "cart.created"; public const string CARTDELETED = "cart.deleted"; public const string CARTUPDATED = "cart.updated"; public const string CATEGORYCREATED = "category.created"; public const string CATEGORYDELETED = "category.deleted"; public const string CATEGORYUPDATED = "category.updated"; public const string CREDITCREATED = "credit.created"; public const string CREDITDELETED = "credit.deleted"; public const string CREDITUPDATED = "credit.updated"; public const string CUSTOMERACCOUNTCREATED = "customeraccount.created"; public const string CUSTOMERACCOUNTDELETED = "customeraccount.deleted"; public const string CUSTOMERACCOUNTUPDATED = "customeraccount.updated"; public const string CUSTOMERSEGMENTCREATED = "customersegment.created"; public const string CUSTOMERSEGMENTCUSTOMERADDED = "customersegment.customeradded"; public const string CUSTOMERSEGMENTCUSTOMERREMOVED = "customersegment.customerremoved"; public const string CUSTOMERSEGMENTDELETED = "customersegment.deleted"; public const string CUSTOMERSEGMENTUPDATED = "customersegment.updated"; public const string DISCOUNTCREATED = "discount.created"; public const string DISCOUNTDELETED = "discount.deleted"; public const string DISCOUNTEXPIRED = "discount.expired"; public const string DISCOUNTUPDATED = "discount.updated"; public const string EMAILREQUESTED = "email.requested"; public const string FACETCREATED = "facet.created"; public const string FACETDELETED = "facet.deleted"; public const string FACETUPDATED = "facet.updated"; public const string LOCATIONTYPECREATED = "locationtype.created"; public const string LOCATIONTYPEDELETED = "locationtype.deleted"; public const string LOCATIONTYPEUPDATED = "locationtype.updated"; public const string ORDERABANDONED = "order.abandoned"; public const string ORDERADDRESSCHANGED = "order.addresschanged"; public const string ORDERCANCELLED = "order.cancelled"; public const string ORDERCLOSED = "order.closed"; public const string ORDERERRORED = "order.errored"; public const string ORDERFULFILLED = "order.fulfilled"; public const string ORDERIMPORTED = "order.imported"; public const string ORDEROPENED = "order.opened"; public const string ORDERPENDINGREVIEW = "order.pendingreview"; public const string ORDERSAVED = "order.saved"; public const string ORDERUPDATED = "order.updated"; public const string PAYMENTREFUNDED = "payment.refunded"; public const string PAYMENTTRANSACTIONERROR = "payment.transactionerror"; public const string PRICELISTCREATED = "pricelist.created"; public const string PRICELISTDELETED = "pricelist.deleted"; public const string PRICELISTUPDATED = "pricelist.updated"; public const string PRICELISTENTRYCREATED = "pricelistentry.created"; public const string PRICELISTENTRYDELETED = "pricelistentry.deleted"; public const string PRICELISTENTRYSTATUSCHANGED = "pricelistentry.statuschanged"; public const string PRICELISTENTRYUPDATED = "pricelistentry.updated"; public const string PRODUCTCODERENAMED = "product.coderenamed"; public const string PRODUCTCREATED = "product.created"; public const string PRODUCTDELETED = "product.deleted"; public const string PRODUCTUPDATED = "product.updated"; public const string PRODUCTDRAFTCREATED = "productdraft.created"; public const string PRODUCTDRAFTDELETED = "productdraft.deleted"; public const string PRODUCTDRAFTDISCARDED = "productdraft.discarded"; public const string PRODUCTDRAFTPUBLISHED = "productdraft.published"; public const string PRODUCTDRAFTUPDATED = "productdraft.updated"; public const string PRODUCTINVENTORYINSTOCK = "productinventory.instock"; public const string PRODUCTINVENTORYOUTOFSTOCK = "productinventory.outofstock"; public const string PRODUCTINVENTORYUPDATED = "productinventory.updated"; public const string PRODUCTTYPECREATED = "producttype.created"; public const string PRODUCTTYPEDELETED = "producttype.deleted"; public const string PRODUCTTYPEUPDATED = "producttype.updated"; public const string RETURNAUTHORIZED = "return.authorized"; public const string RETURNCANCELLED = "return.cancelled"; public const string RETURNCLOSED = "return.closed"; public const string RETURNOPENED = "return.opened"; public const string RETURNREJECTED = "return.rejected"; public const string RETURNUPDATED = "return.updated"; public const string SEARCHSETTINGSUPDATED = "searchsettings.updated"; public const string SHIPMENTADJUSTED = "shipment.adjusted"; public const string SHIPMENTITEMADJUSTED = "shipment.itemadjusted"; public const string SHIPMENTITEMSCANCELED = "shipment.itemscanceled"; public const string SHIPMENTITEMSREJECTED = "shipment.itemsrejected"; public const string SHIPMENTSTATUSCHANGED = "shipment.statuschanged"; public const string SHIPMENTWORKFLOWSTATECHANGED = "shipment.workflowstatechanged"; public const string SITECLONED = "site.cloned"; public const string SITECREATED = "site.created"; public const string SITEDELETED = "site.deleted"; public const string SITEUPDATED = "site.updated"; public const string TENANTCREATED = "tenant.created"; public const string TENANTDELETED = "tenant.deleted"; public const string TENANTUPDATED = "tenant.updated"; public const string WISHLISTCREATED = "wishlist.created"; public const string WISHLISTDELETED = "wishlist.deleted"; public const string WISHLISTUPDATED = "wishlist.updated"; } }
using System.IO; using Macad.Test.Utils; using Macad.Core.Shapes; using NUnit.Framework; namespace Macad.Test.Unit.Modeling.Modify { [TestFixture] public class BooleanTests { const string _BasePath = @"Modeling\Modify\Boolean"; //-------------------------------------------------------------------------------------------------- [Test] public void Fuse() { var shapes = TestGeomGenerator.CreateBooleanBodies(false); var boolOp = BooleanFuse.Create(shapes.target, shapes.operands); Assert.IsTrue(boolOp.Make(Shape.MakeFlags.None)); Assert.IsTrue(ModelCompare.CompareShape(boolOp, Path.Combine(_BasePath, "Fuse"))); } //-------------------------------------------------------------------------------------------------- [Test] public void Common() { var shapes = TestGeomGenerator.CreateBooleanBodies(true); var boolOp = BooleanCommon.Create(shapes.target, shapes.operands); Assert.IsTrue(boolOp.Make(Shape.MakeFlags.None)); Assert.IsTrue(ModelCompare.CompareShape(boolOp, Path.Combine(_BasePath, "Common"))); } //-------------------------------------------------------------------------------------------------- [Test] public void Cut() { var shapes = TestGeomGenerator.CreateBooleanBodies(false); var boolOp = BooleanCut.Create(shapes.target, shapes.operands); Assert.IsTrue(boolOp.Make(Shape.MakeFlags.None)); Assert.IsTrue(ModelCompare.CompareShape(boolOp, Path.Combine(_BasePath, "Cut"))); } //-------------------------------------------------------------------------------------------------- } }
using System; namespace IntegrationCore { public static class ChatManager { public static Action<string, string> ChatAction { get; set; } = (s, s1) => { }; public static void SendColored(string message, string color) { ChatAction.Invoke(message, color); } } }
using System.Collections.Generic; using UnityEngine; public class RPGCraftingStation : ScriptableObject { public int ID = -1; public string _name; public string _fileName; public string displayName; public Sprite icon; public float maxDistance; [System.Serializable] public class CraftSkillsDATA { [SkillID] public int craftSkillID = -1; public RPGSkill craftSkillREF; } [RPGDataList] public List<CraftSkillsDATA> craftSkills = new List<CraftSkillsDATA>(); public void updateThis(RPGCraftingStation newDATA) { _name = newDATA._name; _fileName = newDATA._fileName; icon = newDATA.icon; ID = newDATA.ID; maxDistance = newDATA.maxDistance; craftSkills = newDATA.craftSkills; displayName = newDATA.displayName; } }
#region Copyright // <copyright file="MvxViewModel.cs" company="Cirrious"> // (c) Copyright Cirrious. http://www.cirrious.com // This source is subject to the Microsoft Public License (Ms-PL) // Please see license.txt on http://opensource.org/licenses/ms-pl.html // All other rights reserved. // </copyright> // // Project Lead - Stuart Lodge, Cirrious. http://www.cirrious.com #endregion using System; using System.Collections.Generic; using System.Linq; using Cirrious.MvvmCross.Commands; using Cirrious.MvvmCross.Interfaces.Commands; using Cirrious.MvvmCross.Interfaces.ViewModels; using Cirrious.MvvmCross.Interfaces.Views; namespace Cirrious.MvvmCross.ViewModels { public class MvxViewModel : MvxApplicationObject , IMvxViewModel { private readonly Dictionary<IMvxView, bool> _views = new Dictionary<IMvxView, bool>(); #region Implementation of IMvxViewTracker public void RegisterView(IMvxView view) { lock (this) { _views[view] = true; SafeFireEvent(ViewRegistered); } } public void UnRegisterView(IMvxView view) { lock (this) { _views.Remove(view); SafeFireEvent(ViewUnRegistered); } } #endregion protected MvxViewModel() { RequestedBy = MvxRequestedBy.Unknown; } #region Back functionality - required for iOS which has no hardware back button private MvxRelayCommand _closeCommandImpl; protected MvxRelayCommand CloseCommandImpl { get { if (_closeCommandImpl == null) { _closeCommandImpl = new MvxRelayCommand(Close, CanClose); } return _closeCommandImpl; } } public IMvxCommand CloseCommand { get { return CloseCommandImpl; } } protected virtual bool CanClose() { return true; } protected virtual void Close() { RequestClose(this); } #endregion protected bool HasViews { get { lock (this) { return _views.Any(); } } } protected bool IsVisible { get { lock (this) { return _views.Keys.Any(view => view.IsVisible); } } } #region IMvxViewModel Members public MvxRequestedBy RequestedBy { get; set; } #endregion protected event EventHandler ViewRegistered; protected event EventHandler ViewUnRegistered; private void SafeFireEvent(EventHandler h) { var handler = h; if (handler != null) handler(this, EventArgs.Empty); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Photon.Pun; public class PlayerChatSetup : MonoBehaviourPun { public Text namePrefab; [HideInInspector] public Text nameLabel; public Transform namePos; [HideInInspector] public string textBoxName = ""; public string playerName = "Player"; private void Start() { GameObject canvas = GameObject.FindWithTag("MainCanvas"); nameLabel = Instantiate(namePrefab, Vector3.zero, Quaternion.identity) as Text; nameLabel.transform.SetParent(canvas.transform); } private void Update() { Vector3 nameLabelPos = Camera.main.WorldToScreenPoint(namePos.position); nameLabel.transform.position = nameLabelPos; } private void OnGUI() { textBoxName = GUI.TextField(new Rect(25, 15, 100, 25), textBoxName); if (GUI.Button(new Rect(130, 15, 50, 25), "Send")) { photonView.RPC("ChangeName", RpcTarget.All, textBoxName); } } [PunRPC] public void ChangeName(string _playerName) { playerName = _playerName; nameLabel.text = playerName; } }
using System.Threading.Tasks; using tusdotnet.Adapters; using tusdotnet.Constants; using tusdotnet.Interfaces; using tusdotnet.Models; using tusdotnet.Models.Concatenation; using tusdotnet.Validation; using tusdotnet.Validation.Requirements; namespace tusdotnet.IntentHandlers { /* * The Server MUST always include the Upload-Offset header in the response for a HEAD request, * even if the offset is 0, or the upload is already considered completed. If the size of the upload is known, * the Server MUST include the Upload-Length header in the response. * If the resource is not found, the Server SHOULD return either the 404 Not Found, 410 Gone or 403 Forbidden * status without the Upload-Offset header. * The Server MUST prevent the client and/or proxies from caching the response by adding the * Cache-Control: no-store header to the response. * * If an upload contains additional metadata, responses to HEAD requests MUST include the Upload-Metadata header * and its value as specified by the Client during the creation. * * The response to a HEAD request for a final upload SHOULD NOT contain the Upload-Offset header unless the * concatenation has been successfully finished. After successful concatenation, the Upload-Offset and Upload-Length * MUST be set and their values MUST be equal. The value of the Upload-Offset header before concatenation is not * defined for a final upload. The response to a HEAD request for a partial upload MUST contain the Upload-Offset header. * The Upload-Length header MUST be included if the length of the final resource can be calculated at the time of the request. * Response to HEAD request against partial or final upload MUST include the Upload-Concat header and its value as received * in the upload creation request. */ internal class GetFileInfoHandler : IntentHandler { internal override Requirement[] Requires => new Requirement[] { new FileExist(), new FileHasNotExpired() }; public GetFileInfoHandler(ContextAdapter context) : base(context, IntentType.GetFileInfo, LockType.NoLock) { } internal override async Task Invoke() { Response.SetHeader(HeaderConstants.TusResumable, HeaderConstants.TusResumableValue); Response.SetHeader(HeaderConstants.CacheControl, HeaderConstants.NoStore); var uploadMetadata = await GetMetadata(Context); if (!string.IsNullOrEmpty(uploadMetadata)) { Response.SetHeader(HeaderConstants.UploadMetadata, uploadMetadata); } var uploadLength = await Store.GetUploadLengthAsync(Request.FileId, CancellationToken); SetUploadLengthHeader(Context, uploadLength); var uploadOffset = await Store.GetUploadOffsetAsync(Request.FileId, CancellationToken); FileConcat uploadConcat = null; var addUploadOffset = true; if (Context.Configuration.Store is ITusConcatenationStore tusConcatStore) { uploadConcat = await tusConcatStore.GetUploadConcatAsync(Request.FileId, CancellationToken); // Only add Upload-Offset to final files if they are complete. if (uploadConcat is FileConcatFinal && uploadLength != uploadOffset) { addUploadOffset = false; } } if (addUploadOffset) { Response.SetHeader(HeaderConstants.UploadOffset, uploadOffset.ToString()); } if (uploadConcat != null) { (uploadConcat as FileConcatFinal)?.AddUrlPathToFiles(Context.Configuration.UrlPath); Response.SetHeader(HeaderConstants.UploadConcat, uploadConcat.GetHeader()); } } private Task<string> GetMetadata(ContextAdapter context) { if (context.Configuration.Store is ITusCreationStore tusCreationStore) return tusCreationStore.GetUploadMetadataAsync(Request.FileId, context.CancellationToken); return Task.FromResult<string>(null); } private static void SetUploadLengthHeader(ContextAdapter context, long? uploadLength) { if (uploadLength != null) { context.Response.SetHeader(HeaderConstants.UploadLength, uploadLength.Value.ToString()); } else if (context.Configuration.Store is ITusCreationDeferLengthStore) { context.Response.SetHeader(HeaderConstants.UploadDeferLength, "1"); } } } }
using DbLocalizationProvider.Abstractions; namespace DbLocalizationProvider.Tests.TypeFactoryTests { public class SampleCommand : ICommand { public string Field { get; set; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime.Serialization; namespace RingCentral.EngageDigital.SourceSdk.Models { [JsonConverter(typeof(StringEnumConverter))] public enum Gender { [EnumMember(Value = "man")] Man, [EnumMember(Value = "woman")] Woman, } }
using System; using System.Text; using System.Runtime.CompilerServices; namespace Aardvark.Base { //# foreach (var isDouble in new[] { false, true }) { //# var ft = isDouble ? "double" : "float"; //# var x2t = isDouble ? "2d" : "2f"; //# var x3t = isDouble ? "3d" : "3f"; //# var x4t = isDouble ? "4d" : "4f"; public partial struct M3__x3t__ { #region Coordinate-System Transforms /// <summary> /// Creates an orthonormal basis from the given normal as z-axis. /// The resulting matrix transforms from the local to the global coordinate system. /// The normal is expected to be normalized. /// /// The implementation is based on: /// Building an Orthonormal Basis, Revisited, by Duff et al. 2017 /// </summary> public static M3__x3t__ NormalFrame(V__x3t__ n) { var sg = n.Z >= 0 ? 1 : -1; // original uses copysign(1.0, n.Z) -> not the same as sign where 0 -> 0 var a = -1 / (sg + n.Z); var b = n.X * n.Y * a; // column 0: [1 + sg * n.X * n.X * a, sg * b, -sg * n.X] // column 1: [b, sg + n.Y * n.Y * a, -n.Y] // column 2: n return new M3__x3t__(1 + sg * n.X * n.X * a, b, n.X, sg * b, sg + n.Y * n.Y * a, n.Y, -sg * n.X, -n.Y, n.Z); } /// <summary> /// Computes from a <see cref="V__x3t__"/> normal the transformation matrix /// from the local coordinate system where the normal is the z-axis to /// the global coordinate system. /// </summary> /// <param name="normal">The normal vector of the new ground plane.</param> public static M3__x3t__ NormalFrameLocal2Global(V__x3t__ normal) { V__x3t__ min; double x = Fun.Abs(normal.X); double y = Fun.Abs(normal.Y); double z = Fun.Abs(normal.Z); if (x < y) { if (x < z) { min = V__x3t__.XAxis; } else { min = V__x3t__.ZAxis; } } else { if (y < z) { min = V__x3t__.YAxis; } else { min = V__x3t__.ZAxis; } } var xVec = Vec.Cross(normal, min); xVec.Normalize(); // this is now guaranteed to be normal to the input normal var yVec = Vec.Cross(normal, xVec); yVec.Normalize(); var zVec = normal; zVec.Normalize(); return new M3__x3t__(xVec.X, yVec.X, zVec.X, xVec.Y, yVec.Y, zVec.Y, xVec.Z, yVec.Z, zVec.Z); } #endregion } //# } }
using CommonHelpers.Common; namespace Demo.Uwp.ViewModels { public class HomeViewModel : ViewModelBase { public HomeViewModel() { } } }
using Xunit; namespace ServerLibraryTests { public class DevicesTests { [Fact] public void ToFile_IgnoresCertainProperties() { } } }
using System.Collections.Generic; using Core.Architecture.vCPU.Converters; using Core.Architecture.vCPU.Operations; using Core.Components; using Core.DTO; using Core.Interfaces; using Core.Services; using FluentAssertions; using NUnit.Framework; namespace vCPUTests { [TestFixture] public class OperationConverterTests { private IMemoryBankService m_BankService = null; [Test] public void ConvertLoadValueOp() { var t_Converter = new OpLoadConstConverter(m_BankService); var t_LoadOp = t_Converter.Convert(new OperationDTO(1, new byte[] { 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); t_LoadOp.Should().BeOfType<OpLoadConst<int>>(); } [Test] public void ConvertLoadAddressOp() { var t_Converter = new OpLoadConverter(m_BankService); var t_LoadAddressOp = t_Converter.Convert(new OperationDTO(2, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, })); t_LoadAddressOp.Should().BeOfType<OpLoad<int>>(); } [Test] public void ConvertAddOp() { var t_Converter = new OpAddConverter(m_BankService); var t_AddOp = t_Converter.Convert(new OperationDTO(3, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); t_AddOp.Should().BeOfType<OpAdd>(); } [Test] public void ConvertSubOp() { var t_Converter = new OpSubConverter(m_BankService); var t_SubOp = t_Converter.Convert(new OperationDTO(4, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 })); t_SubOp.Should().BeOfType<OpSub>(); } [SetUp] public void Initialize() { m_BankService = new MemoryBankService(new List<IMemoryBank> { new MemoryBank(128) }); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Ducode.Wolk.Api.Models.Notebooks; using Ducode.Wolk.Application.Notebooks.Commands.CreateNotebook; using Ducode.Wolk.Application.Notebooks.Commands.DeleteNotebook; using Ducode.Wolk.Application.Notebooks.Commands.UpdateNotebook; using Ducode.Wolk.Application.Notebooks.Models; using Ducode.Wolk.Application.Notebooks.Queries.GetAllNotebooks; using Ducode.Wolk.Application.Notebooks.Queries.GetNotebook; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Ducode.Wolk.Api.Controllers { public class NotebookController : BaseApiController { /// <summary> /// Returns a list of all notebooks. /// </summary> /// <returns>A list of all notebooks</returns> [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<ActionResult<IEnumerable<NotebookDto>>> GetAll() => Ok(await Mediator.Send(new GetAllNotebooksQuery())); /// <summary> /// Returns a specific notebook. /// </summary> /// <param name="id">The notebook ID.</param> /// <returns>The notebook.</returns> [HttpGet("{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult<NotebookDto>> Get([FromRoute]long id) => Ok(await Mediator.Send(new GetNotebookQuery(id))); /// <summary> /// Creates a new notebook /// </summary> /// <param name="notebookModel">The notebook.</param> /// <returns>The added notebook.</returns> [HttpPost] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<ActionResult<NotebookDto>> Create([FromBody] MutateNotebookModel notebookModel) { var notebook = await Mediator.Send(Mapper.Map<CreateNotebookCommand>(notebookModel)); return CreatedAtAction(nameof(Get), new { id = notebook.Id}, notebook); } /// <summary> /// Updates an existing notebook. /// </summary> /// <param name="notebookModel">The notebook.</param> /// <param name="id">The notebook ID.</param> /// <returns>No content.</returns> [HttpPut("{id}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult> Update([FromBody] MutateNotebookModel notebookModel, [FromRoute]long id) { var command = Mapper.Map<UpdateNotebookCommand>(notebookModel); command.Id = id; await Mediator.Send(command); return NoContent(); } /// <summary> /// Deletes a specific notebook. /// </summary> /// <param name="id">The notebook ID.</param> /// <returns>No content.</returns> [HttpDelete("{id}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult> Delete([FromRoute] long id) { await Mediator.Send(new DeleteNotebookCommand(id)); return NoContent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SimpleApp.Models { public class Product { public string Name { get; set; } public decimal? Price { get; set; } } public class ProductDataSource : IDataSource { public IEnumerable<Product> Products => new Product[] { new Product {Name = "Kayak", Price = 275M }, new Product {Name = "LifeJacket", Price = 48.95M } }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using Verse; using RimWorld; using System.Reflection; using Harmony; namespace Profiler { public class ProfilerWindow : EditWindow { private string currentProfileKey; private Vector2 scrollPosition = Vector2.zero; private string typeMethodName = ""; public override Vector2 InitialSize { get { return new Vector2(600f, 450f); } } public override void DoWindowContents(Rect inRect) { inRect = inRect.ContractedBy(8f); Text.Font = GameFont.Tiny; GUI.BeginGroup(inRect); typeMethodName = Widgets.TextField(new Rect(0f, 0f, 400f, 30f), typeMethodName); if (Widgets.ButtonText(new Rect(410f, 0f, 120f, 30f), "Profile")) { int i = typeMethodName.LastIndexOf('.'); string typeStr = typeMethodName.Substring(0, i); string methodStr = typeMethodName.Substring(i + 1); Type type = AccessTools.TypeByName(typeStr); if (type == null) { Log.Error(string.Format("Type {0} is not exist.", typeStr)); } MethodInfo methodInfo = AccessTools.Method(type, methodStr); if (methodInfo == null) { Log.Error(string.Format("Method {0}.{1} is not exist.", typeStr, methodStr)); } ProfilePatcher.Patch(HarmonyPatches.harmonyInstance, type, methodInfo); } List<TabRecord> tabList = new List<TabRecord>(); foreach (string key in ProfilerManager.GetTargets()) { tabList.Add(new TabRecord(key, delegate () { scrollPosition = Vector2.zero; currentProfileKey = key; }, currentProfileKey == key)); } if (currentProfileKey == null && ProfilerManager.GetTargets().Count() > 0) { currentProfileKey = ProfilerManager.GetTargets().First(); } TabDrawer.DrawTabs(new Rect(0f, 70f, 560f, 330f), tabList); if (currentProfileKey != null) { int count = ProfilerManager.GetMethods(currentProfileKey).Count(); Rect scrollOutRect = new Rect(0f, 90f, 560f, 320f); Rect scrollViewRect = new Rect(0f, 0f, 550f, count * 22f); float y = 0f; Widgets.BeginScrollView(scrollOutRect, ref scrollPosition, scrollViewRect, true); foreach (string method in ProfilerManager.GetMethods(currentProfileKey)) { long currentTick = ProfilerManager.GetProfileData(currentProfileKey, method).Max(); Widgets.Label(new Rect(0f, y, 420f, 22f), method); Widgets.Label(new Rect(420f, y, 80f, 22f), currentTick.ToString()); y += 22f; } Widgets.EndScrollView(); } GUI.EndGroup(); Text.Font = GameFont.Small; } } }
using System; using System.Collections.Generic; using System.Text; namespace Shared { public class NetworkVector3 { public float X { get; set; } public float Y { get; set; } public float Z { get; set; } public NetworkVector3() { } public NetworkVector3(float x, float y, float z) { X = x; Y = y; Z = z; } public static float Distance(NetworkVector3 v1, NetworkVector3 v2) { NetworkVector3 v = new NetworkVector3(); v.X = v1.X - v2.X; v.Y = v1.Y - v2.Y; v.Z = v1.Z - v2.Z; return (float)Math.Sqrt(v.X * v.X + v.Y * v.Y * v.Z * v.Z); } } }
using System; using System.Collections.Generic; using System.Text; namespace CienciaArgentina.Microservices.Entities.Models { public class BaseModel { public DateTime DateCreated { get; set; } public DateTime? DateDeleted { get; set; } public BaseModel() { DateCreated = DateTime.Now; DateDeleted = null; } } }
using Retypeit.Scripts.Bindings.Ast; namespace Retypeit.Scripts.Bindings.Interpreter { public interface IVisitor { object Visit(VariableNode node); object Visit(ValueNode node); object Visit(SubNode node); object Visit(NotEqualNode node); object Visit(MultiplyNode node); object Visit(IfElseNode node); object Visit(FunctionNode node); object Visit(EqualNode node); object Visit(BoolValueNode node); object Visit(GreaterThanNode node); object Visit(LessThanNode node); object Visit(DivideNode node); object Visit(AddNode node); object Visit(AstRoot node); object Visit(ValueWithNullDefaultNode variableWithDefaultNode); object Visit(ValueWithUndefinedOrNullDefaultNode node); } }
//using System; //using System.Collections.Generic; //using System.Diagnostics.CodeAnalysis; //using System.Text; //using Dhgms.Nucleotide.Features.SignalR; //using Dhgms.Nucleotide.Generators; //using Microsoft.CodeAnalysis; //using Moq; //using Xunit; //namespace Dhgms.Nucleotide.UnitTests.Generators //{ // [ExcludeFromCodeCoverage] // public static class SignalRHubClassGeneratorTests // { // public sealed class ConstructorMethod : BaseGeneratorTests.BaseConstructorMethod<SignalRHubClassGenerator> // { // protected override Func<AttributeData, SignalRHubClassGenerator> GetFactory() // { // return data => new SignalRHubClassGenerator(data); // } // } // } //}
using System; using Axis.Luna.Operation; using Axis.Pollux.Common.Models; using Axis.Pollux.Common.Utils; using Axis.Pollux.Identity.Exceptions; using ErrorCodes = Axis.Pollux.Common.Exceptions.ErrorCodes; namespace Axis.Pollux.Identity.Contracts.Params { public class UserProfileRequestInfo : IValidatable { public Guid UserId { get; set; } public ArrayPageRequest AddressDataRequest { get; set; } public ArrayPageRequest ContactDataRequest { get; set; } public ArrayPageRequest NameDataRequest { get; set; } public ArrayPageRequest UserDataRequest { get; set; } public virtual Operation Validate() => Operation.Try(() => { if (UserId == default(Guid)) throw new IdentityException(ErrorCodes.InvalidContractParamState); }); } }
static void Main(string[] args) { ServerManager serverManager = new ServerManager(); Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection section = config.GetSection("system.webServer/asp"); ConfigurationElement element = section.GetChildElement("session"); Console.Write("allowSessionState attribute value: "); Console.WriteLine(element.GetAttributeValue("allowSessionState")); Console.WriteLine("Set allowSessionState value to false"); element.SetAttributeValue("allowSessionState", false); Console.Write("allowSessionState attribute value: "); Console.WriteLine(element.GetAttributeValue("allowSessionState")); serverManager.CommitChanges(); }
using Cinemachine; using Fumbbl; using System; using UnityEngine; using UnityEngine.SceneManagement; public class InputHandler : MonoBehaviour { public Camera Camera; public Vector3 mouseSensitivity = new Vector3(1,1,1); public Vector2 rotationSpeed = new Vector2(5, 5); public GameObject CameraTarget; public CinemachineVirtualCamera VCam; private Vector3 lastRotatePosition; private Vector3 lastPanPosition; private Vector3 initialRotateAngles; private Vector2 targetRotation; #region MonoBehaviour Methods private void Start() { targetRotation = CameraTarget.transform.rotation.eulerAngles; } private void Update() { if (VCam != null) { if (Input.GetMouseButtonDown(1)) { lastRotatePosition = Input.mousePosition; initialRotateAngles = CameraTarget.transform.rotation.eulerAngles; } var angles = CameraTarget.transform.rotation.eulerAngles; var currentX = angles.x; var currentY = angles.y; if (Input.GetMouseButton(1)) { Vector3 delta = Input.mousePosition - lastRotatePosition; var targetX = MinMax(10, initialRotateAngles.x + (delta.y * mouseSensitivity.y / 100), 90); var targetY = (initialRotateAngles.y + (delta.x * mouseSensitivity.x / 100)) % 360; if (targetY - currentY > 180) { targetY -= 360; } if (targetY - currentY < -180) { targetY += 360; } targetRotation.x = targetX; targetRotation.y = targetY; } var rotationDistance = Vector3.Distance(angles, targetRotation); if (rotationDistance > 0.5) { var targetX = targetRotation.x; var targetY = targetRotation.y; if (targetY - currentY > 180) { targetY -= 360; } if (targetY - currentY < -180) { targetY += 360; } var deltaX = (targetX - currentX) * rotationSpeed.y; var deltaY = ((targetY - currentY)%360) * rotationSpeed.x; angles.x = currentX + deltaX; angles.y = currentY + deltaY; var quaternion = Quaternion.Euler(angles); CameraTarget.transform.rotation = quaternion; //lastRotatePosition = Input.mousePosition; } else if (rotationDistance != 0) { CameraTarget.transform.rotation = Quaternion.Euler(targetRotation); } if (Input.mouseScrollDelta.y != 0) { var componentBase = VCam.GetCinemachineComponent(CinemachineCore.Stage.Body); if (componentBase is Cinemachine3rdPersonFollow) { var distance = (componentBase as Cinemachine3rdPersonFollow).CameraDistance; distance = MinMax(20, distance + Input.mouseScrollDelta.y * mouseSensitivity.z, 300); (componentBase as Cinemachine3rdPersonFollow).CameraDistance = distance; } } if (Input.GetMouseButtonDown(2)) { lastPanPosition = Input.mousePosition; } if (Input.GetMouseButton(2)) { var src = Input.mousePosition; Vector3 screenDelta = Input.mousePosition - lastPanPosition; var dst = src + screenDelta; var srcRay = Camera.ScreenPointToRay(src); var dstRay = Camera.ScreenPointToRay(dst); var plane = new Plane(Vector3.up, 0); float srcDistance; float dstDistance; plane.Raycast(srcRay, out srcDistance); plane.Raycast(dstRay, out dstDistance); var srcHit = srcRay.GetPoint(srcDistance); var dstHit = dstRay.GetPoint(dstDistance); var worldDelta = dstHit - srcHit; var newPosition = CameraTarget.transform.position - worldDelta; newPosition.x = MinMax(-200, newPosition.x, 200); newPosition.z = MinMax(-100, newPosition.z, 50); CameraTarget.transform.position = newPosition; lastPanPosition = Input.mousePosition; } } if (Input.GetKeyDown(KeyCode.F1)) { CameraTarget.transform.position = new Vector3(0, 0, 0); // CameraTarget.transform.rotation = Quaternion.Euler(90, 0, 0); targetRotation = new Vector2(90, 0); //CameraTarget.transform.rotation.eulerAngles; var componentBase = VCam.GetCinemachineComponent(CinemachineCore.Stage.Body); if (componentBase is Cinemachine3rdPersonFollow) { (componentBase as Cinemachine3rdPersonFollow).CameraDistance = 138; } } if (Input.GetKeyDown(KeyCode.Escape)) { string currentScene = SceneManager.GetActiveScene().name; if (string.Equals("SettingsScene", currentScene)) { SwitchToPreviousScene(); } else { SwitchToSettingsScene(); } } } #endregion private float MinMax(float min, float val, float max) { return Math.Min(max, Math.Max(min, val)); } public void SwitchToPreviousScene() { MainHandler.Instance.SetScene(FFB.Instance.PreviousScene); } public void SwitchToSettingsScene() { FFB.Instance.PreviousScene = SceneManager.GetActiveScene().name; MainHandler.Instance.SetScene(MainHandler.SceneType.SettingsScene); } }
namespace Template10.Services.Settings { public enum SettingsStrategies { Local, Roam, Temp } }
using System; using OpenTK; namespace Minalear.Engine.Content.ModelLoader.LineParsers { internal class NormalLineParser : LineParserBase { public override string LinePrefix { get { return "vn"; } } public override void ParseLine(ModelLoader loader, string line) { string[] tokens = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); float x, y, z; x = tokens[0].ParseFloat(); y = tokens[1].ParseFloat(); z = tokens[2].ParseFloat(); loader.AddNewNormal(new Vector3(x, y, z)); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BufferedEventArgs.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.ExceptionHandling { using System; /// <summary> /// /// </summary> public class BufferedEventArgs : EventArgs { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BufferedEventArgs"/> class. /// </summary> /// <param name="bufferedException">The buffered exception.</param> /// <param name="dateTime">the date time that indicates when the buffering was invoked.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="bufferedException"/> is <c>null</c>.</exception> public BufferedEventArgs(Exception bufferedException, DateTime dateTime) { Argument.IsNotNull("bufferedException", bufferedException); BufferedException = bufferedException; DateTime = dateTime; } #endregion #region Properties /// <summary> /// Gets the buffered exception. /// </summary> public Exception BufferedException { get; private set; } /// <summary> /// Gets the date time that indicates when the buffering was invoked. /// </summary> public DateTime DateTime { get; private set; } #endregion } }
using CorePlatformCh12; using Microsoft.Extensions.FileProviders; using PlatformCh16; var builder = WebApplication.CreateBuilder(args); builder.Services.Configure<CookiePolicyOptions>(opts => { opts.CheckConsentNeeded = context => true; }); builder.Services.AddDistributedMemoryCache(); builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.IsEssential = true; }); builder.Services.AddHsts(opts => { opts.MaxAge = TimeSpan.FromDays(1); opts.IncludeSubDomains = true; }); var app = builder.Build(); if(app.Environment.IsProduction()) { app.UseHsts(); } //app.UseDeveloperExceptionPage(); // In .NET 6 Developer Exception pages are ALWAYS used in development environment. // There does not seem to be a way to disable them // Can be over ridden though with an exception handler app.UseExceptionHandler("/error.html"); app.UseStatusCodePages("text/html", Responses.DefaultResponse); app.UseHttpsRedirection(); app.UseCookiePolicy(); app.UseStaticFiles(); app.UseMiddleware<ConsentMiddleware>(); app.UseSession(); app.UseRouting(); app.Use(async (context, next) => { if (context.Request.Path == "/error") { context.Response.StatusCode = StatusCodes.Status404NotFound; await Task.CompletedTask; } else { await next(); } }); app.Run(context => { throw new Exception("Something went wrong!!"); }); app.Use(async (context, next) => { await next(); await context.Response .WriteAsync($"\nHTTPS Request: {context.Request.IsHttps}\n"); }); app.UseEndpoints(endpoints => { endpoints.MapGet("/session", async context => { int counter1 = (context.Session.GetInt32("counter1") ?? 0) + 1; int counter2 = (context.Session.GetInt32("counter2") ?? 0) + 1; context.Session.SetInt32("counter1", counter1); context.Session.SetInt32("counter2", counter2); await context.Session.CommitAsync(); await context.Response .WriteAsync($"Counter1: {counter1}, Counter2: {counter2}"); }); endpoints.MapGet("/cookie", async context => { int counter1 = int.Parse(context.Request.Cookies["counter1"] ?? "0") + 1; context.Response.Cookies.Append("counter1", counter1.ToString(), new CookieOptions { MaxAge = TimeSpan.FromMinutes(30), IsEssential = true, }); int counter2 = int.Parse(context.Request.Cookies["counter2"] ?? "0") + 1; context.Response.Cookies.Append("counter2", counter1.ToString(), new CookieOptions { MaxAge = TimeSpan.FromMinutes(30) }); await context.Response .WriteAsync($"Counter 1: {counter1}, Counter2: {counter2}"); }); endpoints.MapGet("clear", context => { context.Response.Cookies.Delete("counter1"); context.Response.Cookies.Delete("counter2"); context.Response.Redirect("/"); return Task.CompletedTask; }); endpoints.MapFallback(async context => { await context.Response.WriteAsync("Hello World"); }); }); app.Run();
namespace OnionPattern.Domain.Configurations { public class LogLocationConfiguration { /// <summary> /// Log location when in FileName Build Mode /// </summary> public string FileName { get; set; } } }
[Serializable] public class PetNpcPetData // TypeDefIndex: 7403 { // Fields [SerializeField] // RVA: 0x1662D0 Offset: 0x1663D1 VA: 0x1662D0 public ActorID ActorID; // 0x10 [SerializeField] // RVA: 0x1662E0 Offset: 0x1663E1 VA: 0x1662E0 public MonsterDataID MonsterDataID1; // 0x14 [SerializeField] // RVA: 0x1662F0 Offset: 0x1663F1 VA: 0x1662F0 public MonsterDataID MonsterDataID2; // 0x18 [SerializeField] // RVA: 0x166300 Offset: 0x166401 VA: 0x166300 public Gender Gender; // 0x1C // Methods // RVA: 0x1FE6A20 Offset: 0x1FE6B21 VA: 0x1FE6A20 public void .ctor() { } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Windows.Forms; namespace download_manager { public class FileDownload : IDownloader { public Stopwatch m_StopWatch; public Queue<string> m_UrlQueue { get; set; } DownloadStatus e_DownloadStatus; public int m_BufferSize { get; set; } public DataGridView m_DataGrid { private get; set; } public string m_DownloadDestination { get; set; } public long m_TotalSize { get; set; } public int m_TotalBytesRecieved { get; set; } private int m_bytesRead { get; set; } private int m_ThreadIndex { get; set; } public event EventHandler<DownloadProgressChangedEventArgs> DownloadProgressChanged; public event EventHandler<DownloadCompletedEventArgs> DownloadCompleted; public FileDownload() { m_UrlQueue = new Queue<string>(); m_StopWatch = new Stopwatch(); e_DownloadStatus = new DownloadStatus(); m_BufferSize = 1024; m_TotalBytesRecieved = 0; } public void Start(string i_DownloadPath, int i_currentThreadIndex) { m_ThreadIndex = i_currentThreadIndex; m_DownloadDestination = i_DownloadPath; Download(); } public void Download() { WebRequest webRequest = null; WebResponse webResponse = null; Stream remoteStream = null; Stream localStream = null; try { webRequest = WebRequest.Create(m_UrlQueue.Dequeue()); e_DownloadStatus = DownloadStatus.Downloading; //webRequest.Credentials = CredentialCache.DefaultCredentials; webResponse = webRequest.GetResponse(); m_TotalSize = webResponse.ContentLength; if (m_TotalSize <= 0) { throw new ApplicationException("The file that you want to download doesn't exists"); } m_StopWatch.Start(); // TODO when completed stop watch.. remoteStream = webResponse.GetResponseStream(); localStream = File.Create(m_DownloadDestination); byte[] buffer = new byte[m_BufferSize]; m_bytesRead = 0; do { if (remoteStream != null) m_bytesRead = remoteStream.Read(buffer, 0, buffer.Length); localStream.Write(buffer, 0, m_bytesRead); m_TotalBytesRecieved += m_bytesRead; InternalDownloadProgressChanged(); } while (m_bytesRead > 0); } catch (Exception e) { MessageBox.Show(e.Message); } finally { InternalDownloadCompleted(); webResponse?.Close(); remoteStream?.Close(); localStream?.Close(); } } private void InternalDownloadCompleted() { OnDownloadCompleted(new DownloadCompletedEventArgs(m_ThreadIndex)); } private void OnDownloadCompleted(DownloadCompletedEventArgs e) { DownloadCompleted?.Invoke(this, e); } private void InternalDownloadProgressChanged() { OnDownloadProgressChanged(new DownloadProgressChangedEventArgs(m_TotalBytesRecieved, m_TotalSize, (int) (m_TotalBytesRecieved / 1024d / m_StopWatch.Elapsed.TotalSeconds), m_ThreadIndex)); } protected virtual void OnDownloadProgressChanged(DownloadProgressChangedEventArgs e) { DownloadProgressChanged?.Invoke(this, e); } } }
using System; namespace AutomaticDataGeneration.Config { public class DarknetConfig { public DarknetConfig(string configPath, string weightPath, string namesPath) { ConfigPath = configPath ?? throw new ArgumentNullException(nameof(configPath)); WeightPath = weightPath ?? throw new ArgumentNullException(nameof(weightPath)); NamesPath = namesPath ?? throw new ArgumentNullException(nameof(namesPath)); } public string ConfigPath { get; } public string WeightPath { get; } public string NamesPath { get; } } }
using UnityEngine; using UnityEngine.UI; /// <summary> /// Controls the HUD element showing the number of coins the player has. /// </summary> public class ThrowingAmmoMeter : MonoBehaviour { private const float timeToFade = 3; private Animator anim; private Text coinCountText; private float timeLastChanged; private int lastCount; private void Awake() { anim = GetComponent<Animator>(); coinCountText = GetComponentInChildren<Text>(); } private void LateUpdate() { if (lastCount != Prima.PrimaInstance.CoinHand.Pouch.Count) { timeLastChanged = Time.time; } if (Player.CurrentActor.ActorIronSteel.Mode == PrimaPullPushController.ControlMode.Coinshot) { anim.SetBool("IsVisible", true); } else { anim.SetBool("IsVisible", Time.time - timeLastChanged < timeToFade); } coinCountText.text = Prima.PrimaInstance.CoinHand.Pouch.Count.ToString(); lastCount = Prima.PrimaInstance.CoinHand.Pouch.Count; } public void Clear() { timeLastChanged = -100; lastCount = 0; anim.SetBool("IsVisible", false); anim.Play("MetalReserve_Invisible", anim.GetLayerIndex("Visibility")); } public void Alert(Prima.CoinMode mode) { timeLastChanged = Time.time; switch (mode) { case Prima.CoinMode.Semi: anim.Play("ThrowableAmmo_Semi", anim.GetLayerIndex("Image")); break; case Prima.CoinMode.Full: anim.Play("ThrowableAmmo_Full", anim.GetLayerIndex("Image")); break; case Prima.CoinMode.Spray: anim.Play("ThrowableAmmo_Spray", anim.GetLayerIndex("Image")); break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FubuCore.Reflection; namespace FubuTestingSupport { public class EnumerablePersistenceCheck<T> : AccessorPersistenceCheck { public static EnumerablePersistenceCheck<T> For<TParent>(Expression<Func<TParent, IEnumerable<T>>> expression) { var accessor = ReflectionHelper.GetAccessor(expression); return new EnumerablePersistenceCheck<T>(accessor); } public EnumerablePersistenceCheck(Accessor accessor) : base(accessor) { } protected override bool matches(object originalValue, object persistedValue) { IEnumerable<T> enum1 = originalValue as IEnumerable<T>; IEnumerable<T> enum2 = persistedValue as IEnumerable<T>; if (enum1 == null) { if (enum2 == null) return true; } else if (enum2 == null) return false; else { if (enum1.SequenceEqual(enum2)) return true; } return false; } } }
using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using OneSignalSDK_WP_WNS; using RohBot.Converters; using RohBot.Impl; using RohBot.Impl.Packets; namespace RohBot.Views { public sealed class ComboBoxDescriptor<T> { public string Name { get; } public T Value { get; } public ComboBoxDescriptor(string name, T value) { Name = name; Value = value; } public override string ToString() => Name; } public sealed partial class SettingsPage : Page { private AppShell Shell => AppShell.Current; private bool _settingNotificationToggleSwitch; public SettingsPage() { InitializeComponent(); var themes = new ObservableCollection<string> { "Dark", "Light" }; ThemeCombo.ItemsSource = themes; ThemeCombo.SelectedIndex = themes.IndexOf(Settings.Theme.Value); var timeFormats = new ObservableCollection<ComboBoxDescriptor<TimeFormat>> { new ComboBoxDescriptor<TimeFormat>("System", TimeFormat.System), new ComboBoxDescriptor<TimeFormat>("12-hour", TimeFormat.TwelveHour), new ComboBoxDescriptor<TimeFormat>("24-hour", TimeFormat.TwentyFourHour) }; TimeFormatCombo.ItemsSource = timeFormats; TimeFormatCombo.SelectedIndex = timeFormats .Select(d => d.Value) .ToList() .IndexOf((TimeFormat)Settings.TimeFormat.Value); var imageSizes = new ObservableCollection<ComboBoxDescriptor<ImageScale>> { new ComboBoxDescriptor<ImageScale>("Small (500px)", ImageScale.Small), new ComboBoxDescriptor<ImageScale>("Medium (1000px)", ImageScale.Medium), new ComboBoxDescriptor<ImageScale>("Large (2000px)", ImageScale.Large), new ComboBoxDescriptor<ImageScale>("Original", ImageScale.Original) }; ImageSizeCombo.ItemsSource = imageSizes; ImageSizeCombo.SelectedIndex = imageSizes .Select(d => d.Value) .ToList() .IndexOf((ImageScale)Settings.ImageSize.Value); _settingNotificationToggleSwitch = true; NotificationToggleSwitch.IsOn = Settings.NotificationsEnabled.Value; NotificationPatternText.Text = Settings.NotificationPattern.Value; // sometimes we need this? _settingNotificationToggleSwitch = false; } private void SettingsPage_OnUnloaded(object sender, RoutedEventArgs args) { TimeFormatCombo.ItemsSource = null; ThemeCombo.ItemsSource = null; } private void TimeFormatCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs args) { if (TimeFormatCombo.ItemsSource != null && TimeFormatCombo.SelectedItem != null) { var descriptor = (ComboBoxDescriptor<TimeFormat>)TimeFormatCombo.SelectedItem; Settings.TimeFormat.Value = (int)descriptor.Value; } } private void ImageSizeCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs args) { if (ImageSizeCombo.ItemsSource != null && ImageSizeCombo.SelectedItem != null) { var descriptor = (ComboBoxDescriptor<ImageScale>)ImageSizeCombo.SelectedItem; Settings.ImageSize.Value = (int)descriptor.Value; } } private void ThemeCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs args) { if (ThemeCombo.ItemsSource != null && ThemeCombo.SelectedItem != null) Settings.Theme.Value = (string)ThemeCombo.SelectedItem; } private async void LogoutButton_OnClick(object sender, RoutedEventArgs args) { LogoutButton.IsEnabled = false; var playerId = OneSignal.GetPlayerId(); if (Settings.NotificationsEnabled.Value && playerId != null) { try { await OneSignal.SetSubscriptionAsync(false); await Client.Instance.SendAsync(new NotificationUnsubscriptionRequest(playerId)); } catch (Exception e) { Debug.WriteLine($"Failed to unsubscribe on logout: {e}"); } } Settings.LoggedIn.Value = false; Settings.Username.Value = null; Settings.Token.Value = null; Settings.NotificationsEnabled.Value = false; Settings.NotificationPattern.Value = ""; Client.Instance.Connection.Disconnect(); var rootFrame = (Frame)Window.Current.Content; rootFrame.Navigate(typeof(LoginPage)); } private async void NotificationToggleSwitch_OnToggled(object sender, RoutedEventArgs args) { if (_settingNotificationToggleSwitch) { _settingNotificationToggleSwitch = false; return; } var enabled = NotificationToggleSwitch.IsOn; try { var playerId = OneSignal.GetPlayerId(); if (playerId == null) { await App.ShowMessage("Device token is not available."); return; } if (string.IsNullOrEmpty(NotificationPatternText.Text)) NotificationPatternText.Text = Client.Instance.Name; NotificationToggleSwitch.IsEnabled = false; try { await OneSignal.SetSubscriptionAsync(enabled); } catch { await App.ShowMessage("Failed to toggle OneSignal subscription."); throw; } try { if (enabled) { await SaveNotificationPattern(playerId, NotificationPatternText.Text); } else { /* TODO: * unsubscribe causes a sysMessage error if we toggle within a few seconds * skipping this should be fine because onesignal won't push to us, and * rohbot will auto unsubscribe! */ //await Client.Instance.SendAsync(new NotificationUnsubscriptionRequest(playerId)); } } catch { await App.ShowMessage("Failed to toggle RohBot subscription."); throw; } Settings.NotificationsEnabled.Value = enabled; } catch (Exception e) { Debug.WriteLine($"Failed to toggle notifications: {e}"); _settingNotificationToggleSwitch = true; NotificationToggleSwitch.IsOn = !enabled; } NotificationToggleSwitch.IsEnabled = true; } private async void NotificationPatternSaveButton_OnClick(object sender, RoutedEventArgs args) { var playerId = OneSignal.GetPlayerId(); if (playerId == null) { await App.ShowMessage("Device token is not available."); return; } SetNotificationFormEnabled(false); try { await SaveNotificationPattern(playerId, NotificationPatternText.Text); } catch (Exception e) { await App.ShowMessage("Failed to save RohBot subscription."); Debug.WriteLine($"Failed to save notification regex: {e}"); } SetNotificationFormEnabled(true); } private static async Task SaveNotificationPattern(string playerId, string pattern) { await Client.Instance.SendAsync(new NotificationSubscriptionRequest(playerId, pattern)); Settings.NotificationPattern.Value = pattern; } private void SetNotificationFormEnabled(bool isEnabled) { NotificationToggleSwitch.IsEnabled = isEnabled; NotificationPatternSaveButton.IsEnabled = isEnabled; } } }
using Epsilon.Logic.Entities; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.ModelConfiguration; namespace Epsilon.Logic.SqlContext.Mapping { public class AdminAlertMap : EntityTypeConfiguration<AdminAlert> { public const int KEY_MAX_LENGTH = 128; public AdminAlertMap() { // Primary Key this.HasKey(x => x.Id); // Properties this.Property(x => x.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); this.Property(x => x.Key) .HasMaxLength(KEY_MAX_LENGTH) .IsRequired(); this.Property(x => x.SentOn) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed); // Indexes this.Property(x => x.SentOn) .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_AdminAlert_SentOn_Key", 1))); this.Property(x => x.Key) .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_AdminAlert_SentOn_Key", 2))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace RegistroVirtual.Attributes { public class SessionAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { return httpContext.Session["User"] != null; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectResult("/Login?returnUrl=" + HttpContext.Current.Request.Url); } } }
namespace AutoLotDAL2.Models { public class NewCar { public int CarID { get; set; } public string Color { get; set; } public string Make { get; set; } public string PetName { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LibSVMsharp.Helpers { public enum SVMNormType { L1 = 1, L2 = 2, L3 = 3, L4 = 4, L5 = 5 } public static class SVMProblemHelper { /// <summary> /// /// </summary> /// <param name="problem"></param> /// <returns></returns> public static SVMProblem RemoveDuplicates(SVMProblem problem) { SVMProblem temp = new SVMProblem(); for (int i = 0; i < problem.Length; i++) { bool same = false; for (int j = i + 1; j < problem.Length; j++) { same |= SVMNodeHelper.IsEqual(problem.X[i], problem.Y[i], problem.X[j], problem.Y[j]); if (same) { break; } } if (!same) { temp.Add(problem.X[i], problem.Y[i]); } } return temp; } /// <summary> /// /// </summary> /// <param name="problem"></param> /// <param name="type"></param> /// <returns></returns> public static SVMProblem Normalize(SVMProblem problem, SVMNormType type) { SVMProblem temp = new SVMProblem(); for (int i = 0; i < problem.Length; i++) { SVMNode[] x = SVMNodeHelper.Normalize(problem.X[i], type); temp.Add(x, problem.Y[i]); } return temp; } /// <summary> /// /// </summary> /// <param name="problem"></param> /// <returns></returns> public static Dictionary<double, int> GetLabelsCount(SVMProblem problem) { Dictionary<double, int> dic = new Dictionary<double, int>(); for (int i = 0; i < problem.Length; i++) { if (!dic.ContainsKey(problem.Y[i])) { dic.Add(problem.Y[i], 1); } else { dic[problem.Y[i]]++; } } return dic; } /// <summary> /// /// </summary> /// <param name="problem"></param> /// <param name="filename"></param> /// <returns></returns> public static bool Save(SVMProblem problem, string filename) { if (String.IsNullOrWhiteSpace(filename) || problem == null || problem.Length == 0) { return false; } NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; using (StreamWriter sw = new StreamWriter(filename)) { for (int i = 0; i < problem.Length; i++) { sw.Write(problem.Y[i]); if (problem.X[i].Length > 0) { sw.Write(" "); for (int j = 0; j < problem.X[i].Length; j++) { sw.Write(problem.X[i][j].Index); sw.Write(":"); sw.Write(problem.X[i][j].Value.ToString(provider)); if (j < problem.X[i].Length - 1) { sw.Write(" "); } } } sw.Write("\n"); } } return true; } /// <summary> /// /// </summary> /// <param name="filename"></param> /// <returns></returns> public static SVMProblem Load(string filename) { if (String.IsNullOrWhiteSpace(filename) || !File.Exists(filename)) { return null; } NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; SVMProblem problem = new SVMProblem(); using (StreamReader sr = new StreamReader(filename)) { while (true) { string line = sr.ReadLine(); if (line == null) break; string[] list = line.Trim().Split(' '); double y = Convert.ToDouble(list[0].Trim(), provider); List<SVMNode> nodes = new List<SVMNode>(); for (int i = 1; i < list.Length; i++) { string[] temp = list[i].Split(':'); SVMNode node = new SVMNode(); node.Index = Convert.ToInt32(temp[0].Trim()); node.Value = Convert.ToDouble(temp[1].Trim(), provider); nodes.Add(node); } problem.Add(nodes.ToArray(), y); } } return problem; } } }
using System; namespace GoRogue { // TODO: Potentially a crapton more utility stuff to add here. Probably Get around to it closer // to FOV/area of effect libs. /// <summary> /// Class representing different radius types. Similar in architecture to Coord in architecture /// -- it cannot be instantiated. Instead it simply has pre-allocated static variables for each /// type of radius, that should be used whenever a variable of type Radius is required. /// </summary> /// <remarks> /// Also contains utility functions to work with radius types, and is also implicitly convertible /// to the Distance class. /// </remarks> public class Radius { /// <summary> /// Radius is a circle around the center point. Shape that would represent movement radius in /// an 8-way movement scheme, with all movement cost the same based upon distance from the source. /// </summary> public static readonly Radius CIRCLE = new Radius(Types.CIRCLE); /// <summary> /// Radius is a cube around the center point. Similar to SQUARE in 2d shape. /// </summary> public static readonly Radius CUBE = new Radius(Types.CUBE); /// <summary> /// Radius is a diamond around the center point. Shape that would represent movement radius /// in a 4-way movement scheme. /// </summary> public static readonly Radius DIAMOND = new Radius(Types.DIAMOND); /// <summary> /// Radius is an octahedron around the center point. Similar to DIAMOND in 2d shape. /// </summary> public static readonly Radius OCTAHEDRON = new Radius(Types.OCTAHEDRON); /// <summary> /// Radius is a sphere around the center point. Similar to CIRCLE in 2d shape. /// </summary> public static readonly Radius SPHERE = new Radius(Types.SPHERE); /// <summary> /// Radius is a square around the center point. Shape that would represent movement radius in /// an 8-way movement scheme, with no additional cost on diagonal movement. /// </summary> public static readonly Radius SQUARE = new Radius(Types.SQUARE); /// <summary> /// Enum type corresponding to radius type being represented. /// </summary> public readonly Types Type; private static readonly string[] writeVals = Enum.GetNames(typeof(Types)); private Radius(Types type) { Type = type; } /// <summary> /// Enum representing Radius types. Useful for easy mapping of radius types to a primitive /// type (for cases like a switch statement). /// </summary> public enum Types { /// <summary> /// Type for Radius.SQUARE. /// </summary> SQUARE, /// <summary> /// Type for Radius.DIAMOND. /// </summary> DIAMOND, /// <summary> /// Type for Radius.CIRCLE. /// </summary> CIRCLE, /// <summary> /// Type for Radius.CUBE. /// </summary> CUBE, /// <summary> /// Type for Radius.OCTAHEDRON. /// </summary> OCTAHEDRON, /// <summary> /// Type for Radius.SPHERE. /// </summary> SPHERE }; /// <summary> /// Allows implicit casting to AdjacencyRule type. The rule corresponding to the proper /// definition of distance to create the Radius casted will be retrieved. /// </summary> /// <param name="radius">Radius type being casted.</param> public static implicit operator AdjacencyRule(Radius radius) { switch (radius.Type) { case Types.CIRCLE: case Types.SPHERE: case Types.SQUARE: case Types.CUBE: return AdjacencyRule.EIGHT_WAY; case Types.DIAMOND: case Types.OCTAHEDRON: return AdjacencyRule.CARDINALS; default: return null; // Will not occur } } /// <summary> /// Allows implicit casting to Distance type. The distance corresponding to the proper /// definition of distance to create the Radius casted will be retrieved. /// </summary> /// <param name="radius">Radius type being casted.</param> public static implicit operator Distance(Radius radius) { switch (radius.Type) { case Types.CIRCLE: case Types.SPHERE: return Distance.EUCLIDEAN; case Types.DIAMOND: case Types.OCTAHEDRON: return Distance.MANHATTAN; case Types.SQUARE: case Types.CUBE: return Distance.CHEBYSHEV; default: return null; // Will not occur } } /// <summary> /// Gets the Radius class instance representing the distance type specified. /// </summary> /// <param name="radiusType">The enum value for the distance method.</param> /// <returns>The radius class representing the given distance calculation.</returns> public static Radius ToRadius(Types radiusType) { switch (radiusType) { case Types.CIRCLE: return CIRCLE; case Types.CUBE: return CUBE; case Types.DIAMOND: return DIAMOND; case Types.OCTAHEDRON: return OCTAHEDRON; case Types.SPHERE: return SPHERE; case Types.SQUARE: return SQUARE; default: return null; // Will never occur } } /// <summary> /// Returns a string representation of the Radius. /// </summary> /// <returns>A string representation of the Radius.</returns> public override string ToString() => writeVals[(int)Type]; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Dogevents.Core.Domain; using Dogevents.Core.Helpers; using Dogevents.Core.Services; using Microsoft.AspNetCore.Mvc; namespace Dogevents.Web.Areas.Administration.Controllers { [Area("Administration")] public class FetchingController : Controller { private IEventsService _eventsService; private IFacebookService _facebookService; public FetchingController(IEventsService eventsService, IFacebookService facebookService) { _eventsService = eventsService; _facebookService = facebookService; } public IActionResult Index(IEnumerable<Feed> feeds) { return View(feeds); } public async Task<IActionResult> Fetch(DateTime since) { var feeds = await _facebookService.GetFeeds(since); return View("Index", feeds); } public async Task<IActionResult> AddFeeds(string[] feedLinks) { foreach (var link in feedLinks) { if (link.IsEmpty()) { //mark as wrong link, save somewhere, do something with that } var eventId = UrlParser.GetEventId(link); if (eventId.IsEmpty()) { //same as above ... continue; } try { var @event = await _facebookService.GetEventAsync(eventId); await _eventsService.Add(@event); } catch (Exception) { throw; } } return RedirectToAction("Index", "Events"); } } }
// <copyright file="KBInfoHelper.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Apps.ListSearch.Common.Helpers { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Teams.Apps.ListSearch.Common.Models; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; /// <summary> /// Helper class for accessing KB Info /// </summary> public class KBInfoHelper { private const int InsertSuccessResponseCode = 204; private readonly CloudTable cloudTable; private readonly Lazy<Task> initializeTask; /// <summary> /// Initializes a new instance of the <see cref="KBInfoHelper"/> class. /// </summary> /// <param name="connectionString">connection string of storage.</param> public KBInfoHelper(string connectionString) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); this.cloudTable = tableClient.GetTableReference(StorageInfo.KBInfoTableName); this.initializeTask = new Lazy<Task>(() => this.InitializeAsync()); } /// <summary> /// Get KB Info item from storage. /// </summary> /// <param name="kbId">Kb Id</param> /// <returns>Task that resolves to <see cref="KBInfo"/> object for the searched kbId.</returns> public async Task<KBInfo> GetKBInfo(string kbId) { await this.initializeTask.Value; TableOperation searchOperation = TableOperation.Retrieve<KBInfo>(StorageInfo.KBInfoTablePartitionKey, kbId); TableResult searchResult = await this.cloudTable.ExecuteAsync(searchOperation); return (KBInfo)searchResult.Result; } /// <summary> /// Returns all specified fields for entries from the table. /// </summary> /// <param name="fields">Fields to be retrieved.</param> /// <returns><see cref="Task"/> that resolves to <see cref="List{KBInfo}"/>.</returns> public async Task<List<KBInfo>> GetAllKBs(string[] fields) { await this.initializeTask.Value; List<KBInfo> kbList = new List<KBInfo>(); TableQuery<KBInfo> projectionQuery = new TableQuery<KBInfo>().Select(fields); TableContinuationToken token = null; do { TableQuerySegment<KBInfo> seg = await this.cloudTable.ExecuteQuerySegmentedAsync(projectionQuery, token); token = seg.ContinuationToken; kbList.AddRange(seg.Results); } while (token != null); return kbList; } /// <summary> /// Insert or merge KBInfo entity. /// </summary> /// <param name="kBInfo">Kb Info entity.</param> /// <returns><see cref="Task"/> that represents Insert or Merge function.</returns> public async Task InsertOrMergeKBInfo(KBInfo kBInfo) { await this.initializeTask.Value; TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(kBInfo); TableResult insertOrMergeResult = await this.cloudTable.ExecuteAsync(insertOrMergeOperation); if (insertOrMergeResult.HttpStatusCode != InsertSuccessResponseCode) { throw new Exception($"HTTP Error code - {insertOrMergeResult.HttpStatusCode}"); } } /// <summary> /// Deletes KB from KBInfo Storage table /// </summary> /// <param name="kbId">Kb id</param> /// <returns> representing the asynchronous operation</returns> public async Task DeleteKB(string kbId) { await this.initializeTask.Value; var entity = new DynamicTableEntity(StorageInfo.KBInfoTablePartitionKey, kbId); entity.ETag = "*"; await this.cloudTable.ExecuteAsync(TableOperation.Delete(entity)); } private async Task InitializeAsync() { await this.cloudTable.CreateIfNotExistsAsync(); } } }
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using Thrift; using Thrift.Collections; using System.Runtime.Serialization; public static class ZipkinCoreConstants { /// <summary> /// The client sent ("cs") a request to a server. There is only one send per /// span. For example, if there's a transport error, each attempt can be logged /// as a WIRE_SEND annotation. /// /// If chunking is involved, each chunk could be logged as a separate /// CLIENT_SEND_FRAGMENT in the same span. /// /// Annotation.host is not the server. It is the host which logged the send /// event, almost always the client. When logging CLIENT_SEND, instrumentation /// should also log the SERVER_ADDR. /// </summary> public const string CLIENT_SEND = "cs"; /// <summary> /// The client received ("cr") a response from a server. There is only one /// receive per span. For example, if duplicate responses were received, each /// can be logged as a WIRE_RECV annotation. /// /// If chunking is involved, each chunk could be logged as a separate /// CLIENT_RECV_FRAGMENT in the same span. /// /// Annotation.host is not the server. It is the host which logged the receive /// event, almost always the client. The actual endpoint of the server is /// recorded separately as SERVER_ADDR when CLIENT_SEND is logged. /// </summary> public const string CLIENT_RECV = "cr"; /// <summary> /// The server sent ("ss") a response to a client. There is only one response /// per span. If there's a transport error, each attempt can be logged as a /// WIRE_SEND annotation. /// /// Typically, a trace ends with a server send, so the last timestamp of a trace /// is often the timestamp of the root span's server send. /// /// If chunking is involved, each chunk could be logged as a separate /// SERVER_SEND_FRAGMENT in the same span. /// /// Annotation.host is not the client. It is the host which logged the send /// event, almost always the server. The actual endpoint of the client is /// recorded separately as CLIENT_ADDR when SERVER_RECV is logged. /// </summary> public const string SERVER_SEND = "ss"; /// <summary> /// The server received ("sr") a request from a client. There is only one /// request per span. For example, if duplicate responses were received, each /// can be logged as a WIRE_RECV annotation. /// /// Typically, a trace starts with a server receive, so the first timestamp of a /// trace is often the timestamp of the root span's server receive. /// /// If chunking is involved, each chunk could be logged as a separate /// SERVER_RECV_FRAGMENT in the same span. /// /// Annotation.host is not the client. It is the host which logged the receive /// event, almost always the server. When logging SERVER_RECV, instrumentation /// should also log the CLIENT_ADDR. /// </summary> public const string SERVER_RECV = "sr"; /// <summary> /// Optionally logs an attempt to send a message on the wire. Multiple wire send /// events could indicate network retries. A lag between client or server send /// and wire send might indicate queuing or processing delay. /// </summary> public const string WIRE_SEND = "ws"; /// <summary> /// Optionally logs an attempt to receive a message from the wire. Multiple wire /// receive events could indicate network retries. A lag between wire receive /// and client or server receive might indicate queuing or processing delay. /// </summary> public const string WIRE_RECV = "wr"; /// <summary> /// Optionally logs progress of a (CLIENT_SEND, WIRE_SEND). For example, this /// could be one chunk in a chunked request. /// </summary> public const string CLIENT_SEND_FRAGMENT = "csf"; /// <summary> /// Optionally logs progress of a (CLIENT_RECV, WIRE_RECV). For example, this /// could be one chunk in a chunked response. /// </summary> public const string CLIENT_RECV_FRAGMENT = "crf"; /// <summary> /// Optionally logs progress of a (SERVER_SEND, WIRE_SEND). For example, this /// could be one chunk in a chunked response. /// </summary> public const string SERVER_SEND_FRAGMENT = "ssf"; /// <summary> /// Optionally logs progress of a (SERVER_RECV, WIRE_RECV). For example, this /// could be one chunk in a chunked request. /// </summary> public const string SERVER_RECV_FRAGMENT = "srf"; /// <summary> /// The value of "lc" is the component or namespace of a local span. /// /// BinaryAnnotation.host adds service context needed to support queries. /// /// Local Component("lc") supports three key features: flagging, query by /// service and filtering Span.name by namespace. /// /// While structurally the same, local spans are fundamentally different than /// RPC spans in how they should be interpreted. For example, zipkin v1 tools /// center on RPC latency and service graphs. Root local-spans are neither /// indicative of critical path RPC latency, nor have impact on the shape of a /// service graph. By flagging with "lc", tools can special-case local spans. /// /// Zipkin v1 Spans are unqueryable unless they can be indexed by service name. /// The only path to a service name is by (Binary)?Annotation.host.serviceName. /// By logging "lc", a local span can be queried even if no other annotations /// are logged. /// /// The value of "lc" is the namespace of Span.name. For example, it might be /// "finatra2", for a span named "bootstrap". "lc" allows you to resolves /// conflicts for the same Span.name, for example "finatra/bootstrap" vs /// "finch/bootstrap". Using local component, you'd search for spans named /// "bootstrap" where "lc=finch" /// </summary> public const string LOCAL_COMPONENT = "lc"; /// <summary> /// Indicates a client address ("ca") in a span. Most likely, there's only one. /// Multiple addresses are possible when a client changes its ip or port within /// a span. /// </summary> public const string CLIENT_ADDR = "ca"; /// <summary> /// Indicates a server address ("sa") in a span. Most likely, there's only one. /// Multiple addresses are possible when a client is redirected, or fails to a /// different server ip or port. /// </summary> public const string SERVER_ADDR = "sa"; }
// Licensed under the MIT License. See LICENSE in the project root for license information. namespace Crayon { /// <summary> /// Defaults used across Crayon. /// </summary> public static class Defaults { public const float _duration = 0.8f; public const Easing _easing = Easing.Linear; public const string _cubicBezier = ""; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; namespace Alloclave { internal partial class AllocationForm : ToolForm { AddressSpaceScroller_OGL AddressSpaceScroller; RenderManager_OGL RenderManager = new RenderManager_OGL(); Diff Diff; public enum DiffMode { Left, Middle, Right } private AllocationForm() { InitializeComponent(); AddressSpaceControl.Renderer = new AddressSpaceRenderer_OGL(AddressSpaceControl, RenderManager); TopLevel = false; this.SizeChanged += AllocationForm_SizeChanged; } public AllocationForm(History history) : this() { history.Scrubber = MainScrubber; MainScrubber.MousePressed += ((object sender, MouseEventArgs e) => Scrubber_MouseDown(history, e)); MainScrubber.MouseReleased += ((object sender, MouseEventArgs e) => Scrubber_MouseUp(history, e)); SetupScroller(history); // Disabled by default - gets enabled when data comes in this.Enabled = false; AddressSpaceControl.PauseChanged += AddressSpaceControl_PauseChanged; AddressSpaceControl.History = history; } public AllocationForm(Diff diff, int startWidth) : this() { Diff = diff; RenderManager.Rebuild(Diff.Difference, startWidth); SetupScroller(new History(diff.Difference)); } private void SetupScroller(History history) { this.AddressSpaceScroller = new Alloclave.AddressSpaceScroller_OGL(history, RenderManager, AddressSpaceControl.Width); this.AddressSpaceScroller.Dock = System.Windows.Forms.DockStyle.Fill; this.AddressSpaceScroller.Location = new System.Drawing.Point(679, 6); this.AddressSpaceScroller.Name = "AddressSpaceScroller"; this.AddressSpaceScroller.Size = new System.Drawing.Size(44, 436); this.AddressSpaceScroller.TabIndex = 5; this.AddressSpaceScroller.FocusChanged += addressSpaceScroller_FocusChanged; this.AddressSpaceScroller.Margin = new System.Windows.Forms.Padding(1); this.TableLayoutPanel.Controls.Add(this.AddressSpaceScroller, 2, 0); } public void SetDiffMode(DiffMode mode) { switch (mode) { case DiffMode.Left: RenderManager.Rebuild(Diff.Left, AddressSpaceControl.Width); AddressSpaceControl.SnapshotOverride = Diff.Left; break; case DiffMode.Middle: RenderManager.Rebuild(Diff.Difference, AddressSpaceControl.Width); AddressSpaceControl.SnapshotOverride = Diff.Difference; break; case DiffMode.Right: RenderManager.Rebuild(Diff.Right, AddressSpaceControl.Width); AddressSpaceControl.SnapshotOverride = Diff.Right; break; } } void AllocationForm_SizeChanged(object sender, EventArgs e) { if (AddressSpaceScroller != null) { AddressSpaceScroller.ParentWidth = AddressSpaceControl.Width; } } void addressSpaceScroller_FocusChanged(object sender, MouseEventArgs e) { AddressSpaceControl.CenterAt(e.Location.ToVector()); } void PlayPausePictureBox_Click(object sender, System.EventArgs e) { AddressSpaceControl.IsPaused = !AddressSpaceControl.IsPaused; if (AddressSpaceControl.IsPaused) { PlayPausePictureBox.Image = Properties.Resources.play; } else { PlayPausePictureBox.Image = Properties.Resources.pause; } } void AddressSpaceControl_PauseChanged(object sender, EventArgs e) { if (AddressSpaceControl.IsPaused) { PlayPausePictureBox.Image = Properties.Resources.play; } else { PlayPausePictureBox.Image = Properties.Resources.pause; } } void Scrubber_MouseDown(object sender, MouseEventArgs e) { History history = sender as History; history.ArtificialMaxTime = history.TimeRange.Max; AddressSpaceControl.IsPaused = true; } void Scrubber_MouseUp(object sender, MouseEventArgs e) { History history = sender as History; history.ArtificialMaxTime = 0; history.UpdateSnapshotAsync(history.Snapshot); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using BenchmarkDotNet.Running; using Newtonsoft.Json; using System; using System.IO; namespace Microsoft.Data.SqlClient.PerformanceTests { public class Program { private static Config s_config; public static void Main() { // Load config file s_config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("runnerconfig.json")); if (s_config.UseManagedSniOnWindows) { AppContext.SetSwitch("Switch.Microsoft.Data.SqlClient.UseManagedNetworkingOnWindows", true); } Run_SqlConnectionBenchmark(); Run_SqlCommandBenchmark(); Run_SqlBulkCopyBenchmark(); Run_DataTypeReaderBenchmark(); Run_DataTypeReaderAsyncBenchmark(); // TODOs: // Transactions // Insert/Update queries (+CRUD) // Prepared/Regular Parameterized queries // DataType Reader Max (large size / max columns / million row tables) // DataType conversions (Implicit) // MARS enabled // Always Encrypted } private static void Run_SqlConnectionBenchmark() { if (s_config.Benchmarks.SqlConnectionRunnerConfig?.Enabled == true) { BenchmarkRunner.Run<SqlConnectionRunner>(BenchmarkConfig.s_instance(s_config.Benchmarks.SqlConnectionRunnerConfig)); } } private static void Run_SqlCommandBenchmark() { if (s_config.Benchmarks.SqlCommandRunnerConfig?.Enabled == true) { BenchmarkRunner.Run<SqlCommandRunner>(BenchmarkConfig.s_instance(s_config.Benchmarks.SqlCommandRunnerConfig)); } } private static void Run_DataTypeReaderBenchmark() { if (s_config.Benchmarks.DataTypeReaderRunnerConfig?.Enabled == true) { BenchmarkRunner.Run<DataTypeReaderRunner>(BenchmarkConfig.s_instance(s_config.Benchmarks.DataTypeReaderRunnerConfig)); } } private static void Run_DataTypeReaderAsyncBenchmark() { if (s_config.Benchmarks.DataTypeReaderAsyncRunnerConfig?.Enabled == true) { BenchmarkRunner.Run<DataTypeReaderAsyncRunner>(BenchmarkConfig.s_instance(s_config.Benchmarks.DataTypeReaderAsyncRunnerConfig)); } } private static void Run_SqlBulkCopyBenchmark() { if (s_config.Benchmarks.SqlBulkCopyRunnerConfig?.Enabled == true) { BenchmarkRunner.Run<SqlBulkCopyRunner>(BenchmarkConfig.s_instance(s_config.Benchmarks.SqlBulkCopyRunnerConfig)); } } } }
using System; using System.Collections.Generic; using System.Linq; using Ludeo.BingWallpaper.Model.Bing; using Ludeo.BingWallpaper.Service.Bing; namespace Ludeo.BingWallpaper.Model.Cache { internal static class Mapper { internal static IEnumerable<CachedImage> Map(ImageArchive wallpaperImageArchive) => wallpaperImageArchive.Images.Select(Map); private static CachedImage Map(Image wallpaperImage) => new CachedImage { PartitionKey = CachedImage.DefaultPartitionKey, RowKey = MapRowKey(wallpaperImage.StartDate), Copyright = wallpaperImage.Copyright, Title = wallpaperImage.Title, Uri = MapUri(wallpaperImage.UrlBase), }; private static string MapRowKey(string? startDateString) { if (int.TryParse(startDateString, out var startDateInt)) { // set cache RowKey to have most recent items on top return (99999999 - startDateInt).ToString(); } return DateTime.Now.ToString("yyyyMMdd"); } private static string MapUri(string? relativeUrl) => new Uri(WallpaperService.bingHomepageUri, relativeUrl).AbsoluteUri.ToString(); } }
using AllegianceInterop; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Wopr; using Wopr.Constants; using Wopr.Loadouts; namespace Wopr.Strategies { public class ScoutExploreMap : StrategyBase { private const int SweepHopCount = 10; // The number of waypoint hops a scout will make when doing an orbit of a sector scanning for stuff. // Increasing this value makes the circle smoother, but it also slows down the ship! private int _currentSectorID = -1; private bool _isSweeping = false; private IclusterIGCWrapper _navigatingToCluster = null; private bool _waitingForLaunchToComplete = false; //private bool _sweepLeft = false; //private bool _sweepRight = false; //private double _currentAngleInRadians; //private double _startingAngleInRadians; //private double _totalRadiansTraversed; //private VectorWrapper _startingPoint; //private int _currentSweepHop = 0; public ScoutExploreMap() : base(Wopr.Constants.StrategyID.ScoutExploreMap, TimeSpan.MaxValue) { } public override void AttachMessages(MessageReceiver messageReceiver, string botAuthenticationGuid, string playerName, int sideIndex, bool isGameController, bool isCommander) { Log("AttachMessages"); messageReceiver.FMD_S_SET_CLUSTER += MessageReceiver_FMD_S_SET_CLUSTER; messageReceiver.FMD_S_SINGLE_SHIP_UPDATE += MessageReceiver_FMD_S_SINGLE_SHIP_UPDATE; messageReceiver.FMD_S_SHIP_STATUS += MessageReceiver_FMD_S_SHIP_STATUS; messageReceiver.FMD_S_DOCKED += MessageReceiver_FMD_S_DOCKED; messageReceiver.FMD_CS_CHATMESSAGE += MessageReceiver_FMD_CS_CHATMESSAGE; } private void MessageReceiver_FMD_CS_CHATMESSAGE(ClientConnection client, AllegianceInterop.FMD_CS_CHATMESSAGE message) { var ship = ClientConnection.GetShip(); if (message.Message.Equals("die") == true) { AllegianceInterop.FMD_C_SUICIDE suicide = new AllegianceInterop.FMD_C_SUICIDE(); client.SendMessageServer(suicide); } } private void MessageReceiver_FMD_S_DOCKED(ClientConnection client, AllegianceInterop.FMD_S_DOCKED message) { Log("MessageReceiver_FMD_S_DOCKED"); if (_waitingForLaunchToComplete == true) { Log("\tA launch is already in progress, skipping message."); return; } var ship = ClientConnection.GetShip(); var station = ship.GetStation(); // If we are in a station, then get into a scout and get out there. if (station != null) { // Mark the current sector as invalid so that we will aquire a new destination on launch. _currentSectorID = -1; Log("\tDocked at station, changing ship to scout and relaunching."); ChangeShip(ShipType.Scout, new ScoutProbeLoadout()); return; } } private void MessageReceiver_FMD_S_SHIP_STATUS(ClientConnection client, AllegianceInterop.FMD_S_SHIP_STATUS message) { var ship = ClientConnection.GetShip(); var station = ship.GetStation(); // Ignore messages that are not for us. if (message.shipID != ship.GetObjectID()) return; // Ignore messages until we actually get into a sector if (ship.GetCluster() == null) return; Log($"MessageReceiver_FMD_S_SHIP_STATUS: my ship id = {ship.GetObjectID()}, message.shipID = {message.shipID}, message.status.GetSectorID(): {message.status.GetSectorID()}"); string shipName = ship.GetName(); //UpdateUnexploredWarpsList(); // If we are in a station, then get into a scout and get out there. if (station != null) { if (_waitingForLaunchToComplete == false) { Log("\tI'm sitting in base? Time to launch a scout!"); ChangeShip(ShipType.Scout, new ScoutProbeLoadout()); return; } } else { _waitingForLaunchToComplete = false; } if (IsCurrentShipAScout() == false) { Log("\tI'm not in a scout... returning to base."); ReturnToBase(); return; } // If we don't have any command and the ship is stopped, reset and get moving! if ((CommandID)ship.GetCommandID((sbyte)CommandType.c_cmdCurrent) <= CommandID.c_cidNone && ship.GetVelocity().Length() == 0) { Log($"\tWe're stopped with no command. Resetting current variables, and selecting a new destination. _currentSectorID: {_currentSectorID}, _isSweeping: {_isSweeping}, _navigatingToCluster: {_navigatingToCluster}, _waitingForLaunchToComplete: {_waitingForLaunchToComplete}"); _currentSectorID = -1; _isSweeping = false; _navigatingToCluster = null; _waitingForLaunchToComplete = false; //return; } // If we are already moving, and this status message is for our current sector, or we are already sweeping, then ignore it. if (ship.GetVelocity().Length() > 0 && (message.status.GetSectorID() == _currentSectorID || _isSweeping == true)) { Log($"\tSkipping message: ship.GetVelocity(): {ship.GetVelocity().Length()}, ship.GetCluster() = {ship.GetCluster()?.GetName()}, message.status.GetSectorID() = {message.status.GetSectorID()}, _currentSectorID = {_currentSectorID}, _isSweeping = {_isSweeping}"); return; } // These clusters still need to be explored. var currentUnexploredClusters = GameInfo.GetUnexploredClusters(client.GetCore()); // Are we on the way to another cluster to explore? if (_navigatingToCluster != null) { // If we are not at the destination yet... if (_navigatingToCluster.GetObjectID() != ship.GetCluster().GetObjectID()) { // And our destination cluster still hasn't been explored... if (currentUnexploredClusters.ContainsKey(_navigatingToCluster.GetObjectID()) == true) { Log($"\tEntered cluster: {ship.GetCluster().GetName()}, continuing on route to {_navigatingToCluster.GetName()}"); return; } else // The detination was explored by someone else, let's find a new destination. { Log($"\tArrived at cluster: {ship.GetCluster().GetName()}, but destination cluster {_navigatingToCluster.GetName()} has already been swept. Cancelling navigation, checking for next step."); _navigatingToCluster = null; } } else // We've arrived, let's see what we need to do next. { Log($"\tArrived at cluster: {ship.GetCluster().GetName()}, checking for next step."); _navigatingToCluster = null; } } _currentSectorID = message.status.GetSectorID(); var otherFriendlyScoutShips = ship.GetCluster().GetShips().Where(p => p.GetObjectID() != ship.GetObjectID() && p.GetBaseHullType().GetName().Contains("Scout") == true && p.GetSide().GetObjectID() == ship.GetSide().GetObjectID()); //var otherSweepingScoutShips = otherFriendlyScoutShips.Where(p => p.GetCommandTarget((sbyte)CommandType.c_cmdCurrent)?.GetObjectType() == (short)ObjectType.OT_buoy); var sweepingScoutCount = GameInfo.GetSweepingScoutCount(ship.GetCluster()); Log($"\totherFriendlyScoutShips: {otherFriendlyScoutShips.Count()}, otherSweepingScoutShips: {sweepingScoutCount}, is unexplored: {currentUnexploredClusters.ContainsKey(ship.GetCluster().GetObjectID())} "); // Ship has entered a cluster, find the next target and start scouting. // If cluster is unexplored, and less than 2 ships sweeping, start sweeping if (currentUnexploredClusters.ContainsKey(ship.GetCluster().GetObjectID()) == true && sweepingScoutCount < 2) SweepCluster(); // If there are two ships sweeping, fly to a point 1/3 of the angle we entered in at, and wait for alephs to appear. else if (sweepingScoutCount >= 2) FlyToStationPointAndWaitForAelphs(); // If there are no ships sweeping, go to the next system. else SelectNextAelphTarget(); //var mission = ship.GetMission(); //var warps = mission.GetWarps(); //// Get all the clusters that are available in the mission. //var missionClusters = mission.GetClusters(); //var currentShipCluster = ship.GetCluster(); //var currentMissionCluster = missionClusters.FirstOrDefault(p => p.GetObjectID() == currentShipCluster.GetObjectID()); //var shipVisibleWarps = currentShipCluster.GetWarps(); //var allWarpsInCluster = currentMissionCluster.GetWarps(); } //private void UpdateUnexploredWarpsList() //{ // Log("\tUpdateUnexploredWarpsList()"); // //var ship = _client.GetShip(); // var unexploredWarps = ClientConnection.GetCore().GetWarps().Where(p => p.GetDestination().GetCluster().GetAsteroids().Count == 0 && GameInfo.UnexploredClustersByObjectID.ContainsKey(p.GetDestination().GetCluster().GetObjectID()) == false); // foreach (var unexploredWarp in unexploredWarps) // { // Log($"\t\tFound unexplored cluster: {unexploredWarp.GetDestination().GetCluster().GetName()}, adding cluster's id to the GameInfo.UnexploredClustersByObjectID list."); // lock (GameInfo.UnexploredClustersByObjectID) // { // if(GameInfo.UnexploredClustersByObjectID.ContainsKey(unexploredWarp.GetDestination().GetCluster().GetObjectID()) == false) // GameInfo.UnexploredClustersByObjectID.Add(unexploredWarp.GetDestination().GetCluster().GetObjectID(), unexploredWarp.GetDestination().GetCluster().GetName()); // } // } // StringBuilder s = new StringBuilder(); // foreach (var unexploredClusterName in GameInfo.UnexploredClustersByObjectID.Values) // s.Append(unexploredClusterName + " "); // Log("\t\tCurrent unexplored clusters: " + s.ToString()); //} private void FlyToStationPointAndWaitForAelphs() { Log("\tFlyToStationPointAndWaitForAelphs"); var ship = ClientConnection.GetShip(); var centerPoint = new VectorWrapper(0, 0, 0); var shipPosition = ship.GetPosition(); var startingPoint = shipPosition; var startingAngleInRadians = shipPosition.AngleInRadians(centerPoint); // 1/3 of 360 degrees in radians. double oneThirdAngle = Math.PI * 2 / 3; // Move to a new point 1/3 or 2/3 of the total angle and the same distance as the entry aleph. double newAngle = startingAngleInRadians + (oneThirdAngle * _random.Next(1, 3)); VectorWrapper nextPoint = new VectorWrapper((startingPoint - centerPoint).Length() * (float)Math.Cos(newAngle), (startingPoint - centerPoint).Length() * (float)Math.Sin(newAngle), 0); var buoy = ClientConnection.CreateBuoy((sbyte)BuoyType.c_buoyWaypoint, nextPoint.X(), nextPoint.Y(), nextPoint.Z(), ship.GetCluster().GetObjectID(), true); var command = ship.GetDefaultOrder(buoy); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, buoy, command); ship.SetAutopilot(true); //List<int> consideredWarpObjectIDs = new List<int>(); // Wait for Aelphs to appear. Task.Run(() => { try { _runningTasks++; var currentUnexploredClusters = GameInfo.GetUnexploredClusters(ClientConnection.GetCore()); bool foundNewWarp = false; bool updatedUnexploredClusterListAfterMove = false; for (int i = 0; i < 120 * 100 && _cancellationTokenSource.IsCancellationRequested == false && foundNewWarp == false; i++) { var otherScoutShips = ship.GetCluster().GetShips().Where(p => p.GetObjectID() != ship.GetObjectID() && p.GetBaseHullType().GetName().Contains("Scout") == true); //var otherSweepingScoutShips = otherScoutShips.Where(p => p.GetCommandTarget((sbyte)CommandType.c_cmdCurrent)?.GetObjectType() == (short)ObjectType.OT_buoy); int sweepingScoutCount = GameInfo.GetSweepingScoutCount(ship.GetCluster()); if (i % 500 == 0) { Log($"\t\tWaiting for Alephs to be found: {i}."); // Once we get within 400 of the waypoint, update the unexplored clusters list in case we happen to have found a new unexplored cluster. if (updatedUnexploredClusterListAfterMove == false && (nextPoint - ship.GetPosition()).LengthSquared() < Math.Pow(400, 2)) { Log("\t\tUpdating unexplored cluster list after ship move."); currentUnexploredClusters = GameInfo.GetUnexploredClusters(ClientConnection.GetCore()); updatedUnexploredClusterListAfterMove = true; } } var newWarps = ship.GetCluster().GetWarps().Where(p => currentUnexploredClusters.ContainsKey((p?.GetDestination()?.GetCluster()?.GetObjectID()).GetValueOrDefault(-1)) == true /*&& consideredWarpObjectIDs.Contains(p.GetObjectID()) == false*/); if (newWarps.Count() > 0) { foreach (var newWarp in newWarps) { // If there are other non-sweeping ships in the sector, then only 33% of those ships should go to the newly visible aelph. if (otherScoutShips.Count() - sweepingScoutCount > 0) { if (_random.Next(0, 100) < 33) { Log($"\t\tWarp found, 33% chance success, heading to {newWarp.GetName()}"); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, newWarp, (sbyte)CommandID.c_cidGoto); ship.SetAutopilot(true); foundNewWarp = true; break; } } else // We are the only non-sweeping scout in the cluster, go to the new warp. { Log($"\t\tWarp found, heading to {newWarp.GetName()}"); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, newWarp, (sbyte)CommandID.c_cidGoto); ship.SetAutopilot(true); foundNewWarp = true; break; } } } // If the cluster gets marked as explored and no new unexplored alephs were found, then just move on. if (currentUnexploredClusters.ContainsKey(ship.GetCluster().GetObjectID()) == false) { Log("\t\tCluster marked as explored, moving on."); break; } Thread.Sleep(100); } if (foundNewWarp == false) { Log("\t\tNo aelph was found, heading to next available warp."); SelectNextAelphTarget(); } } finally { _runningTasks--; } }); } private void SweepCluster() { Log("\tSweepCluster()"); _isSweeping = true; var ship = ClientConnection.GetShip(); var otherScoutShips = ship.GetCluster().GetShips().Where(p => p.GetObjectID() != ship.GetObjectID() && p.GetBaseHullType().GetName().Contains("Scout") == true); var centerPoint = new VectorWrapper(0, 0, 0); var shipPosition = ship.GetPosition(); var startingPoint = shipPosition; var startingAngleInRadians = shipPosition.AngleInRadians(centerPoint); double nextSliceWidth = (Math.PI * 2 / SweepHopCount); double currentAngleInRadians = startingAngleInRadians; Task.Run(() => { try { int currentSweepingScoutCount = GameInfo.IncrementSweepingScoutCount(ship.GetCluster()); //bool sweepLeft = currentSweepingScoutCount > 0; _runningTasks++; bool sweepComplete = true; int hopCount = SweepHopCount; bool hopCountReduced = false; // Changes to true when a second scout starts sweeping. bool firstSweepingScout = currentSweepingScoutCount == 1; // This is somewhat specific to hihigher, but we will assume that any cluster has an average of 3 warps and a station cluster has 4. // This lets a scout stop sweeping early if all clusters are assumed to be found. int targetWarpCount = 3 + ship.GetCluster().GetStations().Count; for (int i = 1; i < hopCount - 2 // Skip the first hop and the last 2 hops, aelphs won't be that close together. && _cancellationTokenSource.IsCancellationRequested == false && ship.GetCluster().GetWarps().Count < targetWarpCount; // If we find enough warps, we will consider this cluster scanned. If there are more warp clusters will be covered when the other cluster is discovered from the other side. Otherwise, it's up to the humans! i++) { // If another scout starts sweeping, then reduce the hop count by half so that we get done quicker. The other scout will start sweeping from the other direction. if (hopCountReduced == false && GameInfo.GetSweepingScoutCount(ship.GetCluster()) >= 2) { Log($"\t\tA second scout is also sweeping, reducing the hop count to half."); hopCount = (SweepHopCount / 2) + 3; // Go a little farther so that the paths overlap. It's the classic pincer manuver!! } if (firstSweepingScout == true) currentAngleInRadians += nextSliceWidth; else currentAngleInRadians -= nextSliceWidth; VectorWrapper nextPoint = new VectorWrapper((startingPoint - centerPoint).Length() * (float)Math.Cos(currentAngleInRadians), (startingPoint - centerPoint).Length() * (float)Math.Sin(currentAngleInRadians), 0); Log($"\t\tnextPoint: {nextPoint.GetString()}, currentAngleInRadians: {currentAngleInRadians}, sweepHop: {i}, firstSweepingScout: {firstSweepingScout}, target hopCount: {hopCount - 2}"); var buoy = ClientConnection.CreateBuoy((sbyte)BuoyType.c_buoyWaypoint, nextPoint.X(), nextPoint.Y(), nextPoint.Z(), ship.GetCluster().GetObjectID(), true); var command = ship.GetDefaultOrder(buoy); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, buoy, command); ship.SetAutopilot(true); bool reachedWaypoint = false; for (int j = 0; j < 60 * 100 && _cancellationTokenSource.IsCancellationRequested == false; j++) { VectorWrapper difference = nextPoint - ship.GetPosition(); if(j % 500 == 0) Log($"\t\tCurrent distance: {Math.Abs(difference.Length())}, iterations: {j}, {nextPoint.GetString()}, ship velocity: {ship.GetVelocity().Length()}"); if ((nextPoint - ship.GetPosition()).LengthSquared() < Math.Pow(600, 2)) { Log($"\t\tReached waypoint: {nextPoint.GetString()}, ship velocity: {ship.GetVelocity().Length()}"); reachedWaypoint = true; break; } Thread.Sleep(100); } // We didn't reach the waypoint in one minute. Something went wrong, let's just move on. if (reachedWaypoint == false) { sweepComplete = false; Log("\t\tNo waypoint was found in 120 seconds."); break; } } if (sweepComplete == true) { currentSweepingScoutCount = GameInfo.GetSweepingScoutCount(ship.GetCluster()); // If there is more than one sweeping scout, then the second scout will perform the removal of the scanned cluster. if (firstSweepingScout == false || currentSweepingScoutCount == 1) { var currentUnexploredClusters = GameInfo.GetUnexploredClusters(ClientConnection.GetCore()); if (currentUnexploredClusters.ContainsKey(ship.GetCluster().GetObjectID()) == true) { Log("Initial sweep complete, but we didn't find everything. TODO: take a closer look?"); DoTargetedSweep(ship); } else { Log($"\t\tCluster exploration complete for {ship.GetCluster().GetName()}, this cluster is no longer in the unexplored list."); //GameInfo.UnexploredClustersByObjectID.Remove(ship.GetCluster().GetObjectID()); //UpdateUnexploredWarpsList(); } } else { Log($"\t\tCluster exploration complete for {ship.GetCluster().GetName()} for first sweeping scout."); } } SelectNextAelphTarget(); } finally { _runningTasks--; _isSweeping = false; GameInfo.DecrementSweepingScoutCount(ship.GetCluster()); } }); //_startingPoint = shipPosition; //_startingAngleInRadians = shipPosition.AngleInRadians(centerPoint); //if (_startingAngleInRadians < 0) // _startingAngleInRadians = _startingAngleInRadians + 2 * Math.PI; //_currentAngleInRadians = _startingAngleInRadians; //// If there are no scouts, sweep left, otherwise if there is already a scount, then sweep right, otherwise, locate a new aleph and go there! //if (otherScoutShips.Count() == 0) //{ // _sweepLeft = true; // NavigateToNextSweepPoint(); //} //else if (otherScoutShips.Count() == 1) //{ // _sweepRight = true; // NavigateToNextSweepPoint(); //} //else //{ // _sweepRight = false; // _sweepLeft = false; // SelectNextAelphTarget(); //} } private void DoTargetedSweep(IshipIGCWrapper ship) { Log("DoTargetedSweep(): Find the missing aleph using triangulation on the other alephs."); } //private void NavigateToNextSweepPoint() //{ // var ship = _client.GetShip(); // double nextSliceWidth = (Math.PI * 2 / 16); // double nextSlice = nextSliceWidth; // if (_sweepLeft == true) // { // nextSlice = _currentAngleInRadians + nextSliceWidth; // if (nextSlice > Math.PI * 2) // nextSlice -= Math.PI * 2; // } // else // { // nextSlice = _currentAngleInRadians - nextSliceWidth; // if (nextSlice < 0) // nextSlice += Math.PI * 2; // } // // Don't travel the last slice. // if (_totalRadiansTraversed + nextSliceWidth >= Math.PI * 2) // SelectNextAelphTarget(); // _totalRadiansTraversed += nextSliceWidth; // var centerPoint = new VectorWrapper(0, 0, 0); // VectorWrapper nextPoint = new VectorWrapper((_startingPoint - centerPoint).Length() * (float) Math.Cos(nextSlice), (_startingPoint - centerPoint).Length() * (float) Math.Sin(nextSlice), 0); // var buoy = _client.CreateBuoy((sbyte)BuoyType.c_buoyWaypoint, nextPoint.X(), nextPoint.Y(), nextPoint.Z(), ship.GetCluster().GetObjectID(), true); // var command = ship.GetDefaultOrder(buoy); // ship.SetCommand((sbyte)CommandType.c_cmdCurrent, buoy, command); // ship.SetAutopilot(true); //} private void SelectNextAelphTarget() { Log("\tSelectNextAelphTarget()"); var ship = ClientConnection.GetShip(); var visibleWarps = ship.GetCluster().GetWarps(); var otherFriendlyScoutShips = ship.GetCluster().GetShips().Where(p => p.GetObjectID() != ship.GetObjectID() && p.GetBaseHullType().GetName().Contains("Scout") == true && p.GetSide().GetObjectID() == ship.GetSide().GetObjectID()); bool foundTargetWarp = false; var currentUnexploredClusters = GameInfo.GetUnexploredClusters(ClientConnection.GetCore()); // When launching from home, just pick a target at random so that all clusters get some love. if (ship.GetCluster().GetHomeSector() == false) { foreach (var visibleWarp in visibleWarps.Where(p => currentUnexploredClusters.ContainsKey(p.GetDestination().GetCluster().GetObjectID()) == true).OrderBy(p => ClientConnection.GetDistanceSquared(p, ship))) { if (currentUnexploredClusters.ContainsKey(visibleWarp.GetDestination().GetCluster().GetObjectID()) == true) { Log($"\t\tUnexplored Warp found: {visibleWarp.GetName()}"); float myDistance = ClientConnection.GetDistanceSquared(ship, visibleWarp); bool isAnotherScoutCloser = false; foreach (var otherScoutShip in otherFriendlyScoutShips) { float otherScoutDistance = ClientConnection.GetDistanceSquared(otherScoutShip, visibleWarp); if (otherScoutDistance < myDistance) { Log($"\t\tAnother scout: {otherScoutShip.GetName()} is already closer to: {visibleWarp.GetName()}, looking for another target."); isAnotherScoutCloser = true; break; } } // The cluster is on the unexplored list, and there's no other scout that is closer, let's go for it! if (isAnotherScoutCloser == false) { Log($"\t\tFound target warp, going to {visibleWarp.GetName()}"); foundTargetWarp = true; ship.SetCommand((sbyte)CommandType.c_cmdCurrent, visibleWarp, (sbyte)CommandID.c_cidGoto); ship.SetAutopilot(true); break; } } } } if (foundTargetWarp == false) { Log($"\t\tNo target warp found, selecting a visible warp at random."); currentUnexploredClusters = GameInfo.GetUnexploredClusters(ClientConnection.GetCore()); // Pick a random warp that is unexplored. var unvisitedWarps = visibleWarps.Where(p => currentUnexploredClusters.ContainsKey(p.GetDestination().GetCluster().GetObjectID()) == true).ToList(); if (unvisitedWarps.Count > 0) { var targetWarp = unvisitedWarps[_random.Next(0, unvisitedWarps.Count)]; Log($"\t\tFound unvisited random warp, going to: {targetWarp.GetName()}"); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, targetWarp, (sbyte)CommandID.c_cidGoto); ship.SetAutopilot(true); foundTargetWarp = true; } } // Couldn't find any immediately linked clusters, so find the nearest unexplored cluster and go to it. if (foundTargetWarp == false) { IclusterIGCWrapper nearestCluster = FindNearestUnexploredCluster(); if (nearestCluster != null) { Log($"\t\tFound an unexplored cluster {nearestCluster.GetName()}, navigating to it."); var buoy = ClientConnection.CreateBuoy((sbyte)BuoyType.c_buoyWaypoint, 0, 0, 0, nearestCluster.GetObjectID(), true); var command = ship.GetDefaultOrder(buoy); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, buoy, command); ship.SetAutopilot(true); _navigatingToCluster = nearestCluster; foundTargetWarp = true; } } // All the immediate warps have been visited or have other scouts closer, just pick one at random. if (foundTargetWarp == false) { var targetWarp = visibleWarps[_random.Next(0, visibleWarps.Count)]; Log($"\t\tFound visited random warp, going to: {targetWarp.GetName()}"); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, targetWarp, (sbyte)CommandID.c_cidGoto); ship.SetAutopilot(true); foundTargetWarp = true; } } private IclusterIGCWrapper FindNearestUnexploredCluster() { IclusterIGCWrapper nearestCluster = null; int nearestClusterDistance = int.MaxValue; var currentUnexploredClusters = GameInfo.GetUnexploredClusters(ClientConnection.GetCore()); foreach (var unexploredClusterObjectID in currentUnexploredClusters.Keys) { var fromCluster = ClientConnection.GetShip().GetCluster(); var toCluster = ClientConnection.GetCore().GetCluster((short)unexploredClusterObjectID); DijkstraPathFinder pathFinder = new DijkstraPathFinder(ClientConnection.GetCore(), fromCluster, toCluster); int distance = pathFinder.GetDistance(fromCluster, toCluster); if (distance < nearestClusterDistance) nearestCluster = toCluster; } return nearestCluster; } private void MessageReceiver_FMD_S_SINGLE_SHIP_UPDATE(ClientConnection client, AllegianceInterop.FMD_S_SINGLE_SHIP_UPDATE message) { } private void MessageReceiver_FMD_S_SET_CLUSTER(AllegianceInterop.ClientConnection client, AllegianceInterop.FMD_S_SET_CLUSTER message) { } public override void Start() { var ship = ClientConnection.GetShip(); //var side = _client.GetSide(); //var mission = side.GetMission(); //var hullTypes = mission.GetHullTypes(); //var station = ship.GetStation(); // Wait for the ship to join a cluster or a station. //if (ship == null || (ship.GetCluster() == null && ship.GetStation() == null)) //{ // Log("Start(): Waiting 30 seconds for ship to join station or cluster."); // Task.Run(() => // { // for (int i = 0; i < 30 * 100; i++) // { // ship = ClientConnection.GetShip(); // if (ship?.GetCluster() != null || ship?.GetStation() != null) // break; // Thread.Sleep(100); // } // if (ship.GetStation() != null) // { // Log("\tStart(): We are in a station, changing ship to scout and launching."); // ChangeShip(ShipType.Scout, new ScoutProbeLoadout()); // } // else if (IsCurrentShipAScout() == false) // { // Log("\tStart(): We are not in a scout, returing to the nearest station."); // ReturnToBase(); // } // } // ); //} if (ship.GetStation() != null) { Log("\tStart(): We are in a station, changing ship to scout and launching."); ChangeShip(ShipType.Scout, new ScoutProbeLoadout()); } else if (IsCurrentShipAScout() == false) { Log("\tStart(): We are not in a scout, returing to the nearest station."); ReturnToBase(); } } private void ScoutSector() { var ship = ClientConnection.GetShip(); // If the ship is in a station, launch. if (ship.GetStation() != null) { // TODO: Transfer to desired station first. // Launch the ship //_client.BuyLoadout(ship, true); // Wait for the ship to enter the cluster. while (ship.GetCluster() == null) Thread.Sleep(100); } var mission = ship.GetMission(); // Get all the clusters that are available in the mission. var missionClusters = mission.GetClusters(); var currentShipCluster = ship.GetCluster(); var currentMissionCluster = missionClusters.FirstOrDefault(p => p.GetObjectID() == currentShipCluster.GetObjectID()); var shipVisibleWarps = currentShipCluster.GetWarps(); var allWarpsInCluster = currentMissionCluster.GetWarps(); } private void ReturnToBase() { var ship = ClientConnection.GetShip(); var targetBase = ClientConnection.FindTarget(ship, (int) (TargetType.c_ttStation | TargetType.c_ttFriendly | TargetType.c_ttAnyCluster), (short) StationAbilityBitMask.c_sabmFlag); ship.SetCommand((sbyte)CommandType.c_cmdCurrent, targetBase, (sbyte)CommandID.c_cidGoto); ship.SetAutopilot(true); } private bool IsCurrentShipAScout() { var ship = ClientConnection.GetShip(); var baseHullType = ship.GetBaseHullType(); return baseHullType.GetName().Contains("Scout"); } private void ChangeShip(ShipType shipType, LoadoutBase loadOut) { _waitingForLaunchToComplete = true; Log($"\tChanging ship to {shipType}"); var side = ClientConnection.GetSide(); var ship = ClientConnection.GetShip(); var mission = side.GetMission(); var hullTypes = mission.GetHullTypes(); var station = ship.GetStation(); if (station == null) return; string targetHullTypeName = GetHullTypeString(shipType); List<AllegianceInterop.IhullTypeIGCWrapper> buyableHullTypes = new List<AllegianceInterop.IhullTypeIGCWrapper>(); foreach (var hullType in hullTypes) { if (hullType.GetGroupID() >= 0 && station.CanBuy(hullType) == true && station.IsObsolete(hullType) == false) { Log("\t\tbuyable hullType: " + hullType.GetName()); buyableHullTypes.Add(hullType); } } // Get a scout. var scoutHull = buyableHullTypes.FirstOrDefault(p => p.GetName().Contains(targetHullTypeName)); if (scoutHull == null) return; Log($"\tFound Scout: {scoutHull.GetName()}"); var partTypes = mission.GetPartTypes(); List<AllegianceInterop.IpartTypeIGCWrapper> buyablePartTypes = new List<AllegianceInterop.IpartTypeIGCWrapper>(); foreach (var partType in partTypes) { if (partType.GetGroupID() >= 0 && station.CanBuy(partType) == true && station.IsObsolete(partType) == false) { short equipmentTypeID = partType.GetEquipmentType(); bool isIncluded = false; switch ((EquipmentType)equipmentTypeID) { case EquipmentType.NA: isIncluded = true; break; case EquipmentType.ET_Weapon: case EquipmentType.ET_Turret: for (sbyte i = 0; i < scoutHull.GetMaxFixedWeapons(); i++) { isIncluded |= scoutHull.GetPartMask(equipmentTypeID, i) != 0 && scoutHull.CanMount(partType, i) == true; } break; default: isIncluded |= scoutHull.GetPartMask(equipmentTypeID, 0) != 0 && scoutHull.CanMount(partType, 0) == true; break; } if (isIncluded == true) { buyablePartTypes.Add(partType); Log($"\t\tFound part: {partType.GetName()}, capacity for part: {scoutHull.GetCapacity(partType.GetEquipmentType())}"); } } } // Sell all the parts //var emptyShip = _client.CreateEmptyShip(); //emptyShip.SetBaseHullType(scoutHull); //_client.BuyLoadout(emptyShip, false); //emptyShip.Terminate(); // Now get the new empty ship from the client. //ship = _client.GetShip(); foreach (var part in ship.GetParts()) ship.DeletePart(part); // Change the ship to the scout hull. ship.SetBaseHullType(scoutHull); ClientConnection.BuyDefaultLoadout(ship, station, scoutHull, ClientConnection.GetMoney()); ClearShipCargo(ship); // Load Weapons, missiles, dispensers, etc. if (loadOut.Weapon1 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Weapon1.Value)) == true); if(part != null) ClientConnection.BuyPartOnBudget(ship, part, 0, ClientConnection.GetMoney()); } if (loadOut.Weapon2 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Weapon2.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 1, ClientConnection.GetMoney()); } if (loadOut.Weapon3 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Weapon3.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 2, ClientConnection.GetMoney()); } if (loadOut.Weapon4 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Weapon4.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 3, ClientConnection.GetMoney()); } if (loadOut.Turret1 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Turret1.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 0, ClientConnection.GetMoney()); } if (loadOut.Turret2 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Turret2.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 1, ClientConnection.GetMoney()); } if (loadOut.Turret3 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Turret3.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 2, ClientConnection.GetMoney()); } if (loadOut.Turret4 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Turret4.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 3, ClientConnection.GetMoney()); } if (loadOut.Dispenser != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Dispenser.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 0, ClientConnection.GetMoney()); } if (loadOut.Missiles != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Missiles.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, 0, ClientConnection.GetMoney()); } if (loadOut.Cargo1 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Cargo1.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, -1, ClientConnection.GetMoney()); } if (loadOut.Cargo2 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Cargo2.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, -2, ClientConnection.GetMoney()); } if (loadOut.Cargo3 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Cargo3.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, -3, ClientConnection.GetMoney()); } if (loadOut.Cargo4 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Cargo4.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, -4, ClientConnection.GetMoney()); } if (loadOut.Cargo5 != null) { var part = buyablePartTypes.FirstOrDefault(p => p.GetName().Contains(loadOut.GetItemTypeString(loadOut.Cargo5.Value)) == true); if (part != null) ClientConnection.BuyPartOnBudget(ship, part, -5, ClientConnection.GetMoney()); } //_client.EndLockDown(LockdownCriteria.lockdownLoadout); // Launch! ClientConnection.BuyLoadout(ship, true); ClientConnection.EndLockDown(LockdownCriteria.lockdownLoadout); } private void ClearShipCargo(IshipIGCWrapper ship) { // Clear the cargo. for (sbyte i = -5; i < 0; i++) { var currentPart = ship.GetMountedPart((short)EquipmentType.NA, i); if (currentPart != null) currentPart.Terminate(); } // Clear weapons for (sbyte i = 0; i < 4; i++) { var currentPart = ship.GetMountedPart((short)EquipmentType.ET_Weapon, i); if (currentPart != null) currentPart.Terminate(); } // Clear turrets for (sbyte i = 0; i < ship.GetHullType().GetMaxWeapons() - ship.GetHullType().GetMaxFixedWeapons(); i++) { var currentPart = ship.GetMountedPart((short)EquipmentType.ET_Turret, i); if (currentPart != null) currentPart.Terminate(); } // Clear missiles for (sbyte i = 0; i < 1; i++) { var currentPart = ship.GetMountedPart((short)EquipmentType.ET_Magazine, i); if (currentPart != null) currentPart.Terminate(); } // Clear Dispenser for (sbyte i = 0; i < 1; i++) { var currentPart = ship.GetMountedPart((short)EquipmentType.ET_Dispenser, i); if (currentPart != null) currentPart.Terminate(); } } private string GetHullTypeString(ShipType shipType) { switch (shipType) { case ShipType.Scout: return "Scout"; case ShipType.Fighter: return "Fighter"; case ShipType.Interceptor: return "Interceptor"; case ShipType.Bomber: return "Bomber"; case ShipType.Gunship: return "Gunship"; case ShipType.StealthFighter: return "Stealth Fighter"; default: throw new NotSupportedException(shipType.ToString()); } } } }
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.OpcUa.Registry.Deploy { using Microsoft.Azure.IIoT.Deploy; using Microsoft.Azure.IIoT.Hub; using Microsoft.Azure.IIoT.Hub.Models; using Microsoft.Azure.IIoT.Hub.Services; using Microsoft.Azure.IIoT.Serializers; using Serilog; using System; using System.Collections.Generic; using System.Threading.Tasks; /// <summary> /// Deploys metricscollector module /// </summary> public sealed class IoTHubMetricsCollectorDeployment : IHostProcess { /// <summary> /// Create deployer /// </summary> /// <param name="service"></param> /// <param name="config"></param> /// <param name="serializer"></param> /// <param name="logger"></param> public IoTHubMetricsCollectorDeployment(IIoTHubConfigurationServices service, ILogWorkspaceConfig config, IJsonSerializer serializer, ILogger logger) { _service = service ?? throw new ArgumentNullException(nameof(service)); _config = config ?? throw new ArgumentNullException(nameof(service)); _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// <inheritdoc/> public async Task StartAsync() { if (string.IsNullOrEmpty(_config.LogWorkspaceId) || string.IsNullOrEmpty(_config.LogWorkspaceKey)) { _logger.Warning("Azure Log Analytics Workspace configuration is not set." + " Cannot proceed with metricscollector deployment."); return; } await _service.CreateOrUpdateConfigurationAsync(new ConfigurationModel { Id = "__default-metricscollector-linux", Content = new ConfigurationContentModel { ModulesContent = CreateLayeredDeployment(true) }, SchemaVersion = kDefaultSchemaVersion, TargetCondition = IoTHubEdgeBaseDeployment.TargetCondition + " AND tags.os = 'Linux'", Priority = 2 }, true); await _service.CreateOrUpdateConfigurationAsync(new ConfigurationModel { Id = "__default-metricscollector-windows", Content = new ConfigurationContentModel { ModulesContent = CreateLayeredDeployment(false) }, SchemaVersion = kDefaultSchemaVersion, TargetCondition = IoTHubEdgeBaseDeployment.TargetCondition + " AND tags.os = 'Windows'", Priority = 2 }, true); } /// <inheritdoc/> public Task StopAsync() { return Task.CompletedTask; } /// <summary> /// Get base edge configuration /// </summary> /// <param name="isLinux"></param> /// <returns></returns> private IDictionary<string, IDictionary<string, object>> CreateLayeredDeployment( bool isLinux) { // Configure create options and version per os specified string createOptions; if (isLinux) { // Linux createOptions = "{}"; } else { // Windows createOptions = _serializer.SerializeToString(new { User = "ContainerAdministrator" }); } createOptions = createOptions.Replace("\"", "\\\""); var image = "mcr.microsoft.com/azureiotedge-metrics-collector:1.0"; _logger.Information("Updating metrics collector module deployment for {os}", isLinux ? "Linux" : "Windows"); // Return deployment modules object var content = @" { ""$edgeAgent"": { ""properties.desired.modules." + kModuleName + @""": { ""settings"": { ""image"": """ + image + @""", ""createOptions"": """ + createOptions + @""" }, ""type"": ""docker"", ""version"": ""1.0"", ""env"": { ""UploadTarget"": { ""value"": ""AzureMonitor"" }, ""LogAnalyticsWorkspaceId"": { ""value"": """ + _config.LogWorkspaceId + @""" }, ""LogAnalyticsSharedKey"": { ""value"": """ + _config.LogWorkspaceKey + @""" }, ""ResourceId"": { ""value"": """ + _config.IoTHubResourceId + @""" }, ""MetricsEndpointsCSV"": { ""value"": ""http://edgehub:9600/metrics,http://edgeagent:9600/metrics,http://twin:9701/metrics,http://publisher:9702/metrics"" } }, ""status"": ""running"", ""restartPolicy"": ""always"" } }, ""$edgeHub"": { ""properties.desired.routes." + kModuleName + @"ToUpstream"": ""FROM /messages/modules/" + kModuleName + @"/* INTO $upstream"" } }"; return _serializer.Deserialize<IDictionary<string, IDictionary<string, object>>>(content); } private const string kDefaultSchemaVersion = "1.0"; private const string kModuleName = "metricscollector"; private readonly IIoTHubConfigurationServices _service; private readonly ILogWorkspaceConfig _config; private readonly IJsonSerializer _serializer; private readonly ILogger _logger; } }
//MIT, 2009, 2010, 2013-2016 by the Brotli Authors. //MIT, 2017, brezza92 (C# port from original code, by hand) namespace CSharpBrotli.Decode { public enum WordTransformType { IDENTITY, OMIT_LAST_1, OMIT_LAST_2, OMIT_LAST_3, OMIT_LAST_4, OMIT_LAST_5, OMIT_LAST_6, OMIT_LAST_7, OMIT_LAST_8, OMIT_LAST_9, UPPERCASE_FIRST, UPPERCASE_ALL, OMIT_FIRST_1, OMIT_FIRST_2, OMIT_FIRST_3, OMIT_FIRST_4, OMIT_FIRST_5, OMIT_FIRST_6, OMIT_FIRST_7, /* * brotli specification doesn't use OMIT_FIRST_8(8, 0) transform. * Probably, it would be used in future format extensions. */ OMIT_FIRST_8, OMIT_FIRST_9 } internal class TransformType { public static int GetOmitFirst(WordTransformType type) { if(type>=WordTransformType.OMIT_FIRST_1 && type<= WordTransformType.OMIT_FIRST_9) { return (type - WordTransformType.OMIT_FIRST_1) + 1; } return 0; } public static int GetOmitLast(WordTransformType type) { if(type >= WordTransformType.OMIT_LAST_1 && type<= WordTransformType.OMIT_LAST_9) { return (type - WordTransformType.OMIT_LAST_1) + 1; } return 0; } } }
using System; using DtronixMessageQueue.TcpSocket; namespace DtronixMessageQueue { /// <summary> /// Event args used when a session is closed. /// </summary> /// <typeparam name="TSession">Session type for this connection.</typeparam> /// <typeparam name="TConfig">Configuration for this connection.</typeparam> public class SessionClosedEventArgs<TSession, TConfig> : EventArgs where TSession : TcpSocketSession<TSession, TConfig>, new() where TConfig : TcpSocketConfig { /// <summary> /// Closed session. /// </summary> public TSession Session { get; } /// <summary> /// Reason the session was closed. /// </summary> public CloseReason CloseReason { get; } /// <summary> /// Creates a new instance of the session closed event args. /// </summary> /// <param name="session">Closed session.</param> /// <param name="closeReason">Reason the session was closed.</param> public SessionClosedEventArgs(TSession session, CloseReason closeReason) { Session = session; CloseReason = closeReason; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Xin.AQS { public interface IAQIResult { /// <summary> /// 空气质量指数 /// </summary> int? AQI { get; set; } string PrimaryPollutant { get; set; } string Type { get; set; } string Effect { get; set; } string Measure { get; set; } void GetAQI(); } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Mortgage.Data.Entity { public class Prospect { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key, Column(Order = 0)] public int Id { get; set; } [StringLength(60, MinimumLength = 3)] [Required] public string CustomerName { get; set; } [DataType(DataType.Currency)] public Decimal LoanAmount { get; set; } public Decimal AnnualInterest { get; set; } public int LoanTerm { get; set; } } }
using LuaInterface; using System; public class LuaInterface_LuaOutWrap { public static void Register(LuaState L) { L.BeginPreLoad(); L.RegFunction("tolua.out", LuaOpen_ToLua_Out); L.EndPreLoad(); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int LuaOpen_ToLua_Out(IntPtr L) { try { LuaDLL.lua_newtable(L); RawSetOutType<int>(L); RawSetOutType<uint>(L); RawSetOutType<float>(L); RawSetOutType<double>(L); RawSetOutType<long>(L); RawSetOutType<ulong>(L); RawSetOutType<byte>(L); RawSetOutType<sbyte>(L); RawSetOutType<char>(L); RawSetOutType<short>(L); RawSetOutType<ushort>(L); RawSetOutType<bool>(L); RawSetOutType<string>(L); return 1; } catch (Exception e) { return LuaDLL.toluaL_exception(L, e); } } static void RawSetOutType<T>(IntPtr L) { string str = TypeTraits<T>.GetTypeName(); LuaDLL.lua_pushstring(L, str); ToLua.PushOut<T>(L, new LuaOut<T>()); LuaDLL.lua_rawset(L, -3); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.EntityFrameworkCore.TestModels.ManyToManyFieldsModel { public class JoinThreeToCompositeKeyFull { public Guid Id; public int ThreeId; public int CompositeId1; public string CompositeId2; public DateTime CompositeId3; public EntityThree Three; public EntityCompositeKey Composite; } }
using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using OmniSharp.Models; using Xunit; namespace OmniSharp.Tests { public class LinePositionSpanTextChangeFacts { [Fact] public async Task ExtendsTextChangeAtStart() { var workspace = await TestHelpers.CreateSimpleWorkspace("class {\r\n }"); var document = workspace.GetDocument("dummy.cs"); var lineChanges = await LinePositionSpanTextChange.Convert(document, new TextChange[] { new TextChange(TextSpan.FromBounds(8, 11), "\n}") }); Assert.Equal("\r\n}", lineChanges.ElementAt(0).NewText); Assert.Equal(1, lineChanges.ElementAt(0).StartLine); Assert.Equal(8, lineChanges.ElementAt(0).StartColumn); Assert.Equal(2, lineChanges.ElementAt(0).EndLine); Assert.Equal(3, lineChanges.ElementAt(0).EndColumn); } [Fact] public async Task ExtendsTextChangeAtEnd() { var workspace = await TestHelpers.CreateSimpleWorkspace("class {\n}"); var document = workspace.GetDocument("dummy.cs"); var lineChanges = await LinePositionSpanTextChange.Convert(document, new TextChange[] { new TextChange(TextSpan.FromBounds(5, 7), "\r\n {\r") }); Assert.Equal("\r\n {\r\n", lineChanges.ElementAt(0).NewText); Assert.Equal(1, lineChanges.ElementAt(0).StartLine); Assert.Equal(6, lineChanges.ElementAt(0).StartColumn); Assert.Equal(2, lineChanges.ElementAt(0).EndLine); Assert.Equal(1, lineChanges.ElementAt(0).EndColumn); } } }
namespace GameLogic.AI.ActivityCreation { using ActionLoop; using Entities; using GridRelated; using Navigation; using Osnowa.Osnowa.Example; using Osnowa.Osnowa.Fov; using Osnowa.Osnowa.Grid; using Osnowa.Osnowa.Rng; using UI; public interface IActivityCreationContext { INavigator Navigator { get; } IRandomNumberGenerator Rng { get; } IActionFactory ActionFactory { get; } ISceneContext SceneContext { get; } IExampleContextManager ContextManager { get; } IGameConfig GameConfig { get; } IEntityDetector EntityDetector { get; } ICalculatedAreaAccessor CalculatedAreaAccessor { get; } IUiFacade UiFacade { get; } IRasterLineCreator RasterLineCreator { get; } IPositionEffectPresenter PositionEffectPresenter { get; } IFriendshipResolver FriendshipResolver { get; } GameContext Context { get; } } }
using System; using System.Xml.Serialization; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// ZhimaMerchantOrderCreditModifyModel Data Structure. /// </summary> [Serializable] public class ZhimaMerchantOrderCreditModifyModel : AlipayObject { /// <summary> /// 外部订单号, 用于定位需要修改的订单 /// </summary> [JsonProperty("out_order_no")] [XmlElement("out_order_no")] public string OutOrderNo { get; set; } /// <summary> /// 逾期时间,不为空时将修改当前订单的逾期时间,入参不得早于系统当前时间 /// </summary> [JsonProperty("overdue_time")] [XmlElement("overdue_time")] public string OverdueTime { get; set; } /// <summary> /// 芝麻订单号,用于定位要修改的订单 /// </summary> [JsonProperty("zm_order_no")] [XmlElement("zm_order_no")] public string ZmOrderNo { get; set; } } }
using System; using Autofac; using RP_Server_Scripts.Database.Properties; using RP_Server_Scripts.Logging; namespace RP_Server_Scripts.Database { internal class DatabaseInitialization : IStartable { private readonly ILogger _Log; public DatabaseInitialization(ILoggerFactory loggerFactory) { if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } _Log = loggerFactory.GetLogger(GetType()); } public void Start() { using (var context = new GlobalContext()) { _Log.Info(context.Database.CreateIfNotExists() ? Resources.Msg_DatabaseWasCreated : Resources.Msg_DatabaseFound); } } } }
using Microsoft.Extensions.DependencyInjection; using SharpVk.Generator.Pipeline; using System.Collections.Generic; using System.Linq; namespace SharpVk.Generator.Collation { public class ExtensionCollator : IWorker { private readonly IEnumerable<ExtensionInfo> extensions; public ExtensionCollator(IEnumerable<ExtensionInfo> extensions) { this.extensions = extensions; } public void Execute(IServiceCollection services) { foreach (var extension in this.extensions) { var nameParts = extension.Name.Split('_').Skip(2); string outputName = string.Join("", nameParts.Select(StringExtensions.FirstToUpper)); services.AddSingleton(new TypeNameMapping { VkName = extension.Name, OutputName = outputName }); services.AddSingleton(new ExtensionDeclaration { Name = extension.Name, Scope = extension.Scope }); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using supermarket.Domain.Services.Communication; using supermarket.Models; namespace supermarket.Domain.Services { public interface ICategoryService { Task<IEnumerable<Category>> ListAsync(); Task<SaveCategoryResponse> SaveAsync(int id, Category category); Task<SaveCategoryResponse> UpdateAsync(int id, Category category); Task<SaveCategoryResponse> DeleteAsync(int id); } }
using log4net; using Sitecore.Diagnostics; using System; namespace JLS.Foundation.Logging { public static class SmartDeleteLogger { private static readonly ILog _logger = LogManager.GetLogger("JLSFoundationLogger"); public static void Debug(string message) { Assert.ArgumentNotNull(message, "message"); _logger.Debug(message); } public static void Debug(string message, Exception exception) { Assert.ArgumentNotNull(message, "message"); Assert.ArgumentNotNull(exception, "exception"); _logger.Debug(message, exception); } public static void Info(string message) { Assert.ArgumentNotNull(message, "message"); _logger.Info(message); } public static void Info(string message, Exception exception) { Assert.ArgumentNotNull(message, "message"); Assert.ArgumentNotNull(exception, "exception"); _logger.Info(message, exception); } public static void Warn(string message) { Assert.ArgumentNotNull(message, "message"); _logger.Warn(message); } public static void Warn(string message, Exception exception) { Assert.ArgumentNotNull(message, "message"); Assert.ArgumentNotNull(exception, "exception"); _logger.Warn(message, exception); } public static void Error(string message) { Assert.ArgumentNotNull(message, "message"); _logger.Error(message); } public static void Error(string message, Exception exception) { Assert.ArgumentNotNull(message, "message"); Assert.ArgumentNotNull(exception, "exception"); _logger.Error(message, exception); } public static void Fatal(string message) { Assert.ArgumentNotNull(message, "message"); _logger.Fatal(message); } public static void Fatal(string message, Exception exception) { Assert.ArgumentNotNull(message, "message"); Assert.ArgumentNotNull(exception, "exception"); _logger.Fatal(message, exception); } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WpfLiteCoinTester.BfEntities { using System; using System.Collections.Generic; public partial class user { public user() { this.balances = new HashSet<balance>(); this.transactions = new HashSet<transaction>(); } public int uid { get; set; } public string username { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string description { get; set; } public string avatarUrl { get; set; } public Nullable<int> status { get; set; } public Nullable<int> addressid { get; set; } public virtual address address { get; set; } public virtual ICollection<balance> balances { get; set; } public virtual ICollection<transaction> transactions { get; set; } } }
using System.Collections.ObjectModel; using Commandos.Model.Characters; using Commandos.Model.EnemyActions; using Commandos.Model.Map; using CommandosMissionEditor.Helpers; namespace CommandosMissionEditor.ViewModels { public class AddEnemyRouteViewModel : AddItemViewModelBase<EnemyRoute> { public override string TabName => "Routes"; public ObservableCollection<EnemyCharacter> Enemies => Mission.GetEnemies(); private EnemyCharacter _selectedEnemy; public EnemyCharacter SelectedEnemy { get => _selectedEnemy; set { Set(ref _selectedEnemy, value); LoadDefaultItem(); OnPropertyChanged(nameof(ItemCollection)); AddItemCommand.RaiseCanExecuteChanged(); SelectedItem = new EnemyRoute(); } } public override ObservableCollection<EnemyRoute> ItemCollection => SelectedEnemy?.Routes; public override void LoadDefaultItem() { OnPropertyChanged(nameof(ItemCollection)); if (ItemCollection is null) return; foreach (var item in ItemCollection) { if (item.RouteName == SelectedEnemy.DefaultRoute) DefaultItem = item; if (item.RouteName == SelectedEnemy.EventRoute) EventRoute = item; } } public override void OnDefaultItemChanged() { SelectedEnemy.DefaultRoute = DefaultItem?.RouteName; } private EnemyRoute _eventRoute; public EnemyRoute EventRoute { get => _eventRoute; set { Set(ref _eventRoute, value); SelectedEnemy.EventRoute = _eventRoute?.RouteName; } } protected override bool CanAddItem() { return SelectedEnemy != null; } } }