content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using QSP.Utilities; namespace QSP.UI.Views { public partial class Splash { public Splash() { InitializeComponent(); } public void ShowVersion() { SmallTitleLbl.Text = "version " + Version.AppProductVersion(); } } }
16.777778
74
0.529801
[ "MIT" ]
JetStream96/QSimPlanner
src/QSP/UI/Views/Splash.cs
302
C#
using BattleTech; using Harmony; using System; using System.Collections.Generic; namespace ConcreteJungle.Extensions { public static class MechExtensions { // The default method assumes an absractActor exists, and tries to draw a line of fire. We don't have that, so skip it. public static void ResolveSourcelessWeaponDamage(this Mech mech, WeaponHitInfo hitInfo, Weapon weapon, MeleeAttackType meleeAttackType) { AttackDirector.AttackSequence attackSequence = ModState.Combat.AttackDirector.GetAttackSequence(hitInfo.attackSequenceId); float damagePerShot = weapon.DamagePerShot; float structureDamagePerShot = weapon.StructureDamagePerShot; LineOfFireLevel lineOfFireLevel = LineOfFireLevel.LOFClear; damagePerShot = mech.GetAdjustedDamage(damagePerShot, weapon.WeaponCategoryValue, mech.occupiedDesignMask, lineOfFireLevel, false); structureDamagePerShot = mech.GetAdjustedDamage(structureDamagePerShot, weapon.WeaponCategoryValue, mech.occupiedDesignMask, lineOfFireLevel, false); foreach (KeyValuePair<int, float> keyValuePair in hitInfo.ConsolidateCriticalHitInfo(mech.GUID, damagePerShot)) { if (keyValuePair.Key != 0 && keyValuePair.Key != 65536 && (mech.ArmorForLocation(keyValuePair.Key) <= 0f || structureDamagePerShot > 0f)) { ChassisLocations chassisLocationFromArmorLocation = MechStructureRules.GetChassisLocationFromArmorLocation((ArmorLocation)keyValuePair.Key); if (!mech.IsLocationDestroyed(chassisLocationFromArmorLocation)) { Traverse checkForCritT = Traverse.Create(mech).Method("CheckForCrit", new Type[] { typeof(WeaponHitInfo), typeof(ChassisLocations), typeof(Weapon) }); checkForCritT.GetValue(new object[] { hitInfo, chassisLocationFromArmorLocation, weapon }); } } } if (weapon.HeatDamagePerShot > 0f) { bool flag = false; for (int i = 0; i < hitInfo.numberOfShots; i++) { if (hitInfo.DidShotHitTarget(mech.GUID, i) && hitInfo.ShotHitLocation(i) != 0 && hitInfo.ShotHitLocation(i) != 65536) { flag = true; mech.AddExternalHeat(string.Format("Heat Damage from {0}", weapon.Description.Name), (int)weapon.HeatDamagePerShotAdjusted(hitInfo.hitQualities[i])); } } if (flag && attackSequence != null) { attackSequence.FlagAttackDidHeatDamage(mech.GUID); } } float num3 = hitInfo.ConsolidateInstability(mech.GUID, weapon.Instability(), mech.Combat.Constants.ResolutionConstants.GlancingBlowDamageMultiplier, mech.Combat.Constants.ResolutionConstants.NormalBlowDamageMultiplier, mech.Combat.Constants.ResolutionConstants.SolidBlowDamageMultiplier); num3 *= mech.StatCollection.GetValue<float>("ReceivedInstabilityMultiplier"); num3 *= mech.EntrenchedMultiplier; mech.AddAbsoluteInstability(num3, StabilityChangeSource.Attack, hitInfo.attackerId); } } }
50.385965
156
0.762187
[ "MIT" ]
BattletechModders/ConcreteJungle
ConcreteJungle/ConcreteJungle/Extensions/MechExtensions.cs
2,874
C#
using System; namespace SilupostWeb.Domain.ViewModel { public class SystemWebAdminRoleViewModel { public string SystemWebAdminRoleId { get; set; } public string RoleName { get; set; } public SystemRecordManagerViewModel SystemRecordManager { get; set; } public EntityStatusViewModel EntityStatus { get; set; } } }
27.692308
77
0.7
[ "Apache-2.0" ]
erwin-io/Silupost
SilupostWebApp/SilupostWeb.Domain/ViewModel/SystemWebAdminRoleViewModel.cs
362
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.461) // Version 5.461.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.Diagnostics; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Draws the text string for a group label. /// </summary> internal class ViewDrawRibbonGroupLabelText : ViewLeaf, IContentValues { #region Instance Fields private readonly KryptonRibbon _ribbon; private readonly KryptonRibbonGroupLabel _ribbonLabel; private readonly RibbonGroupLabelTextToContent _contentProvider; private IDisposable _memento; private readonly bool _firstText; private int _heightExtra; private Size _preferredSize; private Rectangle _displayRect; private int _dirtyPaletteSize; private int _dirtyPaletteLayout; private PaletteState _cacheState; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawRibbonGroupLabelText class. /// </summary> /// <param name="ribbon">Source ribbon control.</param> /// <param name="ribbonLabel">Group label to display title for.</param> /// <param name="firstText">Should show the first button text.</param> public ViewDrawRibbonGroupLabelText(KryptonRibbon ribbon, KryptonRibbonGroupLabel ribbonLabel, bool firstText) { Debug.Assert(ribbon != null); Debug.Assert(ribbonLabel != null); _ribbon = ribbon; _ribbonLabel = ribbonLabel; _firstText = firstText; // Use a class to convert from ribbon group to content interface _contentProvider = new RibbonGroupLabelTextToContent(ribbon.StateCommon.RibbonGeneral, ribbon.StateNormal.RibbonGroupLabelText, ribbon.StateDisabled.RibbonGroupLabelText, ribbonLabel.StateNormal, ribbonLabel.StateDisabled); } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawRibbonGroupLabelText:" + Id; } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { if (_memento != null) { _memento.Dispose(); _memento = null; } } base.Dispose(disposing); } #endregion #region MakeDirty /// <summary> /// Make dirty so cached values are not used. /// </summary> public void MakeDirty() { _dirtyPaletteSize = 0; _dirtyPaletteLayout = 0; } #endregion #region Layout /// <summary> /// Discover the preferred size of the element. /// </summary> /// <param name="context">Layout context.</param> public override Size GetPreferredSize(ViewLayoutContext context) { Debug.Assert(context != null); // Validate incoming reference if (context == null) { throw new ArgumentNullException(nameof(context)); } // A change in state always causes a size and layout calculation if (_cacheState != State) { MakeDirty(); _cacheState = State; } // If the palette has changed since we last calculated if (_ribbon.DirtyPaletteCounter != _dirtyPaletteSize) { // Ask the renderer for the contents preferred size _preferredSize = context.Renderer.RenderStandardContent.GetContentPreferredSize(context, _contentProvider, this, VisualOrientation.Top, State, false, false); // Subtract the extra space used to ensure it draws _heightExtra = (_ribbon.CalculatedValues.DrawFontHeight - _ribbon.CalculatedValues.RawFontHeight) * 2; _preferredSize.Height -= _heightExtra; // If the text is actually empty, then force it to be zero width if (string.IsNullOrEmpty(GetShortText())) { _preferredSize.Width = 0; } // Cached value is valid till dirty palette noticed _dirtyPaletteSize = _ribbon.DirtyPaletteCounter; } return _preferredSize; } /// <summary> /// Perform a layout of the elements. /// </summary> /// <param name="context">Layout context.</param> public override void Layout(ViewLayoutContext context) { Debug.Assert(context != null); // We take on all the available display area ClientRectangle = context.DisplayRectangle; // A change in state always causes a size and layout calculation if (_cacheState != State) { MakeDirty(); _cacheState = State; } // Do we need to actually perform the relayout? if ((_displayRect != ClientRectangle) || (_ribbon.DirtyPaletteCounter != _dirtyPaletteLayout)) { // Remember to dispose of old memento if (_memento != null) { _memento.Dispose(); _memento = null; } Rectangle drawRect = ClientRectangle; // Adjust the client rect so the text has enough room to be drawn drawRect.Height += _heightExtra; drawRect.Y -= (_heightExtra / 2); // Use the renderer to layout the text _memento = context.Renderer.RenderStandardContent.LayoutContent(context, drawRect, _contentProvider, this, VisualOrientation.Top, PaletteState.Normal, false, false); // Cache values that are needed to decide if layout is needed _displayRect = ClientRectangle; _dirtyPaletteLayout = _ribbon.DirtyPaletteCounter; } } #endregion #region Paint /// <summary> /// Perform rendering before child elements are rendered. /// </summary> /// <param name="context">Rendering context.</param> public override void RenderBefore(RenderContext context) { Rectangle drawRect = ClientRectangle; // Adjust the client rect so the text has enough room to be drawn drawRect.Height += _heightExtra; drawRect.Y -= (_heightExtra / 2); // Use renderer to draw the text content if (_memento != null) { context.Renderer.RenderStandardContent.DrawContent(context, drawRect, _contentProvider, _memento, VisualOrientation.Top, State, false, false, true); } } #endregion #region IContentValues /// <summary> /// Gets the image used for the ribbon tab. /// </summary> /// <param name="state">Tab state.</param> /// <returns>Image.</returns> public Image GetImage(PaletteState state) { return null; } /// <summary> /// Gets the image color that should be interpreted as transparent. /// </summary> /// <param name="state">Tab state.</param> /// <returns>Transparent Color.</returns> public Color GetImageTransparentColor(PaletteState state) { return Color.Empty; } /// <summary> /// Gets the short text used as the main ribbon title. /// </summary> /// <returns>Title string.</returns> public string GetShortText() { if (_ribbonLabel.KryptonCommand != null) { if (_firstText) { return _ribbonLabel.KryptonCommand.TextLine1; } else if (!string.IsNullOrEmpty(_ribbonLabel.KryptonCommand.TextLine2)) { return _ribbonLabel.KryptonCommand.TextLine2; } else { return " "; } } else if (_firstText) { return _ribbonLabel.TextLine1; } else if (!string.IsNullOrEmpty(_ribbonLabel.TextLine2)) { return _ribbonLabel.TextLine2; } else { return " "; } } /// <summary> /// Gets the long text used as the secondary ribbon title. /// </summary> /// <returns>Title string.</returns> public string GetLongText() { return string.Empty; } #endregion } }
37.373288
157
0.513058
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.461
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonGroupLabelText.cs
10,916
C#
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SimpleOverlayForm")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleOverlayForm")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
35.129032
84
0.746556
[ "MIT" ]
OnTheFenceDevelopment/xamarinforms
SimpleOverlayForm/SimpleOverlayForm/SimpleOverlayForm/Properties/AssemblyInfo.cs
1,092
C#
using Newtonsoft.Json; using Platform_Racing_3_Server.Game.Communication.Messages.Incoming.Json; using System; using System.Collections.Generic; using System.Text; namespace Platform_Racing_3_Server.Game.Communication.Messages.Outgoing.Json { internal class JsonLogoutTriggerOutgoingMessage : JsonPacket { internal override string Type => "logoutTrigger"; [JsonProperty("message")] internal string Message { get; set; } internal JsonLogoutTriggerOutgoingMessage(string message) { this.Message = message; } } }
26.636364
76
0.71843
[ "MIT" ]
RMXdotEXE/Platform-Racing-3-Backend
Server/Game/Communication/Messages/Outgoing/Json/JsonLogoutTriggerOutgoingMessage.cs
588
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Primary.Data; using Primary.Data.Orders; using ServiceStack; namespace Primary { public class Api { /// <summary>This is the default production endpoint.</summary> public static Uri ProductionEndpoint => new Uri("https://api.primary.com.ar"); /// <summary>This is the default demo endpoint.</summary> /// <remarks>You can get a demo username at https://remarkets.primary.ventures.</remarks> public static Uri DemoEndpoint => new Uri("https://api.remarkets.primary.com.ar"); /// <summary> /// Build a new API object. /// </summary> public Api(Uri baseUri) { _baseUri = baseUri; } private readonly Uri _baseUri; #region Login public string AccessToken { get; private set; } /// <summary> /// Initialize the specified environment. /// </summary> /// <param name="username">User used for authentication.</param> /// <param name="password">Password used for authentication.</param> /// <returns></returns> public async Task Login(string username, string password) { var uri = new Uri(_baseUri, "/auth/getToken"); await uri.ToString().PostToUrlAsync(null, "*/*", request => { request.Headers.Add("X-Username", username); request.Headers.Add("X-Password", password); }, response => { AccessToken = response.Headers["X-Auth-Token"]; } ); } public const string DemoUsername = "naicigam2046"; public const string DemoPassword = "nczhmL9@"; public const string DemoAccount = "REM2046"; #endregion #region Instruments information /// <summary> /// Get all instruments currently traded on the exchange. /// </summary> /// <returns>Instruments information.</returns> public async Task< IEnumerable<Instrument> > GetAllInstruments() { var uri = new Uri(_baseUri, "/rest/instruments/all"); var response = await uri.ToString().GetJsonFromUrlAsync( request => { request.Headers.Add("X-Auth-Token", AccessToken); }); var data = JsonConvert.DeserializeObject<GetAllInstrumentsResponse>(response); return data.Instruments.Select(i => i.InstrumentId); } private class GetAllInstrumentsResponse { public class InstrumentEntry { [JsonProperty("instrumentId")] public Instrument InstrumentId { get; set; } } [JsonProperty("instruments")] public List<InstrumentEntry> Instruments { get; set; } } #endregion #region Historical data /// <summary> /// Get historical trades for a specific instrument. /// </summary> /// <param name="instrument">Instrument to get information for.</param> /// <param name="dateFrom">First date of trading information.</param> /// <param name="dateTo">Last date of trading information.</param> /// <returns>Trade information for the instrument in the specified period.</returns> public async Task< IEnumerable<Trade> > GetHistoricalTrades(Instrument instrument, DateTime dateFrom, DateTime dateTo) { var uri = new Uri(_baseUri, "/rest/data/getTrades"); var response = await uri.ToString() .AddQueryParam("marketId", instrument.Market) .AddQueryParam("symbol", instrument.Symbol) .AddQueryParam("dateFrom", dateFrom.ToString("yyyy-MM-dd")) .AddQueryParam("dateTo", dateTo.ToString("yyyy-MM-dd")) .GetJsonFromUrlAsync( request => { request.Headers.Add("X-Auth-Token", AccessToken); }); var data = JsonConvert.DeserializeObject<GetTradesResponse>(response); return data.Trades; } private class GetTradesResponse { [JsonProperty("trades")] public List<Trade> Trades { get; set; } } #endregion #region Market data sockets /// <summary> /// Create a Market Data web socket to receive real-time market data. /// </summary> /// <param name="instruments">Instruments to watch.</param> /// <param name="entries">Market data entries to watch.</param> /// <param name="level"></param> /// <param name="depth">Depth of the book.</param> /// <returns>The market data web socket.</returns> public MarketDataWebSocket CreateMarketDataSocket(IEnumerable<Instrument> instruments, IEnumerable<Entry> entries, uint level, uint depth ) { return CreateMarketDataSocket( instruments, entries, level, depth, new CancellationToken() ); } /// <summary> /// Create a Market Data web socket to receive real-time market data. /// </summary> /// <param name="instruments">Instruments to watch.</param> /// <param name="entries">Market data entries to watch.</param> /// <param name="level"></param> /// <param name="depth">Depth of the book.</param> /// <param name="cancellationToken">Custom cancellation token to end the socket task.</param> /// <returns>The market data web socket.</returns> public MarketDataWebSocket CreateMarketDataSocket(IEnumerable<Instrument> instruments, IEnumerable<Entry> entries, uint level, uint depth, CancellationToken cancellationToken ) { var wsScheme = (_baseUri.Scheme == "https" ? "wss" : "ws"); var url = new UriBuilder(_baseUri) { Scheme = wsScheme }; var marketDataToRequest = new MarketDataInfo() { Depth = depth, Entries = entries.ToArray(), Level = level, Products = instruments.ToArray() }; return new MarketDataWebSocket(marketDataToRequest, url.Uri, AccessToken, cancellationToken); } #endregion #region Order data sockets /// <summary> /// Create a Order Data web socket to receive real-time orders data. /// </summary> /// <param name="accounts">Accounts to get order events from.</param> /// <returns>The order data web socket.</returns> public OrderDataWebSocket CreateOrderDataSocket(IEnumerable<string> accounts) { return CreateOrderDataSocket( accounts, new CancellationToken() ); } /// <summary> /// Create a Market Data web socket to receive real-time market data. /// </summary> /// <param name="accounts">Accounts to get order events from.</param> /// <param name="cancellationToken">Custom cancellation token to end the socket task.</param> /// <returns>The order data web socket.</returns> public OrderDataWebSocket CreateOrderDataSocket(IEnumerable<string> accounts, CancellationToken cancellationToken ) { var wsScheme = (_baseUri.Scheme == "https" ? "wss" : "ws"); var url = new UriBuilder(_baseUri) { Scheme = wsScheme }; var request = new Request { Accounts = accounts.Select(a => new OrderStatus.AccountId() { Id = a } ).ToArray() }; return new OrderDataWebSocket(request, url.Uri, AccessToken, cancellationToken); } #endregion #region Orders /// <summary> /// Send an order to the specific account. /// </summary> /// <param name="account">Account to send the order to.</param> /// <param name="order">Order to send.</param> /// <returns>Order identifier.</returns> public async Task<OrderId> SubmitOrder(string account, Order order) { var uri = new Uri(_baseUri, "/rest/order/newSingleOrder").ToString(); uri = uri.AddQueryParam("marketId", "ROFX") .AddQueryParam("symbol", order.Instrument.Symbol) .AddQueryParam("price", order.Price) .AddQueryParam("orderQty", order.Quantity) .AddQueryParam("ordType", order.Type.ToApiString()) .AddQueryParam("side", order.Side.ToApiString()) .AddQueryParam("timeInForce", order.Expiration.ToApiString()) .AddQueryParam("account", account) .AddQueryParam("cancelPrevious", order.CancelPrevious) .AddQueryParam("iceberg", order.Iceberg) .AddQueryParam("expireDate", order.ExpirationDate.ToString("yyyyMMdd")); if (order.Iceberg) { uri = uri.AddQueryParam("displayQty", order.DisplayQuantity); } var jsonResponse = await uri.GetJsonFromUrlAsync( request => { request.Headers.Add("X-Auth-Token", AccessToken); } ); var response = JsonConvert.DeserializeObject<OrderIdResponse>(jsonResponse); if (response.Status == Status.Error) { throw new Exception($"{response.Message} ({response.Description})"); } return new OrderId() { ClientOrderId = response.Order.ClientId, Proprietary = response.Order.Proprietary }; } /// <summary> /// Get order information from identifier. /// </summary> /// <param name="orderId">Order identifier.</param> /// <returns>Order information.</returns> public async Task<OrderStatus> GetOrderStatus(OrderId orderId) { var uri = new Uri(_baseUri, "/rest/order/id").ToString(); uri = uri.AddQueryParam("clOrdId", orderId.ClientOrderId) .AddQueryParam("proprietary", orderId.Proprietary); var jsonResponse = await uri.GetJsonFromUrlAsync( request => { request.Headers.Add("X-Auth-Token", AccessToken); } ); var response = JsonConvert.DeserializeObject<GetOrderResponse>(jsonResponse); if (response.Status == Status.Error) { throw new Exception($"{response.Message} ({response.Description})"); } return response.Order; } /// <summary> /// Cancel an order. /// </summary> /// <param name="orderId">Order identifier to cancel.</param> public async Task CancelOrder(OrderId orderId) { var uri = new Uri(_baseUri, "/rest/order/cancelById").ToString(); uri = uri.AddQueryParam("clOrdId", orderId.ClientOrderId) .AddQueryParam("proprietary", orderId.Proprietary); var jsonResponse = await uri.GetJsonFromUrlAsync( request => { request.Headers.Add("X-Auth-Token", AccessToken); } ); var response = JsonConvert.DeserializeObject<OrderIdResponse>(jsonResponse); //if (response.Status == Status.Error) //{ // throw new Exception($"{response.Message} ({response.Description})"); //} } private struct OrderIdResponse { [JsonProperty("status")] public string Status; [JsonProperty("message")] public string Message; [JsonProperty("description")] public string Description; public struct Id { [JsonProperty("clientId")] public ulong ClientId { get; set; } [JsonProperty("proprietary")] public string Proprietary { get; set; } } [JsonProperty("order")] public Id Order; } private struct GetOrderResponse { [JsonProperty("status")] public string Status; [JsonProperty("message")] public string Message; [JsonProperty("description")] public string Description; [JsonProperty("order")] public OrderStatus Order; } #endregion #region Constants private static class Status { public const string Error = "ERROR"; } #endregion } }
39.434783
105
0.502412
[ "MIT" ]
matbarofex/Primary.Net
Primary/Api.cs
14,514
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * 直播域名配置类接口 * Openapi For JCLOUD cdn * * OpenAPI spec version: v1 * Contact: pid-cdn@jd.com * * NOTE: This class is auto generated by the jdcloud code generator program. */ using JDCloudSDK.Core.Client; using JDCloudSDK.Core.Http; using System; using System.Collections.Generic; using System.Text; namespace JDCloudSDK.Cdn.Client { /// <summary> /// 查询用户推流域名app名/流名 /// </summary> public class QueryPushDomainORAppOrStreamExecutor : JdcloudExecutor { /// <summary> /// 查询用户推流域名app名/流名接口的Http 请求方法 /// </summary> public override string Method { get { return "GET"; } } /// <summary> /// 查询用户推流域名app名/流名接口的Http资源请求路径 /// </summary> public override string Url { get { return "/liveDomain/{domain}/stream:fuzzyQuery"; } } } }
25.433333
76
0.634338
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Cdn/Client/QueryPushDomainORAppOrStreamExecutor.cs
1,642
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace KagEditor.Wpf { public static class FctRegex { /// <summary> /// Efface toutes les lignes de script. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseScript(this KsFile MyFile) { MyFile.EraseTlaData(); MyFile.TextString = Regex.Replace(MyFile.TextString, @"@.*\n", string.Empty); } /// <summary> /// Efface la page '*tladata' jusqu'a la fin du fichier /// </summary> /// <param name="MyFile"></param> public static void EraseTlaData(this KsFile MyFile) { var matches = Regex.Matches(MyFile.TextString, @"\*tladata"); if (matches.Count > 0) { MyFile.TextString = MyFile.TextString.Remove(matches[matches.Count - 1].Index); } } /// <summary> /// Efface toutes les lignes de doublage. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseSay(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, @"^@say.*\n", string.Empty); } /// <summary> /// Efface toutes les lignes de commentaire. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseComment(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, "^;.*\n", string.Empty, RegexOptions.Multiline); } /// <summary> /// Efface toutes les lignes de commentaire. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseCommentedScript(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, "^;@.*\n", string.Empty, RegexOptions.Multiline); } /// <summary> /// Efface toutes les balises '[l][r]' ou '[lr]'. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseLR(this KsFile MyFile, bool isRealtaNua) { if (isRealtaNua) { MyFile.TextString = Regex.Replace(MyFile.TextString, "[[]lr[]]", string.Empty); } else { MyFile.TextString = Regex.Replace(MyFile.TextString, "[[]l[]][[]r[]]", string.Empty); } } /// <summary> /// Efface une couche de balises de Wrap. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseWrap(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, "[[]wrap text=\".*?\"[]]", string.Empty); } /// <summary> /// Efface toutes les balises '[r]'. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseSlashR(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, "[\r]", string.Empty); } /// <summary> /// Efface toutes les lignes 'pageX'. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void ErasePage(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, @"[*].*\n", string.Empty); } /// <summary> /// Efface les balises '[lineX]'. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void EraseLineX(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, @"[[]line.*[]]", string.Empty); } /// <summary> /// Compte le nombre de page d'un Fichier. /// </summary> /// <param name="MyFile">Fichier à traiter.</param> /// <returns>Nombre de pages du Fichier.</returns> public static int CountPage(this KsFile MyFile) { MatchCollection MyMatchCollection = Regex.Matches(MyFile.TextString, "[*]page"); return MyMatchCollection.Count; } /// <summary> /// Compte le nombre de mot de la liste de lignes d'un Fichier. /// </summary> /// <param name="MyFile">Fichier à traiter.</param> /// <returns>Nombre de pages du Fichiers.</returns> public static Int32 CountWord(this KsFile MyFile) { Regex myRegex = new Regex(@"\w"); int nbWords = (from line in MyFile.Lines from word in line.Split(null) where myRegex.IsMatch(word) select word).Count(); return nbWords; } /// <summary> /// Remplace les apostrophes par des simples quotes. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void ReplaceApostrophe(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, "‘", "'"); } /// <summary> /// Remplace les doubles quotes par des guillemets. /// </summary> /// <param name="MyFile">Fichier à nettoyer.</param> public static void ReplaceDoubleQuote(this KsFile MyFile) { MyFile.TextString = Regex.Replace(MyFile.TextString, " \"", " « "); MyFile.TextString = Regex.Replace(MyFile.TextString, "\"", " »"); } /// <summary> /// Teste si la ligne commence par un espace blanc. /// </summary> /// <param name="MyFile">Ligne à tester.</param> public static bool StartWithWhiteSpace(this string line) { return Regex.IsMatch(line, @"^\s"); } /// <summary> /// Teste si la ligne n'est pas une ligne technique. /// </summary> /// <param name="MyFile">Ligne à tester.</param> public static bool IsTechnical(this string line) { return Regex.IsMatch(line, @"^[@*;]") || Regex.IsMatch(line, @"^\[resettime\]"); } /// <summary> /// Teste si la ligne n'est pas un début de section tladata. /// </summary> /// <param name="MyFile">Ligne à tester.</param> public static bool IsTladata(this string line) { return line.StartsWith("*tladata"); } /// <summary> /// Remplace une balise type LineX par des tirets. /// </summary> /// <param name="line">Ligne à traiter.</param> /// <param name="regex">Expression régulière définissant la balise.</param> /// <param name="dash">Chaine de caractères contenant les tirets.</param> /// <returns>Ligne avec la balise word-wrapper.</returns> public static string ReplaceLineX(string line, string regex, string dash) { //On cherche toute les balises du type donnée MatchCollection ReplaceMatches = Regex.Matches(line, regex); //On efface la dernière balise trouvé line = line.Remove(ReplaceMatches[ReplaceMatches.Count - 1].Index, ReplaceMatches[ReplaceMatches.Count - 1].Length); //On insert les X tirets crée auparavant à la place line = line.Insert(ReplaceMatches[ReplaceMatches.Count - 1].Index, dash); return line; } /// <summary> /// Découpe les pages d'un texte en supprimant les balises *page. /// </summary> /// <param name="text">Le texte à découper.</param> /// <returns>La liste des pages.</returns> public static List<string> SplitPage(string text) { return Regex.Split(text, @"[*].*\n").ToList(); } /// <summary> /// Nettoye une liste de pages de tout caractère blanc ou de retour à la ligne. /// </summary> /// <param name="pages">Les pages à nettoyer.</param> /// <returns>Les pages nettoyées.</returns> public static List<string> CleanPages(List<string> pages) { return pages.Select(page => Regex.Replace(page, @"[[][^]]*[]]", String.Empty)) .Select(page => Regex.Replace(page, @"\W", String.Empty)).ToList(); } } }
36.9
114
0.549311
[ "MIT" ]
begerard/KagEditor
KagEditor/KagEditor.Wpf/FctRegex.cs
8,527
C#
namespace Astronomyfi.Web.Areas.Identity.Pages.Account { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using Astronomyfi.Data.Models; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; [AllowAnonymous] public class LoginModel : PageModel { private readonly UserManager<ApplicationUser> userManager; private readonly SignInManager<ApplicationUser> signInManager; private readonly ILogger<LoginModel> logger; public LoginModel( SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger, UserManager<ApplicationUser> userManager) { this.userManager = userManager; this.signInManager = signInManager; this.logger = logger; } [BindProperty] public InputModel Input { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public async Task OnGetAsync(string returnUrl = null) { if (!string.IsNullOrEmpty(this.ErrorMessage)) { this.ModelState.AddModelError(string.Empty, this.ErrorMessage); } returnUrl ??= this.Url.Content("~/"); await this.HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); this.ExternalLogins = (await this.signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); this.ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= this.Url.Content("~/"); this.ExternalLogins = (await this.signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (this.ModelState.IsValid) { var result = await this.signInManager.PasswordSignInAsync(this.Input.Username, this.Input.Password, this.Input.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { this.logger.LogInformation("User logged in."); return this.LocalRedirect(returnUrl); } if (result.RequiresTwoFactor) { return this.RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = this.Input.RememberMe }); } if (result.IsLockedOut) { this.logger.LogWarning("User account locked out."); return this.RedirectToPage("./Lockout"); } else { this.ModelState.AddModelError(string.Empty, "Invalid login attempt."); return this.Page(); } } return this.Page(); } public class InputModel { [Required] public string Username { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } } }
33.045045
164
0.591876
[ "MIT" ]
Ivan-Gyoshev/Astronomyfi
Astronomyfi/Web/Astronomyfi.Web/Areas/Identity/Pages/Account/Login.cshtml.cs
3,668
C#
namespace CodeComposerLib.Irony.Semantic.Expression.Value { public interface ILanguageValue : ILanguageExpressionAtomic { ILanguageValue DuplicateValue(bool deepCopy); } }
24.125
63
0.756477
[ "MIT" ]
ga-explorer/GMac
CodeComposerLib/CodeComposerLib/Irony/Semantic/Expression/Value/ILanguageValue.cs
195
C#
using System; using System.Text; using System.Web; using System.Web.Http.Description; namespace APIAUTH.Areas.HelpPage { public static class ApiDescriptionExtensions { /// <summary> /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" /// </summary> /// <param name="description">The <see cref="ApiDescription"/>.</param> /// <returns>The ID as a string.</returns> public static string GetFriendlyId(this ApiDescription description) { string path = description.RelativePath; string[] urlParts = path.Split('?'); string localPath = urlParts[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; queryKeyString = String.Join("_", queryKeys); } StringBuilder friendlyPath = new StringBuilder(); friendlyPath.AppendFormat("{0}-{1}", description.HttpMethod.Method, localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); if (queryKeyString != null) { friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); } return friendlyPath.ToString(); } } }
38.384615
144
0.571142
[ "MIT" ]
melquelima/WEB
C_SHARP_PROJECTS/APIAUTH/APIAUTH/Areas/HelpPage/ApiDescriptionExtensions.cs
1,497
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class SplitMediaOutputConfig : AbstractModel { /// <summary> /// Name of an output file. This parameter can contain up to 64 characters, and will be generated by the system if it is left empty. /// </summary> [JsonProperty("MediaName")] public string MediaName{ get; set; } /// <summary> /// Output file format. Valid values: mp4 (default), hls. /// </summary> [JsonProperty("Type")] public string Type{ get; set; } /// <summary> /// Category ID, which is used to categorize the media file for management. You can use [CreateClass](https://intl.cloud.tencent.com/document/product/266/7812?from_cn_redirect=1) API to create a category and get the category ID. /// <li>Default value: 0, which means other categories.</li> /// </summary> [JsonProperty("ClassId")] public long? ClassId{ get; set; } /// <summary> /// Expiration time of an output file. After passing the expiration time, the file will be deleted. There is no expiration time set for a file by default. The time is in [ISO date format](https://intl.cloud.tencent.com/document/product/266/11732?lang=en&pg=). /// </summary> [JsonProperty("ExpireTime")] public string ExpireTime{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "MediaName", this.MediaName); this.SetParamSimple(map, prefix + "Type", this.Type); this.SetParamSimple(map, prefix + "ClassId", this.ClassId); this.SetParamSimple(map, prefix + "ExpireTime", this.ExpireTime); } } }
40
267
0.649621
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Vod/V20180717/Models/SplitMediaOutputConfig.cs
2,640
C#
//=============================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation //=============================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=============================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=============================================================================== namespace StockTraderRI.Infrastructure { public class ExtendedHeader { public string ToolTip { get; set; } public string IconUri { get; set; } public string Title { get; set; } } }
48.269231
81
0.545817
[ "Apache-2.0" ]
andrewdbond/CompositeWPF
sourceCode/compositewpf/V1/trunk/Source/StockTraderRI/StockTraderRI.Infrastructure/ExtendedHeader.cs
1,255
C#
namespace Pk3DSRNGTool { partial class MiscRNGTool { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle28 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle36 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle29 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle30 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle31 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle32 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle33 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle34 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle35 = new System.Windows.Forms.DataGridViewCellStyle(); Pk3DSRNGTool.Controls.CheckBoxProperties checkBoxProperties2 = new Pk3DSRNGTool.Controls.CheckBoxProperties(); this.RNGInfo = new System.Windows.Forms.GroupBox(); this.TTT = new System.Windows.Forms.CheckBox(); this.L_Delay = new System.Windows.Forms.Label(); this.Delay = new System.Windows.Forms.NumericUpDown(); this.MaxResults = new System.Windows.Forms.NumericUpDown(); this.L_MaxResults = new System.Windows.Forms.Label(); this.NPC = new System.Windows.Forms.NumericUpDown(); this.StartingFrame = new System.Windows.Forms.NumericUpDown(); this.L_StartingFrame = new System.Windows.Forms.Label(); this.Seed = new Pk3DSRNGTool.Controls.HexMaskedTextBox(); this.label2 = new System.Windows.Forms.Label(); this.L_RNG = new System.Windows.Forms.Label(); this.RNG = new System.Windows.Forms.ComboBox(); this.L_NPC = new System.Windows.Forms.Label(); this.DGV = new System.Windows.Forms.DataGridView(); this.dgv_Frame = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_adv = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_hit = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_mark = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_clock = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_facility = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_pokerus = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_trainer = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_capture = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_SOS = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_randn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_state = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_rand = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_rand64 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_time = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgv_npcstatus = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.B_ResetFrame = new System.Windows.Forms.Button(); this.Range = new System.Windows.Forms.NumericUpDown(); this.Value = new System.Windows.Forms.NumericUpDown(); this.Compare = new System.Windows.Forms.ComboBox(); this.RB_Random = new System.Windows.Forms.RadioButton(); this.RB_Pokerus = new System.Windows.Forms.RadioButton(); this.L_CurrentSeed = new System.Windows.Forms.Label(); this.B_Calc = new System.Windows.Forms.Button(); this.Filters = new System.Windows.Forms.TabControl(); this.TP_Timeline = new System.Windows.Forms.TabPage(); this.CreateTimeline = new System.Windows.Forms.CheckBox(); this.Raining = new System.Windows.Forms.CheckBox(); this.Girl = new System.Windows.Forms.RadioButton(); this.Boy = new System.Windows.Forms.RadioButton(); this.Fidget = new System.Windows.Forms.CheckBox(); this.JumpFrame = new System.Windows.Forms.NumericUpDown(); this.TP_Misc = new System.Windows.Forms.TabPage(); this.BaseTimeText = new Pk3DSRNGTool.Controls.HexMaskedTextBox(); this.CurrentText = new Pk3DSRNGTool.Controls.HexMaskedTextBox(); this.L_TargetSeed = new System.Windows.Forms.Label(); this.RB_SavePar = new System.Windows.Forms.RadioButton(); this.L_BaseTime = new System.Windows.Forms.Label(); this.TP_Capture = new System.Windows.Forms.TabPage(); this.OPower = new System.Windows.Forms.ComboBox(); this.RotoCatch = new System.Windows.Forms.CheckBox(); this.SuccessOnly = new System.Windows.Forms.CheckBox(); this.CB_Detail = new System.Windows.Forms.CheckBox(); this.L_output = new System.Windows.Forms.Label(); this.Status = new System.Windows.Forms.ComboBox(); this.DexBonus = new System.Windows.Forms.ComboBox(); this.BallBonus = new System.Windows.Forms.ComboBox(); this.L_Dex = new System.Windows.Forms.Label(); this.L_Ball = new System.Windows.Forms.Label(); this.CatchRate = new System.Windows.Forms.NumericUpDown(); this.L_CatchRate = new System.Windows.Forms.Label(); this.HPMax = new System.Windows.Forms.NumericUpDown(); this.label_HP = new System.Windows.Forms.Label(); this.HPCurr = new System.Windows.Forms.NumericUpDown(); this.label6 = new System.Windows.Forms.Label(); this.TP_FP = new System.Windows.Forms.TabPage(); this.B_Help = new System.Windows.Forms.Button(); this.L_Color = new System.Windows.Forms.Label(); this.L_NPCType = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.L_Rank = new System.Windows.Forms.Label(); this.Color = new System.Windows.Forms.ComboBox(); this.NPCType = new System.Windows.Forms.ComboBox(); this.Stars = new System.Windows.Forms.ComboBox(); this.Facility = new System.Windows.Forms.ComboBox(); this.Rank = new System.Windows.Forms.ComboBox(); this.Game = new System.Windows.Forms.ComboBox(); this.TP_BattleTree = new System.Windows.Forms.TabPage(); this.L_TrainerName = new System.Windows.Forms.Label(); this.TrainerID = new System.Windows.Forms.NumericUpDown(); this.L_Trainer = new System.Windows.Forms.Label(); this.L_Streak = new System.Windows.Forms.Label(); this.Streak = new System.Windows.Forms.NumericUpDown(); this.TP_SOS = new System.Windows.Forms.TabPage(); this.L_Length = new System.Windows.Forms.Label(); this.ChainLength = new System.Windows.Forms.NumericUpDown(); this.HPBarColor = new System.Windows.Forms.ComboBox(); this.L_HPBarColor = new System.Windows.Forms.Label(); this.LastCallFail = new System.Windows.Forms.CheckBox(); this.SupperEffective = new System.Windows.Forms.CheckBox(); this.SameCaller = new System.Windows.Forms.CheckBox(); this.Intimidate = new System.Windows.Forms.CheckBox(); this.AO = new System.Windows.Forms.CheckBox(); this.L_Weather = new System.Windows.Forms.CheckBox(); this.L_CallRate = new System.Windows.Forms.Label(); this.CB_CallRate = new System.Windows.Forms.ComboBox(); this.TP_SOS2 = new System.Windows.Forms.TabPage(); this.Sync = new System.Windows.Forms.CheckBox(); this.L_Slot = new System.Windows.Forms.Label(); this.HA = new System.Windows.Forms.CheckBox(); this.Slot = new Pk3DSRNGTool.Controls.CheckBoxComboBox(); this.XY = new System.Windows.Forms.CheckBox(); this.ORAS = new System.Windows.Forms.CheckBox(); this.RNGInfo.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.Delay)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.MaxResults)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.NPC)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.StartingFrame)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.DGV)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Range)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Value)).BeginInit(); this.Filters.SuspendLayout(); this.TP_Timeline.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.JumpFrame)).BeginInit(); this.TP_Misc.SuspendLayout(); this.TP_Capture.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CatchRate)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HPMax)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HPCurr)).BeginInit(); this.TP_FP.SuspendLayout(); this.TP_BattleTree.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.TrainerID)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Streak)).BeginInit(); this.TP_SOS.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.ChainLength)).BeginInit(); this.TP_SOS2.SuspendLayout(); this.SuspendLayout(); // // RNGInfo // this.RNGInfo.BackColor = System.Drawing.Color.Transparent; this.RNGInfo.Controls.Add(this.TTT); this.RNGInfo.Controls.Add(this.L_Delay); this.RNGInfo.Controls.Add(this.Delay); this.RNGInfo.Controls.Add(this.MaxResults); this.RNGInfo.Controls.Add(this.L_MaxResults); this.RNGInfo.Controls.Add(this.NPC); this.RNGInfo.Controls.Add(this.StartingFrame); this.RNGInfo.Controls.Add(this.L_StartingFrame); this.RNGInfo.Controls.Add(this.Seed); this.RNGInfo.Controls.Add(this.label2); this.RNGInfo.Controls.Add(this.L_RNG); this.RNGInfo.Controls.Add(this.RNG); this.RNGInfo.Controls.Add(this.L_NPC); this.RNGInfo.Location = new System.Drawing.Point(12, 12); this.RNGInfo.Name = "RNGInfo"; this.RNGInfo.Size = new System.Drawing.Size(209, 215); this.RNGInfo.TabIndex = 0; this.RNGInfo.TabStop = false; this.RNGInfo.Text = "RNGInfo"; // // TTT // this.TTT.AutoSize = true; this.TTT.Location = new System.Drawing.Point(66, 69); this.TTT.Name = "TTT"; this.TTT.Size = new System.Drawing.Size(59, 17); this.TTT.TabIndex = 116; this.TTT.Text = "TTT ->"; this.TTT.UseVisualStyleBackColor = true; this.TTT.CheckedChanged += new System.EventHandler(this.TTT_CheckedChanged); // // L_Delay // this.L_Delay.AutoSize = true; this.L_Delay.Location = new System.Drawing.Point(12, 184); this.L_Delay.Name = "L_Delay"; this.L_Delay.Size = new System.Drawing.Size(34, 13); this.L_Delay.TabIndex = 51; this.L_Delay.Text = "Delay"; // // Delay // this.Delay.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Delay.Location = new System.Drawing.Point(51, 180); this.Delay.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this.Delay.Name = "Delay"; this.Delay.Size = new System.Drawing.Size(49, 22); this.Delay.TabIndex = 50; // // MaxResults // this.MaxResults.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.MaxResults.Location = new System.Drawing.Point(105, 142); this.MaxResults.Name = "MaxResults"; this.MaxResults.Size = new System.Drawing.Size(89, 22); this.MaxResults.TabIndex = 5; this.MaxResults.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // L_MaxResults // this.L_MaxResults.AutoSize = true; this.L_MaxResults.Location = new System.Drawing.Point(12, 144); this.L_MaxResults.Name = "L_MaxResults"; this.L_MaxResults.Size = new System.Drawing.Size(65, 13); this.L_MaxResults.TabIndex = 4; this.L_MaxResults.Text = "Max Results"; // // NPC // this.NPC.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.NPC.Location = new System.Drawing.Point(159, 180); this.NPC.Name = "NPC"; this.NPC.Size = new System.Drawing.Size(35, 22); this.NPC.TabIndex = 48; // // StartingFrame // this.StartingFrame.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.StartingFrame.Location = new System.Drawing.Point(105, 104); this.StartingFrame.Name = "StartingFrame"; this.StartingFrame.Size = new System.Drawing.Size(89, 22); this.StartingFrame.TabIndex = 1; this.StartingFrame.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // L_StartingFrame // this.L_StartingFrame.AutoSize = true; this.L_StartingFrame.Location = new System.Drawing.Point(12, 106); this.L_StartingFrame.Name = "L_StartingFrame"; this.L_StartingFrame.Size = new System.Drawing.Size(75, 13); this.L_StartingFrame.TabIndex = 3; this.L_StartingFrame.Text = "Starting Frame"; // // Seed // this.Seed.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Seed.Location = new System.Drawing.Point(127, 66); this.Seed.Mask = "AAAAAAAA"; this.Seed.Name = "Seed"; this.Seed.Size = new System.Drawing.Size(67, 23); this.Seed.TabIndex = 1; this.Seed.Text = "00000000"; this.Seed.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.Seed.Value = ((uint)(0u)); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 70); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(32, 13); this.label2.TabIndex = 2; this.label2.Text = "Seed"; // // L_RNG // this.L_RNG.AutoSize = true; this.L_RNG.Location = new System.Drawing.Point(12, 32); this.L_RNG.Name = "L_RNG"; this.L_RNG.Size = new System.Drawing.Size(31, 13); this.L_RNG.TabIndex = 1; this.L_RNG.Text = "RNG"; // // RNG // this.RNG.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.RNG.FormattingEnabled = true; this.RNG.Items.AddRange(new object[] { "G7 SFMT (64bit)", "G7 SFMT (32bit)", "G6 MT", "G6 TinyMT"}); this.RNG.Location = new System.Drawing.Point(90, 29); this.RNG.Name = "RNG"; this.RNG.Size = new System.Drawing.Size(104, 21); this.RNG.TabIndex = 1; this.RNG.SelectedIndexChanged += new System.EventHandler(this.RNG_SelectedIndexChanged); // // L_NPC // this.L_NPC.AutoSize = true; this.L_NPC.Location = new System.Drawing.Point(102, 184); this.L_NPC.Name = "L_NPC"; this.L_NPC.Size = new System.Drawing.Size(29, 13); this.L_NPC.TabIndex = 49; this.L_NPC.Text = "NPC"; // // DGV // this.DGV.AllowUserToAddRows = false; this.DGV.AllowUserToDeleteRows = false; this.DGV.AllowUserToResizeRows = false; this.DGV.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); dataGridViewCellStyle28.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle28.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle28.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); dataGridViewCellStyle28.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle28.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle28.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle28.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.DGV.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle28; this.DGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.DGV.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dgv_Frame, this.dgv_adv, this.dgv_hit, this.dgv_mark, this.dgv_clock, this.dgv_facility, this.dgv_pokerus, this.dgv_trainer, this.dgv_capture, this.dgv_SOS, this.dgv_randn, this.dgv_state, this.dgv_rand, this.dgv_rand64, this.dgv_time, this.dgv_npcstatus}); this.DGV.Location = new System.Drawing.Point(227, 12); this.DGV.Name = "DGV"; this.DGV.ReadOnly = true; this.DGV.RowHeadersWidth = 14; dataGridViewCellStyle36.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight; this.DGV.RowsDefaultCellStyle = dataGridViewCellStyle36; this.DGV.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.DGV.Size = new System.Drawing.Size(445, 458); this.DGV.TabIndex = 1; // // dgv_Frame // this.dgv_Frame.DataPropertyName = "Frame"; this.dgv_Frame.HeaderText = "Frame"; this.dgv_Frame.Name = "dgv_Frame"; this.dgv_Frame.ReadOnly = true; this.dgv_Frame.Width = 55; // // dgv_adv // this.dgv_adv.DataPropertyName = "Advance"; dataGridViewCellStyle29.Format = "+#"; this.dgv_adv.DefaultCellStyle = dataGridViewCellStyle29; this.dgv_adv.HeaderText = "Adv."; this.dgv_adv.Name = "dgv_adv"; this.dgv_adv.ReadOnly = true; this.dgv_adv.Visible = false; this.dgv_adv.Width = 40; // // dgv_hit // this.dgv_hit.DataPropertyName = "ActualFrame"; this.dgv_hit.HeaderText = "Actual Hit"; this.dgv_hit.Name = "dgv_hit"; this.dgv_hit.ReadOnly = true; this.dgv_hit.Visible = false; this.dgv_hit.Width = 55; // // dgv_mark // this.dgv_mark.DataPropertyName = "Blinkflag"; dataGridViewCellStyle30.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; this.dgv_mark.DefaultCellStyle = dataGridViewCellStyle30; this.dgv_mark.HeaderText = "Blink"; this.dgv_mark.Name = "dgv_mark"; this.dgv_mark.ReadOnly = true; this.dgv_mark.Width = 40; // // dgv_clock // this.dgv_clock.DataPropertyName = "Clock"; this.dgv_clock.HeaderText = "Clk"; this.dgv_clock.Name = "dgv_clock"; this.dgv_clock.ReadOnly = true; this.dgv_clock.Width = 40; // // dgv_facility // this.dgv_facility.DataPropertyName = "Facility"; this.dgv_facility.HeaderText = "Facility"; this.dgv_facility.Name = "dgv_facility"; this.dgv_facility.ReadOnly = true; this.dgv_facility.Visible = false; this.dgv_facility.Width = 160; // // dgv_pokerus // this.dgv_pokerus.DataPropertyName = "Pokerus"; this.dgv_pokerus.HeaderText = "Pokerus"; this.dgv_pokerus.Name = "dgv_pokerus"; this.dgv_pokerus.ReadOnly = true; this.dgv_pokerus.Width = 55; // // dgv_trainer // this.dgv_trainer.DataPropertyName = "Trainer"; this.dgv_trainer.HeaderText = "TrainerID"; this.dgv_trainer.Name = "dgv_trainer"; this.dgv_trainer.ReadOnly = true; this.dgv_trainer.Visible = false; this.dgv_trainer.Width = 55; // // dgv_capture // this.dgv_capture.DataPropertyName = "Capture"; dataGridViewCellStyle31.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dgv_capture.DefaultCellStyle = dataGridViewCellStyle31; this.dgv_capture.HeaderText = "Capture"; this.dgv_capture.Name = "dgv_capture"; this.dgv_capture.ReadOnly = true; this.dgv_capture.Visible = false; this.dgv_capture.Width = 70; // // dgv_SOS // this.dgv_SOS.DataPropertyName = "SOS"; this.dgv_SOS.HeaderText = "SOS"; this.dgv_SOS.Name = "dgv_SOS"; this.dgv_SOS.ReadOnly = true; this.dgv_SOS.Visible = false; this.dgv_SOS.Width = 200; // // dgv_randn // this.dgv_randn.DataPropertyName = "RandN"; this.dgv_randn.HeaderText = "R(N)"; this.dgv_randn.Name = "dgv_randn"; this.dgv_randn.ReadOnly = true; this.dgv_randn.Width = 40; // // dgv_state // this.dgv_state.DataPropertyName = "CurrentSeed"; dataGridViewCellStyle32.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dgv_state.DefaultCellStyle = dataGridViewCellStyle32; this.dgv_state.HeaderText = "Curr Seed"; this.dgv_state.Name = "dgv_state"; this.dgv_state.ReadOnly = true; this.dgv_state.Visible = false; // // dgv_rand // this.dgv_rand.DataPropertyName = "Rand32"; dataGridViewCellStyle33.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle33.Format = "X8"; this.dgv_rand.DefaultCellStyle = dataGridViewCellStyle33; this.dgv_rand.HeaderText = "Random#"; this.dgv_rand.Name = "dgv_rand"; this.dgv_rand.ReadOnly = true; this.dgv_rand.Visible = false; this.dgv_rand.Width = 70; // // dgv_rand64 // this.dgv_rand64.DataPropertyName = "Rand64"; dataGridViewCellStyle34.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle34.Format = "X16"; this.dgv_rand64.DefaultCellStyle = dataGridViewCellStyle34; this.dgv_rand64.HeaderText = "Random Number"; this.dgv_rand64.Name = "dgv_rand64"; this.dgv_rand64.ReadOnly = true; this.dgv_rand64.Width = 123; // // dgv_time // this.dgv_time.DataPropertyName = "Realtime"; this.dgv_time.HeaderText = "Time"; this.dgv_time.Name = "dgv_time"; this.dgv_time.ReadOnly = true; this.dgv_time.Width = 80; // // dgv_npcstatus // this.dgv_npcstatus.DataPropertyName = "NPCStatus"; dataGridViewCellStyle35.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dgv_npcstatus.DefaultCellStyle = dataGridViewCellStyle35; this.dgv_npcstatus.HeaderText = "NPC"; this.dgv_npcstatus.Name = "dgv_npcstatus"; this.dgv_npcstatus.ReadOnly = true; this.dgv_npcstatus.Visible = false; this.dgv_npcstatus.Width = 40; // // B_ResetFrame // this.B_ResetFrame.Image = global::Pk3DSRNGTool.Properties.Resources.Reset; this.B_ResetFrame.Location = new System.Drawing.Point(173, 142); this.B_ResetFrame.Name = "B_ResetFrame"; this.B_ResetFrame.Size = new System.Drawing.Size(27, 25); this.B_ResetFrame.TabIndex = 101; this.B_ResetFrame.UseVisualStyleBackColor = true; this.B_ResetFrame.Click += new System.EventHandler(this.B_ResetFrame_Click); // // Range // this.Range.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Range.Location = new System.Drawing.Point(92, 70); this.Range.Name = "Range"; this.Range.Size = new System.Drawing.Size(71, 22); this.Range.TabIndex = 57; this.Range.Value = new decimal(new int[] { 100, 0, 0, 0}); // // Value // this.Value.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Value.Location = new System.Drawing.Point(92, 102); this.Value.Name = "Value"; this.Value.Size = new System.Drawing.Size(71, 22); this.Value.TabIndex = 52; this.Value.Value = new decimal(new int[] { 100, 0, 0, 0}); // // Compare // this.Compare.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Compare.FormattingEnabled = true; this.Compare.Items.AddRange(new object[] { "<", ">=", "="}); this.Compare.Location = new System.Drawing.Point(11, 101); this.Compare.Name = "Compare"; this.Compare.Size = new System.Drawing.Size(54, 21); this.Compare.TabIndex = 54; // // RB_Random // this.RB_Random.AutoSize = true; this.RB_Random.Checked = true; this.RB_Random.Location = new System.Drawing.Point(10, 70); this.RB_Random.Name = "RB_Random"; this.RB_Random.Size = new System.Drawing.Size(76, 17); this.RB_Random.TabIndex = 56; this.RB_Random.TabStop = true; this.RB_Random.Text = "Random N"; this.RB_Random.UseVisualStyleBackColor = true; this.RB_Random.CheckedChanged += new System.EventHandler(this.Method_CheckedChanged); // // RB_Pokerus // this.RB_Pokerus.AutoSize = true; this.RB_Pokerus.Location = new System.Drawing.Point(11, 129); this.RB_Pokerus.Name = "RB_Pokerus"; this.RB_Pokerus.Size = new System.Drawing.Size(64, 17); this.RB_Pokerus.TabIndex = 55; this.RB_Pokerus.Text = "Pokerus"; this.RB_Pokerus.UseVisualStyleBackColor = true; this.RB_Pokerus.CheckedChanged += new System.EventHandler(this.Method_CheckedChanged); // // L_CurrentSeed // this.L_CurrentSeed.AutoSize = true; this.L_CurrentSeed.Location = new System.Drawing.Point(8, 7); this.L_CurrentSeed.Name = "L_CurrentSeed"; this.L_CurrentSeed.Size = new System.Drawing.Size(41, 13); this.L_CurrentSeed.TabIndex = 52; this.L_CurrentSeed.Text = "Current"; // // B_Calc // this.B_Calc.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.B_Calc.Location = new System.Drawing.Point(146, 441); this.B_Calc.Name = "B_Calc"; this.B_Calc.Size = new System.Drawing.Size(75, 29); this.B_Calc.TabIndex = 53; this.B_Calc.Text = "Search"; this.B_Calc.UseVisualStyleBackColor = true; this.B_Calc.Click += new System.EventHandler(this.B_Calc_Click); // // Filters // this.Filters.Controls.Add(this.TP_Timeline); this.Filters.Controls.Add(this.TP_Misc); this.Filters.Controls.Add(this.TP_Capture); this.Filters.Controls.Add(this.TP_FP); this.Filters.Controls.Add(this.TP_BattleTree); this.Filters.Controls.Add(this.TP_SOS); this.Filters.Controls.Add(this.TP_SOS2); this.Filters.Location = new System.Drawing.Point(10, 243); this.Filters.Name = "Filters"; this.Filters.SelectedIndex = 0; this.Filters.Size = new System.Drawing.Size(211, 196); this.Filters.TabIndex = 54; this.Filters.SelectedIndexChanged += new System.EventHandler(this.RNG_SelectedIndexChanged); // // TP_Timeline // this.TP_Timeline.Controls.Add(this.CreateTimeline); this.TP_Timeline.Controls.Add(this.Raining); this.TP_Timeline.Controls.Add(this.Girl); this.TP_Timeline.Controls.Add(this.Boy); this.TP_Timeline.Controls.Add(this.Fidget); this.TP_Timeline.Controls.Add(this.JumpFrame); this.TP_Timeline.Location = new System.Drawing.Point(4, 22); this.TP_Timeline.Name = "TP_Timeline"; this.TP_Timeline.Padding = new System.Windows.Forms.Padding(3); this.TP_Timeline.Size = new System.Drawing.Size(203, 170); this.TP_Timeline.TabIndex = 1; this.TP_Timeline.Text = "Timeline"; this.TP_Timeline.UseVisualStyleBackColor = true; // // CreateTimeline // this.CreateTimeline.AutoSize = true; this.CreateTimeline.Location = new System.Drawing.Point(11, 20); this.CreateTimeline.Name = "CreateTimeline"; this.CreateTimeline.Size = new System.Drawing.Size(99, 17); this.CreateTimeline.TabIndex = 115; this.CreateTimeline.Text = "Create Timeline"; this.CreateTimeline.UseVisualStyleBackColor = true; this.CreateTimeline.CheckedChanged += new System.EventHandler(this.RNG_SelectedIndexChanged); // // Raining // this.Raining.AutoSize = true; this.Raining.Location = new System.Drawing.Point(11, 105); this.Raining.Name = "Raining"; this.Raining.Size = new System.Drawing.Size(62, 17); this.Raining.TabIndex = 114; this.Raining.Text = "Raining"; this.Raining.UseVisualStyleBackColor = true; // // Girl // this.Girl.AutoSize = true; this.Girl.Location = new System.Drawing.Point(151, 73); this.Girl.Name = "Girl"; this.Girl.Size = new System.Drawing.Size(40, 17); this.Girl.TabIndex = 113; this.Girl.Text = "Girl"; this.Girl.UseVisualStyleBackColor = true; this.Girl.Visible = false; // // Boy // this.Boy.AutoSize = true; this.Boy.Checked = true; this.Boy.Location = new System.Drawing.Point(151, 50); this.Boy.Name = "Boy"; this.Boy.Size = new System.Drawing.Size(43, 17); this.Boy.TabIndex = 112; this.Boy.TabStop = true; this.Boy.Text = "Boy"; this.Boy.UseVisualStyleBackColor = true; this.Boy.Visible = false; // // Fidget // this.Fidget.AutoSize = true; this.Fidget.Location = new System.Drawing.Point(11, 62); this.Fidget.Name = "Fidget"; this.Fidget.Size = new System.Drawing.Size(55, 17); this.Fidget.TabIndex = 111; this.Fidget.Text = "Fidget"; this.Fidget.UseVisualStyleBackColor = true; this.Fidget.CheckedChanged += new System.EventHandler(this.Fidget_CheckedChanged); // // JumpFrame // this.JumpFrame.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.JumpFrame.Location = new System.Drawing.Point(68, 57); this.JumpFrame.Name = "JumpFrame"; this.JumpFrame.Size = new System.Drawing.Size(76, 22); this.JumpFrame.TabIndex = 110; this.JumpFrame.Visible = false; // // TP_Misc // this.TP_Misc.Controls.Add(this.ORAS); this.TP_Misc.Controls.Add(this.XY); this.TP_Misc.Controls.Add(this.BaseTimeText); this.TP_Misc.Controls.Add(this.CurrentText); this.TP_Misc.Controls.Add(this.L_TargetSeed); this.TP_Misc.Controls.Add(this.RB_SavePar); this.TP_Misc.Controls.Add(this.L_BaseTime); this.TP_Misc.Controls.Add(this.B_ResetFrame); this.TP_Misc.Controls.Add(this.Range); this.TP_Misc.Controls.Add(this.L_CurrentSeed); this.TP_Misc.Controls.Add(this.Value); this.TP_Misc.Controls.Add(this.RB_Pokerus); this.TP_Misc.Controls.Add(this.Compare); this.TP_Misc.Controls.Add(this.RB_Random); this.TP_Misc.Location = new System.Drawing.Point(4, 22); this.TP_Misc.Name = "TP_Misc"; this.TP_Misc.Padding = new System.Windows.Forms.Padding(3); this.TP_Misc.Size = new System.Drawing.Size(203, 170); this.TP_Misc.TabIndex = 0; this.TP_Misc.Text = "Misc"; this.TP_Misc.UseVisualStyleBackColor = true; // // BaseTimeText // this.BaseTimeText.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.BaseTimeText.Location = new System.Drawing.Point(92, 36); this.BaseTimeText.Mask = "AAAAAAAA"; this.BaseTimeText.Name = "BaseTimeText"; this.BaseTimeText.Size = new System.Drawing.Size(71, 23); this.BaseTimeText.TabIndex = 118; this.BaseTimeText.Text = "00000000"; this.BaseTimeText.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.BaseTimeText.Value = ((uint)(0u)); this.BaseTimeText.Visible = false; // // CurrentText // this.CurrentText.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.CurrentText.Location = new System.Drawing.Point(92, 4); this.CurrentText.Mask = "AAAAAAAA"; this.CurrentText.Name = "CurrentText"; this.CurrentText.Size = new System.Drawing.Size(71, 23); this.CurrentText.TabIndex = 117; this.CurrentText.Text = "00000000"; this.CurrentText.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.CurrentText.Value = ((uint)(0u)); // // L_TargetSeed // this.L_TargetSeed.AutoSize = true; this.L_TargetSeed.Location = new System.Drawing.Point(8, 7); this.L_TargetSeed.Name = "L_TargetSeed"; this.L_TargetSeed.Size = new System.Drawing.Size(66, 13); this.L_TargetSeed.TabIndex = 105; this.L_TargetSeed.Text = "Target Seed"; this.L_TargetSeed.Visible = false; // // RB_SavePar // this.RB_SavePar.AutoSize = true; this.RB_SavePar.Location = new System.Drawing.Point(92, 129); this.RB_SavePar.Name = "RB_SavePar"; this.RB_SavePar.Size = new System.Drawing.Size(72, 17); this.RB_SavePar.TabIndex = 104; this.RB_SavePar.Text = "Save Par."; this.RB_SavePar.UseVisualStyleBackColor = true; this.RB_SavePar.CheckedChanged += new System.EventHandler(this.RB_SavePar_CheckedChanged); // // L_BaseTime // this.L_BaseTime.AutoSize = true; this.L_BaseTime.Location = new System.Drawing.Point(8, 39); this.L_BaseTime.Name = "L_BaseTime"; this.L_BaseTime.Size = new System.Drawing.Size(54, 13); this.L_BaseTime.TabIndex = 103; this.L_BaseTime.Text = "BaseTime"; this.L_BaseTime.Visible = false; // // TP_Capture // this.TP_Capture.Controls.Add(this.OPower); this.TP_Capture.Controls.Add(this.RotoCatch); this.TP_Capture.Controls.Add(this.SuccessOnly); this.TP_Capture.Controls.Add(this.CB_Detail); this.TP_Capture.Controls.Add(this.L_output); this.TP_Capture.Controls.Add(this.Status); this.TP_Capture.Controls.Add(this.DexBonus); this.TP_Capture.Controls.Add(this.BallBonus); this.TP_Capture.Controls.Add(this.L_Dex); this.TP_Capture.Controls.Add(this.L_Ball); this.TP_Capture.Controls.Add(this.CatchRate); this.TP_Capture.Controls.Add(this.L_CatchRate); this.TP_Capture.Controls.Add(this.HPMax); this.TP_Capture.Controls.Add(this.label_HP); this.TP_Capture.Controls.Add(this.HPCurr); this.TP_Capture.Controls.Add(this.label6); this.TP_Capture.Location = new System.Drawing.Point(4, 22); this.TP_Capture.Name = "TP_Capture"; this.TP_Capture.Size = new System.Drawing.Size(203, 170); this.TP_Capture.TabIndex = 2; this.TP_Capture.Text = "Capture"; this.TP_Capture.UseVisualStyleBackColor = true; // // OPower // this.OPower.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.OPower.DropDownWidth = 100; this.OPower.FormattingEnabled = true; this.OPower.Items.AddRange(new object[] { "No Opower", "Level 1", "Level 2", "Level 3/S/MAX"}); this.OPower.Location = new System.Drawing.Point(142, 103); this.OPower.Name = "OPower"; this.OPower.Size = new System.Drawing.Size(57, 21); this.OPower.TabIndex = 119; // // RotoCatch // this.RotoCatch.AutoSize = true; this.RotoCatch.Location = new System.Drawing.Point(150, 106); this.RotoCatch.Name = "RotoCatch"; this.RotoCatch.Size = new System.Drawing.Size(49, 17); this.RotoCatch.TabIndex = 118; this.RotoCatch.Text = "Roto"; this.RotoCatch.UseVisualStyleBackColor = true; // // SuccessOnly // this.SuccessOnly.AutoSize = true; this.SuccessOnly.Location = new System.Drawing.Point(80, 13); this.SuccessOnly.Name = "SuccessOnly"; this.SuccessOnly.Size = new System.Drawing.Size(91, 17); this.SuccessOnly.TabIndex = 117; this.SuccessOnly.Text = "Success Only"; this.SuccessOnly.UseVisualStyleBackColor = true; // // CB_Detail // this.CB_Detail.AutoSize = true; this.CB_Detail.Location = new System.Drawing.Point(9, 13); this.CB_Detail.Name = "CB_Detail"; this.CB_Detail.Size = new System.Drawing.Size(58, 17); this.CB_Detail.TabIndex = 116; this.CB_Detail.Text = "Details"; this.CB_Detail.UseVisualStyleBackColor = true; // // L_output // this.L_output.AutoSize = true; this.L_output.Location = new System.Drawing.Point(4, 137); this.L_output.Name = "L_output"; this.L_output.Size = new System.Drawing.Size(47, 13); this.L_output.TabIndex = 62; this.L_output.Text = "Chance:"; // // Status // this.Status.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Status.FormattingEnabled = true; this.Status.Items.AddRange(new object[] { "G7 SFMT (64bit)", "G7 SFMT (32bit)", "G6 MT"}); this.Status.Location = new System.Drawing.Point(134, 43); this.Status.Name = "Status"; this.Status.Size = new System.Drawing.Size(55, 21); this.Status.TabIndex = 61; // // DexBonus // this.DexBonus.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.DexBonus.FormattingEnabled = true; this.DexBonus.Items.AddRange(new object[] { "G7 SFMT (64bit)", "G7 SFMT (32bit)", "G6 MT"}); this.DexBonus.Location = new System.Drawing.Point(71, 103); this.DexBonus.Name = "DexBonus"; this.DexBonus.Size = new System.Drawing.Size(65, 21); this.DexBonus.TabIndex = 60; // // BallBonus // this.BallBonus.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.BallBonus.FormattingEnabled = true; this.BallBonus.Items.AddRange(new object[] { "G7 SFMT (64bit)", "G7 SFMT (32bit)", "G6 MT"}); this.BallBonus.Location = new System.Drawing.Point(143, 73); this.BallBonus.Name = "BallBonus"; this.BallBonus.Size = new System.Drawing.Size(47, 21); this.BallBonus.TabIndex = 52; // // L_Dex // this.L_Dex.AutoSize = true; this.L_Dex.Location = new System.Drawing.Point(4, 107); this.L_Dex.Name = "L_Dex"; this.L_Dex.Size = new System.Drawing.Size(63, 13); this.L_Dex.TabIndex = 59; this.L_Dex.Text = "Dex Caught"; // // L_Ball // this.L_Ball.AutoSize = true; this.L_Ball.Location = new System.Drawing.Point(115, 77); this.L_Ball.Name = "L_Ball"; this.L_Ball.Size = new System.Drawing.Size(24, 13); this.L_Ball.TabIndex = 58; this.L_Ball.Text = "Ball"; // // CatchRate // this.CatchRate.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.CatchRate.Location = new System.Drawing.Point(69, 72); this.CatchRate.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.CatchRate.Name = "CatchRate"; this.CatchRate.Size = new System.Drawing.Size(42, 22); this.CatchRate.TabIndex = 57; this.CatchRate.Value = new decimal(new int[] { 3, 0, 0, 0}); // // L_CatchRate // this.L_CatchRate.AutoSize = true; this.L_CatchRate.Location = new System.Drawing.Point(4, 77); this.L_CatchRate.Name = "L_CatchRate"; this.L_CatchRate.Size = new System.Drawing.Size(61, 13); this.L_CatchRate.TabIndex = 56; this.L_CatchRate.Text = "Catch Rate"; // // HPMax // this.HPMax.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.HPMax.Location = new System.Drawing.Point(89, 42); this.HPMax.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.HPMax.Name = "HPMax"; this.HPMax.Size = new System.Drawing.Size(42, 22); this.HPMax.TabIndex = 55; this.HPMax.Value = new decimal(new int[] { 208, 0, 0, 0}); this.HPMax.ValueChanged += new System.EventHandler(this.HP_ValueChanged); // // label_HP // this.label_HP.AutoSize = true; this.label_HP.Location = new System.Drawing.Point(4, 47); this.label_HP.Name = "label_HP"; this.label_HP.Size = new System.Drawing.Size(22, 13); this.label_HP.TabIndex = 53; this.label_HP.Text = "HP"; // // HPCurr // this.HPCurr.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.HPCurr.Location = new System.Drawing.Point(29, 42); this.HPCurr.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.HPCurr.Name = "HPCurr"; this.HPCurr.Size = new System.Drawing.Size(42, 22); this.HPCurr.TabIndex = 52; this.HPCurr.Value = new decimal(new int[] { 1, 0, 0, 0}); this.HPCurr.ValueChanged += new System.EventHandler(this.HP_ValueChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(74, 47); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(12, 13); this.label6.TabIndex = 54; this.label6.Text = "/"; // // TP_FP // this.TP_FP.Controls.Add(this.B_Help); this.TP_FP.Controls.Add(this.L_Color); this.TP_FP.Controls.Add(this.L_NPCType); this.TP_FP.Controls.Add(this.label8); this.TP_FP.Controls.Add(this.L_Rank); this.TP_FP.Controls.Add(this.Color); this.TP_FP.Controls.Add(this.NPCType); this.TP_FP.Controls.Add(this.Stars); this.TP_FP.Controls.Add(this.Facility); this.TP_FP.Controls.Add(this.Rank); this.TP_FP.Controls.Add(this.Game); this.TP_FP.Location = new System.Drawing.Point(4, 22); this.TP_FP.Name = "TP_FP"; this.TP_FP.Padding = new System.Windows.Forms.Padding(3); this.TP_FP.Size = new System.Drawing.Size(203, 170); this.TP_FP.TabIndex = 3; this.TP_FP.Text = "Festival Plaza"; this.TP_FP.UseVisualStyleBackColor = true; // // B_Help // this.B_Help.Image = global::Pk3DSRNGTool.Properties.Resources.Info; this.B_Help.Location = new System.Drawing.Point(173, 142); this.B_Help.Name = "B_Help"; this.B_Help.Size = new System.Drawing.Size(27, 25); this.B_Help.TabIndex = 122; this.B_Help.UseVisualStyleBackColor = true; this.B_Help.Click += new System.EventHandler(this.B_Help_Click); // // L_Color // this.L_Color.AutoSize = true; this.L_Color.Location = new System.Drawing.Point(123, 109); this.L_Color.Name = "L_Color"; this.L_Color.Size = new System.Drawing.Size(31, 13); this.L_Color.TabIndex = 63; this.L_Color.Text = "Color"; // // L_NPCType // this.L_NPCType.AutoSize = true; this.L_NPCType.Location = new System.Drawing.Point(10, 109); this.L_NPCType.Name = "L_NPCType"; this.L_NPCType.Size = new System.Drawing.Size(29, 13); this.L_NPCType.TabIndex = 62; this.L_NPCType.Text = "NPC"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(133, 66); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(16, 13); this.label8.TabIndex = 61; this.label8.Text = "★"; // // L_Rank // this.L_Rank.AutoSize = true; this.L_Rank.Location = new System.Drawing.Point(100, 26); this.L_Rank.Name = "L_Rank"; this.L_Rank.Size = new System.Drawing.Size(33, 13); this.L_Rank.TabIndex = 52; this.L_Rank.Text = "Rank"; // // Color // this.Color.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Color.FormattingEnabled = true; this.Color.Items.AddRange(new object[] { "-", "0", "1", "2", "3"}); this.Color.Location = new System.Drawing.Point(156, 106); this.Color.Name = "Color"; this.Color.Size = new System.Drawing.Size(36, 21); this.Color.TabIndex = 60; // // NPCType // this.NPCType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.NPCType.FormattingEnabled = true; this.NPCType.Items.AddRange(new object[] { "-", "Ace Trainer F", "Ace Trainer M", "Veteran F", "Veteran M", "Office Worker M", "Office Worker F", "Punk Guy", "Punk Girl", "Breeder M", "Breeder F", "Youngster", "Lass"}); this.NPCType.Location = new System.Drawing.Point(39, 106); this.NPCType.Name = "NPCType"; this.NPCType.Size = new System.Drawing.Size(81, 21); this.NPCType.TabIndex = 59; // // Stars // this.Stars.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Stars.FormattingEnabled = true; this.Stars.Items.AddRange(new object[] { "-", "1", "2", "3", "4", "5"}); this.Stars.Location = new System.Drawing.Point(156, 63); this.Stars.Name = "Stars"; this.Stars.Size = new System.Drawing.Size(36, 21); this.Stars.TabIndex = 58; this.Stars.SelectedIndexChanged += new System.EventHandler(this.FacilityPool_Changed); // // Facility // this.Facility.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Facility.FormattingEnabled = true; this.Facility.Location = new System.Drawing.Point(15, 63); this.Facility.Name = "Facility"; this.Facility.Size = new System.Drawing.Size(104, 21); this.Facility.TabIndex = 57; // // Rank // this.Rank.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Rank.FormattingEnabled = true; this.Rank.Items.AddRange(new object[] { "<=2", "3", "4", "5", "6", "7", "8", "9", "10", "11-20", "21-30", "31-40", "41-50", "51-60", "61-70", "71-80", "81-90", "91-99", "100+"}); this.Rank.Location = new System.Drawing.Point(139, 23); this.Rank.Name = "Rank"; this.Rank.Size = new System.Drawing.Size(57, 21); this.Rank.TabIndex = 56; // // Game // this.Game.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Game.FormattingEnabled = true; this.Game.Items.AddRange(new object[] { "Sun", "Moon", "Ultra Sun", "Ultra Moon"}); this.Game.Location = new System.Drawing.Point(15, 23); this.Game.Name = "Game"; this.Game.Size = new System.Drawing.Size(80, 21); this.Game.TabIndex = 55; this.Game.SelectedIndexChanged += new System.EventHandler(this.FacilityPool_Changed); // // TP_BattleTree // this.TP_BattleTree.Controls.Add(this.L_TrainerName); this.TP_BattleTree.Controls.Add(this.TrainerID); this.TP_BattleTree.Controls.Add(this.L_Trainer); this.TP_BattleTree.Controls.Add(this.L_Streak); this.TP_BattleTree.Controls.Add(this.Streak); this.TP_BattleTree.Location = new System.Drawing.Point(4, 22); this.TP_BattleTree.Name = "TP_BattleTree"; this.TP_BattleTree.Padding = new System.Windows.Forms.Padding(3); this.TP_BattleTree.Size = new System.Drawing.Size(203, 170); this.TP_BattleTree.TabIndex = 4; this.TP_BattleTree.Text = "Battle Tree"; this.TP_BattleTree.UseVisualStyleBackColor = true; // // L_TrainerName // this.L_TrainerName.AutoSize = true; this.L_TrainerName.Location = new System.Drawing.Point(129, 65); this.L_TrainerName.Name = "L_TrainerName"; this.L_TrainerName.Size = new System.Drawing.Size(0, 13); this.L_TrainerName.TabIndex = 55; // // TrainerID // this.TrainerID.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.TrainerID.Location = new System.Drawing.Point(72, 60); this.TrainerID.Maximum = new decimal(new int[] { 254, 0, 0, 0}); this.TrainerID.Name = "TrainerID"; this.TrainerID.Size = new System.Drawing.Size(42, 22); this.TrainerID.TabIndex = 54; this.TrainerID.Value = new decimal(new int[] { 254, 0, 0, 0}); this.TrainerID.ValueChanged += new System.EventHandler(this.Trainer_ValueChanged); // // L_Trainer // this.L_Trainer.AutoSize = true; this.L_Trainer.Location = new System.Drawing.Point(12, 65); this.L_Trainer.Name = "L_Trainer"; this.L_Trainer.Size = new System.Drawing.Size(54, 13); this.L_Trainer.TabIndex = 53; this.L_Trainer.Text = "Trainer ID"; // // L_Streak // this.L_Streak.AutoSize = true; this.L_Streak.Location = new System.Drawing.Point(100, 26); this.L_Streak.Name = "L_Streak"; this.L_Streak.Size = new System.Drawing.Size(38, 13); this.L_Streak.TabIndex = 52; this.L_Streak.Text = "Streak"; // // Streak // this.Streak.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Streak.Location = new System.Drawing.Point(144, 24); this.Streak.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this.Streak.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.Streak.Name = "Streak"; this.Streak.Size = new System.Drawing.Size(49, 22); this.Streak.TabIndex = 52; this.Streak.Value = new decimal(new int[] { 1, 0, 0, 0}); // // TP_SOS // this.TP_SOS.Controls.Add(this.L_Length); this.TP_SOS.Controls.Add(this.ChainLength); this.TP_SOS.Controls.Add(this.HPBarColor); this.TP_SOS.Controls.Add(this.L_HPBarColor); this.TP_SOS.Controls.Add(this.LastCallFail); this.TP_SOS.Controls.Add(this.SupperEffective); this.TP_SOS.Controls.Add(this.SameCaller); this.TP_SOS.Controls.Add(this.Intimidate); this.TP_SOS.Controls.Add(this.AO); this.TP_SOS.Controls.Add(this.L_Weather); this.TP_SOS.Controls.Add(this.L_CallRate); this.TP_SOS.Controls.Add(this.CB_CallRate); this.TP_SOS.Location = new System.Drawing.Point(4, 22); this.TP_SOS.Name = "TP_SOS"; this.TP_SOS.Padding = new System.Windows.Forms.Padding(3); this.TP_SOS.Size = new System.Drawing.Size(203, 170); this.TP_SOS.TabIndex = 5; this.TP_SOS.Text = "SOS"; this.TP_SOS.UseVisualStyleBackColor = true; // // L_Length // this.L_Length.AutoSize = true; this.L_Length.Location = new System.Drawing.Point(113, 43); this.L_Length.Name = "L_Length"; this.L_Length.Size = new System.Drawing.Size(40, 13); this.L_Length.TabIndex = 66; this.L_Length.Text = "Length"; // // ChainLength // this.ChainLength.Font = new System.Drawing.Font("Consolas", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ChainLength.Location = new System.Drawing.Point(157, 39); this.ChainLength.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.ChainLength.Name = "ChainLength"; this.ChainLength.Size = new System.Drawing.Size(42, 22); this.ChainLength.TabIndex = 67; // // HPBarColor // this.HPBarColor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.HPBarColor.FormattingEnabled = true; this.HPBarColor.Location = new System.Drawing.Point(34, 68); this.HPBarColor.Name = "HPBarColor"; this.HPBarColor.Size = new System.Drawing.Size(72, 21); this.HPBarColor.TabIndex = 65; // // L_HPBarColor // this.L_HPBarColor.AutoSize = true; this.L_HPBarColor.Location = new System.Drawing.Point(6, 71); this.L_HPBarColor.Name = "L_HPBarColor"; this.L_HPBarColor.Size = new System.Drawing.Size(22, 13); this.L_HPBarColor.TabIndex = 64; this.L_HPBarColor.Text = "HP"; // // LastCallFail // this.LastCallFail.AutoSize = true; this.LastCallFail.Location = new System.Drawing.Point(9, 141); this.LastCallFail.Name = "LastCallFail"; this.LastCallFail.Size = new System.Drawing.Size(97, 17); this.LastCallFail.TabIndex = 63; this.LastCallFail.Text = "Last Call Failed"; this.LastCallFail.UseVisualStyleBackColor = true; // // SupperEffective // this.SupperEffective.AutoSize = true; this.SupperEffective.Location = new System.Drawing.Point(101, 118); this.SupperEffective.Name = "SupperEffective"; this.SupperEffective.Size = new System.Drawing.Size(99, 17); this.SupperEffective.TabIndex = 62; this.SupperEffective.Text = "Super Effective"; this.SupperEffective.UseVisualStyleBackColor = true; // // SameCaller // this.SameCaller.AutoSize = true; this.SameCaller.Location = new System.Drawing.Point(9, 118); this.SameCaller.Name = "SameCaller"; this.SameCaller.Size = new System.Drawing.Size(82, 17); this.SameCaller.TabIndex = 61; this.SameCaller.Text = "Same Caller"; this.SameCaller.UseVisualStyleBackColor = true; // // Intimidate // this.Intimidate.AutoSize = true; this.Intimidate.Location = new System.Drawing.Point(118, 95); this.Intimidate.Name = "Intimidate"; this.Intimidate.Size = new System.Drawing.Size(71, 17); this.Intimidate.TabIndex = 60; this.Intimidate.Text = "Intimidate"; this.Intimidate.UseVisualStyleBackColor = true; // // AO // this.AO.AutoSize = true; this.AO.Checked = true; this.AO.CheckState = System.Windows.Forms.CheckState.Checked; this.AO.Location = new System.Drawing.Point(9, 95); this.AO.Name = "AO"; this.AO.Size = new System.Drawing.Size(96, 17); this.AO.TabIndex = 59; this.AO.Text = "Adrenaline Orb"; this.AO.UseVisualStyleBackColor = true; // // L_Weather // this.L_Weather.AutoSize = true; this.L_Weather.Location = new System.Drawing.Point(118, 70); this.L_Weather.Name = "L_Weather"; this.L_Weather.Size = new System.Drawing.Size(67, 17); this.L_Weather.TabIndex = 55; this.L_Weather.Text = "Weather"; this.L_Weather.UseVisualStyleBackColor = true; // // L_CallRate // this.L_CallRate.AutoSize = true; this.L_CallRate.Location = new System.Drawing.Point(6, 43); this.L_CallRate.Name = "L_CallRate"; this.L_CallRate.Size = new System.Drawing.Size(50, 13); this.L_CallRate.TabIndex = 57; this.L_CallRate.Text = "Call Rate"; // // CB_CallRate // this.CB_CallRate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CB_CallRate.FormattingEnabled = true; this.CB_CallRate.Location = new System.Drawing.Point(60, 38); this.CB_CallRate.Name = "CB_CallRate"; this.CB_CallRate.Size = new System.Drawing.Size(45, 21); this.CB_CallRate.TabIndex = 58; // // TP_SOS2 // this.TP_SOS2.Controls.Add(this.Sync); this.TP_SOS2.Controls.Add(this.L_Slot); this.TP_SOS2.Controls.Add(this.HA); this.TP_SOS2.Controls.Add(this.Slot); this.TP_SOS2.Location = new System.Drawing.Point(4, 22); this.TP_SOS2.Name = "TP_SOS2"; this.TP_SOS2.Padding = new System.Windows.Forms.Padding(3); this.TP_SOS2.Size = new System.Drawing.Size(203, 170); this.TP_SOS2.TabIndex = 6; this.TP_SOS2.Text = "SOS2"; this.TP_SOS2.UseVisualStyleBackColor = true; // // Sync // this.Sync.AutoSize = true; this.Sync.Location = new System.Drawing.Point(20, 83); this.Sync.Name = "Sync"; this.Sync.Size = new System.Drawing.Size(94, 17); this.Sync.TabIndex = 94; this.Sync.Text = "Sync Success"; this.Sync.UseVisualStyleBackColor = true; // // L_Slot // this.L_Slot.AutoSize = true; this.L_Slot.Location = new System.Drawing.Point(17, 27); this.L_Slot.Name = "L_Slot"; this.L_Slot.Size = new System.Drawing.Size(25, 13); this.L_Slot.TabIndex = 71; this.L_Slot.Text = "Slot"; // // HA // this.HA.AutoSize = true; this.HA.Location = new System.Drawing.Point(20, 110); this.HA.Name = "HA"; this.HA.Size = new System.Drawing.Size(90, 17); this.HA.TabIndex = 70; this.HA.Text = "Hidden Ability"; this.HA.UseVisualStyleBackColor = true; // // Slot // this.Slot.BlankText = null; checkBoxProperties2.ForeColor = System.Drawing.SystemColors.ControlText; this.Slot.CheckBoxProperties = checkBoxProperties2; this.Slot.DisplayMemberSingleItem = ""; this.Slot.DropDownHeight = 230; this.Slot.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.Slot.FormattingEnabled = true; this.Slot.Items.AddRange(new object[] { "1 (1%)", "2 (1%)", "3 (1%)", "4 (10%)", "5 (10%)", "6 (10%)", "7 (67%)", "W1 (1%)", "W2 (10%)"}); this.Slot.Location = new System.Drawing.Point(20, 48); this.Slot.Name = "Slot"; this.Slot.Size = new System.Drawing.Size(100, 21); this.Slot.TabIndex = 93; // // XY // this.XY.AutoSize = true; this.XY.Checked = true; this.XY.CheckState = System.Windows.Forms.CheckState.Checked; this.XY.Location = new System.Drawing.Point(11, 152); this.XY.Name = "XY"; this.XY.Size = new System.Drawing.Size(40, 17); this.XY.TabIndex = 119; this.XY.Text = "XY"; this.XY.UseVisualStyleBackColor = true; this.XY.Visible = false; this.XY.CheckedChanged += new System.EventHandler(this.XY_CheckedChanged); // // ORAS // this.ORAS.AutoSize = true; this.ORAS.Location = new System.Drawing.Point(92, 152); this.ORAS.Name = "ORAS"; this.ORAS.Size = new System.Drawing.Size(56, 17); this.ORAS.TabIndex = 120; this.ORAS.Text = "ORAS"; this.ORAS.UseVisualStyleBackColor = true; this.ORAS.Visible = false; this.ORAS.CheckedChanged += new System.EventHandler(this.ORAS_CheckedChanged); // // MiscRNGTool // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(684, 482); this.Controls.Add(this.Filters); this.Controls.Add(this.B_Calc); this.Controls.Add(this.DGV); this.Controls.Add(this.RNGInfo); this.MinimumSize = new System.Drawing.Size(700, 520); this.Name = "MiscRNGTool"; this.Text = "MiscRNGTool"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MiscRNGTool_FormClosing); this.Load += new System.EventHandler(this.MiscRNGTool_Load); this.RNGInfo.ResumeLayout(false); this.RNGInfo.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.Delay)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.MaxResults)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.NPC)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.StartingFrame)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.DGV)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Range)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Value)).EndInit(); this.Filters.ResumeLayout(false); this.TP_Timeline.ResumeLayout(false); this.TP_Timeline.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.JumpFrame)).EndInit(); this.TP_Misc.ResumeLayout(false); this.TP_Misc.PerformLayout(); this.TP_Capture.ResumeLayout(false); this.TP_Capture.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.CatchRate)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HPMax)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HPCurr)).EndInit(); this.TP_FP.ResumeLayout(false); this.TP_FP.PerformLayout(); this.TP_BattleTree.ResumeLayout(false); this.TP_BattleTree.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.TrainerID)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Streak)).EndInit(); this.TP_SOS.ResumeLayout(false); this.TP_SOS.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.ChainLength)).EndInit(); this.TP_SOS2.ResumeLayout(false); this.TP_SOS2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox RNGInfo; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label L_RNG; private System.Windows.Forms.ComboBox RNG; private Controls.HexMaskedTextBox Seed; private System.Windows.Forms.NumericUpDown MaxResults; private System.Windows.Forms.Label L_MaxResults; private System.Windows.Forms.NumericUpDown StartingFrame; private System.Windows.Forms.Label L_StartingFrame; private System.Windows.Forms.DataGridView DGV; private System.Windows.Forms.Label L_Delay; private System.Windows.Forms.NumericUpDown Delay; private System.Windows.Forms.Label L_NPC; private System.Windows.Forms.NumericUpDown NPC; private System.Windows.Forms.Button B_Calc; private System.Windows.Forms.Label L_CurrentSeed; private System.Windows.Forms.RadioButton RB_Pokerus; private System.Windows.Forms.RadioButton RB_Random; private System.Windows.Forms.ComboBox Compare; private System.Windows.Forms.NumericUpDown Value; private System.Windows.Forms.NumericUpDown Range; private System.Windows.Forms.Button B_ResetFrame; private System.Windows.Forms.TabControl Filters; private System.Windows.Forms.TabPage TP_Misc; private System.Windows.Forms.TabPage TP_Capture; private System.Windows.Forms.NumericUpDown HPMax; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label_HP; private System.Windows.Forms.NumericUpDown HPCurr; private System.Windows.Forms.ComboBox DexBonus; private System.Windows.Forms.ComboBox BallBonus; private System.Windows.Forms.Label L_Dex; private System.Windows.Forms.Label L_Ball; private System.Windows.Forms.NumericUpDown CatchRate; private System.Windows.Forms.Label L_CatchRate; private System.Windows.Forms.ComboBox Status; private System.Windows.Forms.Label L_output; private System.Windows.Forms.CheckBox CB_Detail; private System.Windows.Forms.CheckBox SuccessOnly; private System.Windows.Forms.CheckBox RotoCatch; private System.Windows.Forms.TabPage TP_FP; private System.Windows.Forms.ComboBox Color; private System.Windows.Forms.ComboBox NPCType; private System.Windows.Forms.ComboBox Stars; private System.Windows.Forms.ComboBox Facility; private System.Windows.Forms.ComboBox Rank; private System.Windows.Forms.ComboBox Game; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label L_Rank; private System.Windows.Forms.Label L_Color; private System.Windows.Forms.Label L_NPCType; private System.Windows.Forms.Button B_Help; private System.Windows.Forms.TabPage TP_BattleTree; private System.Windows.Forms.Label L_Streak; private System.Windows.Forms.NumericUpDown Streak; private System.Windows.Forms.Label L_Trainer; private System.Windows.Forms.NumericUpDown TrainerID; private System.Windows.Forms.Label L_TrainerName; private System.Windows.Forms.TabPage TP_SOS; private System.Windows.Forms.TabPage TP_Timeline; private System.Windows.Forms.CheckBox CreateTimeline; private System.Windows.Forms.CheckBox Raining; private System.Windows.Forms.RadioButton Girl; private System.Windows.Forms.RadioButton Boy; private System.Windows.Forms.CheckBox Fidget; private System.Windows.Forms.NumericUpDown JumpFrame; private System.Windows.Forms.Label L_CallRate; private System.Windows.Forms.ComboBox CB_CallRate; private System.Windows.Forms.CheckBox L_Weather; private System.Windows.Forms.CheckBox Intimidate; private System.Windows.Forms.CheckBox AO; private System.Windows.Forms.CheckBox LastCallFail; private System.Windows.Forms.CheckBox SupperEffective; private System.Windows.Forms.CheckBox SameCaller; private System.Windows.Forms.ComboBox HPBarColor; private System.Windows.Forms.Label L_HPBarColor; private System.Windows.Forms.Label L_Length; private System.Windows.Forms.NumericUpDown ChainLength; private System.Windows.Forms.ComboBox OPower; private System.Windows.Forms.TabPage TP_SOS2; private System.Windows.Forms.Label L_Slot; private System.Windows.Forms.CheckBox HA; private Controls.CheckBoxComboBox Slot; private System.Windows.Forms.CheckBox Sync; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_Frame; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_adv; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_hit; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_mark; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_clock; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_facility; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_pokerus; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_trainer; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_capture; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_SOS; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_randn; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_state; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_rand; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_rand64; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_time; private System.Windows.Forms.DataGridViewTextBoxColumn dgv_npcstatus; private System.Windows.Forms.CheckBox TTT; private System.Windows.Forms.RadioButton RB_SavePar; private System.Windows.Forms.Label L_BaseTime; private System.Windows.Forms.Label L_TargetSeed; private Controls.HexMaskedTextBox BaseTimeText; private Controls.HexMaskedTextBox CurrentText; private System.Windows.Forms.CheckBox ORAS; private System.Windows.Forms.CheckBox XY; } }
47.522209
182
0.580256
[ "MIT" ]
Real96/3DSRNGTool
3DSRNGTool/Subforms/MiscRNGTool.Designer.cs
79,176
C#
namespace WpfApp1 { class Class1 { } }
7.428571
18
0.519231
[ "MIT" ]
forki/Gu.Roslyn.Asserts
TestApps/WpfApp1/Class1.cs
54
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace samplemvccore.Services { public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); } }
19.769231
74
0.747082
[ "MIT" ]
elvogel/identityazuretable
sample/samplemvccore/Services/IEmailSender.cs
259
C#
namespace AdventOfCode.Inputs.Year2015 { internal class Day02 { public string Input = @"20x3x11 15x27x5 6x29x7 30x15x9 19x29x21 10x4x15 1x26x4 1x5x18 10x15x23 10x14x20 3x5x18 29x23x30 7x4x10 22x24x29 30x1x2 19x2x5 11x9x22 23x15x10 11x11x10 30x28x5 22x5x4 6x26x20 16x12x30 10x20x5 25x14x24 16x17x22 11x28x26 1x11x10 1x24x15 13x17x21 30x3x13 20x25x17 22x12x5 22x20x24 9x2x14 6x18x8 27x28x24 11x17x1 1x4x12 5x20x13 24x23x23 22x1x25 18x19x5 5x23x13 8x16x4 20x21x9 1x7x11 8x30x17 3x30x9 6x16x18 22x25x27 9x20x26 16x21x23 5x24x17 15x17x15 26x15x10 22x16x3 20x24x24 8x18x10 23x19x16 1x21x24 23x23x9 14x20x6 25x5x5 16x3x1 29x29x20 11x4x26 10x23x24 29x25x16 27x27x22 9x7x22 6x21x18 25x11x19 14x13x3 15x28x17 14x3x12 29x8x19 30x14x20 20x23x4 8x16x5 4x11x18 20x8x24 21x13x21 14x26x29 27x4x17 27x4x25 5x28x6 23x24x11 29x22x5 30x20x6 23x2x10 11x4x7 27x23x6 10x20x19 8x20x22 5x29x22 16x13x2 2x11x14 6x12x4 3x13x6 16x5x18 25x3x28 21x1x5 20x16x19 28x30x27 26x7x18 25x27x24 11x19x7 21x19x17 2x12x27 20x5x14 8x5x8 6x24x8 7x28x20 3x20x28 5x20x30 13x29x1 26x29x5 19x28x25 5x19x11 11x20x22 4x23x1 19x25x12 3x10x6 3x14x10 28x16x12 23x12x2 23x12x19 20x28x10 9x10x25 16x21x16 1x18x20 9x4x26 3x25x8 17x16x28 9x28x16 27x3x12 17x24x12 13x21x10 7x17x13 6x10x9 7x29x25 11x19x30 1x24x5 20x16x23 24x28x21 6x29x19 25x2x19 12x5x26 25x29x12 16x28x22 26x26x15 9x13x5 10x29x7 1x24x16 22x2x2 6x16x13 3x12x28 4x12x13 14x27x21 14x23x26 7x5x18 8x30x27 15x9x18 26x16x5 3x29x17 19x7x18 16x18x1 26x15x30 24x30x21 13x20x7 4x12x10 27x20x11 28x29x21 20x14x30 28x12x3 19x1x8 4x8x6 21x14x2 27x19x21 17x24x14 15x18x11 18x7x26 25x28x29 27x26x9 18x12x17 24x28x25 13x24x14 26x9x28 9x3x30 9x2x9 8x1x29 18x30x10 18x14x5 26x8x30 12x1x1 30x5x28 26x17x21 10x10x10 20x7x27 13x17x6 21x13x17 2x16x8 7x9x9 15x26x4 11x28x25 10x6x19 21x6x29 15x5x6 28x9x16 14x3x10 12x29x5 22x19x19 25x15x22 30x6x28 11x23x13 20x25x14 26x1x13 6x14x15 16x25x17 28x4x13 10x24x25 4x13x10 9x15x16 15x24x6 22x9x19 11x11x8 4x19x12 24x5x4 27x12x13 7x27x16 2x6x9 29x27x15 18x26x23 19x16x15 14x5x25 9x16x30 4x6x4 13x10x10 1x8x29 23x5x17 19x20x20 11x27x24 27x15x5 15x11x12 21x11x3 1x13x22 17x8x8 13x14x14 17x22x7 9x5x8 2x6x3 25x9x15 11x8x13 9x25x12 3x16x12 12x16x8 16x24x17 4x6x26 22x29x11 14x17x19 28x2x27 24x22x19 22x20x30 23x28x4 16x12x14 22x24x22 29x1x28 26x29x16 3x25x30 27x3x13 22x24x26 25x3x2 7x24x2 10x5x3 28x8x29 25x6x4 12x17x14 24x3x5 23x27x7 26x23x30 11x10x19 23x7x11 26x14x15 14x3x25 12x24x14 2x14x12 9x12x16 9x2x28 3x8x2 22x6x9 2x30x2 25x1x9 20x11x2 14x11x12 7x14x12 24x8x26 13x21x23 18x17x23 13x6x17 20x20x19 13x17x29 7x24x24 23x8x6 19x10x28 3x8x21 15x20x18 11x27x1 11x24x28 13x20x11 18x19x22 27x22x12 28x3x2 13x4x29 26x5x6 14x29x25 7x4x7 5x17x7 2x8x1 22x30x24 22x21x28 1x28x13 11x20x4 25x29x19 9x23x4 30x6x11 25x18x10 28x10x24 3x5x20 19x28x10 27x19x2 26x20x4 19x21x6 2x12x30 8x26x27 11x27x10 14x13x17 4x3x21 2x20x21 22x30x3 2x23x2 3x16x12 22x28x22 3x23x29 8x25x15 9x30x4 10x11x1 24x8x20 10x7x27 7x22x4 27x13x17 5x28x5 30x15x13 10x8x17 8x21x5 8x17x26 25x16x4 9x7x25 13x11x20 6x30x9 15x14x12 30x1x23 5x20x24 22x7x6 26x11x23 29x7x5 13x24x28 22x20x10 18x3x1 15x19x23 28x28x20 7x26x2 9x12x20 15x4x6 1x17x21 3x22x17 9x4x20 25x19x5 9x11x22 14x1x17 14x5x16 30x5x18 19x6x12 28x16x22 13x4x25 29x23x18 1x27x3 12x14x4 10x25x19 15x19x30 11x30x4 11x22x26 13x25x2 17x13x27 11x30x24 15x1x14 17x18x4 26x11x3 16x22x28 13x20x9 1x18x3 25x11x12 20x21x1 22x27x4 8x28x23 7x13x27 17x9x26 27x27x20 11x20x12 26x21x11 29x14x12 27x25x1 28x29x25 21x23x28 5x18x18 19x5x4 7x6x30 27x8x11 12x24x12 16x25x22 26x11x29 25x22x17 15x23x23 17x9x6 30x10x16 21x3x5 18x27x2 28x21x14 16x18x17 4x18x2 9x1x14 9x1x9 5x27x12 8x16x30 3x19x19 16x26x24 1x6x9 15x14x3 11x7x19 8x19x3 17x26x26 6x18x11 19x12x4 29x20x16 20x17x23 6x6x5 20x30x19 18x25x18 2x26x2 3x1x1 14x25x18 3x1x6 11x14x18 17x23x27 25x29x9 6x25x20 20x10x9 17x5x18 29x14x8 14x25x26 10x15x29 23x19x11 22x2x2 4x5x5 13x23x25 19x13x19 20x18x6 30x7x28 26x18x17 29x18x10 30x29x1 12x26x24 18x17x26 29x28x15 3x12x20 24x10x8 30x15x6 28x23x15 14x28x11 10x27x19 14x8x21 24x1x23 1x3x27 6x15x6 8x25x26 13x10x25 6x9x8 10x29x29 26x23x5 14x24x1 25x6x22 17x11x18 1x27x26 18x25x23 20x15x6 2x21x28 2x10x13 12x25x14 2x14x23 30x5x23 29x19x21 29x10x25 14x22x16 17x11x26 12x17x30 8x17x7 20x25x28 20x11x30 15x1x12 13x3x24 16x23x23 27x3x3 26x3x27 18x5x12 12x26x7 19x27x12 20x10x28 30x12x25 3x14x10 21x26x1 24x26x26 7x21x30 3x29x12 29x28x5 5x20x7 27x11x2 15x20x4 16x15x15 19x13x7 7x17x15 27x24x15 9x17x28 20x21x14 14x29x29 23x26x13 27x23x21 18x13x6 26x16x21 18x26x27 9x3x12 30x18x24 12x11x29 5x15x1 1x16x3 14x28x11 2x18x1 19x18x19 18x28x21 2x3x14 22x16x5 28x18x28 24x16x18 7x4x10 19x26x19 24x17x7 25x9x6 25x17x7 20x22x20 3x3x7 23x19x15 21x27x21 1x23x11 9x19x4 22x4x18 6x15x5 15x25x2 23x11x20 27x16x6 27x8x5 10x10x19 22x14x1 7x1x29 8x11x17 27x9x27 28x9x24 17x7x3 26x23x8 7x6x30 25x28x2 1x30x25 3x18x18 28x27x15 14x14x1 10x25x29 18x12x9 20x28x16 26x27x22 8x26x1 21x2x12 25x16x14 21x19x5 12x9x22 16x5x4 5x4x16 25x29x3 4x29x13 15x16x29 8x11x24 30x11x20 17x21x14 12x24x10 10x12x6 3x26x30 15x14x25 20x12x21 13x11x16 15x13x3 5x17x29 6x3x23 9x26x11 30x1x8 14x10x30 18x30x10 13x19x19 16x19x17 28x7x10 28x29x4 3x21x10 4x28x24 7x28x9 2x4x9 25x27x13 6x12x15 4x18x20 20x1x16 5x13x24 11x11x10 12x9x23 1x9x30 17x28x24 9x5x27 21x15x16 17x4x14 8x14x4 13x10x7 17x12x14 9x19x19 2x7x21 8x24x23 19x5x12 11x23x21 13x3x1 5x27x15 12x25x25 13x21x16 9x17x11 1x15x21 4x26x17 11x5x15 23x10x15 12x17x21 27x15x1 4x29x14 5x24x25 10x10x12 18x12x9 11x24x23 24x23x3 28x12x15 29x9x14 11x25x8 5x12x2 26x26x29 9x21x2 8x8x25 1x16x30 17x29x20 9x22x13 7x18x16 3x3x23 26x25x30 15x23x24 20x23x5 20x16x10 23x7x8 20x18x26 8x27x6 30x23x23 7x7x24 21x11x15 1x30x25 26x27x22 30x28x13 20x13x13 3x1x15 16x7x1 7x25x15 12x7x18 16x9x23 16x12x18 29x5x2 17x7x7 21x17x5 9x9x17 26x16x10 29x29x23 17x26x10 5x19x17 1x10x1 14x21x20 13x6x4 13x13x3 23x4x18 4x16x3 16x30x11 2x11x2 15x30x15 20x30x22 18x12x16 23x5x16 6x14x15 9x4x11 30x23x21 20x7x12 7x18x6 15x6x5 18x22x19 16x10x22 26x20x25 9x25x25 29x21x10 9x21x24 7x18x21 14x3x15 18x19x19 4x29x17 14x10x9 2x26x14 13x3x24 4x4x17 6x27x24 2x18x3 14x25x2 30x14x17 11x6x14 4x10x18 15x4x2 27x7x10 13x24x1 7x12x6 25x22x26 19x2x18 23x29x2 2x15x4 12x6x9 16x14x29 9x17x3 21x9x12 23x18x22 10x8x4 29x2x7 19x27x15 4x24x27 25x20x14 8x23x19 1x24x19 6x20x10 15x8x5 18x28x5 17x23x22 9x16x13 30x24x4 26x3x13 12x22x18 29x17x29 26x4x16 15x7x20 9x15x30 12x7x18 28x19x18 11x23x23 24x20x1 20x3x24 1x26x1 14x10x6 5x27x24 13x21x12 20x20x5 6x28x9 11x26x11 26x29x12 21x4x11 20x11x17 22x27x20 19x11x21 2x11x11 13x5x7 12x10x25 21x28x1 15x30x17 28x19x1 4x19x12 11x4x12 4x10x30 11x18x5 22x20x12 3x7x27 20x26x4 13x27x26 23x14x13 4x19x7 26x27x16 20x5x20 18x5x8 19x21x1 22x8x1 29x4x1 24x10x15 24x9x20 10x3x8 29x30x3 2x8x24 16x7x18 2x11x23 23x15x16 21x12x6 24x28x9 6x1x13 14x29x20 27x24x13 16x26x8 5x6x17 21x8x1 28x19x21 1x14x16 18x2x9 29x28x10 22x26x27 18x26x23 22x24x2 28x26x1 27x29x12 30x13x11 1x25x5 13x30x18 3x13x22 22x10x11 2x7x7 18x17x8 9x22x26 30x18x16 10x2x3 7x27x13 3x20x16 9x21x16 1x18x15 21x30x30 4x25x23 3x11x7 5x6x12 27x1x20 13x15x24 23x29x2 13x5x24 22x16x15 28x14x3 29x24x9 2x20x4 30x10x4 23x7x20 22x12x21 3x19x11 4x28x28 5x4x7 28x12x25 2x16x26 23x20x7 5x21x29 9x21x16 9x6x10 9x6x4 24x14x29 28x11x6 10x22x1 21x30x20 13x17x8 2x25x24 19x21x3 28x8x14 6x29x28 27x10x28 30x11x12 17x2x10 14x19x17 2x11x4 26x1x2 13x4x4 23x20x18 2x17x21 28x7x15 3x3x27 24x17x30 28x28x20 21x5x29 13x12x19 24x29x29 19x10x6 19x12x14 21x4x17 27x16x1 4x17x30 23x23x18 23x15x27 26x2x11 12x8x8 15x23x26 30x17x15 17x17x15 24x4x30 9x9x10 14x25x20 25x11x19 20x7x1 9x21x3 7x19x9 10x6x19 26x12x30 21x9x20 15x11x6 30x21x9 10x18x17 22x9x8 8x30x26 28x12x27 17x17x7 11x13x8 5x3x21 24x1x29 1x28x2 18x28x10 8x29x14 26x26x27 17x10x25 22x30x3 27x9x13 21x21x4 30x29x16 22x7x20 24x10x2 16x29x17 28x15x17 19x19x22 9x8x6 26x23x24 25x4x27 16x12x2 11x6x18 19x14x8 9x29x13 23x30x19 10x16x1 4x21x28 23x25x25 19x9x16 30x11x12 24x3x9 28x19x4 18x12x9 7x1x25 28x7x1 24x3x12 30x24x22 27x24x26 9x30x30 29x10x8 4x6x18 10x1x15 10x4x26 23x20x16 6x3x14 30x8x16 25x14x20 11x9x3 15x23x25 8x30x22 22x19x18 25x1x12 27x25x7 25x23x3 13x20x8 5x30x7 18x19x27 20x23x3 1x17x21 21x21x27 13x1x24 7x30x20 21x9x18 23x26x6 22x9x29 17x6x21 28x28x29 19x25x26 9x27x21 5x26x8 11x19x1 10x1x18 29x4x8 21x2x22 14x12x8"; } }
8.185885
39
0.873224
[ "MIT" ]
fluttert/AdventOfCode
AdventOfCode/Inputs/Year2015/Day02.cs
8,237
C#
using System.Threading.Tasks; using System.Net; using System.Web.Mvc; using GestionFacturas.Modelos; using GestionFacturas.Servicios; using System.Linq; using GestionFacturas.Website.Viewmodels.Clientes; using System.IO; using System.Collections.Generic; namespace GestionFacturas.Website.Controllers { [Authorize] public class ClientesController : Controller { private readonly ServicioCliente _servicioCliente; public ClientesController(ServicioCliente servicioCliente) { _servicioCliente = servicioCliente; } public ActionResult Index() { return RedirectToAction("ListaGestionClientes"); } [OutputCache(VaryByParam = "*", Duration = 0, NoStore = true)] public async Task<ActionResult> ListaGestionClientes(FiltroBusquedaCliente filtroBusqueda, int? pagina) { if (!filtroBusqueda.TieneFiltrosBusqueda) { filtroBusqueda = RecuperarFiltroBusqueda(); if (pagina.HasValue) filtroBusqueda.IndicePagina = pagina.Value; } var viewmodel = new ListaGestionClientesViewModel { FiltroBusqueda = filtroBusqueda, ListaClientes = await _servicioCliente.ListaGestionClientesAsync(filtroBusqueda) }; GuardarFiltroBusqueda(filtroBusqueda); return View("ListaGestionClientes", viewmodel); } public ActionResult Crear() { var viewmodel = new CrearClienteViewModel { Cliente = new EditorCliente() }; return View(viewmodel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Crear(CrearClienteViewModel viewmodel) { if (!ModelState.IsValid) return View(viewmodel); await _servicioCliente.CrearClienteAsync(viewmodel.Cliente); return RedirectToAction("ListaGestionClientes"); } public async Task<ActionResult> Editar(int? id) { if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var viewmodel = new EditarClienteViewModel { Cliente = await _servicioCliente.BuscaEditorClienteAsync(id) }; if (viewmodel.Cliente == null) return HttpNotFound(); return View(viewmodel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Editar(EditarClienteViewModel viewmodel) { if (!ModelState.IsValid) return View(viewmodel); await _servicioCliente.ActualizarClienteAsync(viewmodel.Cliente); return RedirectToAction("ListaGestionClientes"); } public async Task<ActionResult> Eliminar(int? id) { if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var viewmodel = new EliminarClienteViewModel { Cliente = await _servicioCliente.BuscaEditorClienteAsync(id.Value) }; if (viewmodel.Cliente == null) return HttpNotFound(); return View(viewmodel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Eliminar(EliminarClienteViewModel viewmodel) { if (!ModelState.IsValid) return View(viewmodel); await _servicioCliente.EliminarCliente(viewmodel.Cliente.Id); var nombreOEmpresaCodificado = WebUtility.UrlEncode(viewmodel.Cliente.NombreOEmpresa); return RedirectToAction("EliminarConfirmado", new { nombreOEmpresaEliminado = nombreOEmpresaCodificado }); } public ActionResult EliminarConfirmado(string nombreOEmpresaEliminado) { if (string.IsNullOrEmpty(nombreOEmpresaEliminado)) return HttpNotFound(); ViewBag.NombreOEmpresaEliminado = WebUtility.UrlDecode(nombreOEmpresaEliminado); return View("EliminarConfirmado"); } public ActionResult Importar() { var viewmodel = new ImportarClientesViewModel { SelectorColumnasCliente = new SelectorColumnasExcelCliente() }; return View(viewmodel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Importar(ImportarClientesViewModel viewmodel) { if (!ModelState.IsValid) return View(viewmodel); await _servicioCliente.ImportarClientesDeExcel(viewmodel.ArchivoExcelSeleccionado.InputStream, viewmodel.SelectorColumnasCliente); return RedirectToAction("ListaGestionClientes"); } #region Acciones de autocompletar public async Task<ActionResult> AutocompletarPorNombre(string term) { var filtroBusqueda = new FiltroBusquedaCliente { NombreOEmpresa = term }; var clientes = await _servicioCliente.ListaClientesAsync(filtroBusqueda, 1, 10); return Json(clientes, JsonRequestBehavior.AllowGet); } public async Task<ActionResult> AutocompletarPorId(int term) { var filtroBusqueda = new FiltroBusquedaCliente { Id = term }; var clientes = await _servicioCliente.ListaClientesAsync(filtroBusqueda, 1, 10); return Json(clientes, JsonRequestBehavior.AllowGet); } public async Task<ActionResult> AutocompletarPorIdentificacionFiscal(string term) { var filtroBusqueda = new FiltroBusquedaCliente { IdentificacionFiscal = term }; var clientes = await _servicioCliente.ListaClientesAsync(filtroBusqueda, 1, 10); return Json(clientes, JsonRequestBehavior.AllowGet); } #endregion #region Métodos Privados private FiltroBusquedaCliente RecuperarFiltroBusqueda() { var filtro = Session["FiltroBusquedaClientes"]; if (filtro != null) return (FiltroBusquedaCliente)filtro; return FiltroBusquedaConValoresPorDefecto(); } private void GuardarFiltroBusqueda(FiltroBusquedaCliente filtro) { Session["FiltroBusquedaClientes"] = filtro; } private FiltroBusquedaCliente FiltroBusquedaConValoresPorDefecto() { return new FiltroBusquedaCliente(); } #endregion protected override void Dispose(bool disposing) { if (disposing) { _servicioCliente.Dispose(); } base.Dispose(disposing); } } }
32.634615
142
0.631408
[ "MIT" ]
acapdevila/GestionFacturas
GestionFacturas.Website/Controllers/ClientesController.cs
6,791
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using PcapDotNet.Base; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.IpV6 { /// <summary> /// RFC 5142. /// <pre> /// +-----+----------------+-------------------------+ /// | Bit | 0-7 | 8-15 | /// +-----+----------------+-------------------------+ /// | 0 | Next Header | Header Extension Length | /// +-----+----------------+-------------------------+ /// | 16 | MH Type | Reserved | /// +-----+----------------+-------------------------+ /// | 32 | Checksum | /// +-----+----------------+-------------------------+ /// | 48 | # of Addresses | Reserved | /// +-----+----------------+-------------------------+ /// | 64 | Home Agent Addresses | /// | ... | | /// +-----+------------------------------------------+ /// | | Mobility Options | /// | ... | | /// +-----+------------------------------------------+ /// </pre> /// </summary> public sealed class IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage : IpV6ExtensionHeaderMobility { private static class MessageDataOffset { public const int NumberOfAddresses = 0; public const int HomeAgentAddresses = NumberOfAddresses + sizeof(byte) + sizeof(byte); } /// <summary> /// The minimum number of bytes the message data takes. /// </summary> public const int MinimumMessageDataLength = MessageDataOffset.HomeAgentAddresses; /// <summary> /// Creates an instance from next header, checksum, home agent addresses and options. /// </summary> /// <param name="nextHeader">Identifies the type of header immediately following this extension header.</param> /// <param name="checksum"> /// Contains the checksum of the Mobility Header. /// The checksum is calculated from the octet string consisting of a "pseudo-header" /// followed by the entire Mobility Header starting with the Payload Proto field. /// The checksum is the 16-bit one's complement of the one's complement sum of this string. /// </param> /// <param name="homeAgentAddresses">A list of alternate home agent addresses for the mobile node.</param> /// <param name="options">Zero or more TLV-encoded mobility options.</param> public IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage(IpV4Protocol? nextHeader, ushort checksum, ReadOnlyCollection<IpV6Address> homeAgentAddresses, IpV6MobilityOptions options) : base(nextHeader, checksum, options, MessageDataOffset.HomeAgentAddresses + (homeAgentAddresses == null ? 0 : homeAgentAddresses.Count) * IpV6Address.SizeOf) { if (homeAgentAddresses == null) throw new ArgumentNullException("homeAgentAddresses"); HomeAgentAddresses = homeAgentAddresses; } /// <summary> /// Creates an instance from next header, checksum, home agent addresses and options. /// </summary> /// <param name="nextHeader">Identifies the type of header immediately following this extension header.</param> /// <param name="checksum"> /// Contains the checksum of the Mobility Header. /// The checksum is calculated from the octet string consisting of a "pseudo-header" /// followed by the entire Mobility Header starting with the Payload Proto field. /// The checksum is the 16-bit one's complement of the one's complement sum of this string. /// </param> /// <param name="homeAgentAddresses">A list of alternate home agent addresses for the mobile node.</param> /// <param name="options">Zero or more TLV-encoded mobility options.</param> public IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage(IpV4Protocol? nextHeader, ushort checksum, IList<IpV6Address> homeAgentAddresses, IpV6MobilityOptions options) : this(nextHeader, checksum, (ReadOnlyCollection<IpV6Address>)homeAgentAddresses.AsReadOnly(), options) { } /// <summary> /// Identifies the particular mobility message in question. /// An unrecognized MH Type field causes an error indication to be sent. /// </summary> public override IpV6MobilityHeaderType MobilityHeaderType { get { return IpV6MobilityHeaderType.HomeAgentSwitchMessage; } } /// <summary> /// A list of alternate home agent addresses for the mobile node. /// </summary> public ReadOnlyCollection<IpV6Address> HomeAgentAddresses { get; private set; } internal override int MessageDataLength { get { return MinimumMessageDataLength + HomeAgentAddresses.Count * IpV6Address.SizeOf + MobilityOptions.BytesLength; } } internal override bool EqualsMessageData(IpV6ExtensionHeaderMobility other) { return EqualsMessageData(other as IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage); } internal override int GetMessageDataHashCode() { return HomeAgentAddresses.SequenceGetHashCode(); } internal static IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage ParseMessageData(IpV4Protocol nextHeader, ushort checksum, DataSegment messageData) { if (messageData.Length < MinimumMessageDataLength) return null; byte numberOfAddresses = messageData[MessageDataOffset.NumberOfAddresses]; int homeAgentAddressesSize = numberOfAddresses * IpV6Address.SizeOf; if (messageData.Length < MinimumMessageDataLength + homeAgentAddressesSize) return null; IpV6Address[] homeAgentAddresses = new IpV6Address[numberOfAddresses]; for (int i = 0; i != numberOfAddresses; ++i) homeAgentAddresses[i] = messageData.ReadIpV6Address(MessageDataOffset.HomeAgentAddresses + i * IpV6Address.SizeOf, Endianity.Big); int optionsOffset = MessageDataOffset.HomeAgentAddresses + homeAgentAddressesSize; IpV6MobilityOptions options = new IpV6MobilityOptions(messageData.Subsegment(optionsOffset, messageData.Length - optionsOffset)); return new IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage(nextHeader, checksum, homeAgentAddresses, options); } internal override void WriteMessageData(byte[] buffer, int offset) { buffer.Write(offset + MessageDataOffset.NumberOfAddresses, (byte)HomeAgentAddresses.Count); for (int i = 0; i != HomeAgentAddresses.Count; ++i) buffer.Write(offset + MessageDataOffset.HomeAgentAddresses + i * IpV6Address.SizeOf, HomeAgentAddresses[i], Endianity.Big); MobilityOptions.Write(buffer, offset + MessageDataOffset.HomeAgentAddresses + HomeAgentAddresses.Count * IpV6Address.SizeOf); } private bool EqualsMessageData(IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage other) { return other != null && HomeAgentAddresses.SequenceEqual(other.HomeAgentAddresses); } } }
52.794521
176
0.591463
[ "BSD-3-Clause" ]
Kolibrice/Pcap.Net
PcapDotNet/src/PcapDotNet.Packets/IpV6/ExtensionHeaders/IpV6ExtensionHeaderMobilityHomeAgentSwitchMessage.cs
7,708
C#
using System; using System.Text; using System.Web; using System.Web.Http.Description; namespace AutomationSystemAPI.Areas.HelpPage { public static class ApiDescriptionExtensions { /// <summary> /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" /// </summary> /// <param name="description">The <see cref="ApiDescription"/>.</param> /// <returns>The ID as a string.</returns> public static string GetFriendlyId(this ApiDescription description) { string path = description.RelativePath; string[] urlParts = path.Split('?'); string localPath = urlParts[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; queryKeyString = String.Join("_", queryKeys); } StringBuilder friendlyPath = new StringBuilder(); friendlyPath.AppendFormat("{0}-{1}", description.HttpMethod.Method, localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); if (queryKeyString != null) { friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); } return friendlyPath.ToString(); } } }
38.692308
144
0.574553
[ "MIT" ]
ktodorov/IoT_AutomationSystem
AutomationSystemBackground/AutomationSystemAPI/Areas/HelpPage/ApiDescriptionExtensions.cs
1,509
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp15 { public partial class Form1 : Form { public Form1() { InitializeComponent(); GetPanels(); } string first = "white"; string second = "Black"; bool drag = false; Panel[,] panels = new Panel[8,8]; Panel to; Panel win_to; int Bp_ = 0; int Wp_ = 0; void LeftButtonMouseClick(object sender, MouseEventArgs e) { if(e.Button == MouseButtons.Left) { DoDragDrop((sender as Panel).BackgroundImage, DragDropEffects.Copy); Logic(sender); if (drag == true) { if (win_to == to) { to.BackgroundImage = (sender as Panel).BackgroundImage; } else { to.BackgroundImage = null; win_to.BackgroundImage = (sender as Panel).BackgroundImage; } (sender as Panel).BackgroundImage = null; drag = false; } } if(Wp_ == 12 || Bp_ == 12) { MessageBox.Show("Виграв гравець фішок - " + first + "!\n З рахунком - " + Wp_ + "/" + Bp_, "End", MessageBoxButtons.OK); } } void TextBoxDragDrop(object sender, DragEventArgs e) { Text = "Iamge"; to = sender as Panel; } void GetPanels() { int k = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (Controls[k].Name.Contains("panel")) { try { panels[i, j] = Controls[k] as Panel; } catch {} } else { j--; } k++; } } for (int kl = 0; kl < 8; kl++) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { int Y = panels[i, j].Location.Y; int X = panels[i, j].Location.X / 100; Y = (Y - (Y / 100) * 100) - 12; if (i != X || j != Y) { Panel p = panels[i, j]; panels[i, j] = panels[X, Y]; panels[X, Y] = p; } } } } } void swap(object a,object b) { object buffer; buffer = a; a = b; b = buffer; } void Logic(object sender) { int i_from = 0; int j_from = 0; int i_to = 0; int j_to = 0; win_to = to; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (panels[j, i].Location == to.Location) { i_to = j; j_to = i; } if (panels[j, i].Location == (sender as Panel).Location) { i_from = j; j_from = i; } } } if(first == (sender as Panel).Tag.ToString()) { if (panels[i_from,j_from].Location.X + 150 > panels[i_to,j_to].Location.X && panels[i_from, j_from].Location.X - 150 < panels[i_to, j_to].Location.X) { if (panels[i_from, j_from].Location.Y + 101 == panels[i_to, j_to].Location.Y) { if (panels[i_from, j_from].Tag == "Black") { } else { if (panels[i_from, j_from].Tag == "white" && first == "white") { if(panels[i_to, j_to].Tag == "Black") { if (panels[i_to, j_to].Location.X >= 705 || panels[i_to, j_to].Location.X <= 13 || panels[i_to, j_to].Location.Y == 709 || panels[i_to, j_to].Location.Y == 12) { drag = false; } else { if (panels[i_from, j_from].Location.X + 150 > panels[i_to, j_to].Location.X && panels[i_from, j_from].Location.X + 50 < panels[i_to, j_to].Location.X) { if(panels[i_to + 1,j_to + 1].Tag != "Black" && panels[i_to + 1, j_to + 1].Tag != "white") { win_to = panels[i_to + 1, j_to + 1]; drag = true; } } else { if (panels[i_to - 1, j_to + 1].Tag != "Black" && panels[i_to - 1, j_to + 1].Tag != "white") { win_to = panels[i_to - 1, j_to + 1]; drag = true; } } Wp_ += 1; Wp.Text = Convert.ToString(Wp_); } } else if (panels[i_to, j_to].Tag == "white") { drag = false; } else { drag = true; } } } } else if (panels[i_from, j_from].Location.Y - 101 == panels[i_to, j_to].Location.Y) { if (panels[i_from, j_from].Tag == "white") { } else { if (panels[i_from, j_from].Tag == "Black" && first == "Black") { if (panels[i_to, j_to].Tag == "white") { if (panels[i_to, j_to].Location.X >= 705 || panels[i_to, j_to].Location.X <= 13 || panels[i_to, j_to].Location.Y == 709 || panels[i_to, j_to].Location.Y == 12) { drag = false; } else { if (panels[i_from, j_from].Location.X + 150 > panels[i_to, j_to].Location.X && panels[i_from, j_from].Location.X + 50 < panels[i_to, j_to].Location.X) { if (panels[i_to + 1, j_to - 1].Tag != "Black" && panels[i_to + 1, j_to - 1].Tag != "white") { win_to = panels[i_to + 1, j_to - 1]; drag = true; } } else { if (panels[i_to - 1, j_to - 1].Tag != "Black" && panels[i_to - 1, j_to - 1].Tag != "white") { win_to = panels[i_to - 1, j_to - 1]; drag = true; } } Bp_ += 1; Bp.Text = Convert.ToString(Bp_); } } else if (panels[i_to, j_to].Tag == "black") { drag = false; } else { drag = true; } } } } } if(drag == true) { string buffer = first; Image img; panels[i_from,j_from].Tag = " "; if(win_to == to) { panels[i_to, j_to].Tag = buffer; first = second; second = buffer; } else { panels[i_to, j_to].Tag = " "; win_to.Tag = buffer; } if (first == "white") img = Bitmap.FromFile(@"../../Resources/imgonline-com-ua-Transparent-backgr-be1xfHEFov6n2xDT.bmp"); else img = Bitmap.FromFile(@"..\..\Resources\imgonline-com-ua-Transparent-backgr-dhVHs4mewy.bmp"); picture.BackgroundImage = img; } } } void TextBoxDragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; } private void Form1_Load(object sender, EventArgs e) { } private void panel14_Paint(object sender, PaintEventArgs e) { } private void panel30_Paint(object sender, PaintEventArgs e) { } private void panel16_Paint(object sender, PaintEventArgs e) { } private void panel31_Paint(object sender, PaintEventArgs e) { } private void panel27_Paint(object sender, PaintEventArgs e) { } private void panel26_Paint(object sender, PaintEventArgs e) { } private void panel12_Paint(object sender, PaintEventArgs e) { } private void panel23_Paint(object sender, PaintEventArgs e) { } private void panel22_Paint(object sender, PaintEventArgs e) { } private void panel10_Paint(object sender, PaintEventArgs e) { } private void panel19_Paint(object sender, PaintEventArgs e) { } private void panel18_Paint(object sender, PaintEventArgs e) { } private void panel37_Paint(object sender, PaintEventArgs e) { } private void panel45_Paint(object sender, PaintEventArgs e) { } private void panel53_Paint(object sender, PaintEventArgs e) { } private void panel62_Paint(object sender, PaintEventArgs e) { } private void panel63_Paint(object sender, PaintEventArgs e) { } private void panel55_Paint(object sender, PaintEventArgs e) { } private void panel47_Paint(object sender, PaintEventArgs e) { } private void panel39_Paint(object sender, PaintEventArgs e) { } private void panel34_Paint(object sender, PaintEventArgs e) { } private void panel42_Paint(object sender, PaintEventArgs e) { } private void panel50_Paint(object sender, PaintEventArgs e) { } private void panel58_Paint(object sender, PaintEventArgs e) { } private void panel64_Paint(object sender, PaintEventArgs e) { } private void button2_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Ви точно хочете закінчити свій хід?", "Закінчити Хід", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { string buffer = first; first = second; second = buffer; Image img; if (first == "white") img = Bitmap.FromFile(@"../../Resources/imgonline-com-ua-Transparent-backgr-be1xfHEFov6n2xDT.bmp"); else img = Bitmap.FromFile(@"..\..\Resources\imgonline-com-ua-Transparent-backgr-dhVHs4mewy.bmp"); picture.BackgroundImage = img; } } private void button1_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Ви точно хочете здатися?", "Здатися", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { MessageBox.Show("Ви здалися!\nВиграв гравець фішок - " + second + "!", "End", MessageBoxButtons.OK); this.DestroyHandle(); } } } }
32.984479
196
0.341086
[ "Apache-2.0" ]
DekToper/master
WindowsFormsApp15/Form1.cs
15,000
C#
using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using PlaywrightSharp.Helpers; using PlaywrightSharp.Tests.Attributes; using PlaywrightSharp.Tests.BaseTests; using PlaywrightSharp.Tests.Helpers; using Xunit; using Xunit.Abstractions; namespace PlaywrightSharp.Tests { ///<playwright-file>screencast.spec.js</playwright-file> [Collection(TestConstants.TestFixtureBrowserCollectionName)] public class ScreencastTests : PlaywrightSharpBrowserBaseTest { /// <inheritdoc/> public ScreencastTests(ITestOutputHelper output) : base(output) { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>videoSize should require videosPath</playwright-it> [Fact(Skip = "We are not using old properties")] public void VideoSizeShouldRequireVideosPath() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should work with old options</playwright-it> [Fact(Skip = "We are not using old properties")] public void ShouldWorkWithOldOptions() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should throw without recordVideo.dir</playwright-it> [Fact(Skip = "We don't need to test this")] public void ShouldThrowWithoutRecordVideoDir() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should capture static page</playwright-it> [SkipBrowserAndPlatformFact(skipWebkit: true, skipWindows: true)] public async Task ShouldCaptureStaticPage() { using var tempDirectory = new TempDirectory(); var context = await Browser.NewContextAsync( recordVideo: new RecordVideoOptions { Dir = tempDirectory.Path, Size = new ViewportSize { Width = 100, Height = 100 }, }); var page = await context.NewPageAsync(); await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'"); await Task.Delay(1000); await context.CloseAsync(); Assert.NotEmpty(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm")); } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should expose video path</playwright-it> [Fact(Timeout = PlaywrightSharp.Playwright.DefaultTimeout)] public async Task ShouldExposeVideoPath() { using var tempDirectory = new TempDirectory(); var context = await Browser.NewContextAsync( recordVideo: new RecordVideoOptions { Dir = tempDirectory.Path, Size = new ViewportSize { Width = 100, Height = 100 } }); var page = await context.NewPageAsync(); await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'"); string path = await page.Video.GetPathAsync(); Assert.Contains(tempDirectory.Path, path); await context.CloseAsync(); Assert.True(new FileInfo(path).Exists); } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should expose video path blank page</playwright-it> [Fact(Timeout = PlaywrightSharp.Playwright.DefaultTimeout)] public async Task ShouldExposeVideoPathBlankPage() { using var tempDirectory = new TempDirectory(); var context = await Browser.NewContextAsync( recordVideo: new RecordVideoOptions { Dir = tempDirectory.Path, Size = new ViewportSize { Width = 100, Height = 100 } }); var page = await context.NewPageAsync(); string path = await page.Video.GetPathAsync(); Assert.Contains(tempDirectory.Path, path); await context.CloseAsync(); Assert.True(new FileInfo(path).Exists); } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should expose video path blank popup</playwright-it> [Fact(Skip = "We don't need to test video details")] public void ShouldExposeVideoPathBlankPopup() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should capture navigation</playwright-it> [Fact(Skip = "We don't need to test video details")] public void ShouldCaptureNavigation() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should capture css transformation</playwright-it> [Fact(Skip = "We don't need to test video details")] public void ShouldCaptureCssTransformation() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should work for popups</playwright-it> [Fact(Skip = "We don't need to test video details")] public void ShouldWorkForPopups() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should scale frames down to the requested size</playwright-it> [Fact(Skip = "We don't need to test video details")] public void ShouldScaleFramesDownToTheRequestedSize() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should use viewport as default size</playwright-it> [Fact(Skip = "We don't need to test video details")] public void ShouldUseViewportAsDefaultSize() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should be 1280x720 by default</playwright-it> [Fact(Skip = "We don't need to test video details")] public void ShouldBe1280x720ByDefault() { } ///<playwright-file>screencast.spec.js</playwright-file> ///<playwright-it>should capture static page in persistent context</playwright-it> [SkipBrowserAndPlatformFact(skipWebkit: true, skipWindows: true)] public async Task ShouldCaptureStaticPageInPersistentContext() { using var userDirectory = new TempDirectory(); using var tempDirectory = new TempDirectory(); var context = await BrowserType.LaunchPersistentContextAsync( userDirectory.Path, recordVideo: new RecordVideoOptions { Dir = tempDirectory.Path, Size = new ViewportSize { Width = 100, Height = 100 } }); var page = await context.NewPageAsync(); await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'"); await Task.Delay(1000); await context.CloseAsync(); Assert.NotEmpty(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm")); } } }
39.955801
90
0.609237
[ "MIT" ]
ScottHuangZL/playwright-sharp
src/PlaywrightSharp.Tests/ScreencastTests.cs
7,232
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; namespace Azure.ResourceManager.Core { /// <summary> /// A class representing a resource type filter used in Azure API calls. /// </summary> public class ResourceTypeFilter : GenericResourceFilter, IEquatable<ResourceTypeFilter>, IEquatable<string> { /// <summary> /// Initializes a new instance of the <see cref="ResourceTypeFilter"/> class. /// </summary> /// <param name="resourceType"> The resource type to filter by. </param> /// <exception cref="ArgumentNullException"> If <see cref="ResourceType"/> is null. </exception> public ResourceTypeFilter(ResourceType resourceType) { if (resourceType is null) throw new ArgumentNullException(nameof(resourceType)); ResourceType = resourceType; } /// <summary> /// Gets the resource type to filter by. /// </summary> public ResourceType ResourceType { get; } /// <inheritdoc/> public bool Equals(string other) { return ResourceType.Equals(other); } /// <inheritdoc/> public bool Equals(ResourceTypeFilter other) { return ResourceType.Equals(other); } /// <inheritdoc/> public override string GetFilterString() { return $"resourceType EQ '{ResourceType}'"; } /// <inheritdoc/> public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(null, obj)) return false; if (obj is string other) return Equals(other); return Equals(obj as ResourceTypeFilter); } /// <inheritdoc/> public override int GetHashCode() { return ResourceType.GetHashCode(); } } }
28.591549
111
0.570936
[ "MIT" ]
lynxz/azure-sdk-for-net
sdk/resourcemanager/Azure.ResourceManager.Core/src/ResourceFilter/ResourceTypeFilter.cs
2,032
C#
using System; using System.IO; using Microsoft.Win32; namespace Karadzhov.ExternalInvocations.VisualStudioCommonTools { internal static class WindowsSdkLocator { public static string Root { get { return WindowsSdkLocator.rootPath.Value; } } public static string Lib { get { return WindowsSdkLocator.libPath.Value; } } public static string Lib64 { get { return WindowsSdkLocator.lib64Path.Value; } } public static string Include { get { return WindowsSdkLocator.includePath.Value; } } private static string FindRootPath() { var sdkRootPath = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.1A", "InstallationFolder", null) as string; if (null == sdkRootPath) throw new InvalidOperationException("Could not find Windows SDK 7.1A installation folder."); return sdkRootPath; } private static string FindLibPath() { return Path.Combine(WindowsSdkLocator.Root, "Lib"); } private static string FindLib64Path() { return Path.Combine(WindowsSdkLocator.Root, "Lib\\x64"); } private static string FindIncludePath() { return Path.Combine(WindowsSdkLocator.Root, "Include"); } private static readonly Lazy<string> rootPath = new Lazy<string>(WindowsSdkLocator.FindRootPath); private static readonly Lazy<string> libPath = new Lazy<string>(WindowsSdkLocator.FindLibPath); private static readonly Lazy<string> lib64Path = new Lazy<string>(WindowsSdkLocator.FindLib64Path); private static readonly Lazy<string> includePath = new Lazy<string>(WindowsSdkLocator.FindIncludePath); } }
28.859155
161
0.588092
[ "Apache-2.0" ]
Boyko-Karadzhov/External-Invocations
Karadzhov.ExternalInvocations.VisualStudioCommonTools/WindowsSdkLocator.cs
2,051
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101 { using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell; /// <summary>The list Kusto database principal assignments operation response.</summary> [System.ComponentModel.TypeConverter(typeof(DatabasePrincipalAssignmentListResultTypeConverter))] public partial class DatabasePrincipalAssignmentListResult { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.DatabasePrincipalAssignmentListResult" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal DatabasePrincipalAssignmentListResult(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignment[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignment>(__y, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.DatabasePrincipalAssignmentTypeConverter.ConvertFrom)); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.DatabasePrincipalAssignmentListResult" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal DatabasePrincipalAssignmentListResult(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResultInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignment[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignment>(__y, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.DatabasePrincipalAssignmentTypeConverter.ConvertFrom)); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.DatabasePrincipalAssignmentListResult" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResult" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new DatabasePrincipalAssignmentListResult(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.DatabasePrincipalAssignmentListResult" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResult" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new DatabasePrincipalAssignmentListResult(content); } /// <summary> /// Creates a new instance of <see cref="DatabasePrincipalAssignmentListResult" />, deserializing the content from a json /// string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabasePrincipalAssignmentListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// The list Kusto database principal assignments operation response. [System.ComponentModel.TypeConverter(typeof(DatabasePrincipalAssignmentListResultTypeConverter))] public partial interface IDatabasePrincipalAssignmentListResult { } }
67.574627
632
0.707344
[ "MIT" ]
Agazoth/azure-powershell
src/Kusto/generated/api/Models/Api202101/DatabasePrincipalAssignmentListResult.PowerShell.cs
8,922
C#
using System; using System.Collections.Generic; using System.Net; using System.Reflection; using Nini.Config; using log4net; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Data; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.ExperienceService { public class ExperienceService : ExperienceServiceBase, IExperienceService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private IUserAccountService m_UserService = null; private const int MAX_QUOTA = 1024 * 1024 * 16; public ExperienceService(IConfigSource config) : base(config) { m_log.Debug("[EXPERIENCE SERVICE]: Starting experience service"); IConfig userConfig = config.Configs["ExperienceService"]; if (userConfig == null) throw new Exception("No ExperienceService configuration"); string userServiceDll = userConfig.GetString("UserAccountService", string.Empty); if (userServiceDll != string.Empty) m_UserService = LoadPlugin<IUserAccountService>(userServiceDll, new Object[] { config }); if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand("Experience", false, "create new experience", "create new experience <first> <last>", "Create a new experience owned by a user.", HandleCreateNewExperience); MainConsole.Instance.Commands.AddCommand("Experience", false, "suspend experience", "suspend experience <key> <true/false>", "Suspend/unsuspend an experience by its key.", HandleSuspendExperience); } } private void HandleCreateNewExperience(string module, string[] cmdparams) { string firstName; string lastName; string experienceKey; if (cmdparams.Length < 4) firstName = MainConsole.Instance.Prompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.Prompt("Last name"); else lastName = cmdparams[4]; if (cmdparams.Length < 6) experienceKey = MainConsole.Instance.Prompt("Experience Key (leave blank for random):", ""); else experienceKey = cmdparams[5]; UUID newExperienceKey; if (experienceKey == "") newExperienceKey = UUID.Random(); else { if(!UUID.TryParse(experienceKey, out newExperienceKey)) { MainConsole.Instance.Output("Invalid UUID"); return; } } UserAccount account = m_UserService.GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { MainConsole.Instance.Output("No such user as {0} {1}", firstName, lastName); return; } var existing = GetExperienceInfos(new UUID[] { newExperienceKey }); if(existing.Length > 0) { MainConsole.Instance.Output("Experience already exists!"); return; } ExperienceInfo new_info = new ExperienceInfo { public_id = newExperienceKey, owner_id = account.PrincipalID }; var stored_info = UpdateExpereienceInfo(new_info); if (stored_info == null) MainConsole.Instance.Output("Unable to create experience!"); else { MainConsole.Instance.Output("Experience created!"); if(m_KeyValueDatabase.CreateKeyValueTable(stored_info.public_id)) { MainConsole.Instance.Output("KeyValue database created successfully!"); } else { MainConsole.Instance.Output("Failed to create KeyValue database!"); } } } private void HandleSuspendExperience(string module, string[] cmdparams) { string experience_key; string enabled_str; if (cmdparams.Length < 3) experience_key = MainConsole.Instance.Prompt("Experience Key"); else experience_key = cmdparams[2]; UUID experienceID; if(!UUID.TryParse(experience_key, out experienceID)) { MainConsole.Instance.Output("Invalid key!"); return; } if (cmdparams.Length < 4) enabled_str = MainConsole.Instance.Prompt("Suspended:", "false"); else enabled_str = cmdparams[3]; bool suspend = enabled_str == "true"; var infos = GetExperienceInfos(new UUID[] { experienceID }); if(infos.Length != 1) { MainConsole.Instance.Output("Experience not found!"); return; } ExperienceInfo info = infos[0]; bool is_suspended = (info.properties & (int)ExperienceFlags.Suspended) != 0; string message = ""; bool update = false; if (suspend && !is_suspended) { info.properties |= (int)ExperienceFlags.Suspended; message = "Experience has been suspended"; update = true; } else if(!suspend && is_suspended) { info.properties &= ~(int)ExperienceFlags.Suspended; message = "Experience has been unsuspended"; update = true; } else if(suspend && is_suspended) { message = "Experience is already suspended"; } else if (!suspend && !is_suspended) { message = "Experience is not suspended"; } if(update) { var updated = UpdateExpereienceInfo(info); if (updated != null) { MainConsole.Instance.Output(message); } else MainConsole.Instance.Output("Error updating experience!"); } else { MainConsole.Instance.Output(message); } } public Dictionary<UUID, bool> FetchExperiencePermissions(UUID agent_id) { return m_Database.GetExperiencePermissions(agent_id); } public ExperienceInfo[] FindExperiencesByName(string search) { List<ExperienceInfo> infos = new List<ExperienceInfo>(); ExperienceInfoData[] datas = m_Database.FindExperiences(search); foreach (var data in datas) { ExperienceInfo info = new ExperienceInfo(data.ToDictionary()); infos.Add(info); } return infos.ToArray(); } public UUID[] GetAgentExperiences(UUID agent_id) { return m_Database.GetAgentExperiences(agent_id); } public ExperienceInfo[] GetExperienceInfos(UUID[] experiences) { ExperienceInfoData[] datas = m_Database.GetExperienceInfos(experiences); List<ExperienceInfo> infos = new List<ExperienceInfo>(); foreach (var data in datas) { infos.Add(new ExperienceInfo(data.ToDictionary())); } return infos.ToArray(); } public UUID[] GetExperiencesForGroups(UUID[] groups) { return m_Database.GetExperiencesForGroups(groups); } public UUID[] GetGroupExperiences(UUID group_id) { return m_Database.GetGroupExperiences(group_id); } public ExperienceInfo UpdateExpereienceInfo(ExperienceInfo info) { ExperienceInfoData data = new ExperienceInfoData(); data.public_id = info.public_id; data.owner_id = info.owner_id; data.name = info.name; data.description = info.description; data.group_id = info.group_id; data.slurl = info.slurl; data.logo = info.logo; data.marketplace = info.marketplace; data.maturity = info.maturity; data.properties = info.properties; if (m_Database.UpdateExperienceInfo(data)) { var find = GetExperienceInfos(new UUID[] { data.public_id }); if(find.Length == 1) { return new ExperienceInfo(find[0].ToDictionary()); } } return null; } public bool UpdateExperiencePermissions(UUID agent_id, UUID experience, ExperiencePermission perm) { if (perm == ExperiencePermission.None) return m_Database.ForgetExperiencePermissions(agent_id, experience); else return m_Database.SetExperiencePermissions(agent_id, experience, perm == ExperiencePermission.Allowed); } public string GetKeyValue(UUID experience, string key) { return m_KeyValueDatabase.GetKeyValue(experience, key); } public string CreateKeyValue(UUID experience, string key, string value) { int current_size = m_KeyValueDatabase.GetSize(experience); if (current_size + key.Length + value.Length > MAX_QUOTA) return "full"; string get = m_KeyValueDatabase.GetKeyValue(experience, key); if (get == null) { if (m_KeyValueDatabase.SetKeyValue(experience, key, value)) return "success"; else return "error"; } else return "exists"; } public string UpdateKeyValue(UUID experience, string key, string val, bool check, string original) { string get = m_KeyValueDatabase.GetKeyValue(experience, key); if (get != null) { if (check && get != original) return "mismatch"; int current_size = m_KeyValueDatabase.GetSize(experience); if ((current_size - get.Length) + val.Length > MAX_QUOTA) return "full"; if (m_KeyValueDatabase.SetKeyValue(experience, key, val)) return "success"; else return "error"; } else return "missing"; } public string DeleteKey(UUID experience, string key) { string get = m_KeyValueDatabase.GetKeyValue(experience, key); if (get != null) { return m_KeyValueDatabase.DeleteKey(experience, key) ? "success" : "failed"; } return "missing"; } public int GetKeyCount(UUID experience) { return m_KeyValueDatabase.GetKeyCount(experience); } public string[] GetKeys(UUID experience, int start, int count) { return m_KeyValueDatabase.GetKeys(experience, start, count); } public int GetSize(UUID experience) { return m_KeyValueDatabase.GetSize(experience); } } }
34.140351
120
0.547876
[ "BSD-3-Clause" ]
BillBlight/ycfs-opensim
OpenSim/Services/ExperienceService/ExperienceService.cs
11,676
C#
// 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. namespace System.Drawing { /// <summary> /// Specifies alignment of content on the drawing surface. /// </summary> [System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public enum ContentAlignment { /// <summary> /// Content is vertically aligned at the top, and horizontally aligned on the left. /// </summary> TopLeft = 0x001, /// <summary> /// Content is vertically aligned at the top, and horizontally aligned at the center. /// </summary> TopCenter = 0x002, /// <summary> /// Content is vertically aligned at the top, and horizontally aligned on the right. /// </summary> TopRight = 0x004, /// <summary> /// Content is vertically aligned in the middle, and horizontally aligned on the left. /// </summary> MiddleLeft = 0x010, /// <summary> /// Content is vertically aligned in the middle, and horizontally aligned at the center. /// </summary> MiddleCenter = 0x020, /// <summary> /// Content is vertically aligned in the middle, and horizontally aligned on the right. /// </summary> MiddleRight = 0x040, /// <summary> /// Content is vertically aligned at the bottom, and horizontally aligned on the left. /// </summary> BottomLeft = 0x100, /// <summary> /// Content is vertically aligned at the bottom, and horizontally aligned at the center. /// </summary> BottomCenter = 0x200, /// <summary> /// Content is vertically aligned at the bottom, and horizontally aligned on the right. /// </summary> BottomRight = 0x400, } }
39.823529
140
0.615953
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Drawing.Common/src/System/Drawing/ContentAlignment.cs
2,031
C#
using System; using Android; using Android.App; using Android.OS; using Android.Support.Design.Widget; using Android.Support.V4.View; using Android.Support.V4.Widget; using Android.Support.V7.App; using Android.Views; using Android.Widget; using APPMTP.Fragments; namespace APPMTP { [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)] public class MainActivity : AppCompatActivity, NavigationView.IOnNavigationItemSelectedListener { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab); fab.Click += FabOnClick; DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close); drawer.AddDrawerListener(toggle); toggle.SyncState(); NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view); navigationView.SetNavigationItemSelectedListener(this); // } public override void OnBackPressed() { DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout); if(drawer.IsDrawerOpen(GravityCompat.Start)) { drawer.CloseDrawer(GravityCompat.Start); } else { base.OnBackPressed(); } } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.menu_main, menu); return true; } public override bool OnOptionsItemSelected(IMenuItem item) { int id = item.ItemId; if (id == Resource.Id.action_settings) { return true; } return base.OnOptionsItemSelected(item); } private void FabOnClick(object sender, EventArgs eventArgs) { View view = (View) sender; Snackbar.Make(view, "Replace with your own action", Snackbar.LengthLong) .SetAction("Action", (Android.Views.View.IOnClickListener)null).Show(); } public bool OnNavigationItemSelected(IMenuItem item) { int id = item.ItemId; if (id == Resource.Id.nav_camera) { // Handle the camera action } else if (id == Resource.Id.nav_gallery) { changeFrame("aboutus"); } else if (id == Resource.Id.nav_slideshow) { changeFrame("products"); } else if (id == Resource.Id.nav_manage) { } else if (id == Resource.Id.nav_share) { } else if (id == Resource.Id.nav_send) { } DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout); drawer.CloseDrawer(GravityCompat.Start); return true; } private void changeFrame(string _type) { FragmentTransaction ft = FragmentManager.BeginTransaction(); Fragment fragment = null; if (_type.Equals("aboutus")) { fragment = new FragmentAboutUs(); } else if (_type.Equals("products")) { fragment = new FragmentProducts(); } else { } if (fragment != null) { ft.Replace(Resource.Id.fragmentMany, fragment); //////ft.AddToBackStack(null); ft.SetTransition(FragmentTransit.FragmentFade); ft.Commit(); } } } }
31.708955
173
0.571664
[ "Apache-2.0" ]
GiancarloNunezMacha/AMTPATTY
src/APPMTP/APPMTP/MainActivity.cs
4,251
C#
// <auto-generated /> using System; using Bing_Picture.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Bing_Picture.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-preview1") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
35.07173
125
0.488811
[ "MIT" ]
Night-Dawn/StudyDemo
Bing Picture/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
8,312
C#
// 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. #nullable enable using System; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { private sealed class LazyRemoteService { public readonly AsyncLazy<InitializedRemoteService> InitializedService; public readonly CancellationTokenSource CancellationSource; public readonly InteractiveHostOptions Options; public readonly InteractiveHost Host; public readonly bool SkipInitialization; public readonly int InstanceId; public LazyRemoteService(InteractiveHost host, InteractiveHostOptions options, int instanceId, bool skipInitialization) { InitializedService = new AsyncLazy<InitializedRemoteService>(TryStartAndInitializeProcessAsync, cacheResult: true); CancellationSource = new CancellationTokenSource(); InstanceId = instanceId; Options = options; Host = host; SkipInitialization = skipInitialization; } public void Dispose() { // Cancel the creation of the process if it is in progress. // If it is the cancellation will clean up all resources allocated during the creation. CancellationSource.Cancel(); // If the value has been calculated already, dispose the service. if (InitializedService.TryGetValue(out var initializedService)) { initializedService.Service?.Dispose(); } } private async Task<InitializedRemoteService> TryStartAndInitializeProcessAsync(CancellationToken cancellationToken) { try { Host.ProcessStarting?.Invoke(Options.InitializationFile != null); var remoteService = await TryStartProcessAsync(Options.GetHostPath(), Options.Culture, cancellationToken).ConfigureAwait(false); if (remoteService == null) { return default; } if (SkipInitialization) { return new InitializedRemoteService(remoteService, new RemoteExecutionResult(success: true)); } bool initializing = true; cancellationToken.Register(() => { if (initializing) { // kill the process without triggering auto-reset: remoteService.Dispose(); } }); // try to execute initialization script: var initializationResult = await Async<RemoteExecutionResult>(remoteService, (service, operation) => { service.InitializeContext(operation, Options.InitializationFile, isRestarting: InstanceId > 1); }).ConfigureAwait(false); initializing = false; if (!initializationResult.Success) { Host.ReportProcessExited(remoteService.Process); remoteService.Dispose(); return default; } // Hook up a handler that initiates restart when the process exits. // Note that this is just so that we restart the process as soon as we see it dying and it doesn't need to be 100% bullet-proof. // If we don't receive the "process exited" event we will restart the process upon the next remote operation. remoteService.HookAutoRestartEvent(); return new InitializedRemoteService(remoteService, initializationResult); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private Task<RemoteService?> TryStartProcessAsync(string hostPath, CultureInfo culture, CancellationToken cancellationToken) { return Task.Run(() => Host.TryStartProcess(hostPath, culture, cancellationToken)); } } } }
42.353982
148
0.576055
[ "MIT" ]
Dean-ZhenYao-Wang/roslyn
src/Interactive/Host/Interactive/Core/InteractiveHost.LazyRemoteService.cs
4,788
C#
using System; namespace LinkDev.MOA.POC.API.Areas.HelpPage.ModelDescriptions { public class ParameterAnnotation { public Attribute AnnotationAttribute { get; set; } public string Documentation { get; set; } } }
21.818182
62
0.695833
[ "MIT" ]
EmadSaad/LinkDev.MOA.POC
LinkDev.MOA.POC.API/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs
240
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ApiManagement.V20180601Preview.Outputs { /// <summary> /// Custom hostname configuration. /// </summary> [OutputType] public sealed class HostnameConfigurationResponse { /// <summary> /// Certificate information. /// </summary> public readonly Outputs.CertificateInformationResponse? Certificate; /// <summary> /// Certificate Password. /// </summary> public readonly string? CertificatePassword; /// <summary> /// Specify true to setup the certificate associated with this Hostname as the Default SSL Certificate. If a client does not send the SNI header, then this will be the certificate that will be challenged. The property is useful if a service has multiple custom hostname enabled and it needs to decide on the default ssl certificate. The setting only applied to Proxy Hostname Type. /// </summary> public readonly bool? DefaultSslBinding; /// <summary> /// Base64 Encoded certificate. /// </summary> public readonly string? EncodedCertificate; /// <summary> /// Hostname to configure on the Api Management service. /// </summary> public readonly string HostName; /// <summary> /// Url to the KeyVault Secret containing the Ssl Certificate. If absolute Url containing version is provided, auto-update of ssl certificate will not work. This requires Api Management service to be configured with MSI. The secret should be of type *application/x-pkcs12* /// </summary> public readonly string? KeyVaultId; /// <summary> /// Specify true to always negotiate client certificate on the hostname. Default Value is false. /// </summary> public readonly bool? NegotiateClientCertificate; /// <summary> /// Hostname type. /// </summary> public readonly string Type; [OutputConstructor] private HostnameConfigurationResponse( Outputs.CertificateInformationResponse? certificate, string? certificatePassword, bool? defaultSslBinding, string? encodedCertificate, string hostName, string? keyVaultId, bool? negotiateClientCertificate, string type) { Certificate = certificate; CertificatePassword = certificatePassword; DefaultSslBinding = defaultSslBinding; EncodedCertificate = encodedCertificate; HostName = hostName; KeyVaultId = keyVaultId; NegotiateClientCertificate = negotiateClientCertificate; Type = type; } } }
37.790123
389
0.650114
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ApiManagement/V20180601Preview/Outputs/HostnameConfigurationResponse.cs
3,061
C#
using System; using Xunit; using AtCoderBeginnerContest139.Questions; using System.Collections.Generic; using System.Linq; namespace AtCoderBeginnerContest139.Test { public class AtCoderTester { [Theory] [InlineData(@"CSS CSR", @"2")] [InlineData(@"SSR SSR", @"3")] [InlineData(@"RRR SSS", @"0")] public void QuestionATest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionA(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"4 10", @"3")] [InlineData(@"8 9", @"2")] [InlineData(@"8 8", @"1")] public void QuestionBTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionB(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"5 10 4 8 7 3", @"2")] [InlineData(@"7 4 4 5 6 6 5 5", @"3")] [InlineData(@"4 1 2 3 4", @"0")] public void QuestionCTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionC(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"2", @"1")] [InlineData(@"13", @"78")] [InlineData(@"1", @"0")] public void QuestionDTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionD(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } [Theory] [InlineData(@"3 2 3 1 3 1 2", @"3")] [InlineData(@"4 2 3 4 1 3 4 4 1 2 3 1 2", @"4")] [InlineData(@"3 2 3 3 1 1 2", @"-1")] public void QuestionETest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionE(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } //[Theory] //[InlineData(@"", @"")] public void QuestionFTest(string input, string output) { var outputs = SplitByNewLine(output); IAtCoderQuestion question = new QuestionF(); var answers = question.Solve(input).Select(o => o.ToString()).ToArray(); Assert.Equal(outputs, answers); } IEnumerable<string> SplitByNewLine(string input) => input?.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None) ?? new string[0]; } }
27.0625
145
0.551963
[ "MIT" ]
terry-u16/AtCoder
AtCoderBeginnerContest139/AtCoderBeginnerContest139/AtCoderBeginnerContest139.Test/AtCoderTester.cs
3,031
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; using StardewValley.Menus; using StardewValley.Locations; using StardewValley.Objects; namespace ChefsCloset { public class ModEntry : Mod { public override void Entry(IModHelper helper) { LocationEvents.CurrentLocationChanged += UpdateLocation; MenuEvents.MenuChanged += ExtendCookingItems; MenuEvents.MenuClosed += ResolveCookedItems; } private FarmHouse _farmHouse; private Vector2 _kitchenRange = new Vector2(6, 0); private List<Item> _fridgeItems = new List<Item>(); private List<List<Item>> _chestItems = new List<List<Item>>(); private bool _isCookingSkillLoaded; private bool IsCookingMenu(IClickableMenu menu) { if (_farmHouse == null || _farmHouse.upgradeLevel == 0) { return false; } if (menu is CraftingPage) { return true; } if (_isCookingSkillLoaded && menu.GetType() == Type.GetType("CookingSkill.NewCraftingPage, CookingSkill")) { return true; } return false; } private void ResolveCookedItems(object seneder, EventArgsClickableMenuClosed e) { if (IsCookingMenu(e.PriorMenu)) { // remove all used items from fridge and reset fridge inventory if (_fridgeItems.Any()) { _fridgeItems.RemoveAll(x => x.Stack == 0); _farmHouse.fridge.items = _fridgeItems; } // remove all used items from chests if (_chestItems.Any()) { foreach (var obj in _farmHouse.objects) { Chest chest = obj.Value as Chest; if (chest == null || chest == _farmHouse.fridge || obj.Key.X > _kitchenRange.X || obj.Key.Y < _kitchenRange.Y) continue; chest.items = _chestItems.First(x => x == chest.items); if (chest.items.Any()) { chest.items.RemoveAll(x => x.Stack == 0); } } _chestItems.Clear(); } } } private void ExtendCookingItems(object sender, EventArgsClickableMenuChanged e) { if (IsCookingMenu(e.NewMenu)) { _fridgeItems = _farmHouse.fridge.items; var cookingItems = new List<Item>(); var chestKeys = new List<Vector2>(); // collect chest keys from kitchen tiles foreach (var obj in _farmHouse.objects) { Chest chest = obj.Value as Chest; if (chest == null || chest == _farmHouse.fridge) continue; if (obj.Key.X > _kitchenRange.X || obj.Key.Y < _kitchenRange.Y) { // Monitor.Log($"Chest found out of range at {obj.Key.X},{obj.Key.Y}"); continue; } chestKeys.Add(obj.Key); } // order keys to ensure chest items are consumed in the correct order: left-right/top-bottom chestKeys = chestKeys.OrderBy(x => x.X).ToList().OrderBy(x => x.Y).ToList(); chestKeys.Reverse(); // consolidate cooking items foreach (var chestKey in chestKeys) { StardewValley.Object chest; _farmHouse.objects.TryGetValue(chestKey, out chest); if (chest != null) { // Monitor.Log($"Adding {((Chest)chest).items.Count} items from chest at {chestKey.X},{chestKey.Y}"); _chestItems.Add(((Chest)chest).items); cookingItems.AddRange(((Chest)chest).items); } } cookingItems.AddRange(_fridgeItems); // apply cooking items _farmHouse.fridge.items = cookingItems; } } // keeps track of location state private void UpdateLocation(object sender, EventArgsCurrentLocationChanged e) { _isCookingSkillLoaded = this.Helper.ModRegistry.IsLoaded("spacechase0.CookingSkill"); if (e.NewLocation is FarmHouse) { _farmHouse = (FarmHouse)e.NewLocation; if (_farmHouse.upgradeLevel >= 2) { _kitchenRange.X = 9; _kitchenRange.Y = 14; } } else { _farmHouse = null; } } } }
27.257143
116
0.668501
[ "MIT" ]
ja450n/ChefsCloset
ChefsCloset/ModEntry.cs
3,818
C#
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.ApplicationInsights.Extensibility; using AppInsights.EnterpriseTelemetry.AspNetCore.Extension; using AppInsights.EnterpriseTelemetry.Web.Extension.Filters; using AppInsights.EnterpriseTelemetry.AppInsightsInitializers; namespace AppInsights.EnterpriseTelemetry.Web.Extension { /// <summary> /// Extensions class to use Enterprise Logger in ASP.NET Core Applications /// </summary> public static class EnterpriseTelemetryExtensions { private static readonly object _lock = new object(); private static ITelemetryExtensionsBuilder extensionBuilder; public static void SetExtensionsBuilder(ITelemetryExtensionsBuilder builder) { extensionBuilder = builder; } private static ITelemetryExtensionsBuilder GetBuilder(IConfiguration config, params ITelemetryInitializer[] customTelemetryInitializers) { lock(_lock) { if (extensionBuilder != null) { return extensionBuilder; } extensionBuilder = new TelemetryExtensionsBuilder(config, customTelemetryInitializers); return extensionBuilder; } } /// <summary> /// Creates an instance of <see cref="ILogger"/> /// </summary> /// <param name="config" cref="IConfiguration">Configuration</param> /// <param name="customTelemetryInitializers" cref="ITelemetryInitializer[]">App specific additional telemetry initializers</param> /// <returns cref="ILogger">Enterprise Logger</returns> public static ILogger CreateLogger(IConfiguration config, params ITelemetryInitializer[] customTelemetryInitializers) { ITelemetryExtensionsBuilder builder = GetBuilder(config, customTelemetryInitializers); return builder.CreateLogger(); } /// <summary> /// Registers <see cref="ILogger"/> in <see cref="IServiceCollection"/> for dependency injection /// </summary> /// <param name="services"></param> /// <param name="config" cref="IConfiguration">Configuration</param> /// <param name="customTelemetryInitializer" cref="ITelemetryInitializer[]">App specific additional telemetry initializers</param> public static void AddEnterpriseTelemetry(this IServiceCollection services, IConfiguration config, params ITelemetryInitializer[] customTelemetryInitializers) { ITelemetryExtensionsBuilder builder = GetBuilder(config, customTelemetryInitializers); builder.AddEnterpriseTelemetry(services); } /// <summary> /// Registers the filter <see cref= "RequestResponseInitializer"/> for adding additional attributes in the Request/Response for HTTP request /// </summary> /// <param name="services"></param> /// <param name="config" cref="IConfiguration">Configuration</param> public static void RegisterRequestResponseLoggingFilter(this IServiceCollection services, IConfiguration config, params ITelemetryInitializer[] customTelemetryInitializers) { ITelemetryExtensionsBuilder builder = GetBuilder(config, customTelemetryInitializers); builder.AddRequestResponseFilter(services); } /// <summary> /// Registers the filter <see cref="TrackingPropertiesFilterAttribute"/> to add tracking IDs in each HTTP request and response /// </summary> /// <param name="services"></param> /// <param name="config" cref="IConfiguration">Configuration</param> public static void RegisterTrackingPropertiesFilter(this IServiceCollection services, IConfiguration config, params ITelemetryInitializer[] customTelemetryInitializers) { ITelemetryExtensionsBuilder builder = GetBuilder(config, customTelemetryInitializers); builder.AddTrackingFilter(services); } /// <summary> /// Adds enterprise telemetry in the request pipeline /// </summary> /// <param name="app" cref="IApplicationBuilder"></param> /// <param name="config" cref="IConfiguration">Configuration</param> /// <param name="customTelemetryInitializer" cref="ITelemetryInitializer[]">App specific additional telemetry initializers</param> public static void UseEnterpriseTelemetry(this IApplicationBuilder app, IConfiguration config, params ITelemetryInitializer[] customTelemetryInitializers) { ITelemetryExtensionsBuilder builder = GetBuilder(config, customTelemetryInitializers); builder.UseEnterpriseTelemetry(app); } /// <summary> /// Adds a global Exception Handling Middleware in the request pipeline /// </summary> /// <param name="app"></param> /// <param name="config" cref="IConfiguration">Configuration</param> public static void UseExceptionMiddleware(this IApplicationBuilder app, IConfiguration config, params ITelemetryInitializer[] customTelemetryInitializers) { ITelemetryExtensionsBuilder builder = GetBuilder(config, customTelemetryInitializers); builder.UseExceptionMiddleware(app); } } }
50.560748
180
0.692976
[ "MIT" ]
microsoft/AppInsights.EnterpriseTelemetry.AspNetCore.Extension
src/EnterpriseTelemetryExtensions.cs
5,412
C#
/** * Autogenerated by Thrift Compiler (0.9.1) * * 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; using Thrift.Protocol; using Thrift.Transport; namespace StormThrift { #if !SILVERLIGHT [Serializable] #endif public partial class TopologySummary : TBase { private string _sched_status; private string _owner; private int _replication_count; private double _requested_memonheap; private double _requested_memoffheap; private double _requested_cpu; private double _assigned_memonheap; private double _assigned_memoffheap; private double _assigned_cpu; public string Id { get; set; } public string Name { get; set; } public int Num_tasks { get; set; } public int Num_executors { get; set; } public int Num_workers { get; set; } public int Uptime_secs { get; set; } public string Status { get; set; } public string Sched_status { get { return _sched_status; } set { __isset.sched_status = true; this._sched_status = value; } } public string Owner { get { return _owner; } set { __isset.owner = true; this._owner = value; } } public int Replication_count { get { return _replication_count; } set { __isset.replication_count = true; this._replication_count = value; } } public double Requested_memonheap { get { return _requested_memonheap; } set { __isset.requested_memonheap = true; this._requested_memonheap = value; } } public double Requested_memoffheap { get { return _requested_memoffheap; } set { __isset.requested_memoffheap = true; this._requested_memoffheap = value; } } public double Requested_cpu { get { return _requested_cpu; } set { __isset.requested_cpu = true; this._requested_cpu = value; } } public double Assigned_memonheap { get { return _assigned_memonheap; } set { __isset.assigned_memonheap = true; this._assigned_memonheap = value; } } public double Assigned_memoffheap { get { return _assigned_memoffheap; } set { __isset.assigned_memoffheap = true; this._assigned_memoffheap = value; } } public double Assigned_cpu { get { return _assigned_cpu; } set { __isset.assigned_cpu = true; this._assigned_cpu = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool sched_status; public bool owner; public bool replication_count; public bool requested_memonheap; public bool requested_memoffheap; public bool requested_cpu; public bool assigned_memonheap; public bool assigned_memoffheap; public bool assigned_cpu; } public TopologySummary() { } public TopologySummary(string id, string name, int num_tasks, int num_executors, int num_workers, int uptime_secs, string status) : this() { this.Id = id; this.Name = name; this.Num_tasks = num_tasks; this.Num_executors = num_executors; this.Num_workers = num_workers; this.Uptime_secs = uptime_secs; this.Status = status; } public void Read (TProtocol iprot) { bool isset_id = false; bool isset_name = false; bool isset_num_tasks = false; bool isset_num_executors = false; bool isset_num_workers = false; bool isset_uptime_secs = false; bool isset_status = false; TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.String) { Id = iprot.ReadString(); isset_id = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.String) { Name = iprot.ReadString(); isset_name = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.I32) { Num_tasks = iprot.ReadI32(); isset_num_tasks = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 4: if (field.Type == TType.I32) { Num_executors = iprot.ReadI32(); isset_num_executors = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 5: if (field.Type == TType.I32) { Num_workers = iprot.ReadI32(); isset_num_workers = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 6: if (field.Type == TType.I32) { Uptime_secs = iprot.ReadI32(); isset_uptime_secs = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 7: if (field.Type == TType.String) { Status = iprot.ReadString(); isset_status = true; } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 513: if (field.Type == TType.String) { Sched_status = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 514: if (field.Type == TType.String) { Owner = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 515: if (field.Type == TType.I32) { Replication_count = iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 521: if (field.Type == TType.Double) { Requested_memonheap = iprot.ReadDouble(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 522: if (field.Type == TType.Double) { Requested_memoffheap = iprot.ReadDouble(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 523: if (field.Type == TType.Double) { Requested_cpu = iprot.ReadDouble(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 524: if (field.Type == TType.Double) { Assigned_memonheap = iprot.ReadDouble(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 525: if (field.Type == TType.Double) { Assigned_memoffheap = iprot.ReadDouble(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 526: if (field.Type == TType.Double) { Assigned_cpu = iprot.ReadDouble(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); if (!isset_id) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_name) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_num_tasks) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_num_executors) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_num_workers) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_uptime_secs) throw new TProtocolException(TProtocolException.INVALID_DATA); if (!isset_status) throw new TProtocolException(TProtocolException.INVALID_DATA); } public void Write(TProtocol oprot) { TStruct struc = new TStruct("TopologySummary"); oprot.WriteStructBegin(struc); TField field = new TField(); field.Name = "id"; field.Type = TType.String; field.ID = 1; oprot.WriteFieldBegin(field); oprot.WriteString(Id); oprot.WriteFieldEnd(); field.Name = "name"; field.Type = TType.String; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteString(Name); oprot.WriteFieldEnd(); field.Name = "num_tasks"; field.Type = TType.I32; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteI32(Num_tasks); oprot.WriteFieldEnd(); field.Name = "num_executors"; field.Type = TType.I32; field.ID = 4; oprot.WriteFieldBegin(field); oprot.WriteI32(Num_executors); oprot.WriteFieldEnd(); field.Name = "num_workers"; field.Type = TType.I32; field.ID = 5; oprot.WriteFieldBegin(field); oprot.WriteI32(Num_workers); oprot.WriteFieldEnd(); field.Name = "uptime_secs"; field.Type = TType.I32; field.ID = 6; oprot.WriteFieldBegin(field); oprot.WriteI32(Uptime_secs); oprot.WriteFieldEnd(); field.Name = "status"; field.Type = TType.String; field.ID = 7; oprot.WriteFieldBegin(field); oprot.WriteString(Status); oprot.WriteFieldEnd(); if (Sched_status != null && __isset.sched_status) { field.Name = "sched_status"; field.Type = TType.String; field.ID = 513; oprot.WriteFieldBegin(field); oprot.WriteString(Sched_status); oprot.WriteFieldEnd(); } if (Owner != null && __isset.owner) { field.Name = "owner"; field.Type = TType.String; field.ID = 514; oprot.WriteFieldBegin(field); oprot.WriteString(Owner); oprot.WriteFieldEnd(); } if (__isset.replication_count) { field.Name = "replication_count"; field.Type = TType.I32; field.ID = 515; oprot.WriteFieldBegin(field); oprot.WriteI32(Replication_count); oprot.WriteFieldEnd(); } if (__isset.requested_memonheap) { field.Name = "requested_memonheap"; field.Type = TType.Double; field.ID = 521; oprot.WriteFieldBegin(field); oprot.WriteDouble(Requested_memonheap); oprot.WriteFieldEnd(); } if (__isset.requested_memoffheap) { field.Name = "requested_memoffheap"; field.Type = TType.Double; field.ID = 522; oprot.WriteFieldBegin(field); oprot.WriteDouble(Requested_memoffheap); oprot.WriteFieldEnd(); } if (__isset.requested_cpu) { field.Name = "requested_cpu"; field.Type = TType.Double; field.ID = 523; oprot.WriteFieldBegin(field); oprot.WriteDouble(Requested_cpu); oprot.WriteFieldEnd(); } if (__isset.assigned_memonheap) { field.Name = "assigned_memonheap"; field.Type = TType.Double; field.ID = 524; oprot.WriteFieldBegin(field); oprot.WriteDouble(Assigned_memonheap); oprot.WriteFieldEnd(); } if (__isset.assigned_memoffheap) { field.Name = "assigned_memoffheap"; field.Type = TType.Double; field.ID = 525; oprot.WriteFieldBegin(field); oprot.WriteDouble(Assigned_memoffheap); oprot.WriteFieldEnd(); } if (__isset.assigned_cpu) { field.Name = "assigned_cpu"; field.Type = TType.Double; field.ID = 526; oprot.WriteFieldBegin(field); oprot.WriteDouble(Assigned_cpu); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } public override string ToString() { StringBuilder sb = new StringBuilder("TopologySummary("); sb.Append("Id: "); sb.Append(Id); sb.Append(",Name: "); sb.Append(Name); sb.Append(",Num_tasks: "); sb.Append(Num_tasks); sb.Append(",Num_executors: "); sb.Append(Num_executors); sb.Append(",Num_workers: "); sb.Append(Num_workers); sb.Append(",Uptime_secs: "); sb.Append(Uptime_secs); sb.Append(",Status: "); sb.Append(Status); sb.Append(",Sched_status: "); sb.Append(Sched_status); sb.Append(",Owner: "); sb.Append(Owner); sb.Append(",Replication_count: "); sb.Append(Replication_count); sb.Append(",Requested_memonheap: "); sb.Append(Requested_memonheap); sb.Append(",Requested_memoffheap: "); sb.Append(Requested_memoffheap); sb.Append(",Requested_cpu: "); sb.Append(Requested_cpu); sb.Append(",Assigned_memonheap: "); sb.Append(Assigned_memonheap); sb.Append(",Assigned_memoffheap: "); sb.Append(Assigned_memoffheap); sb.Append(",Assigned_cpu: "); sb.Append(Assigned_cpu); sb.Append(")"); return sb.ToString(); } } }
27.023033
144
0.556645
[ "Apache-2.0" ]
FsStorm/FsShelter
ext/StormThrift/StormThrift/TopologySummary.cs
14,079
C#
namespace SpicyInvader.Models { public class Score { public string PlayerName { get; set; } public int Value { get; set; } public Score() { } public Score(string playerName, int value) { PlayerName = playerName; Value = value; } } }
16.85
50
0.495549
[ "MIT" ]
Kalaneee/SpicyInvader
SpicyInvader/Models/Score.cs
339
C#
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace CRMAPP1 { /// <summary> /// Summary description for Home. /// </summary> public class Home : System.Web.UI.Page { protected System.Web.UI.WebControls.Label Label3; protected System.Web.UI.WebControls.Button Button2; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.LinkButton LinkButton4; protected System.Web.UI.WebControls.Panel Panel3; protected System.Web.UI.WebControls.LinkButton LinkButton1; protected System.Web.UI.WebControls.Image Image2; protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.TextBox TextBox2; protected System.Web.UI.WebControls.Panel Panel1; protected System.Web.UI.WebControls.Panel Panel2; public SqlConnection con=new SqlConnection ("server=.;database=crm;uid=sa;pwd=;"); private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Button2.Click += new System.EventHandler(this.Button2_Click); this.LinkButton1.Click += new System.EventHandler(this.LinkButton1_Click); this.LinkButton4.Click += new System.EventHandler(this.LinkButton4_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void LinkButton1_Click(object sender, System.EventArgs e) { Response.Redirect("Official Link.aspx"); } private void LinkButton2_Click(object sender, System.EventArgs e) { } private void LinkButton4_Click(object sender, System.EventArgs e) { Response.Redirect("CustomerModule/CustReg.aspx"); } private void Button2_Click(object sender, System.EventArgs e) { SqlCommand cmd=new SqlCommand(); con.Open(); cmd.Connection =con; cmd.CommandText ="select count(*) from crm_custreg where custname='"+TextBox1.Text+"' and pwd='"+TextBox2.Text+"'"; object re=cmd.ExecuteScalar(); con.Close(); int chk=Convert.ToInt32(re); if(chk==1) { Response.Redirect("CustomerModule/CustoMain.aspx"); } else { Response.Redirect("CustomerModule/Invaliduidpwd.aspx"); } } } }
28.138614
118
0.730823
[ "Apache-2.0" ]
Claudio1986/CRMAPP1
Home.aspx.cs
2,842
C#
namespace CSETWebCore.Model.Question { public class RequirementLevel { public int LevelOrder { get; set; } public string StandardLevel { get; set; } } }
22.625
49
0.640884
[ "MIT" ]
Project-CSET-RM-Module/cset
CSETWebApi/CSETWeb_Api/CSETWebCore.Model/Question/RequirementLevel.cs
183
C#
using System; using System.Buffers; using System.Collections.Generic; using System.Numerics; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; namespace GraphQL.SystemTextJson { /// <summary> /// A custom JsonConverter for reading a dictionary of objects of their real underlying type. /// Does not support write. /// </summary> public class ObjectDictionaryConverter : JsonConverter<Dictionary<string, object>> { public override void Write(Utf8JsonWriter writer, Dictionary<string, object> value, JsonSerializerOptions options) => throw new NotImplementedException( "This converter currently is only intended to be used to read a JSON object into a strongly-typed representation."); public override Dictionary<string, object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => ReadDictionary(ref reader); private static Dictionary<string, object> ReadDictionary(ref Utf8JsonReader reader) { if (reader.TokenType != JsonTokenType.StartObject) throw new JsonException(); var result = new Dictionary<string, object>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) break; if (reader.TokenType != JsonTokenType.PropertyName) throw new JsonException(); string key = reader.GetString(); // move to property value if (!reader.Read()) throw new JsonException(); result.Add(key, ReadValue(ref reader)); } return result; } private static object ReadValue(ref Utf8JsonReader reader) => reader.TokenType switch { JsonTokenType.StartArray => ReadArray(ref reader), JsonTokenType.StartObject => ReadDictionary(ref reader), JsonTokenType.Number => ReadNumber(ref reader), JsonTokenType.True => BoolBox.True, JsonTokenType.False => BoolBox.False, JsonTokenType.String => reader.GetString(), JsonTokenType.Null => null, JsonTokenType.None => null, _ => throw new InvalidOperationException($"Unexpected token type: {reader.TokenType}") }; private static List<object> ReadArray(ref Utf8JsonReader reader) { if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException(); var result = new List<object>(); while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndArray) break; result.Add(ReadValue(ref reader)); } return result; } private static object ReadNumber(ref Utf8JsonReader reader) { if (reader.TryGetInt32(out int i)) return i; else if (reader.TryGetInt64(out long l)) return l; else if (reader.TryGetDouble(out double d)) { // the idea is to see if there is a loss of accuracy of value // example: // value from json : 636474637870330463636474637870330463636474637870330463 // successfully parsed d : 6.3647463787033043E+53 // new BigInteger(d) : 636474637870330432588044308848152942336795574685138944 if (JsonConverterBigInteger.TryGetBigInteger(ref reader, out var bi)) { if (bi != new BigInteger(d)) return bi; } return d; } else if (reader.TryGetDecimal(out decimal dm)) { // the same idea as for a double value above if (JsonConverterBigInteger.TryGetBigInteger(ref reader, out var bi)) { if (bi != new BigInteger(dm)) return bi; } return dm; } throw new NotImplementedException($"Unexpected Number value. Raw text was: {Encoding.UTF8.GetString(reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan)}"); } } }
37.403361
192
0.568636
[ "MIT" ]
GrangerAts/graphql-dotnet
src/GraphQL.SystemTextJson/ObjectDictionaryConverter.cs
4,451
C#
using System; using System.Windows; using System.Windows.Controls.Primitives; namespace SimpleRemote.Controls.Dragablz { public delegate void DragablzDragStartedEventHandler(object sender, DragablzDragStartedEventArgs e); public class DragablzDragStartedEventArgs : DragablzItemEventArgs { private readonly DragStartedEventArgs _dragStartedEventArgs; public DragablzDragStartedEventArgs(DragablzItem dragablzItem, DragStartedEventArgs dragStartedEventArgs) : base(dragablzItem) { if (dragStartedEventArgs == null) throw new ArgumentNullException("dragStartedEventArgs"); _dragStartedEventArgs = dragStartedEventArgs; } public DragablzDragStartedEventArgs(RoutedEvent routedEvent, DragablzItem dragablzItem, DragStartedEventArgs dragStartedEventArgs) : base(routedEvent, dragablzItem) { _dragStartedEventArgs = dragStartedEventArgs; } public DragablzDragStartedEventArgs(RoutedEvent routedEvent, object source, DragablzItem dragablzItem, DragStartedEventArgs dragStartedEventArgs) : base(routedEvent, source, dragablzItem) { _dragStartedEventArgs = dragStartedEventArgs; } public DragStartedEventArgs DragStartedEventArgs { get { return _dragStartedEventArgs; } } } }
36.763158
153
0.721546
[ "Apache-2.0" ]
GeekCatPYG/SimpleRemote
SimoleRemote/Controls/Dragablz/DragablzDragStartedEventArgs.cs
1,397
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stopwatch.ViewModel { using System.Windows.Data; class BooleanNotConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if ((value is bool) && ((bool)value) == false) return true; else return false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
29.740741
83
0.575342
[ "MIT" ]
JianGuoWan/third-edition
WPF/Chapter_16/Stopwatch/Stopwatch/ViewModel/BooleanNotConverter.cs
805
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using static System.Linq.Enumerable; using Randomizer.SMZ3.Regions.Zelda; using Randomizer.SMZ3.Text; using static Randomizer.SMZ3.ItemType; using static Randomizer.SMZ3.Reward; using static Randomizer.SMZ3.FileData.DropPrize; using Randomizer.SMZ3.Regions; namespace Randomizer.SMZ3 { static class KeycardPlaque { public const ushort Level1 = 0xe0; public const ushort Level2 = 0xe1; public const ushort Boss = 0xe2; public const ushort None = 0x00; } }
24.375
48
0.748718
[ "MIT" ]
MattEqualsCoder/SMZ3Randomizer
src/Randomizer.SMZ3/FileData/KeycardPlaque.cs
587
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Blog.Entities.Concrete; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage; namespace Blog.Data.Concrete.EntityFramework.Mappings { public class ArticleMap : IEntityTypeConfiguration<Article> { public void Configure(EntityTypeBuilder<Article> builder) { builder.HasKey(a => a.Id); builder.Property(a => a.Id).ValueGeneratedOnAdd();//Identity alanımız. builder.Property(a => a.Title).HasMaxLength(100); builder.Property(a => a.Title).IsRequired(true); builder.Property(a => a.Content).IsRequired(true); builder.Property(a => a.Content).HasColumnType("NVARCHAR(MAX)"); builder.Property(a => a.Date).IsRequired(true); builder.Property(a => a.SeoAuthor).IsRequired(true); builder.Property(a => a.SeoAuthor).HasMaxLength(50); builder.Property(a => a.SeoDescription).HasMaxLength(150); builder.Property(a => a.SeoDescription).IsRequired(true); builder.Property(a => a.SeoTags).IsRequired(true); builder.Property(a => a.SeoTags).HasMaxLength(70); builder.Property(a => a.ViewsCount).IsRequired(true); builder.Property(a => a.CommentCount).IsRequired(true); builder.Property(a => a.Thumbnail).IsRequired(true); builder.Property(a => a.Thumbnail).HasMaxLength(250); builder.Property(a => a.CreatedByName).IsRequired(true); builder.Property(a => a.CreatedByName).HasMaxLength(50); builder.Property(a => a.ModifiedByName).IsRequired(true); builder.Property(a => a.ModifiedByName).HasMaxLength(50); builder.Property(a=>a.CreatedDate).IsRequired(true); builder.Property(a=>a.ModifiedDate).IsRequired(true); builder.Property(a => a.IsActive).IsRequired(true); builder.Property(a => a.IsDeleted).IsRequired(true); builder.Property(a => a.Note).HasMaxLength(500); builder.HasOne<Category>(a => a.Category).WithMany(c=>c.Articles).HasForeignKey(a=>a.CategoryId); builder.HasOne<User>(a => a.User).WithMany(u => u.Article).HasForeignKey(a => a.UserId); builder.ToTable("Articles"); //builder.HasData( // new Article // { // Id=1, // CategoryId = 1, // Title = "C# 9.0 ve .NET 5 Yenilikleri", // Content = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", // Thumbnail = "Default.jpg", // SeoDescription = "C# 9.0 ve .NET 5 Yenilikleri", // SeoTags = "C#, C# 9, .NET5, .NET FRAMEWORK, .NET Core", // SeoAuthor = "Tuncay Cem Uzun", // Date = DateTime.Now, // UserId = 1, // IsActive = true, // IsDeleted = false, // CreatedByName = "InitialCreate", // CreatedDate = DateTime.Now, // ModifiedByName = "InitialCreate", // ModifiedDate = DateTime.Now, // Note = "C# 9.0 ve .NET 5 Yenilikleri", // ViewsCount = 100, // CommentCount = 1 // }, // new Article // { // Id = 2, // CategoryId = 2, // Title = "C++ 11 ve 19 Yenilikleri", // Content = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", // Thumbnail = "Default.jpg", // SeoDescription = "C++ 11 ve 19 Yenilikleri", // SeoTags = "C++ 11 ve 19 Yenilikleri", // SeoAuthor = "Tuncay Cem Uzun", // Date = DateTime.Now, // UserId = 1, // IsActive = true, // IsDeleted = false, // CreatedByName = "InitialCreate", // CreatedDate = DateTime.Now, // ModifiedByName = "InitialCreate", // ModifiedDate = DateTime.Now, // Note = "C++ 11 ve 19 Yenilikleri", // ViewsCount = 295, // CommentCount = 1 // }, // new Article // { // Id = 3, // CategoryId = 3, // Title = "Javascript ES2019 ve ES2020 Yenilikleri", // Content = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", // Thumbnail = "Default.jpg", // SeoDescription = "Javascript ES2019 ve ES2020 Yenilikleri", // SeoTags = "Javascript ES2019 ve ES2020 Yenilikleri", // SeoAuthor = "Tuncay Cem Uzun", // Date = DateTime.Now, // UserId = 1, // IsActive = true, // IsDeleted = false, // CreatedByName = "InitialCreate", // CreatedDate = DateTime.Now, // ModifiedByName = "InitialCreate", // ModifiedDate = DateTime.Now, // Note = "Javascript ES2019 ve ES2020 Yenilikleri", // ViewsCount = 12, // CommentCount = 1 // }); } } }
62.112069
609
0.577654
[ "MIT" ]
tuncaycemuzun/Blog-Project
Blog.Data/Concrete/EntityFramework/Mappings/ArticleMap.cs
7,209
C#
using System; using System.Threading.Tasks; using Moralis.Platform; using Moralis.Platform.Abstractions; using Moralis.Platform.Objects; using Moralis.Platform.Queries; using Moralis.Platform.Services.ClientServices; using System.Collections.Generic; using System.Threading; using Moralis.Web3Api.Interfaces; using Moralis.Platform.Services.Infrastructure; using Moralis.SolanaApi.Interfaces; namespace Moralis { public class MoralisClient<TUser> where TUser : MoralisUser { string serverAuthToken = ""; public MoralisClient(ServerConnectionData connectionData, IWeb3Api web3Api = null, ISolanaApi solanaApi = null, IJsonSerializer jsonSerializer = null) { if (jsonSerializer == null) { throw new ArgumentException("jsonSerializer cannot be null."); } connectionData.Key = connectionData.Key ?? ""; moralisService = new MoralisService<TUser>(connectionData.ApplicationID, connectionData.ServerURI, connectionData.Key, jsonSerializer); moralisService.ServerConnectionData.Key = connectionData.Key; moralisService.ServerConnectionData.ServerURI = connectionData.ServerURI; moralisService.ServerConnectionData.ApplicationID = connectionData.ApplicationID; moralisService.ServerConnectionData.LocalStoragePath = connectionData.LocalStoragePath; // Make sure local folder for Unity apps is used if defined. MoralisCacheService<TUser>.BaseFilePath = connectionData.LocalStoragePath; // Make sure singleton instance is available. moralisService.Publicize(); this.Web3Api = web3Api; if (this.Web3Api is { }) { if (connectionData.ApiKey is { }) { this.Web3Api.Initialize(); } else { this.Web3Api.Initialize(connectionData.ServerURI); } } this.SolanaApi = solanaApi; if (this.SolanaApi is { }) { if (connectionData.ApiKey is { }) { this.SolanaApi.Initialize(); } else { this.SolanaApi.Initialize(connectionData.ServerURI); } } } public string EthAddress { get; } public IServiceHub<TUser> ServiceHub => moralisService.Services; MoralisService<TUser> moralisService; public void SetLocalDatastoreController() { throw new NotImplementedException(); } public string ApplicationId { get => moralisService.ServerConnectionData.ApplicationID; set { moralisService.ServerConnectionData.ApplicationID = value; } } public string Key { get => moralisService.ServerConnectionData.Key; set { moralisService.ServerConnectionData.Key = value; } } public string MasterKey { get => moralisService.ServerConnectionData.MasterKey; set { moralisService.ServerConnectionData.MasterKey = value; } } public string ServerUrl { get => moralisService.ServerConnectionData.ServerURI; set { moralisService.ServerConnectionData.ServerURI = value; } } public void SetServerAuthToken(string value) { serverAuthToken = value; } public string GetServerAuthToken() { return serverAuthToken; } public void SetServerAuthType(string value) { serverAuthToken = value; } public string GetServerAuthType() { return serverAuthToken; } public void SetLiveQueryServerURL(string value) { throw new NotImplementedException(); } public string GetLiveQueryServerURL() { throw new NotImplementedException(); } public void SetEncryptedUser(string value) { throw new NotImplementedException(); } public string GetEncryptedUser() { throw new NotImplementedException(); } public void SetSecret(string value) { throw new NotImplementedException(); } public string GetSecret() { throw new NotImplementedException(); } public void SetIdempotency(string value) { throw new NotImplementedException(); } public string GetIdempotency() { throw new NotImplementedException(); } public IFileService File => moralisService.FileService; public IInstallationService InstallationService => moralisService.InstallationService; public IQueryService QueryService => moralisService.QueryService; public ISessionService<TUser> Session => moralisService.SessionService; public IUserService<TUser> UserService => moralisService.UserService; public MoralisCloud<TUser> Cloud => moralisService.Cloud; public async Task<Guid?> GetInstallationIdAsync() => await InstallationService.GetAsync(); public MoralisQuery<T> Query<T>() where T : MoralisObject { return new MoralisQuery<T>(this.ServiceHub.QueryService, InstallationService, moralisService.ServerConnectionData, moralisService.JsonSerializer, this.ServiceHub.CurrentUserService.CurrentUser.sessionToken); } public T Create<T>(object[] parameters = null) where T : MoralisObject { return this.ServiceHub.Create<T>(parameters); } public MoralisUser GetCurrentUser() => this.ServiceHub.GetCurrentUser(); public void Dispose() { MoralisLiveQueryManager.DisposeService(); } /// <summary> /// Retrieve user object by sesion token. /// </summary> /// <param name="sessionToken"></param> /// <returns>Task<MoralisUser</returns> public Task<TUser> UserFromSession(string sessionToken) { return this.ServiceHub.BecomeAsync<TUser>(sessionToken); } /// <summary> /// Provid async user login. /// data: /// id: Address /// signature: Signature from wallet /// data: Message that was signed /// </summary> /// <param name="data">Authentication data</param> /// <returns>Task<TUser></returns> public Task<TUser> LogInAsync(IDictionary<string, object> data) { return this.LogInAsync(data, CancellationToken.None); } /// Provid async user login. /// data: /// id: Address /// signature: Signature from wallet /// data: Message that was signed /// </summary> /// <param name="data">Authentication data</param> /// <param name="cancellationToken"></param> /// <returns>Task<TUser></returns> public Task<TUser> LogInAsync(IDictionary<string, object> data, CancellationToken cancellationToken) { return this.ServiceHub.LogInWithAsync("moralisEth", data, cancellationToken); } /// <summary> /// Logs out the current user. /// </summary> /// <returns></returns> public Task LogOutAsync() { return this.ServiceHub.LogOutAsync<TUser>(); } /// <summary> /// Constructs a query that is the and of the given queries. /// </summary> /// <typeparam name="T">The type of MoralisObject being queried.</typeparam> /// <param name="serviceHub"></param> /// <param name="source">An initial query to 'and' with additional queries.</param> /// <param name="queries">The list of MoralisQueries to 'and' together.</param> /// <returns>A query that is the and of the given queries.</returns> public MoralisQuery<T> BuildAndQuery<T>(MoralisQuery<T> source, params MoralisQuery<T>[] queries) where T : MoralisObject { return ServiceHub.ConstructAndQuery<T, TUser>(source, queries); } /// <summary> /// Construct a query that is the and of two or more queries. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serviceHub"></param> /// <param name="queries">The list of MoralisQueries to 'and' together.</param> /// <returns>A MoralisQquery that is the 'and' of the passed in queries.</returns> public MoralisQuery<T> BuildAndQuery<T>(IEnumerable<MoralisQuery<T>> queries) where T : MoralisObject { return ServiceHub.ConstructAndQuery<T, TUser>(queries); } /// <summary> /// Constructs a query that is the or of the given queries. /// </summary> /// <typeparam name="T">The type of MoralisObject being queried.</typeparam> /// <param name="source">An initial query to 'or' with additional queries.</param> /// <param name="queries">The list of MoralisQueries to 'or' together.</param> /// <returns>A query that is the or of the given queries.</returns> public MoralisQuery<T> BuildOrQuery<T>(MoralisQuery<T> source, params MoralisQuery<T>[] queries) where T : MoralisObject { return ServiceHub.ConstructOrQuery<T, TUser>(source, queries); } /// <summary> /// Construct a query that is the 'or' of two or more queries. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serviceHub"></param> /// <param name="queries">The list of MoralisQueries to 'and' together.</param> /// <returns>A MoralisQquery that is the 'or' of the passed in queries.</returns> public MoralisQuery<T> BuildOrQuery<T>(IEnumerable<MoralisQuery<T>> queries) where T : MoralisObject { return ServiceHub.ConstructOrQuery<T, TUser>(queries); } /// <summary> /// Constructs a query that is the nor of the given queries. /// </summary> /// <typeparam name="T">The type of MoralisObject being queried.</typeparam> /// <param name="source">An initial query to 'or' with additional queries.</param> /// <param name="queries">The list of MoralisQueries to 'or' together.</param> /// <returns>A query that is the nor of the given queries.</returns> public MoralisQuery<T> BuildNorQuery<T>(MoralisQuery<T> source, params MoralisQuery<T>[] queries) where T : MoralisObject { return ServiceHub.ConstructNorQuery<T, TUser>(source, queries); } /// <summary> /// Construct a query that is the 'nor' of two or more queries. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serviceHub"></param> /// <param name="queries">The list of MoralisQueries to 'and' together.</param> /// <returns>A MoralisQquery that is the 'nor' of the passed in queries.</returns> public MoralisQuery<T> BuildNorQuery<T>(IEnumerable<MoralisQuery<T>> queries) where T : MoralisObject { return ServiceHub.ConstructNorQuery<T, TUser>(queries); } /// <summary> /// Deletes target object from the Moralis database. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> /// <returns></returns> public Task DeleteAsync<T>(T target) where T : MoralisObject { return target.DeleteAsync(); } /// <summary> /// Provide an object hook for Web3Api incase developer supplies a /// web3api client at initialize /// </summary> public IWeb3Api Web3Api { get; private set; } /// <summary> /// Provide an object hook for SolanaApi /// </summary> public ISolanaApi SolanaApi { get; private set; } /// <summary> /// Included so that this can be set prior to initialization for systems /// (Unity, Xamarin, etc.) that may not have Assembly Attributes available. /// </summary> public static HostManifestData ManifestData { get => Moralis.Platform.Services.ServiceHub<TUser>.ManifestData; set { Moralis.Platform.Services.ServiceHub<TUser>.ManifestData = value; Moralis.Platform.Services.MutableServiceHub<TUser>.ManifestData = value; } } } }
35.385246
219
0.592927
[ "MIT" ]
CryptoProject0417/P2E-UnityGameExample
Assets/MoralisWeb3ApiSdk/Moralis/MoralisDotNet/MoralisDynamic.cs
12,953
C#
using System; using Loki.Core.Domain.Entities; using Xunit; namespace Loki.Core.Domain.Tests.Entities { public class ClienteTest { private readonly Cliente _cliente; public ClienteTest() { _cliente = new Cliente(); } [Fact] public void Id__AtribuiELeValor__DeveTerGetSet() { // Prepara e Testa const int id = 10; _cliente.Id = id; // Testa e Asserta Assert.True(_cliente.Id == id, "Id deve ter Get e Set"); } [Fact] public void Uuid__AtribuiELeValor__DeveTerGetSet() { // Prepara e Testa var uuid = Guid.NewGuid(); _cliente.Uuid = uuid; // Testa e Asserta Assert.True(_cliente.Uuid == uuid, "Uuid deve ter Get e Set"); } [Fact] public void Nome__AtribuiELeValor__DeveTerGetSet() { // Prepara e Testa const string nome = "Nome"; _cliente.Nome = nome; // Testa e Asserta Assert.True(_cliente.Nome == nome, "Nome deve ter Get e Set"); } [Fact] public void PessoaFisica__AtribuiELeValor__DeveTerGetSet() { // Prepara e Testa var pessoaFisica = new PessoaFisica { Cpf = "000.000.000-00", DataNascimento = new DateTime(2018, 02, 03) }; _cliente.PessoaFisica = pessoaFisica; // Testa e Asserta Assert.True(_cliente.PessoaFisica == pessoaFisica, "Pessoa Fisica deve ter Get e Set"); } [Fact] public void PessoaJuridica__AtribuiELeValor__DeveTerGetSet() { // Prepara e Testa var pessoaJuridica = new PessoaJuridica { Cnpj = "00.000.0000/0000-00", RazaoSocial = "Razão Social" }; _cliente.PessoaJuridica = pessoaJuridica; // Testa e Asserta Assert.True(_cliente.PessoaJuridica == pessoaJuridica, "Pessoa Juridica deve ter Get e Set"); } } }
27.481013
105
0.528789
[ "MIT" ]
Hugokk/Loki
Loki.Core/Loki.Core.Domain.Tests/Entities/ClienteTest.cs
2,174
C#
using System; using System.Threading; using System.Threading.Tasks; namespace Arc4u.Caching { /// <summary> /// The interface define the contract implemented by a cache. /// </summary> public interface ICache : IDisposable { /// <summary> /// Initialize the cache. This must be called once ervery time a cache is created. /// </summary> /// <param name="store">The store name for identify the cache used.</param> void Initialize(string store); /// <summary> /// Add or set a value in the cache. /// </summary> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <param name="value">The object to save.</param> /// <returns>Return an <see cref="object"/> defining a version for the data added in the cache.</returns> /// <exception cref="DataCacheException">Thrown when the cache encounters a problem.</exception> void Put<T>(string key, T value); /// <summary> /// Add or set a value in the cache. /// </summary> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <param name="value">The object to save.</param> /// <returns>Return an <see cref="object"/> defining a version for the data added in the cache.</returns> /// <exception cref="DataCacheException">Thrown when the cache encounters a problem.</exception> Task PutAsync<T>(string key, T value, CancellationToken cancellation = default(CancellationToken)); /// <summary> /// Add or set a value in the cache. /// </summary> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <param name="timeout">Define the period of validity for the data added to the cache. When the timeout is expired, the data is removed from the cache.</param> /// <param name="value">The object to save.</param> /// <param name="isSlided">A <see cref="bool"/> value indicating if the timeout period is reset again. If true, the data availability will be prolounge each time the data is accessed.</param> /// <returns>Return an <see cref="object"/> defining a version for the data added in the cache.</returns> /// <exception cref="DataCacheException">Thrown when the cache encounters a problem.</exception> void Put<T>(string key, TimeSpan timeout, T value, bool isSlided = false); /// <summary> /// Add or set a value in the cache. /// </summary> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <param name="timeout">Define the period of validity for the data added to the cache. When the timeout is expired, the data is removed from the cache.</param> /// <param name="value">The object to save.</param> /// <param name="isSlided">A <see cref="bool"/> value indicating if the timeout period is reset again. If true, the data availability will be prolounge each time the data is accessed.</param> /// <returns>Return an <see cref="object"/> defining a version for the data added in the cache.</returns> /// <exception cref="DataCacheException">Thrown when the cache encounters a problem.</exception> Task PutAsync<T>(string key, TimeSpan timeout, T value, bool isSlided = false, CancellationToken cancellation = default(CancellationToken)); /// <summary> /// retrieve an <see cref="object"/> from the cache and cast it to the type of <see cref="TValue"/>. /// </summary> /// <typeparam name="TValue">The type used to cast the <see cref="object"/> from the cache.</typeparam> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <returns>An object typed to <see cref="TValue"/>, or the default value defined for the type <see cref="TValue"/> if no value exist for the specified key.</returns> /// <exception cref="DataCacheException">Thrown when the cache encounters a problem.</exception> /// <exception cref="InvalidCastException">Thrown when the <see cref="object"/> cannot be casted to the type <see cref="TValue"/> or when a cache has a problem.</exception> TValue Get<TValue>(string key); /// <summary> /// retrieve an <see cref="object"/> from the cache and cast it to the type of <see cref="TValue"/>. /// </summary> /// <typeparam name="TValue">The type used to cast the <see cref="object"/> from the cache.</typeparam> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <returns>An object typed to <see cref="TValue"/>, or the default value defined for the type <see cref="TValue"/> if no value exist for the specified key.</returns> /// <exception cref="DataCacheException">Thrown when the cache encounters a problem.</exception> /// <exception cref="InvalidCastException">Thrown when the <see cref="object"/> cannot be casted to the type <see cref="TValue"/> or when a cache has a problem.</exception> Task<TValue> GetAsync<TValue>(string key, CancellationToken cancellation = default(CancellationToken)); /// <summary> /// Get a value from the cache, if a value exist for the specified key. Does not thrown an exception, if the cast to <see cref="TValue"/> is not possible. /// </summary> /// <typeparam name="TValue">The type expected from the cache.</typeparam> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <param name="value">An object typed to <see cref="TValue"/>. The default value defined for the type <see cref="TValue"/> if no value exist for the specified key or if the cast is not possible.</param> /// <returns>An object typed to <see cref="TValue"/>, or the default value defined for the type <see cref="TValue"/> if no value exist for the specified key.</returns> bool TryGetValue<TValue>(string key, out TValue value); /// <summary> /// Get a value from the cache, if a value exist for the specified key. Does not thrown an exception, if the cast to <see cref="TValue"/> is not possible. /// </summary> /// <typeparam name="TValue">The type expected from the cache.</typeparam> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <returns>An object typed to <see cref="TValue"/>. The default value defined for the type <see cref="TValue"/> if no value exist for the specified key or if the cast is not possible.</returns> Task<TValue> TryGetValueAsync<TValue>(string key, CancellationToken cancellation = default(CancellationToken)); /// <summary> /// Rempve the data from the cache for the specified key. /// </summary> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <returns>True if the data was removed.</returns> bool Remove(string key); /// <summary> /// Rempve the data from the cache for the specified key. /// </summary> /// <param name="key">The key used to identify the <see cref="object"/> in the cache.</param> /// <returns>True if the data was removed.</returns> Task<bool> RemoveAsync(string key, CancellationToken cancellation = default(CancellationToken)); /// <summary> /// The name of the cache, usefull to identify the log used. /// </summary> /// <returns>The name of the cache.</returns> String ToString(); } }
66.008475
212
0.645783
[ "Apache-2.0" ]
GFlisch/Arc4u
src/Arc4u.Standard.Caching/ICache.cs
7,791
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bridge.Contract { public interface IJsDoc { List<string> Namespaces { get; set; } List<string> Callbacks { get; set; } void Init(); } }
14.8
33
0.535135
[ "Apache-2.0" ]
corefan/Bridge
Compiler/Contract/IJsDoc.cs
372
C#
using Microsoft.AspNet.Identity; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Google; using Owin; namespace BarcodeScanner { public partial class Startup { // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301883 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user // and also store information about a user logging in with a third party login provider. // This is required if your application allows users to login app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); } } }
36.577778
122
0.610571
[ "MIT" ]
alexdotwells/barcode-scanner
WebForms/BarcodeScanner/BarcodeScanner/App_Code/Startup.Auth.cs
1,648
C#
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved. // This is licensed software from AccelByte Inc, for limitations // and restrictions contact your company contract manager. // This code is generated by tool. DO NOT EDIT. using AccelByte.Sdk.Api.Eventlog.Model; using AccelByte.Sdk.Api.Eventlog.Operation; using AccelByte.Sdk.Core; namespace AccelByte.Sdk.Api.Eventlog.Wrapper { public class EventDescriptions { private readonly AccelByteSDK _sdk; public EventDescriptions(AccelByteSDK sdk) { _sdk = sdk; } #region Operation Builders [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public AgentTypeDescriptionHandler.AgentTypeDescriptionHandlerBuilder AgentTypeDescriptionHandlerOp { get { return Operation.AgentTypeDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public SpecificAgentTypeDescriptionHandler.SpecificAgentTypeDescriptionHandlerBuilder SpecificAgentTypeDescriptionHandlerOp { get { return Operation.SpecificAgentTypeDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public EventIDDescriptionHandler.EventIDDescriptionHandlerBuilder EventIDDescriptionHandlerOp { get { return Operation.EventIDDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public SpecificEventIDDescriptionHandler.SpecificEventIDDescriptionHandlerBuilder SpecificEventIDDescriptionHandlerOp { get { return Operation.SpecificEventIDDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public EventLevelDescriptionHandler.EventLevelDescriptionHandlerBuilder EventLevelDescriptionHandlerOp { get { return Operation.EventLevelDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public SpecificEventLevelDescriptionHandler.SpecificEventLevelDescriptionHandlerBuilder SpecificEventLevelDescriptionHandlerOp { get { return Operation.SpecificEventLevelDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public EventTypeDescriptionHandler.EventTypeDescriptionHandlerBuilder EventTypeDescriptionHandlerOp { get { return Operation.EventTypeDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public SpecificEventTypeDescriptionHandler.SpecificEventTypeDescriptionHandlerBuilder SpecificEventTypeDescriptionHandlerOp { get { return Operation.SpecificEventTypeDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public UXNameDescriptionHandler.UXNameDescriptionHandlerBuilder UXNameDescriptionHandlerOp { get { return Operation.UXNameDescriptionHandler.Builder.SetWrapperObject(this); } } [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public SpecificUXDescriptionHandler.SpecificUXDescriptionHandlerBuilder SpecificUXDescriptionHandlerOp { get { return Operation.SpecificUXDescriptionHandler.Builder.SetWrapperObject(this); } } #endregion #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleAgentType? AgentTypeDescriptionHandler(AgentTypeDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleAgentType? SpecificAgentTypeDescriptionHandler(SpecificAgentTypeDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleEventID? EventIDDescriptionHandler(EventIDDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleEventID? SpecificEventIDDescriptionHandler(SpecificEventIDDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleEventLevel? EventLevelDescriptionHandler(EventLevelDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleEventLevel? SpecificEventLevelDescriptionHandler(SpecificEventLevelDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleEventType? EventTypeDescriptionHandler(EventTypeDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleEventType? SpecificEventTypeDescriptionHandler(SpecificEventTypeDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleUX? UXNameDescriptionHandler(UXNameDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation #pragma warning disable ab_deprecated_operation [Obsolete(DiagnosticId ="ab_deprecated_operation_wrapper")] public Model.ModelsMultipleUX? SpecificUXDescriptionHandler(SpecificUXDescriptionHandler input) { var response = _sdk.RunRequest(input); return input.ParseResponse( response.Code, response.ContentType, response.Payload); } #pragma warning restore ab_deprecated_operation } }
47.691892
134
0.689675
[ "MIT" ]
AccelByte/accelbyte-csharp-sdk
AccelByte.Sdk/Api/Eventlog/Wrapper/EventDescriptions.cs
8,823
C#
using System; using System.Collections.Generic; namespace LokerIT.Code128.Nodes { public class CodeSetRun : SuccessorNode { private readonly IHighMode _highMode; private readonly HighModeChange _highModeChange; private readonly bool _needsChangeOfSet; public CodeSetRun(INode predecessor, CodeSetType codeSet, int length, bool isTerminal, HighModeChange highModeChange) : base(predecessor) { _highModeChange = highModeChange; _needsChangeOfSet = predecessor.FinalCodeSet != codeSet; FinalCodeSet = codeSet; Length = length; IsTerminal = isTerminal; _highMode = highModeChange.Instantiate(); } public override int Length { get; } public override int EmitCount => (_needsChangeOfSet ? 1 : 0) + Length + _highMode.GetOverhead(Length); public override bool IsTerminal { get; } public override bool IsHigh => Predecessor.IsHigh != (_highModeChange == HighModeChange.Toggle); public override CodeSetType FinalCodeSet { get; } public override void Emit(IMapping mapping, byte[] input, ICollection<Symbol> buffer) { if (_needsChangeOfSet) { var previousSet = mapping.GetCodeSet(Predecessor.FinalCodeSet); var mySet = mapping.GetCodeSet(FinalCodeSet); if (!mySet.SwitchToCode.HasValue) { throw new InvalidOperationException($"Cannot switch to {FinalCodeSet} from "); } buffer.Add(previousSet.GetSymbolForCode(mySet.SwitchToCode.Value)); } var set = mapping.GetCodeSet(FinalCodeSet); _highMode.Wrap(set, buffer, FlushHelper.CreateFlushEmits(set, input, buffer, Start, Length)); } } }
39.659574
110
0.631974
[ "MIT" ]
aloker/LokerIT.Code128
source/LokerIT.Code128/LokerIT.Code128/Nodes/CodeSetRun.cs
1,866
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SCDN相关接口 * Openapi For JCLOUD cdn * * OpenAPI spec version: v1 * Contact: pid-cdn@jd.com * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; using JDCloudSDK.Core.Annotation; namespace JDCloudSDK.Cdn.Apis { /// <summary> /// 查询WAF总开关 /// </summary> public class QueryWafWhiteRuleSwitchRequest : JdcloudRequest { ///<summary> /// 用户域名 ///Required:true ///</summary> [Required] public string Domain{ get; set; } } }
25.479167
76
0.686018
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Cdn/Apis/QueryWafWhiteRuleSwitchRequest.cs
1,249
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------ using System.Linq; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.OData.Common; using Microsoft.OpenApi.OData.Edm; using Microsoft.OpenApi.OData.Generator; namespace Microsoft.OpenApi.OData.Operation { /// <summary> /// Retrieve a $count get /// </summary> internal class DollarCountGetOperationHandler : OperationHandler { /// <inheritdoc/> public override OperationType OperationType => OperationType.Get; /// <summary> /// Gets/sets the segment before $count. /// this segment could be "entity set", "Collection property", "Composable function whose return is collection",etc. /// </summary> internal ODataSegment LastSecondSegment { get; set; } private const int SecondLastSegmentIndex = 2; /// <inheritdoc/> protected override void Initialize(ODataContext context, ODataPath path) { base.Initialize(context, path); // get the last second segment int count = path.Segments.Count; if(count >= SecondLastSegmentIndex) LastSecondSegment = path.Segments.ElementAt(count - SecondLastSegmentIndex); } /// <inheritdoc/> protected override void SetBasicInfo(OpenApiOperation operation) { // Summary operation.Summary = $"Get the number of the resource"; // OperationId if (Context.Settings.EnableOperationId) { operation.OperationId = $"Get.Count.{LastSecondSegment.Identifier}-{Path.GetPathHash(Context.Settings)}"; } base.SetBasicInfo(operation); } /// <inheritdoc/> protected override void SetResponses(OpenApiOperation operation) { operation.Responses = new OpenApiResponses { { Constants.StatusCode200, new OpenApiResponse { UnresolvedReference = true, Reference = new OpenApiReference() { Type = ReferenceType.Response, Id = Constants.DollarCountSchemaName } } } }; operation.AddErrorResponses(Context.Settings, false); base.SetResponses(operation); } } }
35.220779
124
0.553466
[ "MIT" ]
Microsoft/OpenAPI.NET.OData
src/Microsoft.OpenApi.OData.Reader/Operation/DollarCountGetOperationHandler.cs
2,714
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Reflection; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; using Microsoft.Build.Utilities; namespace Microsoft.Build.Shared { /// <summary> /// Interop methods. /// </summary> internal static class NativeMethodsShared { #region Constants internal const uint ERROR_INSUFFICIENT_BUFFER = 0x8007007A; internal const uint STARTUP_LOADER_SAFEMODE = 0x10; internal const uint S_OK = 0x0; internal const uint S_FALSE = 0x1; internal const uint ERROR_ACCESS_DENIED = 0x5; internal const uint ERROR_FILE_NOT_FOUND = 0x80070002; internal const uint FUSION_E_PRIVATE_ASM_DISALLOWED = 0x80131044; // Tried to find unsigned assembly in GAC internal const uint RUNTIME_INFO_DONT_SHOW_ERROR_DIALOG = 0x40; internal const uint FILE_TYPE_CHAR = 0x0002; internal const Int32 STD_OUTPUT_HANDLE = -11; internal const uint RPC_S_CALLPENDING = 0x80010115; internal const uint E_ABORT = (uint)0x80004004; internal const int FILE_ATTRIBUTE_READONLY = 0x00000001; internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010; internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400; /// <summary> /// Default buffer size to use when dealing with the Windows API. /// </summary> internal const int MAX_PATH = 260; private const string kernel32Dll = "kernel32.dll"; private const string mscoreeDLL = "mscoree.dll"; private const string WINDOWS_FILE_SYSTEM_REGISTRY_KEY = @"SYSTEM\CurrentControlSet\Control\FileSystem"; private const string WINDOWS_LONG_PATHS_ENABLED_VALUE_NAME = "LongPathsEnabled"; internal static DateTime MinFileDate { get; } = DateTime.FromFileTimeUtc(0); #if FEATURE_HANDLEREF internal static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero); #endif internal static IntPtr NullIntPtr = new IntPtr(0); // As defined in winnt.h: internal const ushort PROCESSOR_ARCHITECTURE_INTEL = 0; internal const ushort PROCESSOR_ARCHITECTURE_ARM = 5; internal const ushort PROCESSOR_ARCHITECTURE_IA64 = 6; internal const ushort PROCESSOR_ARCHITECTURE_AMD64 = 9; internal const ushort PROCESSOR_ARCHITECTURE_ARM64 = 12; internal const uint INFINITE = 0xFFFFFFFF; internal const uint WAIT_ABANDONED_0 = 0x00000080; internal const uint WAIT_OBJECT_0 = 0x00000000; internal const uint WAIT_TIMEOUT = 0x00000102; #if FEATURE_CHARSET_AUTO internal const CharSet AutoOrUnicode = CharSet.Auto; #else internal const CharSet AutoOrUnicode = CharSet.Unicode; #endif #endregion #region Enums private enum PROCESSINFOCLASS : int { ProcessBasicInformation = 0, ProcessQuotaLimits, ProcessIoCounters, ProcessVmCounters, ProcessTimes, ProcessBasePriority, ProcessRaisePriority, ProcessDebugPort, ProcessExceptionPort, ProcessAccessToken, ProcessLdtInformation, ProcessLdtSize, ProcessDefaultHardErrorMode, ProcessIoPortHandlers, // Note: this is kernel mode only ProcessPooledUsageAndLimits, ProcessWorkingSetWatch, ProcessUserModeIOPL, ProcessEnableAlignmentFaultFixup, ProcessPriorityClass, ProcessWx86Information, ProcessHandleCount, ProcessAffinityMask, ProcessPriorityBoost, MaxProcessInfoClass }; private enum eDesiredAccess : int { DELETE = 0x00010000, READ_CONTROL = 0x00020000, WRITE_DAC = 0x00040000, WRITE_OWNER = 0x00080000, SYNCHRONIZE = 0x00100000, STANDARD_RIGHTS_ALL = 0x001F0000, PROCESS_TERMINATE = 0x0001, PROCESS_CREATE_THREAD = 0x0002, PROCESS_SET_SESSIONID = 0x0004, PROCESS_VM_OPERATION = 0x0008, PROCESS_VM_READ = 0x0010, PROCESS_VM_WRITE = 0x0020, PROCESS_DUP_HANDLE = 0x0040, PROCESS_CREATE_PROCESS = 0x0080, PROCESS_SET_QUOTA = 0x0100, PROCESS_SET_INFORMATION = 0x0200, PROCESS_QUERY_INFORMATION = 0x0400, PROCESS_ALL_ACCESS = SYNCHRONIZE | 0xFFF } /// <summary> /// Flags for CoWaitForMultipleHandles /// </summary> [Flags] public enum COWAIT_FLAGS : int { /// <summary> /// Exit when a handle is signaled. /// </summary> COWAIT_NONE = 0, /// <summary> /// Exit when all handles are signaled AND a message is received. /// </summary> COWAIT_WAITALL = 0x00000001, /// <summary> /// Exit when an RPC call is serviced. /// </summary> COWAIT_ALERTABLE = 0x00000002 } /// <summary> /// Processor architecture values /// </summary> internal enum ProcessorArchitectures { // Intel 32 bit X86, // AMD64 64 bit X64, // Itanium 64 IA64, // ARM ARM, // ARM64 ARM64, // Who knows Unknown } #endregion #region Structs /// <summary> /// Structure that contain information about the system on which we are running /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_INFO { // This is a union of a DWORD and a struct containing 2 WORDs. internal ushort wProcessorArchitecture; internal ushort wReserved; internal uint dwPageSize; internal IntPtr lpMinimumApplicationAddress; internal IntPtr lpMaximumApplicationAddress; internal IntPtr dwActiveProcessorMask; internal uint dwNumberOfProcessors; internal uint dwProcessorType; internal uint dwAllocationGranularity; internal ushort wProcessorLevel; internal ushort wProcessorRevision; } /// <summary> /// Wrap the intptr returned by OpenProcess in a safe handle. /// </summary> internal class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { // Create a SafeHandle, informing the base class // that this SafeHandle instance "owns" the handle, // and therefore SafeHandle should call // our ReleaseHandle method when the SafeHandle // is no longer in use private SafeProcessHandle() : base(true) { } protected override bool ReleaseHandle() { return CloseHandle(handle); } } /// <summary> /// Contains information about the current state of both physical and virtual memory, including extended memory /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = AutoOrUnicode)] internal class MemoryStatus { /// <summary> /// Initializes a new instance of the <see cref="T:MemoryStatus"/> class. /// </summary> public MemoryStatus() { #if (CLR2COMPATIBILITY) _length = (uint)Marshal.SizeOf(typeof(NativeMethodsShared.MemoryStatus)); #else _length = (uint)Marshal.SizeOf<NativeMethodsShared.MemoryStatus>(); #endif } /// <summary> /// Size of the structure, in bytes. You must set this member before calling GlobalMemoryStatusEx. /// </summary> private uint _length; /// <summary> /// Number between 0 and 100 that specifies the approximate percentage of physical /// memory that is in use (0 indicates no memory use and 100 indicates full memory use). /// </summary> public uint MemoryLoad; /// <summary> /// Total size of physical memory, in bytes. /// </summary> public ulong TotalPhysical; /// <summary> /// Size of physical memory available, in bytes. /// </summary> public ulong AvailablePhysical; /// <summary> /// Size of the committed memory limit, in bytes. This is physical memory plus the /// size of the page file, minus a small overhead. /// </summary> public ulong TotalPageFile; /// <summary> /// Size of available memory to commit, in bytes. The limit is ullTotalPageFile. /// </summary> public ulong AvailablePageFile; /// <summary> /// Total size of the user mode portion of the virtual address space of the calling process, in bytes. /// </summary> public ulong TotalVirtual; /// <summary> /// Size of unreserved and uncommitted memory in the user mode portion of the virtual /// address space of the calling process, in bytes. /// </summary> public ulong AvailableVirtual; /// <summary> /// Size of unreserved and uncommitted memory in the extended portion of the virtual /// address space of the calling process, in bytes. /// </summary> public ulong AvailableExtendedVirtual; } [StructLayout(LayoutKind.Sequential)] private struct PROCESS_BASIC_INFORMATION { public uint ExitStatus; public IntPtr PebBaseAddress; public UIntPtr AffinityMask; public int BasePriority; public UIntPtr UniqueProcessId; public UIntPtr InheritedFromUniqueProcessId; public uint Size { get { unsafe { return (uint)sizeof(PROCESS_BASIC_INFORMATION); } } } }; /// <summary> /// Contains information about a file or directory; used by GetFileAttributesEx. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct WIN32_FILE_ATTRIBUTE_DATA { internal int fileAttributes; internal uint ftCreationTimeLow; internal uint ftCreationTimeHigh; internal uint ftLastAccessTimeLow; internal uint ftLastAccessTimeHigh; internal uint ftLastWriteTimeLow; internal uint ftLastWriteTimeHigh; internal uint fileSizeHigh; internal uint fileSizeLow; } /// <summary> /// Contains the security descriptor for an object and specifies whether /// the handle retrieved by specifying this structure is inheritable. /// </summary> [StructLayout(LayoutKind.Sequential)] internal class SecurityAttributes { public SecurityAttributes() { #if (CLR2COMPATIBILITY) _nLength = (uint)Marshal.SizeOf(typeof(NativeMethodsShared.SecurityAttributes)); #else _nLength = (uint)Marshal.SizeOf<NativeMethodsShared.SecurityAttributes>(); #endif } private uint _nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } private class SystemInformationData { /// <summary> /// Architecture as far as the current process is concerned. /// It's x86 in wow64 (native architecture is x64 in that case). /// Otherwise it's the same as the native architecture. /// </summary> public readonly ProcessorArchitectures ProcessorArchitectureType; /// <summary> /// Actual architecture of the system. /// </summary> public readonly ProcessorArchitectures ProcessorArchitectureTypeNative; /// <summary> /// Convert SYSTEM_INFO architecture values to the internal enum /// </summary> /// <param name="arch"></param> /// <returns></returns> private static ProcessorArchitectures ConvertSystemArchitecture(ushort arch) { switch (arch) { case PROCESSOR_ARCHITECTURE_INTEL: return ProcessorArchitectures.X86; case PROCESSOR_ARCHITECTURE_AMD64: return ProcessorArchitectures.X64; case PROCESSOR_ARCHITECTURE_ARM: return ProcessorArchitectures.ARM; case PROCESSOR_ARCHITECTURE_IA64: return ProcessorArchitectures.IA64; case PROCESSOR_ARCHITECTURE_ARM64: return ProcessorArchitectures.ARM64; default: return ProcessorArchitectures.Unknown; } } /// <summary> /// Read system info values /// </summary> public SystemInformationData() { ProcessorArchitectureType = ProcessorArchitectures.Unknown; ProcessorArchitectureTypeNative = ProcessorArchitectures.Unknown; if (IsWindows) { var systemInfo = new SYSTEM_INFO(); GetSystemInfo(ref systemInfo); ProcessorArchitectureType = ConvertSystemArchitecture(systemInfo.wProcessorArchitecture); GetNativeSystemInfo(ref systemInfo); ProcessorArchitectureTypeNative = ConvertSystemArchitecture(systemInfo.wProcessorArchitecture); } else { try { // On Unix run 'uname -m' to get the architecture. It's common for Linux and Mac using ( var proc = Process.Start( new ProcessStartInfo("uname") { Arguments = "-m", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true })) { string arch = null; if (proc != null) { // Since uname -m simply returns kernel property, it should be quick. // 1 second is the best guess for a safe timeout. proc.WaitForExit(1000); arch = proc.StandardOutput.ReadLine(); } if (!string.IsNullOrEmpty(arch)) { if (arch.StartsWith("x86_64", StringComparison.OrdinalIgnoreCase)) { ProcessorArchitectureType = ProcessorArchitectures.X64; } else if (arch.StartsWith("ia64", StringComparison.OrdinalIgnoreCase)) { ProcessorArchitectureType = ProcessorArchitectures.IA64; } else if (arch.StartsWith("arm", StringComparison.OrdinalIgnoreCase)) { ProcessorArchitectureType = ProcessorArchitectures.ARM; } else if (arch.StartsWith("i", StringComparison.OrdinalIgnoreCase) && arch.EndsWith("86", StringComparison.OrdinalIgnoreCase)) { ProcessorArchitectureType = ProcessorArchitectures.X86; } } } } catch { ProcessorArchitectureType = ProcessorArchitectures.Unknown; } ProcessorArchitectureTypeNative = ProcessorArchitectureType; } } } #endregion #region Member data internal static bool HasMaxPath => MaxPath == MAX_PATH; /// <summary> /// Gets the max path limit of the current OS. /// </summary> internal static int MaxPath { get { if (!IsMaxPathSet) { SetMaxPath(); } return _maxPath; } } /// <summary> /// Cached value for MaxPath. /// </summary> private static int _maxPath; private static bool IsMaxPathSet { get; set; } private static readonly object MaxPathLock = new object(); private static void SetMaxPath() { lock (MaxPathLock) { if (!IsMaxPathSet) { bool isMaxPathRestricted = Traits.Instance.EscapeHatches.DisableLongPaths || IsMaxPathLegacyWindows(); _maxPath = isMaxPathRestricted ? MAX_PATH : int.MaxValue; IsMaxPathSet = true; } } } internal static bool IsMaxPathLegacyWindows() { try { return IsWindows && !IsLongPathsEnabledRegistry(); } catch { return true; } } private static bool IsLongPathsEnabledRegistry() { using (RegistryKey fileSystemKey = Registry.LocalMachine.OpenSubKey(WINDOWS_FILE_SYSTEM_REGISTRY_KEY)) { object longPathsEnabledValue = fileSystemKey?.GetValue(WINDOWS_LONG_PATHS_ENABLED_VALUE_NAME, 0); return fileSystemKey != null && Convert.ToInt32(longPathsEnabledValue) == 1; } } /// <summary> /// Cached value for IsUnixLike (this method is called frequently during evaluation). /// </summary> private static readonly bool s_isUnixLike = IsLinux || IsOSX || IsBSD; /// <summary> /// Gets a flag indicating if we are running under a Unix-like system (Mac, Linux, etc.) /// </summary> internal static bool IsUnixLike { get { return s_isUnixLike; } } /// <summary> /// Gets a flag indicating if we are running under Linux /// </summary> internal static bool IsLinux { #if CLR2COMPATIBILITY get { return false; } #else get { return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); } #endif } /// <summary> /// Gets a flag indicating if we are running under flavor of BSD (NetBSD, OpenBSD, FreeBSD) /// </summary> internal static bool IsBSD { #if CLR2COMPATIBILITY get { return false; } #else get { return RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")) || RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")) || RuntimeInformation.IsOSPlatform(OSPlatform.Create("OPENBSD")); } #endif } private static readonly object IsMonoLock = new object(); private static bool? _isMono; /// <summary> /// Gets a flag indicating if we are running under MONO /// </summary> internal static bool IsMono { get { if (_isMono != null) return _isMono.Value; lock (IsMonoLock) { if (_isMono == null) { // There could be potentially expensive TypeResolve events, so cache IsMono. // Also, VS does not host Mono runtimes, so turn IsMono off when msbuild is running under VS _isMono = !BuildEnvironmentHelper.Instance.RunningInVisualStudio && Type.GetType("Mono.Runtime") != null; } } return _isMono.Value; } } #if !CLR2COMPATIBILITY private static bool? _isWindows; #endif /// <summary> /// Gets a flag indicating if we are running under some version of Windows /// </summary> internal static bool IsWindows { #if CLR2COMPATIBILITY get { return true; } #else get { if (_isWindows == null) { _isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } return _isWindows.Value; } #endif } #if !CLR2COMPATIBILITY private static bool? _isOSX; #endif /// <summary> /// Gets a flag indicating if we are running under Mac OSX /// </summary> internal static bool IsOSX { #if CLR2COMPATIBILITY get { return false; } #else get { if (_isOSX == null) { _isOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } return _isOSX.Value; } #endif } /// <summary> /// Gets a string for the current OS. This matches the OS env variable /// for Windows (Windows_NT). /// </summary> internal static string OSName { get { return IsWindows ? "Windows_NT" : "Unix"; } } /// <summary> /// OS name that can be used for the msbuildExtensionsPathSearchPaths element /// for a toolset /// </summary> internal static string GetOSNameForExtensionsPath() { return IsOSX ? "osx" : IsUnixLike ? "unix" : "windows"; } internal static bool OSUsesCaseSensitivePaths { get { return IsLinux; } } /// <summary> /// The base directory for all framework paths in Mono /// </summary> private static string s_frameworkBasePath; /// <summary> /// The directory of the current framework /// </summary> private static string s_frameworkCurrentPath; /// <summary> /// Gets the currently running framework path /// </summary> internal static string FrameworkCurrentPath { get { if (s_frameworkCurrentPath == null) { var baseTypeLocation = AssemblyUtilities.GetAssemblyLocation(typeof(string).GetTypeInfo().Assembly); s_frameworkCurrentPath = Path.GetDirectoryName(baseTypeLocation) ?? string.Empty; } return s_frameworkCurrentPath; } } /// <summary> /// Gets the base directory of all Mono frameworks /// </summary> internal static string FrameworkBasePath { get { if (s_frameworkBasePath == null) { var dir = FrameworkCurrentPath; if (dir != string.Empty) { dir = Path.GetDirectoryName(dir); } s_frameworkBasePath = dir ?? string.Empty; } return s_frameworkBasePath; } } /// <summary> /// System information, initialized when required. /// </summary> /// <remarks> /// Initially implemented as <see cref="Lazy{SystemInformationData}"/>, but /// that's .NET 4+, and this is used in MSBuildTaskHost. /// </remarks> private static SystemInformationData SystemInformation { get { if (!_systemInformationInitialized) { lock (SystemInformationLock) { if (!_systemInformationInitialized) { _systemInformation = new SystemInformationData(); _systemInformationInitialized = true; } } } return _systemInformation; } } private static SystemInformationData _systemInformation; private static bool _systemInformationInitialized; private static readonly object SystemInformationLock = new object(); /// <summary> /// Architecture getter /// </summary> internal static ProcessorArchitectures ProcessorArchitecture => SystemInformation.ProcessorArchitectureType; /// <summary> /// Native architecture getter /// </summary> internal static ProcessorArchitectures ProcessorArchitectureNative => SystemInformation.ProcessorArchitectureTypeNative; #endregion #region Set Error Mode (copied from BCL) private static readonly Version s_threadErrorModeMinOsVersion = new Version(6, 1, 0x1db0); internal static int SetErrorMode(int newMode) { #if FEATURE_OSVERSION if (Environment.OSVersion.Version < s_threadErrorModeMinOsVersion) { return SetErrorMode_VistaAndOlder(newMode); } #endif int num; SetErrorMode_Win7AndNewer(newMode, out num); return num; } [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", EntryPoint = "SetThreadErrorMode", SetLastError = true)] private static extern bool SetErrorMode_Win7AndNewer(int newMode, out int oldMode); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", EntryPoint = "SetErrorMode", ExactSpelling = true)] private static extern int SetErrorMode_VistaAndOlder(int newMode); #endregion #region Wrapper methods /// <summary> /// Really truly non pumping wait. /// Raw IntPtrs have to be used, because the marshaller does not support arrays of SafeHandle, only /// single SafeHandles. /// </summary> [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] public static extern Int32 WaitForMultipleObjects(uint handle, IntPtr[] handles, bool waitAll, uint milliseconds); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", SetLastError = true)] internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", SetLastError = true)] internal static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo); /// <summary> /// Get the last write time of the fullpath to a directory. If the pointed path is not a directory, or /// if the directory does not exist, then false is returned and fileModifiedTimeUtc is set DateTime.MinValue. /// </summary> /// <param name="fullPath">Full path to the file in the filesystem</param> /// <param name="fileModifiedTimeUtc">The UTC last write time for the directory</param> internal static bool GetLastWriteDirectoryUtcTime(string fullPath, out DateTime fileModifiedTimeUtc) { // This code was copied from the reference manager, if there is a bug fix in that code, see if the same fix should also be made // there if (IsWindows) { fileModifiedTimeUtc = DateTime.MinValue; WIN32_FILE_ATTRIBUTE_DATA data = new WIN32_FILE_ATTRIBUTE_DATA(); bool success = false; success = GetFileAttributesEx(fullPath, 0, ref data); if (success) { if ((data.fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { long dt = ((long)(data.ftLastWriteTimeHigh) << 32) | ((long)data.ftLastWriteTimeLow); fileModifiedTimeUtc = DateTime.FromFileTimeUtc(dt); } else { // Path does not point to a directory success = false; } } return success; } if (Directory.Exists(fullPath)) { fileModifiedTimeUtc = Directory.GetLastWriteTimeUtc(fullPath); return true; } else { fileModifiedTimeUtc = DateTime.MinValue; return false; } } /// <summary> /// Takes the path and returns the short path /// </summary> internal static string GetShortFilePath(string path) { if (!IsWindows) { return path; } if (path != null) { int length = GetShortPathName(path, null, 0); int errorCode = Marshal.GetLastWin32Error(); if (length > 0) { StringBuilder fullPathBuffer = new StringBuilder(length); length = GetShortPathName(path, fullPathBuffer, length); errorCode = Marshal.GetLastWin32Error(); if (length > 0) { string fullPath = fullPathBuffer.ToString(); path = fullPath; } } if (length == 0 && errorCode != 0) { ThrowExceptionForErrorCode(errorCode); } } return path; } /// <summary> /// Takes the path and returns a full path /// </summary> /// <param name="path"></param> /// <returns></returns> internal static string GetLongFilePath(string path) { if (IsUnixLike) { return path; } if (path != null) { int length = GetLongPathName(path, null, 0); int errorCode = Marshal.GetLastWin32Error(); if (length > 0) { StringBuilder fullPathBuffer = new StringBuilder(length); length = GetLongPathName(path, fullPathBuffer, length); errorCode = Marshal.GetLastWin32Error(); if (length > 0) { string fullPath = fullPathBuffer.ToString(); path = fullPath; } } if (length == 0 && errorCode != 0) { ThrowExceptionForErrorCode(errorCode); } } return path; } /// <summary> /// Retrieves the current global memory status. /// </summary> internal static MemoryStatus GetMemoryStatus() { if (NativeMethodsShared.IsWindows) { MemoryStatus status = new MemoryStatus(); bool returnValue = NativeMethodsShared.GlobalMemoryStatusEx(status); if (!returnValue) { return null; } return status; } return null; } /// <summary> /// Get the last write time of the fullpath to the file. /// </summary> /// <param name="fullPath">Full path to the file in the filesystem</param> /// <returns>The last write time of the file, or DateTime.MinValue if the file does not exist.</returns> /// <remarks> /// This method should be accurate for regular files and symlinks, but can report incorrect data /// if the file's content was modified by writing to it through a different link, unless /// MSBUILDALWAYSCHECKCONTENTTIMESTAMP=1. /// </remarks> internal static DateTime GetLastWriteFileUtcTime(string fullPath) { DateTime fileModifiedTime = DateTime.MinValue; if (IsWindows) { if (Traits.Instance.EscapeHatches.AlwaysUseContentTimestamp) { return GetContentLastWriteFileUtcTime(fullPath); } WIN32_FILE_ATTRIBUTE_DATA data = new WIN32_FILE_ATTRIBUTE_DATA(); bool success = false; success = NativeMethodsShared.GetFileAttributesEx(fullPath, 0, ref data); if (success && (data.fileAttributes & NativeMethodsShared.FILE_ATTRIBUTE_DIRECTORY) == 0) { long dt = ((long)(data.ftLastWriteTimeHigh) << 32) | ((long)data.ftLastWriteTimeLow); fileModifiedTime = DateTime.FromFileTimeUtc(dt); // If file is a symlink _and_ we're not instructed to do the wrong thing, get a more accurate timestamp. if ((data.fileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT && !Traits.Instance.EscapeHatches.UseSymlinkTimeInsteadOfTargetTime) { fileModifiedTime = GetContentLastWriteFileUtcTime(fullPath); } } return fileModifiedTime; } else { return File.Exists(fullPath) ? File.GetLastWriteTimeUtc(fullPath) : DateTime.MinValue; } } /// <summary> /// Get the last write time of the content pointed to by a file path. /// </summary> /// <param name="fullPath">Full path to the file in the filesystem</param> /// <returns>The last write time of the file, or DateTime.MinValue if the file does not exist.</returns> /// <remarks> /// This is the most accurate timestamp-extraction mechanism, but it is too slow to use all the time. /// See https://github.com/Microsoft/msbuild/issues/2052. /// </remarks> private static DateTime GetContentLastWriteFileUtcTime(string fullPath) { DateTime fileModifiedTime = DateTime.MinValue; using (SafeFileHandle handle = CreateFile(fullPath, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, /* No FILE_FLAG_OPEN_REPARSE_POINT; read through to content */ IntPtr.Zero)) { if (!handle.IsInvalid) { FILETIME ftCreationTime, ftLastAccessTime, ftLastWriteTime; if (!GetFileTime(handle, out ftCreationTime, out ftLastAccessTime, out ftLastWriteTime) != true) { long fileTime = ((long)(uint)ftLastWriteTime.dwHighDateTime) << 32 | (long)(uint)ftLastWriteTime.dwLowDateTime; fileModifiedTime = DateTime.FromFileTimeUtc(fileTime); } } } return fileModifiedTime; } /// <summary> /// Did the HRESULT succeed /// </summary> public static bool HResultSucceeded(int hr) { return (hr >= 0); } /// <summary> /// Did the HRESULT Fail /// </summary> public static bool HResultFailed(int hr) { return (hr < 0); } /// <summary> /// Given an error code, converts it to an HRESULT and throws the appropriate exception. /// </summary> /// <param name="errorCode"></param> public static void ThrowExceptionForErrorCode(int errorCode) { // See ndp\clr\src\bcl\system\io\__error.cs for this code as it appears in the CLR. // Something really bad went wrong with the call // translate the error into an exception // Convert the errorcode into an HRESULT (See MakeHRFromErrorCode in Win32Native.cs in // ndp\clr\src\bcl\microsoft\win32) errorCode = unchecked(((int)0x80070000) | errorCode); // Throw an exception as best we can Marshal.ThrowExceptionForHR(errorCode); } /// <summary> /// Kills the specified process by id and all of its children recursively. /// </summary> internal static void KillTree(int processIdToKill) { // Note that GetProcessById does *NOT* internally hold on to the process handle. // Only when you create the process using the Process object // does the Process object retain the original handle. Process thisProcess = null; try { thisProcess = Process.GetProcessById(processIdToKill); } catch (ArgumentException) { // The process has already died for some reason. So shrug and assume that any child processes // have all also either died or are in the process of doing so. return; } try { DateTime myStartTime = thisProcess.StartTime; // Grab the process handle. We want to keep this open for the duration of the function so that // it cannot be reused while we are running. SafeProcessHandle hProcess = OpenProcess(eDesiredAccess.PROCESS_QUERY_INFORMATION, false, processIdToKill); if (hProcess.IsInvalid) { return; } try { try { // Kill this process, so that no further children can be created. thisProcess.Kill(); } catch (Win32Exception e) { // Access denied is potentially expected -- it happens when the process that // we're attempting to kill is already dead. So just ignore in that case. if (e.NativeErrorCode != ERROR_ACCESS_DENIED) { throw; } } // Now enumerate our children. Children of this process are any process which has this process id as its parent // and which also started after this process did. List<KeyValuePair<int, SafeProcessHandle>> children = GetChildProcessIds(processIdToKill, myStartTime); try { foreach (KeyValuePair<int, SafeProcessHandle> childProcessInfo in children) { KillTree(childProcessInfo.Key); } } finally { foreach (KeyValuePair<int, SafeProcessHandle> childProcessInfo in children) { childProcessInfo.Value.Dispose(); } } } finally { // Release the handle. After this point no more children of this process exist and this process has also exited. hProcess.Dispose(); } } finally { thisProcess.Dispose(); } } /// <summary> /// Returns the parent process id for the specified process. /// Returns zero if it cannot be gotten for some reason. /// </summary> internal static int GetParentProcessId(int processId) { int ParentID = 0; #if !CLR2COMPATIBILITY if (IsUnixLike) { string line = null; try { // /proc/<processID>/stat returns a bunch of space separated fields. Get that string using (var r = FileUtilities.OpenRead("/proc/" + processId + "/stat")) { line = r.ReadLine(); } } catch // Ignore errors since the process may have terminated { } if (!string.IsNullOrWhiteSpace(line)) { // One of the fields is the process name. It may contain any characters, but since it's // in parenthesis, we can finds its end by looking for the last parenthesis. After that, // there comes a space, then the second fields separated by a space is the parent id. string[] statFields = line.Substring(line.LastIndexOf(')')).Split(MSBuildConstants.SpaceChar, 4); if (statFields.Length >= 3) { ParentID = Int32.Parse(statFields[2]); } } } else #endif { SafeProcessHandle hProcess = OpenProcess(eDesiredAccess.PROCESS_QUERY_INFORMATION, false, processId); if (!hProcess.IsInvalid) { try { // UNDONE: NtQueryInformationProcess will fail if we are not elevated and other process is. Advice is to change to use ToolHelp32 API's // For now just return zero and worst case we will not kill some children. PROCESS_BASIC_INFORMATION pbi = new PROCESS_BASIC_INFORMATION(); int pSize = 0; if (0 == NtQueryInformationProcess(hProcess, PROCESSINFOCLASS.ProcessBasicInformation, ref pbi, pbi.Size, ref pSize)) { ParentID = (int)pbi.InheritedFromUniqueProcessId; } } finally { hProcess.Dispose(); } } } return (ParentID); } /// <summary> /// Returns an array of all the immediate child processes by id. /// NOTE: The IntPtr in the tuple is the handle of the child process. CloseHandle MUST be called on this. /// </summary> internal static List<KeyValuePair<int, SafeProcessHandle>> GetChildProcessIds(int parentProcessId, DateTime parentStartTime) { List<KeyValuePair<int, SafeProcessHandle>> myChildren = new List<KeyValuePair<int, SafeProcessHandle>>(); foreach (Process possibleChildProcess in Process.GetProcesses()) { using (possibleChildProcess) { // Hold the child process handle open so that children cannot die and restart with a different parent after we've started looking at it. // This way, any handle we pass back is guaranteed to be one of our actual children. SafeProcessHandle childHandle = OpenProcess(eDesiredAccess.PROCESS_QUERY_INFORMATION, false, possibleChildProcess.Id); if (childHandle.IsInvalid) { continue; } bool keepHandle = false; try { if (possibleChildProcess.StartTime > parentStartTime) { int childParentProcessId = GetParentProcessId(possibleChildProcess.Id); if (childParentProcessId != 0) { if (parentProcessId == childParentProcessId) { // Add this one myChildren.Add(new KeyValuePair<int, SafeProcessHandle>(possibleChildProcess.Id, childHandle)); keepHandle = true; } } } } finally { if (!keepHandle) { childHandle.Dispose(); } } } } return myChildren; } /// <summary> /// Internal, optimized GetCurrentDirectory implementation that simply delegates to the native method /// </summary> /// <returns></returns> internal unsafe static string GetCurrentDirectory() { #if FEATURE_LEGACY_GETCURRENTDIRECTORY if (IsWindows) { int bufferSize = GetCurrentDirectoryWin32(0, null); char* buffer = stackalloc char[bufferSize]; int pathLength = GetCurrentDirectoryWin32(bufferSize, buffer); return new string(buffer, startIndex: 0, length: pathLength); } #endif return Directory.GetCurrentDirectory(); } private unsafe static int GetCurrentDirectoryWin32(int nBufferLength, char* lpBuffer) { int pathLength = GetCurrentDirectory(nBufferLength, lpBuffer); VerifyThrowWin32Result(pathLength); return pathLength; } internal unsafe static string GetFullPath(string path) { int bufferSize = GetFullPathWin32(path, 0, null, IntPtr.Zero); char* buffer = stackalloc char[bufferSize]; int fullPathLength = GetFullPathWin32(path, bufferSize, buffer, IntPtr.Zero); // Avoid creating new strings unnecessarily return AreStringsEqual(buffer, fullPathLength, path) ? path : new string(buffer, startIndex: 0, length: fullPathLength); } private unsafe static int GetFullPathWin32(string target, int bufferLength, char* buffer, IntPtr mustBeZero) { int pathLength = GetFullPathName(target, bufferLength, buffer, mustBeZero); VerifyThrowWin32Result(pathLength); return pathLength; } /// <summary> /// Compare an unsafe char buffer with a <see cref="System.String"/> to see if their contents are identical. /// </summary> /// <param name="buffer">The beginning of the char buffer.</param> /// <param name="len">The length of the buffer.</param> /// <param name="s">The string.</param> /// <returns>True only if the contents of <paramref name="s"/> and the first <paramref name="len"/> characters in <paramref name="buffer"/> are identical.</returns> private unsafe static bool AreStringsEqual(char* buffer, int len, string s) { if (len != s.Length) { return false; } foreach (char ch in s) { if (ch != *buffer++) { return false; } } return true; } internal static void VerifyThrowWin32Result(int result) { bool isError = result == 0; if (isError) { int code = Marshal.GetLastWin32Error(); ThrowExceptionForErrorCode(code); } } #endregion #region PInvoke /// <summary> /// Gets the current OEM code page which is used by console apps /// (as opposed to the Windows/ANSI code page) /// Basically for each ANSI code page (set in Regional settings) there's a corresponding OEM code page /// that needs to be used for instance when writing to batch files /// </summary> [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport(kernel32Dll)] internal static extern int GetOEMCP(); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport(kernel32Dll, SetLastError = true, CharSet = CharSet.Unicode)] private static extern uint SearchPath ( string path, string fileName, string extension, int numBufferChars, [Out] StringBuilder buffer, int[] filePart ); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", PreserveSig = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FreeLibrary([In] IntPtr module); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", PreserveSig = true, BestFitMapping = false, ThrowOnUnmappableChar = true, CharSet = CharSet.Ansi, SetLastError = true)] internal static extern IntPtr GetProcAddress(IntPtr module, string procName); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true)] internal static extern IntPtr LoadLibrary(string fileName); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport(mscoreeDLL, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern uint GetRequestedRuntimeInfo(String pExe, String pwszVersion, String pConfigurationFile, uint startupFlags, uint runtimeInfoFlags, [Out] StringBuilder pDirectory, int dwDirectory, out uint dwDirectoryLength, [Out] StringBuilder pVersion, int cchBuffer, out uint dwlength); /// <summary> /// Gets the fully qualified filename of the currently executing .exe /// </summary> [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport(kernel32Dll, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int GetModuleFileName( #if FEATURE_HANDLEREF HandleRef hModule, #else IntPtr hModule, #endif [Out] StringBuilder buffer, int length); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll")] internal static extern IntPtr GetStdHandle(int nStdHandle); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll")] internal static extern uint GetFileType(IntPtr hFile); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Justification = "Using unmanaged equivalent for performance reasons")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal unsafe static extern int GetCurrentDirectory(int nBufferLength, char* lpBuffer); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Justification = "Using unmanaged equivalent for performance reasons")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetCurrentDirectory")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetCurrentDirectoryWindows(string path); internal static bool SetCurrentDirectory(string path) { if (IsWindows) { return SetCurrentDirectoryWindows(path); } // Make sure this does not throw try { Directory.SetCurrentDirectory(path); } catch { } return true; } [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] internal static unsafe extern int GetFullPathName(string target, int bufferLength, char* buffer, IntPtr mustBeZero); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("KERNEL32.DLL")] private static extern SafeProcessHandle OpenProcess(eDesiredAccess dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("NTDLL.DLL")] private static extern int NtQueryInformationProcess(SafeProcessHandle hProcess, PROCESSINFOCLASS pic, ref PROCESS_BASIC_INFORMATION pbi, uint cb, ref int pSize); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [return: MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", CharSet = AutoOrUnicode, SetLastError = true)] private static extern bool GlobalMemoryStatusEx([In, Out] MemoryStatus lpBuffer); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", CharSet = CharSet.Unicode, BestFitMapping = false)] internal static extern int GetShortPathName(string path, [Out] StringBuilder fullpath, [In] int length); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", CharSet = CharSet.Unicode, BestFitMapping = false)] internal static extern int GetLongPathName([In] string path, [Out] StringBuilder fullpath, [In] int length); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", CharSet = AutoOrUnicode, SetLastError = true)] internal static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, SecurityAttributes lpPipeAttributes, int nSize); [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("kernel32.dll", CharSet = AutoOrUnicode, SetLastError = true)] internal static extern bool ReadFile(SafeFileHandle hFile, byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped); /// <summary> /// CoWaitForMultipleHandles allows us to wait in an STA apartment and still service RPC requests from other threads. /// VS needs this in order to allow the in-proc compilers to properly initialize, since they will make calls from the /// build thread which the main thread (blocked on BuildSubmission.Execute) must service. /// </summary> [SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Justification = "Class name is NativeMethodsShared for increased clarity")] [DllImport("ole32.dll")] public static extern int CoWaitForMultipleHandles(COWAIT_FLAGS dwFlags, int dwTimeout, int cHandles, [MarshalAs(UnmanagedType.LPArray)] IntPtr[] pHandles, out int pdwIndex); internal const uint GENERIC_READ = 0x80000000; internal const uint FILE_SHARE_READ = 0x1; internal const uint FILE_ATTRIBUTE_NORMAL = 0x80; internal const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000; internal const uint OPEN_EXISTING = 3; [DllImport("kernel32.dll", CharSet = AutoOrUnicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)] internal static extern SafeFileHandle CreateFile( string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile ); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool GetFileTime( SafeFileHandle hFile, out FILETIME lpCreationTime, out FILETIME lpLastAccessTime, out FILETIME lpLastWriteTime ); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr hObject); #endregion #region Extensions /// <summary> /// Waits while pumping APC messages. This is important if the waiting thread is an STA thread which is potentially /// servicing COM calls from other threads. /// </summary> [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle", Scope = "member", Target = "Microsoft.Build.Shared.NativeMethodsShared.#MsgWaitOne(System.Threading.WaitHandle,System.Int32)", Justification = "This is necessary and it has been used for a long time. No need to change it now.")] internal static bool MsgWaitOne(this WaitHandle handle) { return handle.MsgWaitOne(Timeout.Infinite); } /// <summary> /// Waits while pumping APC messages. This is important if the waiting thread is an STA thread which is potentially /// servicing COM calls from other threads. /// </summary> internal static bool MsgWaitOne(this WaitHandle handle, TimeSpan timeout) { return MsgWaitOne(handle, (int)timeout.TotalMilliseconds); } /// <summary> /// Waits while pumping APC messages. This is important if the waiting thread is an STA thread which is potentially /// servicing COM calls from other threads. /// </summary> [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle", Justification = "Necessary to avoid pumping")] internal static bool MsgWaitOne(this WaitHandle handle, int timeout) { // CoWaitForMultipleHandles allows us to wait in an STA apartment and still service RPC requests from other threads. // VS needs this in order to allow the in-proc compilers to properly initialize, since they will make calls from the // build thread which the main thread (blocked on BuildSubmission.Execute) must service. int waitIndex; #if FEATURE_HANDLE_SAFEWAITHANDLE IntPtr handlePtr = handle.SafeWaitHandle.DangerousGetHandle(); #else IntPtr handlePtr = handle.GetSafeWaitHandle().DangerousGetHandle(); #endif int returnValue = CoWaitForMultipleHandles(COWAIT_FLAGS.COWAIT_NONE, timeout, 1, new IntPtr[] { handlePtr }, out waitIndex); ErrorUtilities.VerifyThrow(returnValue == 0 || ((uint)returnValue == RPC_S_CALLPENDING && timeout != Timeout.Infinite), "Received {0} from CoWaitForMultipleHandles, but expected 0 (S_OK)", returnValue); return returnValue == 0; } #endregion #region helper methods internal static bool DirectoryExists(string fullPath) { return NativeMethodsShared.IsWindows ? DirectoryExistsWindows(fullPath) : Directory.Exists(fullPath); } internal static bool DirectoryExistsWindows(string fullPath) { NativeMethodsShared.WIN32_FILE_ATTRIBUTE_DATA data = new NativeMethodsShared.WIN32_FILE_ATTRIBUTE_DATA(); bool success = false; success = NativeMethodsShared.GetFileAttributesEx(fullPath, 0, ref data); return success && (data.fileAttributes & NativeMethodsShared.FILE_ATTRIBUTE_DIRECTORY) != 0; } internal static bool FileExists(string fullPath) { return NativeMethodsShared.IsWindows ? FileExistsWindows(fullPath) : File.Exists(fullPath); } internal static bool FileExistsWindows(string fullPath) { NativeMethodsShared.WIN32_FILE_ATTRIBUTE_DATA data = new NativeMethodsShared.WIN32_FILE_ATTRIBUTE_DATA(); bool success = false; success = NativeMethodsShared.GetFileAttributesEx(fullPath, 0, ref data); return success && (data.fileAttributes & NativeMethodsShared.FILE_ATTRIBUTE_DIRECTORY) == 0; } internal static bool FileOrDirectoryExists(string path) { return IsWindows ? FileOrDirectoryExistsWindows(path) : File.Exists(path) || Directory.Exists(path); } internal static bool FileOrDirectoryExistsWindows(string path) { WIN32_FILE_ATTRIBUTE_DATA data = new WIN32_FILE_ATTRIBUTE_DATA(); return GetFileAttributesEx(path, 0, ref data); } #endregion } }
40.463145
395
0.568813
[ "MIT" ]
AnandShastry/msbuild
src/Shared/NativeMethodsShared.cs
65,874
C#
using System; namespace Tailviewer.BusinessLogic.Analysis { /// <summary> /// The interface for a result of a <see cref="ILogAnalyser" />. /// </summary> public interface ILogAnalysisResult : ISerializableType , ICloneable { } }
18.769231
69
0.692623
[ "MIT" ]
fhmcn/Tailviewer
Tailviewer.Api/BusinessLogic/Analysis/ILogAnalysisResult.cs
246
C#
using System; using System.Linq; using System.Windows.Forms; namespace ExperimentMakerNew { public partial class MainForm : Form { public const string WEBSITE_ADDRESS = "http://130.211.98.43/dfpt"; public MainForm() { InitializeComponent(); comboBox_clients.DropDownStyle = ComboBoxStyle.DropDownList; textBox_tempFolder.Text = AppDomain.CurrentDomain.BaseDirectory; ToolTip tool = new ToolTip(); tool.SetToolTip(label_ClientId, "מופיע בקובץ הקונפיגורציה שנוצר לאחר הרצה של הסוכן"); } private void button1_Click(object sender, EventArgs e) { if (!ValidateForm()) return; this.Enabled = false; try { while (true) { try { string parmaeters = string.Format("DateOfAttack={0}&TimeGap={1}&ClientID={2}&TempFolder={3}&NumOfClustersToCreate={4}&ClusterData={5}", dateTimePicker.Value.ToString("MM-dd-yyyy HH:mm:ss").Replace(" ", "%20"), (int)numericUpDown_CheckMinutes.Value * 1000 * 60, comboBox_clients.Items[comboBox_clients.SelectedIndex], textBox_tempFolder.Text.Replace(" ", "%20").Replace("\\", "\\\\"), numericUpDown_numOfFiles.Value, RandomBase64Cluster()); string res = Common.SendPostRequest(WEBSITE_ADDRESS + "/AddExperiment.php", parmaeters); MessageBox.Show(res); break; } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } } catch (Exception exception) { MessageBox.Show("Error occured while calculating which files to use in attack: " + exception); } this.Enabled = true; } private string RandomBase64Cluster() { Random rnd = new Random(); byte[] b = new byte[4096]; rnd.NextBytes(b); return Convert.ToBase64String(b); } private bool ValidateForm() { if (string.IsNullOrEmpty(textBox_tempFolder.Text)) { MessageBox.Show("שימו ערך בתיקיה הזמנית!"); return false; } if (string.IsNullOrEmpty(comboBox_clients.Text)) { MessageBox.Show("נא למלא ClientId!"); return false; } return true; } private void MainForm_Load(object sender, EventArgs e) { string url = WEBSITE_ADDRESS + "/GetClientsAndTempFolder.php"; string response = Common.SendGetRequest(url); var rows = response.Split(new[] { "<br />" }, StringSplitOptions.RemoveEmptyEntries); var list = rows.Select(row => new { rowArr = row.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) }). Select(t => int.Parse(t.rowArr[0])).ToList(); list.Sort(); comboBox_clients.DataSource = list; } private void comboBox_clients_SelectedIndexChanged(object sender, EventArgs e) { string url = WEBSITE_ADDRESS + "/GetClientDetails.php?clientId=" + comboBox_clients.Items[comboBox_clients.SelectedIndex]; string response = Common.SendGetRequest(url); var rows = response.Split(new[] {";"}, StringSplitOptions.RemoveEmptyEntries).ToList(); label_client_description.Text = (rows.Count <= 1) ? "" : Convert.ToString(rows[1]); textBox_tempFolder.Text = (rows.Count == 0) ? "" : Convert.ToString(rows[0]); } } }
39.009346
160
0.503833
[ "MIT" ]
supermathbond/DeletedFilePersistenceExperiment
ExperimentMaker/MainForm.cs
4,243
C#
namespace SoundFingerprinting.Command { using SoundFingerprinting.Audio; /// <summary> /// Query services selector /// </summary> public interface IUsingQueryServices { /// <summary> /// Sets model service as well as audio service using in querying the source /// </summary> /// <param name="modelService">Model Service used as access interfaces to underlying fingerprints storage</param> /// <param name="audioService">Audio Service used in building the fingerprints from the source</param> /// <returns>Query command</returns> IQueryCommand UsingServices(IModelService modelService, IAudioService audioService); } }
39.111111
121
0.681818
[ "MIT" ]
FourPee/soundfingerprinting
src/SoundFingerprinting/Command/IUsingQueryServices.cs
704
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// This is the response object from the DescribeClusterTracks operation. /// </summary> public partial class DescribeClusterTracksResponse : AmazonWebServiceResponse { private List<MaintenanceTrack> _maintenanceTracks = new List<MaintenanceTrack>(); private string _marker; /// <summary> /// Gets and sets the property MaintenanceTracks. /// <para> /// A list of maintenance tracks output by the <code>DescribeClusterTracks</code> operation. /// /// </para> /// </summary> public List<MaintenanceTrack> MaintenanceTracks { get { return this._maintenanceTracks; } set { this._maintenanceTracks = value; } } // Check to see if MaintenanceTracks property is set internal bool IsSetMaintenanceTracks() { return this._maintenanceTracks != null && this._maintenanceTracks.Count > 0; } /// <summary> /// Gets and sets the property Marker. /// <para> /// The starting point to return a set of response tracklist records. You can retrieve /// the next set of response records by providing the returned marker value in the <code>Marker</code> /// parameter and retrying the request. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } } }
32.897436
110
0.641076
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Redshift/Generated/Model/DescribeClusterTracksResponse.cs
2,566
C#
using AspNetSkeleton.POTools.Extracting.Resources; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; namespace AspNetSkeleton.POTools.Extracting { public class ResourceTextExtractor : ILocalizableTextExtractor { public IEnumerable<LocalizableTextInfo> Extract(string content, CancellationToken cancellationToken = default(CancellationToken)) { ResXFileReader resourceReader; using (var reader = new StringReader(content)) resourceReader = new ResXFileReader(reader); return resourceReader.Select(kvp => new LocalizableTextInfo { Id = kvp.Value, Comment = kvp.Key }); } } }
33.714286
137
0.717514
[ "MIT" ]
adams85/AspNetSkeleton
source/Tools/POTools/Extracting/ResourceTextExtractor.cs
710
C#
using System; using System.Collections.Generic; namespace SamuraiAppCore.Domain { public class Battle { public int Id { get; set; } public string Name { get; set; } public DateTime StartDate { get; private set; } public DateTime EndDate { get; private set; } public List<Samurai> Samurais { get; set; } public List<SamuraiBattle> SamuraiBattles { get; set; } } }
26.5625
63
0.632941
[ "MIT" ]
Steven-ErHU/LearnProgramming
03-Pluralsight/EntityFrameworkCore2/src/Entity-Framework-Core-Getting-Started-Julie-Lerman-master/SamuraiAppCore/SamuraiAppCore.Domain/Battle.cs
427
C#
namespace AnimalCentre.Models.Services.Procedures { using AnimalCentre.Models.Contracts; using System; public class Chip : Procedure { private const int RemoveHappiness = 5; public override void DoService(IAnimal animal, int procedureTime) { base.CheckTime(procedureTime, animal); if (animal.IsChipped) { throw new ArgumentException($"{animal.Name} is already chipped"); } animal.Happiness -= RemoveHappiness; animal.IsChipped = true; base.procedureHistory.Add(animal); } } }
28.590909
81
0.599364
[ "MIT" ]
VeselinBPavlov/csharp-oop-basics
17. Exam - 18 November 2018/AnimalCentre/Models/Services/Chip.cs
631
C#
//------------------------------------------------------------------------------ // <copyright file="GPRECT.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing.Internal { using System.Diagnostics; using System; using System.Drawing; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] internal struct GPRECT { internal int X; internal int Y; internal int Width; internal int Height; internal GPRECT(int x, int y, int width, int height) { X = x; Y = y; Width = width; Height = height; } internal GPRECT(Rectangle rect) { X = rect.X; Y = rect.Y; Width = rect.Width; Height = rect.Height; } internal Rectangle ToRectangle() { return new Rectangle(X, Y, Width, Height); } } }
27.261905
80
0.444541
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/commonui/System/Drawing/Advanced/GPRECT.cs
1,145
C#
using System.Web.Http; using Newtonsoft.Json.Serialization; namespace GeekQuiz { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // use camel case for JSON data config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
27.923077
127
0.607438
[ "MIT" ]
kenwilcox/GeekQuiz
GeekQuiz/App_Start/WebApiConfig.cs
728
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ToDo.RazorPages.Data { public class TodoDbSeeder { public static void Seed(IServiceProvider serviceProvider) { using var context = new TodoDbContext(serviceProvider.GetRequiredService<DbContextOptions<TodoDbContext>>()); // Look for any todos. if (context.Todos.Any()) { //if we get here then data already seeded return; } context.Todos.AddRange( new Todo { Id = 1, TaskName = "Work on book chapter", IsComplete = false }, new Todo { Id = 2, TaskName = "Create video content", IsComplete = false } ); context.SaveChanges(); } } }
26.357143
121
0.504968
[ "MIT" ]
Devdiegoadias/CORE5_Iniciantes
Chapter 04/Chapter_04_RazorViewEngine_Examples/ToDo.RazorPages/Data/TodoDbSeeder.cs
1,109
C#
// Copyright (c) 2002-2020 "Neo4j," // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using Neo4j.Driver; namespace Neo4j.Driver.Internal.Metrics { /// <summary> /// The driver metrics /// </summary> internal interface IMetrics { /// <summary> /// The connection pool metrics. /// </summary> IDictionary<string, IConnectionPoolMetrics> ConnectionPoolMetrics { get; } } /// <summary> /// The connection pool metrics /// </summary> internal interface IConnectionPoolMetrics { /// <summary> /// The unique name of this metrics, used as an unique identifier among all <see cref="IConnectionPoolMetrics"/> instances. /// </summary> string Id { get; } /// <summary> /// The amount of the connections that are used by user's application /// </summary> int InUse { get; } /// <summary> /// The amount of connections that are buffered by the pool /// </summary> int Idle { get; } /// <summary> /// The amount of connections that are waiting to be created. /// </summary> int Creating { get; } /// <summary> /// The amount of connections that have been created by this driver /// </summary> long Created { get; } /// <summary> /// The amount of connections that are failed to be created. /// The cause of the error could be pool is full for example. /// </summary> long FailedToCreate { get; } /// <summary> /// The amount of connections that are waiting to be closed. /// </summary> int Closing { get; } /// <summary> /// The amount of connections that have been closed by this driver. /// </summary> long Closed { get; } /// <summary> /// The amount of requests trying to acquire a connection from the pool. /// </summary> int Acquiring { get; } /// <summary> /// The amount of requests that have acquired a connection out of the pool. /// </summary> long Acquired { get; } /// <summary> /// The amount of requests to acquire a connection from pool but failed due to acquisition timeout. /// </summary> long TimedOutToAcquire { get; } } }
31.061856
131
0.598075
[ "Apache-2.0" ]
2hdddg/neo4j-dotnet-driver
Neo4j.Driver/Neo4j.Driver/Internal/Metrics/IMetrics.cs
3,015
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace IEB3C.WebAPI.Results { public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
29.060606
96
0.693431
[ "Apache-2.0" ]
carydiy/BackToFront
IEB3C.WebAPI/Results/ChallengeResult.cs
961
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace OnlineTradingSystem { [DefaultProperty("Text")] [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")] public class WebCustomControl1 : WebControl { [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string Text { get { String s = (String)ViewState["Text"]; return ((s == null) ? String.Empty : s); } set { ViewState["Text"] = value; } } protected override void RenderContents(HtmlTextWriter output) { output.Write(Text); } } }
23.025
81
0.554832
[ "BSD-2-Clause" ]
orenber/Online-Trading-System
OnlineTradingSystem/OnlineTradingSystem/WebCustomControl1.cs
923
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #nullable enable using System; using System.Composition; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; namespace Roslyn.Diagnostics.Analyzers { /// <summary> /// This refactoring looks for numbered comments `// N` or `// N, N+1, ...` on non-empty lines within string literals /// and checks that the numbers are sequential. If they are not, the refactoring is offered. /// /// This pattern is commonly used by compiler tests. /// Comments that don't look like numbered comments are left alone. For instance, any comment that contains alpha characters. /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof(NumberCommentslRefactoring)), Shared] internal sealed class NumberCommentslRefactoring : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(context.Span); if (node is LiteralExpressionSyntax literal && literal.Kind() == SyntaxKind.StringLiteralExpression && !IsProperlyNumbered(literal.Token.ValueText)) { var action = CodeAction.Create( RoslynDiagnosticsAnalyzersResources.FixNumberedComments, c => FixCommentsAsync(context.Document, literal, c)); context.RegisterRefactoring(action); } } private async Task<Document> FixCommentsAsync(Document document, LiteralExpressionSyntax stringLiteral, CancellationToken c) { var newValueText = FixComments(stringLiteral.Token.ValueText, prefixOpt: null); var oldText = stringLiteral.Token.Text; var newText = FixComments(oldText, getPrefix(oldText)); var newStringLiteral = stringLiteral.Update(SyntaxFactory.Literal(text: newText, value: newValueText)).WithTriviaFrom(stringLiteral); var editor = await DocumentEditor.CreateAsync(document, c).ConfigureAwait(false); editor.ReplaceNode(stringLiteral, newStringLiteral); return editor.GetChangedDocument(); static string? getPrefix(string text) { if (text.StartsWith("@\"", StringComparison.OrdinalIgnoreCase)) { return "@\""; } if (text.StartsWith("\"", StringComparison.OrdinalIgnoreCase)) { return "\""; } return null; } } public static bool IsProperlyNumbered(string text) { int exptectedNumber = 1; int cursor = 0; do { var (eolOrEofIndex, newLine) = FindNewLineOrEndOfFile(cursor, text, hasPrefix: false); // find the last comment between cursor and newLineIndex (int commentStartIndex, _) = FindNumberComment(cursor, eolOrEofIndex, text); if (commentStartIndex > 0) { var separatedNumbers = text.Substring(commentStartIndex, eolOrEofIndex - commentStartIndex); var numbers = separatedNumbers.Split(',').Select(s => removeWhiteSpace(s)); foreach (var number in numbers) { if (string.IsNullOrEmpty(number)) { return false; } if (!int.TryParse(number, out var actualNumber) || exptectedNumber != actualNumber) { return false; } exptectedNumber++; } } cursor = eolOrEofIndex + newLine.Length; } while (cursor < text.Length); return true; static string removeWhiteSpace(string self) => new string(self.Where(c => !char.IsWhiteSpace(c)).ToArray()); } /// <summary> /// Returns the index of the end of line terminator or the end of file. /// If hasPrefix, we'll consider the terminating double-quotes (") to be the end of file. /// </summary> internal static (int Index, string NewLine) FindNewLineOrEndOfFile(int index, string comment, bool hasPrefix) { int length = GetStringLengthIgnoringQuote(comment, hasPrefix); for (int i = index; i < length; i++) { var current = comment[i]; if (current == '\n') { return (i, "\n"); } else if (current == '\r') { if (i + 1 < length && comment[i + 1] == '\n') { return (i, "\r\n"); } return (i, "\r"); } } return (length, ""); // EOF } internal static (int FoundIndex, int CommaCount) FindNumberComment(int cursor, int newLineIndex, string comment) { int commaCount = 0; for (int index = newLineIndex - 1; index > cursor + 2; index--) { var current = comment[index]; if (current == ',') { commaCount++; } if (current == '/' && comment[index - 1] == '/' && comment[index - 2] == ' ') { // found start of comment return (index + 1, commaCount); } if (!IsDigitOrComma(current)) { break; } } return (-1, 0); } internal static bool IsDigitOrComma(char c) { if (c >= '0' && c <= '9') { return true; } if (c == ' ' || c == ',') { return true; } return false; } static internal int GetStringLengthIgnoringQuote(string text, bool hasPrefix) { if (hasPrefix) { return text.Length - 1; } return text.Length; } private static string FixComments(string text, string? prefixOpt) { var builder = new StringBuilder(); int nextNumber = 1; int cursor = 0; if (prefixOpt != null) { builder.Append(prefixOpt); cursor += prefixOpt.Length; } int length = GetStringLengthIgnoringQuote(text, prefixOpt != null); do { var (eolOrEofIndex, newLine) = FindNewLineOrEndOfFile(cursor, text, prefixOpt != null); // find the last comment between cursor and newLineIndex (int commentStartIndex, int commaCount) = FindNumberComment(cursor, eolOrEofIndex, text); if (commentStartIndex > 0) { builder.Append(text, cursor, commentStartIndex - cursor); appendFixedNumberComment(builder, commaCount, ref nextNumber); builder.Append(newLine); } else { builder.Append(text, cursor, eolOrEofIndex + newLine.Length - cursor); } cursor = eolOrEofIndex + newLine.Length; } while (cursor < length); if (prefixOpt != null) { builder.Append("\""); } return builder.ToString(); static void appendFixedNumberComment(StringBuilder builder, int commaCount, ref int nextNumber) { for (int commaIndex = 0; commaIndex <= commaCount; commaIndex++) { builder.Append(' '); builder.Append(nextNumber.ToString(CultureInfo.InvariantCulture)); nextNumber++; if (commaIndex < commaCount) { builder.Append(','); } } } } } }
37.384937
161
0.51953
[ "Apache-2.0" ]
RussKie/roslyn-analyzers
src/Roslyn.Diagnostics.Analyzers/Core/NumberCommentslRefactoring.cs
8,937
C#
namespace ExcelX.AddIn.Command { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// 「問題の報告」コマンド /// </summary> public class ReportIssuesCommand : ICommand { /// <summary> /// 新規Issuesリンク /// </summary> private const string NewIssuesUrl = @"https://github.com/garafu/ExcelExtension/issues"; /// <summary> /// コマンドを実行します。 /// </summary> public void Execute() { Process.Start(ReportIssuesCommand.NewIssuesUrl); } } }
22.965517
95
0.576577
[ "MIT" ]
garafu/ExcelExtension
AddIn/Command/ReportIssuesCommand.cs
722
C#
using System; using Ncqrs.Eventing.Sourcing; using Ncqrs.Eventing.Storage; using Xunit; using FluentAssertions; namespace Ncqrs.Tests.Eventing.Storage { public class PropertyBagConverterTests { public class TestEvent { public string SomeString { get; set; } } [Fact] public void Restoration_of_an_event_from_a_property_bag_containing_nulls_should_not_fail() { try { var converter = new PropertyBagConverter { TypeResolver = new SimpleEventTypeResolver() }; var bag = new PropertyBag(typeof(TestEvent).AssemblyQualifiedName); bag.AddPropertyValue("SomeString", null); var obj = converter.Convert(bag); obj.Should().NotBeNull(); obj.Should().BeOfType<TestEvent>(); ((TestEvent) obj).SomeString.Should().BeNull(); } catch(Exception e) { Assert.True(false, e.ToString()); } } } }
28.45
107
0.534271
[ "Apache-2.0" ]
adamcogx/ncqrs
Framework/src/Ncqrs.Tests/Eventing/Storage/PropertyBagConverterTests.cs
1,138
C#
using EMS.EDXL.CT; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Xml.Serialization; namespace EMS.EDXL.EXT { /// <summary> /// Repersetns a Parameter Value Type /// </summary> public class ParameterValueType { private EDXLString paramValue; private string uom; /// <summary> /// XML Text of a Parameter value /// </summary> [XmlText] public string Value { get { return this.paramValue; } set { this.paramValue = value; } } /// <summary> /// Unit of measure of the Parameter value /// </summary> [XmlAttribute("uom")] public string UOM { get { return this.uom; } set { this.uom = value; } } /// <summary> /// Indicates whether or not the UOM was specified /// </summary> [XmlIgnore] public bool UOMSpecified { get { return !string.IsNullOrWhiteSpace(this.uom); } } } }
19.836735
58
0.610082
[ "Apache-2.0" ]
1stResponder/em-serializers
EDXL/EMS.EDXL.EXT/ParameterValueType.cs
974
C#
using System.ServiceModel; using System.Threading.Tasks; using MyJetWallet.Domain; using Service.ClientWallets.Grpc.Models; namespace Service.ClientWallets.Grpc { [ServiceContract] public interface IClientWalletService { [OperationContract] Task<ClientWalletList> GetWalletsByClient(JetClientIdentity clientId); [OperationContract] Task<CreateWalletResponse> CreateWalletAsync(CreateWalletRequest request); [OperationContract] Task<SearchWalletsResponse> SearchClientsAsync(SearchWalletsRequest request); [OperationContract] Task<SetBaseAssetResponse> SetBaseAssetAsync(SetBaseAssetRequest request); [OperationContract] Task SetEnableUseTestNetAsync(SetEnableUseTestNetRequest request); [OperationContract] Task<GetAllClientsResponse> GetAllClientsAsync(); [OperationContract] Task SetIsInternalByWalletAsync(SetIsInternalByWalletRequest request); [OperationContract] Task<GetWalletInfoByIdResponse> GetWalletInfoByIdAsync(GetWalletInfoByIdRequest request); [OperationContract] Task SetEarnProgramByWalletAsync(SetEarnProgramByWalletRequest request); } }
32.205128
97
0.737261
[ "MIT" ]
MyJetWallet/Service.ClientWallets
src/Service.ClientWallets.Grpc/IClientWalletService.cs
1,256
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("SEDC.Lamazon.DataAccess")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("SEDC.Lamazon.DataAccess")] [assembly: System.Reflection.AssemblyTitleAttribute("SEDC.Lamazon.DataAccess")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
42.458333
81
0.654563
[ "MIT" ]
chris-t-yan/ASP.NETCoreMVC-projects
Lamazon Store/SEDC.Lamazon/SEDC.Lamazon.DataAccess/obj/Debug/netcoreapp2.1/SEDC.Lamazon.DataAccess.AssemblyInfo.cs
1,019
C#
using Ship; using SubPhases; using System.Collections.Generic; using System.Linq; using UnityEngine; using Upgrade; namespace Ship { namespace SecondEdition.Z95AF4Headhunter { public class AirenCracken : Z95AF4Headhunter { public AirenCracken() : base() { PilotInfo = new PilotCardInfo( "Airen Cracken", 5, 36, isLimited: true, abilityType: typeof(Abilities.SecondEdition.AirenCrackenAbility), extraUpgradeIcon: UpgradeType.Talent, seImageNumber: 27 ); } } } } namespace Abilities.SecondEdition { public class AirenCrackenAbility : Abilities.FirstEdition.AirenCrackenAbiliity { protected override void PerformFreeAction() { Selection.ThisShip = TargetShip; TargetShip.AskPerformFreeAction( TargetShip.GetAvailableActionsAsRed(), delegate { Selection.ThisShip = HostShip; SelectShipSubPhase.FinishSelection(); }); } } }
25.851064
85
0.545679
[ "MIT" ]
GeneralVryth/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Pilots/Z95AF4Headhunter/AirenCracken.cs
1,217
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using ArcFaceProSDK4net.Models; namespace ArcFaceProSDK4net { /// <summary> /// sdk import /// </summary> public partial class ASFFunctions { /// <summary> /// dll path /// </summary> public const string Dll_PATH = "libarcsoft_face_engine.dll"; /// <summary> /// 获取版本信息 /// </summary> /// <returns>调用结果</returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern ASF_VERSION ASFGetVersion(); /// <summary> /// 获取激活文件信息。 /// </summary> /// <param name="activeFileInfo">激活文件信息</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetActiveFileInfo(out ASF_ActiveFileInfo activeFileInfo); /// <summary> /// 用于在线激活SDK。 /// </summary> /// <param name="AppId">官网获取的APPID</param> /// <param name="SDKKey">官网获取的SDKKEY</param> /// <param name="ActiveKey">官网获取的ACTIVEKEY</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFOnlineActivation(string AppId, string SDKKey, string ActiveKey); /// <summary> /// 采集当前设备信息(可离线)。 /// </summary> /// <param name="deviceInfo">采集的设备信息,用于上传到后台生成离线授权文件</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetActiveDeviceInfo(out IntPtr deviceInfo); /// <summary> /// 用于离线激活SDK。 /// </summary> /// <param name="filePath">许可文件路径(虹软开放平台开发者中心端获取的文件)</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFOfflineActivation(string filePath); /// <summary> /// 初始化引擎。 /// </summary> /// <param name="detectMode">VIDEO模式:处理连续帧的图像数据 IMAGE模式:处理单张的图像数据</param> /// <param name="detectFaceOrientPriority">人脸检测角度,推荐单一角度检测</param> /// <param name="detectFaceMaxNum">最大需要检测的人脸个数,取值范围[1,10]</param> /// <param name="combinedMask">需要启用的功能组合,可多选</param> /// <param name="hEngine">引擎句柄</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFInitEngine(ASF_DetectMode detectMode, ArcSoftFace_OrientPriority detectFaceOrientPriority, int detectFaceMaxNum, int combinedMask, out IntPtr hEngine); /// <summary> /// 检测人脸信息。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="width">图片宽度,为4的倍数</param> /// <param name="height">图片高度,YUYV/I420/NV21/NV12格式为2的倍数;BGR24/GRAY/DEPTH_U16格式无限制;</param> /// <param name="format">图像的颜色格式</param> /// <param name="imgData">图像数据</param> /// <param name="detectedFaces">检测到的人脸信息</param> /// <param name="detectModel">预留字段,当前版本使用默认参数即可</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFDetectFaces(IntPtr hEngine, int width, int height, int format, IntPtr imgData, out ASF_MultiFaceInfo detectedFaces, ASF_DetectModel detectModel = ASF_DetectModel.ASF_DETECT_MODEL_RGB); /// <summary> /// 检测人脸信息。 /// <para>注:该接口与 ASFDetectFaces 功能一致,但采用结构体的形式传入图像数据,对更高精度的图像兼容性更好。</para> /// </summary> /// <param name="hEngine"></param> /// <param name="imgData"></param> /// <param name="detectedFaces"></param> /// <param name="detectModel"></param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFDetectFacesEx(IntPtr hEngine, ASVLOFFSCREEN imgData, out ASF_MultiFaceInfo detectedFaces, ASF_DetectModel detectModel = ASF_DetectModel.ASF_DETECT_MODEL_RGB); /// <summary> /// 更新人脸信息。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="width">图片宽度,为4的倍数</param> /// <param name="height">图片高度,YUYV/I420/NV21/NV12格式为2的倍数;BGR24/GRAY/DEPTH_U16格式无限制;</param> /// <param name="format">图像的颜色格式</param> /// <param name="imgData">图像数据</param> /// <param name="detectedFaces">更新后的人脸信息(既为入参也为出参,该接口主要是更新faceDataInfoList值)</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFUpdateFaceData(IntPtr hEngine, int width, int height, int format, IntPtr imgData, out ASF_MultiFaceInfo detectedFaces); /// <summary> /// 更新人脸信息。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="imgData">图像数据</param> /// <param name="detectedFaces">更新后的人脸信息(既为入参也为出参,该接口主要是更新faceDataInfoList值)</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFUpdateFaceDataEx(IntPtr hEngine, ASVLOFFSCREEN imgData, out ASF_MultiFaceInfo detectedFaces); /// <summary> /// 支持单人脸图像质量检测。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="width">图片宽度</param> /// <param name="height">图片高度</param> /// <param name="format">颜色空间格式</param> /// <param name="imgData">图片数据</param> /// <param name="faceInfo">人脸位置信息</param> /// <param name="isMask">仅支持传入1、0、-1,戴口罩 1,否则认为未戴口罩</param> /// <param name="confidenceLevel">人脸图像质量检测结果</param> /// <param name="detectModel">预留字段,当前版本使用默认参数即可</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFImageQualityDetect(IntPtr hEngine, int width, int height, int format, IntPtr imgData, ASF_SingleFaceInfo faceInfo, int isMask, out float confidenceLevel, ASF_DetectModel detectModel = ASF_DetectModel.ASF_DETECT_MODEL_RGB); /// <summary> /// 支持单人脸图像质量检测。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="imgData">图像数据</param> /// <param name="faceInfo">人脸位置信息</param> /// <param name="isMask">仅支持传入1、0、-1,戴口罩 1,否则认为未戴口罩</param> /// <param name="confidenceLevel">人脸图像质量检测结果</param> /// <param name="detectModel">预留字段,当前版本使用默认参数即可</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFImageQualityDetectEx(IntPtr hEngine, ASVLOFFSCREEN imgData, ASF_SingleFaceInfo faceInfo, int isMask, out float confidenceLevel, ASF_DetectModel detectModel = ASF_DetectModel.ASF_DETECT_MODEL_RGB); /// <summary> /// 单人脸特征提取。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="width">图片宽度,为4的倍数</param> /// <param name="height">图片高度,YUYV/I420/NV21/NV12格式为2的倍数;BGR24/GRAY/DEPTH_U16格式无限制;</param> /// <param name="format">图像的颜色格式</param> /// <param name="imgData">图像数据</param> /// <param name="faceInfo">单人脸信息(人脸框、人脸角度、人脸数据)</param> /// <param name="registerOrNot">注册照:ASF_REGISTER 识别照:ASF_RECOGNITION</param> /// <param name="mask">带口罩 1,否则0</param> /// <param name="feature">提取到的人脸特征信息</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFFaceFeatureExtract(IntPtr hEngine, int width, int height, int format, IntPtr imgData, ASF_SingleFaceInfo faceInfo, ASF_RegisterOrNot registerOrNot, int mask, out ASF_FaceFeature feature); /// <summary> /// 单人特征提取。 /// <para>注:该接口与 ASFFaceFeatureExtract 功能一致,但采用结构体的形式传入图像数据,对更高精度的图像兼容性更好。</para> /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="imgData">图像数据</param> /// <param name="faceInfo">单人脸信息(人脸框、人脸角度)</param> /// <param name="registerOrNot">注册照:ASF_REGISTER 识别照:ASF_RECOGNITION</param> /// <param name="mask">带口罩 1,否则0</param> /// <param name="feature">提取到的人脸特征信息</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFFaceFeatureExtractEx(IntPtr hEngine, ASVLOFFSCREEN imgData, ASF_SingleFaceInfo faceInfo, ASF_RegisterOrNot registerOrNot, int mask, out ASF_FaceFeature feature); /// <summary> /// 人脸属性检测(年龄/性别/3D角度/口罩/额头区域),最多支持4张人脸信息检测,超过部分返回未知(活体仅支持单张人脸检测,超出返回未知),接口不支持IR图像检测。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="width">图片宽度,为4的倍数</param> /// <param name="height">图片高度,YUYV/I420/NV21/NV12格式为2的倍数;BGR24格式无限制;</param> /// <param name="format">支持YUYV/I420/NV21/NV12/BGR24</param> /// <param name="imgData">图像数据</param> /// <param name="detectedFaces">多人脸信息</param> /// <param name="combinedMask">1.检测的属性(ASF_AGE、ASF_GENDER、 ASF_FACE3DANGLE、ASF_LIVENESS、ASF_FACELANDMARK、ASF_MASKDETECT)支持多选;2.检测的属性须在引擎初始化接口的combinedMask参数中启用</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFProcess(IntPtr hEngine, int width, int height, int format, IntPtr imgData, ASF_MultiFaceInfo detectedFaces, int combinedMask); /// <summary> /// 人脸属性检测(年龄/性别/人脸3D角度/口罩/额头区域),最多支持4张人脸信息检测,超过部分返回未知(活体仅支持单张人脸检测,超出返回未知),接口不支持IR图像检测。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="imgData">图像数据</param> /// <param name="detectedFaces">多人脸信息</param> /// <param name="combinedMask">1.检测的属性(ASF_AGE、ASF_GENDER、 ASF_FACE3DANGLE、ASF_LIVENESS、ASF_FACELANDMARK、ASF_MASKDETECT)支持多选2.检测的属性须在引擎初始化接口的combinedMask参数中启用</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFProcessEx(IntPtr hEngine, ASVLOFFSCREEN imgData, ASF_MultiFaceInfo detectedFaces, int combinedMask); /// <summary> /// 获取年龄信息。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="ageInfo">检测到的年龄信息数组</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetAge(IntPtr hEngine, out ASF_AgeInfo ageInfo); /// <summary> /// 获取性别信息。 /// </summary> /// <param name="hEngine"></param> /// <param name="genderInfo"></param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetGender(IntPtr hEngine, out ASF_GenderInfo genderInfo); /// <summary> /// 获取3D角度信息。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="face3DAngle">检测到的3D角度信息数组</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetFace3DAngle(IntPtr hEngine, out ASF_Face3DAngle face3DAngle); /// <summary> /// 获取RGB活体信息。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="livenessInfo">检测到的活体信息</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetLivenessScore(IntPtr hEngine, out ASF_LivenessInfo livenessInfo); /// <summary> /// 设置遮挡算法检测的阈值。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="ShelterThreshhold">设置遮挡算法检测的阈值</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFSetFaceShelterParam(IntPtr hEngine, float ShelterThreshhold); /// <summary> /// 获取人脸是否戴口罩。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="maskInfo">检测到人脸是否戴口罩的信息</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetMask(IntPtr hEngine, out ASF_MaskInfo maskInfo); /// <summary> /// 获取额头区域位置。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="LandMarkInfo">人脸额头点数组,每张人脸额头区域通过四个点表示</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetFaceLandMark(IntPtr hEngine, out ASF_LandMarkInfo LandMarkInfo); /// <summary> /// 该接口仅支持单人脸 IR 活体检测,超出返回未知。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="width">图片宽度,为4的倍数</param> /// <param name="height">图片高度</param> /// <param name="format">图像颜色格式</param> /// <param name="imgData">图像数据</param> /// <param name="detectedFaces">多人脸信息</param> /// <param name="combinedMask">目前仅支持 ASF_IR_LIVENESS</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFProcess_IR(IntPtr hEngine, int width, int height, int format, IntPtr imgData, ASF_MultiFaceInfo detectedFaces, ASF_Mask combinedMask = ASF_Mask.ASF_IR_LIVENESS); /// <summary> /// 该接口仅支持单人脸 IR 活体检测,超出返回未知。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="imgData">图像数据</param> /// <param name="detectedFaces">多人脸信息</param> /// <param name="combinedMask">目前仅支持 ASF_IR_LIVENESS</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFProcessEx_IR(IntPtr hEngine, ASVLOFFSCREEN imgData, ASF_MultiFaceInfo detectedFaces, ASF_Mask combinedMask = ASF_Mask.ASF_IR_LIVENESS); /// <summary> /// 获取IR活体信息。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="livenessInfo">检测到的IR活体信息</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFGetLivenessScore_IR(IntPtr hEngine, out ASF_LivenessInfo livenessInfo); /// <summary> /// 人脸特征比对,输出比对相似度。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <param name="faceFeature1">人脸特征</param> /// <param name="faceFeature2">人脸特征</param> /// <param name="confidenceLevel">比对相似度</param> /// <param name="compareModel">选择人脸特征比对模型,默认为ASF_LIFE_PHOTO。1. ASF_LIFE_PHOTO:用于生活照之间的特征比对,推荐阈值0.80;2. ASF_ID_PHOTO:用于证件照或证件照和生活照之间的特征比对,推荐阈值0.82;</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFFaceFeatureCompare(IntPtr hEngine, ASF_FaceFeature faceFeature1, ASF_FaceFeature faceFeature2, out float confidenceLevel, ASF_CompareModel compareModel = ASF_CompareModel.ASF_LIFE_PHOTO); /// <summary> /// 设置RGB/IR活体阈值,若不设置内部默认RGB:0.5 IR:0.7。 /// </summary> /// <param name="hEngine"></param> /// <param name="threshold"></param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFSetLivenessParam(IntPtr hEngine, ASF_LivenessThreshold threshold); /// <summary> /// 销毁SDK引擎。 /// </summary> /// <param name="hEngine">引擎句柄</param> /// <returns></returns> [DllImport(Dll_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern MResult ASFUninitEngine(IntPtr hEngine); } }
51.338558
262
0.6398
[ "Apache-2.0" ]
JiangJingxuan/ArcFaceProSDK4net
ArcFaceProSDK4net/ASFFunctions.cs
19,273
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Information about the most recent job under a job schedule. /// </summary> public partial class RecentJob : IPropertyMetadata { #region Constructors internal RecentJob(Models.RecentJob protocolObject) { this.Id = protocolObject.Id; this.Url = protocolObject.Url; } #endregion Constructors #region RecentJob /// <summary> /// Gets the id of the job. /// </summary> public string Id { get; } /// <summary> /// Gets the URL of the job. /// </summary> public string Url { get; } #endregion // RecentJob #region IPropertyMetadata bool IModifiable.HasBeenModified { //This class is compile time readonly so it cannot have been modified get { return false; } } bool IReadOnly.IsReadOnly { get { return true; } set { // This class is compile time readonly already } } #endregion // IPropertyMetadata } }
24.926471
95
0.59056
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/batch/Microsoft.Azure.Batch/src/Generated/RecentJob.cs
1,695
C#
// Copyright 2016 Jon Skeet. All Rights Reserved. // Licensed under the Apache License Version 2.0. namespace Slides { /// <summary> /// This is immutable. Really. I promise that no maintenance /// programmer ever will add a method that calls the setter, /// because they will all read this comment. /// </summary> public sealed class LazilyImmutable { public int Value { get; private set; } public void FixBug() { // I didn't bother reading the comment. This should be fine. Value = 20; } public LazilyImmutable(int value) { Value = value; } } }
25
72
0.586667
[ "Apache-2.0" ]
23dproject/DemoCode
Immutability/Slides/026 NotQuiteImmutableReally.cs
677
C#
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. using UnrealBuildTool; using System.Collections.Generic; public class MotionMatchingTesterEditorTarget : TargetRules { public MotionMatchingTesterEditorTarget(TargetInfo Target) : base(Target) { Type = TargetType.Editor; DefaultBuildSettings = BuildSettingsVersion.V2; ExtraModuleNames.Add("MotionMatchingTester"); } }
26.066667
74
0.803069
[ "MIT" ]
Svietq/MotionMatching
Source/MotionMatchingTesterEditor.Target.cs
391
C#
using Newtonsoft.Json; namespace Pleer.Net.Model { public abstract class BaseTrack { [JsonProperty("artist")] public string Artist { get; set; } [JsonProperty("track")] public string TrackName { get; set; } // Yes, 'lenght' [JsonProperty("lenght")] public int Length { get; set; } [JsonProperty("bitrate")] public string Bitrate { get; set; } } }
21.75
45
0.567816
[ "MIT" ]
redmanmale/Pleer.Net
Pleer.Net/Model/BaseTrack.cs
437
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using WordCounter.Controllers; using WordCounter.Models; namespace WordCounter.Tests { [TestClass] public class WordsControllerTest { [TestMethod] public void Index_ReturnsCorrectView_True() { WordsController controller = new WordsController(); ActionResult indexView = controller.Index(); Assert.IsInstanceOfType(indexView, typeof(ViewResult)); } [TestMethod] public void Show_ReturnsCorrectView_True() { WordsController controller = new WordsController(); ActionResult showView = controller.Show(); Assert.IsInstanceOfType(showView, typeof(ViewResult)); } } }
25.3
65
0.73913
[ "MIT" ]
ohthatmarissa/WordCounter2.Solution
WordCounter.Tests/ControllerTests.cs/WordCounterTests.cs
759
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DkpWeb.Models.MyDebtViewModels { public class DebtLedger { [Required] public List<DebtLedgerEntry> Entries { get; set; } [Required] public Person Debtor { get; set; } [Required] public Person Creditor { get; set; } [Required] public int AmountCents { get; set; } [Required] public string AmountDollars { get; set; } } }
21.125
58
0.615385
[ "MIT" ]
AustinWise/DinnerKillPoints
src/DkpWeb/Models/MyDebtViewModels/DebtLedger.cs
509
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sms-2016-10-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.ServerMigrationService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ServerMigrationService.Model.Internal.MarshallTransformations { /// <summary> /// StartOnDemandAppReplication Request Marshaller /// </summary> public class StartOnDemandAppReplicationRequestMarshaller : IMarshaller<IRequest, StartOnDemandAppReplicationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((StartOnDemandAppReplicationRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(StartOnDemandAppReplicationRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ServerMigrationService"); string target = "AWSServerMigrationService_V2016_10_24.StartOnDemandAppReplication"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-10-24"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAppId()) { context.Writer.WritePropertyName("appId"); context.Writer.Write(publicRequest.AppId); } if(publicRequest.IsSetDescription()) { context.Writer.WritePropertyName("description"); context.Writer.Write(publicRequest.Description); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static StartOnDemandAppReplicationRequestMarshaller _instance = new StartOnDemandAppReplicationRequestMarshaller(); internal static StartOnDemandAppReplicationRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static StartOnDemandAppReplicationRequestMarshaller Instance { get { return _instance; } } } }
36.810811
169
0.637543
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/ServerMigrationService/Generated/Model/Internal/MarshallTransformations/StartOnDemandAppReplicationRequestMarshaller.cs
4,086
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using NuGet.Services.Entities; using NuGetGallery; namespace GitHubVulnerabilities2Db.Fakes { public class FakeFeatureFlagService : IFeatureFlagService { public bool AreDynamicODataCacheDurationsEnabled() { throw new NotImplementedException(); } public bool AreEmbeddedIconsEnabled(User user) { throw new NotImplementedException(); } public bool AreEmbeddedReadmesEnabled(User user) { throw new NotImplementedException(); } public bool IsDisplayPackagePageV2Enabled(User user) { throw new NotImplementedException(); } public bool ArePatternSetTfmHeuristicsEnabled() { throw new NotImplementedException(); } public bool IsABTestingEnabled(User user) { throw new NotImplementedException(); } public bool IsAdvancedSearchEnabled(User user) { throw new NotImplementedException(); } public bool IsAlternateStatisticsSourceEnabled() { throw new NotImplementedException(); } public bool IsAsyncAccountDeleteEnabled() { throw new NotImplementedException(); } public bool IsDeletePackageApiEnabled(User user) { throw new NotImplementedException(); } public bool IsDisplayBannerEnabled() { throw new NotImplementedException(); } public bool IsDisplayFuGetLinksEnabled() { throw new NotImplementedException(); } public bool IsDisplayVulnerabilitiesEnabled() { throw new NotImplementedException(); } public bool IsForceFlatContainerIconsEnabled() { throw new NotImplementedException(); } public bool IsGet2FADismissFeedbackEnabled() { throw new NotImplementedException(); } public bool IsGitHubUsageEnabled(User user) { throw new NotImplementedException(); } public bool IsGravatarProxyEnabled() { throw new NotImplementedException(); } public bool IsImageAllowlistEnabled() { throw new NotImplementedException(); } public bool IsLicenseMdRenderingEnabled(User user) { throw new NotImplementedException(); } public bool IsManageDeprecationApiEnabled(User user) { throw new NotImplementedException(); } public bool IsManageDeprecationEnabled(User user, PackageRegistration registration) { throw new NotImplementedException(); } public bool IsManageDeprecationEnabled(User user, IEnumerable<Package> allVersions) { throw new NotImplementedException(); } public bool IsManagePackagesVulnerabilitiesEnabled() { throw new NotImplementedException(); } public bool IsMarkdigMdRenderingEnabled() { throw new NotImplementedException(); } public bool IsODataDatabaseReadOnlyEnabled() { throw new NotImplementedException(); } public bool IsODataV1FindPackagesByIdCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1FindPackagesByIdNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1GetAllCountEnabled() { throw new NotImplementedException(); } public bool IsODataV1GetAllEnabled() { throw new NotImplementedException(); } public bool IsODataV1GetSpecificNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1SearchCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV1SearchNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2FindPackagesByIdCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2FindPackagesByIdNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2GetAllCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2GetAllNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2GetSpecificNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2SearchCountNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsODataV2SearchNonHijackedEnabled() { throw new NotImplementedException(); } public bool IsShowReportAbuseSafetyChangesEnabled() { throw new NotImplementedException(); } public bool IsPackageDependentsEnabled(User user) { throw new NotImplementedException(); } public bool IsPackageRenamesEnabled(User user) { throw new NotImplementedException(); } public bool IsPackagesAtomFeedEnabled() { throw new NotImplementedException(); } public bool IsPreviewHijackEnabled() { throw new NotImplementedException(); } public bool IsSearchSideBySideEnabled(User user) { throw new NotImplementedException(); } public bool IsSelfServiceAccountDeleteEnabled() { throw new NotImplementedException(); } public bool IsShowEnable2FADialogEnabled() { throw new NotImplementedException(); } public bool IsTyposquattingEnabled() { throw new NotImplementedException(); } public bool IsTyposquattingEnabled(User user) { throw new NotImplementedException(); } public bool ProxyGravatarEnSubdomain() { throw new NotImplementedException(); } public bool IsDisplayNuGetPackageExplorerLinkEnabled() { throw new NotImplementedException(); } public bool IsDisplayPackagePageV2PreviewEnabled(User user) { throw new NotImplementedException(); } public bool IsDisplayTargetFrameworkEnabled(User user) { throw new NotImplementedException(); } public bool IsComputeTargetFrameworkEnabled() { throw new NotImplementedException(); } } }
25.639576
111
0.59785
[ "Apache-2.0" ]
qaseleniumtesting01/NuGetGallery
src/GitHubVulnerabilities2Db/Fakes/FakeFeatureFlagService.cs
7,258
C#
namespace MauiPreview11Play; public partial class MainPage : ContentPage { int count = 0; public MainPage() { InitializeComponent(); } private void OnCounterClicked(object sender, EventArgs e) { count++; CounterLabel.Text = $"Current count: {count}"; SemanticScreenReader.Announce(CounterLabel.Text); } private void CloseWindow(object sender, EventArgs e) { var window = this.GetParentWindow(); if (window is not null) Application.Current.CloseWindow(window); } private void OpenWindow(object sender, EventArgs e) { Application.Current.OpenWindow(new Window(new MainPage())); } private void AddOverlay(object sender, EventArgs e) { var window = GetParentWindow(); var overlay = new TestWindowOverlay(window); window.AddOverlay(overlay); } } public class TestWindowOverlay : WindowOverlay { IWindowOverlayElement _testWindowDrawable; public TestWindowOverlay(Window window) : base(window) { _testWindowDrawable = new TestOverlayElement(this); AddWindowElement(_testWindowDrawable); EnableDrawableTouchHandling = true; Tapped += OnTapped; } async void OnTapped(object sender, WindowOverlayTappedEventArgs e) { if (!e.WindowOverlayElements.Contains(_testWindowDrawable)) return; var window = Application.Current.Windows.FirstOrDefault(w => w == Window); System.Diagnostics.Debug.WriteLine($"Tapped the test overlay button."); var result = await window.Page.DisplayActionSheet( "Greetings from Visual Studio Client Experiences!", "Goodbye!", null, "Do something", "Do something else", "Do something... with feeling."); System.Diagnostics.Debug.WriteLine(result); } class TestOverlayElement : IWindowOverlayElement { readonly WindowOverlay _overlay; Circle _circle = new Circle(0, 0, 0); int _size = 20; public TestOverlayElement(WindowOverlay overlay) { _overlay = overlay; Device.StartTimer(TimeSpan.FromMilliseconds(1), () => { _size += 10; _overlay.Invalidate(); return true; }); } public void Draw(ICanvas canvas, RectangleF dirtyRect) { canvas.FillColor = Color.FromRgba(255, 0, 0, 225); canvas.StrokeColor = Color.FromRgba(225, 0, 0, 225); canvas.FontColor = Colors.Orange; canvas.FontSize = 40f; var centerX = dirtyRect.Width / 2 - (_size/2); var centerY = dirtyRect.Height / 2 - (_size/2); _circle = new Circle(centerX, centerY, _size); canvas.FillCircle(centerX, centerY, _size); canvas.DrawString("🔥", centerX, centerY + 10, HorizontalAlignment.Center); } public bool Contains(Point point) => _circle.ContainsPoint(new Point(point.X / _overlay.Density, point.Y / _overlay.Density)); struct Circle { public float Radius; public PointF Center; public Circle(float x, float y, float r) { Radius = r; Center = new PointF(x, y); } public bool ContainsPoint(Point p) => p.X <= Center.X + Radius && p.X >= Center.X - Radius && p.Y <= Center.Y + Radius && p.Y >= Center.Y - Radius; } } }
24.875969
94
0.660642
[ "MIT" ]
rid00z/NETMAUIMultiWindow
MainPage.xaml.cs
3,214
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using BBBCSIO; using CS_LCD; /// +------------------------------------------------------------------------------------------------------------------------------+ /// ¦ TERMS OF USE: MIT License ¦ /// +------------------------------------------------------------------------------------------------------------------------------¦ /// ¦Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation ¦ /// ¦files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, ¦ /// ¦modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software¦ /// ¦is furnished to do so, subject to the following conditions: ¦ /// ¦ ¦ /// ¦The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.¦ /// ¦ ¦ /// ¦THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE ¦ /// ¦WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR ¦ /// ¦COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ¦ /// ¦ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ¦ /// +------------------------------------------------------------------------------------------------------------------------------+ namespace CS_LCD_BBBTest { /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// A class to specifically handle the transmission of data via I2C on a /// BBB F7 board. Because we inherit from CS_I2C_LCD_Generic we will receive /// data in byte arrays suitable for a generic HD44780 LCD over I2C all we /// really have to do here is send it via the built-in I2C driver. /// </summary> /// <history> /// 13 Jun 20 Cynic - Started /// </history> public class BBB_LCD : CS_LCD_I2C_Generic { // this is passed in during construction. It is expected that the // caller will close and dispose of it appropriately I2CPortFS i2cPeripheral = null; int i2cAddr = 0x27; /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Constructor /// </summary> /// <param name="i2cPeripheralIn">the i2c object we use</param> /// <param name="numRowsIn">the number of rows on the display</param> /// <param name="numColsIn">the number of cols on the display</param> /// <history> /// 13 Jun 20 Cynic - Started /// </history> public BBB_LCD(I2CPortFS i2cPeripheralIn, int i2cAddr, int numRowsIn, int numColsIn) : base(numRowsIn, numColsIn) { I2cPeripheral = i2cPeripheralIn; } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets/Sets the I2cPeripheral. Never permits a null value to be returned /// </summary> /// <history> /// 13 Jun 20 Cynic - Started /// </history> public I2CPortFS I2cPeripheral { get { if (i2cPeripheral == null) throw new Exception("The I2cPeripheral object is not set"); return i2cPeripheral; } set { i2cPeripheral = value; } } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Gets/Sets the i2cAddr /// </summary> /// <history> /// 13 Jun 20 Cynic - Started /// </history> public int I2CAddr { get { return i2cAddr; } set { i2cAddr = value; } } // # ################################################################## // # ##### Abstract functions - implemented to support the parent classes // # ################################################################## /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Send an array of binary data /// </summary> /// <param name="byteArray">an array of bytes</param> /// <history> /// 13 Jun 20 Cynic - Started /// </history> public override void SendByteArray(byte[] byteArray) { if (byteArray == null) return; I2cPeripheral.Write(I2CAddr, byteArray, byteArray.Length); } /// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= /// <summary> /// Send a single byte /// </summary> /// <param name="byteVal">a single byte of data</param> /// <history> /// 13 Jun 20 Cynic - Started /// </history> public override void SendByte(byte byteVal) { I2cPeripheral.Write(I2CAddr, new byte[] { byteVal }, 1); } } }
43.823529
132
0.425336
[ "MIT" ]
OfItselfSo/CS_LCD
CS_LCD_BBBTest/BBB_LCD.cs
5,987
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; namespace ArchShop.Backend { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ArchShop.Backend.EventSource", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ArchShop.Backend.EventSource v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
29.849057
120
0.607459
[ "MIT" ]
FrederickRies/ArchShop
Sources/Backends/ArchShop.Backend.EventSource/Startup.cs
1,582
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.Azure.RemoteRendering; using Microsoft.Azure.RemoteRendering.Unity; using Microsoft.MixedReality.Toolkit.Extensions; using Microsoft.MixedReality.Toolkit.Physics; using Microsoft.MixedReality.Toolkit.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// This is a specialized Mixed Reality Toolkit (MRTK) focus provider for Azure Remote Rendering (ARR). This /// class will execute both local and remote ray casts, and give focus to closest object, be it either local or /// remote. /// /// When using this focus provider, focusing behaves as follows: /// /// (1) For each MRTK pointer asynchronously query for remote focus, only if all previous remote queries have /// completed. /// (2) Execute local focus logic. Note, this will clear any previously focused remote targets, and fire the /// related focus events. /// (3) Compare the last known remote target with the current local target. The closest target becomes the new /// focus target. This will also fire the related focus events. /// (4) Repeat steps 1-4 /// /// Note that the extra layer of 'focus' events may introduce a performance hit, if the application has many or /// complex focus handlers. /// /// Also note that local objects still require an Unity collider in order to obtain focus. While remote object do /// not require an Unity collider. If a remote object has an Unity collider, then the local focus logic may override /// the remote focus logic for that remote object. /// /// To help with debugging the remote ray casts, set _debugRayCasts to true. /// </summary> public class RemoteFocusProviderNoCollider : BaseCoreSystem, IRemoteFocusProvider, IPointerPreferences { public RemoteFocusProviderNoCollider( MixedRealityInputSystemProfile profile) : base(profile) { _localFocusProvider = new FocusProvider(profile); } private readonly FocusProvider _localFocusProvider; private IMixedRealityInputSystem _inputSystem; private float _lastRemoteRayCast; private bool _isQuitting; private readonly Dictionary<uint, RemotePointerResult> _remotePointerData = new Dictionary<uint, RemotePointerResult>(); private readonly List<(IMixedRealityPointer pointer, GameObject oldFocus, GameObject newFocus)> _pendingFocusChanges = new List<(IMixedRealityPointer, GameObject, GameObject)>(); private readonly Dictionary<GameObject, int> _localFocusExits = new Dictionary<GameObject, int>(); private readonly RayCastTasks _remoteRayCasts = new RayCastTasks(_raycastMaxCacheSize); private static RayCastHit _invalidRemoteResult = new RayCastHit() { HitObject = null }; private static RayCastHit[] _invalidRemoteResults = new RayCastHit[1] { _invalidRemoteResult }; /// <summary> /// This is the max number of remote ray casts that can executed simultaneously. /// </summary> private const int _raycastMaxCacheSize = 10; #region Public Properties /// <summary> /// The max rate to perform a remote ray casts /// </summary> public float RemoteRayCastRate { get; set; } = 1.0f / 30.0f; /// <summary> /// Get or set if debug ray casts should be drawn within the app. /// </summary> public bool DebugRayCasts { get; set; } = false; #endregion Public Properties #region IMixedRealityService public override void Initialize() { Application.quitting += OnApplicationQuit; _localFocusProvider.Initialize(); _inputSystem = CoreServices.InputSystem; } public override void Destroy() { Application.quitting -= OnApplicationQuit; _localFocusProvider.Destroy(); } public override void Update() { PreLocalRaycast(); _localFocusProvider.Update(); PostLocalRaycast(); DoRemoteCasts(); } #endregion IMixedRealityService #region IMixedRealityFocusProvider public float GlobalPointingExtent => ((IMixedRealityFocusProvider)_localFocusProvider).GlobalPointingExtent; public LayerMask[] FocusLayerMasks => _localFocusProvider.FocusLayerMasks; public Camera UIRaycastCamera => _localFocusProvider.UIRaycastCamera; public IMixedRealityPointer PrimaryPointer => _localFocusProvider.PrimaryPointer; public uint GenerateNewPointerId() { return _localFocusProvider.GenerateNewPointerId(); } public GameObject GetFocusedObject(IMixedRealityPointer pointer) { return _localFocusProvider.GetFocusedObject(pointer); } public bool IsPointerRegistered(IMixedRealityPointer pointer) { return _localFocusProvider.IsPointerRegistered(pointer); } public void OnSourceDetected(SourceStateEventData eventData) { _localFocusProvider.OnSourceDetected(eventData); foreach (var pointer in eventData.InputSource.Pointers) { GetRemotePointerResult(pointer, true); } } public void OnSourceLost(SourceStateEventData eventData) { _localFocusProvider.OnSourceLost(eventData); foreach (var pointer in eventData.InputSource.Pointers) { ReleasePointer(pointer); } } public void OnSpeechKeywordRecognized(SpeechEventData eventData) { _localFocusProvider.OnSpeechKeywordRecognized(eventData); } public bool RegisterPointer(IMixedRealityPointer pointer) { bool result = _localFocusProvider.RegisterPointer(pointer); GetRemotePointerResult(pointer, true); return result; } public void SubscribeToPrimaryPointerChanged(PrimaryPointerChangedHandler handler, bool invokeHandlerWithCurrentPointer) { _localFocusProvider.SubscribeToPrimaryPointerChanged(handler, invokeHandlerWithCurrentPointer); } public bool TryGetFocusDetails(IMixedRealityPointer pointer, out FocusDetails focusDetails) { return _localFocusProvider.TryGetFocusDetails(pointer, out focusDetails); } public bool TryOverrideFocusDetails(IMixedRealityPointer pointer, FocusDetails focusDetails) { return _localFocusProvider.TryOverrideFocusDetails(pointer, focusDetails); } public bool UnregisterPointer(IMixedRealityPointer pointer) { var result = _localFocusProvider.UnregisterPointer(pointer); ReleasePointer(pointer); return result; } public void UnsubscribeFromPrimaryPointerChanged(PrimaryPointerChangedHandler handler) { _localFocusProvider.UnsubscribeFromPrimaryPointerChanged(handler); } IEnumerable<T> IMixedRealityFocusProvider.GetPointers<T>() { return _localFocusProvider.GetPointers<T>(); } #endregion IMixedRealityFocusProvider #region IPointerPreferences public PointerBehavior GazePointerBehavior { get => _localFocusProvider.GazePointerBehavior; set => _localFocusProvider.GazePointerBehavior = value; } public PointerBehavior GetPointerBehavior(IMixedRealityPointer pointer) { return _localFocusProvider.GetPointerBehavior(pointer); } PointerBehavior IPointerPreferences.GetPointerBehavior<T>(Handedness handedness, InputSourceType sourceType) { return _localFocusProvider.GetPointerBehavior<T>(handedness, sourceType); } void IPointerPreferences.SetPointerBehavior<T>(Handedness handedness, InputSourceType inputType, PointerBehavior pointerBehavior) { _localFocusProvider.SetPointerBehavior<T>(handedness, inputType, pointerBehavior); } #endregion IPointerPreferences #region IRemoteFocusProvider /// <summary> /// Get the pointer's remote focus information. This result contains which remote Entity the pointer is currently /// focused on. /// </summary> public IRemotePointerResult GetRemoteResult(IMixedRealityPointer pointer) { return GetRemotePointerResult(pointer, false); } /// <summary> /// Get the entity from a pointer target. This makes it easier to consume Input events which return game objects. /// Upon handling those events, you can use this method to resolve the entity that was focused. /// </summary> public Entity GetEntity(IMixedRealityPointer pointer, GameObject pointerTarget) { Entity result = null; RemotePointerResult remoteResult = GetRemotePointerResult(pointer, false); if (remoteResult != null) { if (remoteResult.IsTargetValid && pointerTarget == NearestFocusableGameObject(remoteResult.TargetEntity)) { result = remoteResult.TargetEntity; } else if (remoteResult.IsPreviousTargetValid && pointerTarget == NearestFocusableGameObject(remoteResult.PreviousTargetEntity)) { result = remoteResult.PreviousTargetEntity; } // If the remote ray-cast didn't find an entity, it's possible the entity doesn't have remote mesh // colliders. So search for the nearest sync object, and use its entity. if (result == null && !remoteResult.IsTargetValid) { result = pointerTarget.GetComponentInChildren<RemoteEntitySyncObject>()?.Entity; } } return result; } /// <summary> /// Try switching focus to a child object. This is will fail if the current target is not a parent of the child. /// </summary> public void TryFocusingChild(IMixedRealityPointer pointer, GameObject childTarget) { RemotePointerResult remoteResult = GetRemotePointerResult(pointer, false); Entity childEntity = childTarget.GetComponentInParent<RemoteEntitySyncObject>()?.Entity; if (remoteResult != null) { remoteResult.TrySettingOverrideTarget(childEntity); } } #endregion IRemoteFocusProvider #region Private Methods /// <summary> /// Listen for application quits, and stop ray casting if application is shutting down. /// </summary> private void OnApplicationQuit() { _isQuitting = true; } /// <summary> /// Get the pointer's remote focus information. This result contains which remote Entity the pointer is currently /// focused on. /// </summary> private RemotePointerResult GetRemotePointerResult(IMixedRealityPointer pointer, bool allowCreate = true) { if (pointer == null) { return null; } RemotePointerResult result = null; if (!_remotePointerData.TryGetValue(pointer.PointerId, out result) && allowCreate) { result = _remotePointerData[pointer.PointerId] = new RemotePointerResult(pointer); } return result; } /// <summary> /// Dispose or release all remote data associated with the given pointer. /// </summary> private void ReleasePointer(IMixedRealityPointer pointer) { if (pointer == null) { return; } ReleasePointer(pointer.PointerId); } /// <summary> /// Dispose or release all remote data associated with the given pointer. /// </summary> private void ReleasePointer(uint pointerId) { RemotePointerResult data = null; if (_remotePointerData.TryGetValue(pointerId, out data)) { data.Dispose(); _remotePointerData.Remove(pointerId); } } /// <summary> /// Prepare remote data to handle local focus changes, and delete invalid remote pointer data objects. /// </summary> private void PreLocalRaycast() { List<uint> toRemove = new List<uint>(); foreach (var remoteResultEntry in _remotePointerData) { // If pointer has been deleted, don't update and clean it up var remoteResult = remoteResultEntry.Value; if (remoteResult == null || remoteResult.Pointer == null || remoteResult.IsDisposed) { toRemove.Add(remoteResultEntry.Key); continue; } // Save current target, and clear it remoteResult.PreLocalRaycast(); } foreach (uint pointerId in toRemove) { ReleasePointer(pointerId); } } /// <summary> /// Commit remote focus changes after completing local focusing. /// </summary> private void PostLocalRaycast() { Debug.Assert(_localFocusExits.Count == 0, "Data should have been cleared earlier"); foreach (var remoteResultEntry in _remotePointerData) { var remoteResult = remoteResultEntry.Value; // Merge local and remote focus data. If merge fails, stop proccessing pointer. FocusDetails oldLocalFocusDetails = default; _localFocusProvider.TryGetFocusDetails(remoteResult.Pointer, out oldLocalFocusDetails); if (!remoteResult.PostLocalRaycast(oldLocalFocusDetails)) { continue; } // Track which local objects have exited local focus int totalFocusExits = 0; if (oldLocalFocusDetails.Object != null) { _localFocusExits.TryGetValue(oldLocalFocusDetails.Object, out totalFocusExits); } // Override the local providers cache with the remote results if (remoteResult.IsTargetValid) { if (oldLocalFocusDetails.Object != null) { _localFocusExits[oldLocalFocusDetails.Object] = totalFocusExits + 1; } remoteResult.Pointer.OnPreSceneQuery(); remoteResult.Pointer.OnPreCurrentPointerTargetChange(); remoteResult.Pointer.IsTargetPositionLockedOnFocusLock = true; _localFocusProvider.TryOverrideFocusDetails(remoteResult.Pointer, remoteResult.RemoteDetails); remoteResult.Pointer.OnPostSceneQuery(); _pendingFocusChanges.Add(( remoteResult.Pointer, oldLocalFocusDetails.Object, remoteResult.RemoteDetails.Object)); } else if (oldLocalFocusDetails.Object != null) { // Prevent focus exited from firing _localFocusExits[oldLocalFocusDetails.Object] = int.MinValue; } } foreach (var focusChange in _pendingFocusChanges) { // Focus will change every frame when a remote item is focused RaiseFocusEvents(focusChange.pointer, focusChange.oldFocus, focusChange.newFocus); } _pendingFocusChanges.Clear(); _localFocusExits.Clear(); } /// <summary> /// Raises the Focus Events to the Input Manger. /// </summary> private void RaiseFocusEvents(IMixedRealityPointer pointer, GameObject oldFocused, GameObject newFocused) { if (_inputSystem == null) { return; } _inputSystem.RaisePreFocusChanged( pointer, oldFocused, newFocused); // Fire focus exited if this is the last pointer exiting the object's focus int focusExits = 0; if (oldFocused != null) { focusExits = _localFocusExits[oldFocused]; } if (focusExits > 0) { _localFocusExits[oldFocused] = --focusExits; if (focusExits == 0) { _inputSystem.RaiseFocusExit( pointer, oldFocused); } } _inputSystem.RaiseFocusEnter( pointer, newFocused); _inputSystem.RaiseFocusChanged( pointer, oldFocused, newFocused); } /// <summary> /// Find the nearest parent object that has been marked as focusable. /// </summary> /// <param name="entity"> /// The remote Entity where the search starts. /// </param> private static GameObject NearestFocusableGameObject(Entity entity) { GameObject result = null; while (entity != null && entity.Valid && result == null) { result = entity.GetExistingGameObject(); entity = entity.Parent; } // Unity overrides the == operator, so 'result' may not really be null. // Unity doesn't (and can't) override the Null-conditional operator (?), // so we can't also rely on this operator. // // If Unity claims this is null, because its native object has been // destroyed for some reason, force a real null value to be returned so to // prevent bugs by the callers of this function. // See this Unity blog post for details: // https://blogs.unity3d.com/2014/05/16/custom-operator-should-we-keep-it/ // And this Unity documentation on the Object.operator ==: // https://docs.unity3d.com/ScriptReference/Object-operator_eq.html if (result == null) { result = null; } return result; } /// <summary> /// Execute the remote casts (ray cast or star cast) if all pending ray casts have completed, and client is connected to a remote /// rendering session. /// </summary> private void DoRemoteCasts() { var machine = AppServices.RemoteRendering?.PrimaryMachine; // Exit if there is no connection for doing remote ray casts, and ignore/clear any pending ray casts. if (_isQuitting || machine == null || machine.Session.Connection.ConnectionStatus != ConnectionStatus.Connected) { _remoteRayCasts.Clear(); return; } // Throttle remote ray-casts, and don't start another remote ray-cast until old operations have completed. float currentTime = Time.time; if ((currentTime - _lastRemoteRayCast < RemoteRayCastRate) || (!_remoteRayCasts.IsCompletedOrEmpty())) { return; } _lastRemoteRayCast = currentTime; // Execute a remote ray-cast for all pointers. _remoteRayCasts.Clear(); foreach (var remotePointerData in _remotePointerData) { _remoteRayCasts.Add(DoRemoteCast(remotePointerData.Value)); } } /// <summary> /// Execute a remote cast (ray cast or star cast) for the given pointer. /// </summary> private async Task<RayCastHit[]> DoRemoteCast(RemotePointerResult pointerResult) { IMixedRealityPointer pointer = pointerResult?.Pointer; if (pointer == null) { return default; } // If the pointer is locked, keep the focused object the same. // This will ensure that we execute events on those objects // even if the pointer isn't pointing at them. if (pointer.IsFocusLocked && pointer.IsTargetPositionLockedOnFocusLock) { return default; } Task<RayCastHit[]> castTask = null; switch (pointer.SceneQueryType) { case SceneQueryType.SimpleRaycast: castTask = DoRaycast(pointerResult); break; case SceneQueryType.SphereCast: case SceneQueryType.SphereOverlap: castTask = DoMultiRaycast(pointerResult); break; default: castTask = Task.FromResult(_invalidRemoteResults); break; } RayCastHit[] rayCastResults = await castTask; if (!(pointerResult.IsDisposed) && (pointer != null) && !(pointer.IsFocusLocked && pointer.IsTargetPositionLockedOnFocusLock)) { pointerResult.StageRemoteData(rayCastResults); } return rayCastResults; } /// <summary> /// Execute a remote ray cast for the given pointer. /// </summary> private Task<RayCastHit[]> DoRaycast(RemotePointerResult pointerResult) { var pointer = pointerResult?.Pointer; if (pointer == null || pointer.Rays == null || pointer.Rays.Length == 0) { return null; } RayStep firstStep = pointer.Rays[0]; RayStep lastStep = pointer.Rays[pointer.Rays.Length - 1]; Vector3 start = firstStep.Origin; Vector3 end = lastStep.Terminus; Vector3 direction = (end - start); return DoRemoteRaycast( pointerResult, start, direction.normalized, direction.magnitude); } /// <summary> /// Execute a remote star cast (multi-ray cast) for the given pointer. /// </summary> private async Task<RayCastHit[]> DoMultiRaycast(RemotePointerResult pointerResult) { var pointer = pointerResult?.Pointer; if (pointer == null || pointer.Rays == null) { return null; } RayCastTasks rayCastTasks = pointerResult.RayCasts; rayCastTasks.Clear(); int rayCount = Math.Min(pointer.Rays.Length, rayCastTasks.MaxSize); for (int i = 0; i < rayCount; i++) { RayStep step = pointer.Rays[i]; if (step.Length > 0) { rayCastTasks.Add(DoRemoteRaycast(pointerResult, step.Origin, step.Direction, step.Length)); } } RayCastHit[][] hits = await Task.WhenAll(rayCastTasks); return await SortHits(hits); } /// <summary> /// Actually do the work of submitting a ray cast request to the remote session. /// </summary> private async Task<RayCastHit[]> DoRemoteRaycast(RemotePointerResult pointerResult, Vector3 position, Vector3 direction, float distance) { RayCast cast = new RayCast( position.toRemotePos(), direction.toRemoteDir(), distance, HitCollectionPolicy.ClosestHit); if (DebugRayCasts) { pointerResult.Visualizer.Add(position, direction, distance); } RayCastHit[] hits = null; try { var result = await AppServices.RemoteRendering.PrimaryMachine.Actions.RayCastQueryAsync(cast); hits = result.Hits; } catch (Exception ex) { Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, null, "{0}", $"Failed to execute a remote ray cast ({cast.StartPos.toUnityPos()}) -> ({cast.EndPos.toUnityPos()}). Reason: {ex.Message}"); } return hits; } /// <summary> /// Sort a list of lists of multiple ray cast results. Sort by distances in ascending order. Sorting happens /// on a background thread. /// </summary> private Task<RayCastHit[]> SortHits(RayCastHit[][] hits) { return Task.Run(() => { if (hits == null) { return new RayCastHit[0]; } List<RayCastHit> sortedHits = new List<RayCastHit>(); foreach (var rayResults in hits) { if (rayResults == null) { continue; } foreach (var rayResult in rayResults) { if (rayResult.HitObject != null) { sortedHits.Add(rayResult); } } } sortedHits.Sort((RayCastHit a, RayCastHit b) => { if (a.DistanceToHit == b.DistanceToHit) { return 0; } else if (a.DistanceToHit < b.DistanceToHit) { return -1; } else { return 1; } }); return sortedHits.ToArray(); }); } #endregion Private Methods #region Private Classes /// <summary> /// This represents a pointer ray casts performed on the Azure Remote Rendering service. /// </summary> private class RemotePointerResult : IRemotePointerResult { private float _lastStagedTime = 0; private const uint _rayCastCacheSize = 5; private RayCastVisualizer _visualizer = null; private InnerData _staged = InnerData.DefaultUncommitted; private InnerData _committed = InnerData.DefaultUncommitted; private InnerData _override = InnerData.DefaultCommitted; private bool _useLocal = true; private bool _restoreFocusLockOnce = false; private IRemoteSpherePointer _remoteSpherePointer = null; private IRemotePointer _remotePointer = null; private bool _hidingHandRays = false; private FocusDetails _remoteFocusDetails = default; private static FocusDetails _emptyFocusDetails = default; public RemotePointerResult(IMixedRealityPointer pointer) { RayCasts = new RayCastTasks(_rayCastCacheSize); Pointer = pointer; _remotePointer = pointer as IRemotePointer; _remoteSpherePointer = pointer as IRemoteSpherePointer; if (_remotePointer != null) { _remotePointer.RemoteResult = this; } bool sphereCastPointer = pointer != null && (pointer.SceneQueryType == SceneQueryType.SphereCast || pointer.SceneQueryType == SceneQueryType.SphereOverlap); Debug.Assert(!sphereCastPointer || _remoteSpherePointer != null, "The given sphere pointers won't work correctly with remoting, as it doesn't implement IRemoteSpherePointer."); } /// <summary> /// The source of the pointer ray casts. /// </summary> public IMixedRealityPointer Pointer { get; } /// <summary> /// Get the latest 'remote' focus details /// </summary> public FocusDetails RemoteDetails => _useLocal ? _emptyFocusDetails : _remoteFocusDetails; /// <summary> /// Has this result been disposed of. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// The Azure Remote Rendering ray cast hit. /// </summary> public RayCastHit RemoteResult => _useLocal ? default : _committed.RemoteResult; /// <summary> /// The remote Entity that was hit. /// </summary> public Entity TargetEntity { get { if (_useLocal || !_committed.IsTargetValid) { return null; } return _committed.TargetEntity; } } /// <summary> /// The previously focused remote Entity that was hit. /// </summary> public Entity PreviousTargetEntity { get; private set; } /// <summary> /// If true, the pointer ray casts hit a valid remote object. /// </summary> public bool IsTargetValid { get => TargetEntity != null && TargetEntity.Valid; } /// <summary> /// If true, the pointer ray casts hit a valid remote object. /// </summary> public bool IsPreviousTargetValid { get => PreviousTargetEntity != null && PreviousTargetEntity.Valid; } /// <summary> /// This is a cache of remote ray casts, exposed has a clear-able enumerator. This is helpful when doing /// multiple ray casts every frame, and wanting to avoid allocations when awaiting for the results. /// </summary> public RayCastTasks RayCasts { get; private set; } /// <summary> /// A helper object to aid in visualizing remote ray casts. /// </summary> public RayCastVisualizer Visualizer { get { if (_visualizer == null) { _visualizer = new RayCastVisualizer(Pointer, _rayCastCacheSize); } return _visualizer; } } /// <summary> /// Release the pointer result and its resources /// </summary> public void Dispose() { this.IsDisposed = true; this._visualizer?.Dispose(); this._visualizer = null; this.PreviousTargetEntity = this.TargetEntity; this._useLocal = true; this.ReleaseHandRays(); if (_remotePointer != null && _remotePointer.RemoteResult == this) { _remotePointer.RemoteResult = null; } } /// <summary> /// Try to stage remote focus data, so it can be committed during the next update. /// </summary> public void StageRemoteData(RayCastHit[] result) { if (this.IsDisposed) { return; } Debug.Assert( Time.time > _lastStagedTime, "There was more than one call to StageRemoteData() during the frame update. Check if there are multiple 'in-flight' remote ray casts occuring for this pointer."); _lastStagedTime = Time.time; if (result == null || result.Length == 0) { this._staged.RemoteResult = _invalidRemoteResult; } else { this._staged.RemoteResult = result[0]; } // Copy target entity to our public field Entity hitEntity = this._staged.RemoteResult.HitEntity; this._staged.TargetEntity = (hitEntity != null && hitEntity.Valid) ? hitEntity : null; // Data will be committed during the update loop this._staged.Committed = false; // Reset the debug visualizer, so it's ready for the next update _visualizer?.Reset(); } /// <summary> /// Force the hit data from the last remote ray cast to use this override target. This /// request is ignored if there is no valid remote hit data, or the override target is /// not a child of the current target. /// </summary> public void TrySettingOverrideTarget(Entity overrideTarget) { if (_useLocal || !_committed.IsTargetValid || overrideTarget == null || !overrideTarget.Valid || !overrideTarget.IsChildOf(_committed.TargetEntity)) { return; } _override.Committed = false; _override.RemoteResult = new RayCastHit() { DistanceToHit = _committed.RemoteResult.DistanceToHit, HitNormal = _committed.RemoteResult.HitNormal, HitObject = overrideTarget, HitPosition = _committed.RemoteResult.HitPosition, }; _override.TargetEntity = overrideTarget; } /// <summary> /// Determine if the new remote target has changed, and if so commit the data. The committed data /// originates from either the current override target or the staged data. The staged data originates /// from the remote ray cast results. /// </summary> public bool PreLocalRaycast() { if (this.IsDisposed) { return false; } // If there is an override to commit, temporary release the focus lock if (!_override.Committed) { _restoreFocusLockOnce = Pointer.IsFocusLocked; Pointer.IsFocusLocked = false; } // If pointer focused is locked, don't update the committed ray cast data. bool success = false; if (!Pointer.IsFocusLocked || !Pointer.IsTargetPositionLockedOnFocusLock) { this.PreviousTargetEntity = this.TargetEntity; this._useLocal = true; // Commit staged data if not done already if (!_override.Committed) { _committed.RemoteResult = _override.RemoteResult; _committed.TargetEntity = _override.TargetEntity; _committed.Committed = _override.Committed = true; } else if (!_staged.Committed) { _committed.RemoteResult = _staged.RemoteResult; _committed.TargetEntity = _staged.TargetEntity; _committed.Committed = _staged.Committed = true; } if (_committed.IsTargetValid) { HideHandRays(); } else { ReleaseHandRays(); } success = true; } return success; } /// <summary> /// After local ray casts have been completed, decide if the remote ray cast result or the local /// ray cast result should be exposed to the consumers of this focus provider. /// </summary> public bool PostLocalRaycast(FocusDetails localResult) { // If pointer focused is locked, don't update the "use local" flag. if (Pointer.IsFocusLocked && Pointer.IsTargetPositionLockedOnFocusLock) { return false; } // Restore focus lock as needed if (_restoreFocusLockOnce) { Pointer.IsFocusLocked = true; _restoreFocusLockOnce = false; } // Decide whether to use the local or remote ray cast result if (!Pointer.IsInteractionEnabled) { _useLocal = true; } else if (!_committed.IsTargetValid) { _useLocal = true; } else if (localResult.Object == null) { _useLocal = false; } else if ((float)_committed.RemoteResult.DistanceToHit <= localResult.RayDistance) { _useLocal = false; } else { _useLocal = true; } UpdateFocusDetails(); return true; } /// <summary> /// Update the current focus details using the remote data, if the remote data is being used. /// </summary> private void UpdateFocusDetails() { if (_useLocal) { return; } GameObject target = NearestFocusableGameObject(TargetEntity); Transform transform = (target == null) ? null : target.transform; RayCastHit currentRemoteHit = RemoteResult; float distance = (float)currentRemoteHit.DistanceToHit; Vector3 normal = currentRemoteHit.HitNormal.toUnity(); Vector3 point = currentRemoteHit.HitPosition.toUnityPos(); _remoteFocusDetails.LastRaycastHit = new MixedRealityRaycastHit() { distance = distance, normal = normal, point = point, transform = transform }; _remoteFocusDetails.Normal = normal; _remoteFocusDetails.NormalLocalSpace = (transform == null) ? normal : transform.InverseTransformDirection(normal); _remoteFocusDetails.Object = target; _remoteFocusDetails.Point = point; _remoteFocusDetails.PointLocalSpace = (transform == null) ? point : transform.InverseTransformPoint(point); _remoteFocusDetails.RayDistance = distance; } /// <summary> /// Hide hand rays as needed /// </summary> private void HideHandRays() { if (_remoteSpherePointer != null && !_hidingHandRays) { _remoteSpherePointer.IsNearRemoteGrabbable = true; _hidingHandRays = true; } } /// <summary> /// Release hand rays as needed /// </summary> private void ReleaseHandRays() { if (_hidingHandRays) { _remoteSpherePointer.IsNearRemoteGrabbable = false; _hidingHandRays = false; } } /// <summary> /// A struct used to hold both staged and commit remote data /// </summary> private struct InnerData { public static InnerData DefaultCommitted = new InnerData() { Committed = true, TargetEntity = null, RemoteResult = _invalidRemoteResult }; public static InnerData DefaultUncommitted = new InnerData() { Committed = false, TargetEntity = null, RemoteResult = _invalidRemoteResult }; /// <summary> /// Get or set if data has been committed /// </summary> public bool Committed { get; set; } /// <summary> /// If true, the pointer ray casts hit a valid remote object. /// </summary> public bool IsTargetValid { get { return TargetEntity != null && TargetEntity.Valid; } } /// <summary> /// The Azure Remote Rendering ray cast hit. /// </summary> public RayCastHit RemoteResult { get; set; } /// <summary> /// The remote Entity that was hit. /// </summary> public Entity TargetEntity { get; set; } } } /// <summary> /// This is a cache of remote ray casts, exposed has a clear-able enumerator. This is helpful when doing /// multiple ray casts every frame, and wanting to avoid allocations when awaiting for the results. /// </summary> private class RayCastTasks : IEnumerator<Task<RayCastHit[]>>, IEnumerable<Task<RayCastHit[]>> { private Task<RayCastHit[]>[] cache = null; private int current = -1; private uint size = 0; public RayCastTasks(uint cacheSize) { cache = new Task<RayCastHit[]>[cacheSize]; size = 0; } public int MaxSize => cache.Length; public void Add(Task<RayCastHit[]> value) { if (size >= cache.Length) { Debug.LogAssertion("Failed to add ray cast task to cache. Size limit has been reached."); return; } cache[size++] = value; } public Task<RayCastHit[]> GetCurrent() { if (current < 0 || current > size) { return null; } return cache[current]; } public Task<RayCastHit[]> Current => GetCurrent(); object IEnumerator.Current => GetCurrent(); public void Dispose() { Clear(); } public bool MoveNext() { current++; return current < size; } public void Reset() { current = -1; } public void Clear() { Reset(); size = 0; } public bool IsCompletedOrEmpty() { bool completed = true; for (uint i = 0; i < size; i++) { completed &= cache[i].IsCompleted; } return completed; } public IEnumerator<Task<RayCastHit[]>> GetEnumerator() { Reset(); return this; } IEnumerator IEnumerable.GetEnumerator() { Reset(); return this; } } /// <summary> /// A helper class to aid in visualizing remote ray casts /// </summary> private class RayCastVisualizer : IDisposable { private IMixedRealityPointer pointer = null; private GameObject[] debugRays = null; private GameObject debugContainer = null; private const float debugRayWidth = 0.001f; private uint currentDebugRay = 0; public uint maxDebugRays = 0; public RayCastVisualizer(IMixedRealityPointer pointer, uint maxDebugRays) { this.pointer = pointer; this.maxDebugRays = maxDebugRays; debugContainer = new GameObject(); debugContainer.name = $"Debug Ray {pointer.PointerName}"; debugRays = new GameObject[maxDebugRays]; for (int i = 0; i < maxDebugRays; i++) { debugRays[i] = GameObject.CreatePrimitive(PrimitiveType.Cube); debugRays[i].transform.SetParent(debugContainer.transform, false); debugRays[i].transform.localScale = new Vector3(debugRayWidth, debugRayWidth, 0.0f); debugRays[i].SetActive(false); } } public void Dispose() { if (debugContainer != null) { GameObject.Destroy(debugContainer); } debugContainer = null; debugRays = null; } public void Reset() { currentDebugRay = 0; } public void Add(Vector3 position, Vector3 direction, float distance) { if (debugRays == null || currentDebugRay >= debugRays.Length) { return; } if (currentDebugRay == 0) { for (int i = 0; i < maxDebugRays; i++) { debugRays[i].SetActive(false); } } GameObject ray = debugRays[currentDebugRay++]; Component.Destroy(ray.GetComponent<Collider>()); ray.transform.position = position + (direction * distance * 0.5f); ray.transform.rotation = UnityEngine.Quaternion.LookRotation(direction); ray.transform.localScale = new Vector3(debugRayWidth, debugRayWidth, distance); ray.SetActive(true); } } #endregion Private Classes } }
37.546975
212
0.536207
[ "MIT" ]
Azure/azure-remote-rendering
Unity/Showcase/App/Assets/App/Focus/RemoteFocusProviderNoColliders.cs
47,161
C#
using System; namespace EasyAbp.FileManagement.Files { public class FileOperationInfoModel { public Guid? ParentId { get; set; } public string FileContainerName { get; set; } public Guid? OwnerUserId { get; set; } public File File { get; set; } } }
21.4
53
0.576324
[ "MIT" ]
EasyAbp/FileManagement
src/EasyAbp.FileManagement.Application/EasyAbp/FileManagement/Files/FileOperationInfoModel.cs
323
C#
using System.Reflection; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("RoutingService")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RoutingService")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("00741716-1f4d-425b-a260-576b8fd23e83")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.611111
103
0.747606
[ "MIT" ]
zdimension/eiin839
letsgobiking/LetsGoBiking/RoutingService/Properties/AssemblyInfo.cs
1,487
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace BizHawk.Client.EmuHawk { /// <summary> /// A performant VirtualListView implementation that doesn't rely on native Win32 API calls /// (and in fact does not inherit the ListView class at all) /// It is an enhanced version of the work done with GDI+ rendering in InputRoll.cs /// ------------------------------ /// *** GDI+ Rendering Methods *** /// ------------------------------ /// </summary> public partial class PlatformAgnosticVirtualListView { // reusable Pen and Brush objects private Pen sPen = null; private Brush sBrush = null; /// <summary> /// Called when font sizes are changed /// Recalculates cell sizes /// </summary> private void SetCharSize() { using (var g = CreateGraphics()) { var sizeC = Size.Round(g.MeasureString("A", ColumnHeaderFont)); var sizeI = Size.Round(g.MeasureString("A", CellFont)); if (sizeC.Width > sizeI.Width) _charSize = sizeC; else _charSize = sizeI; } UpdateCellSize(); ColumnWidth = CellWidth; ColumnHeight = CellHeight + 2; } /// <summary> /// We draw everthing manually and never call base.OnPaint() /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { // white background sBrush = new SolidBrush(Color.White); sPen = new Pen(Color.White); Rectangle rect = e.ClipRectangle; e.Graphics.FillRectangle(sBrush, rect); e.Graphics.Flush(); var visibleColumns = _columns.VisibleColumns.ToList(); if (visibleColumns.Any()) { DrawColumnBg(e, visibleColumns); DrawColumnText(e, visibleColumns); } // Background DrawBg(e, visibleColumns); // Foreground DrawData(e, visibleColumns); DrawColumnDrag(e); DrawCellDrag(e); if (BorderSize > 0) { // paint parent border using (var gParent = this.Parent.CreateGraphics()) { Pen borderPen = new Pen(BorderColor); for (int b = 1, c = 1; b <= BorderSize; b++, c += 2) { gParent.DrawRectangle(borderPen, this.Left - b, this.Top - b, this.Width + c, this.Height + c); } } } } private void DrawColumnDrag(PaintEventArgs e) { if (_draggingCell != null) { var text = ""; int offsetX = 0; int offsetY = 0; QueryItemText?.Invoke(_draggingCell.RowIndex.Value, _columns.IndexOf(_draggingCell.Column), out text); QueryItemTextAdvanced?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, out text, ref offsetX, ref offsetY); Color bgColor = ColumnHeaderBackgroundColor; QueryItemBkColor?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, ref bgColor); int x1 = _currentX.Value - (_draggingCell.Column.Width.Value / 2); int y1 = _currentY.Value - (CellHeight / 2); int x2 = x1 + _draggingCell.Column.Width.Value; int y2 = y1 + CellHeight; sBrush = new SolidBrush(bgColor); e.Graphics.FillRectangle(sBrush, x1, y1, x2 - x1, y2 - y1); sBrush = new SolidBrush(ColumnHeaderFontColor); e.Graphics.DrawString(text, ColumnHeaderFont, sBrush, (PointF)(new Point(x1 + CellWidthPadding + offsetX, y1 + CellHeightPadding + offsetY))); } } private void DrawCellDrag(PaintEventArgs e) { if (_draggingCell != null) { var text = ""; int offsetX = 0; int offsetY = 0; QueryItemText?.Invoke(_draggingCell.RowIndex.Value, _columns.IndexOf(_draggingCell.Column), out text); QueryItemTextAdvanced?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, out text, ref offsetX, ref offsetY); Color bgColor = CellBackgroundColor; QueryItemBkColor?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, ref bgColor); int x1 = _currentX.Value - (_draggingCell.Column.Width.Value / 2); int y1 = _currentY.Value - (CellHeight / 2); int x2 = x1 + _draggingCell.Column.Width.Value; int y2 = y1 + CellHeight; sBrush = new SolidBrush(bgColor); e.Graphics.FillRectangle(sBrush, x1, y1, x2 - x1, y2 - y1); sBrush = new SolidBrush(CellFontColor); e.Graphics.DrawString(text, CellFont, sBrush, (PointF)(new Point(x1 + CellWidthPadding + offsetX, y1 + CellHeightPadding + offsetY))); } } private void DrawColumnText(PaintEventArgs e, List<ListColumn> visibleColumns) { sBrush = new SolidBrush(ColumnHeaderFontColor); foreach (var column in visibleColumns) { var point = new Point(column.Left.Value + 2 * CellWidthPadding - _hBar.Value, CellHeightPadding); // TODO: fix this CellPadding issue (2 * CellPadding vs just CellPadding) string t = column.Text; ResizeTextToFit(ref t, column.Width.Value, ColumnHeaderFont); if (IsHoveringOnColumnCell && column == CurrentCell.Column) { sBrush = new SolidBrush(InvertColor(ColumnHeaderBackgroundHighlightColor)); e.Graphics.DrawString(t, ColumnHeaderFont, sBrush, (PointF)(point)); sBrush = new SolidBrush(ColumnHeaderFontColor); } else { e.Graphics.DrawString(t, ColumnHeaderFont, sBrush, (PointF)(point)); } } } private void DrawData(PaintEventArgs e, List<ListColumn> visibleColumns) { // Prevent exceptions with small windows if (visibleColumns.Count == 0) { return; } if (QueryItemText != null || QueryItemTextAdvanced != null) { int startRow = FirstVisibleRow; int range = Math.Min(LastVisibleRow, ItemCount - 1) - startRow + 1; sBrush = new SolidBrush(CellFontColor); int xPadding = CellWidthPadding + 1 - _hBar.Value; for (int i = 0, f = 0; f < range; i++, f++) // Vertical { //f += _lagFrames[i]; int LastVisible = LastVisibleColumnIndex; for (int j = FirstVisibleColumn; j <= LastVisible; j++) // Horizontal { ListColumn col = visibleColumns[j]; string text = ""; int strOffsetX = 0; int strOffsetY = 0; Point point = new Point(col.Left.Value + xPadding, RowsToPixels(i) + CellHeightPadding); Bitmap image = null; int bitmapOffsetX = 0; int bitmapOffsetY = 0; QueryItemIcon?.Invoke(f + startRow, visibleColumns[j], ref image, ref bitmapOffsetX, ref bitmapOffsetY); if (image != null) { e.Graphics.DrawImage(image, new Point(point.X + bitmapOffsetX, point.Y + bitmapOffsetY + CellHeightPadding)); } QueryItemText?.Invoke(f + startRow, _columns.IndexOf(visibleColumns[j]), out text); QueryItemTextAdvanced?.Invoke(f + startRow, visibleColumns[j], out text, ref strOffsetX, ref strOffsetY); bool rePrep = false; if (_selectedItems.Contains(new Cell { Column = visibleColumns[j], RowIndex = f + startRow })) { sBrush = new SolidBrush(InvertColor(CellBackgroundHighlightColor)); rePrep = true; } if (!string.IsNullOrWhiteSpace(text)) { ResizeTextToFit(ref text, col.Width.Value, CellFont); e.Graphics.DrawString(text, CellFont, sBrush, (PointF)(new Point(point.X + strOffsetX, point.Y + strOffsetY))); } if (rePrep) { sBrush = new SolidBrush(CellFontColor); } } } } } private void ResizeTextToFit(ref string text, int destinationSize, Font font) { Size strLen; using (var g = CreateGraphics()) { strLen = Size.Round(g.MeasureString(text, font)); } if (strLen.Width > destinationSize - CellWidthPadding) { // text needs trimming List<char> chars = new List<char>(); for (int s = 0; s < text.Length; s++) { chars.Add(text[s]); Size tS; Size dotS; using (var g = CreateGraphics()) { tS = Size.Round(g.MeasureString(new string(chars.ToArray()), CellFont)); dotS = Size.Round(g.MeasureString(".", CellFont)); } int dotWidth = dotS.Width * 3; if (tS.Width >= destinationSize - CellWidthPadding - dotWidth) { text = new string(chars.ToArray()) + "..."; break; } } } } // https://stackoverflow.com/a/34107015/6813055 private Color InvertColor(Color color) { var inverted = Color.FromArgb(color.ToArgb() ^ 0xffffff); if (inverted.R > 110 && inverted.R < 150 && inverted.G > 110 && inverted.G < 150 && inverted.B > 110 && inverted.B < 150) { int avg = (inverted.R + inverted.G + inverted.B) / 3; avg = avg > 128 ? 200 : 60; inverted = Color.FromArgb(avg, avg, avg); } return inverted; } private void DrawColumnBg(PaintEventArgs e, List<ListColumn> visibleColumns) { sBrush = new SolidBrush(ColumnHeaderBackgroundColor); sPen = new Pen(ColumnHeaderOutlineColor); int bottomEdge = RowsToPixels(0); // Gray column box and black line underneath e.Graphics.FillRectangle(sBrush, 0, 0, Width + 1, bottomEdge + 1); e.Graphics.DrawLine(sPen, 0, 0, TotalColWidth.Value + 1, 0); e.Graphics.DrawLine(sPen, 0, bottomEdge, TotalColWidth.Value + 1, bottomEdge); // Vertical black seperators for (int i = 0; i < visibleColumns.Count; i++) { int pos = visibleColumns[i].Left.Value - _hBar.Value; e.Graphics.DrawLine(sPen, pos, 0, pos, bottomEdge); } // Draw right most line if (visibleColumns.Any()) { int right = TotalColWidth.Value - _hBar.Value; e.Graphics.DrawLine(sPen, right, 0, right, bottomEdge); } // Emphasis foreach (var column in visibleColumns.Where(c => c.Emphasis)) { sBrush = new SolidBrush(SystemColors.ActiveBorder); e.Graphics.FillRectangle(sBrush, column.Left.Value + 1 - _hBar.Value, 1, column.Width.Value - 1, ColumnHeight - 1); } // If the user is hovering over a column if (IsHoveringOnColumnCell) { // TODO multiple selected columns for (int i = 0; i < visibleColumns.Count; i++) { if (visibleColumns[i] == CurrentCell.Column) { // Left of column is to the right of the viewable area or right of column is to the left of the viewable area if (visibleColumns[i].Left.Value - _hBar.Value > Width || visibleColumns[i].Right.Value - _hBar.Value < 0) { continue; } int left = visibleColumns[i].Left.Value - _hBar.Value; int width = visibleColumns[i].Right.Value - _hBar.Value - left; if (CurrentCell.Column.Emphasis) { sBrush = new SolidBrush(Color.FromArgb(ColumnHeaderBackgroundHighlightColor.ToArgb() + 0x00550000)); } else { sBrush = new SolidBrush(ColumnHeaderBackgroundHighlightColor); } e.Graphics.FillRectangle(sBrush, left + 1, 1, width - 1, ColumnHeight - 1); } } } } // TODO refactor this and DoBackGroundCallback functions. /// <summary> /// Draw Gridlines and background colors using QueryItemBkColor. /// </summary> private void DrawBg(PaintEventArgs e, List<ListColumn> visibleColumns) { if (UseCustomBackground && QueryItemBkColor != null) { DoBackGroundCallback(e, visibleColumns); } if (GridLines) { sPen = new Pen(GridLineColor); // Columns int y = ColumnHeight + 1; int? totalColWidth = TotalColWidth; foreach (var column in visibleColumns) { int x = column.Left.Value - _hBar.Value; e.Graphics.DrawLine(sPen, x, y, x, Height - 1); } if (visibleColumns.Any()) { e.Graphics.DrawLine(sPen, totalColWidth.Value - _hBar.Value, y, totalColWidth.Value - _hBar.Value, Height - 1); } // Rows for (int i = 1; i < VisibleRows + 1; i++) { e.Graphics.DrawLine(sPen, 0, RowsToPixels(i), Width + 1, RowsToPixels(i)); } } if (_selectedItems.Any() && !HideSelection) { DoSelectionBG(e, visibleColumns); } } /// <summary> /// Given a cell with rowindex inbetween 0 and VisibleRows, it draws the background color specified. Do not call with absolute rowindices. /// </summary> private void DrawCellBG(PaintEventArgs e, Color color, Cell cell, List<ListColumn> visibleColumns) { int x, y, w, h; w = cell.Column.Width.Value - 1; x = cell.Column.Left.Value - _hBar.Value + 1; y = RowsToPixels(cell.RowIndex.Value) + 1; // We can't draw without row and column, so assume they exist and fail catastrophically if they don't h = CellHeight - 1; if (y < ColumnHeight) { return; } if (x > DrawWidth || y > DrawHeight) { return; } // Don't draw if off screen. var col = cell.Column.Name; if (color.A == 0) { sBrush = new SolidBrush(Color.FromArgb(255, color)); } else { sBrush = new SolidBrush(color); } e.Graphics.FillRectangle(sBrush, x, y, w, h); } protected override void OnPaintBackground(PaintEventArgs pevent) { // Do nothing, and this should never be called } private void DoSelectionBG(PaintEventArgs e, List<ListColumn> visibleColumns) { // SuuperW: This allows user to see other colors in selected frames. Color rowColor = CellBackgroundColor; // Color.White; int _lastVisibleRow = LastVisibleRow; int lastRow = -1; foreach (Cell cell in _selectedItems) { if (cell.RowIndex > _lastVisibleRow || cell.RowIndex < FirstVisibleRow || !VisibleColumns.Contains(cell.Column)) { continue; } Cell relativeCell = new Cell { RowIndex = cell.RowIndex - FirstVisibleRow, Column = cell.Column, }; if (QueryRowBkColor != null && lastRow != cell.RowIndex.Value) { QueryRowBkColor(cell.RowIndex.Value, ref rowColor); lastRow = cell.RowIndex.Value; } Color cellColor = rowColor; QueryItemBkColor?.Invoke(cell.RowIndex.Value, cell.Column, ref cellColor); // Alpha layering for cell before selection float alpha = (float)cellColor.A / 255; if (cellColor.A != 255 && cellColor.A != 0) { cellColor = Color.FromArgb(rowColor.R - (int)((rowColor.R - cellColor.R) * alpha), rowColor.G - (int)((rowColor.G - cellColor.G) * alpha), rowColor.B - (int)((rowColor.B - cellColor.B) * alpha)); } // Alpha layering for selection alpha = 0.85f; cellColor = Color.FromArgb(cellColor.R - (int)((cellColor.R - CellBackgroundHighlightColor.R) * alpha), cellColor.G - (int)((cellColor.G - CellBackgroundHighlightColor.G) * alpha), cellColor.B - (int)((cellColor.B - CellBackgroundHighlightColor.B) * alpha)); DrawCellBG(e, cellColor, relativeCell, visibleColumns); } } /// <summary> /// Calls QueryItemBkColor callback for all visible cells and fills in the background of those cells. /// </summary> /// <param name="e"></param> private void DoBackGroundCallback(PaintEventArgs e, List<ListColumn> visibleColumns) { int startIndex = FirstVisibleRow; int range = Math.Min(LastVisibleRow, ItemCount - 1) - startIndex + 1; int lastVisible = LastVisibleColumnIndex; int firstVisibleColumn = FirstVisibleColumn; // Prevent exceptions with small windows if (firstVisibleColumn < 0) { return; } for (int i = 0, f = 0; f < range; i++, f++) // Vertical { //f += _lagFrames[i]; Color rowColor = CellBackgroundColor; QueryRowBkColor?.Invoke(f + startIndex, ref rowColor); for (int j = FirstVisibleColumn; j <= lastVisible; j++) // Horizontal { Color itemColor = CellBackgroundColor; QueryItemBkColor(f + startIndex, visibleColumns[j], ref itemColor); if (itemColor == CellBackgroundColor) { itemColor = rowColor; } else if (itemColor.A != 255 && itemColor.A != 0) { float alpha = (float)itemColor.A / 255; itemColor = Color.FromArgb(rowColor.R - (int)((rowColor.R - itemColor.R) * alpha), rowColor.G - (int)((rowColor.G - itemColor.G) * alpha), rowColor.B - (int)((rowColor.B - itemColor.B) * alpha)); } if (itemColor != Color.White) // An easy optimization, don't draw unless the user specified something other than the default { var cell = new Cell { Column = visibleColumns[j], RowIndex = i }; DrawCellBG(e, itemColor, cell, visibleColumns); } } } } } }
30.589695
175
0.651008
[ "MIT" ]
Asnivor/BizHawk
BizHawk.Client.EmuHawk/CustomControls/PlatformAgnosticVirtualListView.Drawing.cs
16,031
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 // 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 // 이러한 특성 값을 변경하세요. [assembly: AssemblyTitle("DustSensorViewer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DustSensorViewer")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("8f68bb11-e431-4375-910d-56e5a6923ecf")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호가 자동으로 // 지정되도록 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.918919
56
0.7
[ "MIT" ]
BruceNUAA/DustViewerSharp
DustSensorViewer/Properties/AssemblyInfo.cs
1,511
C#
namespace Pubs.CoreDomain.Enums { /// <summary> /// This enumeration lists all of the possible application user statuses. /// </summary> public enum ApplicationUserStatusEnum { Active = 1001, Inactive = 1002, Locked = 1003 } }
21.230769
77
0.608696
[ "MIT" ]
theMickster/pubs
src/Pubs.CoreDomain/Enums/ApplicationUserStatusEnum.cs
278
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DeviceFarm.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DeviceFarm.Model.Internal.MarshallTransformations { /// <summary> /// UntagResource Request Marshaller /// </summary> public class UntagResourceRequestMarshaller : IMarshaller<IRequest, UntagResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UntagResourceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UntagResourceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DeviceFarm"); string target = "DeviceFarm_20150623.UntagResource"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-06-23"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetResourceARN()) { context.Writer.WritePropertyName("ResourceARN"); context.Writer.Write(publicRequest.ResourceARN); } if(publicRequest.IsSetTagKeys()) { context.Writer.WritePropertyName("TagKeys"); context.Writer.WriteArrayStart(); foreach(var publicRequestTagKeysListValue in publicRequest.TagKeys) { context.Writer.Write(publicRequestTagKeysListValue); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UntagResourceRequestMarshaller _instance = new UntagResourceRequestMarshaller(); internal static UntagResourceRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UntagResourceRequestMarshaller Instance { get { return _instance; } } } }
35.948276
141
0.613669
[ "Apache-2.0" ]
costleya/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/Internal/MarshallTransformations/UntagResourceRequestMarshaller.cs
4,170
C#
using UnityEngine; using System.Collections; public class ThirdCharacterController : MonoBehaviour { Animator _anim; int _hashSpeed; // Use this for initialization void Start () { _anim = GetComponent<Animator>(); _hashSpeed = Animator.StringToHash("Speed"); } // Update is called once per frame void Update () { if (Input.GetKey(KeyCode.UpArrow)){ _anim.SetFloat("Speed", 0.2f); } } }
17.956522
55
0.699758
[ "Unlicense" ]
yanjingzhaisun/doodlearound
Assets/Z_MyAsset/Scripts/ThirdCharacterController.cs
415
C#
using System; using System.Net; using System.Threading.Tasks; using Nethereum.Web3; namespace NethereumSample { class Program { static void Main(string[] args) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; // | SecurityProtocolType.Ssl3; System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => { // put a breakpoint and debug the 'error' variable return true; }; //GetAccountBalance().Wait(); var t = new VaultClient().getSecret("infuraUrl"); t.Wait(); var url = t.Result; Console.WriteLine(url); Console.ReadLine(); } static async Task GetAccountBalance() { var web3 = new Web3("https://ropsten.infura.io/v3/83f9baf669d145d4844a13c58897bfec"); var balance = await web3.Eth.GetBalance.SendRequestAsync("0x4CB0D46FbC185B3bA776C1Cc594B1adBF19C5c3B"); Console.WriteLine($"Balance in Wei: {balance.Value}"); var etherAmount = Web3.Convert.FromWei(balance.Value); Console.WriteLine($"Balance in Ether: {etherAmount}"); } } }
30.140351
120
0.548894
[ "Apache-2.0" ]
fintex-dev/fintex.dev
src/csharp/consoleproject/Program.cs
1,720
C#
using System; using System.Linq; using AutoFixture; using Xunit; namespace AutoFixtureUnitTest { public class CurrentDateTimeCustomizationTest { [Fact] public void SutIsCustomization() { // Arrange // Act var sut = new CurrentDateTimeCustomization(); // Assert Assert.IsAssignableFrom<ICustomization>(sut); } [Fact] public void CustomizeWithNullThrowsArgumentNullException() { // Arrange var sut = new CurrentDateTimeCustomization(); // Act & assert Assert.Throws<ArgumentNullException>(() => sut.Customize(null)); } [Fact] public void CustomizeAddsCurrentDateTimeGeneratorToFixture() { // Arrange var fixture = new Fixture(); var sut = new CurrentDateTimeCustomization(); // Act sut.Customize(fixture); // Assert Assert.True(fixture.Customizations.OfType<CurrentDateTimeGenerator>().Any()); } } }
26.853659
89
0.565849
[ "MIT" ]
AutoFixture/AutoFixture
Src/AutoFixtureUnitTest/CurrentDateTimeCustomizationTest.cs
1,103
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DXVisualTestFixer.Farm.Configuration { public static class VersionInfo { public const string VersionString = "1.0.0"; public static readonly Version Version = new Version(VersionString); } }
27.307692
77
0.721127
[ "MIT" ]
Xarlot/DXVisualTestFixer
DXVisualTestFixer.FarmIntegrator/Config/VersionInfo.cs
357
C#
// 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 System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.Utilities { internal static class GeneratorDriverRunResultExtensions { public static bool TryGetGeneratorAndHint( this GeneratorDriverRunResult? generatorRunResult, SyntaxTree tree, [NotNullWhen(true)] out ISourceGenerator? generator, [NotNullWhen(true)] out string? generatedSourceHintName) { if (generatorRunResult != null) { foreach (var generatorResult in generatorRunResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { if (generatedSource.SyntaxTree == tree) { generator = generatorResult.Generator; generatedSourceHintName = generatedSource.HintName; return true; } } } } generator = null; generatedSourceHintName = null; return false; } } }
34.55
85
0.560781
[ "MIT" ]
333fred/roslyn
src/Workspaces/Core/Portable/Utilities/GeneratorDriverRunResultExtensions.cs
1,384
C#
#nullable disable using System.Text; using BinarySerializer; using Newtonsoft.Json; namespace RayCarrot.RCP.Metro; public class GameMaker_DSMapDataObject : BinarySerializable { public ObjectType Type { get; set; } public double NumberValue { get; set; } [JsonIgnore] public int NumberValueAsInt => (int)NumberValue; [JsonIgnore] public bool NumberValueAsBool => NumberValue > 0; public int StringLength { get; set; } public string StringValue { get; set; } public override void SerializeImpl(SerializerObject s) { Type = s.Serialize<ObjectType>(Type, name: nameof(Type)); switch (Type) { case ObjectType.Number: NumberValue = s.Serialize<double>(NumberValue, name: nameof(NumberValue)); break; case ObjectType.String: StringLength = s.Serialize<int>(StringLength, name: nameof(StringLength)); StringValue = s.SerializeString(StringValue, StringLength, Encoding.ASCII, name: nameof(StringValue)); break; default: throw new BinarySerializableException(this, $"Unsupported object type {Type}"); } } public enum ObjectType { Number = 0, String = 1, } }
27.553191
118
0.630116
[ "MIT" ]
RayCarrot/Rayman-Control-Panel-Metro
src/RayCarrot.RCP.Metro/Binary/GameMaker/GameMaker_DSMapDataObject.cs
1,297
C#