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
#if EF using EfLocalDb; #else using LocalDb; #endif public static class ModuleInitializer { [ModuleInitializer] public static void Initialize() { XunitContext.Init(); LocalDbLogging.EnableVerbose(); LocalDbSettings.ConnectionBuilder((instance, database) => $"Data Source=(LocalDb)\\{instance};Database={database};Pooling=true;Connection Timeout=300"); VerifierSettings.ScrubLinesContaining("filename = '"); VerifierSettings.IgnoreMember<LocalDbInstanceInfo>(x => x.OwnerSID); VerifierSettings.IgnoreMember<LocalDbInstanceInfo>(x => x.Connection); VerifierSettings.IgnoreMember<LocalDbInstanceInfo>(x => x.LastStartUtc); VerifierSettings.IgnoreMember<LocalDbInstanceInfo>(x => x.Build); VerifierSettings.IgnoreMember<LocalDbInstanceInfo>(x => x.Major); VerifierSettings.IgnoreMember<LocalDbInstanceInfo>(x => x.Minor); VerifierSettings.IgnoreMember<LocalDbInstanceInfo>(x => x.Revision); } }
39.88
160
0.721163
[ "MIT" ]
SimonCropp/EF.LocalDB
src/LocalDb.Tests/ModuleInitializer.cs
999
C#
/* Copyright 2017 Microsoft 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 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. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace DMDashboard { public class DMControlList : DMControl { public virtual UIElementCollection Controls { get { throw new NotImplementedException(); } } public override string ToJson() { if (!base.IsIncluded && base.IsOptional) { return ""; } StringBuilder sb = new StringBuilder(); foreach (UIElement uc in Controls) { if (!(uc is DMControl)) { continue; } DMControl dmControl = (DMControl)uc; string controlJson = dmControl.ToJson(); if (!String.IsNullOrEmpty(controlJson)) { if (sb.Length > 0) { sb.Append(",\n"); } sb.Append(controlJson); } } StringBuilder asb = new StringBuilder(); if (PropertyName.Length > 0) { asb.Append("\"" + PropertyName + "\" : "); asb.Append("{\n"); asb.Append(sb.ToString()); asb.Append("}\n"); } else { asb.Append(sb.ToString()); } return asb.ToString(); } } }
31.802469
104
0.566382
[ "MIT" ]
mehrdad-shokri/iot-core-azure-dm-client
samples/DMDashboard/Common/DMControlList.cs
2,578
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> //------------------------------------------------------------------------------ namespace Debug.Kubernetes.Extension.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Debug.Kubernetes.Extension.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap edit_outline_black { get { object obj = ResourceManager.GetObject("edit-outline-black", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap open_outline_black { get { object obj = ResourceManager.GetObject("open-outline-black", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap reload_outline_black { get { object obj = ResourceManager.GetObject("reload-outline-black", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap remove_outline_black { get { object obj = ResourceManager.GetObject("remove-outline-black", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap save_outline_black { get { object obj = ResourceManager.GetObject("save-outline-black", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
42.780702
193
0.572688
[ "MIT" ]
ricardoalkain/debug-k8s-pod-vsix
Debug.Kubernetes.Extension/Properties/Resources.Designer.cs
4,879
C#
using System; namespace SolidStack.Core.Flow.Internal.Result { internal class ResolvedMappableSuccess<TError, TSuccess, TMappingDestination> : MappableContent< ResolvedMappableSuccess<TError, TSuccess, TMappingDestination>, TSuccess, TMappingDestination>, IMappableSuccess<TError, TSuccess, TMappingDestination> { public ResolvedMappableSuccess(TSuccess content) : base(content) { } public ResolvedMappableSuccess(TSuccess content, Func<TSuccess, TMappingDestination> firstMapping) : base(content, firstMapping) { } public IFilteredMappableContent< TSpecificError, TMappingDestination, IMappableSuccess<TError, TSuccess, TMappingDestination>> WhenError<TSpecificError>() where TSpecificError : TError => SkipNextMapping<TSpecificError>(); public IFilteredMappableContent<TError, TMappingDestination> WhenError() => SkipLastMapping<TError>(); } }
36.206897
108
0.673333
[ "MIT" ]
idmobiles/solidstack
src/SolidStack.Core.Flow/Internal/Result/ResolvedMappableSuccess.cs
1,052
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; namespace ES3Internal { public class ES3WebClass { protected string url; protected string apiKey; protected List<KeyValuePair<string,string>> formData = new List<KeyValuePair<string, string>>(); protected UnityWebRequest _webRequest = null; public bool isDone = false; public float uploadProgress { get { if(_webRequest == null) return 0; else return _webRequest.uploadProgress; } } public float downloadProgress { get { if(_webRequest == null) return 0; else return _webRequest.downloadProgress; } } #region Error Handling /// <summary>An error message, if an error occurred.</summary> public string error = null; /// <summary>This is set to true if an error occurred while performing an operation.</summary> public bool isError{ get{ return !string.IsNullOrEmpty(error) || errorCode > 0; } } /// <summary>The error code relating to the error, if one occurred. If it's a server error, this will return the HTTP error code.</summary> public long errorCode = 0; #endregion protected ES3WebClass(string url, string apiKey) { this.url = url; this.apiKey = apiKey; } #region Other Methods /// <summary>Adds POST data to any requests sent by this ES3Cloud object. Use this if you are sending data to a custom script on your server.</summary> /// <param name="fieldName">The name of the POST field we want to add.</param> /// <param name="value">The string value of the POST field we want to add.</param> public void AddPOSTField(string fieldName, string value) { formData.Add(new KeyValuePair<string, string>(fieldName, value)); } #endregion #region Internal Methods protected string GetUser(string user, string password) { if(string.IsNullOrEmpty(user)) return ""; // Final user string is a combination of the username and password, and hashed if encryption is enabled. if(!string.IsNullOrEmpty(password)) user += password; #if !DISABLE_ENCRYPTION && !DISABLE_HASHING user = ES3Internal.ES3Hash.SHA1Hash(user); #endif return user; } protected WWWForm CreateWWWForm() { var form = new WWWForm(); foreach(var kvp in formData) form.AddField(kvp.Key, kvp.Value); return form; } /* Checks if an error occurred and sets relevant details, and returns true if an error did occur */ protected bool HandleError(UnityWebRequest webRequest, bool errorIfDataIsDownloaded) { #if UNITY_5 if(webRequest.isError) #else if(webRequest.isNetworkError) // isError was renamed to isNetworkError in Unity 2017. #endif { errorCode = 1; error = "Error: " + webRequest.error; } else if(webRequest.responseCode >= 400) { errorCode = webRequest.responseCode; if(string.IsNullOrEmpty(webRequest.downloadHandler.text)) error = string.Format("Server returned {0} error with no message", webRequest.responseCode); else error = webRequest.downloadHandler.text; } else if(errorIfDataIsDownloaded && webRequest.downloadedBytes > 0) { errorCode = 2; error = "Server error: " + webRequest.downloadHandler.text; } else return false; return true; } protected IEnumerator SendWebRequest(UnityWebRequest webRequest) { _webRequest = webRequest; #if !UNITY_2017_2_OR_NEWER yield return webRequest.Send(); #else yield return webRequest.SendWebRequest(); #endif } protected virtual void Reset() { error = null; errorCode = 0; isDone = false; } #endregion } }
25.423611
153
0.698989
[ "MIT" ]
Hir-o/Settlers-of-Albion-Project-Files
Assets/Plugins/Easy Save 3/Scripts/Web/ES3WebClass.cs
3,663
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Snake { public class Program { public static void Main(string[] args) { int lastFoodTime = 0; int foodDisappearTime = 8000; int negativePoints = 0; Position[] directions = new Position[] { new Position(0, 1), // right new Position(0, -1), // left new Position(1, 0), // down new Position(-1, 0), // up }; double sleepTime = 100; int direction = (int) Direction.Right; Random randomNumbersGenerator = new Random(); Console.BufferHeight = Console.WindowHeight; lastFoodTime = Environment.TickCount; List<Position> obstacles = new List<Position>() { new Position(12, 12), new Position(14, 20), new Position(7, 7), new Position(19, 19), new Position(6, 9), }; foreach (Position obstacle in obstacles) { Console.ForegroundColor = ConsoleColor.Cyan; Console.SetCursorPosition(obstacle.col, obstacle.row); Console.Write("="); } Queue<Position> snakeElements = new Queue<Position>(); for (int i = 0; i <= 5; i++) { snakeElements.Enqueue(new Position(0, i)); } Position food; do { food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); } while (snakeElements.Contains(food) || obstacles.Contains(food)); Console.SetCursorPosition(food.col, food.row); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("@"); foreach (Position position in snakeElements) { Console.SetCursorPosition(position.col, position.row); Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write("*"); } while (true) { negativePoints++; if (Console.KeyAvailable) { ConsoleKeyInfo userInput = Console.ReadKey(); if (userInput.Key == ConsoleKey.LeftArrow) { if (direction != (int) Direction.Right) direction = (int) Direction.Left; } if (userInput.Key == ConsoleKey.RightArrow) { if (direction != (int) Direction.Left) direction = (int) Direction.Right; } if (userInput.Key == ConsoleKey.UpArrow) { if (direction != (int) Direction.Down) direction = (int) Direction.Up; } if (userInput.Key == ConsoleKey.DownArrow) { if (direction != (int) Direction.Up) direction = (int) Direction.Down; } } Position snakeHead = snakeElements.Last(); Position nextDirection = directions[direction]; Position snakeNewHead = new Position(snakeHead.row + nextDirection.row, snakeHead.col + nextDirection.col); if (snakeNewHead.col < 0) snakeNewHead.col = Console.WindowWidth - 1; if (snakeNewHead.row < 0) snakeNewHead.row = Console.WindowHeight - 1; if (snakeNewHead.row >= Console.WindowHeight) snakeNewHead.row = 0; if (snakeNewHead.col >= Console.WindowWidth) snakeNewHead.col = 0; if (snakeElements.Contains(snakeNewHead) || obstacles.Contains(snakeNewHead)) { Console.SetCursorPosition(0, 0); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Game over!"); int userPoints = (snakeElements.Count - 6) * 100 - negativePoints; //if (userPoints < 0) userPoints = 0; userPoints = Math.Max(userPoints, 0); Console.WriteLine("Your points are: {0}", userPoints); return; } Console.SetCursorPosition(snakeHead.col, snakeHead.row); Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write("*"); snakeElements.Enqueue(snakeNewHead); Console.SetCursorPosition(snakeNewHead.col, snakeNewHead.row); Console.ForegroundColor = ConsoleColor.Gray; if (direction == (int) Direction.Right) Console.Write(">"); if (direction == (int) Direction.Left) Console.Write("<"); if (direction == (int) Direction.Up) Console.Write("^"); if (direction == (int) Direction.Down) Console.Write("v"); if (snakeNewHead.col == food.col && snakeNewHead.row == food.row) { // feeding the snake do { food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); } while (snakeElements.Contains(food) || obstacles.Contains(food)); lastFoodTime = Environment.TickCount; Console.SetCursorPosition(food.col, food.row); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("@"); sleepTime--; Position obstacle = new Position(); do { obstacle = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); } while (snakeElements.Contains(obstacle) || obstacles.Contains(obstacle) || (food.row != obstacle.row && food.col != obstacle.row)); obstacles.Add(obstacle); Console.SetCursorPosition(obstacle.col, obstacle.row); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("="); } else { // moving... Position last = snakeElements.Dequeue(); Console.SetCursorPosition(last.col, last.row); Console.Write(" "); } if (Environment.TickCount - lastFoodTime >= foodDisappearTime) { negativePoints = negativePoints + 50; Console.SetCursorPosition(food.col, food.row); Console.Write(" "); do { food = new Position(randomNumbersGenerator.Next(0, Console.WindowHeight), randomNumbersGenerator.Next(0, Console.WindowWidth)); } while (snakeElements.Contains(food) || obstacles.Contains(food)); lastFoodTime = Environment.TickCount; } Console.SetCursorPosition(food.col, food.row); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("@"); sleepTime -= 0.01; Thread.Sleep((int)sleepTime); } } } }
40.839378
101
0.4915
[ "MIT" ]
PetarTolev/High-Quality-Code
04. Refactoring/Program.cs
7,884
C#
using System; using System.Globalization; namespace HvA.API.NetStandard1.Extensions { public static class DateTimeExtensions { public static int GetIso8601WeekOfYear(this DateTime time) { DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } } }
26.863636
130
0.648054
[ "MIT" ]
AeonLucid/HvA-API-NetStandard1
src/HvA.API.NetStandard1/Extensions/DateTimeExtensions.cs
593
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace HullMaker.Account { public partial class Manage { /// <summary> /// successMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder successMessage; /// <summary> /// ChangePassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink ChangePassword; /// <summary> /// CreatePassword control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink CreatePassword; /// <summary> /// PhoneNumber control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label PhoneNumber; } }
33.884615
84
0.521566
[ "MIT" ]
ArenaDave/CodeFighter
CodeFighter/HullMaker/Account/Manage.aspx.designer.cs
1,764
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("Modificador_Out")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Modificador_Out")] [assembly: System.Reflection.AssemblyTitleAttribute("Modificador_Out")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.458333
80
0.652261
[ "MIT" ]
Cicerofer/Udemy_Poo_Projetos_CSharp
Modificador_Out/Modificador_Out/obj/Debug/netcoreapp3.1/Modificador_Out.AssemblyInfo.cs
995
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.WebJobs.Host; using TollBooth.Models; namespace TollBooth { internal class DatabaseMethods { private readonly string _endpointUrl = ConfigurationManager.AppSettings["cosmosDBEndPointUrl"]; private readonly string _authorizationKey = ConfigurationManager.AppSettings["cosmosDBAuthorizationKey"]; private readonly string _databaseId = ConfigurationManager.AppSettings["cosmosDBDatabaseId"]; private readonly string _collectionId = ConfigurationManager.AppSettings["cosmosDBCollectionId"]; private readonly TraceWriter _log; // Reusable instance of DocumentClient which represents the connection to a Cosmos DB endpoint. private DocumentClient _client; public DatabaseMethods(TraceWriter log) { _log = log; } /// <summary> /// Retrieves all license plate records (documents) that have not yet been exported. /// </summary> /// <returns></returns> public List<LicensePlateDataDocument> GetLicensePlatesToExport() { _log.Info("Retrieving license plates to export"); int exportedCount = 0; var collectionLink = UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId); List<LicensePlateDataDocument> licensePlates; using (_client = new DocumentClient(new Uri(_endpointUrl), _authorizationKey)) { // MaxItemCount value tells the document query to retrieve 100 documents at a time until all are returned. // TODO 5: Retrieve a List of LicensePlateDataDocument objects from the collectionLink where the exported value is false. // COMPLETE: licensePlates = _client.CreateDocumentQuery ... // TODO 6: Remove the line below. licensePlates = new List<LicensePlateDataDocument>(); } exportedCount = licensePlates.Count(); _log.Info($"{exportedCount} license plates found that are ready for export"); return licensePlates; } /// <summary> /// Updates license plate records (documents) as exported. Call after successfully /// exporting the passed in license plates. /// In a production environment, it would be best to create a stored procedure that /// bulk updates the set of documents, vastly reducing the number of transactions. /// </summary> /// <param name="licensePlates"></param> /// <returns></returns> public async Task MarkLicensePlatesAsExported(IEnumerable<LicensePlateDataDocument> licensePlates) { _log.Info("Updating license plate documents exported values to true"); var collectionLink = UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId); using (_client = new DocumentClient(new Uri(_endpointUrl), _authorizationKey)) { foreach (var licensePlate in licensePlates) { licensePlate.exported = true; var response = await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_databaseId, _collectionId, licensePlate.Id), licensePlate); var updated = response.Resource; //_log.Info($"Exported value of updated document: {updated.GetPropertyValue<bool>("exported")}"); } } } } }
45.7375
159
0.662476
[ "MIT" ]
griffinbird/MCW-Serverless-architecture
Hands-on lab/starter/TollBooth/TollBooth/DatabaseMethods.cs
3,661
C#
namespace AltinnCore.Common.Models { using System; /// <summary> /// The service identifier. /// </summary> public class ServiceIdentifier : IEquatable<ServiceIdentifier> { /// <summary> Gets or sets the org. </summary> public string Org { get; set; } /// <summary> Gets or sets the service. </summary> public string Service { get; set; } /// <summary> Asserts that Org and Service got values. </summary> public bool Ok => !string.IsNullOrWhiteSpace(Org) && !string.IsNullOrWhiteSpace(Service); /// <summary> Checks equality. Case insensitive. </summary> /// <param name="other"> The other. </param> /// <returns> The <see cref="bool"/>. </returns> public bool Equals(ServiceIdentifier other) { return Org != null && Service != null && Org.Equals(other?.Org, StringComparison.CurrentCultureIgnoreCase) && Service.Equals(other?.Service, StringComparison.CurrentCultureIgnoreCase); } /// <summary> String representation of object. </summary> /// <returns> The <see cref="string"/>. </returns> public override string ToString() { return $"ServiceIdentifier[{Org}, {Service}]"; } } }
35.486486
97
0.588728
[ "BSD-3-Clause" ]
iotryti/altinn-studio
src/AltinnCore/Common/Models/ServiceIdentifier.cs
1,315
C#
using System; using Skybrud.Social.Google.YouTube.Options.Common; namespace Skybrud.Social.Google.YouTube.Exceptions { /// <summary> /// Exception class throw when a given string can't be parsed into an instance of <see cref="YouTubePart"/>. /// </summary> public class YouTubeUnknownPartException : Exception { #region Properties /// <summary> /// Gets the name of the part. /// </summary> public string PartName { get; } #endregion #region Constructors /// <summary> /// Initializes a new exception for the part with the specified <paramref name="partName"/>. /// </summary> /// <param name="partName">The name of the part.</param> public YouTubeUnknownPartException(string partName) : this(partName, "Property cannot be empty.") { } /// <summary> /// Initializes a new exception for the part with the specified <paramref name="partName"/>. /// </summary> /// <param name="partName">The name of the part.</param> /// <param name="message">The message of the exception.</param> public YouTubeUnknownPartException(string partName, string message) : base(message) { PartName = partName; } #endregion #region Member methods /// <inheritdoc /> public override string Message { get { string s = base.Message; if (string.IsNullOrEmpty(PartName) == false) { return s + Environment.NewLine + "Property name: " + PartName; } return s; } } #endregion } }
30.357143
112
0.575882
[ "MIT" ]
abjerner/Skybrud.Social.Google.YouTube
src/Skybrud.Social.Google.YouTube/Exceptions/YouTubeUnknownPartException.cs
1,702
C#
using System; namespace TCC.TeraCommon.Game { public struct Vector3f { public float X; public float Y; public float Z; public override string ToString() { return $"({X},{Y},{Z})"; } public float DistanceTo(Vector3f target) { double a = target.X - X; double b = target.Y - Y; double c = target.Z - Z; return (float) Math.Sqrt(a*a + b*b + c*c); } public Vector3f MoveForvard(Vector3f target, int speed, long time) { if (time == 0 || speed == 0) return this; var toGo = (float) speed*time/TimeSpan.TicksPerSecond; var distance = DistanceTo(target); if (toGo >= distance || distance == 0) return target; Vector3f result; result.X = X + (target.X - X)*toGo/distance; result.Y = Y + (target.Y - Y)*toGo/distance; result.Z = Z + (target.Z - Z)*toGo/distance; return result; } public Angle GetHeading(Vector3f target) { return new Angle((short) (Math.Atan2(target.Y - Y, target.X - X)*0x8000/Math.PI)); } } }
29
94
0.50821
[ "MIT" ]
sarisia/Tera-custom-cooldowns
TCC.Core/TeraCommon/Game/Vector3f.cs
1,220
C#
#region License /* Copyright © 2014-2021 European Support Limited 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. */ #endregion using Amdocs.Ginger.Common; using Amdocs.Ginger.CoreNET.Run.SolutionCategory; using Ginger.UserControls; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; namespace Ginger.SolutionCategories { /// <summary> /// Interaction logic for SolutionCategoryOptionalValuesEditPage.xaml /// </summary> public partial class SolutionCategoryOptionalValuesEditPage : Page { SolutionCategory mSolutionCategory; bool mEditWasDone = true; GenericWindow mWin; public SolutionCategoryOptionalValuesEditPage(SolutionCategory solutionCategory) { InitializeComponent(); mSolutionCategory = solutionCategory; InitGrid(); } private void InitGrid() { this.Title = mSolutionCategory.Category.ToString() + " " + "Category Optional Values"; GridViewDef view = new GridViewDef(GridViewDef.DefaultViewName); view.GridColsView = new ObservableList<GridColView>(); view.GridColsView.Add(new GridColView() { Field = nameof(SolutionCategoryValue.Value), WidthWeight = 10 }); xOptionalValuesGrid.SetAllColumnsDefaultView(view); xOptionalValuesGrid.InitViewItems(); //mParentObject.OptionalValuesList.PropertyChanged += mAMDP_PropertyChanged; xOptionalValuesGrid.btnAdd.AddHandler(Button.ClickEvent, new RoutedEventHandler(AddOptionalValue)); xOptionalValuesGrid.SetbtnDeleteHandler(btnDelete_Click); xOptionalValuesGrid.SetbtnClearAllHandler(btnClearAll_Click); xOptionalValuesGrid.SetbtnCopyHandler(BtnCopyClicked); xOptionalValuesGrid.SetbtnPastHandler(BtnPastClicked); xOptionalValuesGrid.DataSourceList = mSolutionCategory.CategoryOptionalValues; } private void btnClearAll_Click(object sender, RoutedEventArgs e) { mSolutionCategory.CategoryOptionalValues.Clear(); } private void AddOptionalValue(object sender, RoutedEventArgs e) { xOptionalValuesGrid.Grid.CommitEdit(DataGridEditingUnit.Row, true); SolutionCategoryValue newVal = new SolutionCategoryValue(string.Empty); mSolutionCategory.CategoryOptionalValues.Add(newVal); xOptionalValuesGrid.Grid.SelectedItem = newVal; xOptionalValuesGrid.Grid.CurrentItem = newVal; mEditWasDone = true; xOptionalValuesGrid.Grid.CommitEdit(DataGridEditingUnit.Row, true); } private void btnDelete_Click(object sender, RoutedEventArgs e) { List<SolutionCategoryValue> optionalValuesToRemove = new List<SolutionCategoryValue>(); foreach (SolutionCategoryValue selectedOV in xOptionalValuesGrid.Grid.SelectedItems) { optionalValuesToRemove.Add(selectedOV); } foreach (SolutionCategoryValue ov in optionalValuesToRemove) { mSolutionCategory.CategoryOptionalValues.RemoveItem(ov); mEditWasDone = true; } } List<SolutionCategoryValue> mCopiedItems = new List<SolutionCategoryValue>(); private void BtnCopyClicked(object sender, RoutedEventArgs e) { mCopiedItems.Clear(); foreach (SolutionCategoryValue cat in xOptionalValuesGrid.Grid.SelectedItems) { mCopiedItems.Add(cat); } } private void BtnPastClicked(object sender, RoutedEventArgs e) { foreach (SolutionCategoryValue cat in mCopiedItems) { SolutionCategoryValue newCopy= (SolutionCategoryValue)cat.CreateCopy(); newCopy.Value += "_Copy"; mSolutionCategory.CategoryOptionalValues.Add(newCopy); } } public bool ShowAsWindow(eWindowShowStyle windowStyle = eWindowShowStyle.Dialog) { Button OKButton = new Button(); OKButton.Content = "OK"; OKButton.Click += new RoutedEventHandler(OKButton_Click); this.Width = 300; this.Height = 300; GenericWindow.LoadGenericWindow(ref mWin, null, windowStyle, this.Title, this, new ObservableList<Button> { OKButton }, showClosebtn: false); return mEditWasDone; } private void OKButton_Click(object sender, RoutedEventArgs e) { xOptionalValuesGrid.Grid.CommitEdit(DataGridEditingUnit.Row, true); //remove empty rows for (int i = 0; i < xOptionalValuesGrid.Grid.Items.Count; i++) { SolutionCategoryValue cat = (SolutionCategoryValue)xOptionalValuesGrid.Grid.Items[i]; if (string.IsNullOrEmpty(cat.Value)) { mSolutionCategory.CategoryOptionalValues.Remove(cat); i--; } } xOptionalValuesGrid.Grid.CommitEdit(DataGridEditingUnit.Row, true); mWin.Close(); mSolutionCategory.PropertyChangedEventHandler(); } //string mOldValue = string.Empty; //bool mEditWasDone = false; //private void xOptionalValuesGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) //{ // mOldValue = ((SolutionCategoryValue)xOptionalValuesGrid.CurrentItem).Value; // mEditWasDone = true; //} //private void xOptionalValuesGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) //{ // SolutionCategoryValue currentOP = null; // if (e.Column.Header.ToString() == nameof(SolutionCategoryValue.Value)) // { // currentOP = (SolutionCategoryValue)xOptionalValuesGrid.CurrentItem; // } // if (currentOP != null) // { // if (mOldValue.Equals(GlobalAppModelParameter.CURRENT_VALUE)) // { // currentOP.Value = OldValue; // } // else // { // foreach (OptionalValue OP in mParentObject.OptionalValuesList) // { // if (OP != currentOP && OP.Value == currentOP.Value) // { // currentOP.Value = OldValue; // break; // } // } // } // } //} } }
37.609375
153
0.624567
[ "Apache-2.0" ]
Ginger-Automation/Ginger
Ginger/Ginger/SolutionCategories/SolutionCategoryOptionalValuesEditPage.xaml.cs
7,222
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Migrations.Model { using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Utilities; using System.Diagnostics.CodeAnalysis; using System.Linq; /// <summary> /// Represents changes made to custom annotations on a table. /// Entity Framework Migrations APIs are not designed to accept input provided by untrusted sources /// (such as the end user of an application). If input is accepted from such sources it should be validated /// before being passed to these APIs to protect against SQL injection attacks etc. /// </summary> public class AlterTableOperation : MigrationOperation, IAnnotationTarget { private readonly string _name; private readonly List<ColumnModel> _columns = new List<ColumnModel>(); private readonly IDictionary<string, AnnotationValues> _annotations; /// <summary> /// Initializes a new instance of the AlterTableOperation class. /// Entity Framework Migrations APIs are not designed to accept input provided by untrusted sources /// (such as the end user of an application). If input is accepted from such sources it should be validated /// before being passed to these APIs to protect against SQL injection attacks etc. /// </summary> /// <param name="name"> Name of the table on which annotations have changed. </param> /// <param name="annotations">The custom annotations on the table that have changed.</param> /// <param name="anonymousArguments"> /// Additional arguments that may be processed by providers. Use anonymous type syntax to /// specify arguments e.g. 'new { SampleArgument = "MyValue" }'. /// </param> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public AlterTableOperation(string name, IDictionary<string, AnnotationValues> annotations, object anonymousArguments = null) : base(anonymousArguments) { Check.NotEmpty(name, "name"); _name = name; _annotations = annotations ?? new Dictionary<string, AnnotationValues>(); } /// <summary> /// Gets the name of the table on which annotations have changed. /// </summary> public virtual string Name { get { return _name; } } /// <summary> /// Gets the columns to be included in the table for which annotations have changed. /// </summary> public virtual IList<ColumnModel> Columns { get { return _columns; } } /// <summary> /// Gets the custom annotations that have changed on the table. /// </summary> public virtual IDictionary<string, AnnotationValues> Annotations { get { return _annotations; } } /// <summary> /// Gets an operation that is the inverse of this one such that annotations will be changed back to how /// they were before this operation was applied. /// </summary> public override MigrationOperation Inverse { get { var inverse = new AlterTableOperation( Name, Annotations.ToDictionary(a => a.Key, a => new AnnotationValues(a.Value.NewValue, a.Value.OldValue))); inverse._columns.AddRange(_columns); return inverse; } } /// <inheritdoc /> public override bool IsDestructiveChange { get { return false; } } bool IAnnotationTarget.HasAnnotations { get { return Annotations.Any() || Columns.SelectMany(c => c.Annotations).Any(); } } } }
39.637255
132
0.621568
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EntityFramework/Migrations/Model/AlterTableOperation.cs
4,043
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace calculations { class Program { static void Main(string[] args) { double n = double.Parse(Console.ReadLine()); double secondNum = n * 4 - 4; double num = 0; num = secondNum/ 2; //num = Math.Round((n/secondNum),MidpointRounding.AwayFromZero); Console.WriteLine(secondNum); Console.WriteLine(num); } } }
23.869565
76
0.582878
[ "MIT" ]
1ooIL40/FundamentalsRepo
new project 02.18/calculations/calculations/Program.cs
551
C#
using Nethereum.JsonRpc.Client; //using Nethereum.JsonRpc.IpcClient; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Nethereum.JsonRpc.Client.Streaming; using Nethereum.RPC.Tests.Testers; using Nethereum.JsonRpc.WebSocketClient; using Nethereum.JsonRpc.WebSocketStreamingClient; namespace Nethereum.RPC.Tests { public class ClientFactory { public static IClient GetClient(TestSettings settings) { var url = settings.GetRPCUrl(); return new RpcClient(new Uri(url)); } //TODO:Subscriptions public static IStreamingClient GetStreamingClient(TestSettings settings) { var url = settings.GetLiveWSRpcUrl(); return new StreamingWebSocketClient(url); } } }
27.4
80
0.70438
[ "MIT" ]
6ara6aka/Nethereum
tests/Nethereum.RPC.IntegrationTests/ClientFactory.cs
824
C#
namespace Bog.Web.Dashboard.Areas.HelpPage { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Bog.Web.Dashboard.Areas.HelpPage.Models; /// <summary> /// The help page configuration extensions. /// </summary> public static class HelpPageConfigurationExtensions { #region Constants /// <summary> /// The api model prefix. /// </summary> private const string ApiModelPrefix = "MS_HelpPageApiModel_"; #endregion #region Public Methods and Operators /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and /// cached for subsequent calls. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="apiDescriptionId"> /// The <see cref="ApiDescription"/> ID. /// </param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault( api => string.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <returns> /// The help page sample generator. /// </returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator) config.Properties.GetOrAdd(typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the /// <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> public static void SetActualRequestType( this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator() .ActualHttpMessageTypes.Add( new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the /// <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> /// <param name="parameterNames"> /// The parameter names. /// </param> public static void SetActualRequestType( this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator() .ActualHttpMessageTypes.Add( new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the /// <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> public static void SetActualResponseType( this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator() .ActualHttpMessageTypes.Add( new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the /// <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> /// <param name="parameterNames"> /// The parameter names. /// </param> public static void SetActualResponseType( this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator() .ActualHttpMessageTypes.Add( new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="documentationProvider"> /// The documentation provider. /// </param> public static void SetDocumentationProvider( this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="sampleGenerator"> /// The help page sample generator. /// </param> public static void SetHelpPageSampleGenerator( this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="sample"> /// The sample. /// </param> /// <param name="mediaType"> /// The media type. /// </param> /// <param name="type"> /// The parameter type or return type of an action. /// </param> public static void SetSampleForType( this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="sampleObjects"> /// The sample objects. /// </param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="sample"> /// The sample request. /// </param> /// <param name="mediaType"> /// The media type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> public static void SetSampleRequest( this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator() .ActionSamples.Add( new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="sample"> /// The sample request. /// </param> /// <param name="mediaType"> /// The media type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> /// <param name="parameterNames"> /// The parameter names. /// </param> public static void SetSampleRequest( this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator() .ActionSamples.Add( new HelpPageSampleKey( mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="sample"> /// The sample response. /// </param> /// <param name="mediaType"> /// The media type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> public static void SetSampleResponse( this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator() .ActionSamples.Add( new HelpPageSampleKey( mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config"> /// The <see cref="HttpConfiguration"/>. /// </param> /// <param name="sample"> /// The sample response. /// </param> /// <param name="mediaType"> /// The media type. /// </param> /// <param name="controllerName"> /// Name of the controller. /// </param> /// <param name="actionName"> /// Name of the action. /// </param> /// <param name="parameterNames"> /// The parameter names. /// </param> public static void SetSampleResponse( this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator() .ActionSamples.Add( new HelpPageSampleKey( mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } #endregion #region Methods /// <summary> /// The generate api model. /// </summary> /// <param name="apiDescription"> /// The api description. /// </param> /// <param name="sampleGenerator"> /// The sample generator. /// </param> /// <returns> /// The <see cref="HelpPageApiModel"/>. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel( ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { var apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add( string.Format( CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } /// <summary> /// The log invalid sample as error. /// </summary> /// <param name="apiModel"> /// The api model. /// </param> /// <param name="sample"> /// The sample. /// </param> private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { var invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } #endregion } }
35.933468
124
0.526286
[ "MIT" ]
BankOfGiving/Bog.net
Bog.Web.Dashboard/Areas/HelpPage/HelpPageConfigurationExtensions.cs
17,823
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.IO; using Xunit; namespace Microsoft.Build.UnitTests.Framework { /// <summary> /// Tests for LazyFormattedEventArgs /// </summary> public class LazyFormattedEventArgs_Tests { #if FEATURE_CODETASKFACTORY /// <summary> /// Don't crash when task logs with too few format markers /// </summary> [Fact] public void DoNotCrashOnInvalidFormatExpression() { string content = @" <Project DefaultTargets=`t` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`http://schemas.microsoft.com/developer/msbuild/2003`> <UsingTask TaskName=`Crash` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)" + Path.DirectorySeparatorChar + @"Microsoft.Build.Tasks.Core.dll` > <Task> <Code Type=`Fragment` Language=`cs`> this.Log.LogError(`Correct: {0}`, `[goodone]`); this.Log.LogError(`This is a message logged from a task {1} blah blah [crashing].`, `[crasher]`); try { this.Log.LogError(`Correct: {0}`, 4224); this.Log.LogError(`Malformed: {1}`, 42); // Line 13 throw new InvalidOperationException(); } catch (Exception e) { this.Log.LogError(`Catching: {0}`, e.GetType().Name); } finally { this.Log.LogError(`Finally`); } try { this.Log.LogError(`Correct: {0}`, 4224); throw new InvalidOperationException(); } catch (Exception e) { this.Log.LogError(`Catching: {0}`, e.GetType().Name); this.Log.LogError(`Malformed: {1}`, 42); // Line 19 } finally { this.Log.LogError(`Finally`); } try { this.Log.LogError(`Correct: {0}`, 4224); throw new InvalidOperationException(); } catch (Exception e) { this.Log.LogError(`Catching: {0}`, e.GetType().Name); } finally { this.Log.LogError(`Finally`); this.Log.LogError(`Malformed: {1}`, 42); // Line 24 } </Code> </Task> </UsingTask> <Target Name=`t`> <Crash /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[goodone]"); log.AssertLogContains("[crashing]"); } #endif } }
29.926316
131
0.516356
[ "MIT" ]
0xced/msbuild
src/Build.OM.UnitTests/LazyFormattedEventArgs_Tests.cs
2,843
C#
//----------------------------------------------------------------------- // <copyright file="NullSerializer.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; namespace Akka.Serialization { /// <summary> /// This is a special <see cref="Serializer"/> that serializes and deserializes nulls only /// </summary> public class NullSerializer : Serializer { private static readonly byte[] nullBytes = {}; /// <summary> /// Initializes a new instance of the <see cref="NullSerializer" /> class. /// </summary> /// <param name="system">The actor system to associate with this serializer. </param> public NullSerializer(ExtendedActorSystem system) : base(system) { } /// <summary> /// Completely unique value to identify this implementation of the <see cref="Serializer"/> used to optimize network traffic /// </summary> public override int Identifier { get { return 0; } } /// <summary> /// Returns whether this serializer needs a manifest in the fromBinary method /// </summary> public override bool IncludeManifest { get { return false; } } /// <summary> /// Serializes the given object into a byte array /// </summary> /// <param name="obj">The object to serialize </param> /// <returns>A byte array containing the serialized object</returns> public override byte[] ToBinary(object obj) { return nullBytes; } /// <summary> /// Deserializes a byte array into an object of type <paramref name="type"/> /// </summary> /// <param name="bytes">The array containing the serialized object</param> /// <param name="type">The type of object contained in the array</param> /// <returns>The object contained in the array</returns> public override object FromBinary(byte[] bytes, Type type) { return null; } } }
34.573529
132
0.554232
[ "Apache-2.0" ]
corefan/akka.net
src/core/Akka/Serialization/NullSerializer.cs
2,353
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; using System.Text; using System.Threading.Tasks; using HitRefresh.GloVeWrapper.Models; namespace HitRefresh.GloVeWrapper.IO; /// <summary> /// input.PeekChar() != -1 /// </summary> public class BinaryGloveAccessor : IGloveAccessor, IDisposable { /// <summary> /// </summary> /// <param name="dictFile"></param> /// <param name="vecFile"></param> public BinaryGloveAccessor(string dictFile, string vecFile) { using var input = new BinaryReader(File.OpenRead(dictFile), Encoding.UTF8); var size = -1L; for (;;) try { var s = input.ReadString(); var offset = input.Read7BitEncodedInt64(); if (size <= 0) size = offset; Dictionary.TryAdd(s, offset); } catch (EndOfStreamException) { break; } BlockSize = size; var vecFs = Path.GetFullPath(vecFile); Vectors = MemoryMappedFile.CreateFromFile(File.OpenRead( vecFile), vecFile.Split("\\")[^1], 0, MemoryMappedFileAccess.Read, HandleInheritability.Inheritable, true); } private Dictionary<string, long> Dictionary { get; } = new(); private MemoryMappedFile Vectors { get; } private long BlockSize { get; } /// <inheritdoc /> public bool Contains(string word) { return Dictionary.ContainsKey(word); } /// <inheritdoc /> public IDoubleVector? this[string word] { get { if (!Contains(word)) return null; var offset = Dictionary[word]; using var br = new BinaryReader( Vectors.CreateViewStream(offset, BlockSize, MemoryMappedFileAccess.Read) ); return IGloveReader.ReadVec(BlockSize, br); } } /// <inheritdoc /> public async Task<IDoubleVector?> GetAsync(string word) { if (!Contains(word)) return null; return await Task.Run(() => { var offset = Dictionary[word]; using var br = new BinaryReader( Vectors.CreateViewStream(offset, BlockSize, MemoryMappedFileAccess.Read) ); return IGloveReader.ReadVec(BlockSize, br); }); } /// <inheritdoc /> public void Dispose() { Vectors.Dispose(); GC.SuppressFinalize(this); } }
27.714286
88
0.574148
[ "MIT" ]
HIT-ReFreSH/GloVeWrapper
src/IO/BinaryGloveAccessor.cs
2,524
C#
// // Copyright 2013 Hans Wolff // // 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.Reflection; 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("RedFoxMQ.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ca228c5d-87ad-48ca-9fc1-c70282b9f013")]
41.030303
84
0.757016
[ "Apache-2.0" ]
hanswolff/redfoxmq
RedFoxMQ.Tests/Properties/AssemblyInfo.cs
1,356
C#
using System; using System.Collections.Generic; using System.Text; namespace Test.Handlers { class DeleteAllSpecialistTestsHandler { } }
13.727273
41
0.741722
[ "MIT" ]
sunrise-solutions/Certification-Center
CertificationCenter/Test/Handlers/DeleteAllSpecialistTestsHandler.cs
153
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace MonoGame.Extended.TextureAtlases { public class NinePatchRegion2D : TextureRegion2D { public Rectangle[] SourcePatches { get; } = new Rectangle[9]; public Thickness Padding { get; } public int LeftPadding => Padding.Left; public int TopPadding => Padding.Top; public int RightPadding => Padding.Right; public int BottomPadding => Padding.Bottom; public NinePatchRegion2D(TextureRegion2D textureRegion, Thickness padding) : base(textureRegion.Name, textureRegion.Texture, textureRegion.X, textureRegion.Y, textureRegion.Width, textureRegion.Height) { Padding = padding; CachePatches(textureRegion.Bounds, SourcePatches); } public NinePatchRegion2D(TextureRegion2D textureRegion, int padding) : this(textureRegion, padding, padding, padding, padding) { } public NinePatchRegion2D(TextureRegion2D textureRegion, int leftRightPadding, int topBottomPadding) : this(textureRegion, leftRightPadding, topBottomPadding, leftRightPadding, topBottomPadding) { } public NinePatchRegion2D(TextureRegion2D textureRegion, int leftPadding, int topPadding, int rightPadding, int bottomPadding) : this(textureRegion, new Thickness(leftPadding, topPadding, rightPadding, bottomPadding)) { } public NinePatchRegion2D(Texture2D texture, Thickness thickness) : this(new TextureRegion2D(texture), thickness) { } public const int TopLeft = 0; public const int TopMiddle = 1; public const int TopRight = 2; public const int MiddleLeft = 3; public const int Middle = 4; public const int MiddleRight = 5; public const int BottomLeft = 6; public const int BottomMiddle = 7; public const int BottomRight = 8; private readonly Rectangle[] _destinationPatches = new Rectangle[9]; public Rectangle[] CreatePatches(Rectangle rectangle) { CachePatches(rectangle, _destinationPatches); return _destinationPatches; } private void CachePatches(Rectangle sourceRectangle, Rectangle[] patchCache) { var x = sourceRectangle.X; var y = sourceRectangle.Y; var w = sourceRectangle.Width; var h = sourceRectangle.Height; var middleWidth = w - LeftPadding - RightPadding; var middleHeight = h - TopPadding - BottomPadding; var bottomY = y + h - BottomPadding; var rightX = x + w - RightPadding; var leftX = x + LeftPadding; var topY = y + TopPadding; patchCache[TopLeft] = new Rectangle(x, y, LeftPadding, TopPadding); patchCache[TopMiddle] = new Rectangle(leftX, y, middleWidth, TopPadding); patchCache[TopRight] = new Rectangle(rightX, y, RightPadding, TopPadding); patchCache[MiddleLeft] = new Rectangle(x, topY, LeftPadding, middleHeight); patchCache[Middle] = new Rectangle(leftX, topY, middleWidth, middleHeight); patchCache[MiddleRight] = new Rectangle(rightX, topY, RightPadding, middleHeight); patchCache[BottomLeft] = new Rectangle(x, bottomY, LeftPadding, BottomPadding); patchCache[BottomMiddle] = new Rectangle(leftX, bottomY, middleWidth, BottomPadding); patchCache[BottomRight] = new Rectangle(rightX, bottomY, RightPadding, BottomPadding); } } }
43.47619
138
0.654436
[ "MIT" ]
Acidburn0zzz/MonoGame.Extended
Source/MonoGame.Extended/TextureAtlases/NinePatchRegion2D.cs
3,652
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // As informações gerais sobre um assembly são controladas através do seguinte // conjunto de atributos a seguir. Altere esses valores de atributo para modificar as informações // associadas a um assembly. [assembly: AssemblyTitle("AgenciaViagem_TCM")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AgenciaViagem_TCM")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Definir ComVisible como falso torna não visíveis os tipos neste assembly // para componentes COM. Caso precise acessar um tipo neste assembly a partir de // COM, defina o atributo ComVisible como true nesse tipo. [assembly: ComVisible(false)] // A GUID a seguir será referente à ID do typelib se este projeto for exposto ao COM [assembly: Guid("8aad06ce-16fd-4605-ad9a-62cf2c1d2b74")] // As informações de versão de um assembly consistem nos seguintes quatro valores: // // Versão Principal // Versão Secundária // Número da Versão // Revisão // // É possível especificar todos os valores ou definir como padrão os números de revisão e de versão // usando o '*' como mostrado abaixo: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.472222
99
0.761436
[ "MIT" ]
mikhailsb/Projeto_TCM_AgenciaViagem
AgenciaViagem_TCM/AgenciaViagem_TCM/Properties/AssemblyInfo.cs
1,449
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using NLog; using Project1.Domain.Interfaces; using Project1.Domain.Model; namespace Project1.DataAccess { public class Project1Repository : IProject1Repository { private readonly Project1Context _dbContext; private static readonly ILogger s_logger = LogManager.GetCurrentClassLogger(); //initializes a new Project0 Repository given an available Database public Project1Repository(Project1Context dbContext) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); } //Returns collection of Locations public IEnumerable<StoreLocation> GetLocations(string search = null) { IQueryable<StoreLocation> items = _dbContext.StoreLocation .Include(r => r.Product).Include(o => o.Orders).AsNoTracking(); if (search != null) { items = items.Include(o => o.Orders).Include(p => p.Product).Where(r => r.LocationName.Contains(search)); } return items.Select(Mapper.MapStoreLocationWithOrdersAndProduct); } //get location by id public StoreLocation GetLocationsById(int id) { return Mapper.MapStoreLocationWithOrdersAndProduct(_dbContext.StoreLocation.Include(o => o.Orders).Include(p => p.Product).First(l => l.Id == id)); } //Add a location public void AddLocation(StoreLocation storeLocation) { if (storeLocation.Id != 0) { //Identity insert will not allow us to change the Id s_logger.Warn($"Location to be added has an ID ({storeLocation.Id}) already: ignoring."); } s_logger.Info($"Adding location"); StoreLocation entity = Mapper.MapStoreLocationWithOrdersAndProduct(storeLocation); entity.Id = 0; _dbContext.Add(entity); } //Delete a Location by Id public void DeleteLocation(int locationId) { s_logger.Info($"Deleting location with ID {locationId}"); StoreLocation entity = _dbContext.StoreLocation.Find(locationId); _dbContext.Remove(entity); } //Update a Location public void UpdateLocation(StoreLocation storeLocation) { s_logger.Info($"Updating Location with ID {storeLocation.Id}"); StoreLocation currentEntity = _dbContext.StoreLocation.Include(o => o.Orders).Include(p => p.Product).First(r => r.Id == storeLocation.Id); StoreLocation newEntity = Mapper.MapStoreLocationWithOrdersAndProduct(storeLocation); //This marks only the changed properties as modified _dbContext.Entry(currentEntity).CurrentValues.SetValues(newEntity); } //Returns collection of Customers public IEnumerable<Customer> GetCustomers(string search = null) { IQueryable<Customer> items = _dbContext.Customer .Include(r => r.Orders).AsNoTracking(); if (search != null) { items = items.Include(o => o.Orders).Where(r => r.FirstName == search || r.LastName == search || r.FirstName+" "+r.LastName == search); } return items.Select(Mapper.MapCustomerWithOrders); } //get Customer by id public Customer GetCustomerById(int id) { return Mapper.MapCustomerWithOrders(_dbContext.Customer.Include(o => o.Orders).First(c => c.Id == id)); } //Add a Customer public void AddCustomer(Customer customer) { if (customer.Id != 0) { //Identity insert will not allow us to change the Id s_logger.Warn($"Customer to be added has an ID ({customer.Id}) already: ignoring."); } s_logger.Info($"Adding customer"); Customer entity = Mapper.MapCustomerWithOrders(customer); entity.Id = 0; _dbContext.Add(entity); } //Delete a Customer by Id public void DeleteCustomer(int customerId) { s_logger.Info($"Deleting Customer with ID {customerId}"); Customer entity = _dbContext.Customer.Find(customerId); _dbContext.Remove(entity); } //Update a Customer public void UpdateCustomer(Customer customer) { s_logger.Info($"Updating Customer with ID {customer.Id}"); Customer currentEntity = _dbContext.Customer.Include(r => r.Orders).First(c => c.Id == (customer.Id)); Customer newEntity = Mapper.MapCustomerWithOrders(customer); //This marks only the changed properties as modified _dbContext.Entry(currentEntity).CurrentValues.SetValues(newEntity); } //Returns collection of Orders public IEnumerable<Orders> GetOrders(string search = null) { IQueryable<Orders> items = _dbContext.Orders.Include(o=>o.StoreLocation).Include(o => o.Customer).Include(o => o.Product); if (search != null) { items = items.Where(r => r.Id == Int32.Parse(search)); } return items.Select(Mapper.Map); } //get Order by id public Orders GetOrderById(int id) { return Mapper.Map(_dbContext.Orders.Include(o => o.StoreLocation).Include(o => o.Customer).Include(o => o.Product).First(o=>o.Id == id)); } //Add a Order public void AddOrder(Orders order) { if (order.Id != 0) { //Identity insert will not allow us to change the Id s_logger.Warn($"Order to be added has an ID ({order.Id}) already: ignoring."); } s_logger.Info($"Adding Order"); Orders entity = Mapper.Map(order); entity.Id = 0; _dbContext.Add(entity); } //Delete a Order by Id public void DeleteOrder(int orderId) { s_logger.Info($"Deleting Order with ID {orderId}"); Orders entity = _dbContext.Orders.First(c=>c.Id==orderId); _dbContext.Remove(entity); } //Update a Order public void UpdateOrder(Orders order) { s_logger.Info($"Updating Order with ID {order.Id}"); Orders currentEntity = _dbContext.Orders.Include(o => o.StoreLocation).Include(o => o.Customer).Include(o => o.Product).First(c => c.Id == order.Id); Orders newEntity = Mapper.Map(order); //This marks only the changed properties as modified _dbContext.Entry(currentEntity).CurrentValues.SetValues(newEntity); } //Returns collection of Products public IEnumerable<Product> GetProducts(string search = null) { IQueryable<Product> items = _dbContext.Product; if (search != null) { items = items.Include(o => o.Orders).Where(r => r.Id == Int32.Parse(search)); } return items.Select(Mapper.Map); } //get Product by id public Product GetProductById(int id) { return Mapper.Map(_dbContext.Product.Include(o => o.Orders).First(p => p.Id == id)); } //Add a Product public void AddProduct(Product product) { if (product.Id != 0) { //Identity insert will not allow us to change the Id s_logger.Warn($"Product to be added has an ID ({product.Id}) already: ignoring."); } s_logger.Info($"Adding Order"); Product entity = Mapper.Map(product); entity.Id = 0; _dbContext.Add(entity); } //Delete a Product by Id public void DeleteProduct(int productId) { s_logger.Info($"Deleting Order with ID {productId}"); Product entity = _dbContext.Product.Find(productId); _dbContext.Remove(entity); } //Update a Product public void UpdateProduct(Product product) { s_logger.Info($"Updating Product with ID {product.Id}"); Product currentEntity = _dbContext.Product.Include(o => o.Orders).First(p=>p.Id == product.Id); Product newEntity = Mapper.Map(product); //This marks only the changed properties as modified _dbContext.Entry(currentEntity).CurrentValues.SetValues(newEntity); } //Persisting changes to database public void Save() { s_logger.Info("Saving changes to the database"); _dbContext.SaveChanges(); } //Provided by the Restaurant review example #region IDisposable Support private bool _disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _dbContext.Dispose(); } _disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } #endregion } }
37.566929
161
0.581953
[ "MIT" ]
2002-feb24-net/jacob-project1
Project1.DataAccess/Project1Repository.cs
9,544
C#
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using Aris.Moe.Ocr; using Aris.Moe.OverlayTranslate.Configuration; using Aris.Moe.OverlayTranslate.Server.AspNetCore; using Aris.Moe.OverlayTranslate.Server.Image; using Aris.Moe.Translate; using FluentResults; using FluentResults.Extensions.FluentAssertions; using Lamar; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace Aris.Moe.OverlayTranslate.Server.IntegrationTests { public class Sanity { private async Task<Container> PrepareContainer() { var container = new Container(x => { x.IncludeRegistry(new ApiRegistry(new ApiConfiguration { Database = new DatabaseConfiguration() })); x.For<ITranslate>().Use<DummyTranslate>(); x.For<IOcr>().Use<DummyOcr>(); x.For<IImageFetcher>().Use<DummyFetcher>(); x.For(typeof(ILogger<>)).Use(typeof(NullLogger<>)); }); var allOnStartup = container.GetAllInstances<IOnStartup>(); foreach (var onStartup in allOnStartup) await onStartup.OnStartup(); return container; } [Fact] public async Task Translate_WishHash_Success() { using var container = await PrepareContainer(); var analyzer = container.GetInstance<IImageAnalyser>(); var service = container.GetInstance<IOverlayTranslateServer>(); ImageInfo testImageInfo; // ReSharper disable once UseAwaitUsing using (var dummyImage = DummyFetcher.DummyImage()) testImageInfo = await analyzer.Analyse(dummyImage); var translationResult = await service.TranslatePublic(new PublicOcrTranslationRequest { ImageHash = testImageInfo.Sha256Hash, ImageUrl = "lel" }); translationResult.Should().NotBeNull().And.BeSuccess(); } [Fact] public async Task Translate_OnlyUrl_Success() { using var container = await PrepareContainer(); var analyzer = container.GetInstance<IImageAnalyser>(); var service = container.GetInstance<IOverlayTranslateServer>(); ImageInfo testImageInfo; // ReSharper disable once UseAwaitUsing using (var dummyImage = DummyFetcher.DummyImage()) testImageInfo = await analyzer.Analyse(dummyImage); var translationResult = await service.TranslatePublic(new PublicOcrTranslationRequest { ImageUrl = "lel", Height = testImageInfo.Height, Width = testImageInfo.Width, }); translationResult.Should().NotBeNull().And.BeSuccess(); } [Fact] public async Task Translate_SameImageDifferentUrls_Success() { using var container = await PrepareContainer(); var analyzer = container.GetInstance<IImageAnalyser>(); var service = container.GetInstance<IOverlayTranslateServer>(); ImageInfo testImageInfo; // ReSharper disable once UseAwaitUsing using (var dummyImage = DummyFetcher.DummyImage()) testImageInfo = await analyzer.Analyse(dummyImage); var translationResult = await service.TranslatePublic(new PublicOcrTranslationRequest { ImageUrl = "A", Height = testImageInfo.Height, Width = testImageInfo.Width, }); translationResult.Should().NotBeNull().And.BeSuccess(); var translationResult2 = await service.TranslatePublic(new PublicOcrTranslationRequest { ImageUrl = "B", Height = testImageInfo.Height, Width = testImageInfo.Width, }); translationResult2.Should().NotBeNull().And.BeSuccess(); } } public class DummyTranslate : ITranslate { public Task<IEnumerable<Translate.Translation>> Translate(IEnumerable<string> originals, string? targetLanguage = "en", string? inputLanguage = null) { var translations = new List<Translate.Translation> { new("Yay", "YAY") }; return Task.FromResult(translations.AsEnumerable()); } } public class DummyOcr : IOcr { public Task<(IEnumerable<ISpatialText> Texts, string Language)> Ocr(Stream image, string? inputLanguage = null) { var ocr = new List<ISpatialText>() { new Moe.Ocr.SpatialText("YAY", new Rectangle(10, 10, 10, 10)) }; return Task.FromResult((ocr.AsEnumerable(), "ja")); } } public class DummyFetcher : IImageFetcher { public Task<Result<Stream>> Get(string url) { return Task.FromResult(Result.Ok(DummyImage())); } public static Stream DummyImage() { return typeof(Sanity).Assembly.GetManifestResourceStream("Aris.Moe.OverlayTranslate.Server.IntegrationTests.test.jpg")!; } } }
34.641509
157
0.592229
[ "MIT" ]
Amiron49/Aris.Moe.Ocr.Translation.Overlay
Aris.Moe.OverlayTranslate.Server.IntegrationTests/Sanity.cs
5,508
C#
namespace DilMS_UI.Client.Areas.HelpPage.ModelDescriptions { public class CollectionModelDescription : ModelDescription { public ModelDescription ElementDescription { get; set; } } }
28.857143
64
0.752475
[ "Apache-2.0" ]
kwkau/DilMS-UI
DilMS-UI.Client/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs
202
C#
using System.Text.RegularExpressions; using CurlToCSharp.Extensions; namespace CurlToCSharp.Models.Parsing; public class ProxyParameterEvaluator : ParameterEvaluator { private static readonly Regex PortRegex = new Regex(@":\d+$", RegexOptions.Compiled); public ProxyParameterEvaluator() { Keys = new HashSet<string> { "-x", "--proxy" }; } protected override HashSet<string> Keys { get; } protected override void EvaluateInner(ref Span<char> commandLine, ConvertResult<CurlOptions> convertResult) { var value = commandLine.ReadValue(); // https://curl.se/docs/manpage.html#-x // No protocol specified or http:// will be treated as HTTP proxy. var uriString = value.ToString(); if (!uriString.Contains("://")) { uriString = "http://" + uriString; } if (!Uri.TryCreate(uriString, UriKind.Absolute, out Uri proxyUri)) { convertResult.Warnings.Add("Unable to parse proxy URI"); return; } // If the port number is not specified in the proxy string, it is assumed to be 1080. if (!PortRegex.IsMatch(proxyUri.OriginalString)) { proxyUri = new UriBuilder(proxyUri.Scheme, proxyUri.Host, 1080).Uri; } convertResult.Data.ProxyUri = proxyUri; } }
29.434783
111
0.634417
[ "MIT" ]
RuioWolf/curl-to-csharp
src/CurlToCSharp/Models/Parsing/ProxyParameterEvaluator.cs
1,354
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace eIVOGo.Module.SAM.Business { public partial class OrganizationList { /// <summary> /// pagingList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Uxnet.Web.Module.Ajax.PagingControl pagingList; /// <summary> /// EnterpriseGroupSelector control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::Uxnet.Web.Module.DataModel.ItemSelector EnterpriseGroupSelector; } }
33.5
90
0.51273
[ "MIT" ]
uxb2bralph/IFS-EIVO03
eIVOGo/Module/SAM/Business/OrganizationList.ascx.designer.cs
1,141
C#
namespace calendar { public static class StringExtensions { public static bool IsGreaterThan(this string first, string second) { return first.CompareTo(second) > 0; } public static string GetGreater(this string first, string second) { return first.IsGreaterThan(second) ? first : second; } public static bool IsLessThan(this string first, string second) { return first.CompareTo(second) < 0; } public static string GetLesser(this string first, string second) { return first.IsLessThan(second) ? first : second; } } }
27
74
0.594074
[ "MIT" ]
alexturcu/calendarmeetings
StringExtensions.cs
675
C#
namespace ServerKinect.Samples { partial class SettingServerKinect { /// <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() { this.checkBox1 = new System.Windows.Forms.CheckBox(); this.checkBox2 = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.trackBar1 = new System.Windows.Forms.TrackBar(); this.textBoxSlider = new System.Windows.Forms.TextBox(); this.videoControlSetting = new VideoControl(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.SuspendLayout(); // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Checked = true; this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox1.Location = new System.Drawing.Point(16, 46); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(82, 17); this.checkBox1.TabIndex = 0; this.checkBox1.Text = "All Skeleton"; this.checkBox1.UseVisualStyleBackColor = true; this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged); // // checkBox2 // this.checkBox2.AutoSize = true; this.checkBox2.Location = new System.Drawing.Point(16, 69); this.checkBox2.Name = "checkBox2"; this.checkBox2.Size = new System.Drawing.Size(105, 17); this.checkBox2.TabIndex = 1; this.checkBox2.Text = "Primary Skeleton"; this.checkBox2.UseVisualStyleBackColor = true; this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(13, 19); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(101, 13); this.label1.TabIndex = 2; this.label1.Text = "Skeleton Setting"; // // button1 // this.button1.Location = new System.Drawing.Point(192, 238); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(72, 27); this.button1.TabIndex = 3; this.button1.Text = "Apply"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(37, 19); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(216, 13); this.label2.TabIndex = 4; this.label2.Text = "Elevation Angle (only SDK Microsoft)"; // // trackBar1 // this.trackBar1.LargeChange = 1; this.trackBar1.Location = new System.Drawing.Point(12, 46); this.trackBar1.Maximum = 27; this.trackBar1.Minimum = -27; this.trackBar1.Name = "trackBar1"; this.trackBar1.Orientation = System.Windows.Forms.Orientation.Vertical; this.trackBar1.Size = new System.Drawing.Size(45, 129); this.trackBar1.TabIndex = 1; this.trackBar1.TickStyle = System.Windows.Forms.TickStyle.Both; this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll); // // textBoxSlider // this.textBoxSlider.BackColor = System.Drawing.SystemColors.Info; this.textBoxSlider.Enabled = false; this.textBoxSlider.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBoxSlider.Location = new System.Drawing.Point(12, 181); this.textBoxSlider.Name = "textBoxSlider"; this.textBoxSlider.Size = new System.Drawing.Size(40, 26); this.textBoxSlider.TabIndex = 5; this.textBoxSlider.Text = "0"; this.textBoxSlider.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // videoControlSetting // this.videoControlSetting.BackColor = System.Drawing.SystemColors.ActiveCaption; this.videoControlSetting.Location = new System.Drawing.Point(70, 46); this.videoControlSetting.Name = "videoControlSetting"; this.videoControlSetting.Size = new System.Drawing.Size(210, 157); this.videoControlSetting.Stretch = false; this.videoControlSetting.TabIndex = 6; // // splitContainer1 // this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.splitContainer1.Location = new System.Drawing.Point(12, 12); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.label1); this.splitContainer1.Panel1.Controls.Add(this.checkBox1); this.splitContainer1.Panel1.Controls.Add(this.checkBox2); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.videoControlSetting); this.splitContainer1.Panel2.Controls.Add(this.textBoxSlider); this.splitContainer1.Panel2.Controls.Add(this.label2); this.splitContainer1.Panel2.Controls.Add(this.trackBar1); this.splitContainer1.Size = new System.Drawing.Size(447, 220); this.splitContainer1.SplitterDistance = 149; this.splitContainer1.TabIndex = 7; // // SettingServerKinect // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(469, 272); this.Controls.Add(this.splitContainer1); this.Controls.Add(this.button1); this.Name = "SettingServerKinect"; this.Text = "SettingServerKinect"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SettingServerKinect_FormClosing); ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit(); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel1.PerformLayout(); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.Panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.CheckBox checkBox1; private System.Windows.Forms.CheckBox checkBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TrackBar trackBar1; private System.Windows.Forms.TextBox textBoxSlider; private VideoControl videoControlSetting; private System.Windows.Forms.SplitContainer splitContainer1; } }
49.534031
174
0.598457
[ "BSD-3-Clause" ]
mcassola/ServerKinect
ServerKinect/Samples/SettingServerKinect.Designer.cs
9,463
C#
using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace Plasma_Rev { public class Map { public Player player = new Player(0, 0); public List<Chunk> loadedChunks = new List<Chunk>(); public Map() { player = new Player(0, 0); checkChunks(); } public Map(Player newPlayer) { player = newPlayer; checkChunks(); } public void checkChunks() { int playerChunkX = MathHelper.fastFloor(player.posX / (double)Ref.tileAmountX); int playerChunkY = MathHelper.fastFloor(player.posY / (double)Ref.tileAmountY); /** Unload chunks */ unloadChunks(playerChunkX, playerChunkY); /** Load chunks */ loadChunks(playerChunkX, playerChunkY); } public void Draw(SpriteBatch spriteBatch) { loadedChunks.ForEach(chunk => chunk.Draw(spriteBatch)); } private void unloadChunks(int playerChunkX, int playerChunkY) { Chunk chunk = new Chunk(0, 0); loadedChunks.ForEach(thisChunk => chunk = thisChunk); if(chunk.chunkX > playerChunkX + (Ref.chunkAmountX - 1) / 2 || chunk.chunkX < playerChunkX - (Ref.chunkAmountX - 1) / 2 || chunk.chunkY > playerChunkY + (Ref.chunkAmountY - 1) / 2 || chunk.chunkY < playerChunkY - (Ref.chunkAmountY -1) / 2) loadedChunks.Remove(chunk); } private void loadChunks(int playerChunkX, int playerChunkY) { for (int x = playerChunkX - (Ref.chunkAmountX - 1) / 2; x <= playerChunkX + (Ref.chunkAmountX - 1) / 2; x++) { for (int y = playerChunkY - (Ref.chunkAmountY - 1) / 2; y <= playerChunkY + (Ref.chunkAmountY - 1) / 2; y++) { if (!loadedChunks.Contains(new Chunk(x, y))) { Chunk chunk = new Chunk(x, y); chunk.populate(); loadedChunks.Add(chunk); } } } } } }
31.955882
252
0.525541
[ "MIT" ]
aliostad/deep-learning-lang-detection
data/train/csharp/493242011415cf4bd84b970f1f0bf10d98ae5044Map.cs
2,175
C#
//////////////////////////////////////////////////////////////////////////////// //EF Core Provider for LCPI OLE DB. // IBProvider and Contributors. 06.10.2021. using System; using System.Diagnostics; using System.Reflection; namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D0.Expressions.Op2.Code{ //////////////////////////////////////////////////////////////////////////////// //using using T_ARG1 =System.DateTime; using T_ARG2 =System.Nullable<System.DateTime>; using T_RESULT =System.Nullable<System.TimeSpan>; //////////////////////////////////////////////////////////////////////////////// //class Op2_Code__Subtract___DateTime__NullableDateTime static class Op2_Code__Subtract___DateTime__NullableDateTime { public static readonly System.Reflection.MethodInfo MethodInfo_V_V =typeof(Op2_Code__Subtract___DateTime__NullableDateTime) .GetTypeInfo() .GetDeclaredMethod(nameof(Exec_V_V)); //----------------------------------------------------------------------- private static T_RESULT Exec_V_V(T_ARG1 a,T_ARG2 b) { if(!b.HasValue) return null; Debug.Assert(b.HasValue); return D0.Expressions.Op2.MasterCode.Op2_MasterCode__Subtract___DateTime__DateTime.Exec (a, b.Value); }//Exec_V_V };//class Op2_Code__Subtract___DateTime__NullableDateTime //////////////////////////////////////////////////////////////////////////////// }//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D0.Expressions.Op2.Code
33.708333
130
0.583436
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Code/Provider/Source/Basement/EF/Dbms/Firebird/V03_0_0/Query/Local/D0/Expressions/Op2/Code/Subtract/DateTime/Op2_Code__Subtract___DateTime__NullableDateTime.cs
1,620
C#
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; using BrainyStories.Objects; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using BrainyStories.RealmObjects; using Realms; namespace BrainyStories { // Story class used for each story // We can't have child classes for the Story and Imagines from a common base class- this isn't supported by Ralm public class Story : RealmObject { public string StoryId { get; private set; } = Guid.NewGuid().ToString(); // String of the name of story public String Name { get; set; } //TODO: should this be ImageSource? // string link to the image public string Icon { get; set; } // String of a short description of the story public String Description { get; set; } // Appeal type for colored dots //this has to be an int to be added to Realm since enum's aren't supported public int Appeal { get; set; } //String for audio file public String AudioClip { get; set; } // Timespan for the duration of the story public double DurationInSeconds { get; set; } //this is necessary because Realm doesn't support timespan [Ignored] public TimeSpan DurationInTimeSpan { get { return new TimeSpan(hours: 0, minutes: 0, seconds: (int)DurationInSeconds); } } public int WordCount { get; set; } /// <summary> /// This allows us to easily separate out the imagines, stories, and alternate story sets. Realm requires /// us to save this as an int /// </summary> public int StorySet { get; private set; } [Ignored] public StorySet StorySetAsEnum { get { return (RealmObjects.StorySet)StorySet; } set { StorySet = (int)value; } } // TODO: give the quiz object a FK reference to a story //public int QuizNum { get; set; } = 0; // Dictionary of cues for quizzes to quizzes //public Dictionary<TimeSpan, Quiz> QuizCues { get; set; } //TODO: replace with a FK reference to the Quiz object // Observable Collection of associated Quizzes //public ObservableCollection<Quiz> Quizzes { get; set; } = new ObservableCollection<Quiz>(); // Int for the nNumber of quizzes that have been completed //public int NumCompletedQuizzes { get { return Quizzes.Count(q => q.NumAttemptsQuiz > 0); } } ////List of Icon Images //public ICollection<String> ListOfIcons { get; set; } } }
31.954023
116
0.605755
[ "MIT" ]
BrainyEducation/Novelidea
BrainyStories/BrainyStories/BrainyStories/RealmObjects/Story.cs
2,782
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using ProjectRestaurant.Data; namespace ProjectRestaurant.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20201217134016_AddNumberOfPeopleInReservationModel")] partial class AddNumberOfPeopleInReservationModel { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.1"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.ApplicationRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("Address") .IsRequired() .HasMaxLength(80) .HasColumnType("nvarchar(80)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(20) .HasColumnType("nvarchar(20)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(20) .HasColumnType("nvarchar(20)"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasMaxLength(20) .HasColumnType("nvarchar(20)"); b.HasKey("Id"); b.ToTable("Categories"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<double>("Price") .HasColumnType("float"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.ToTable("Events"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.EventImage", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<int>("EventId") .HasColumnType("int"); b.Property<string>("Extension") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("RemoteImageUrl") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("EventId") .IsUnique(); b.ToTable("EventImages"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.MenuImage", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<string>("Extension") .HasColumnType("nvarchar(max)"); b.Property<int>("MenuItemId") .HasColumnType("int"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("RemoteImageUrl") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("MenuItemId") .IsUnique(); b.ToTable("MenuImages"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.MenuItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("CategoryId") .HasColumnType("int"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<string>("Description") .IsRequired() .HasMaxLength(1500) .HasColumnType("nvarchar(1500)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasMaxLength(40) .HasColumnType("nvarchar(40)"); b.Property<double>("PortionWeight") .HasColumnType("float"); b.Property<double>("Price") .HasColumnType("float"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.HasIndex("IsDeleted"); b.ToTable("MenuItems"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Rating", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<string>("Description") .IsRequired() .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<int>("Star") .HasColumnType("int"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("UserId") .IsUnique() .HasFilter("[UserId] IS NOT NULL"); b.ToTable("Ratings"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Reservation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime>("DateAndTimeOfReservation") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Message") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<int>("NumberOfPeople") .HasColumnType("int"); b.Property<int>("TableId") .HasColumnType("int"); b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("TableId"); b.HasIndex("UserId"); b.ToTable("Reservations"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Subscribe", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<string>("Email") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Subscribes"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Table", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<int>("NumberOfSeats") .HasColumnType("int"); b.Property<string>("ShapeOfTable") .IsRequired() .HasMaxLength(10) .HasColumnType("nvarchar(10)"); b.Property<int>("TableNumber") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.ToTable("Tables"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("ProjectRestaurant.Data.Models.ApplicationRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("ProjectRestaurant.Data.Models.ApplicationUser", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("ProjectRestaurant.Data.Models.ApplicationUser", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("ProjectRestaurant.Data.Models.ApplicationRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("ProjectRestaurant.Data.Models.ApplicationUser", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("ProjectRestaurant.Data.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.EventImage", b => { b.HasOne("ProjectRestaurant.Data.Models.Event", "Event") .WithOne("EventImage") .HasForeignKey("ProjectRestaurant.Data.Models.EventImage", "EventId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Event"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.MenuImage", b => { b.HasOne("ProjectRestaurant.Data.Models.MenuItem", "MenuItem") .WithOne("MenuImage") .HasForeignKey("ProjectRestaurant.Data.Models.MenuImage", "MenuItemId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("MenuItem"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.MenuItem", b => { b.HasOne("ProjectRestaurant.Data.Models.Category", "Category") .WithMany("MenuItem") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Category"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Rating", b => { b.HasOne("ProjectRestaurant.Data.Models.ApplicationUser", "User") .WithOne("Rating") .HasForeignKey("ProjectRestaurant.Data.Models.Rating", "UserId"); b.Navigation("User"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Reservation", b => { b.HasOne("ProjectRestaurant.Data.Models.Table", "Table") .WithMany("Reservations") .HasForeignKey("TableId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("ProjectRestaurant.Data.Models.ApplicationUser", "User") .WithMany("Reservations") .HasForeignKey("UserId"); b.Navigation("Table"); b.Navigation("User"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.ApplicationUser", b => { b.Navigation("Claims"); b.Navigation("Logins"); b.Navigation("Rating"); b.Navigation("Reservations"); b.Navigation("Roles"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Category", b => { b.Navigation("MenuItem"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Event", b => { b.Navigation("EventImage"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.MenuItem", b => { b.Navigation("MenuImage"); }); modelBuilder.Entity("ProjectRestaurant.Data.Models.Table", b => { b.Navigation("Reservations"); }); #pragma warning restore 612, 618 } } }
35.51046
95
0.437493
[ "MIT" ]
VasilUzunov/ProjectRestaurant
Data/ProjectRestaurant.Data/Migrations/20201217134016_AddNumberOfPeopleInReservationModel.Designer.cs
25,463
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MijnSauna.Backend.Api.Common; using MijnSauna.Backend.Logic.Interfaces; using MijnSauna.Common.DataTransferObjects.Logs; namespace MijnSauna.Backend.Api.Controllers { [Route("logs")] [ApiController] public class LogsController : ApiController<ILogLogic> { public LogsController( ILogLogic logLogic, ILogger<ILogLogic> logger) : base(logLogic, logger) { } [HttpPost("info")] public Task<IActionResult> LogInformation([FromBody] LogInformationRequest request) { return Execute(l => l.LogInformation(request)); } [HttpPost("error")] public Task<IActionResult> LogError([FromBody] LogErrorRequest request) { return Execute(l => l.LogError(request)); } } }
29.966667
91
0.669633
[ "Unlicense" ]
Djohnnie/BuildCloudNativeApplicationsWithDotNet5-DotNetDeveloperDays-2020
mijnsauna/MijnSauna.Backend.Api/Controllers/LogsController.cs
901
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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client { internal static class HostLanguageServicesExtensions { public static TLanguageService GetOriginalLanguageService<TLanguageService>(this HostLanguageServices languageServices) where TLanguageService : class, ILanguageService => languageServices.GetOriginalLanguageServices().GetService<TLanguageService>(); public static HostLanguageServices GetOriginalLanguageServices(this HostLanguageServices languageServices) { var language = languageServices.Language; string originalLanguage; switch (language) { case StringConstants.CSharpLspLanguageName: originalLanguage = LanguageNames.CSharp; break; case StringConstants.VBLspLanguageName: originalLanguage = LanguageNames.VisualBasic; break; default: // Unknown language. return null; } return languageServices.WorkspaceServices.GetLanguageServices(originalLanguage); } } }
39.405405
176
0.672154
[ "MIT" ]
Jay-Madden/roslyn
src/VisualStudio/LiveShare/Impl/Client/HostLanguageServicesExtensions.cs
1,460
C#
using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.Controllers; namespace Swashbuckle.AspNetCore.SwaggerGen { public static class ApiDescriptionExtensions { public static bool TryGetMethodInfo(this ApiDescription apiDescription, out MethodInfo methodInfo) { var controllerActionDescriptor = apiDescription.ActionDescriptor as ControllerActionDescriptor; methodInfo = controllerActionDescriptor?.MethodInfo; return (methodInfo != null); } public static void GetAdditionalMetadata( this ApiDescription apiDescription, out MethodInfo methodInfo, out IEnumerable<object> methodAttributes) { methodAttributes = Enumerable.Empty<object>(); if (apiDescription.TryGetMethodInfo(out methodInfo)) { methodAttributes = methodInfo.GetCustomAttributes(true) .Union(methodInfo.DeclaringType.GetCustomAttributes(true)); } } internal static string RelativePathSansQueryString(this ApiDescription apiDescription) { return apiDescription.RelativePath.Split('?').First(); } internal static bool IsObsolete(this ApiDescription apiDescription) { apiDescription.GetAdditionalMetadata(out MethodInfo methodInfo, out IEnumerable<object> methodAttributes); return methodAttributes.OfType<ObsoleteAttribute>().Any(); } } }
34.489362
118
0.682295
[ "MIT" ]
AndrewJByrne/Swashbuckle.AspNetCore
src/Swashbuckle.AspNetCore.SwaggerGen/Generator/ApiDescriptionExtensions.cs
1,623
C#
using OpenTK.Graphics.OpenGL; using Ryujinx.Common.Logging; using Ryujinx.Graphics.GAL; using Ryujinx.Graphics.OpenGL.Image; using Ryujinx.Graphics.OpenGL.Queries; using Ryujinx.Graphics.Shader; using System; namespace Ryujinx.Graphics.OpenGL { public sealed class Renderer : IRenderer { private readonly Pipeline _pipeline; public IPipeline Pipeline => _pipeline; private readonly Counters _counters; private readonly Window _window; public IWindow Window => _window; internal TextureCopy TextureCopy { get; } public string GpuVendor { get; private set; } public string GpuRenderer { get; private set; } public string GpuVersion { get; private set; } public Renderer() { _pipeline = new Pipeline(); _counters = new Counters(); _window = new Window(this); TextureCopy = new TextureCopy(this); } public IShader CompileShader(ShaderProgram shader) { return new Shader(shader); } public BufferHandle CreateBuffer(int size) { return Buffer.Create(size); } public IProgram CreateProgram(IShader[] shaders, TransformFeedbackDescriptor[] transformFeedbackDescriptors) { return new Program(shaders, transformFeedbackDescriptors); } public ISampler CreateSampler(SamplerCreateInfo info) { return new Sampler(info); } public ITexture CreateTexture(TextureCreateInfo info, float scaleFactor) { return info.Target == Target.TextureBuffer ? new TextureBuffer(info) : new TextureStorage(this, info, scaleFactor).CreateDefaultView(); } public void DeleteBuffer(BufferHandle buffer) { Buffer.Delete(buffer); } public byte[] GetBufferData(BufferHandle buffer, int offset, int size) { return Buffer.GetData(buffer, offset, size); } public Capabilities GetCapabilities() { return new Capabilities( HwCapabilities.SupportsAstcCompression, HwCapabilities.SupportsImageLoadFormatted, HwCapabilities.SupportsNonConstantTextureOffset, HwCapabilities.SupportsViewportSwizzle, HwCapabilities.MaximumComputeSharedMemorySize, HwCapabilities.MaximumSupportedAnisotropy, HwCapabilities.StorageBufferOffsetAlignment); } public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data) { Buffer.SetData(buffer, offset, data); } public void UpdateCounters() { _counters.Update(); } public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler) { return _counters.QueueReport(type, resultHandler); } public void Initialize() { PrintGpuInformation(); _counters.Initialize(); } private void PrintGpuInformation() { GpuVendor = GL.GetString(StringName.Vendor); GpuRenderer = GL.GetString(StringName.Renderer); GpuVersion = GL.GetString(StringName.Version); Logger.PrintInfo(LogClass.Gpu, $"{GpuVendor} {GpuRenderer} ({GpuVersion})"); } public void ResetCounter(CounterType type) { _counters.QueueReset(type); } public void Dispose() { TextureCopy.Dispose(); _pipeline.Dispose(); _window.Dispose(); _counters.Dispose(); } } }
29.100775
147
0.609483
[ "MIT" ]
Supa604/Ryujinx
Ryujinx.Graphics.OpenGL/Renderer.cs
3,756
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IManagedDeviceUpdateWindowsDeviceAccountRequest. /// </summary> public partial interface IManagedDeviceUpdateWindowsDeviceAccountRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> ManagedDeviceUpdateWindowsDeviceAccountRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task PostAsync( CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IManagedDeviceUpdateWindowsDeviceAccountRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IManagedDeviceUpdateWindowsDeviceAccountRequest Select(string value); } }
33.746032
153
0.594544
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IManagedDeviceUpdateWindowsDeviceAccountRequest.cs
2,126
C#
ILogger logger = new ConsoleLogger(); logger.Log("message"); logger.Log(new Exception("sample exception")); IEnumerableEx<string> names = new MyCollection<string> { "James", "Jack", "Jochen", "Sebastian", "Lewis", "Juan" }; var jNames = names.Where(n => n.StartsWith("J")); foreach (var name in jNames) { Console.WriteLine(name); }
30.727273
115
0.689349
[ "MIT" ]
christiannagel/ProfessionalCSharp2021
1_CS/ObjectOrientation/DefaultInterfaceMethods/Program.cs
340
C#
namespace TeraPacketParser.TeraCommon.Game { public class Server { public Server(string name, string region, string ip, uint serverId = uint.MaxValue) { Ip = ip; Name = name; Region = region; ServerId = serverId; } public string Ip { get; private set; } public string Name { get; private set; } public string Region { get; private set; } public uint ServerId { get; private set; } public override string ToString() { return $"[{Region}/{ServerId}] {Name} @ {Ip}"; } } }
27.130435
91
0.535256
[ "MIT" ]
Foglio1024/Tera-custom-cooldowns
TeraPacketParser/TeraCommon/Game/Server.cs
626
C#
using BackEndServer.Models.ViewModels; using MySql.Data.MySqlClient; namespace BackEndServer.Models.DBModels { public class DatabaseRoom { // Table Name public static readonly string TABLE_NAME = "room"; // Attributes of Room table. public static readonly string ROOM_ID_LABEL = "id"; public static readonly string LOCATION_ID_LABEL = "Location_id"; public static readonly string ROOM_NAME_LABEL = "room_name"; public int RoomId { get; set; } public int LocationId { get; set; } public string RoomName { get; set; } public DatabaseRoom() { } public DatabaseRoom(CameraDetails cameraDetails) { LocationId = cameraDetails.LocationId; RoomName = cameraDetails.NewRoomName; } public DatabaseRoom(RoomInfo roomInfo) { RoomId = roomInfo.RoomId; LocationId = roomInfo.LocationId; RoomName = roomInfo.RoomName; } public void EscapeStringFields() { if (RoomName != null) RoomName = MySqlHelper.EscapeString(RoomName); } } }
28.880952
72
0.592745
[ "MIT" ]
Loriko/group2049-project
BackEnd/BackEndServer/Models/DBModels/DatabaseRoom.cs
1,215
C#
using System.Collections.Generic; using App.Metrics; using App.Metrics.Formatters.Wavefront; using Moq; using Wavefront.SDK.CSharp.Common; using Wavefront.SDK.CSharp.Common.Metrics; using Wavefront.SDK.CSharp.Entities.Histograms; using Xunit; namespace Wavefront.AppMetrics.SDK.CSharp.Test { public class MetricSnapshotWavefrontWriterTest { private readonly Mock<IWavefrontSender> wfSenderMock = new Mock<IWavefrontSender>(); private readonly MetricSnapshotWavefrontWriter writer; public MetricSnapshotWavefrontWriterTest() { var wfSender = wfSenderMock.Object; var globalTags = new Dictionary<string, string> { { "globalKey1", "globalVal1" }, { "globalKey2", "globalVal2" } }; var histogramGranularities = new HashSet<HistogramGranularity> { HistogramGranularity.Minute }; var sdkMetricsRegistry = new WavefrontSdkMetricsRegistry.Builder(wfSender).Build(); writer = new MetricSnapshotWavefrontWriter(wfSender, "source", globalTags, histogramGranularities, sdkMetricsRegistry, new MetricFields()); } [Fact] public void TestFilterTags() { var metricTags = new MetricTags( new string[] { "globalKey1", "env", "location", "env" }, new string[] { "pointValue1", "dev", "sf", "prod" }); // Verify that global and point tags are included, and duplicate tag keys are handled. IDictionary<string, string> filteredTags = writer.FilterTags(metricTags); Assert.Equal(4, filteredTags.Count); Assert.Contains("globalKey1", filteredTags); Assert.Contains("globalKey2", filteredTags); Assert.Contains("env", filteredTags); Assert.Contains("location", filteredTags); // Verify that point tag value overrides global tag value Assert.Equal("pointValue1", filteredTags["globalKey1"]); } } }
40.615385
99
0.625473
[ "Apache-2.0" ]
wavefrontHQ/wavefront-appmetrics-csharp-sdk
test/Wavefront.AppMetrics.SDK.CSharp.Test/MetricSnapshotWavefrontWriterTest.cs
2,112
C#
using System; using System.Linq; using Engine.Application; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SharedApplication; using Textrude; namespace Tests { [TestClass] public class TextrudeCliTests { [TestMethod] public void SimpleRenderPass() { AddTemplate("some text"); Run(); } [TestMethod] public void ThrowsWhenCantReadTemplate() { _options.Template = "nofile"; Action act = Run; act.Should().Throw<ApplicationException>().WithMessage("*missing*nofile*"); } [TestMethod] public void ProvidesCorrectFileNameInErrorMessageWhenFileNonExistent() { _options.Models = _options.Models.Append(Name("model", "elusive.json")).ToArray(); AddTemplate("{{model.A}} ddd"); Action act = Run; act.Should().Throw<ApplicationException>().WithMessage("*elusive.json*"); } [TestMethod] public void ProvidesCorrectFileNameInErrorMessageWhenReadFault() { var problemFile = "unreadable.json"; AddModel(problemFile, "abcd"); _fileSystem.ThrowOnRead(problemFile); AddTemplate("{{model.A}} ddd"); Action act = Run; act.Should().Throw<ApplicationException>().WithMessage($"*{problemFile}*"); } [TestMethod] public void SimpleModelGeneratesOutput() { AddModel(ModelFile, "A: 123"); AddTemplate("{{model.A}} ddd"); AddOutputFile(OutputFile); Run(); _fileSystem.ReadAllText(OutputFile) .Should().Be("123 ddd"); } [TestMethod] public void NamedModelsAreUnderstood() { AddModel("test", ModelFile, "A: 123"); AddTemplate("{{test.A}} ddd"); AddOutputFile(OutputFile); Run(); _fileSystem.ReadAllText(OutputFile) .Should().Be("123 ddd"); } [TestMethod] public void NamedOutputsAreUnderstood() { AddModel(ModelFile, "A: 123"); AddTemplate("{{capture testOut}}hello{{end}} "); AddOutputFile("testOut", OutputFile); Run(); _fileSystem.ReadAllText(OutputFile) .Should().Be("hello"); } [TestMethod] public void DynamicOutputsAreUnderstood() { AddModel(ModelFile, "A: 123"); AddTemplate(@" {{ capture xout ""this is the value of x"" end textrude.add_output this ""abc.txt"" xout }} "); UseDynamicOutput(); Run(); _fileSystem.ReadAllText("abc.txt") .Should().Be("this is the value of x"); } [TestMethod] public void EmptyDynamicOutputsDoNotCrash() { AddModel(ModelFile, "A: 123"); AddTemplate(@""); UseDynamicOutput(); Run(); } [TestMethod] public void WhenLazyEngineDoesNotRunUnlessInputTouched() { _options.Lazy = true; AddModel(ModelFile, "A: 123"); AddTemplate("{{model.A}}"); AddOutputFile(OutputFile); //create this last so that it post-dates the input _fileSystem.WriteAllText(OutputFile, string.Empty); Run(); _fileSystem.ReadAllText(OutputFile).Should().BeEmpty(); _fileSystem.Touch(ModelFile); Run(); _fileSystem.ReadAllText(OutputFile).Should().Be("123"); _fileSystem.WriteAllText(TemplateFile, "abc"); Run(); _fileSystem.ReadAllText(OutputFile).Should().Be("abc"); } [TestMethod] public void WhenLazyEngineRunsIfOutputDoesNotExist() { _options.Lazy = true; AddModel(ModelFile, "A: 123"); AddTemplate("{{model.A}}"); AddOutputFile(OutputFile); Run(); _fileSystem.ReadAllText(OutputFile).Should().Be("123"); } #region helper methods private const string ModelFile = "model.yaml"; private const string OutputFile = "output.txt"; private const string TemplateFile = "template.sbn"; private readonly MockFileSystem _fileSystem = new(); private readonly MockFileSystem _mockWeb = new(); private readonly Helpers _helper = new() { ExitHandler = msg => throw new ApplicationException(msg) }; private readonly RenderOptions _options = new(); private void Run() { var hybrid = new HybridFileSystem(_fileSystem, _mockWeb); CmdRender.Run(_options, new RunTimeEnvironment(hybrid), _helper); } private void UseDynamicOutput() { _options.DynamicOutput = true; } private void AddTemplate(string someText) { _fileSystem.WriteAllText(TemplateFile, someText); _options.Template = TemplateFile; } private void AddModel(string fileName, string text) => AddModel(string.Empty, fileName, text); private string Name(string modelName, string fileName) => modelName.Length == 0 ? fileName : $"{modelName}={fileName}"; private void AddModel(string modelName, string fileName, string text) { _fileSystem.WriteAllText(fileName, text); _options.Models = _options.Models.Append(Name(modelName, fileName)).ToArray(); } private void AddOutputFile(string fileName) => AddOutputFile(string.Empty, fileName); private void AddOutputFile(string name, string fileName) { _options.Output = _options.Output.Append(Name(name, fileName)).ToArray(); } #endregion } }
28.875598
94
0.560895
[ "MIT" ]
NeilMacMullen/Textrude
Tests/TextrudeCliTests.cs
6,035
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 Win.ERP { public partial class FormUsuarios : Form { public FormUsuarios() { InitializeComponent(); } } }
18.095238
44
0.689474
[ "MIT" ]
MVallecillo/Proyecto-L3
Sistema ERP/ERP/Win.ERP/FormUsuarios.cs
382
C#
using System; using Asteroids.Components; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; namespace Asteroids.Systems { public class OffScreenWrapperSystem : SystemBase { enum Direction { Right, Down, Left, Up } protected override void OnUpdate() { ScreenInfoComponentData screenDataComponent = GetSingleton<ScreenInfoComponentData>(); Entities.WithAll<OffScreenWrapperComponentData>().ForEach( ( Entity entity, ref OffScreenWrapperComponentData offScreenWrapperComponentData, ref Translation translation ) => { if (offScreenWrapperComponentData.IsOffScreenLeft) translation.Value = SpawnOnOppositeDirection(translation.Value, offScreenWrapperComponentData.RendererSize.x, screenDataComponent, Direction.Right); else if (offScreenWrapperComponentData.IsOffScreenRight) translation.Value = SpawnOnOppositeDirection(translation.Value, offScreenWrapperComponentData.RendererSize.x, screenDataComponent, Direction.Left); else if (offScreenWrapperComponentData.IsOffScreenUp) translation.Value = SpawnOnOppositeDirection(translation.Value, offScreenWrapperComponentData.RendererSize.y, screenDataComponent, Direction.Down); else if (offScreenWrapperComponentData.IsOffScreenDown) translation.Value = SpawnOnOppositeDirection(translation.Value, offScreenWrapperComponentData.RendererSize.y, screenDataComponent, Direction.Up); offScreenWrapperComponentData.IsOffScreenDown = false; offScreenWrapperComponentData.IsOffScreenRight = false; offScreenWrapperComponentData.IsOffScreenUp = false; offScreenWrapperComponentData.IsOffScreenLeft = false; }).ScheduleParallel(); } static float3 SpawnOnOppositeDirection(float3 position, float bounds, ScreenInfoComponentData screenInfoComponentData, Direction wantedDirection) { switch (wantedDirection) { case Direction.Right: return new float3((bounds + screenInfoComponentData.Width) * .5f, position.y, 0); case Direction.Down: return new float3(position.x, -(bounds + screenInfoComponentData.Height) * .5f, 0); case Direction.Left: return new float3(-(bounds + screenInfoComponentData.Width) * .5f, position.y, 0); case Direction.Up: return new float3(position.x, (bounds + screenInfoComponentData.Height) * .5f, 0); default: throw new ArgumentOutOfRangeException(nameof(wantedDirection), wantedDirection, null); } } } }
45.608696
172
0.609152
[ "MIT" ]
lipemon1/asteroids-unity-dots
Assets/Scripts/Systems/Screen/OffScreenWrapperSystem.cs
3,147
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.WebJobs.Host.Executors; using Xunit; namespace Microsoft.Azure.WebJobs.Host.UnitTests.Executors { public class NullInstanceFactoryTests { [Fact] public void Create_ReturnsNull() { // Arrange IFactory<object> product = CreateProductUnderTest<object>(); // Act object instance = product.Create(); // Assert Assert.Null(instance); } private static NullInstanceFactory<TReflected> CreateProductUnderTest<TReflected>() { return NullInstanceFactory<TReflected>.Instance; } } }
26.733333
95
0.637157
[ "MIT" ]
Azure-App-Service/azure-webjobs-sdk
test/Microsoft.Azure.WebJobs.Host.UnitTests/Executors/NullInstanceFactoryTests.cs
804
C#
using System.Net.Http; using System.Threading.Tasks; using BizzebeeSharp.Entities; using BizzebeeSharp.Extensions; using BizzebeeSharp.Filters; using BizzebeeSharp.Infrastructure; namespace BizzebeeSharp.Services.Product { /// <summary> /// A service for manipulating Bizzebee products. /// </summary> public class ProductService : BizzebeeService { /// <summary> /// Creates a new instance of <see cref="ProductService" />. /// </summary> /// <param name="myBizzebeeUrl">The shop's *.mystrweb.se/api/vX URL.</param> /// <param name="shopAccessToken">An API access token for the shop.</param> public ProductService(string myBizzebeeUrl, string shopAccessToken) : base(myBizzebeeUrl, shopAccessToken) { } /// <summary> /// Gets a list of products. Max 100 per call. /// </summary> /// <returns></returns> public virtual async Task<ProductModelCollection> ListAsync(ProductFilter filter = null) { var req = PrepareRequest("products"); if (filter != null) { req.QueryParams.AddRange(filter.ToParameters()); } return await ExecuteRequestAsync<ProductModelCollection>(req, HttpMethod.Get, rootElement: ""); } /// <summary> /// Count products. /// </summary> /// <returns></returns> public virtual async Task<int> CountAsync() { var req = PrepareRequest("products"); var filter = new ProductFilter { Page = 1000 }; req.QueryParams.AddRange(filter.ToParameters()); var productMeta = await ExecuteRequestAsync<ProductModelCollection>(req, HttpMethod.Get, rootElement: ""); return productMeta.Meta.Pagination.Total.GetValueOrDefault(0); } /// <summary> /// Retrieves the <see cref="ProductModel"/> with the given id. /// </summary> /// <param name="productId">The id of the product to retrieve.</param> /// <param name="include">If you want to include child data in the result. Example: ?include=variants (to include product variants); ?include=variants,languages (to include both product variants and languages). Available includes: primaryVariant, primaryVariant.prices, mediaFiles, languages, vatRates, categories, unit, metaData. NOTE! Only one variant is included in result for performance reason. To fetch all variants, instead use /products/x/variants (unnecessary if hasSeveralVariants is false)</param> /// <returns>The <see cref="ProductModel"/>.</returns> public virtual async Task<ProductModel> GetAsync(int productId, string include = null) { var req = PrepareRequest($"products/{productId}"); if (!string.IsNullOrEmpty(include)) { req.QueryParams.Add("include", include); } return await ExecuteRequestAsync<ProductModel>(req, HttpMethod.Get, rootElement: "data"); } /// <summary> /// Creates a new <see cref="ProductModel"/> on the store. /// </summary> /// <param name="product">A new <see cref="ProductCreateUpdateModel"/>. Id should be set to null.</param> /// <returns>The new <see cref="ProductModel"/>.</returns> public virtual async Task<ProductModel> CreateAsync(ProductCreateUpdateModel product) { var req = PrepareRequest("products"); var body = product.ToDictionary(); var content = new JsonContent(body); return await ExecuteRequestAsync<ProductModel>(req, HttpMethod.Post, content, "data"); } /// <summary> /// Updates the given <see cref="ProductModel"/>. /// </summary> /// <param name="productId">Id of the object being updated.</param> /// <param name="product">The <see cref="ProductCreateUpdateModel"/> to update.</param> /// <returns>The updated <see cref="ProductModel"/>.</returns> public virtual async Task<ProductModel> UpdateAsync(int productId, ProductCreateUpdateModel product) { var req = PrepareRequest($"products/{productId}"); var body = product.ToDictionary(); var content = new JsonContent(body); return await ExecuteRequestAsync<ProductModel>(req, HttpMethod.Put, content, "data"); } #if NETCORE /// <summary> /// Updates the given <see cref="ProductModel"/>. /// </summary> /// <param name="productId">Id of the object being updated.</param> /// <param name="product">The <see cref="ProductCreateUpdateModel"/> to update.</param> /// <returns>The updated <see cref="ProductModel"/>.</returns> public virtual async Task<ProductModel> PatchAsync(int productId, ProductCreateUpdateModel product) { var req = PrepareRequest($"products/{productId}"); var body = product.ToDictionary(); var content = new JsonContent(body); return await ExecuteRequestAsync<ProductModel>(req, HttpMethod.Patch, content, "data"); } #endif /// <summary> /// Deletes a product with the given Id. /// </summary> /// <param name="productId">The product object's Id.</param> public virtual async Task DeleteAsync(int productId) { var req = PrepareRequest($"products/{productId}"); await ExecuteRequestAsync(req, HttpMethod.Delete); } } }
43.826772
516
0.622889
[ "MIT" ]
PrimePenguin/BizzebeeSharp
BizzebeeSharp/Services/Product/ProductService.cs
5,568
C#
namespace BlackMirror.Configuration.SerilogSupport { using System.Xml.Serialization; [XmlRoot("serilog")] public class SerilogConfig { [XmlElement("RollingFile.pathFormat")] public string LogFilePath { get; set; } [XmlElement("RollingFile.serilogPathFormat")] public string SerilogLogFilePath { get; set; } [XmlElement("RollingFile.retainedFileCountLimit")] public int RetainedFileCountLimit { get; set; } [XmlElement("RollingFile.fileSizeLimitBytes")] public long FileSizeLimitBytes { get; set; } } }
26.909091
58
0.673986
[ "MIT" ]
Rosiv/BlackMirror
src/BlackMirror.Configuration/SerilogSupport/SerilogConfig.cs
592
C#
#region License //-------------------------------------------------- // <License> // <Copyright> 2018 © Top Nguyen </Copyright> // <Url> http://topnguyen.com/ </Url> // <Author> Top </Author> // <Project> Elect </Project> // <File> // <Name> IServiceCollectionExtensions.cs </Name> // <Created> 19/03/2018 9:12:37 PM </Created> // <Key> da7e0630-b4f3-487e-a550-6fc58157d848 </Key> // </File> // <Summary> // IServiceCollectionExtensions.cs is a part of Elect // </Summary> // <License> //-------------------------------------------------- #endregion License using Elect.Core.Attributes; using Elect.Notification.OneSignal.Interfaces; using Elect.Notification.OneSignal.Models; using Elect.Notification.OneSignal.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; namespace Elect.Notification.OneSignal { public static class IServiceCollectionExtensions { public static IServiceCollection AddElectOneSignal(this IServiceCollection services, [NotNull]ElectOneSignalOptions configuration) { return services.AddElectOneSignal(_ => { _.AuthKey = configuration.AuthKey; _.Apps = configuration.Apps; }); } public static IServiceCollection AddElectOneSignal(this IServiceCollection services, [NotNull]Action<ElectOneSignalOptions> configuration) { services.Configure(configuration); services.TryAddScoped<IElectOneSignalApp, ElectOneSignalApp>(); services.TryAddScoped<IElectOneSignalDevice, ElectOneSignalDevice>(); services.TryAddScoped<IElectOneSignalNotification, ElectOneSignalNotification>(); services.TryAddScoped<IElectOneSignalClient, ElectOneSignalClient>(); return services; } } }
34.785714
146
0.640144
[ "MIT" ]
anglesen1120/Elect
src/Notification/Elect.Notification.OneSignal/IServiceCollectionExtensions.cs
1,951
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Models; namespace BackEnd.Migrations { [DbContext(typeof(BolnicaContext))] [Migration("20220118135209_V14")] partial class V14 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.12"); modelBuilder.Entity("Models.Bolest", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("nazivBolesti") .HasColumnType("nvarchar(max)"); b.HasKey("ID"); b.ToTable("bolesti"); }); modelBuilder.Entity("Models.Bolnica", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("duzina") .HasColumnType("int"); b.Property<int>("kapacitet") .HasColumnType("int"); b.Property<string>("naziv") .HasColumnType("nvarchar(max)"); b.Property<int>("sirina") .HasColumnType("int"); b.HasKey("ID"); b.ToTable("bolnice"); }); modelBuilder.Entity("Models.Krevet", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("bolestID") .HasColumnType("int"); b.Property<int?>("bolnicaID") .HasColumnType("int"); b.HasKey("ID"); b.HasIndex("bolestID"); b.HasIndex("bolnicaID"); b.ToTable("kreveti"); }); modelBuilder.Entity("Models.Pacijent", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Ime") .HasColumnType("nvarchar(max)"); b.Property<string>("Prezime") .HasColumnType("nvarchar(max)"); b.Property<int>("pacijentID") .HasColumnType("int"); b.HasKey("ID"); b.HasIndex("pacijentID") .IsUnique(); b.ToTable("pacijenti"); }); modelBuilder.Entity("Models.Krevet", b => { b.HasOne("Models.Bolest", "bolest") .WithMany("bolestSpoj") .HasForeignKey("bolestID"); b.HasOne("Models.Bolnica", "bolnica") .WithMany("bolnicaSpoj") .HasForeignKey("bolnicaID"); b.Navigation("bolest"); b.Navigation("bolnica"); }); modelBuilder.Entity("Models.Pacijent", b => { b.HasOne("Models.Krevet", "pacijentSpoj") .WithOne("pacijent") .HasForeignKey("Models.Pacijent", "pacijentID") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("pacijentSpoj"); }); modelBuilder.Entity("Models.Bolest", b => { b.Navigation("bolestSpoj"); }); modelBuilder.Entity("Models.Bolnica", b => { b.Navigation("bolnicaSpoj"); }); modelBuilder.Entity("Models.Krevet", b => { b.Navigation("pacijent"); }); #pragma warning restore 612, 618 } } }
31.019608
75
0.432364
[ "Apache-2.0" ]
djokatruElfak/WebProjekat
BackEnd/Migrations/20220118135209_V14.Designer.cs
4,748
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Jdart.Swiffy { public class SwiffyOptions { public int MillisecondsTimeout { get; set; } } }
17.214286
52
0.717842
[ "MIT" ]
alvaro-jdart/swiffy
Jdart.Swiffy/SwiffyOptions.cs
243
C#
private sealed class AddOvfInstruction.AddOvfUInt64 : AddOvfInstruction // TypeDefIndex: 2344 { // Methods // RVA: 0x1974F30 Offset: 0x1975031 VA: 0x1974F30 Slot: 8 public override int Run(InterpretedFrame frame) { } // RVA: 0x1974390 Offset: 0x1974491 VA: 0x1974390 public void .ctor() { } }
25.083333
93
0.740864
[ "MIT" ]
SinsofSloth/RF5-global-metadata
_no_namespace/AddOvfInstruction.AddOvfUInt64.cs
301
C#
// Copyright © 2006-2010 Travis Robinson. All rights reserved. // // website: http://sourceforge.net/projects/libusbdotnet // e-mail: libusbdotnet@gmail.com // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. or // visit www.gnu.org. using LibUsbDotNet.Main; using System.Collections.Generic; namespace LibUsbDotNet.LibUsb { // Implements functionality for the UsbDevice class, related to Interfaces public partial class UsbDevice { private readonly List<int> mClaimedInterfaces = new List<int>(); private readonly byte[] usbAltInterfaceSettings = new byte[UsbConstants.MaxDeviceCount]; /// <summary> /// Claims the specified interface of the device. /// </summary> /// <param name="interfaceID">The interface to claim.</param> /// <returns>True on success.</returns> public bool ClaimInterface(int interfaceID) { this.EnsureOpen(); if (this.mClaimedInterfaces.Contains(interfaceID)) { return true; } NativeMethods.ClaimInterface(this.deviceHandle, interfaceID).ThrowOnError(); this.mClaimedInterfaces.Add(interfaceID); return true; } public bool GetAltInterface(out int alternateID) { int interfaceID = this.mClaimedInterfaces.Count == 0 ? 0 : this.mClaimedInterfaces[this.mClaimedInterfaces.Count - 1]; return this.GetAltInterface(interfaceID, out alternateID); } /// <summary> /// Gets the alternate interface number for the specified interfaceID. /// </summary> /// <param name="interfaceID">The interface number of to get the alternate setting for.</param> /// <param name="alternateID">The currrently selected alternate interface number.</param> /// <returns>True on success.</returns> public bool GetAltInterface(int interfaceID, out int alternateID) { alternateID = this.usbAltInterfaceSettings[interfaceID & (UsbConstants.MaxDeviceCount - 1)]; return true; } /// <summary> /// Gets the selected alternate interface of the specified interface. /// </summary> /// <param name="interfaceID">The interface settings number (index) to retrieve the selected alternate interface setting for.</param> /// <param name="selectedAltInterfaceID">The alternate interface setting selected for use with the specified interface.</param> public void GetAltInterfaceSetting(byte interfaceID, out byte selectedAltInterfaceID) { byte[] buf = new byte[1]; int uTransferLength; UsbSetupPacket setupPkt = new UsbSetupPacket(); setupPkt.RequestType = (byte)EndpointDirection.In | (byte)UsbRequestType.TypeStandard | (byte)UsbRequestRecipient.RecipInterface; setupPkt.Request = (byte)StandardRequest.GetInterface; setupPkt.Value = 0; setupPkt.Index = interfaceID; setupPkt.Length = 1; uTransferLength = this.ControlTransfer(setupPkt, buf, 0, buf.Length); if (uTransferLength == 1) { selectedAltInterfaceID = buf[0]; } else { selectedAltInterfaceID = 0; } } /// <summary> /// Releases an interface that was previously claimed with <see cref="ClaimInterface"/>. /// </summary> /// <param name="interfaceID">The interface to release.</param> /// <returns>True on success.</returns> public bool ReleaseInterface(int interfaceID) { this.EnsureOpen(); var ret = NativeMethods.ReleaseInterface(this.deviceHandle, interfaceID); this.mClaimedInterfaces.Remove(interfaceID); ret.ThrowOnError(); return true; } /// <summary> /// Sets an alternate interface for the most recent claimed interface. /// </summary> /// <param name="alternateID">The alternate interface to select for the most recent claimed interface See <see cref="ClaimInterface"/>.</param> /// <returns>True on success.</returns> public bool SetAltInterface(int interfaceID, int alternateID) { this.EnsureOpen(); NativeMethods.SetInterfaceAltSetting(this.deviceHandle, interfaceID, alternateID).ThrowOnError(); this.usbAltInterfaceSettings[interfaceID & (UsbConstants.MaxDeviceCount - 1)] = (byte)alternateID; return true; } /// <summary> /// Sets an alternate interface for the most recent claimed interface. /// </summary> /// <param name="alternateID">The alternate interface to select for the most recent claimed interface See <see cref="ClaimInterface"/>.</param> /// <returns>True on success.</returns> public bool SetAltInterface(int alternateID) { if (this.mClaimedInterfaces.Count == 0) { throw new UsbException("You must claim an interface before setting an alternate interface."); } return this.SetAltInterface(this.mClaimedInterfaces[this.mClaimedInterfaces.Count - 1], alternateID); } } }
42.251748
151
0.638365
[ "BSD-2-Clause" ]
addixon/ErgCompetePM
LibUsbDotNet/LibUsbDotNet/LibUsb/UsbDevice.Interfaces.cs
6,045
C#
namespace DigitalLearningSolutions.Web.Controllers.TrackingSystem.Centre.Reports { using System; using System.Collections.Generic; using System.Linq; using DigitalLearningSolutions.Data.DataServices.UserDataService; using DigitalLearningSolutions.Data.Enums; using DigitalLearningSolutions.Data.Models.TrackingSystem; using DigitalLearningSolutions.Data.Models.User; using DigitalLearningSolutions.Data.Services; using DigitalLearningSolutions.Web.Attributes; using DigitalLearningSolutions.Web.Helpers; using DigitalLearningSolutions.Web.ViewModels.TrackingSystem.Centre.Reports; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.FeatureManagement.Mvc; [FeatureGate(FeatureFlags.RefactoredTrackingSystem)] [Authorize(Policy = CustomPolicies.UserCentreAdmin)] [Route("/TrackingSystem/Centre/Reports")] public class ReportsController : Controller { private readonly IActivityService activityService; private readonly IEvaluationSummaryService evaluationSummaryService; private readonly IUserDataService userDataService; public ReportsController( IActivityService activityService, IUserDataService userDataService, IEvaluationSummaryService evaluationSummaryService ) { this.activityService = activityService; this.userDataService = userDataService; this.evaluationSummaryService = evaluationSummaryService; } public IActionResult Index() { var centreId = User.GetCentreId(); var adminId = User.GetAdminId()!.Value; var adminUser = userDataService.GetAdminUserById(adminId)!; var filterData = Request.Cookies.RetrieveFilterDataFromCookie(adminUser); Response.Cookies.SetReportsFilterCookie(filterData, DateTime.UtcNow); var activity = activityService.GetFilteredActivity(centreId, filterData); var (jobGroupName, courseCategoryName, courseName) = activityService.GetFilterNames(filterData); var filterModel = new ReportsFilterModel( filterData, jobGroupName, courseCategoryName, courseName, adminUser.CategoryId == 0 ); var evaluationResponseBreakdowns = evaluationSummaryService.GetEvaluationSummary(centreId, filterData); var model = new ReportsViewModel(activity, filterModel, evaluationResponseBreakdowns); return View(model); } [NoCaching] [Route("Data")] public IEnumerable<ActivityDataRowModel> GetGraphData() { var centreId = User.GetCentreId(); var adminId = User.GetAdminId()!.Value; var adminUser = userDataService.GetAdminUserById(adminId)!; var filterData = Request.Cookies.RetrieveFilterDataFromCookie(adminUser); var activity = activityService.GetFilteredActivity(centreId, filterData!); return activity.Select( p => new ActivityDataRowModel(p, DateHelper.GetFormatStringForGraphLabel(p.DateInformation.Interval)) ); } [HttpGet] [Route("EditFilters")] public IActionResult EditFilters() { var centreId = User.GetCentreId(); var adminId = User.GetAdminId()!.Value; var adminUser = userDataService.GetAdminUserById(adminId)!; var filterData = Request.Cookies.RetrieveFilterDataFromCookie(adminUser); var filterOptions = GetDropdownValues(centreId, adminUser); var dataStartDate = activityService.GetStartOfActivityForCentre(centreId); var model = new EditFiltersViewModel( filterData, adminUser.CategoryId, filterOptions, dataStartDate ); return View(model); } [HttpPost] [Route("EditFilters")] public IActionResult EditFilters(EditFiltersViewModel model) { if (!ModelState.IsValid) { var centreId = User.GetCentreId(); var adminId = User.GetAdminId()!.Value; var adminUser = userDataService.GetAdminUserById(adminId)!; var filterOptions = GetDropdownValues(centreId, adminUser); model.SetUpDropdowns(filterOptions, adminUser.CategoryId); model.DataStart = activityService.GetStartOfActivityForCentre(centreId); return View(model); } var filterData = new ActivityFilterData( model.GetValidatedStartDate(), model.GetValidatedEndDate(), model.JobGroupId, model.CourseCategoryId, model.CustomisationId, model.FilterType, model.ReportInterval ); Response.Cookies.SetReportsFilterCookie(filterData, DateTime.UtcNow); return RedirectToAction("Index"); } [HttpGet] [Route("Download")] public IActionResult DownloadUsageData( int? jobGroupId, int? courseCategoryId, int? customisationId, string startDate, string endDate, ReportInterval reportInterval ) { var centreId = User.GetCentreId(); var adminId = User.GetAdminId()!.Value; var adminUser = userDataService.GetAdminUserById(adminId)!; var dateRange = activityService.GetValidatedUsageStatsDateRange(startDate, endDate, centreId); if (dateRange == null) { return new NotFoundResult(); } var filterData = new ActivityFilterData( dateRange.Value.startDate, dateRange.Value.endDate, jobGroupId, adminUser.CategoryId == 0 ? courseCategoryId : adminUser.CategoryId, customisationId, customisationId.HasValue ? CourseFilterType.Course : CourseFilterType.CourseCategory, reportInterval ); var dataFile = activityService.GetActivityDataFileForCentre(centreId, filterData); return File( dataFile, FileHelper.ExcelContentType, $"Activity data for centre {centreId} downloaded {DateTime.Today:yyyy-MM-dd}.xlsx" ); } [HttpGet] [Route("DownloadEvaluationSummaries")] public IActionResult DownloadEvaluationSummaries( int? jobGroupId, int? courseCategoryId, int? customisationId, string startDate, string endDate, ReportInterval reportInterval ) { var centreId = User.GetCentreId(); var adminId = User.GetAdminId()!.Value; var adminUser = userDataService.GetAdminUserById(adminId)!; var dateRange = activityService.GetValidatedUsageStatsDateRange(startDate, endDate, centreId); if (dateRange == null) { return new NotFoundResult(); } var filterData = new ActivityFilterData( dateRange.Value.startDate, dateRange.Value.endDate, jobGroupId, adminUser.CategoryId == 0 ? courseCategoryId : adminUser.CategoryId, customisationId, customisationId.HasValue ? CourseFilterType.Course : CourseFilterType.CourseCategory, reportInterval ); var content = evaluationSummaryService.GetEvaluationSummaryFileForCentre(centreId, filterData); return File( content, FileHelper.ExcelContentType, $"DLS Evaluation Stats {DateTime.Today:yyyy-MM-dd}.xlsx" ); } private ReportsFilterOptions GetDropdownValues( int centreId, AdminUser adminUser ) { return activityService.GetFilterOptions( centreId, adminUser.CategoryId == 0 ? (int?)null : adminUser.CategoryId ); } } }
37.886463
118
0.596012
[ "MIT" ]
TechnologyEnhancedLearning/DLSV2
DigitalLearningSolutions.Web/Controllers/TrackingSystem/Centre/Reports/ReportsController.cs
8,678
C#
using All; using System; using System.IO; namespace CongressManager.Congress { public partial class BoardDown : System.Web.UI.Page { private string dir = ""; private CongressRepository _repository; public BoardDown() { _repository = new CongressRepository(); } protected void Page_Load(object sender, EventArgs e) { // 넘겨져 온 번호에 해당하는 파일명 가져오기(보안때문에... 파일명 숨김) string fileName = _repository.GetFileNameById(Convert.ToInt32(Request["Id"])); // 다운로드 폴더 지정 : 실제 사용시 반드시 변경 dir = Server.MapPath("./MyFiles/"); if (fileName == null) // 특정 번호에 해당하는 첨부파일이 없다면, { Response.Clear(); Response.End(); } else { // 다운로드 카운트 증가 메서드 호출 //_repository.UpdateDownCount(fileName); _repository.UpdateDownCountById(int.Parse(Request["Id"])); //[!] 강제 다운로드 창 띄우기 주요 로직 Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode( (fileName.Length > 50) ? fileName.Substring(fileName.Length - 50, 50) : fileName)); Response.WriteFile(Path.Combine(dir, fileName)); Response.End(); } } } }
31.12
90
0.503856
[ "MIT" ]
VisualAcademy/AspNetCoreBook
CongressManager/CongressManager/Congress/BoardDown.aspx.cs
1,740
C#
namespace AlertToCare.Utility { public static class Utils { public static bool IsValueNull(object value) { return (value == null); } public static bool IsLengthValid(string word, int length) { return word.Length == length; } } }
20.933333
65
0.547771
[ "MIT" ]
kavyashukla18/AlertToCare
AlertToCare/AlertToCare/Utility/Utils.cs
316
C#
using System.Linq; using System.Threading.Tasks; using NJsonSchema; using NSwag.Generation.AspNetCore.Tests.Web.Controllers.Parameters; using Xunit; namespace NSwag.Generation.AspNetCore.Tests.Parameters { public class FormDataTests : AspNetCoreTestsBase { [Fact] public async Task WhenOperationHasFormDataFile_ThenItIsInRequestBody() { // Arrange var settings = new AspNetCoreOpenApiDocumentGeneratorSettings { SchemaType = SchemaType.OpenApi3 }; // Act var document = await GenerateDocumentAsync(settings, typeof(FileUploadController)); var json = document.ToJson(); // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "FileUpload_UploadFile").Operation; var schema = operation.RequestBody.Content["multipart/form-data"].Schema; Assert.Equal("binary", schema.Properties["file"].Format); Assert.Equal(JsonObjectType.String, schema.Properties["file"].Type); Assert.Equal(JsonObjectType.String, schema.Properties["test"].Type); Assert.Contains(@" ""/api/FileUpload/UploadFiles"": { ""post"": { ""tags"": [ ""FileUpload"" ], ""operationId"": ""FileUpload_UploadFiles"", ""requestBody"": { ""content"": { ""multipart/form-data"": { ""schema"": { ""properties"": { ""files"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""format"": ""binary"" } }, ""test"": { ""type"": ""string"" } } } } } },".Replace("\r", ""), json.Replace("\r", "")); } [Fact] public async Task WhenOperationHasFormDataComplex_ThenItIsInRequestBody() { // Arrange var settings = new AspNetCoreOpenApiDocumentGeneratorSettings { SchemaType = SchemaType.OpenApi3 }; // Act var document = await GenerateDocumentAsync(settings, typeof(FileUploadController)); var json = document.ToJson(); // Assert var operation = document.Operations.First(o => o.Operation.OperationId == "FileUpload_UploadAttachment").Operation; Assert.NotNull(operation); Assert.Contains(@"""requestBody"": { ""content"": { ""multipart/form-data"": { ""schema"": { ""type"": ""object"", ""properties"": { ""Description"": { ""type"": ""string"", ""nullable"": true }, ""Contents"": { ""type"": ""string"", ""format"": ""binary"", ""nullable"": true } } } } } },".Replace("\r", ""), json.Replace("\r", "")); } } }
34.27957
127
0.483375
[ "MIT" ]
0xced/NSwag
src/NSwag.Generation.AspNetCore.Tests/Parameters/FormDataTests.cs
3,190
C#
#pragma checksum "C:\Users\yu\Desktop\Sobey.TimeLine\Sobey.TimeLine\Controls\TimeLineControl.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "DFDDE6296DB3B17F4DBC5FE140F52F36" //------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.33440 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace Sobey.TimeLine.Controls { public partial class TimeLineControl : System.Windows.Controls.UserControl { internal System.Windows.Controls.ScrollViewer sv_Main; internal System.Windows.Controls.Grid ItemContainer; internal System.Windows.Controls.Grid TopMoreContainer; internal System.Windows.Controls.Button TopMore; internal System.Windows.Controls.ItemsControl tc_Items; internal System.Windows.Controls.Grid BottomMoreContainer; internal System.Windows.Controls.Button BottomMore; private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/Sobey.TimeLine;component/Controls/TimeLineControl.xaml", System.UriKind.Relative)); this.sv_Main = ((System.Windows.Controls.ScrollViewer)(this.FindName("sv_Main"))); this.ItemContainer = ((System.Windows.Controls.Grid)(this.FindName("ItemContainer"))); this.TopMoreContainer = ((System.Windows.Controls.Grid)(this.FindName("TopMoreContainer"))); this.TopMore = ((System.Windows.Controls.Button)(this.FindName("TopMore"))); this.tc_Items = ((System.Windows.Controls.ItemsControl)(this.FindName("tc_Items"))); this.BottomMoreContainer = ((System.Windows.Controls.Grid)(this.FindName("BottomMoreContainer"))); this.BottomMore = ((System.Windows.Controls.Button)(this.FindName("BottomMore"))); } } }
38.866667
175
0.656604
[ "MIT" ]
DoyuLy/TimeLine
Sobey.TimeLine/obj/Debug/Controls/TimeLineControl.g.cs
3,023
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 Sciencetific_Calc { public partial class AnalogClock : Form { Timer t = new Timer(); int WIDTH = 300, HEIGHT = 300, secHAND = 140, minHAND = 110, hrHAND = 80; int cx, cy; Bitmap bmp; Graphics g; public AnalogClock() { InitializeComponent(); } private void AnalogClock_Load(object sender, EventArgs e) { bmp = new Bitmap(WIDTH + 1, HEIGHT + 1); cx = WIDTH / 2; cy = HEIGHT / 2; this.BackColor = Color.White; t.Interval = 1000; t.Tick += new EventHandler(this.t_Tick); t.Start(); } private void t_Tick(object sender, EventArgs e) { g = Graphics.FromImage(bmp); int ss = DateTime.Now.Second; int mm = DateTime.Now.Minute; int hh = DateTime.Now.Hour; int[] handCoord = new int[2]; g.Clear(Color.White); g.DrawEllipse(new Pen(Color.Black, 1f), 0, 0, WIDTH, HEIGHT); g.DrawString("12", new Font("Arial", 12), Brushes.Black, new PointF(140, 2)); g.DrawString("3", new Font("Arial", 12), Brushes.Black, new PointF(286, 140)); g.DrawString("6", new Font("Arial", 12), Brushes.Black, new PointF(142, 282)); g.DrawString("9", new Font("Arial", 12), Brushes.Black, new PointF(0, 140)); handCoord = msCoord(ss, secHAND); g.DrawLine(new Pen(Color.Red, 1f), new Point(cx, cy), new Point(handCoord[0], handCoord[1])); handCoord = msCoord(mm, minHAND); g.DrawLine(new Pen(Color.Black, 2f), new Point(cx, cy), new Point(handCoord[0], handCoord[1])); handCoord = hrCoord(hh%12, mm, hrHAND); g.DrawLine(new Pen(Color.Gray, 3f), new Point(cx, cy), new Point(handCoord[0], handCoord[1])); this.Text = "Analog Clock - " + hh + ":" + mm + ":" + ss; g.Dispose(); } private int[] msCoord(int val, int hlen) { int[] coord = new int[2]; val *= 6; if (val >= 0 && val <= 100) { coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180)); coord[1] = cy + (int)(hlen * Math.Cos(Math.PI * val / 180)); } else { coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180)); coord[1] = cy + (int)(hlen * Math.Cos(Math.PI * val / 180)); } return coord; } private int[] hrCoord(int hval, int mval, int hlen) { int[] coord = new int[2]; int val = (int)((hval * 30) + (mval * 0.5)); if (val >= 0 && val <= 100) { coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180)); coord[1] = cy + (int)(hlen * Math.Cos(Math.PI * val / 180)); } else { coord[0] = cx + (int)(hlen * Math.Sin(Math.PI * val / 180)); coord[1] = cy + (int)(hlen * Math.Cos(Math.PI * val / 180)); } return coord; } } }
31.166667
108
0.475654
[ "CC0-1.0" ]
RedStoneCr33per/AtoZGamesV2
New folder/AnalogClock.cs
3,555
C#
using System.Linq.Expressions; namespace NuClear.ValidationRules.SingleCheck.Optimization { internal sealed class PredicateVisitor : ExpressionVisitor { private readonly ParameterExpression _parameter; private bool _isSimple = true; public PredicateVisitor(ParameterExpression parameter) { _parameter = parameter; } public bool IsSimple => _isSimple; protected override Expression VisitParameter(ParameterExpression node) { // Предикат считаем простыи, если в нём используется его параметр и константы - никаких внешних объектов _isSimple = _isSimple & (node == _parameter); return base.VisitParameter(node); } } }
31.291667
116
0.672437
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
i-maslennikov/nuclear-river-validation-rules
ValidationRules.SingleCheck/Optimization/PredicateVisitor.cs
838
C#
using EngineeringUnits; using EngineeringUnits.Units; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using System.Diagnostics; namespace UnitTests { [TestClass] public class AreaTest { [TestMethod] public void AreaSimple() { Length L1 = new(1d, LengthUnit.Meter); Length L2 = new(1d, LengthUnit.Meter); Debug.WriteLine($"{L1}"); Debug.WriteLine($"{L2}"); Area A1 = L1 * L2; string jsonString = JsonConvert.SerializeObject(A1); Area JSON = JsonConvert.DeserializeObject<Area>(jsonString); Assert.AreEqual(1, A1.As(AreaUnit.SquareMeter)); Assert.AreEqual(10000, A1.As(AreaUnit.SquareCentimeter)); Assert.AreEqual(1.195990046301080256481500558, A1.As(AreaUnit.SquareYard)); //JSON Assert.AreEqual(1, JSON.As(AreaUnit.SquareMeter)); Assert.AreEqual(10000, JSON.As(AreaUnit.SquareCentimeter)); Assert.AreEqual(1.195990046301080256481500558, JSON.As(AreaUnit.SquareYard)); } [TestMethod] public void AreaMany() { //Length L1 = new Length(10, LengthUnit.Meter); //Length L2 = new Length(10, LengthUnit.Meter); //Area A1 = ((L1 * L2) * (L1 * L2) * (L1 * L2)) / ((L1 * L2) * (L1 * L2)); ////Assert.AreEqual(1000000, A1.As(LengthUnit.Centimeter)); //Assert.AreEqual(100, A1.As(LengthUnit.Meter)); ////Assert.AreEqual(119.599004630108, A1.As(LengthUnit.Yard), 0.000000001); } [TestMethod] public void AreaTimesDouble() { //Length L1 = new Length(10, LengthUnit.Meter); //Length L2 = new Length(10, LengthUnit.Meter); //Area A1 = (L1 * L2) * 2; ////Debug.Print($"{A1}"); ////Assert.AreEqual(1000000, A1.As(LengthUnit.Centimeter)); //Assert.AreEqual(200, A1.As(LengthUnit.Meter)); ////Assert.AreEqual(119.599004630108, A1.As(LengthUnit.Yard), 0.000000001); } } }
30.042254
89
0.578528
[ "MIT" ]
AtefeBahrani/EngineeringUnits
UnitTests/CombinedUnits/Area/AreaTest.cs
2,133
C#
/* * Copyright (c) 2017-2020. RainyRizzle. All rights reserved * Contact to : https://www.rainyrizzle.com/ , contactrainyrizzle@gmail.com * * This file is part of [AnyPortrait]. * * AnyPortrait can not be copied and/or distributed without * the express perission of [Seungjik Lee]. * * Unless this file is downloaded from the Unity Asset Store or RainyRizzle homepage, * this file and its users are illegal. * In that case, the act may be subject to legal penalties. */ using UnityEngine; using UnityEditor; using System.Collections; using System; using System.Collections.Generic; using AnyPortrait; namespace AnyPortrait { public partial class apGizmoController { // 작성해야하는 함수 // Select : int - (Vector2 mousePosGL, Vector2 mousePosW, int btnIndex, apGizmos.SELECT_TYPE selectType) // Move : void - (Vector2 curMouseGL, Vector2 curMousePosW, Vector2 deltaMoveW, int btnIndex) // Rotate : void - (float deltaAngleW) // Scale : void - (Vector2 deltaScaleW) // TODO : 현재 Transform이 가능한지도 알아야 할 것 같다. // Transform Position : void - (Vector2 pos, int depth) // Transform Rotation : void - (float angle) // Transform Scale : void - (Vector2 scale) // Transform Color : void - (Color color) // Pivot Return : apGizmos.TransformParam - () // Multiple Select : int - (Vector2 mousePosGL_Min, Vector2 mousePosGL_Max, Vector2 mousePosW_Min, Vector2 mousePosW_Max, SELECT_TYPE areaSelectType) // FFD Style Transform : void - (List<object> srcObjects, List<Vector2> posWorlds) // FFD Style Transform Start : bool - () // Vertex 전용 툴 // SoftSelection() : bool // PressBlur(Vector2 pos, float tDelta) : bool //---------------------------------------------------------------- // Gizmo - Physics Modifier에서 Vertex 선택한다. 제어는 없음 // Area 선택이 가능하다 // < ModRenderVert 선택시 ModVertWeight를 선택하도록 주의 > //---------------------------------------------------------------- /// <summary> /// Modifier [Physics]에 대한 Gizmo Event의 Set이다. /// </summary> /// <returns></returns> public apGizmos.GizmoEventSet GetEventSet_Modifier_Physics() { apGizmos.GizmoEventSet.I.Clear(); apGizmos.GizmoEventSet.I.SetEvent_1_Basic( Select__Modifier_Physics, Unselect__Modifier_Physics, null, null, null, PivotReturn__Modifier_Physics); apGizmos.GizmoEventSet.I.SetEvent_2_TransformGUI( null, null, null, null, null, null, apGizmos.TRANSFORM_UI.None ); apGizmos.GizmoEventSet.I.SetEvent_3_Tools( MultipleSelect__Modifier_Physics, null, null, null, null, null); apGizmos.GizmoEventSet.I.SetEvent_4_EtcAndKeyboard( FirstLink__Modifier_Physic, AddHotKeys__Modifier_Physics, null, null, null); return apGizmos.GizmoEventSet.I; //이전 //return new apGizmos.GizmoEventSet( // Select__Modifier_Physics, // Unselect__Modifier_Physics, // null, null, null, null, // null, null, null, null, null, // PivotReturn__Modifier_Physics, // MultipleSelect__Modifier_Physics, // null, // null, // null, // null, // null, // apGizmos.TRANSFORM_UI.None, // FirstLink__Modifier_Physic, // AddHotKeys__Modifier_Physics); } public apGizmos.SelectResult FirstLink__Modifier_Physic() { if (Editor.Select.MeshGroup == null || Editor.Select.Modifier == null) { return null; } if (Editor.Select.ModRenderVertListOfMod != null) { //return Editor.Select.ModRenderVertListOfMod.Count; return apGizmos.SelectResult.Main.SetMultiple<apSelection.ModRenderVert>(Editor.Select.ModRenderVertListOfMod); } return null; } /// <summary> /// Physic Modifier내에서의 Gizmo 이벤트 : Vertex 계열 선택시 [단일 선택] /// </summary> /// <param name="mousePosGL"></param> /// <param name="mousePosW"></param> /// <param name="btnIndex"></param> /// <param name="selectType"></param> /// <returns></returns> public apGizmos.SelectResult Select__Modifier_Physics(Vector2 mousePosGL, Vector2 mousePosW, int btnIndex, apGizmos.SELECT_TYPE selectType) { if (Editor.Select.MeshGroup == null || Editor.Select.Modifier == null) { return null; } //(Editing 상태일 때) //1. Vertex 선택 //2. (Lock 걸리지 않았다면) 다른 Transform을 선택 //(Editing 상태가 아닐 때) //(Lock 걸리지 않았다면) Transform을 선택한다. // Child 선택이 가능하면 MeshTransform을 선택. 그렇지 않아면 MeshGroupTransform을 선택해준다. if (Editor.Select.ModRenderVertListOfMod == null) { return null; } int prevSelectedCount = Editor.Select.ModRenderVertListOfMod.Count; if (!Editor.Controller.IsMouseInGUI(mousePosGL)) { return apGizmos.SelectResult.Main.SetMultiple<apSelection.ModRenderVert>(Editor.Select.ModRenderVertListOfMod); } bool isChildMeshTransformSelectable = Editor.Select.Modifier.IsTarget_ChildMeshTransform; //apGizmos.SELECT_RESULT result = apGizmos.SELECT_RESULT.None; bool isTransformSelectable = false; if (Editor.Select.ExEditingMode != apSelection.EX_EDIT.None) { //(Editing 상태일 때) //1. Vertex 선택 //2. (Lock 걸리지 않았다면) 다른 Transform을 선택 bool selectVertex = false; if (Editor.Select.ExKey_ModMesh != null && Editor.Select.MeshGroup != null) { //일단 선택한 Vertex가 클릭 가능한지 체크 if (Editor.Select.ModRenderVertOfMod != null) { if (Editor.Select.ModRenderVertListOfMod.Count == 1) { if (Editor.Controller.IsVertexClickable(apGL.World2GL(Editor.Select.ModRenderVertOfMod._renderVert._pos_World), mousePosGL)) { if (selectType == apGizmos.SELECT_TYPE.Subtract) { //삭제인 경우 : ModVertWeight를 선택한다. Editor.Select.RemoveModVertexOfModifier(null, null, Editor.Select.ModRenderVertOfMod._modVertWeight, Editor.Select.ModRenderVertOfMod._renderVert); } else { //그 외에는 => 그대로 갑시다. selectVertex = true; //return apGizmos.SELECT_RESULT.SameSelected; } //return Editor.Select.ModRenderVertListOfMod.Count; return apGizmos.SelectResult.Main.SetMultiple<apSelection.ModRenderVert>(Editor.Select.ModRenderVertListOfMod); } } else { //여러개라고 하네요. List<apSelection.ModRenderVert> modRenderVerts = Editor.Select.ModRenderVertListOfMod; for (int iModRenderVert = 0; iModRenderVert < modRenderVerts.Count; iModRenderVert++) { apSelection.ModRenderVert modRenderVert = modRenderVerts[iModRenderVert]; if (Editor.Controller.IsVertexClickable(apGL.World2GL(modRenderVert._renderVert._pos_World), mousePosGL)) { if (selectType == apGizmos.SELECT_TYPE.Subtract) { //삭제인 경우 //하나 지우고 끝 //결과는 List의 개수 Editor.Select.RemoveModVertexOfModifier(null, null, modRenderVert._modVertWeight, modRenderVert._renderVert); } else if (selectType == apGizmos.SELECT_TYPE.Add) { //Add 상태에서 원래 선택된걸 누른다면 //추가인 경우 => 그대로 selectVertex = true; } else { //만약... new 라면? //다른건 초기화하고 //얘만 선택해야함 apRenderVertex selectedRenderVert = modRenderVert._renderVert; apModifiedVertexWeight selectedModVertWeight = modRenderVert._modVertWeight; Editor.Select.SetModVertexOfModifier(null, null, null, null); Editor.Select.SetModVertexOfModifier(null, null, selectedModVertWeight, selectedRenderVert); } //return Editor.Select.ModRenderVertListOfMod.Count; return apGizmos.SelectResult.Main.SetMultiple<apSelection.ModRenderVert>(Editor.Select.ModRenderVertListOfMod); } } } } if (selectType == apGizmos.SELECT_TYPE.New) { //Add나 Subtract가 아닐땐, 잘못 클릭하면 선택을 해제하자 (전부) Editor.Select.SetModVertexOfModifier(null, null, null, null); } if (selectType != apGizmos.SELECT_TYPE.Subtract) { if (Editor.Select.ExKey_ModMesh._transform_Mesh != null && Editor.Select.ExKey_ModMesh._vertices != null) { //선택된 RenderUnit을 고르자 apRenderUnit targetRenderUnit = Editor.Select.MeshGroup.GetRenderUnit(Editor.Select.ExKey_ModMesh._transform_Mesh); if (targetRenderUnit != null) { for (int iVert = 0; iVert < targetRenderUnit._renderVerts.Count; iVert++) { apRenderVertex renderVert = targetRenderUnit._renderVerts[iVert]; bool isClick = Editor.Controller.IsVertexClickable(apGL.World2GL(renderVert._pos_World), mousePosGL); if (isClick) { apModifiedVertexWeight selectedModVertWeight = Editor.Select.ExKey_ModMesh._vertWeights.Find(delegate (apModifiedVertexWeight a) { return renderVert._vertex._uniqueID == a._vertexUniqueID; }); if (selectedModVertWeight != null) { if (selectType == apGizmos.SELECT_TYPE.New) { Editor.Select.SetModVertexOfModifier(null, null, selectedModVertWeight, renderVert); } else if (selectType == apGizmos.SELECT_TYPE.Add) { Editor.Select.AddModVertexOfModifier(null, null, selectedModVertWeight, renderVert); } selectVertex = true; //result = apGizmos.SELECT_RESULT.NewSelected; break; } } } } } } } //Vertex를 선택한게 없다면 //+ Lock 상태가 아니라면 if (!selectVertex && !Editor.Select.IsSelectionLock) { //Transform을 선택 isTransformSelectable = true; } } else { //(Editing 상태가 아닐때) isTransformSelectable = true; if (Editor.Select.ExKey_ModMesh != null && Editor.Select.IsSelectionLock) { //뭔가 선택된 상태에서 Lock이 걸리면 다른건 선택 불가 isTransformSelectable = false; } } if (isTransformSelectable && selectType == apGizmos.SELECT_TYPE.New) { //(Editing 상태가 아닐 때) //Transform을 선택한다. apTransform_Mesh selectedMeshTransform = null; //정렬된 Render Unit //List<apRenderUnit> renderUnits = Editor.Select.MeshGroup._renderUnits_All;//<<이전 : RenderUnits_All 이용 List<apRenderUnit> renderUnits = Editor.Select.MeshGroup.SortedRenderUnits;//<<변경 : Sorted 리스트 이용 for (int iUnit = 0; iUnit < renderUnits.Count; iUnit++) { apRenderUnit renderUnit = renderUnits[iUnit]; if (renderUnit._meshTransform != null && renderUnit._meshTransform._mesh != null) { if (renderUnit._meshTransform._isVisible_Default && renderUnit._meshColor2X.a > 0.1f)//Alpha 옵션 추가 { //Debug.LogError("TODO : Mouse Picking 바꿀것"); bool isPick = apEditorUtil.IsMouseInRenderUnitMesh( mousePosGL, renderUnit); if (isPick) { selectedMeshTransform = renderUnit._meshTransform; //찾았어도 계속 찾는다. //뒤의 아이템이 "앞쪽"에 있는 것이기 때문 } } } } if (selectedMeshTransform != null) { //만약 ChildMeshGroup에 속한 거라면, //Mesh Group 자체를 선택해야 한다. <- 추가 : Child Mesh Transform이 허용되는 경우 그럴 필요가 없다. apMeshGroup parentMeshGroup = Editor.Select.MeshGroup.FindParentMeshGroupOfMeshTransform(selectedMeshTransform); if (parentMeshGroup == null || parentMeshGroup == Editor.Select.MeshGroup || isChildMeshTransformSelectable) { Editor.Select.SetSubMeshInGroup(selectedMeshTransform); } else { apTransform_MeshGroup childMeshGroupTransform = Editor.Select.MeshGroup.FindChildMeshGroupTransform(parentMeshGroup); if (childMeshGroupTransform != null) { Editor.Select.SetSubMeshGroupInGroup(childMeshGroupTransform); } else { Editor.Select.SetSubMeshInGroup(selectedMeshTransform); } } } else { Editor.Select.SetSubMeshInGroup(null); } Editor.RefreshControllerAndHierarchy(false); //Editor.Repaint(); Editor.SetRepaint(); } //개수에 따라 한번더 결과 보정 if (Editor.Select.ModRenderVertListOfMod != null) { //return Editor.Select.ModRenderVertListOfMod.Count; return apGizmos.SelectResult.Main.SetMultiple<apSelection.ModRenderVert>(Editor.Select.ModRenderVertListOfMod); } return null; } public void Unselect__Modifier_Physics() { if (Editor.Select.MeshGroup == null || Editor.Select.Modifier == null) { return; } Editor.Select.SetModVertexOfModifier(null, null, null, null); if (!Editor.Select.IsSelectionLock) { Editor.Select.SetSubMeshInGroup(null); } Editor.RefreshControllerAndHierarchy(false); Editor.SetRepaint(); } //--------------------------------------------------------------------------------------- // 단축키 //--------------------------------------------------------------------------------------- public void AddHotKeys__Modifier_Physics(bool isGizmoRenderable, apGizmos.CONTROL_TYPE controlType, bool isFFDMode) { Editor.AddHotKeyEvent(OnHotKeyEvent__Modifier_Physics__Ctrl_A, apHotKey.LabelText.SelectAllVertices, KeyCode.A, false, false, true, null); } // 단축키 : 버텍스 전체 선택 private void OnHotKeyEvent__Modifier_Physics__Ctrl_A(object paramObject) { if (Editor.Select.MeshGroup == null || Editor.Select.Modifier == null) { return; } if (Editor.Select.ModRenderVertListOfMod == null) { return; } if (Editor.Select.ExEditingMode != apSelection.EX_EDIT.None && Editor.Select.ExKey_ModMesh != null && Editor.Select.MeshGroup != null) { //선택된 RenderUnit을 고르자 apRenderUnit targetRenderUnit = Editor.Select.MeshGroup.GetRenderUnit(Editor.Select.ExKey_ModMesh._transform_Mesh); if (targetRenderUnit != null) { //모든 버텍스를 선택 for (int iVert = 0; iVert < targetRenderUnit._renderVerts.Count; iVert++) { apRenderVertex renderVert = targetRenderUnit._renderVerts[iVert]; apModifiedVertexWeight selectedModVertWeight = Editor.Select.ExKey_ModMesh._vertWeights.Find(delegate (apModifiedVertexWeight a) { return renderVert._vertex._uniqueID == a._vertexUniqueID; }); Editor.Select.AddModVertexOfModifier(null, null, selectedModVertWeight, renderVert); } Editor.Gizmos.SetSelectResultForce_Multiple<apSelection.ModRenderVert>(Editor.Select.ModRenderVertListOfMod); Editor.RefreshControllerAndHierarchy(false); //Editor.Repaint(); Editor.SetRepaint(); Editor.Select.AutoSelectModMeshOrModBone(); } } } //--------------------------------------------------------------------------------------- /// <summary> /// Physics Modifier내에서의 Gizmo 이벤트 : Vertex 계열 선택시 [복수 선택] /// </summary> /// <param name="mousePosGL_Min"></param> /// <param name="mousePosGL_Max"></param> /// <param name="mousePosW_Min"></param> /// <param name="mousePosW_Max"></param> /// <param name="areaSelectType"></param> /// <returns></returns> public apGizmos.SelectResult MultipleSelect__Modifier_Physics(Vector2 mousePosGL_Min, Vector2 mousePosGL_Max, Vector2 mousePosW_Min, Vector2 mousePosW_Max, apGizmos.SELECT_TYPE areaSelectType) { if (Editor.Select.MeshGroup == null || Editor.Select.Modifier == null) { return null; } if (Editor.Select.ModRenderVertListOfMod == null) { return null; } // 이건 다중 버텍스 선택밖에 없다. //Transform 선택은 없음 bool isAnyChanged = false; if (Editor.Select.ExEditingMode != apSelection.EX_EDIT.None && Editor.Select.ExKey_ModMesh != null && Editor.Select.MeshGroup != null) { //선택된 RenderUnit을 고르자 apRenderUnit targetRenderUnit = Editor.Select.MeshGroup.GetRenderUnit(Editor.Select.ExKey_ModMesh._transform_Mesh); if (targetRenderUnit != null) { for (int iVert = 0; iVert < targetRenderUnit._renderVerts.Count; iVert++) { apRenderVertex renderVert = targetRenderUnit._renderVerts[iVert]; bool isSelectable = (mousePosW_Min.x < renderVert._pos_World.x && renderVert._pos_World.x < mousePosW_Max.x) && (mousePosW_Min.y < renderVert._pos_World.y && renderVert._pos_World.y < mousePosW_Max.y); if (isSelectable) { apModifiedVertexWeight selectedModVertWeight = Editor.Select.ExKey_ModMesh._vertWeights.Find(delegate (apModifiedVertexWeight a) { return renderVert._vertex._uniqueID == a._vertexUniqueID; }); if (selectedModVertWeight != null) { if (areaSelectType == apGizmos.SELECT_TYPE.Add || areaSelectType == apGizmos.SELECT_TYPE.New) { Editor.Select.AddModVertexOfModifier(null, null, selectedModVertWeight, renderVert); } else { Editor.Select.RemoveModVertexOfModifier(null, null, selectedModVertWeight, renderVert); } isAnyChanged = true; } } } Editor.RefreshControllerAndHierarchy(false); //Editor.Repaint(); Editor.SetRepaint(); } } if (isAnyChanged) { Editor.Select.AutoSelectModMeshOrModBone(); } //return Editor.Select.ModRenderVertListOfMod.Count; return apGizmos.SelectResult.Main.SetMultiple<apSelection.ModRenderVert>(Editor.Select.ModRenderVertListOfMod); } public apGizmos.TransformParam PivotReturn__Modifier_Physics() { //Weight는 Pivot이 없다. return null; } } }
31.727605
194
0.652895
[ "MIT" ]
LuanmaStudio/Seek-The-Trace
Assets/AnyPortrait/Editor/Scripts/Subtool/apGizmoController_Physics.cs
18,359
C#
using GuruComponents.Netrix.WebEditing; using GuruComponents.Netrix.ComInterop; using System; using System.ComponentModel; using System.Web.UI.WebControls; namespace GuruComponents.Netrix.WebEditing.Elements { /// <summary> /// &lt;TITLE ...&gt; gives the page a unique name. /// </summary> /// <remarks> /// Use <see cref="Element.InnerText"/> to check the inner part of title. /// </remarks> public sealed class TitleElement : Element { internal TitleElement(Interop.IHTMLElement peer, IHtmlEditor editor) : base(peer, editor) { } } }
23.653846
77
0.653659
[ "MIT" ]
andydunkel/netrix
Netrix2.0/NetRixMain/NetRix/WebEditing/Elements/HeadElements/TitleElement.cs
615
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SQLite; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Quizzer { public partial class EditQuestion : Form { public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [System.Runtime.InteropServices.DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [System.Runtime.InteropServices.DllImportAttribute("user32.dll")] public static extern bool ReleaseCapture(); private void Draggable_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); } } private void btnExit_Click(object sender, EventArgs e) { HandleExit(); } public void HandleExit() { this.Close(); } public EditQuestion() { InitializeComponent(); txtQuestion.Enabled = false; txtA.Enabled = false; txtB.Enabled = false; txtC.Enabled = false; txtD.Enabled = false; rdoA.Enabled = false; rdoB.Enabled = false; rdoC.Enabled = false; rdoD.Enabled = false; diffDiff.Enabled = false; diffEasy.Enabled = false; diffMod.Enabled = false; Edit.Enabled = false; refreshValues(); } private void btnAdd_Click(object sender, EventArgs e) { if (Editor.QuizFilePath == string.Empty) { DialogResult r = MessageBox.Show("Please open a question file using the Editor first.", "Quizzer Question Adder", MessageBoxButtons.OK); return; } string connString = "Data Source=" + Editor.QuizFilePath + ";"; SQLiteConnection sqlConn = new SQLiteConnection(connString); sqlConn.Open(); string delete = @"DELETE FROM questions WHERE id = @ID"; SQLiteCommand deletion = new SQLiteCommand(delete, sqlConn); deletion.Parameters.Add("@ID", DbType.Int32); deletion.Parameters["@ID"].Value = Int32.Parse(numID.SelectedItem.ToString()); deletion.ExecuteNonQuery(); Int16 difficulty = 0; if (diffEasy.Checked) difficulty = 0; else if (diffMod.Checked) difficulty = 1; else if (diffDiff.Checked) difficulty = 2; Int16 correct = 0; if (rdoA.Checked) correct = 0; else if (rdoB.Checked) correct = 1; else if (rdoC.Checked) correct = 2; else if (rdoD.Checked) correct = 3; string addIntoSQL = @"INSERT INTO questions (id, question, A, B, C, D, correct, difficulty) VALUES (@ID, @Question, @A, @B, @C, @D, @Correct, @Difficulty)"; SQLiteCommand cmd = new SQLiteCommand(addIntoSQL, sqlConn); cmd.Parameters.Add("@ID", DbType.Int32); cmd.Parameters["@ID"].Value = Int32.Parse(numID.SelectedItem.ToString()); cmd.Parameters.Add("@Question", DbType.String); cmd.Parameters["@Question"].Value = txtQuestion.Text; cmd.Parameters.Add("@A", DbType.String); cmd.Parameters["@A"].Value = txtA.Text; cmd.Parameters.Add("@B", DbType.String); cmd.Parameters["@B"].Value = txtB.Text; cmd.Parameters.Add("@C", DbType.String); cmd.Parameters["@C"].Value = txtC.Text; cmd.Parameters.Add("@D", DbType.String); cmd.Parameters["@D"].Value = txtD.Text; cmd.Parameters.Add("@Correct", DbType.Int32); cmd.Parameters["@Correct"].Value = correct; cmd.Parameters.Add("@Difficulty", DbType.Int32); cmd.Parameters["@Difficulty"].Value = difficulty; cmd.ExecuteNonQuery(); Editor.reupdatequestions = true; sqlConn.Close(); status.Text = "Edited question: \"" + txtQuestion.Text + "\""; refreshValues(); } private void refreshValues() { if (Editor.QuizFilePath == string.Empty) { DialogResult r = MessageBox.Show("Please open a question file using the Editor first.", "Quizzer Question Adder", MessageBoxButtons.OK); return; } string connString = "Data Source=" + Editor.QuizFilePath + ";"; SQLiteConnection sqlConn = new SQLiteConnection(connString); sqlConn.Open(); string findAllIDS = @"SELECT `id` FROM questions"; SQLiteCommand allIDS = new SQLiteCommand(findAllIDS, sqlConn); SQLiteDataReader reader = allIDS.ExecuteReader(); List<int> IDs = new List<int>(); while (reader.Read()) IDs.Add(Int32.Parse(reader["id"].ToString())); if (IDs.Count != 0) { IDs.OrderBy(i => i); numID.Items.Clear(); foreach (int i in IDs) numID.Items.Add(i); } } private void update(Object sender, EventArgs e) { if (Editor.QuizFilePath == string.Empty) { DialogResult r = MessageBox.Show("Please open a question file using the Editor first.", "Quizzer Question Adder", MessageBoxButtons.OK); return; } string connString = "Data Source=" + Editor.QuizFilePath + ";"; SQLiteConnection sqlConn = new SQLiteConnection(connString); sqlConn.Open(); string findAllIDS = @"SELECT * FROM questions WHERE id = @ID"; SQLiteCommand allIDS = new SQLiteCommand(findAllIDS, sqlConn); allIDS.Parameters.Add("@ID", DbType.Int32); allIDS.Parameters["@ID"].Value = Int32.Parse(numID.SelectedItem.ToString()); SQLiteDataReader reader = allIDS.ExecuteReader(); status.Text = "Writing previous values..."; while (reader.Read()) { txtQuestion.Enabled = true; txtA.Enabled = true; txtB.Enabled = true; txtC.Enabled = true; txtD.Enabled = true; rdoA.Enabled = true; rdoB.Enabled = true; rdoC.Enabled = true; rdoD.Enabled = true; diffDiff.Enabled = true; diffEasy.Enabled = true; diffMod.Enabled = true; Edit.Enabled = true; rdoA.Checked = false; rdoB.Checked = false; rdoC.Checked = false; rdoD.Checked = false; diffDiff.Checked = false; diffEasy.Checked = false; diffMod.Checked = false; txtQuestion.Text = reader["question"].ToString(); txtA.Text = reader["A"].ToString(); txtB.Text = reader["B"].ToString(); txtC.Text = reader["C"].ToString(); txtD.Text = reader["D"].ToString(); switch (Int32.Parse(reader["correct"].ToString())) { case 0: rdoA.Checked = true; break; case 1: rdoB.Checked = true; break; case 2: rdoC.Checked = true; break; case 3: rdoD.Checked = true; break; } switch (Int32.Parse(reader["difficulty"].ToString())) { case 0: diffEasy.Checked = true; break; case 1: diffMod.Checked = true; break; case 2: diffDiff.Checked = true; break; } Edit.Enabled = true; } status.Text = "Ready."; } private void btnDelete_Click(object sender, EventArgs e) { if (Editor.QuizFilePath == string.Empty) { DialogResult r = MessageBox.Show("Please open a question file using the Editor first.", "Quizzer Question Adder", MessageBoxButtons.OK); return; } string connString = "Data Source=" + Editor.QuizFilePath + ";"; SQLiteConnection sqlConn = new SQLiteConnection(connString); sqlConn.Open(); string delete = @"DELETE FROM questions WHERE id = @ID"; SQLiteCommand deletion = new SQLiteCommand(delete, sqlConn); deletion.Parameters.Add("@ID", DbType.Int32); deletion.Parameters["@ID"].Value = Int32.Parse(numID.SelectedItem.ToString()); deletion.ExecuteNonQuery(); Editor.reupdatequestions = true; sqlConn.Close(); status.Text = "Deleted question: \"" + txtQuestion.Text + "\""; refreshValues(); } } }
39.377593
168
0.525817
[ "MIT" ]
ChlodAlejandro/quizzer-cs
Quizzer/Editor/EditQuestion.cs
9,492
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 ds-2015-04-16.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.DirectoryService.Model { /// <summary> /// Describes a trust relationship between an AWS Managed Microsoft AD directory and an /// external domain. /// </summary> public partial class Trust { private DateTime? _createdDateTime; private string _directoryId; private DateTime? _lastUpdatedDateTime; private string _remoteDomainName; private SelectiveAuth _selectiveAuth; private DateTime? _stateLastUpdatedDateTime; private TrustDirection _trustDirection; private string _trustId; private TrustState _trustState; private string _trustStateReason; private TrustType _trustType; /// <summary> /// Gets and sets the property CreatedDateTime. /// <para> /// The date and time that the trust relationship was created. /// </para> /// </summary> public DateTime CreatedDateTime { get { return this._createdDateTime.GetValueOrDefault(); } set { this._createdDateTime = value; } } // Check to see if CreatedDateTime property is set internal bool IsSetCreatedDateTime() { return this._createdDateTime.HasValue; } /// <summary> /// Gets and sets the property DirectoryId. /// <para> /// The Directory ID of the AWS directory involved in the trust relationship. /// </para> /// </summary> public string DirectoryId { get { return this._directoryId; } set { this._directoryId = value; } } // Check to see if DirectoryId property is set internal bool IsSetDirectoryId() { return this._directoryId != null; } /// <summary> /// Gets and sets the property LastUpdatedDateTime. /// <para> /// The date and time that the trust relationship was last updated. /// </para> /// </summary> public DateTime LastUpdatedDateTime { get { return this._lastUpdatedDateTime.GetValueOrDefault(); } set { this._lastUpdatedDateTime = value; } } // Check to see if LastUpdatedDateTime property is set internal bool IsSetLastUpdatedDateTime() { return this._lastUpdatedDateTime.HasValue; } /// <summary> /// Gets and sets the property RemoteDomainName. /// <para> /// The Fully Qualified Domain Name (FQDN) of the external domain involved in the trust /// relationship. /// </para> /// </summary> public string RemoteDomainName { get { return this._remoteDomainName; } set { this._remoteDomainName = value; } } // Check to see if RemoteDomainName property is set internal bool IsSetRemoteDomainName() { return this._remoteDomainName != null; } /// <summary> /// Gets and sets the property SelectiveAuth. /// <para> /// Current state of selective authentication for the trust. /// </para> /// </summary> public SelectiveAuth SelectiveAuth { get { return this._selectiveAuth; } set { this._selectiveAuth = value; } } // Check to see if SelectiveAuth property is set internal bool IsSetSelectiveAuth() { return this._selectiveAuth != null; } /// <summary> /// Gets and sets the property StateLastUpdatedDateTime. /// <para> /// The date and time that the TrustState was last updated. /// </para> /// </summary> public DateTime StateLastUpdatedDateTime { get { return this._stateLastUpdatedDateTime.GetValueOrDefault(); } set { this._stateLastUpdatedDateTime = value; } } // Check to see if StateLastUpdatedDateTime property is set internal bool IsSetStateLastUpdatedDateTime() { return this._stateLastUpdatedDateTime.HasValue; } /// <summary> /// Gets and sets the property TrustDirection. /// <para> /// The trust relationship direction. /// </para> /// </summary> public TrustDirection TrustDirection { get { return this._trustDirection; } set { this._trustDirection = value; } } // Check to see if TrustDirection property is set internal bool IsSetTrustDirection() { return this._trustDirection != null; } /// <summary> /// Gets and sets the property TrustId. /// <para> /// The unique ID of the trust relationship. /// </para> /// </summary> public string TrustId { get { return this._trustId; } set { this._trustId = value; } } // Check to see if TrustId property is set internal bool IsSetTrustId() { return this._trustId != null; } /// <summary> /// Gets and sets the property TrustState. /// <para> /// The trust relationship state. /// </para> /// </summary> public TrustState TrustState { get { return this._trustState; } set { this._trustState = value; } } // Check to see if TrustState property is set internal bool IsSetTrustState() { return this._trustState != null; } /// <summary> /// Gets and sets the property TrustStateReason. /// <para> /// The reason for the TrustState. /// </para> /// </summary> public string TrustStateReason { get { return this._trustStateReason; } set { this._trustStateReason = value; } } // Check to see if TrustStateReason property is set internal bool IsSetTrustStateReason() { return this._trustStateReason != null; } /// <summary> /// Gets and sets the property TrustType. /// <para> /// The trust relationship type. <code>Forest</code> is the default. /// </para> /// </summary> public TrustType TrustType { get { return this._trustType; } set { this._trustType = value; } } // Check to see if TrustType property is set internal bool IsSetTrustType() { return this._trustType != null; } } }
30.58871
100
0.572634
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DirectoryService/Generated/Model/Trust.cs
7,586
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OnStateEnterBool : StateMachineBehaviour { [Header("Target Bool Parameter")] [Tooltip("The boolean anim parameter that you want to change.")] public string boolName; [Header("Target Status")] [Tooltip("The target status that this boolean anim parameter will change to once it enter to this state.")] public bool status; override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { animator.SetBool(boolName, status); } }
30
111
0.735
[ "MIT" ]
Amulet-Games/VolunsTale-Codes-Repository
Assets/Scripts/Animator State Machine/OnStateEnterBool.cs
602
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> //------------------------------------------------------------------------------ // Generation date: 10/4/2020 2:55:10 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for PayrollCalculationBasis in the schema. /// </summary> public enum PayrollCalculationBasis { All = 0, Custom = 1 } }
29.695652
81
0.490483
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/PayrollCalculationBasis.cs
685
C#
using System; namespace AnAusAutomat.Sensors.GUI.HotKeys { public interface IHotKeyHandler { event EventHandler<HotKeyPressedEventArgs> HotKeyPressed; void Start(); void Stop(); } }
18.333333
65
0.668182
[ "MIT" ]
yannickbock/AnAusAutomat
src/AnAusAutomat.Sensors.GUI/HotKeys/IHotKeyHandler.cs
222
C#
using Xamarin.Forms; using Xamarin.Forms.Xaml; using XF40Demo.ViewModels; namespace XF40Demo.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PowerOverviewPage : ContentPage { private readonly PowerDetailViewModel vm = new PowerDetailViewModel(); public PowerOverviewPage() { InitializeComponent(); BindingContext = vm; } protected override void OnAppearing() { vm.OnAppearing(); } protected override void OnDisappearing() { vm.OnDisappearing(); } } }
18.642857
72
0.741379
[ "MIT" ]
irongut/XF40Demo
XF40Demo/XF40Demo/Views/PowerOverviewPage.xaml.cs
524
C#
using System; using Avalonia.Skia; namespace Avalonia { /// <summary> /// Options for Skia rendering subsystem. /// </summary> public class SkiaOptions { /// <summary> /// Custom gpu factory to use. Can be used to customize behavior of Skia renderer. /// </summary> public Func<ISkiaGpu> CustomGpuFactory { get; set; } /// <summary> /// The maximum number of bytes for video memory to store textures and resources. /// </summary> /// <remarks> /// This is set by default to the recommended value for Avalonia. /// Setting this to null will give you the default Skia value. /// </remarks> public long? MaxGpuResourceSizeBytes { get; set; } = 1024 * 600 * 4 * 12; // ~28mb 12x 1024 x 600 textures. } }
31.653846
116
0.596598
[ "MIT" ]
0x0ade/Avalonia
src/Skia/Avalonia.Skia/SkiaOptions.cs
823
C#
using System; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.user.info.share /// </summary> public class AlipayUserInfoShareRequest : IAopRequest<AlipayUserInfoShareResponse> { #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.user.info.share"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.680851
86
0.609287
[ "MIT" ]
erikzhouxin/CSharpSolution
OSS/Alipay/F2FPayDll/Projects/alipay-sdk-NET20161213174056/Request/AlipayUserInfoShareRequest.cs
2,132
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Outputs.Packages.V1Alpha1 { [OutputType] public sealed class StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLivenessProbeTcpSocket { public readonly string Host; public readonly Pulumi.Kubernetes.Types.Outputs.Packages.V1Alpha1.StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLivenessProbeTcpSocketPort Port; [OutputConstructor] private StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLivenessProbeTcpSocket( string host, Pulumi.Kubernetes.Types.Outputs.Packages.V1Alpha1.StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLivenessProbeTcpSocketPort port) { Host = host; Port = port; } } }
36.333333
171
0.765138
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/crossplane/dotnet/Kubernetes/Crds/Operators/Crossplane/Packages/V1Alpha1/Outputs/StackDefinitionSpecControllerDeploymentSpecTemplateSpecContainersLivenessProbeTcpSocket.cs
1,090
C#
namespace AH.ModuleController.UI.OPR.Forms { partial class frmOPRDashboard { /// <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() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmOPRDashboard)); this.lvwDasboard = new System.Windows.Forms.ListView(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.timer1 = new System.Windows.Forms.Timer(this.components); this.dteDashboardDate = new System.Windows.Forms.DateTimePicker(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.lblDisplay = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.lvwDoctors = new AtiqsControlLibrary.SmartListViewDetails(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.txtStatus = new AtiqsControlLibrary.SmartTextBox(); this.smartLabel8 = new AtiqsControlLibrary.SmartLabel(); this.txtRegName = new AtiqsControlLibrary.SmartTextBox(); this.txtEndtime = new AtiqsControlLibrary.SmartTextBox(); this.smartLabel7 = new AtiqsControlLibrary.SmartLabel(); this.smartLabel6 = new AtiqsControlLibrary.SmartLabel(); this.smartLabel5 = new AtiqsControlLibrary.SmartLabel(); this.smartLabel4 = new AtiqsControlLibrary.SmartLabel(); this.smartLabel3 = new AtiqsControlLibrary.SmartLabel(); this.txtstarttime = new AtiqsControlLibrary.SmartTextBox(); this.txtTheaterName = new AtiqsControlLibrary.SmartTextBox(); this.txtPackageName = new AtiqsControlLibrary.SmartTextBox(); this.txtInchargeName = new AtiqsControlLibrary.SmartTextBox(); this.txtOTDate = new AtiqsControlLibrary.SmartTextBox(); this.smartLabel2 = new AtiqsControlLibrary.SmartLabel(); this.txtRegNo = new AtiqsControlLibrary.SmartTextBox(); this.smartLabel1 = new AtiqsControlLibrary.SmartLabel(); this.lvwPackage = new AtiqsControlLibrary.SmartListViewDetails(); this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.lblDoctorsTotal = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.lblItemRate = new System.Windows.Forms.Label(); this.mnuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.mnuComplete = new System.Windows.Forms.ToolStripMenuItem(); this.mnuCancel = new System.Windows.Forms.ToolStripMenuItem(); this.btnRefresh = new System.Windows.Forms.Button(); this.panel2 = new System.Windows.Forms.Panel(); this.txtNormal = new AtiqsControlLibrary.SmartTextBox(); this.label11 = new System.Windows.Forms.Label(); this.txtCancel = new AtiqsControlLibrary.SmartTextBox(); this.txtEmergency = new AtiqsControlLibrary.SmartTextBox(); this.txtComplete = new AtiqsControlLibrary.SmartTextBox(); this.label10 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.pnlMain.SuspendLayout(); this.pnlTop.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.mnuStrip.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // frmLabel // this.frmLabel.Size = new System.Drawing.Size(0, 33); this.frmLabel.Text = ""; this.frmLabel.Visible = false; // // pnlMain // this.pnlMain.Controls.Add(this.panel2); this.pnlMain.Controls.Add(this.btnRefresh); this.pnlMain.Controls.Add(this.lblItemRate); this.pnlMain.Controls.Add(this.label6); this.pnlMain.Controls.Add(this.lblDoctorsTotal); this.pnlMain.Controls.Add(this.label5); this.pnlMain.Controls.Add(this.label4); this.pnlMain.Controls.Add(this.label3); this.pnlMain.Controls.Add(this.lvwPackage); this.pnlMain.Controls.Add(this.groupBox3); this.pnlMain.Controls.Add(this.lvwDoctors); this.pnlMain.Controls.Add(this.label1); this.pnlMain.Controls.Add(this.dteDashboardDate); this.pnlMain.Controls.Add(this.lvwDasboard); this.pnlMain.Location = new System.Drawing.Point(5, 59); this.pnlMain.Size = new System.Drawing.Size(1514, 607); // // pnlTop // this.pnlTop.Controls.Add(this.groupBox2); this.pnlTop.Size = new System.Drawing.Size(1521, 58); this.pnlTop.Controls.SetChildIndex(this.frmLabel, 0); this.pnlTop.Controls.SetChildIndex(this.btnTopClose, 0); this.pnlTop.Controls.SetChildIndex(this.groupBox2, 0); // // btnEdit // this.btnEdit.Location = new System.Drawing.Point(666, 666); this.btnEdit.Visible = false; // // btnSave // this.btnSave.Location = new System.Drawing.Point(553, 666); this.btnSave.Visible = false; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(779, 666); this.btnDelete.Visible = false; // // btnNew // this.btnNew.Location = new System.Drawing.Point(440, 666); this.btnNew.Visible = false; // // btnClose // this.btnClose.Location = new System.Drawing.Point(1001, 666); this.btnClose.Visible = false; // // btnPrint // this.btnPrint.Location = new System.Drawing.Point(890, 666); this.btnPrint.Visible = false; // // groupBox1 // this.groupBox1.Location = new System.Drawing.Point(0, 705); this.groupBox1.Size = new System.Drawing.Size(1521, 25); // // lvwDasboard // this.lvwDasboard.BackColor = System.Drawing.SystemColors.Control; this.lvwDasboard.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lvwDasboard.LargeImageList = this.imageList1; this.lvwDasboard.Location = new System.Drawing.Point(17, 66); this.lvwDasboard.Name = "lvwDasboard"; this.lvwDasboard.Size = new System.Drawing.Size(970, 301); this.lvwDasboard.TabIndex = 3; this.lvwDasboard.UseCompatibleStateImageBehavior = false; this.lvwDasboard.SelectedIndexChanged += new System.EventHandler(this.lvwDasboard_SelectedIndexChanged); this.lvwDasboard.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lvwDasboard_MouseDown); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "folio.JPG"); this.imageList1.Images.SetKeyName(1, "Depend01.ico"); this.imageList1.Images.SetKeyName(2, "DELETE.ICO"); this.imageList1.Images.SetKeyName(3, "01.jpg"); this.imageList1.Images.SetKeyName(4, "03.jpg"); this.imageList1.Images.SetKeyName(5, "Bed3.jpeg"); this.imageList1.Images.SetKeyName(6, "Cancel1.jpeg"); this.imageList1.Images.SetKeyName(7, "Emer1.jpeg"); this.imageList1.Images.SetKeyName(8, "Normal.jpeg"); // // timer1 // this.timer1.Interval = 15; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // dteDashboardDate // this.dteDashboardDate.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.dteDashboardDate.Format = System.Windows.Forms.DateTimePickerFormat.Short; this.dteDashboardDate.Location = new System.Drawing.Point(475, 28); this.dteDashboardDate.Name = "dteDashboardDate"; this.dteDashboardDate.Size = new System.Drawing.Size(220, 23); this.dteDashboardDate.TabIndex = 4; this.dteDashboardDate.ValueChanged += new System.EventHandler(this.dteDashboardDate_ValueChanged); // // groupBox2 // this.groupBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.groupBox2.Controls.Add(this.lblDisplay); this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox2.Location = new System.Drawing.Point(1, 4); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(1635, 48); this.groupBox2.TabIndex = 43; this.groupBox2.TabStop = false; // // lblDisplay // this.lblDisplay.AutoSize = true; this.lblDisplay.Font = new System.Drawing.Font("Verdana", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblDisplay.ForeColor = System.Drawing.Color.Red; this.lblDisplay.Location = new System.Drawing.Point(1427, 13); this.lblDisplay.Name = "lblDisplay"; this.lblDisplay.Size = new System.Drawing.Size(73, 25); this.lblDisplay.TabIndex = 0; this.lblDisplay.Text = "None"; this.lblDisplay.Click += new System.EventHandler(this.lblDisplay_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(421, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(45, 16); this.label1.TabIndex = 5; this.label1.Text = "Date:"; // // lvwDoctors // this.lvwDoctors.BackColor = System.Drawing.Color.LemonChiffon; this.lvwDoctors.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lvwDoctors.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2}); this.lvwDoctors.Cursor = System.Windows.Forms.Cursors.Hand; this.lvwDoctors.Font = new System.Drawing.Font("Maiandra GD", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lvwDoctors.FullRowSelect = true; this.lvwDoctors.GridLines = true; this.lvwDoctors.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.lvwDoctors.Location = new System.Drawing.Point(1021, 80); this.lvwDoctors.Name = "lvwDoctors"; this.lvwDoctors.Size = new System.Drawing.Size(348, 199); this.lvwDoctors.TabIndex = 6; this.lvwDoctors.UseCompatibleStateImageBehavior = false; this.lvwDoctors.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Doctors Code"; this.columnHeader1.Width = 0; // // columnHeader2 // this.columnHeader2.Text = "Doctors Name"; this.columnHeader2.Width = 480; // // groupBox3 // this.groupBox3.Controls.Add(this.txtStatus); this.groupBox3.Controls.Add(this.smartLabel8); this.groupBox3.Controls.Add(this.txtRegName); this.groupBox3.Controls.Add(this.txtEndtime); this.groupBox3.Controls.Add(this.smartLabel7); this.groupBox3.Controls.Add(this.smartLabel6); this.groupBox3.Controls.Add(this.smartLabel5); this.groupBox3.Controls.Add(this.smartLabel4); this.groupBox3.Controls.Add(this.smartLabel3); this.groupBox3.Controls.Add(this.txtstarttime); this.groupBox3.Controls.Add(this.txtTheaterName); this.groupBox3.Controls.Add(this.txtPackageName); this.groupBox3.Controls.Add(this.txtInchargeName); this.groupBox3.Controls.Add(this.txtOTDate); this.groupBox3.Controls.Add(this.smartLabel2); this.groupBox3.Controls.Add(this.txtRegNo); this.groupBox3.Controls.Add(this.smartLabel1); this.groupBox3.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); this.groupBox3.Location = new System.Drawing.Point(17, 372); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(1002, 141); this.groupBox3.TabIndex = 7; this.groupBox3.TabStop = false; this.groupBox3.Text = "Details Information"; // // txtStatus // this.txtStatus.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtStatus.Location = new System.Drawing.Point(27, 105); this.txtStatus.Name = "txtStatus"; this.txtStatus.Size = new System.Drawing.Size(100, 24); this.txtStatus.TabIndex = 25; this.txtStatus.Visible = false; // // smartLabel8 // this.smartLabel8.AutoSize = true; this.smartLabel8.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel8.Location = new System.Drawing.Point(382, 25); this.smartLabel8.Name = "smartLabel8"; this.smartLabel8.Size = new System.Drawing.Size(101, 14); this.smartLabel8.TabIndex = 24; this.smartLabel8.Text = "Patient Name:"; // // txtRegName // this.txtRegName.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtRegName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtRegName.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtRegName.Location = new System.Drawing.Point(484, 23); this.txtRegName.Name = "txtRegName"; this.txtRegName.ReadOnly = true; this.txtRegName.Size = new System.Drawing.Size(226, 24); this.txtRegName.TabIndex = 23; // // txtEndtime // this.txtEndtime.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtEndtime.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtEndtime.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtEndtime.Location = new System.Drawing.Point(705, 105); this.txtEndtime.Name = "txtEndtime"; this.txtEndtime.ReadOnly = true; this.txtEndtime.Size = new System.Drawing.Size(169, 24); this.txtEndtime.TabIndex = 22; // // smartLabel7 // this.smartLabel7.AutoSize = true; this.smartLabel7.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel7.Location = new System.Drawing.Point(630, 109); this.smartLabel7.Name = "smartLabel7"; this.smartLabel7.Size = new System.Drawing.Size(72, 14); this.smartLabel7.TabIndex = 21; this.smartLabel7.Text = "End Time:"; // // smartLabel6 // this.smartLabel6.AutoSize = true; this.smartLabel6.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel6.Location = new System.Drawing.Point(287, 109); this.smartLabel6.Name = "smartLabel6"; this.smartLabel6.Size = new System.Drawing.Size(81, 14); this.smartLabel6.TabIndex = 20; this.smartLabel6.Text = "Start Time:"; // // smartLabel5 // this.smartLabel5.AutoSize = true; this.smartLabel5.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel5.Location = new System.Drawing.Point(373, 69); this.smartLabel5.Name = "smartLabel5"; this.smartLabel5.Size = new System.Drawing.Size(110, 14); this.smartLabel5.TabIndex = 19; this.smartLabel5.Text = "Package Name:"; // // smartLabel4 // this.smartLabel4.AutoSize = true; this.smartLabel4.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel4.Location = new System.Drawing.Point(24, 66); this.smartLabel4.Name = "smartLabel4"; this.smartLabel4.Size = new System.Drawing.Size(113, 14); this.smartLabel4.TabIndex = 18; this.smartLabel4.Text = "Incharge Name:"; // // smartLabel3 // this.smartLabel3.AutoSize = true; this.smartLabel3.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel3.Location = new System.Drawing.Point(723, 69); this.smartLabel3.Name = "smartLabel3"; this.smartLabel3.Size = new System.Drawing.Size(97, 14); this.smartLabel3.TabIndex = 17; this.smartLabel3.Text = "Theter Name:"; // // txtstarttime // this.txtstarttime.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtstarttime.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtstarttime.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtstarttime.Location = new System.Drawing.Point(368, 106); this.txtstarttime.Name = "txtstarttime"; this.txtstarttime.ReadOnly = true; this.txtstarttime.Size = new System.Drawing.Size(169, 24); this.txtstarttime.TabIndex = 16; // // txtTheaterName // this.txtTheaterName.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtTheaterName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtTheaterName.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtTheaterName.Location = new System.Drawing.Point(825, 63); this.txtTheaterName.Name = "txtTheaterName"; this.txtTheaterName.ReadOnly = true; this.txtTheaterName.Size = new System.Drawing.Size(169, 24); this.txtTheaterName.TabIndex = 15; // // txtPackageName // this.txtPackageName.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtPackageName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtPackageName.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtPackageName.Location = new System.Drawing.Point(484, 66); this.txtPackageName.Name = "txtPackageName"; this.txtPackageName.ReadOnly = true; this.txtPackageName.Size = new System.Drawing.Size(227, 24); this.txtPackageName.TabIndex = 14; // // txtInchargeName // this.txtInchargeName.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtInchargeName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtInchargeName.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtInchargeName.Location = new System.Drawing.Point(138, 64); this.txtInchargeName.Name = "txtInchargeName"; this.txtInchargeName.ReadOnly = true; this.txtInchargeName.Size = new System.Drawing.Size(216, 24); this.txtInchargeName.TabIndex = 13; // // txtOTDate // this.txtOTDate.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtOTDate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtOTDate.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtOTDate.Location = new System.Drawing.Point(825, 24); this.txtOTDate.Name = "txtOTDate"; this.txtOTDate.ReadOnly = true; this.txtOTDate.Size = new System.Drawing.Size(169, 24); this.txtOTDate.TabIndex = 12; // // smartLabel2 // this.smartLabel2.AutoSize = true; this.smartLabel2.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel2.Location = new System.Drawing.Point(754, 26); this.smartLabel2.Name = "smartLabel2"; this.smartLabel2.Size = new System.Drawing.Size(66, 14); this.smartLabel2.TabIndex = 11; this.smartLabel2.Text = "OT Date:"; // // txtRegNo // this.txtRegNo.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.txtRegNo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtRegNo.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtRegNo.Location = new System.Drawing.Point(138, 23); this.txtRegNo.Name = "txtRegNo"; this.txtRegNo.ReadOnly = true; this.txtRegNo.Size = new System.Drawing.Size(218, 24); this.txtRegNo.TabIndex = 10; // // smartLabel1 // this.smartLabel1.AutoSize = true; this.smartLabel1.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold); this.smartLabel1.Location = new System.Drawing.Point(75, 24); this.smartLabel1.Name = "smartLabel1"; this.smartLabel1.Size = new System.Drawing.Size(59, 14); this.smartLabel1.TabIndex = 9; this.smartLabel1.Text = "Reg No:"; // // lvwPackage // this.lvwPackage.BackColor = System.Drawing.Color.LemonChiffon; this.lvwPackage.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lvwPackage.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader4, this.columnHeader5}); this.lvwPackage.Cursor = System.Windows.Forms.Cursors.Hand; this.lvwPackage.Font = new System.Drawing.Font("Maiandra GD", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lvwPackage.FullRowSelect = true; this.lvwPackage.GridLines = true; this.lvwPackage.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.lvwPackage.Location = new System.Drawing.Point(1021, 311); this.lvwPackage.Name = "lvwPackage"; this.lvwPackage.Size = new System.Drawing.Size(346, 235); this.lvwPackage.TabIndex = 8; this.lvwPackage.UseCompatibleStateImageBehavior = false; this.lvwPackage.View = System.Windows.Forms.View.Details; // // columnHeader4 // this.columnHeader4.Text = "Package Item Name"; this.columnHeader4.Width = 250; // // columnHeader5 // this.columnHeader5.Text = "Item Rate"; this.columnHeader5.Width = 130; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.label3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(1021, 60); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(139, 16); this.label3.TabIndex = 9; this.label3.Text = "Doctors Information"; // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.label4.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(1024, 287); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(143, 16); this.label4.TabIndex = 10; this.label4.Text = "Package Information"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); this.label5.Location = new System.Drawing.Point(1180, 288); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(100, 14); this.label5.TabIndex = 11; this.label5.Text = "No of Persons:"; // // lblDoctorsTotal // this.lblDoctorsTotal.AutoSize = true; this.lblDoctorsTotal.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblDoctorsTotal.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); this.lblDoctorsTotal.Location = new System.Drawing.Point(1300, 288); this.lblDoctorsTotal.Name = "lblDoctorsTotal"; this.lblDoctorsTotal.Size = new System.Drawing.Size(16, 16); this.lblDoctorsTotal.TabIndex = 12; this.lblDoctorsTotal.Text = "0"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); this.label6.Location = new System.Drawing.Point(1172, 555); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(76, 14); this.label6.TabIndex = 13; this.label6.Text = "Total Rate:"; // // lblItemRate // this.lblItemRate.AutoSize = true; this.lblItemRate.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblItemRate.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.lblItemRate.Location = new System.Drawing.Point(1300, 554); this.lblItemRate.Name = "lblItemRate"; this.lblItemRate.Size = new System.Drawing.Size(16, 16); this.lblItemRate.TabIndex = 14; this.lblItemRate.Text = "0"; // // mnuStrip // this.mnuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuComplete, this.mnuCancel}); this.mnuStrip.Name = "mnuStrip"; this.mnuStrip.Size = new System.Drawing.Size(120, 48); // // mnuComplete // this.mnuComplete.Name = "mnuComplete"; this.mnuComplete.Size = new System.Drawing.Size(119, 22); this.mnuComplete.Text = "Complete"; this.mnuComplete.Click += new System.EventHandler(this.mnuComplete_Click); // // mnuCancel // this.mnuCancel.Name = "mnuCancel"; this.mnuCancel.Size = new System.Drawing.Size(119, 22); this.mnuCancel.Text = "Cancel"; this.mnuCancel.Click += new System.EventHandler(this.mnuCancel_Click); // // btnRefresh // this.btnRefresh.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.btnRefresh.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnRefresh.ForeColor = System.Drawing.Color.Blue; this.btnRefresh.Image = ((System.Drawing.Image)(resources.GetObject("btnRefresh.Image"))); this.btnRefresh.Location = new System.Drawing.Point(697, 27); this.btnRefresh.Name = "btnRefresh"; this.btnRefresh.Size = new System.Drawing.Size(25, 25); this.btnRefresh.TabIndex = 15; this.btnRefresh.UseVisualStyleBackColor = false; this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click); // // panel2 // this.panel2.BackColor = System.Drawing.Color.MistyRose; this.panel2.Controls.Add(this.txtNormal); this.panel2.Controls.Add(this.label11); this.panel2.Controls.Add(this.txtCancel); this.panel2.Controls.Add(this.txtEmergency); this.panel2.Controls.Add(this.txtComplete); this.panel2.Controls.Add(this.label10); this.panel2.Controls.Add(this.label9); this.panel2.Controls.Add(this.label8); this.panel2.ForeColor = System.Drawing.Color.Yellow; this.panel2.Location = new System.Drawing.Point(17, 518); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(394, 82); this.panel2.TabIndex = 16; // // txtNormal // this.txtNormal.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtNormal.Enabled = false; this.txtNormal.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtNormal.Location = new System.Drawing.Point(289, 12); this.txtNormal.Name = "txtNormal"; this.txtNormal.Size = new System.Drawing.Size(100, 24); this.txtNormal.TabIndex = 7; this.txtNormal.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.ForeColor = System.Drawing.Color.DodgerBlue; this.label11.Location = new System.Drawing.Point(225, 15); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(58, 16); this.label11.TabIndex = 6; this.label11.Text = "Normal:"; // // txtCancel // this.txtCancel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtCancel.Enabled = false; this.txtCancel.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtCancel.Location = new System.Drawing.Point(289, 42); this.txtCancel.Name = "txtCancel"; this.txtCancel.Size = new System.Drawing.Size(100, 24); this.txtCancel.TabIndex = 5; this.txtCancel.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // txtEmergency // this.txtEmergency.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtEmergency.Enabled = false; this.txtEmergency.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtEmergency.ForeColor = System.Drawing.Color.Red; this.txtEmergency.Location = new System.Drawing.Point(102, 42); this.txtEmergency.Name = "txtEmergency"; this.txtEmergency.Size = new System.Drawing.Size(100, 24); this.txtEmergency.TabIndex = 4; this.txtEmergency.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // txtComplete // this.txtComplete.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtComplete.Enabled = false; this.txtComplete.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtComplete.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.txtComplete.Location = new System.Drawing.Point(102, 12); this.txtComplete.Name = "txtComplete"; this.txtComplete.Size = new System.Drawing.Size(100, 24); this.txtComplete.TabIndex = 3; this.txtComplete.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.ForeColor = System.Drawing.Color.DarkOrchid; this.label10.Location = new System.Drawing.Point(227, 45); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(58, 16); this.label10.TabIndex = 2; this.label10.Text = "Cancel:"; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.ForeColor = System.Drawing.Color.Red; this.label9.Location = new System.Drawing.Point(15, 46); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(81, 14); this.label9.TabIndex = 1; this.label9.Text = "Emergency:"; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.ForeColor = System.Drawing.Color.Fuchsia; this.label8.Location = new System.Drawing.Point(13, 14); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(72, 14); this.label8.TabIndex = 0; this.label8.Text = "Complete:"; // // frmOPRDashboard // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.ClientSize = new System.Drawing.Size(1521, 730); this.isEnterTabAllow = true; this.Name = "frmOPRDashboard"; this.Load += new System.EventHandler(this.frmOPRDashboard_Load); this.Controls.SetChildIndex(this.groupBox1, 0); this.Controls.SetChildIndex(this.pnlMain, 0); this.Controls.SetChildIndex(this.pnlTop, 0); this.Controls.SetChildIndex(this.btnSave, 0); this.Controls.SetChildIndex(this.btnEdit, 0); this.Controls.SetChildIndex(this.btnDelete, 0); this.Controls.SetChildIndex(this.btnNew, 0); this.Controls.SetChildIndex(this.btnClose, 0); this.Controls.SetChildIndex(this.btnPrint, 0); this.pnlMain.ResumeLayout(false); this.pnlMain.PerformLayout(); this.pnlTop.ResumeLayout(false); this.pnlTop.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.mnuStrip.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListView lvwDasboard; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.DateTimePicker dteDashboardDate; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label lblDisplay; private System.Windows.Forms.GroupBox groupBox3; private AtiqsControlLibrary.SmartLabel smartLabel6; private AtiqsControlLibrary.SmartLabel smartLabel5; private AtiqsControlLibrary.SmartLabel smartLabel4; private AtiqsControlLibrary.SmartLabel smartLabel3; private AtiqsControlLibrary.SmartTextBox txtstarttime; private AtiqsControlLibrary.SmartTextBox txtTheaterName; private AtiqsControlLibrary.SmartTextBox txtPackageName; private AtiqsControlLibrary.SmartTextBox txtInchargeName; private AtiqsControlLibrary.SmartTextBox txtOTDate; private AtiqsControlLibrary.SmartLabel smartLabel2; private AtiqsControlLibrary.SmartTextBox txtRegNo; private AtiqsControlLibrary.SmartLabel smartLabel1; private AtiqsControlLibrary.SmartListViewDetails lvwDoctors; private System.Windows.Forms.Label label1; private AtiqsControlLibrary.SmartListViewDetails lvwPackage; private AtiqsControlLibrary.SmartTextBox txtEndtime; private AtiqsControlLibrary.SmartLabel smartLabel7; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private AtiqsControlLibrary.SmartTextBox txtRegName; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private AtiqsControlLibrary.SmartLabel smartLabel8; private System.Windows.Forms.Label lblDoctorsTotal; private System.Windows.Forms.Label label5; private System.Windows.Forms.ColumnHeader columnHeader5; private System.Windows.Forms.Label lblItemRate; private System.Windows.Forms.Label label6; private System.Windows.Forms.ContextMenuStrip mnuStrip; private System.Windows.Forms.ToolStripMenuItem mnuComplete; private System.Windows.Forms.ToolStripMenuItem mnuCancel; private System.Windows.Forms.Button btnRefresh; private System.Windows.Forms.Panel panel2; private AtiqsControlLibrary.SmartTextBox txtCancel; private AtiqsControlLibrary.SmartTextBox txtEmergency; private AtiqsControlLibrary.SmartTextBox txtComplete; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label8; private AtiqsControlLibrary.SmartTextBox txtNormal; private System.Windows.Forms.Label label11; private AtiqsControlLibrary.SmartTextBox txtStatus; } }
55.544192
175
0.608624
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/OPR/Forms/frmOPRDashboard.Designer.cs
43,993
C#
namespace NurserySchoolWebPortal.Data.Common.Models { using System; public abstract class BaseDeletableModel<TKey> : BaseModel<TKey>, IDeletableEntity { public bool IsDeleted { get; set; } public DateTime? DeletedOn { get; set; } } }
22.416667
86
0.67658
[ "MIT" ]
DiyanaMancheva/NurserySchoolWebPortal
Data/NurserySchoolWebPortal.Data.Common/Models/BaseDeletableModel.cs
271
C#
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("ArrowPoint CANBus Tool")] [assembly: AssemblyDescription("ArrowPoint CANBus Tool is a tool origionally developed by Jason Queen and Cameron Tuesley. It is used to test and debug all CANBus Systems")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Prohelion & TeamArrow")] [assembly: AssemblyProduct("ArrowPoint CANBus Tool")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e6497f38-3505-4e90-b2b8-b9e58a6bc412")] // 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.6.0.0")] [assembly: AssemblyFileVersion("1.6.0.0")]
42.594595
173
0.754442
[ "MIT" ]
Prohelion/ArrowPoint-CANbus-Tools
ArrowPoint-CANbus-Tools/Properties/AssemblyInfo.cs
1,579
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; namespace Azure.Messaging.EventHubs.Errors { /// <summary> /// An exception which occurs when an <see cref="EventHubConsumerClient" /> is forcefully disconnected /// from an Event Hub instance. This typically occurs when another consumer with higher <see cref="ReadEventOptions.OwnerLevel" /> /// asserts ownership over the partition and consumer group. /// </summary> /// public sealed class ConsumerDisconnectedException : EventHubsException { /// <summary> /// Initializes a new instance of the <see cref="ConsumerDisconnectedException"/> class. /// </summary> /// /// <param name="resourceName">The name of the Event Hubs resource, such as an Event Hub, consumer group, or partition, to which the exception is associated.</param> /// <param name="message">The error message that explains the reason for the exception.</param> /// public ConsumerDisconnectedException(string resourceName, string message) : this(resourceName, message, null) { } /// <summary> /// Initializes a new instance of the <see cref="ConsumerDisconnectedException"/> class. /// </summary> /// /// <param name="resourceName">The name of the Event Hubs resource, such as an Event Hub, consumer group, or partition, to which the exception is associated.</param> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param> /// public ConsumerDisconnectedException(string resourceName, string message, Exception innerException) : base(false, resourceName, message, innerException) { } } }
49.209302
173
0.632325
[ "MIT" ]
Azkel/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/src/Errors/ConsumerDisconnectedException.cs
2,118
C#
// *********************************************************************** // Copyright (c) 2015 Charlie Poole // // 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. // *********************************************************************** using NUnitLite; namespace NUnitLite.Tests { public class Program { /// <summary> /// The main program executes the tests. Output may be routed to /// various locations, depending on the arguments passed. /// </summary> /// <remarks>Run with --help for a full list of arguments supported</remarks> /// <param name="args"></param> public static void Main(string[] args) { System.Environment.Exit(new AutoRun().Execute(args)); } } }
43.756098
85
0.647715
[ "MIT" ]
SallyAbbas/TrYNet
src/tests/Program.cs
1,794
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.ModelsBuilder; using Umbraco.ModelsBuilder.Umbraco; [assembly: PureLiveAssembly] [assembly:ModelsBuilderAssembly(PureLive = true, SourceHash = "62af7f657426dc73")] [assembly:System.Reflection.AssemblyVersion("0.0.0.1")] // FILE: models.generated.cs //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder v8.1.0 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Umbraco.Web.PublishedModels { /// <summary>Folder</summary> [PublishedModel("Folder")] public partial class Folder : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const string ModelTypeAlias = "Folder"; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const PublishedItemType ModelItemType = PublishedItemType.Media; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new static IPublishedContentType GetModelContentType() => PublishedModelUtility.GetModelContentType(ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public static IPublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Folder, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(), selector); #pragma warning restore 0109 // ctor public Folder(IPublishedContent content) : base(content) { } // properties } /// <summary>Image</summary> [PublishedModel("Image")] public partial class Image : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const string ModelTypeAlias = "Image"; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const PublishedItemType ModelItemType = PublishedItemType.Media; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new static IPublishedContentType GetModelContentType() => PublishedModelUtility.GetModelContentType(ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public static IPublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(), selector); #pragma warning restore 0109 // ctor public Image(IPublishedContent content) : base(content) { } // properties ///<summary> /// Size: in bytes ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoBytes")] public long UmbracoBytes => this.Value<long>("umbracoBytes"); ///<summary> /// Type ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension => this.Value<string>("umbracoExtension"); ///<summary> /// Upload image ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoFile")] public Umbraco.Core.PropertyEditors.ValueConverters.ImageCropperValue UmbracoFile => this.Value<Umbraco.Core.PropertyEditors.ValueConverters.ImageCropperValue>("umbracoFile"); ///<summary> /// Height: in pixels ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoHeight")] public int UmbracoHeight => this.Value<int>("umbracoHeight"); ///<summary> /// Width: in pixels ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoWidth")] public int UmbracoWidth => this.Value<int>("umbracoWidth"); } /// <summary>File</summary> [PublishedModel("File")] public partial class File : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const string ModelTypeAlias = "File"; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const PublishedItemType ModelItemType = PublishedItemType.Media; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new static IPublishedContentType GetModelContentType() => PublishedModelUtility.GetModelContentType(ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public static IPublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<File, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(), selector); #pragma warning restore 0109 // ctor public File(IPublishedContent content) : base(content) { } // properties ///<summary> /// Size: in bytes ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoBytes")] public long UmbracoBytes => this.Value<long>("umbracoBytes"); ///<summary> /// Type ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension => this.Value<string>("umbracoExtension"); ///<summary> /// Upload file ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoFile")] public string UmbracoFile => this.Value<string>("umbracoFile"); } /// <summary>Member</summary> [PublishedModel("Member")] public partial class Member : PublishedContentModel { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const string ModelTypeAlias = "Member"; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new const PublishedItemType ModelItemType = PublishedItemType.Member; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public new static IPublishedContentType GetModelContentType() => PublishedModelUtility.GetModelContentType(ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] public static IPublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Member, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(), selector); #pragma warning restore 0109 // ctor public Member(IPublishedContent content) : base(content) { } // properties ///<summary> /// Is Approved ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberApproved")] public bool UmbracoMemberApproved => this.Value<bool>("umbracoMemberApproved"); ///<summary> /// Comments ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberComments")] public string UmbracoMemberComments => this.Value<string>("umbracoMemberComments"); ///<summary> /// Failed Password Attempts ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberFailedPasswordAttempts")] public int UmbracoMemberFailedPasswordAttempts => this.Value<int>("umbracoMemberFailedPasswordAttempts"); ///<summary> /// Last Lockout Date ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberLastLockoutDate")] public DateTime UmbracoMemberLastLockoutDate => this.Value<DateTime>("umbracoMemberLastLockoutDate"); ///<summary> /// Last Login Date ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberLastLogin")] public DateTime UmbracoMemberLastLogin => this.Value<DateTime>("umbracoMemberLastLogin"); ///<summary> /// Last Password Change Date ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberLastPasswordChangeDate")] public DateTime UmbracoMemberLastPasswordChangeDate => this.Value<DateTime>("umbracoMemberLastPasswordChangeDate"); ///<summary> /// Is Locked Out ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberLockedOut")] public bool UmbracoMemberLockedOut => this.Value<bool>("umbracoMemberLockedOut"); ///<summary> /// Password Answer ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberPasswordRetrievalAnswer")] public DateTime UmbracoMemberPasswordRetrievalAnswer => this.Value<DateTime>("umbracoMemberPasswordRetrievalAnswer"); ///<summary> /// Password Question ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.1.0")] [ImplementPropertyType("umbracoMemberPasswordRetrievalQuestion")] public DateTime UmbracoMemberPasswordRetrievalQuestion => this.Value<DateTime>("umbracoMemberPasswordRetrievalQuestion"); } } // EOF
38.269373
177
0.746794
[ "MIT" ]
Nicholas-Westby/umbraco-minify
src/Website/App_Data/Models/all.generated.cs
10,371
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; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; #if !NETSTANDARD2_0 using Internal.Runtime.CompilerServices; #endif namespace System.Runtime.CompilerServices { /// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask"/>.</summary> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable { /// <summary>The wrapped <see cref="Task"/>.</summary> private readonly ValueTask _value; /// <summary>Initializes the awaitable.</summary> /// <param name="value">The wrapped <see cref="ValueTask"/>.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(in ValueTask value) => _value = value; /// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable"/> instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value); /// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable"/>.</summary> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter { /// <summary>The value being awaited.</summary> private readonly ValueTask _value; /// <summary>Initializes the awaiter.</summary> /// <param name="value">The value to be awaited.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(in ValueTask value) => _value = value; /// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable"/> has completed.</summary> public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _value.IsCompleted; } /// <summary>Gets the result of the ValueTask.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetResult() => _value.ThrowIfCompletedUnsuccessfully(); /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary> public void OnCompleted(Action continuation) { object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary> public void UnsafeOnCompleted(Action continuation) { object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) { TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext); } else if (obj != null) { Unsafe.As<IValueTaskSource>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } } } /// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask{TResult}"/>.</summary> /// <typeparam name="TResult">The type of the result produced.</typeparam> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable<TResult> { /// <summary>The wrapped <see cref="ValueTask{TResult}"/>.</summary> private readonly ValueTask<TResult> _value; /// <summary>Initializes the awaitable.</summary> /// <param name="value">The wrapped <see cref="ValueTask{TResult}"/>.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(in ValueTask<TResult> value) => _value = value; /// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable{TResult}"/> instance.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() => new ConfiguredValueTaskAwaiter(in _value); /// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter { /// <summary>The value being awaited.</summary> private readonly ValueTask<TResult> _value; /// <summary>Initializes the awaiter.</summary> /// <param name="value">The value to be awaited.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(in ValueTask<TResult> value) => _value = value; /// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable{TResult}"/> has completed.</summary> public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _value.IsCompleted; } /// <summary>Gets the result of the ValueTask.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public TResult GetResult() => _value.Result; /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void OnCompleted(Action continuation) { object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void UnsafeOnCompleted(Action continuation) { object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) { t.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { ValueTask.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) { TaskAwaiter.UnsafeOnCompletedInternal(t, box, _value._continueOnCapturedContext); } else if (obj != null) { Unsafe.As<IValueTaskSource<TResult>>(obj).OnCompleted(ThreadPoolGlobals.s_invokeAsyncStateMachineBox, box, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } } } }
49.871681
159
0.623104
[ "MIT" ]
939481896/dotnet-corefx
src/Common/src/CoreLib/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs
11,271
C#
using NiconicoToolkit.User; using NiconicoToolkit.Video; using System; using System.Text.Json.Serialization; namespace NiconicoToolkit.Community { public sealed class CommunityVideoListItemsResponse : ResponseWithMeta { [JsonPropertyName("data")] public CommunityVideoListItemsData Data { get; set; } public sealed class CommunityVideoListItemsData { [JsonPropertyName("videos")] public CommunityVideoListItem[] Videos { get; set; } } public sealed class CommunityVideoListItem { [JsonPropertyName("id")] public VideoId Id { get; set; } [JsonPropertyName("member_only")] public bool MemberOnly { get; set; } [JsonPropertyName("title")] public string Title { get; set; } [JsonPropertyName("description")] public string Description { get; set; } [JsonPropertyName("thumbnail_url")] public Uri ThumbnailUrl { get; set; } [JsonPropertyName("latest_comments")] public string[] LatestComments { get; set; } [JsonPropertyName("content_length")] public long ContentLength { get; set; } [JsonPropertyName("user_id")] public UserId UserId { get; set; } [JsonPropertyName("create_time")] public string CreateTime { get; set; } [JsonPropertyName("deleted_reason")] public string DeletedReason { get; set; } public DateTime GetCreateTime() { return DateTimeOffset.Parse(CreateTime).DateTime; } } } }
27.852459
74
0.588582
[ "MIT" ]
tor4kichi/NiconicoToolkit
NiconicoToolkit.Shared/Community/CommunityVideoListItemsResponse.cs
1,701
C#
#region License /*** * Copyright © 2018-2021, 张强 (943620963@qq.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. */ #endregion using Newtonsoft.Json; namespace ZqUtils.Core.WeChat.Models { /// <summary> /// 微信授权返回数据模型 /// </summary> public class OAuthModel { /// <summary> /// 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 /// </summary> [JsonProperty("access_token")] public string Access_Token { get; set; } /// <summary> /// access_token过期时间 /// </summary> [JsonProperty("access_token_expires_in")] public string Access_Token_Expires_In { get; set; } /// <summary> /// 用户刷新access_token /// </summary> [JsonProperty("refresh_token")] public string Refresh_Token { get; set; } /// <summary> /// 用户刷新access_token过期时间 /// </summary> [JsonProperty("refresh_token_expires_in")] public string Refresh_Token_Expires_In { get; set; } /// <summary> /// 用户openId /// </summary> [JsonProperty("openid")] public string OpenId { get; set; } /// <summary> /// 用户授权的作用域 /// </summary> [JsonProperty("scope")] public string Scope { get; set; } } }
28.076923
75
0.608219
[ "Apache-2.0" ]
zqlovejyc/ZqUtils.Core
ZqUtils.Core/WeChat/Models/OAuthModel.cs
1,948
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.HybridCompute.Outputs { /// <summary> /// Specifies the operating system settings for the hybrid machine. /// </summary> [OutputType] public sealed class MachinePropertiesResponseOsProfile { /// <summary> /// Specifies the host OS name of the hybrid machine. /// </summary> public readonly string ComputerName; [OutputConstructor] private MachinePropertiesResponseOsProfile(string computerName) { ComputerName = computerName; } } }
27.935484
81
0.676674
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/HybridCompute/Outputs/MachinePropertiesResponseOsProfile.cs
866
C#
using RimWorld; using Verse; namespace QEthics { public class PawnRelationWorker_SiblingCloneCheck : PawnRelationWorker_Sibling { public override void CreateRelation(Pawn generated, Pawn other, ref PawnGenerationRequest request) { //check if 'other' pawn is a Clone. If so, prevent the relation from happening if (other.health.hediffSet.HasHediff(QEHediffDefOf.QE_CloneStatus)) { return; } else { base.CreateRelation(generated, other, ref request); } } } }
25.541667
106
0.597064
[ "MIT" ]
Danikuh/QuestionableEthicsEnhanced
QEE/Workers/PawnRelationWorker_SiblingCloneCheck.cs
615
C#
/* JustMock Lite Copyright © 2018 Progress Software Corporation 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 System.Reflection; using Telerik.JustMock.Core; using Telerik.JustMock.Expectations.Abstraction.Local; using Telerik.JustMock.Expectations.Abstraction.Local.Function; namespace Telerik.JustMock.Expectations { internal sealed class FunctionExpectation : IFunctionExpectation { public ActionExpectation Arrange(object target, string methodName, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; return this.Arrange(target, methodName, emptyParamTypes, localFunctionName, args); }); } public ActionExpectation Arrange(object target, string methodName, Type[] memberParamTypes, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, memberParamTypes, null); return this.Arrange(target, method, localFunctionName, args); }); } public ActionExpectation Arrange(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange(target, methodName, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public ActionExpectation Arrange(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; return this.Arrange(target, methodName, emptyParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public ActionExpectation Arrange(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange(target, methodName, methodParamTypes, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public ActionExpectation Arrange(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); if(methodGenericTypes != null) { combinedTypes.AddRange(methodGenericTypes); } if (localFunctionGenericTypes != null) { combinedTypes.AddRange(localFunctionGenericTypes); } MethodInfo localMethod = MockingUtil.GetLocalFunction(target, method, localFunctionName, combinedTypes.ToArray()); return Mock.NonPublic.Arrange(target, localMethod, args); }); } public ActionExpectation Arrange(object target, MethodInfo method, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo localMethod = MockingUtil.GetLocalFunction(target, method, localFunctionName, null); return Mock.NonPublic.Arrange(target, localMethod, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(object target, string methodName, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; return this.Arrange<TReturn>(target, methodName, emptyParamTypes, localFunctionName, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] localFunctionGenericTypes = new Type[] { }; return this.Arrange<TReturn>(target, methodName, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; return this.Arrange<TReturn>(target, methodName, emptyParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] localFunctionGenericTypes = new Type[] { }; return this.Arrange<TReturn>(target, methodName, methodParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(target, method, localFunctionName, combinedTypes.ToArray()); return Mock.NonPublic.Arrange<TReturn>(target, localMethod, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(object target, string methodName, Type[] memberParamTypes, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, memberParamTypes, null); return this.Arrange<TReturn>(target, method, localFunctionName, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(object target, MethodInfo method, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = target.GetType(); MethodInfo localMethod = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); return Mock.NonPublic.Arrange<TReturn>(target, localMethod, args); }); } public FuncExpectation<TReturn> Arrange<T, TReturn>(string methodName, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = typeof(T); return this.Arrange<TReturn>(type, methodName, localFunctionName, args); }); } public FuncExpectation<TReturn> Arrange<T, TReturn>(string methodName, string localMemberName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange<T, TReturn>(methodName, localMemberName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<T, TReturn>(string methodName, string localMemberName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptymethodParamTypes = new Type[] { }; return this.Arrange<T, TReturn>(methodName, emptymethodParamTypes, localMemberName, methodGenericTypes, localFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<T, TReturn>(string methodName, Type[] methodParamTypes, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = typeof(T); return this.Arrange<TReturn>(type, methodName, methodParamTypes, localFunctionName, args); }); } public FuncExpectation<TReturn> Arrange<T, TReturn>(string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange<T, TReturn>(methodName, methodParamTypes, localMemberName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<T, TReturn>(string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(typeof(T), methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(typeof(T), method, localMemberName, combinedTypes.ToArray()); return Mock.NonPublic.Arrange<TReturn>(typeof(T), localMethod, args); }); } public FuncExpectation<TReturn> Arrange<T, TReturn>(MethodInfo method, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = typeof(T); return this.Arrange<TReturn>(type, method, localFunctionName, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(Type type, string methodName, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; return this.Arrange<TReturn>(type, methodName, emptyParamTypes, localFunctionName, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(Type type, string methodName, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange<TReturn>(type, methodName, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(Type type, string methodName, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyMethodParamTypes = new Type[] { }; return this.Arrange<TReturn>(type, methodName, emptyMethodParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(Type type, string methodName, Type[] methodParamTypes, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(type, methodName, methodParamTypes, null); return this.Arrange<TReturn>(type, method, localFunctionName, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(Type type, string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange<TReturn>(type, methodName, methodParamTypes, localMemberName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(Type type, string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(type, methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(type, method, localMemberName, combinedTypes.ToArray()); return Mock.NonPublic.Arrange<TReturn>(type, localMethod, args); }); } public FuncExpectation<TReturn> Arrange<TReturn>(Type type, MethodInfo method, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo localMethod = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); return Mock.NonPublic.Arrange<TReturn>(type, localMethod, args); }); } public ActionExpectation Arrange<T>(string methodName, string localMemberName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = typeof(T); return this.Arrange(type, methodName, localMemberName, args); }); } public ActionExpectation Arrange<T>(string methodName, string localMemberName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange<T>(methodName, localMemberName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public ActionExpectation Arrange<T>(string methodName, string localMemberName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyMethodParam = new Type[] { }; return this.Arrange<T>(methodName, emptyMethodParam, localMemberName, methodGenericTypes, localFunctionGenericTypes, args); }); } public ActionExpectation Arrange<T>(string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyGenericLocalTypes = new Type[] { }; return this.Arrange<T>(methodName, methodParamTypes, localMemberName, methodGenericTypes, emptyGenericLocalTypes, args); }); } public ActionExpectation Arrange<T>(string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(typeof(T), methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(typeof(T), method, localMemberName, combinedTypes.ToArray()); return Mock.NonPublic.Arrange(typeof(T), localMethod, args); }); } public ActionExpectation Arrange<T>(string methodName, Type[] methodParamTypes, string localMemberName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = typeof(T); return this.Arrange(type, methodName, methodParamTypes, localMemberName, args); }); } public ActionExpectation Arrange<T>(MethodInfo method, string localMemberName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = typeof(T); return this.Arrange(type, method, localMemberName, args); }); } public ActionExpectation Arrange(Type type, string methodName, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; return this.Arrange(type, methodName, emptyParamTypes, localFunctionName, args); }); } public ActionExpectation Arrange(Type type, string methodName, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange(type, methodName, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public ActionExpectation Arrange(Type type, string methodName, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyMethodParamTypes = new Type[] { }; return this.Arrange(type, methodName, emptyMethodParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public ActionExpectation Arrange(Type type, string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Arrange(type, methodName, methodParamTypes, localMemberName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public ActionExpectation Arrange(Type type, string methodName, Type[] methodParamTypes, string localMemberName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(type, methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(type, method, localMemberName, combinedTypes.ToArray()); return Mock.NonPublic.Arrange(type, localMethod, args); }); } public ActionExpectation Arrange(Type type, string methodName, Type[] methodParamTypes, string localMemberName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(type, methodName, methodParamTypes, null); return this.Arrange(type, method, localMemberName, args); }); } public ActionExpectation Arrange(Type type, MethodInfo method, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); return Mock.NonPublic.Arrange(type, localFunction, args); }); } public object Call(object target, string methodName, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = target.GetType(); MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName); MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); return Mock.NonPublic.MakePrivateAccessor(target).CallMethod(localFunction, args); }); } public T Call<T>(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { var resObject = this.Call(target, methodName, localFunctionName, methodGenericTypes, args); T res = (T)resObject; return res; }); } public T Call<T>(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { var resObject = this.Call(target, methodName, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); T res = (T)resObject; return res; }); } public T Call<T>(object target, string methodName, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; var resObject = this.Call(target, methodName, emptyParamTypes, localFunctionName, args); T res = (T)resObject; return res; }); } public object Call(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Call(target, methodName, methodParamTypes, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public object Call(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(target.GetType(), method, localFunctionName, combinedTypes.ToArray()); return Mock.NonPublic.MakePrivateAccessor(target).CallMethod(localMethod, args); }); } public object Call(object target, string methodName, Type[] methodParamTypes, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = target.GetType(); MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, null); MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); return Mock.NonPublic.MakePrivateAccessor(target).CallMethod(localFunction, args); }); } public object Call(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; return this.Call(target, methodName, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public object Call(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type[] emptyMethodParamTypes = new Type[] { }; return this.Call(target, methodName, emptyMethodParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public T Call<T>(object target, string methodName, Type[] methodParamTypes, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { var resObject = this.Call(target, methodName, methodParamTypes, localFunctionName, args); T res = (T)resObject; return res; }); } public T Call<T>(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { var resObject = this.Call(target, methodName, methodParamTypes, localFunctionName, methodGenericTypes, args); T res = (T)resObject; return res; }); } public T Call<T>(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { var resObject = this.Call(target, methodName, methodParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); T res = (T)resObject; return res; }); } public object Call(object target, MethodInfo method, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { Type type = target.GetType(); MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); return Mock.NonPublic.MakePrivateAccessor(target).CallMethod(localFunction, args); }); } public T Call<T>(object target, MethodInfo method, string localFunctionName, params object[] args) { return ProfilerInterceptor.GuardInternal(() => { var resObject = this.Call(target, method, localFunctionName, args); T res = (T)resObject; return res; }); } public void Assert(object target, MethodInfo method, string localFunctionName, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type type = target.GetType(); MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); Mock.NonPublic.Assert(target, localFunction, args); }); } public void Assert(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; this.Assert(target, methodName, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public void Assert(object target, string methodName, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyMethodParamTypes = new Type[] { }; this.Assert(target, methodName, emptyMethodParamTypes, localFunctionName, methodGenericTypes, localFunctionGenericTypes, args); }); } public void Assert(object target, string methodName, string localFunctionName, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; this.Assert(target, methodName, emptyParamTypes, localFunctionName, args); }); } public void Assert(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; this.Assert(target, methodName, methodParamTypes, localFunctionName, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public void Assert(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(target.GetType(), method, localFunctionName, combinedTypes.ToArray()); Mock.NonPublic.Assert(target, localMethod, args); }); } public void Assert(object target, string methodName, Type[] methodParamTypes, string localFunctionName, params object[] args) { ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, null); this.Assert(target, method, localFunctionName, args); }); } public void Assert(object target, MethodInfo method, string localFunctionName, Occurs occurs, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type type = target.GetType(); MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName, null); Mock.NonPublic.Assert(target, localFunction, occurs, args); }); } public void Assert(object target, string methodName, string localFunctionName, Occurs occurs, Type[] methodGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; this.Assert(target, methodName, localFunctionName, occurs, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public void Assert(object target, string methodName, string localFunctionName, Occurs occurs, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyMethodParamTypes = new Type[] { }; this.Assert(target, methodName, emptyMethodParamTypes, localFunctionName, occurs, methodGenericTypes, localFunctionGenericTypes, args); }); } public void Assert(object target, string methodName, string localFunctionName, Occurs occurs, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyParamTypes = new Type[] { }; this.Assert(target, methodName, emptyParamTypes, localFunctionName, occurs, args); }); } public void Assert(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Occurs occurs, Type[] methodGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { Type[] emptyLocalFunctionGenericTypes = new Type[] { }; this.Assert(target, methodName, methodParamTypes, localFunctionName, occurs, methodGenericTypes, emptyLocalFunctionGenericTypes, args); }); } public void Assert(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Occurs occurs, Type[] methodGenericTypes, Type[] localFunctionGenericTypes, params object[] args) { ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, methodGenericTypes); List<Type> combinedTypes = new List<Type>(); combinedTypes.AddRange(methodGenericTypes); combinedTypes.AddRange(localFunctionGenericTypes); MethodInfo localMethod = MockingUtil.GetLocalFunction(target.GetType(), method, localFunctionName, combinedTypes.ToArray()); Mock.NonPublic.Assert(target, localMethod, occurs, args); }); } public void Assert(object target, string methodName, Type[] methodParamTypes, string localFunctionName, Occurs occurs, params object[] args) { ProfilerInterceptor.GuardInternal(() => { MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes, null); this.Assert(target, method, localFunctionName, occurs, args); }); } } }
46.362184
224
0.669654
[ "Apache-2.0" ]
telerik/JustMockLite
Telerik.JustMock/Expectations/Local/FunctionExpectation.cs
34,821
C#
using System; using System.Collections.Generic; using System.Linq; using PretiaArCloud.Pcx; using UnityEngine; using Utf8Json; namespace PretiaMap2PLY { public static class MapDataConverter { public static (bool isSuccess, Exception err) TryGetPointCloudDataFromMap( string mapData, out List<Vector3> pointCloud ) { var pretiaMapData = JsonSerializer.Deserialize<PretiaPointCloudData>(mapData); if (pretiaMapData == null) { pointCloud = null; return (false, new InvalidOperationException("invalid map data")); } pointCloud = pretiaMapData .GetVertices() .Select(point => new Vector3(point.x, -point.y, point.z)) .ToList(); return (true, null); } } }
27.28125
90
0.581901
[ "Apache-2.0" ]
drumath2237/PretiaMap2PLY
Packages/PretiaMap2PLY/Runtime/MapDataConverter.cs
875
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] public class Crate : MonoBehaviour { public List<AudioClip> clips; private AudioSource audio_; private Player player_; private bool isCarried_; private Rigidbody2D rigidbody_; private BoxCollider2D collider_; void Start() { GameObject playerObject = GameObject.FindGameObjectWithTag("Player"); rigidbody_ = GetComponent<Rigidbody2D>(); collider_ = GetComponent<BoxCollider2D>(); audio_ = GetComponent<AudioSource>(); if (playerObject != null) { player_ = playerObject.GetComponent<Player>(); TypeWriter typeWriter = playerObject.GetComponent<TypeWriter>(); typeWriter.RegisterWord("use", WordListener); typeWriter.RegisterWord("throw", WordListener); } else { Debug.LogWarning("Couldn't find player object in the scene. Crates won't function now."); } } void FixedUpdate() { if (isCarried_) { transform.position = player_.transform.position + (player_.transform.localScale.x * Vector3.right * 1.30f) + (Vector3.up * 0.35f); } } void WordListener(string word) { switch (word) { case "use": if (!isCarried_) { TryPickup(); } else { Drop(); } break; case "throw": if (isCarried_) { TryThrow(); } break; } } void TryPickup() { if (!player_.isCarrying) { float dist = Vector3.Distance(player_.transform.position, transform.position); if (dist <= player_.pickupDistance) { player_.isCarrying = true; isCarried_ = true; rigidbody_.isKinematic = true; player_.pickupCollider.enabled = true; collider_.enabled = false; transform.rotation = Quaternion.identity; } } } void Drop() { player_.isCarrying = false; isCarried_ = false; rigidbody_.isKinematic = false; player_.pickupCollider.enabled = false; collider_.enabled = true; } void TryThrow() { Drop(); int direction = 0; if (player_.transform.position.x < transform.position.x) { direction = 1; } else { direction = -1; } Vector3 force = new Vector3(player_.pickupThrowForce.x * direction, player_.pickupThrowForce.y); rigidbody_.AddForceAtPosition(force, transform.position + (Vector3.left * direction * 0.2f), ForceMode2D.Impulse); } void OnCollisionEnter2D(Collision2D collision) { //audio_.Play(); } }
21.406504
136
0.625902
[ "MIT" ]
SunParlorStudios/LudumDare41
unity/Ludum Dare 41/Assets/Scripts/Crate.cs
2,635
C#
using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Toolbelt.Blazor.Test.Internals { internal class NullHttpMessageHandler : HttpMessageHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var responseMessage = new HttpResponseMessage(HttpStatusCode.NoContent); return Task.FromResult(responseMessage); } } }
31.375
127
0.741036
[ "MPL-2.0" ]
americanslon/Toolbelt.Blazor.HttpClientInterceptor
Toolbelt.Blazor.HttpClientInterceptor.Test/Internals/NullHttpMessageHandler.cs
504
C#
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using NN = MathCore.Annotations.NotNullAttribute; using CN = MathCore.Annotations.CanBeNullAttribute; // ReSharper disable UnusedMember.Global // ReSharper disable ConvertToAutoPropertyWhenPossible // ReSharper disable UnusedMethodReturnValue.Global namespace MathCore.Xml { /// <summary>Настраиваемый сериализатор объектов в XML</summary> public abstract class LambdaXmlSerializer { /// <summary>Создать новый сериализатор объектов</summary> /// <typeparam name="T">Тип сериализуемого класса</typeparam> /// <param name="RootName">Имя корневого элемента (если не указано, то будет использовано имя класса)</param> /// <returns>Сериализатор</returns> [NN] public static LambdaXmlSerializer<T> Create<T>([CN] string RootName = null) => new(RootName ?? typeof(T).Name); } /// <summary>Настраиваемый сериализатор объектов в XML</summary> /// <typeparam name="T">Тип сериализуемого класса</typeparam> public class LambdaXmlSerializer<T> : LambdaXmlSerializer { /// <summary>Название элемента по умолчанию</summary> // ReSharper disable once StaticMemberInGenericType private static string __EmptyName = "item"; /// <summary>Название элемента по умолчанию</summary> public static string EmptyName { get => __EmptyName; set => __EmptyName = value; } /// <summary>Название элемента</summary> [CN] private readonly string _ElementName; /// <summary>Список методов формирования атрибутов элемента</summary> [NN] private readonly List<Func<T, object>> _Attributes = new(); /// <summary>Список методов формирования дочерних элементов</summary> [NN] private readonly List<Func<T, object>> _Elements = new(); /// <summary>Инициализация нового настраиваемого сериализатора</summary> /// <param name="ElementName">Название корневого элемента</param> public LambdaXmlSerializer([CN] string ElementName = null) => _ElementName = ElementName; /// <summary>Выполнение процесса сериализации</summary> /// <param name="value">Сериализуемый объект</param> /// <returns>xml-представление сериализуемого объекта</returns> [NN] public XElement Serialize(T value) => new(_ElementName ?? __EmptyName, Content(value).ToArray()); /// <summary>Выполнение процесса сериализации</summary> /// <param name="Name">Название корневого элемента</param> /// <param name="value">Сериализуемый объект</param> /// <returns>xml-представление сериализуемого объекта</returns> [NN] public XElement Serialize([CN] string Name, T value) => new(Name ?? _ElementName ?? __EmptyName, Content(value).ToArray()); /// <summary>Формирование содержимого элемента</summary> /// <remarks>Выполнение списков методов вычисления значений атрибутов, затем - дочерних элементов</remarks> /// <param name="value">Сериализуемый объект</param> /// <returns>Перечисление атрибутов и дочерних элементов, вкладываемых в корневой элемент</returns> [NN] private IEnumerable<object> Content(T value) => _Attributes.Select(a => a(value)).Concat(_Elements.Select(e => e(value))); /// <summary>Добавление конфигурации атрибута</summary> /// <typeparam name="TValue">ТИп значения атрибута</typeparam> /// <param name="Name">Имя атрибута</param> /// <param name="Selector">Метод определения значения атрибута</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Attribute<TValue>([CN] string Name, [NN] Func<T, TValue> Selector) { _Attributes.Add(v => new XAttribute(Name ?? __EmptyName, Selector(v))); return this; } /// <summary>Добавление конфигурации атрибутов</summary> /// <typeparam name="TItem">Тип данных сериализуемого элемента</typeparam> /// <typeparam name="TValue">Тип значения атрибута</typeparam> /// <param name="Selector">Метод определения набора данных, который должен быть упакован в атрибуты</param> /// <param name="NameSelector">Метод определения имени каждого конкретного атрибута</param> /// <param name="ValueSelector">Метод определения значения каждого конкретного атрибута</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Attributes<TItem, TValue>( [NN] Func<T, IEnumerable<TItem>> Selector, [NN] Func<TItem, string> NameSelector, [NN] Func<TItem, TValue> ValueSelector) { _Attributes.Add(items => Selector(items).ToArray(item => new XAttribute(NameSelector(item), ValueSelector(item)))); return this; } /// <summary>Добавление конфигурации атрибутов</summary> /// <typeparam name="TItem">Тип данных сериализуемого элемента</typeparam> /// <typeparam name="TValue">Тип значения атрибута</typeparam> /// <param name="Selector">Метод определения набора данных, который должен быть упакован в атрибуты</param> /// <param name="NameSelector">Метод определения имени каждого конкретного атрибута</param> /// <param name="NeedToSerialize">Метод, определяющий - требуется ли выполнять сериализацию конкретного значения в атрибут?</param> /// <param name="ValueSelector">Метод определения значения каждого конкретного атрибута</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Attributes<TItem, TValue>( [NN] Func<T, IEnumerable<TItem>> Selector, [NN] Func<TItem, string> NameSelector, [NN] Func<TItem, bool> NeedToSerialize, [NN] Func<TItem, TValue> ValueSelector) { _Attributes.Add(items => Selector(items).Where(NeedToSerialize).ToArray(item => new XAttribute(NameSelector(item), ValueSelector(item)))); return this; } /// <summary>Добавление конфигурации атрибутов</summary> /// <typeparam name="TItem">Тип данных сериализуемого элемента</typeparam> /// <typeparam name="TValue">Тип значения атрибута</typeparam> /// <param name="Selector">Метод определения набора данных, который должен быть упакован в атрибуты</param> /// <param name="NameSelector">Метод определения имени каждого конкретного атрибута в том числе по порядковому номеру</param> /// <param name="ValueSelector">Метод определения значения каждого конкретного атрибута</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Attributes<TItem, TValue>( [NN] Func<T, IEnumerable<TItem>> Selector, [NN] Func<TItem, int, string> NameSelector, [NN] Func<TItem, TValue> ValueSelector) { _Attributes.Add(items => Selector(items).ToArray((item, i) => new XAttribute(NameSelector(item, i), ValueSelector(item)))); return this; } /// <summary>Добавление конфигурации атрибутов</summary> /// <typeparam name="TItem">Тип данных сериализуемого элемента</typeparam> /// <typeparam name="TValue">Тип значения атрибута</typeparam> /// <param name="Selector">Метод определения набора данных, который должен быть упакован в атрибуты</param> /// <param name="NameSelector">Метод определения имени каждого конкретного атрибута в том числе по порядковому номеру</param> /// <param name="NeedToSerialize">Метод, определяющий - требуется ли выполнять сериализацию конкретного значения в атрибут?</param> /// <param name="ValueSelector">Метод определения значения каждого конкретного атрибута</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Attributes<TItem, TValue>( [NN] Func<T, IEnumerable<TItem>> Selector, [NN] Func<TItem, int, string> NameSelector, [NN] Func<TItem, bool> NeedToSerialize, [NN] Func<TItem, TValue> ValueSelector) { _Attributes.Add(items => Selector(items).Where(NeedToSerialize).ToArray((item, i) => new XAttribute(NameSelector(item, i), ValueSelector(item)))); return this; } /// <summary>Добавление конфигурации атрибутов</summary> /// <typeparam name="TItem">Тип данных сериализуемого элемента</typeparam> /// <typeparam name="TValue">Тип значения атрибута</typeparam> /// <param name="Selector">Метод определения набора данных, который должен быть упакован в атрибуты</param> /// <param name="NameSelector">Метод определения имени каждого конкретного атрибута в том числе</param> /// <param name="ValueSelector">Метод определения значения каждого конкретного атрибута по порядковому номеру</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Attributes<TItem, TValue>( [NN] Func<T, IEnumerable<TItem>> Selector, [NN] Func<TItem, string> NameSelector, [NN] Func<TItem, int, TValue> ValueSelector) { _Attributes.Add(element => Selector(element).ToArray((item, i) => new XAttribute(NameSelector(item), ValueSelector(item, i)))); return this; } /// <summary>Добавление конфигурации атрибутов</summary> /// <typeparam name="TItem">Тип данных сериализуемого элемента</typeparam> /// <typeparam name="TValue">Тип значения атрибута</typeparam> /// <param name="Selector">Метод определения набора данных, который должен быть упакован в атрибуты</param> /// <param name="NameSelector">Метод определения имени каждого конкретного атрибута в том числе</param> /// <param name="NeedToSerialize">Метод, определяющий - требуется ли выполнять сериализацию конкретного значения в атрибут?</param> /// <param name="ValueSelector">Метод определения значения каждого конкретного атрибута по порядковому номеру</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Attributes<TItem, TValue>( [NN] Func<T, IEnumerable<TItem>> Selector, [NN] Func<TItem, int, string> NameSelector, [NN] Func<TItem, bool> NeedToSerialize, [NN] Func<TItem, int, TValue> ValueSelector) { _Attributes.Add(element => Selector(element).Where(NeedToSerialize).ToArray((item, i) => new XAttribute(NameSelector(item, i), ValueSelector(item, i)))); return this; } /// <summary>Добавление конфигурации элемента</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="Name">Имя элемента</param> /// <param name="Selector">Метод определения значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Element<TValue>( [CN] string Name, [NN] Func<T, TValue> Selector) { _Elements.Add(v => new XElement(Name ?? __EmptyName, Selector(v))); return this; } /// <summary>Добавление конфигурации элемента</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="Name">Имя элемента</param> /// <param name="Selector">Метод определения значения элемента</param> /// <param name="NeedToSerialize">Метод, определяющий - нужно ли выполнять сериализацию данного элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Element<TValue>( [CN] string Name, [NN] Func<T, TValue> Selector, [NN] Func<TValue, bool> NeedToSerialize) { _Elements.Add(item => { var value = Selector(item); return NeedToSerialize(value) ? new XElement(Name ?? __EmptyName, value) : null; }); return this; } /// <summary>Добавление конфигурации элемента</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="Name">Имя элемента</param> /// <param name="Selector">Метод определения значения элемента</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Element<TValue>( [CN] string Name, [NN] Func<T, TValue> Selector, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(Name); Configurator(serializer); _Elements.Add(value => serializer.Serialize(Selector(value))); return this; } /// <summary>Добавление конфигурации элемента</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="Name">Имя элемента</param> /// <param name="Selector">Метод определения значения элемента</param> /// <param name="NeedToSerialize">Метод, определяющий - нужно ли выполнять сериализацию данного элемента</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Element<TValue>( [CN] string Name, [NN] Func<T, TValue> Selector, [NN] Func<TValue, bool> NeedToSerialize, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(Name); Configurator(serializer); _Elements.Add(item => { var value = Selector(item); return NeedToSerialize(value) ? serializer.Serialize(value) : null; }); return this; } /// <summary>Добавление конфигурации набора элементов</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="Name">Имя элемента</param> /// <param name="ElementsSelector">Метод определения набора значений элементов для сериализации</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Elements<TValue>( [CN] string Name, [NN] Func<T, IEnumerable<TValue>> ElementsSelector, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(Name); Configurator(serializer); _Elements.Add(value => ElementsSelector(value).ToArray(serializer.Serialize)); return this; } /// <summary>Добавление конфигурации набора элементов</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="Name">Имя элемента</param> /// <param name="ElementsSelector">Метод определения набора значений элементов для сериализации</param> /// <param name="NeedToSerialize">Метод, определяющий - нужно ли выполнять сериализацию данного элемента</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Elements<TValue>( [CN] string Name, [NN] Func<T, IEnumerable<TValue>> ElementsSelector, [NN] Func<TValue, bool> NeedToSerialize, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(Name); Configurator(serializer); _Elements.Add(value => ElementsSelector(value).Where(NeedToSerialize).ToArray(serializer.Serialize)); return this; } /// <summary>Добавление конфигурации набора элементов</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="ElementsSelector">Метод определения набора значений элементов для сериализации</param> /// <param name="NameSelector">Метод определения имени элемента</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Elements<TValue>( [NN] Func<T, IEnumerable<TValue>> ElementsSelector, [NN] Func<TValue, string> NameSelector, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(); Configurator(serializer); _Elements.Add(value => ElementsSelector(value).ToArray(v => serializer.Serialize(NameSelector(v), v))); return this; } /// <summary>Добавление конфигурации набора элементов</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="ElementsSelector">Метод определения набора значений элементов для сериализации</param> /// <param name="NameSelector">Метод определения имени элемента</param> /// <param name="NeedToSerialize">Метод, определяющий - нужно ли выполнять сериализацию данного элемента</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Elements<TValue>( [NN] Func<T, IEnumerable<TValue>> ElementsSelector, [NN] Func<TValue, string> NameSelector, [NN] Func<TValue, bool> NeedToSerialize, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(); Configurator(serializer); _Elements.Add(value => ElementsSelector(value).Where(NeedToSerialize).ToArray(v => serializer.Serialize(NameSelector(v), v))); return this; } /// <summary>Добавление конфигурации набора элементов</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="ElementsSelector">Метод определения набора значений элементов для сериализации</param> /// <param name="NameSelector">Метод определения имени элемента</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Elements<TValue>( [NN] Func<T, IEnumerable<TValue>> ElementsSelector, [NN] Func<TValue, int, string> NameSelector, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(); Configurator(serializer); _Elements.Add(value => ElementsSelector(value).ToArray((v, i) => serializer.Serialize(NameSelector(v, i), v))); return this; } /// <summary>Добавление конфигурации набора элементов</summary> /// <typeparam name="TValue">Тип данных значения элемента</typeparam> /// <param name="ElementsSelector">Метод определения набора значений элементов для сериализации</param> /// <param name="NameSelector">Метод определения имени элемента</param> /// <param name="NeedToSerialize">Метод, определяющий - нужно ли выполнять сериализацию данного элемента</param> /// <param name="Configurator">Конфигурация сериализатора значения элемента</param> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Elements<TValue>( [NN] Func<T, IEnumerable<TValue>> ElementsSelector, [NN] Func<TValue, int, string> NameSelector, [NN] Func<TValue, bool> NeedToSerialize, [NN] Action<LambdaXmlSerializer<TValue>> Configurator) { var serializer = new LambdaXmlSerializer<TValue>(); Configurator(serializer); _Elements.Add(value => ElementsSelector(value).Where(NeedToSerialize).ToArray((v, i) => serializer.Serialize(NameSelector(v, i), v))); return this; } /// <summary>Добавление конфигурации, устанавливающий необходимость включения значения сериализуемого объекта</summary> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Value() { _Elements.Add(v => v); return this; } /// <summary>Добавление конфигурации, устанавливающий необходимость включения указанного значения</summary> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Value<TValue>(TValue Value) { _Elements.Add(v => Value); return this; } /// <summary>Добавление конфигурации, устанавливающий необходимость включения значения, определяемого на основе сериализуемого объекта</summary> /// <returns>Исходный сериализатор</returns> [NN] public LambdaXmlSerializer<T> Value<TValue>(Func<T, TValue> Selector) { _Elements.Add(v => Selector(v)); return this; } } }
53.992556
165
0.650811
[ "MIT" ]
Infarh/MathCore
MathCore/Xml/LambdaXmlSerializer.cs
26,986
C#
using System; using System.Collections.Generic; namespace Gem.Engine.AI.BehaviorTree.Decorators { public class Inverter<AIContext> : IDecorator<AIContext> { private readonly IBehaviorNode<AIContext> decoratedNode; private BehaviorResult behaviorResult; public event EventHandler OnBehaved; public Inverter(IBehaviorNode<AIContext> decoratedNode) { this.decoratedNode = decoratedNode; } public IEnumerable<IBehaviorNode<AIContext>> SubNodes { get { yield return decoratedNode; } } public string Name { get; set; } = string.Empty; public BehaviorResult Behave(AIContext context) { if (behaviorResult != BehaviorResult.Running) { return InvokeAndReturn(); } switch (decoratedNode.Behave(context)) { case BehaviorResult.Success: behaviorResult = BehaviorResult.Failure; break; case BehaviorResult.Failure: behaviorResult = BehaviorResult.Success; break; } return InvokeAndReturn(); } private BehaviorResult InvokeAndReturn() { OnBehaved?.Invoke(this, new BehaviorInvokationEventArgs(behaviorResult)); return behaviorResult; } } }
30.06383
85
0.590234
[ "MIT" ]
gmich/Gem
Gem.Engine/AI/BehaviorTree/Decorators/Inverter.cs
1,415
C#
/* * Copyright 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 macie2-2020-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Macie2.Model { /// <summary> /// Provides information about the category, types, and occurrences of sensitive data /// that produced a sensitive data finding. /// </summary> public partial class SensitiveDataItem { private SensitiveDataItemCategory _category; private List<DefaultDetection> _detections = new List<DefaultDetection>(); private long? _totalCount; /// <summary> /// Gets and sets the property Category. /// <para> /// The category of sensitive data that was detected. For example: CREDENTIALS, for credentials /// data such as private keys or Amazon Web Services secret access keys; FINANCIAL_INFORMATION, /// for financial data such as credit card numbers; or, PERSONAL_INFORMATION, for personal /// health information, such as health insurance identification numbers, or personally /// identifiable information, such as passport numbers. /// </para> /// </summary> public SensitiveDataItemCategory Category { get { return this._category; } set { this._category = value; } } // Check to see if Category property is set internal bool IsSetCategory() { return this._category != null; } /// <summary> /// Gets and sets the property Detections. /// <para> /// An array of objects, one for each type of sensitive data that was detected. Each object /// reports the number of occurrences of a specific type of sensitive data that was detected, /// and the location of up to 15 of those occurrences. /// </para> /// </summary> public List<DefaultDetection> Detections { get { return this._detections; } set { this._detections = value; } } // Check to see if Detections property is set internal bool IsSetDetections() { return this._detections != null && this._detections.Count > 0; } /// <summary> /// Gets and sets the property TotalCount. /// <para> /// The total number of occurrences of the sensitive data that was detected. /// </para> /// </summary> public long TotalCount { get { return this._totalCount.GetValueOrDefault(); } set { this._totalCount = value; } } // Check to see if TotalCount property is set internal bool IsSetTotalCount() { return this._totalCount.HasValue; } } }
34.568627
104
0.632161
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Macie2/Generated/Model/SensitiveDataItem.cs
3,526
C#
namespace Problem_3.Collection_of_Products { using System; using System.Collections.Generic; class Program { static void Main() { var collection = new ProductCollection<Product>(); SeedProducts(collection); var productsByTitleAndPrice350 = collection.Find("Neshto", 350); PrintCollection(productsByTitleAndPrice350, "Products with title Neshto and price 350", "######"); var productsInRange220to420 = collection.Find(220, 420); PrintCollection(productsInRange220to420, "Products in range 220 to 420", "######"); var productsBySupplierInRange150to600 = collection.Find(Supplier.Apple, 150, 600); PrintCollection(productsBySupplierInRange150to600, "Products by supplier Apple in range 150 to 420", "######"); //var product10 = new Product("1", "drugoNeshto", Supplier.Toshiba, 77); } static void SeedProducts(ProductCollection<Product> collection) { var product = new Product(1, "Neshto", Supplier.Acer, 350); var product1 = new Product(2, "something", Supplier.Toshiba, 400); var product2 = new Product(3, "something", Supplier.Razer, 377); var product3 = new Product(4, "Neshto", Supplier.Nakov, 420); var product4 = new Product(5, "rick", Supplier.Acer, 280); var product5 = new Product(6, "morty", Supplier.Razer, 500); var product6 = new Product(7, "Stamat", Supplier.Toshiba, 350); var product7 = new Product(8, "something", Supplier.Apple, 350); var product8 = new Product(9, "Neshto", Supplier.Acer, 350); var product9 = new Product(10, "Mariika", Supplier.Nakov, 415); var product10 = new Product(11, "telefonche", Supplier.Apple, 70); var product11 = new Product(12, "SomethingIntrsting", Supplier.Apple, 900); var product12 = new Product(13, "Neshto", Supplier.Nakov, 350); var product13 = new Product(14, "Neshto", Supplier.Razer, 500); var product14 = new Product(15, "Pesho", Supplier.Apple, 140); var product15 = new Product(16, "Gosho", Supplier.Apple, 330); collection.Add(product); collection.Add(product1); collection.Add(product2); collection.Add(product3); collection.Add(product4); collection.Add(product5); collection.Add(product6); collection.Add(product7); collection.Add(product8); collection.Add(product9); collection.Add(product10); collection.Add(product11); collection.Add(product12); collection.Add(product13); collection.Add(product14); collection.Add(product15); } static void PrintCollection(IEnumerable<Product> collection, string startMessage, string endMessage) { Console.WriteLine(startMessage); foreach (Product product in collection) { Console.WriteLine(product); } Console.WriteLine(endMessage); } } }
43.391892
123
0.603862
[ "MIT" ]
Supbads/Softuni-Education
05. Datastructures 02.16/Homework/10. Data-Structure-Efficiency-Homework/Problem 3. Collection of Products/Program.cs
3,213
C#
using UnityEditor.Graphing; using UnityEditor.ShaderGraph.Internal; namespace UnityEditor.ShaderGraph { interface IMayRequireTangent { NeededCoordinateSpace RequiresTangent(ShaderStageCapability stageCapability = ShaderStageCapability.All); } static class MayRequireTangentExtensions { public static NeededCoordinateSpace RequiresTangent(this MaterialSlot slot) { var mayRequireTangent = slot as IMayRequireTangent; return mayRequireTangent != null ? mayRequireTangent.RequiresTangent() : NeededCoordinateSpace.None; } } }
31.2
114
0.716346
[ "MIT" ]
ellcraig/RollABall
Roll-A-Ball/Library/PackageCache/com.unity.shadergraph@10.2.2/Editor/Data/Interfaces/IMayRequireTangent.cs
624
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using FluentAssertions; using KsWare.Presentation.Collections; using NUnit.Framework; namespace KsWare.Presentation.Core.Tests.Collections { [TestFixture()] public class ObservableDictionaryTests { [Test()] public void ObservableDictionaryTest() { var dic = new ObservableDictionary<int,string>(); } [Test()] public void ObservableDictionaryTest1() { var dic0 = new Dictionary<string, string>() {{"a", "1"}}; var dic = new ObservableDictionary<string, string>(dic0); dic.ContainsKey("a").Should().BeTrue(); } [Test()] public void ObservableDictionaryTest2() { var dic0 = new Dictionary<string, string>() {{"a", "1"}}; var dic = new ObservableDictionary<string, string>(dic0, StringComparer.OrdinalIgnoreCase); dic.ContainsKey("A").Should().BeTrue(); } [Test()] public void ObservableDictionaryTest3() { var dic = new ObservableDictionary<string, string>(StringComparer.OrdinalIgnoreCase) {{"a", "1"}}; dic.ContainsKey("A").Should().BeTrue(); } [Test()] public void ObservableDictionaryTest4() { var dic = new ObservableDictionary<string, string>(1,StringComparer.OrdinalIgnoreCase) {{"a", "1"}}; dic.ContainsKey("A").Should().BeTrue(); } [Test()] public void ObservableDictionaryTest5() { var dic = new ObservableDictionary<int, string>(1); dic.Count.Should().Be(0); } [Test()] public void AddTest() { var dic = new ObservableDictionary<int, string>(); List<NotifyCollectionChangedEventArgs> collectionsEvents = new List<NotifyCollectionChangedEventArgs>(); List<PropertyChangedEventArgs> propertyEvents = new List<PropertyChangedEventArgs>(); ((INotifyCollectionChanged) dic).CollectionChanged += (s, e) => collectionsEvents.Add(e); ((INotifyPropertyChanged) dic).PropertyChanged += (s, e) => propertyEvents.Add(e); dic.Add(1,"1"); collectionsEvents[0].Action.Should().Be(NotifyCollectionChangedAction.Add); propertyEvents.First(e => e.PropertyName == "Count").Should().NotBeNull(); dic.Count.Should().Be(1); } [Test()] public void AddTest1() { var dic = new ObservableDictionary<int, string>(); List<NotifyCollectionChangedEventArgs> collectionsEvents = new List<NotifyCollectionChangedEventArgs>(); List<PropertyChangedEventArgs> propertyEvents = new List<PropertyChangedEventArgs>(); var entry = new KeyValuePair<int, string>(1, "1"); ((INotifyCollectionChanged) dic).CollectionChanged += (s, e) => collectionsEvents.Add(e); ((INotifyPropertyChanged) dic).PropertyChanged += (s, e) => propertyEvents.Add(e); dic.Add(entry); collectionsEvents[0].Action.Should().Be(NotifyCollectionChangedAction.Add); propertyEvents.First(e => e.PropertyName == "Count").Should().NotBeNull(); dic.Count.Should().Be(1); } [Test()] public void ContainsKeyTest() { var dic = new ObservableDictionary<int, string>(); dic.Add(1,"1"); dic.ContainsKey(1).Should().BeTrue(); } [Test()] public void RemoveTest() { var dic = new ObservableDictionary<int, string>(); List<NotifyCollectionChangedEventArgs> collectionsEvents = new List<NotifyCollectionChangedEventArgs>(); List<PropertyChangedEventArgs> propertyEvents = new List<PropertyChangedEventArgs>(); dic.Add(1, "1"); ((INotifyCollectionChanged) dic).CollectionChanged += (s, e) => collectionsEvents.Add(e); ((INotifyPropertyChanged) dic).PropertyChanged += (s, e) => propertyEvents.Add(e); dic.Remove(1); collectionsEvents[0].Action.Should().Be(NotifyCollectionChangedAction.Remove); propertyEvents.First(e => e.PropertyName == "Count").Should().NotBeNull(); dic.Count.Should().Be(0); } [Test()] public void RemoveTest1() { var dic = new ObservableDictionary<int, string>(); List<NotifyCollectionChangedEventArgs> collectionsEvents = new List<NotifyCollectionChangedEventArgs>(); List<PropertyChangedEventArgs> propertyEvents = new List<PropertyChangedEventArgs>(); var entry=new KeyValuePair<int,string>(1,"1"); dic.Add(entry); ((INotifyCollectionChanged) dic).CollectionChanged += (s, e) => collectionsEvents.Add(e); ((INotifyPropertyChanged) dic).PropertyChanged += (s, e) => propertyEvents.Add(e); dic.Remove(entry); collectionsEvents[0].Action.Should().Be(NotifyCollectionChangedAction.Remove); propertyEvents.First(e => e.PropertyName == "Count").Should().NotBeNull(); dic.Count.Should().Be(0); } [Test()] public void TryGetValueTest() { var dic = new ObservableDictionary<int, string>(); string value; dic.TryGetValue(1,out value).Should().BeFalse(); dic.Add(1, "1"); dic.Add(2, "2"); dic.TryGetValue(1,out value).Should().BeTrue(); value.Should().Be("1"); } [Test()] public void ClearTest() { var dic = new ObservableDictionary<int, string>(); List<NotifyCollectionChangedEventArgs> collectionsEvents = new List<NotifyCollectionChangedEventArgs>(); List<PropertyChangedEventArgs> propertyEvents = new List<PropertyChangedEventArgs>(); dic.Add(1, "1"); ((INotifyCollectionChanged) dic).CollectionChanged += (s, e) => collectionsEvents.Add(e); ((INotifyPropertyChanged) dic).PropertyChanged += (s, e) => propertyEvents.Add(e); dic.Clear(); collectionsEvents[0].Action.Should().Be(NotifyCollectionChangedAction.Reset); propertyEvents.First(e => e.PropertyName == "Count").Should().NotBeNull(); dic.Count.Should().Be(0); } [Test()] public void ContainsTest() { var dic = new ObservableDictionary<int, string>(); dic.Contains(new KeyValuePair<int, string>(1, null)).Should().BeFalse(); dic.Add(1, "1"); dic.Add(2, "2"); dic.Contains(new KeyValuePair<int, string>(1, "1")).Should().BeTrue(); } [Test()] public void CopyToTest() { var dic = new ObservableDictionary<int, string>(); dic.Add(1, "1"); var array=new KeyValuePair<int, string>[1]; dic.CopyTo(array,0); array[0].Key.Should().Be(1); array[0].Value.Should().Be("1"); } [Test()] public void GetEnumeratorTest() { var dic = new ObservableDictionary<int, string>(); dic.Add(1, "1"); using (var enumerator = dic.GetEnumerator()) { enumerator.Reset(); enumerator.MoveNext().Should().BeTrue(); enumerator.Current.Key.Should().Be(1); enumerator.Current.Value.Should().Be("1"); enumerator.MoveNext().Should().BeFalse(); } } [Test()] public void AddRangeTest() { var dic = new ObservableDictionary<int, string>(); List<NotifyCollectionChangedEventArgs> collectionsEvents = new List<NotifyCollectionChangedEventArgs>(); List<PropertyChangedEventArgs> propertyEvents = new List<PropertyChangedEventArgs>(); ((INotifyCollectionChanged) dic).CollectionChanged += (s, e) => collectionsEvents.Add(e); ((INotifyPropertyChanged) dic).PropertyChanged += (s, e) => propertyEvents.Add(e); dic.AddRange(new Dictionary<int, string>(){{1,"1"},{2, "2"}}); collectionsEvents[0].Action.Should().Be(NotifyCollectionChangedAction.Add); propertyEvents.First(e => e.PropertyName == "Count").Should().NotBeNull(); dic.Count.Should().Be(2); } } }
39.338542
107
0.666755
[ "MIT" ]
KsWare/KsWare.Presentation
src/KsWare.Presentation.Core.Tests/Collections/ObservableDictionaryTests.cs
7,555
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.Services.OpcUa.Twin { using Microsoft.Azure.IIoT.Services.OpcUa.Twin.Runtime; using Microsoft.Azure.IIoT.OpcUa.Edge.Control.Services; using Microsoft.Azure.IIoT.OpcUa.Edge.Export; using Microsoft.Azure.IIoT.OpcUa.Protocol.Services; using Microsoft.Azure.IIoT.OpcUa.Testing.Runtime; using Microsoft.Azure.IIoT.OpcUa.Core.Models; using Microsoft.Azure.IIoT.Hub.Client; using Microsoft.Azure.IIoT.Auth.Models; using Microsoft.Azure.IIoT.Auth; using Microsoft.Azure.IIoT.Utils; using Microsoft.Azure.IIoT.Serializers.NewtonSoft; using Microsoft.Azure.IIoT.Serializers.MessagePack; using Microsoft.Azure.IIoT.Hub; using Microsoft.Azure.IIoT.Hub.Models; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Autofac; using Autofac.Extensions.Hosting; using System; using System.Net.Http; using System.Text; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using System.Linq; /// <summary> /// Startup class for tests /// </summary> public class TestStartup : Startup { /// <summary> /// Create startup /// </summary> /// <param name="env"></param> public TestStartup(IWebHostEnvironment env) : base(env, new Config(null)) { } /// <inheritdoc/> public override void ConfigureContainer(ContainerBuilder builder) { base.ConfigureContainer(builder); builder.RegisterType<TestIoTHubConfig>() .AsImplementedInterfaces(); builder.RegisterType<TestModule>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterType<ClientServices>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterType<TestClientServicesConfig>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterType<AddressSpaceServices>() .AsImplementedInterfaces(); builder.RegisterType<UploadServicesStub<EndpointModel>>() .AsImplementedInterfaces(); builder.RegisterType<VariantEncoderFactory>() .AsImplementedInterfaces().SingleInstance(); builder.RegisterType<TestAuthConfig>() .AsImplementedInterfaces(); } public class TestAuthConfig : IServerAuthConfig { public bool AllowAnonymousAccess => true; public IEnumerable<IOAuthServerConfig> JwtBearerProviders { get; } } public class TestIoTHubConfig : IIoTHubConfig, IIoTHubConfigurationServices { public string IoTHubConnString => ConnectionString.CreateServiceConnectionString( "test.test.org", "iothubowner", Convert.ToBase64String( Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()))).ToString(); public Task ApplyConfigurationAsync(string deviceId, ConfigurationContentModel configuration, CancellationToken ct = default) { return Task.CompletedTask; } public Task<ConfigurationModel> CreateOrUpdateConfigurationAsync( ConfigurationModel configuration, bool forceUpdate, CancellationToken ct = default) { return Task.FromResult<ConfigurationModel>(new ConfigurationModel()); } public Task DeleteConfigurationAsync(string configurationId, string etag, CancellationToken ct = default) { return Task.CompletedTask; } public Task<ConfigurationModel> GetConfigurationAsync(string configurationId, CancellationToken ct = default) { return Task.FromResult<ConfigurationModel>(new ConfigurationModel()); } public Task<IEnumerable<ConfigurationModel>> ListConfigurationsAsync( int? maxCount, CancellationToken ct = default) { return Task.FromResult(Enumerable.Empty<ConfigurationModel>()); } } } /// <inheritdoc/> public class WebAppFixture : WebApplicationFactory<TestStartup>, IHttpClientFactory { public static IEnumerable<object[]> GetSerializers() { yield return new object[] { new MessagePackSerializer() }; yield return new object[] { new NewtonSoftJsonSerializer() }; } /// <inheritdoc/> protected override IHostBuilder CreateHostBuilder() { return Host.CreateDefaultBuilder(); } /// <inheritdoc/> protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseContentRoot(".").UseStartup<TestStartup>(); base.ConfigureWebHost(builder); } /// <inheritdoc/> protected override IHost CreateHost(IHostBuilder builder) { builder.UseAutofac(); return base.CreateHost(builder); } /// <inheritdoc/> public HttpClient CreateClient(string name) { return CreateClient(); } /// <summary> /// Resolve service /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T Resolve<T>() { return (T)Server.Services.GetService(typeof(T)); } } }
39.258503
101
0.624848
[ "MIT" ]
JMayrbaeurl/Industrial-IoT
services/src/Microsoft.Azure.IIoT.Services.OpcUa.Twin/tests/TestStartup.cs
5,771
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; using System.Threading.Tasks; using InceptionCache.Core; using Shouldly; using SimpleLogging.Core; namespace InceptionCache.Providers.InMemoryCacheProvider { public class InMemoryCacheProvider : ICacheProvider, IInMemoryCacheProvider { private readonly ObjectCache _cache; private readonly ILoggingService _loggingService; public InMemoryCacheProvider(ObjectCache cache, ILoggingService loggingService) { cache.ShouldNotBeNull(); loggingService.ShouldNotBeNull(); _cache = cache; _loggingService = loggingService; _loggingService.Info("Created In Memory Cache"); } public string Name => "In-Memory Cache Provider"; public async Task<T> GetAsync<T>(string key) where T : class { key.ShouldNotBeNullOrWhiteSpace(); return Get<T>(key); } public T Get<T>(string key) where T : class { key.ShouldNotBeNullOrWhiteSpace(); LogDebug<T>("GET", key); return (T) _cache.Get(key); } public T[] Get<T>(string[] keys) where T : class { keys.ShouldNotBeNull(); LogDebug<T>("BATCH GET", $"(multiple) ({keys.Length}) keys"); return keys.Select(Get<T>).ToArray(); } public async Task<T[]> GetAsync<T>(string[] keys) where T : class { keys.ShouldNotBeNull(); return Get<T>(keys); } public async Task AddAsync<T>(string key, T value, TimeSpan expiry) where T : class { key.ShouldNotBeNullOrWhiteSpace(); value.ShouldNotBeNull(); await Task.Run(() => Add(key, value, expiry)) .ConfigureAwait(false); } public void Add<T>(string key, T value, TimeSpan expiry) where T : class { key.ShouldNotBeNullOrWhiteSpace(); value.ShouldNotBeNull(); LogDebug<T>("SET", key); var existingItem = _cache.Get(key); if (existingItem != null) { Delete(key); } _cache.Add(key, value, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.UtcNow.AddTicks(expiry.Ticks) }); } public async Task AddAsync<T>(Dictionary<string, T> values, TimeSpan expiry) where T : class { values.ShouldNotBeNull(); await Task.Run(() => Add(values, expiry)).ConfigureAwait(false); } public void Add<T>(Dictionary<string, T> values, TimeSpan expiry) where T : class { values.ShouldNotBeNull() ; foreach (var kv in values) { Add(kv.Key, kv.Value, expiry); } } public async Task DeleteAsync(string key) { key.ShouldNotBeNullOrWhiteSpace(); await Task.Run(() => Delete(key)).ConfigureAwait(false); } public async Task DeleteAsync(string[] keys) { keys.ShouldNotBeNull(); await Task.Run(() => Delete(keys)).ConfigureAwait(false); } public void Delete(string[] keys) { keys.ShouldNotBeNull(); foreach (var key in keys) { Delete(key); } } public void Delete(string key) { key.ShouldNotBeNullOrWhiteSpace(); LogDebug<string>("DELETE", key); _cache.Remove(key); } public long TotalCount() { return _cache.GetCount(); } private void LogDebug<T>(string operation, string key) { operation.ShouldBeNullOrWhiteSpace(); key.ShouldNotBeNullOrWhiteSpace(); _loggingService.Debug($"In-Memory Cache|{operation}|Type:{typeof(T).Name}|Key:{key}"); } } }
28.981132
99
0.486979
[ "MIT" ]
RPM1984/InceptionCache
Code/InceptionCache.Providers.InMemoryCacheProvider/InMemoryCacheProvider.cs
4,610
C#
using UnityEngine; using System.Collections; using BulletUnity; public class MoveKinematicObject : MonoBehaviour { void FixedUpdate() { transform.position = new UnityEngine.Vector3(Mathf.Sin(Time.time),0f,Mathf.Cos(Time.time)) * 5f; //test switching between dynamic and kinematic } }
22.571429
104
0.712025
[ "MIT" ]
ashab015/Unity-Softbody-Cutting
Assets/BulletUnity/Examples/Scripts/MoveKinematicObject.cs
318
C#
namespace Workflow.Steps.Catch; internal class WorkflowTypeCatchStep<TException, TContext> : IWorkflowStep<TContext> where TContext : WorkflowBaseContext where TException : Exception { private readonly Func<TContext, Task> _action; public WorkflowTypeCatchStep(Func<TContext, Task> action) { _action = action; } public WorkflowTypeCatchStep(Action<TContext> action) { _action = context => Task.Run(() => action(context)); } public async Task ExecuteAsync(TContext context) { await _action(context).ConfigureAwait(true); context.Exception = null; } public async Task<bool> ShouldExecuteAsync(TContext context) { return context.Exception is TException && await context.ShouldExecuteAsync().ConfigureAwait(true); } }
27.533333
106
0.690073
[ "MIT" ]
byCrookie/Workflow
src/Workflow/Steps/Catch/WorkflowTypeCatchStep.cs
828
C#