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
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wingdi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { public partial struct DISPLAYCONFIG_PATH_SOURCE_INFO { public LUID adapterId; [NativeTypeName("UINT32")] public uint id; [NativeTypeName("DISPLAYCONFIG_PATH_SOURCE_INFO::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/wingdi.h:2950:5)")] public _Anonymous_e__Union Anonymous; [NativeTypeName("UINT32")] public uint statusFlags; public ref uint modeInfoIdx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous.modeInfoIdx, 1)); } } public uint cloneGroupId { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.cloneGroupId; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.cloneGroupId = value; } } public uint sourceModeInfoIdx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Anonymous.Anonymous.sourceModeInfoIdx; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Anonymous.Anonymous.sourceModeInfoIdx = value; } } [StructLayout(LayoutKind.Explicit)] public partial struct _Anonymous_e__Union { [FieldOffset(0)] [NativeTypeName("UINT32")] public uint modeInfoIdx; [FieldOffset(0)] [NativeTypeName("DISPLAYCONFIG_PATH_SOURCE_INFO::(anonymous struct at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/wingdi.h:2953:9)")] public _Anonymous_e__Struct Anonymous; public partial struct _Anonymous_e__Struct { public uint _bitfield; [NativeTypeName("UINT32 : 16")] public uint cloneGroupId { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _bitfield & 0xFFFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~0xFFFFu) | (value & 0xFFFFu); } } [NativeTypeName("UINT32 : 16")] public uint sourceModeInfoIdx { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (_bitfield >> 16) & 0xFFFFu; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { _bitfield = (_bitfield & ~(0xFFFFu << 16)) | ((value & 0xFFFFu) << 16); } } } } } }
31.672566
164
0.531992
[ "MIT" ]
manju-summoner/terrafx.interop.windows
sources/Interop/Windows/um/wingdi/DISPLAYCONFIG_PATH_SOURCE_INFO.cs
3,581
C#
using System; using System.Globalization; using System.Windows.Data; namespace DeltaEngine.Editor.LevelEditor { public class EnumToBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(parameter); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value.Equals(true) ? parameter : Binding.DoNothing; } } }
25.2
94
0.738095
[ "Apache-2.0" ]
DeltaEngine/DeltaEngine
Editor/LevelEditor/EnumToBooleanConverter.cs
506
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 FrontEndASPNETTest { public partial class About { } }
24.277778
81
0.411899
[ "Apache-2.0" ]
atombryan/ThaiResortFull
ServiceStackHub/Thai Resort/FrontEndASPNETTest/About.aspx.designer.cs
439
C#
using System; namespace UnityEngine.Experimental.U2D.Animation { /// <summary> /// Updates a SpriteRenderer's Sprite reference on the Category and Label value it is set /// </summary> /// <Description> /// By setting the SpriteResolver's Category and Label value, it will request for a Sprite from /// a SpriteLibrary Component the Sprite that is registered for the Category and Label. /// If a SpriteRenderer is present in the same GameObject, the SpriteResolver will update the /// SpriteRenderer's Sprite reference to the corresponding Sprite. /// </Description> [ExecuteInEditMode] [DisallowMultipleComponent] [AddComponentMenu("2D Animation/Sprite Resolver (Experimental)")] [DefaultExecutionOrder(-2)] [HelpURL("https://docs.unity3d.com/Packages/com.unity.2d.animation@4.1/manual/SRComponent.html")] public class SpriteResolver : MonoBehaviour { // These are for animation [SerializeField] private float m_CategoryHash; [SerializeField] private float m_labelHash; // For comparing hash values private int m_CategoryHashInt; private int m_LabelHashInt; // For OnUpdate during animation playback private int m_PreviousCategoryHash; private int m_PreviouslabelHash; #if UNITY_EDITOR bool m_SpriteLibChanged; #endif void OnEnable() { m_CategoryHashInt = ConvertFloatToInt(m_CategoryHash); m_PreviousCategoryHash = m_CategoryHashInt; m_LabelHashInt = ConvertFloatToInt(m_labelHash); m_PreviouslabelHash = m_LabelHashInt; ResolveSpriteToSpriteRenderer(); } SpriteRenderer spriteRenderer { get { return GetComponent<SpriteRenderer>(); } } /// <summary> /// Set the Category and label to use /// </summary> /// <param name="category">Category to use</param> /// <param name="label">Label to use</param> public void SetCategoryAndLabel(string category, string label) { categoryHashInt = SpriteLibraryAsset.GetStringHash(category); m_PreviousCategoryHash = categoryHashInt; labelHashInt = SpriteLibraryAsset.GetStringHash(label); m_PreviouslabelHash = categoryHashInt; ResolveSpriteToSpriteRenderer(); } /// <summary> /// Get the Category set for the SpriteResolver /// </summary> /// <returns>The Category's name</returns> public string GetCategory() { var returnString = ""; var sl = spriteLibrary; if (sl) returnString = sl.GetCategoryNameFromHash(categoryHashInt); return returnString; } /// <summary> /// Get the Label set for the SpriteResolver /// </summary> /// <returns>The Label's name</returns> public string GetLabel() { var returnString = ""; var sl = spriteLibrary; if (sl) returnString = sl.GetLabelNameFromHash(categoryHashInt, labelHashInt); return returnString; } /// <summary> /// Property to get the SpriteLibrary the SpriteResolver is resolving from /// </summary> public SpriteLibrary spriteLibrary { get { var t = transform; while (t != null) { var sl = t.GetComponent<SpriteLibrary>(); if (sl != null) return sl; t = t.parent; } return null; } } void LateUpdate() { m_CategoryHashInt = ConvertFloatToInt(m_CategoryHash); m_LabelHashInt = ConvertFloatToInt(m_labelHash); if (m_LabelHashInt != m_PreviouslabelHash || m_CategoryHashInt != m_PreviousCategoryHash) { m_PreviousCategoryHash = m_CategoryHashInt; m_PreviouslabelHash = m_LabelHashInt; ResolveSpriteToSpriteRenderer(); } } internal Sprite GetSprite(out bool validEntry) { var lib = spriteLibrary; if (lib != null) { return lib.GetSprite(m_CategoryHashInt, m_LabelHashInt, out validEntry); } validEntry = false; return null; } /// <summary> /// Set the Sprite in SpriteResolver to the SpriteRenderer component that is in the same GameObject. /// </summary> public void ResolveSpriteToSpriteRenderer() { m_PreviousCategoryHash = m_CategoryHashInt; m_PreviouslabelHash = m_LabelHashInt; bool validEntry; var sprite = GetSprite(out validEntry); var sr = spriteRenderer; if (sr != null && (sprite != null || validEntry)) sr.sprite = sprite; } void OnTransformParentChanged() { ResolveSpriteToSpriteRenderer(); #if UNITY_EDITOR spriteLibChanged = true; #endif } int categoryHashInt { get { return m_CategoryHashInt; } set { m_CategoryHashInt = value; m_CategoryHash = ConvertIntToFloat(m_CategoryHashInt); } } int labelHashInt { get { return m_LabelHashInt; } set { m_LabelHashInt = value; m_labelHash = ConvertIntToFloat(m_LabelHashInt); } } internal unsafe static int ConvertFloatToInt(float f) { float* fp = &f; int* i = (int*)fp; return *i; } internal unsafe static float ConvertIntToFloat(int f) { int* fp = &f; float* i = (float*)fp; return *i; } #if UNITY_EDITOR internal bool spriteLibChanged { get {return m_SpriteLibChanged;} set { m_SpriteLibChanged = value; } } #endif } }
31.079208
108
0.561166
[ "MIT" ]
BerkTUNA/Project5
Proje5/Library/PackageCache/com.unity.2d.animation@4.2.4/Runtime/SpriteLib/SpriteResolver.cs
6,278
C#
using Spriten.ColorTable; using System.Drawing; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; namespace Spriten.Utility { public static class ThemeHelper { public enum ThemeStyle { Light, Dark } public static Color DockBackColor { get; private set; } public static Color Background { get; private set; } public static Color Foreground { get; private set; } public static Color TreeListBackground { get; private set; } public static Color Pressed { get; private set; } public static Color Hovered { get; private set; } private static ThemeBase mTheme; public static ToolStripProfessionalRenderer ToolStripRenderer { get; private set; } public static ThemeStyle Style { get; private set; } public static ThemeBase Theme { get { return mTheme; } set { if(mTheme != null) mTheme.Dispose(); mTheme = value; // general Background = Theme.ColorPalette.TabSelectedActive.Background; Foreground = Theme.ColorPalette.TabSelectedActive.Text; Pressed = Theme.ColorPalette.TabUnselected.Background; Hovered = Theme.ColorPalette.TabButtonSelectedActiveHovered.Background; ToolStripRenderer = new ToolStripProfessionalRenderer(new MenuStripColorTable(Hovered, Pressed)); if (Background.GetBrightness() > 0.5) { // light DockBackColor = Color.FromArgb(120, 120, 120); TreeListBackground = Color.FromArgb(240, 240, 240); Style = ThemeStyle.Light; } else { // dark DockBackColor = Color.FromArgb(32, 32, 32); TreeListBackground = Color.FromArgb(96, 96, 96); Style = ThemeStyle.Dark; } } } } }
35.016667
113
0.554974
[ "MIT" ]
Chris95Hua/Sproc
Spriten/Utility/ThemeHelper.cs
2,103
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("IntegrationTool.Module.ODBCExecute")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IntegrationTool.Module.ODBCExecute")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("17af3859-ed21-43e7-a547-2cbfe1d6d374")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.945946
84
0.750173
[ "MIT" ]
peterwidmer/IntegrationTool
IntegrationTool.Module.ODBCExecute/Properties/AssemblyInfo.cs
1,444
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LettuceEncrypt4core.Pages { public class PrivacyModel : PageModel { private readonly ILogger<PrivacyModel> _logger; public PrivacyModel(ILogger<PrivacyModel> logger) { _logger = logger; } public void OnGet() { } } }
20.72
57
0.679537
[ "Apache-2.0" ]
densen2014/RookieProject
LettuceEncrypt4core/Pages/Privacy.cshtml.cs
520
C#
namespace Kothar.Server.Interfaces.Marshalling { public interface IInjectionGenerator { } }
16.285714
47
0.666667
[ "MIT" ]
TheWizardAndTheWyrd/Kothar
Kothar.Server.Interfaces/Marshalling/IInjectionGenerator.cs
116
C#
using Common; using Portal.Entities; using Portal.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Helpers; namespace Portal.Repositories { public interface IPermissionRepository { Task<int> Count(PermissionFilter PermissionFilter); Task<List<Permission>> List(PermissionFilter PermissionFilter); Task<Permission> Get(long Id); Task<bool> Create(Permission Permission); Task<bool> Update(Permission Permission); Task<bool> Delete(Permission Permission); Task<bool> BulkMerge(List<Permission> Permissions); Task<bool> BulkDelete(List<Permission> Permissions); } public class PermissionRepository : IPermissionRepository { private DataContext DataContext; public PermissionRepository(DataContext DataContext) { this.DataContext = DataContext; } private IQueryable<PermissionDAO> DynamicFilter(IQueryable<PermissionDAO> query, PermissionFilter filter) { if (filter == null) return query.Where(q => false); if (filter.Id != null) query = query.Where(q => q.Id, filter.Id); if (filter.Name != null) query = query.Where(q => q.Name, filter.Name); if (filter.RoleId != null) query = query.Where(q => q.RoleId, filter.RoleId); query = OrFilter(query, filter); return query; } private IQueryable<PermissionDAO> OrFilter(IQueryable<PermissionDAO> query, PermissionFilter filter) { if (filter.OrFilter == null) return query; IQueryable<PermissionDAO> initQuery = query.Where(q => false); foreach (PermissionFilter PermissionFilter in filter.OrFilter) { IQueryable<PermissionDAO> queryable = query; if (filter.Id != null) queryable = queryable.Where(q => q.Id, filter.Id); if (filter.Name != null) queryable = queryable.Where(q => q.Name, filter.Name); if (filter.RoleId != null) queryable = queryable.Where(q => q.RoleId, filter.RoleId); initQuery = initQuery.Union(queryable); } return initQuery; } private IQueryable<PermissionDAO> DynamicOrder(IQueryable<PermissionDAO> query, PermissionFilter filter) { switch (filter.OrderType) { case OrderType.ASC: switch (filter.OrderBy) { case PermissionOrder.Id: query = query.OrderBy(q => q.Id); break; case PermissionOrder.Name: query = query.OrderBy(q => q.Name); break; case PermissionOrder.Role: query = query.OrderBy(q => q.RoleId); break; } break; case OrderType.DESC: switch (filter.OrderBy) { case PermissionOrder.Id: query = query.OrderByDescending(q => q.Id); break; case PermissionOrder.Name: query = query.OrderByDescending(q => q.Name); break; case PermissionOrder.Role: query = query.OrderByDescending(q => q.RoleId); break; } break; } query = query.Skip(filter.Skip).Take(filter.Take); return query; } private async Task<List<Permission>> DynamicSelect(IQueryable<PermissionDAO> query, PermissionFilter filter) { List<Permission> Permissions = await query.Select(q => new Permission() { Id = filter.Selects.Contains(PermissionSelect.Id) ? q.Id : default(long), Name = filter.Selects.Contains(PermissionSelect.Name) ? q.Name : default(string), RoleId = filter.Selects.Contains(PermissionSelect.Role) ? q.RoleId : default(long), Role = filter.Selects.Contains(PermissionSelect.Role) && q.Role != null ? new Role { Id = q.Role.Id, Name = q.Role.Name, } : null, }).ToListAsync(); return Permissions; } public async Task<int> Count(PermissionFilter filter) { IQueryable<PermissionDAO> Permissions = DataContext.Permission; Permissions = DynamicFilter(Permissions, filter); return await Permissions.CountAsync(); } public async Task<List<Permission>> List(PermissionFilter filter) { if (filter == null) return new List<Permission>(); IQueryable<PermissionDAO> PermissionDAOs = DataContext.Permission; PermissionDAOs = DynamicFilter(PermissionDAOs, filter); PermissionDAOs = DynamicOrder(PermissionDAOs, filter); List<Permission> Permissions = await DynamicSelect(PermissionDAOs, filter); return Permissions; } public async Task<Permission> Get(long Id) { Permission Permission = await DataContext.Permission.Where(x => x.Id == Id).Select(x => new Permission() { Id = x.Id, Name = x.Name, RoleId = x.RoleId, Role = x.Role == null ? null : new Role { Id = x.Role.Id, Name = x.Role.Name, }, }).FirstOrDefaultAsync(); if (Permission == null) return null; Permission.PermissionDatas = await DataContext.PermissionData .Where(x => x.PermissionId == Permission.Id) .Select(x => new PermissionData { Id = x.Id, PermissionId = x.PermissionId, PermissionFieldId = x.PermissionFieldId, Value = x.Value, }).ToListAsync(); Permission.Pages = await DataContext.PermissionPageMapping .Where(x => x.PermissionId == Permission.Id) .Select(x => new Page { Id = x.Page.Id, Name = x.Page.Name, Path = x.Page.Path, ViewId = x.Page.ViewId, IsDeleted = x.Page.IsDeleted, }).ToListAsync(); return Permission; } public async Task<bool> Create(Permission Permission) { PermissionDAO PermissionDAO = new PermissionDAO(); PermissionDAO.Id = Permission.Id; PermissionDAO.Name = Permission.Name; PermissionDAO.RoleId = Permission.RoleId; DataContext.Permission.Add(PermissionDAO); await DataContext.SaveChangesAsync(); Permission.Id = PermissionDAO.Id; await SaveReference(Permission); return true; } public async Task<bool> Update(Permission Permission) { PermissionDAO PermissionDAO = DataContext.Permission.Where(x => x.Id == Permission.Id).FirstOrDefault(); if (PermissionDAO == null) return false; PermissionDAO.Id = Permission.Id; PermissionDAO.Name = Permission.Name; PermissionDAO.RoleId = Permission.RoleId; await DataContext.SaveChangesAsync(); await SaveReference(Permission); return true; } public async Task<bool> Delete(Permission Permission) { await DataContext.PermissionData.Where(x => x.PermissionId == Permission.Id).DeleteFromQueryAsync(); await DataContext.PermissionPageMapping.Where(x => x.PermissionId == Permission.Id).DeleteFromQueryAsync(); await DataContext.Permission.Where(x => x.Id == Permission.Id).DeleteFromQueryAsync(); return true; } public async Task<bool> BulkMerge(List<Permission> Permissions) { List<PermissionDAO> PermissionDAOs = new List<PermissionDAO>(); foreach (Permission Permission in Permissions) { PermissionDAO PermissionDAO = new PermissionDAO(); PermissionDAO.Id = Permission.Id; PermissionDAO.Name = Permission.Name; PermissionDAO.RoleId = Permission.RoleId; PermissionDAOs.Add(PermissionDAO); } await DataContext.BulkMergeAsync(PermissionDAOs); return true; } public async Task<bool> BulkDelete(List<Permission> Permissions) { List<long> Ids = Permissions.Select(x => x.Id).ToList(); await DataContext.PermissionData.Where(x => Ids.Contains(x.PermissionId)).DeleteFromQueryAsync(); await DataContext.PermissionPageMapping.Where(x => Ids.Contains(x.PermissionId)).DeleteFromQueryAsync(); await DataContext.Permission.Where(x => Ids.Contains(x.Id)).DeleteFromQueryAsync(); return true; } private async Task SaveReference(Permission Permission) { await DataContext.PermissionData .Where(x => x.PermissionId == Permission.Id) .DeleteFromQueryAsync(); List<PermissionDataDAO> PermissionDataDAOs = new List<PermissionDataDAO>(); if (Permission.PermissionDatas != null) { foreach (PermissionData PermissionData in Permission.PermissionDatas) { PermissionDataDAO PermissionDataDAO = new PermissionDataDAO(); PermissionDataDAO.Id = PermissionData.Id; PermissionDataDAO.PermissionId = PermissionData.PermissionId; PermissionDataDAO.PermissionFieldId = PermissionData.PermissionFieldId; PermissionDataDAO.Value = PermissionData.Value; PermissionDataDAOs.Add(PermissionDataDAO); } await DataContext.PermissionData.BulkMergeAsync(PermissionDataDAOs); } await DataContext.PermissionPageMapping.Where(x => x.PermissionId == Permission.Id).DeleteFromQueryAsync(); if (Permission.Pages != null) { List<PermissionPageMappingDAO> PermissionPageMappingDAOs = Permission.Pages .Select(x => new PermissionPageMappingDAO { PageId = x.Id, PermissionId = Permission.Id, }).ToList(); await DataContext.PermissionPageMapping.BulkInsertAsync(PermissionPageMappingDAOs); } } } }
42.558491
119
0.549566
[ "Apache-2.0" ]
LeDucThang/Portal
Portal.BE/Repositories/PermissionRepository.cs
11,278
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; using System.Globalization; using System.Collections.Generic; namespace System { [Immutable] public class String { [System.Runtime.CompilerServices.IndexerName("Chars")] public char this[int index] { get { Contract.Requires(0 <= index); Contract.Requires(index < this.Length); return default(char); } } public int Length { [Pure] [Reads(ReadsAttribute.Reads.Nothing)] get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } } #if !SILVERLIGHT [Pure] [GlobalAccess(false)] [Escapes(true, false)] public CharEnumerator GetEnumerator() { // Contract.Ensures(Contract.Result<string>().IsNew); Contract.Ensures(Contract.Result<CharEnumerator>() != null); return default(CharEnumerator); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String IsInterned(String str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>() == null || Contract.Result<string>().Length == str.Length); Contract.Ensures(Contract.Result<string>() == null || str.Equals(Contract.Result<string>())); return default(String); } public static String Intern(String str) { Contract.Requires(str != null); Contract.Ensures(Contract.Result<string>().Length == str.Length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String[] values) { Contract.Requires(values != null); //Contract.Ensures(Contract.Result<string>().Length == Sum({ String s in values); s.Length })); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1, String str2, String str3) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length) + (str2 == null ? 0 : str2.Length) + (str3 == null ? 0 : str3.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1, String str2) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length) + (str2 == null ? 0 : str2.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(String str0, String str1) { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == (str0 == null ? 0 : str0.Length) + (str1 == null ? 0 : str1.Length)); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object[] args) { Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1, object arg2, object arg3) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1, object arg2) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0, object arg1) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(object arg0) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if NETFRAMEWORK_4_0 || NETFRAMEWORK_4_5 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat(IEnumerable<string> args) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Concat<T>(IEnumerable<T> args) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Copy(String str) { Contract.Requires(str != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object[] args) { Contract.Requires(format != null); Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if NETFRAMEWORK_4_6 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object arg0, object arg1, object arg2) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object arg0, object arg1) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(IFormatProvider provider, String format, object arg0) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object[] args) { Contract.Requires(format != null); Contract.Requires(args != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0, object arg1, object arg2) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0, object arg1) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Format(String format, object arg0) { Contract.Requires(format != null); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] public String Remove(int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex < this.Length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<String>().Length == startIndex); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Remove(int index, int count) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= Length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length - count); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Replace(String oldValue, String newValue) { Contract.Requires(oldValue != null); Contract.Requires(oldValue.Length > 0); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Replace(char oldChar, char newChar) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Insert(int startIndex, String value) { Contract.Requires(value != null); Contract.Requires(0 <= startIndex); Contract.Requires(startIndex <= this.Length); // When startIndex == this.Length, then it is added at the end of the instance Contract.Ensures(Contract.Result<string>().Length == this.Length + value.Length); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Trim() { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToUpper(System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length, "Are there languages for which this isn't true?!?"); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToUpper() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } #if !SILVERLIGHT [Pure] public string ToUpperInvariant() { Contract.Ensures(Contract.Result<string>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(string); } #endif [Pure] public String ToLower(System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToLower() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == this.Length); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String ToLowerInvariant() { Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<String>().Length == this.Length); return default(String); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool StartsWith(String value, bool ignoreCase, CultureInfo culture) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadRight(int totalWidth) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadRight(int totalWidth, char paddingChar) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadLeft(int totalWidth, char paddingChar) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String PadLeft(int totalWidth) { Contract.Requires(totalWidth >= 0); Contract.Ensures(Contract.Result<string>().Length == totalWidth); Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value) { Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value) { Contract.Requires(value != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value, int startIndex) { Contract.Requires(this == Empty || startIndex >= 0); Contract.Requires(this == Empty || startIndex < this.Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex) { Contract.Requires(value != null); Contract.Requires(this == Empty || startIndex >= 0); Contract.Requires(this == Empty || startIndex < this.Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(char value, int startIndex, int count) { Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= startIndex - count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || startIndex + 1 - count >= 0); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf) { Contract.Requires(anyOf != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf, int startIndex) { Contract.Requires(anyOf != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { Contract.Requires(anyOf != null); Contract.Requires(this == String.Empty || startIndex >= 0); Contract.Requires(this == String.Empty || startIndex < this.Length); Contract.Requires(this == String.Empty || count >= 0); Contract.Requires(this == String.Empty || startIndex - count >= 0); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(char value) { Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value) { Contract.Requires(value != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() <= Length - value.Length); return default(int); } // F: Funny enough the IndexOf* family do not have the special case for the empty string... [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(char value, int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] public int IndexOf(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() <= Length - value.Length); Contract.Ensures(value != String.Empty || Contract.Result<int>() == 0); return default(int); } [Pure] public int IndexOf(char value, int startIndex, int count) { Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < startIndex + count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < startIndex + count); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] public int IndexOf(String value, int startIndex, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < Length); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(value == String.Empty || Contract.Result<int>() < startIndex + count); Contract.Ensures(Contract.Result<int>() == -1 || Contract.Result<int>() >= startIndex); Contract.Ensures(value != String.Empty || Contract.Result<int>() == startIndex); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf) { Contract.Requires(anyOf != null); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf, int startIndex) { Contract.Requires(anyOf != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public int IndexOfAny(char[] anyOf, int startIndex, int count) { Contract.Requires(anyOf != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= Length); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Length); return default(int); } public static readonly string/*!*/ Empty; [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || value.Length <= this.Length); return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value, StringComparison comparisonType) { Contract.Requires(value != null); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public bool EndsWith(String value, bool ignoreCase, CultureInfo culture) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } #endif [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int CompareOrdinal(String strA, String strB) { return default(int); } [Pure] public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); // From the documentation (and a quick test) one can derive that == is admissible Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, String strB) { return default(int); } #if !SILVERLIGHT [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); return default(int); } #endif [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options) { Contract.Requires(culture != null); return default(int); } [Pure] public static int Compare(string strA, string strB, StringComparison comparisonType) { return default(int); } [Pure] public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); Contract.Requires(Enum.IsDefined(typeof(StringComparison), comparisonType)); return default(int); } [Pure] public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) { Contract.Requires(culture != null); return default(int); } [Pure] public static int Compare(String strA, int indexA, String strB, int indexB, int length) { Contract.Requires(indexA >= 0); Contract.Requires(indexB >= 0); Contract.Requires(length >= 0); Contract.Requires(indexA <= strA.Length); Contract.Requires(indexB <= strB.Length); Contract.Requires((strA != null && strB != null) || length == 0); return default(int); } #if !SILVERLIGHT [Pure] public static int Compare(String strA, String strB, bool ignoreCase, System.Globalization.CultureInfo culture) { Contract.Requires(culture != null); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static int Compare(String strA, String strB, bool ignoreCase) { return default(int); } #endif [Pure] public bool Contains(string value) { Contract.Requires(value != null); Contract.Ensures(!Contract.Result<bool>() || this.Length >= value.Length); return default(bool); } public String(char c, int count) { Contract.Ensures(this.Length == count); } public String(char[] array) { Contract.Ensures(array != null || this.Length == 0); Contract.Ensures(array == null || this.Length == array.Length); } public String(char[] value, int startIndex, int length) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(length >= 0); Contract.Requires(startIndex + length <= value.Length); Contract.Ensures(this.Length == length); } /* These should all be pointer arguments return default(String); } public String (ref SByte arg0, int arg1, int arg2, System.Text.Encoding arg3) { return default(String); } public String (ref SByte arg0, int arg1, int arg2) { return default(String); } public String (ref SByte arg0) { return default(String); } public String (ref char arg0, int arg1, int arg2) { return default(String); } public String (ref char arg0) { return default(String); } */ [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String TrimEnd(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String TrimStart(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Trim(params char[] trimChars) { Contract.Ensures(Contract.Result<String>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Substring(int startIndex, int length) { Contract.Requires(0 <= startIndex); Contract.Requires(0 <= length); Contract.Requires(startIndex <= this.Length ); Contract.Requires(startIndex <= this.Length - length); Contract.Ensures(Contract.Result<String>() != null); Contract.Ensures(Contract.Result<string>().Length == length); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String Substring(int startIndex) { Contract.Requires(0 <= startIndex); Contract.Requires(startIndex <= this.Length); Contract.Ensures(Contract.Result<string>().Length == this.Length - startIndex); Contract.Ensures(Contract.Result<String>() != null); return default(String); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String[] Split(char[] arg0, int arg1) { Contract.Ensures(Contract.Result<String[]>() != null); Contract.Ensures(Contract.Result<String[]>().Length >= 1); Contract.Ensures(Contract.Result<String[]>()[0].Length <= this.Length); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(String[]); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public String[] Split(char[] separator) { Contract.Ensures(Contract.Result<String[]>() != null); Contract.Ensures(Contract.Result<String[]>().Length >= 1); Contract.Ensures(Contract.Result<String[]>()[0].Length <= this.Length); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(String[]); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(char[] separator, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(string[] separator, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public string[] Split(char[] separator, int count, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #endif #if !SILVERLIGHT_4_0_WP [Pure] [Reads(ReadsAttribute.Reads.Owned)] #if !SILVERLIGHT public #else internal #endif string[] Split(string[] separator, int count, StringSplitOptions options) { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(0, Contract.Result<string[]>().Length, i => Contract.Result<string[]>()[i] != null)); return default(string[]); } #endif #if !SILVERLIGHT [Pure] [Reads(ReadsAttribute.Reads.Owned)] public char[] ToCharArray(int startIndex, int length) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= this.Length); Contract.Requires(startIndex + length <= this.Length); Contract.Requires(length >= 0); Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } #endif [Pure] [Reads(ReadsAttribute.Reads.Owned)] public char[] ToCharArray() { Contract.Ensures(Contract.Result<char[]>() != null); return default(char[]); } public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { Contract.Requires(destination != null); Contract.Requires(count >= 0); Contract.Requires(sourceIndex >= 0); Contract.Requires(count <= (this.Length - sourceIndex)); Contract.Requires(destinationIndex <= (destination.Length - count)); Contract.Requires(destinationIndex >= 0); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool operator !=(String a, String b) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool operator ==(String a, String b) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static bool Equals(String a, String b) { Contract.Ensures((object)a != (object)b || Contract.Result<bool>()); return default(bool); } [Pure] public virtual bool Equals(String arg0) { Contract.Ensures((object)this != (object)arg0 || Contract.Result<bool>()); return default(bool); } [Pure] public bool Equals(String value, StringComparison comparisonType) { return default(bool); } [Pure] public static bool Equals(String a, String b, StringComparison comparisonType) { return default(bool); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, String[] value, int startIndex, int count) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(startIndex + count <= value.Length); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, String[] value) { Contract.Requires(value != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } #if NETFRAMEWORK_4_0 || NETFRAMEWORK_4_5 [Pure] [Reads(ReadsAttribute.Reads.Nothing)] public static String Join(String separator, Object[] value) { Contract.Requires(value != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] public static string Join(string separator, IEnumerable<string> values) { Contract.Requires(values != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } [Pure] public static string Join<T>(string separator, IEnumerable<T> values) { Contract.Requires(values != null); Contract.Ensures(Contract.Result<string>() != null); return default(String); } #endif [Pure] public static bool IsNullOrEmpty(string str) { Contract.Ensures( Contract.Result<bool>() && (str == null || str.Length == 0) || !Contract.Result<bool>() && str != null && str.Length > 0); #if NETFRAMEWORK_4_5 || NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0 Contract.Ensures(!Contract.Result<bool>() || IsNullOrWhiteSpace(str)); #endif return default(bool); } #if NETFRAMEWORK_4_5 || NETFRAMEWORK_4_0 || SILVERLIGHT_4_0 || SILVERLIGHT_5_0 [Pure] public static bool IsNullOrWhiteSpace(string str) { Contract.Ensures(Contract.Result<bool>() && (str == null || str.Length == 0) || !Contract.Result<bool>() && str != null && str.Length > 0); return default(bool); } #endif } }
30.453364
463
0.641553
[ "MIT" ]
Patashu/CodeContracts
Microsoft.Research/Contracts/MsCorlib/System.String.cs
39,833
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Prototype.Gameplay.RoomFacility.Store { public class DialogueBubbleCanvas : MonoBehaviour { private Text _contentText; // Start is called before the first frame update void Awake() { _contentText = GetComponentInChildren<Text>(); } public void DisplayText(String content) { _contentText.text = content; gameObject.SetActive(true); } public void EndDisplay() { gameObject.SetActive(false); } } }
21.28125
58
0.609398
[ "MIT" ]
RaymondMOirae/PixelPrototypeSync
Assets/Script/Gameplay/RoomFacility/Store/DialogueBubbleCanvas.cs
681
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 ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SimpleSystemsManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for InventoryItemSchema Object /// </summary> public class InventoryItemSchemaUnmarshaller : IUnmarshaller<InventoryItemSchema, XmlUnmarshallerContext>, IUnmarshaller<InventoryItemSchema, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> InventoryItemSchema IUnmarshaller<InventoryItemSchema, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public InventoryItemSchema Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; InventoryItemSchema unmarshalledObject = new InventoryItemSchema(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Attributes", targetDepth)) { var unmarshaller = new ListUnmarshaller<InventoryItemAttribute, InventoryItemAttributeUnmarshaller>(InventoryItemAttributeUnmarshaller.Instance); unmarshalledObject.Attributes = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DisplayName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DisplayName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TypeName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.TypeName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Version", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Version = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static InventoryItemSchemaUnmarshaller _instance = new InventoryItemSchemaUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static InventoryItemSchemaUnmarshaller Instance { get { return _instance; } } } }
37.581818
170
0.627721
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/InventoryItemSchemaUnmarshaller.cs
4,134
C#
// (C) 2022 christian@schadetsch.com using System; using System.Windows.Forms; namespace Mtg { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
18.842105
65
0.597765
[ "MIT" ]
cschladetsch/MtG-Library
Program.cs
360
C#
public class BonusActionExecutor { BonusModelComponent component; public BonusActionExecutor(BonusModelComponent component) { this.component = component; } public void Execute(IChangeBonusAction modifier) { modifier.Execute(component); } }
24.083333
64
0.692042
[ "MIT" ]
kicholen/GamePrototype
Assets/EditorScript/View/Bonus/Executor/BonusActionExecutor.cs
291
C#
using System; using System.ComponentModel.DataAnnotations; using System.Net; using System.Net.Http; using System.Threading.Tasks; using DFC.Common.Standard.Logging; using DFC.Composite.Regions.Models; using DFC.Composite.Regions.Services; using DFC.Functions.DI.Standard.Attributes; using DFC.HTTP.Standard; using DFC.JSON.Standard; using DFC.Swagger.Standard.Annotations; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using static DFC.Composite.Regions.Models.Constants; namespace DFC.Composite.Regions.Functions { public static class DeleteRegionHttpTrigger { [FunctionName("Delete")] [ProducesResponseType((int)HttpStatusCode.OK)] [Response(HttpStatusCode = (int)HttpStatusCode.OK, Description = "Region found", ShowSchema = true)] [Response(HttpStatusCode = (int)HttpStatusCode.NoContent, Description = "Region does not exist", ShowSchema = false)] [Response(HttpStatusCode = (int)HttpStatusCode.BadRequest, Description = "Request was malformed", ShowSchema = false)] [Response(HttpStatusCode = (int)HttpStatusCode.UnprocessableEntity, Description = "Region validation error(s)", ShowSchema = false)] [Display(Name = "Delete", Description = "Ability to delete a new Region for a Path.")] public static async Task<HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "paths/{path}/regions/{pageRegion}")] HttpRequest req, ILogger log, string path, int pageRegion, [Inject] ILoggerHelper loggerHelper, [Inject] IHttpRequestHelper httpRequestHelper, [Inject] IHttpResponseMessageHelper httpResponseMessageHelper, [Inject] IJsonHelper jsonHelper, [Inject] IRegionService regionService ) { loggerHelper.LogMethodEnter(log); // validate the parameters are present var dssCorrelationId = httpRequestHelper.GetDssCorrelationId(req); if (string.IsNullOrEmpty(dssCorrelationId)) { log.LogInformation($"Unable to locate '{nameof(dssCorrelationId)}' in request header"); } if (!Guid.TryParse(dssCorrelationId, out var correlationGuid)) { log.LogInformation($"Unable to parse '{nameof(dssCorrelationId)}' to a Guid"); correlationGuid = Guid.NewGuid(); } if (string.IsNullOrEmpty(path)) { loggerHelper.LogInformationMessage(log, correlationGuid, $"Missing value in request for '{nameof(path)}'"); return httpResponseMessageHelper.BadRequest(); } if (pageRegion == 0 || !Enum.IsDefined(typeof(PageRegions), pageRegion)) { loggerHelper.LogInformationMessage(log, correlationGuid, $"Missing/invalid value in request for '{nameof(pageRegion)}'"); return httpResponseMessageHelper.BadRequest(); } PageRegions pageRegionValue = (PageRegions)pageRegion; loggerHelper.LogInformationMessage(log, correlationGuid, $"Attempting to get Region {pageRegionValue} for Path {path}"); var regionModel = await regionService.GetAsync(path, pageRegionValue); if (regionModel == null) { loggerHelper.LogInformationMessage(log, correlationGuid, $"Region does not exist for {pageRegionValue} for Path {path}"); return httpResponseMessageHelper.NoContent(); } loggerHelper.LogInformationMessage(log, correlationGuid, $"Attempting to delete Region {pageRegionValue} for Path {path}"); var result = await regionService.DeleteAsync(regionModel.DocumentId.Value); loggerHelper.LogMethodExit(log); return result ? httpResponseMessageHelper.Ok() : httpResponseMessageHelper.NoContent(); } } }
43.25
140
0.667389
[ "MIT" ]
SkillsFundingAgency/dfc-composite-regions
DFC.Composite.Regions/Functions/DeleteRegionHttpTrigger.cs
4,152
C#
// Copyright (c) 2016, David Aramant // Distributed under the 3-clause BSD license. For full terms see the file LICENSE. using System.Collections.Generic; using System.Linq; using Tiledriver.Core.LevelGeometry; namespace Tiledriver.Core.FormatModels.Common.BinaryMaps { public enum BinaryMapPlaneId { Geometry, Thing, Sector, } public sealed class BinaryMap { public string Name { get; } public Size Size { get; } private readonly ushort[][] _planes; public BinaryMap( string name, ushort width, ushort height, IEnumerable<ushort[]> planes) { Name = name; Size = new Size(width, height); _planes = planes.ToArray(); } public IEnumerable<ushort> GetRawPlaneData(BinaryMapPlaneId planeId) => _planes[(int)planeId]; public IEnumerable<OldMapSpot> GetAllSpots(BinaryMapPlaneId planeId) { var plane = _planes[(int)planeId]; for (int index = 0; index < plane.Length; index++) { var x = index % Size.Width; var y = index / Size.Height; yield return new OldMapSpot(plane[index], index, x, y); } } } }
26.22
102
0.57132
[ "BSD-3-Clause" ]
davidaramant/tiledriver
src/Tiledriver.Core/FormatModels/Common/BinaryMaps/BinaryMap.cs
1,313
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The synthesized type added to a compilation to hold captured variables for closures. /// </summary> internal sealed class SynthesizedClosureEnvironment : SynthesizedContainer, ISynthesizedMethodBodyImplementationSymbol { private readonly MethodSymbol _topLevelMethod; internal readonly SyntaxNode ScopeSyntaxOpt; internal readonly int ClosureOrdinal; /// <summary> /// The closest method/lambda that this frame is originally from. Null if nongeneric static closure. /// Useful because this frame's type parameters are constructed from this method and all methods containing this method. /// </summary> internal readonly MethodSymbol OriginalContainingMethodOpt; internal readonly FieldSymbol SingletonCache; internal readonly MethodSymbol StaticConstructor; private ArrayBuilder<Symbol> _membersBuilder = ArrayBuilder<Symbol>.GetInstance(); private ImmutableArray<Symbol> _members; public override TypeKind TypeKind { get; } internal override MethodSymbol Constructor { get; } internal SynthesizedClosureEnvironment( MethodSymbol topLevelMethod, MethodSymbol containingMethod, bool isStruct, SyntaxNode scopeSyntaxOpt, DebugId methodId, DebugId closureId) : base(MakeName(scopeSyntaxOpt, methodId, closureId), containingMethod) { TypeKind = isStruct ? TypeKind.Struct : TypeKind.Class; _topLevelMethod = topLevelMethod; OriginalContainingMethodOpt = containingMethod; Constructor = isStruct ? null : new SynthesizedClosureEnvironmentConstructor(this); this.ClosureOrdinal = closureId.Ordinal; // static lambdas technically have the class scope so the scope syntax is null if (scopeSyntaxOpt == null) { StaticConstructor = new SynthesizedStaticConstructor(this); var cacheVariableName = GeneratedNames.MakeCachedFrameInstanceFieldName(); SingletonCache = new SynthesizedLambdaCacheFieldSymbol(this, this, cacheVariableName, topLevelMethod, isReadOnly: true, isStatic: true); } AssertIsClosureScopeSyntax(scopeSyntaxOpt); this.ScopeSyntaxOpt = scopeSyntaxOpt; } internal void AddHoistedField(LambdaCapturedVariable captured) => _membersBuilder.Add(captured); private static string MakeName(SyntaxNode scopeSyntaxOpt, DebugId methodId, DebugId closureId) { if (scopeSyntaxOpt == null) { // Display class is shared among static non-generic lambdas across generations, method ordinal is -1 in that case. // A new display class of a static generic lambda is created for each method and each generation. return GeneratedNames.MakeStaticLambdaDisplayClassName(methodId.Ordinal, methodId.Generation); } Debug.Assert(methodId.Ordinal >= 0); return GeneratedNames.MakeLambdaDisplayClassName(methodId.Ordinal, methodId.Generation, closureId.Ordinal, closureId.Generation); } [Conditional("DEBUG")] private static void AssertIsClosureScopeSyntax(SyntaxNode syntaxOpt) { // See C# specification, chapter 3.7 Scopes. // static lambdas technically have the class scope so the scope syntax is null if (syntaxOpt == null) { return; } if (LambdaUtilities.IsClosureScope(syntaxOpt)) { return; } throw ExceptionUtilities.UnexpectedValue(syntaxOpt.Kind()); } public override ImmutableArray<Symbol> GetMembers() { if (_members.IsDefault) { var builder = _membersBuilder; if ((object)StaticConstructor != null) { builder.Add(StaticConstructor); builder.Add(SingletonCache); } builder.AddRange(base.GetMembers()); _members = builder.ToImmutableAndFree(); _membersBuilder = null; } return _members; } /// <summary> /// All fields should have already been added as synthesized members on the /// <see cref="CommonPEModuleBuilder" />, so we don't want to duplicate them here. /// </summary> internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => (object)SingletonCache != null ? SpecializedCollections.SingletonEnumerable(SingletonCache) : SpecializedCollections.EmptyEnumerable<FieldSymbol>(); // display classes for static lambdas do not have any data and can be serialized. public override bool IsSerializable => (object)SingletonCache != null; public override Symbol ContainingSymbol => _topLevelMethod.ContainingSymbol; // Closures in the same method share the same SynthesizedClosureEnvironment. We must // always return true because two closures in the same method might have different // AreLocalsZeroed flags. public sealed override bool AreLocalsZeroed => true; // The lambda method contains user code from the lambda bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true; IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method => _topLevelMethod; } }
43.744681
161
0.667315
[ "Apache-2.0" ]
GrahamTheCoder/roslyn
src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/SynthesizedClosureEnvironment.cs
6,170
C#
using System.Threading; using System.Threading.Tasks; using Accord.Domain; using Accord.Domain.Model; using Accord.Services.Moderation; using Accord.Services.Permissions; using MediatR; using Microsoft.EntityFrameworkCore; namespace Accord.Services.Raid; public sealed record RaidCalculationRequest(ulong DiscordGuildId, GuildUserDto User) : IRequest, IEnsureUserExistsRequest { public ulong DiscordUserId => User.Id; } public sealed record RaidAlertRequest(ulong DiscordGuildId, bool IsRaidDetected, bool IsInExistingRaidMode, bool IsAutoRaidModeEnabled) : IRequest; public class RaidCalculationHandler : AsyncRequestHandler<RaidCalculationRequest> { private readonly RaidCalculator _raidCalculator; private readonly IMediator _mediator; private readonly AccordContext _db; public RaidCalculationHandler(RaidCalculator raidCalculator, IMediator mediator, AccordContext db) { _raidCalculator = raidCalculator; _mediator = mediator; _db = db; } protected override async Task Handle(RaidCalculationRequest request, CancellationToken cancellationToken) { var bypassRaidCheck = await _mediator.Send(new UserIsExemptFromRaidRequest(request.User.Id), cancellationToken); if (bypassRaidCheck) { return; } var sequentialLimit = await _mediator.Send(new GetJoinLimitPerMinuteRequest(), cancellationToken); var accountCreationLimit = await _mediator.Send(new GetAccountCreationSimilarityLimitRequest(), cancellationToken); var raidResult = await _raidCalculator.CalculateIsRaid(new UserJoin(request.User.Id, request.User.DiscordAvatarUrl, request.User.JoinedDateTime.DateTime), sequentialLimit, accountCreationLimit); var isAutoRaidModeEnabled = await _mediator.Send(new GetIsAutoRaidModeEnabledRequest(), cancellationToken); var isInExistingRaidMode = await _mediator.Send(new GetIsInRaidModeRequest(), cancellationToken); if (raidResult.IsRaid != isInExistingRaidMode) { var runOption = await _db.RunOptions .SingleAsync(x => x.Type == RunOptionType.RaidModeEnabled, cancellationToken: cancellationToken); runOption.Value = raidResult.IsRaid.ToString(); await _db.SaveChangesAsync(cancellationToken); await _mediator.Send(new InvalidateGetIsInRaidModeRequest(), cancellationToken); } if (raidResult.IsRaid && !isInExistingRaidMode) { // If this is a raid and we haven't already detected a raid prior to this // request, send the alert await _mediator.Send(new RaidAlertRequest(request.DiscordGuildId, raidResult.IsRaid, isInExistingRaidMode, isAutoRaidModeEnabled), cancellationToken); } if (raidResult.IsRaid && isAutoRaidModeEnabled) { await _mediator.Send(new KickRequest(request.DiscordGuildId, new GuildUserDto(request.User.Id, request.User.Username, request.User.Discriminator, request.User.DiscordAvatarUrl, null, request.User.JoinedDateTime), $"Auto detection - {raidResult.Reason}"), cancellationToken); } } }
41.4375
202
0.708296
[ "MIT" ]
patrickklaeren/Accord
src/Accord.Services/Raid/RaidCalculation.cs
3,317
C#
// // Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace NLog.Targets.FileArchiveModes { /// <summary> /// Archives the log-files using a sequence style numbering. The most recent archive has the /// highest number. When the number of archive files exceed <see cref="P:MaxArchiveFiles"/> the obsolete /// archives are deleted. /// </summary> sealed class FileArchiveModeSequence : FileArchiveModeBase { private readonly string _archiveDateFormat; public FileArchiveModeSequence(string archiveDateFormat) { _archiveDateFormat = archiveDateFormat; } public override bool AttemptCleanupOnInitializeFile(string archiveFilePath, int maxArchiveFiles) { return false; // For historic reasons, then cleanup of sequence archives are not done on startup } protected override DateAndSequenceArchive GenerateArchiveFileInfo(FileInfo archiveFile, FileNameTemplate fileTemplate) { string baseName = Path.GetFileName(archiveFile.FullName) ?? ""; int trailerLength = fileTemplate.Template.Length - fileTemplate.EndAt; string number = baseName.Substring(fileTemplate.BeginAt, baseName.Length - trailerLength - fileTemplate.BeginAt); int num; try { num = Convert.ToInt32(number, CultureInfo.InvariantCulture); } catch (FormatException) { return null; } return new DateAndSequenceArchive(archiveFile.FullName, DateTime.MinValue, string.Empty, num); } public override DateAndSequenceArchive GenerateArchiveFileName(string archiveFilePath, DateTime archiveDate, List<DateAndSequenceArchive> existingArchiveFiles) { int nextSequenceNumber = 0; FileNameTemplate archiveFileNameTemplate = GenerateFileNameTemplate(archiveFilePath); foreach (var existingFile in existingArchiveFiles) nextSequenceNumber = Math.Max(nextSequenceNumber, existingFile.Sequence + 1); int minSequenceLength = archiveFileNameTemplate.EndAt - archiveFileNameTemplate.BeginAt - 2; string paddedSequence = nextSequenceNumber.ToString().PadLeft(minSequenceLength, '0'); string dirName = Path.GetDirectoryName(archiveFilePath); archiveFilePath = Path.Combine(dirName, archiveFileNameTemplate.ReplacePattern("*").Replace("*", paddedSequence)); archiveFilePath = Path.GetFullPath(archiveFilePath); // Rebuild to fix non-standard path-format return new DateAndSequenceArchive(archiveFilePath, archiveDate, _archiveDateFormat, nextSequenceNumber); } public override IEnumerable<DateAndSequenceArchive> CheckArchiveCleanup(string archiveFilePath, List<DateAndSequenceArchive> existingArchiveFiles, int maxArchiveFiles) { if (maxArchiveFiles <= 0 || existingArchiveFiles.Count == 0 || existingArchiveFiles.Count < maxArchiveFiles) yield break; int nextSequenceNumber = existingArchiveFiles[existingArchiveFiles.Count - 1].Sequence; int minNumberToKeep = nextSequenceNumber - maxArchiveFiles + 1; if (minNumberToKeep <= 0) yield break; foreach (var existingFile in existingArchiveFiles) if (existingFile.Sequence < minNumberToKeep) yield return existingFile; } } }
47.563636
175
0.706613
[ "BSD-3-Clause" ]
AchimStuy/NLog
src/NLog/Targets/FileArchiveModes/FileArchiveModeSequence.cs
5,232
C#
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (C) 2009-2013 Michael Möller <mmoeller@openhardwaremonitor.org> */ namespace OpenHardwareMonitor.GUI { partial class MainForm { /// <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(MainForm)); this.sensor = new Aga.Controls.Tree.TreeColumn(); this.value = new Aga.Controls.Tree.TreeColumn(); this.min = new Aga.Controls.Tree.TreeColumn(); this.max = new Aga.Controls.Tree.TreeColumn(); this.nodeImage = new Aga.Controls.Tree.NodeControls.NodeIcon(); this.nodeCheckBox = new Aga.Controls.Tree.NodeControls.NodeCheckBox(); this.nodeTextBoxText = new Aga.Controls.Tree.NodeControls.NodeTextBox(); this.nodeTextBoxValue = new Aga.Controls.Tree.NodeControls.NodeTextBox(); this.nodeTextBoxMin = new Aga.Controls.Tree.NodeControls.NodeTextBox(); this.nodeTextBoxMax = new Aga.Controls.Tree.NodeControls.NodeTextBox(); this.mainMenu = new System.Windows.Forms.MainMenu(this.components); this.fileMenuItem = new System.Windows.Forms.MenuItem(); this.saveReportMenuItem = new System.Windows.Forms.MenuItem(); this.sumbitReportMenuItem = new System.Windows.Forms.MenuItem(); this.MenuItem2 = new System.Windows.Forms.MenuItem(); this.resetMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem5 = new System.Windows.Forms.MenuItem(); this.mainboardMenuItem = new System.Windows.Forms.MenuItem(); this.cpuMenuItem = new System.Windows.Forms.MenuItem(); this.ramMenuItem = new System.Windows.Forms.MenuItem(); this.gpuMenuItem = new System.Windows.Forms.MenuItem(); this.fanControllerMenuItem = new System.Windows.Forms.MenuItem(); this.hddMenuItem = new System.Windows.Forms.MenuItem(); this.menuItem6 = new System.Windows.Forms.MenuItem(); this.exitMenuItem = new System.Windows.Forms.MenuItem(); this.viewMenuItem = new System.Windows.Forms.MenuItem(); this.resetMinMaxMenuItem = new System.Windows.Forms.MenuItem(); this.MenuItem3 = new System.Windows.Forms.MenuItem(); this.hiddenMenuItem = new System.Windows.Forms.MenuItem(); this.plotMenuItem = new System.Windows.Forms.MenuItem(); this.gadgetMenuItem = new System.Windows.Forms.MenuItem(); this.MenuItem1 = new System.Windows.Forms.MenuItem(); this.columnsMenuItem = new System.Windows.Forms.MenuItem(); this.valueMenuItem = new System.Windows.Forms.MenuItem(); this.minMenuItem = new System.Windows.Forms.MenuItem(); this.maxMenuItem = new System.Windows.Forms.MenuItem(); this.optionsMenuItem = new System.Windows.Forms.MenuItem(); this.startMinMenuItem = new System.Windows.Forms.MenuItem(); this.minTrayMenuItem = new System.Windows.Forms.MenuItem(); this.minCloseMenuItem = new System.Windows.Forms.MenuItem(); this.startupMenuItem = new System.Windows.Forms.MenuItem(); this.separatorMenuItem = new System.Windows.Forms.MenuItem(); this.temperatureUnitsMenuItem = new System.Windows.Forms.MenuItem(); this.celsiusMenuItem = new System.Windows.Forms.MenuItem(); this.fahrenheitMenuItem = new System.Windows.Forms.MenuItem(); this.plotLocationMenuItem = new System.Windows.Forms.MenuItem(); this.plotWindowMenuItem = new System.Windows.Forms.MenuItem(); this.plotBottomMenuItem = new System.Windows.Forms.MenuItem(); this.plotRightMenuItem = new System.Windows.Forms.MenuItem(); this.logSeparatorMenuItem = new System.Windows.Forms.MenuItem(); this.logSensorsMenuItem = new System.Windows.Forms.MenuItem(); this.loggingIntervalMenuItem = new System.Windows.Forms.MenuItem(); this.log1sMenuItem = new System.Windows.Forms.MenuItem(); this.log2sMenuItem = new System.Windows.Forms.MenuItem(); this.log5sMenuItem = new System.Windows.Forms.MenuItem(); this.log10sMenuItem = new System.Windows.Forms.MenuItem(); this.log30sMenuItem = new System.Windows.Forms.MenuItem(); this.log1minMenuItem = new System.Windows.Forms.MenuItem(); this.log2minMenuItem = new System.Windows.Forms.MenuItem(); this.log5minMenuItem = new System.Windows.Forms.MenuItem(); this.log10minMenuItem = new System.Windows.Forms.MenuItem(); this.log30minMenuItem = new System.Windows.Forms.MenuItem(); this.log1hMenuItem = new System.Windows.Forms.MenuItem(); this.log2hMenuItem = new System.Windows.Forms.MenuItem(); this.log6hMenuItem = new System.Windows.Forms.MenuItem(); this.webMenuItemSeparator = new System.Windows.Forms.MenuItem(); this.webMenuItem = new System.Windows.Forms.MenuItem(); this.runWebServerMenuItem = new System.Windows.Forms.MenuItem(); this.serverPortMenuItem = new System.Windows.Forms.MenuItem(); this.arduinoServerMenuItem = new System.Windows.Forms.MenuItem(); this.arduinoReportSensorsMenuItem = new System.Windows.Forms.MenuItem(); this.arduinoConfigurationMenuItem = new System.Windows.Forms.MenuItem(); this.helpMenuItem = new System.Windows.Forms.MenuItem(); this.aboutMenuItem = new System.Windows.Forms.MenuItem(); this.treeContextMenu = new System.Windows.Forms.ContextMenu(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.timer = new System.Windows.Forms.Timer(this.components); this.splitContainer = new OpenHardwareMonitor.GUI.SplitContainerAdv(); this.treeView = new Aga.Controls.Tree.TreeViewAdv(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).BeginInit(); this.splitContainer.Panel1.SuspendLayout(); this.splitContainer.SuspendLayout(); this.SuspendLayout(); // // sensor // this.sensor.Header = "Sensor"; this.sensor.SortOrder = System.Windows.Forms.SortOrder.None; this.sensor.TooltipText = null; // // value // this.value.Header = "Value"; this.value.SortOrder = System.Windows.Forms.SortOrder.None; this.value.TooltipText = null; // // min // this.min.Header = "Min"; this.min.SortOrder = System.Windows.Forms.SortOrder.None; this.min.TooltipText = null; // // max // this.max.Header = "Max"; this.max.SortOrder = System.Windows.Forms.SortOrder.None; this.max.TooltipText = null; // // nodeImage // this.nodeImage.DataPropertyName = "Image"; this.nodeImage.LeftMargin = 1; this.nodeImage.ParentColumn = this.sensor; this.nodeImage.ScaleMode = Aga.Controls.Tree.ImageScaleMode.Fit; // // nodeCheckBox // this.nodeCheckBox.DataPropertyName = "Plot"; this.nodeCheckBox.EditEnabled = true; this.nodeCheckBox.LeftMargin = 3; this.nodeCheckBox.ParentColumn = this.sensor; // // nodeTextBoxText // this.nodeTextBoxText.DataPropertyName = "Text"; this.nodeTextBoxText.EditEnabled = true; this.nodeTextBoxText.IncrementalSearchEnabled = true; this.nodeTextBoxText.LeftMargin = 3; this.nodeTextBoxText.ParentColumn = this.sensor; this.nodeTextBoxText.Trimming = System.Drawing.StringTrimming.EllipsisCharacter; this.nodeTextBoxText.UseCompatibleTextRendering = true; // // nodeTextBoxValue // this.nodeTextBoxValue.DataPropertyName = "Value"; this.nodeTextBoxValue.IncrementalSearchEnabled = true; this.nodeTextBoxValue.LeftMargin = 3; this.nodeTextBoxValue.ParentColumn = this.value; this.nodeTextBoxValue.Trimming = System.Drawing.StringTrimming.EllipsisCharacter; this.nodeTextBoxValue.UseCompatibleTextRendering = true; // // nodeTextBoxMin // this.nodeTextBoxMin.DataPropertyName = "Min"; this.nodeTextBoxMin.IncrementalSearchEnabled = true; this.nodeTextBoxMin.LeftMargin = 3; this.nodeTextBoxMin.ParentColumn = this.min; this.nodeTextBoxMin.Trimming = System.Drawing.StringTrimming.EllipsisCharacter; this.nodeTextBoxMin.UseCompatibleTextRendering = true; // // nodeTextBoxMax // this.nodeTextBoxMax.DataPropertyName = "Max"; this.nodeTextBoxMax.IncrementalSearchEnabled = true; this.nodeTextBoxMax.LeftMargin = 3; this.nodeTextBoxMax.ParentColumn = this.max; this.nodeTextBoxMax.Trimming = System.Drawing.StringTrimming.EllipsisCharacter; this.nodeTextBoxMax.UseCompatibleTextRendering = true; // // mainMenu // this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.fileMenuItem, this.viewMenuItem, this.optionsMenuItem, this.helpMenuItem}); // // fileMenuItem // this.fileMenuItem.Index = 0; this.fileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.saveReportMenuItem, this.sumbitReportMenuItem, this.MenuItem2, this.resetMenuItem, this.menuItem5, this.menuItem6, this.exitMenuItem}); this.fileMenuItem.Text = "File"; // // saveReportMenuItem // this.saveReportMenuItem.Index = 0; this.saveReportMenuItem.Text = "Save Report..."; this.saveReportMenuItem.Click += new System.EventHandler(this.saveReportMenuItem_Click); // // sumbitReportMenuItem // this.sumbitReportMenuItem.Index = 1; this.sumbitReportMenuItem.Text = "Submit Report..."; this.sumbitReportMenuItem.Click += new System.EventHandler(this.sumbitReportMenuItem_Click); // // MenuItem2 // this.MenuItem2.Index = 2; this.MenuItem2.Text = "-"; // // resetMenuItem // this.resetMenuItem.Index = 3; this.resetMenuItem.Text = "Reset"; this.resetMenuItem.Click += new System.EventHandler(this.resetClick); // // menuItem5 // this.menuItem5.Index = 4; this.menuItem5.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mainboardMenuItem, this.cpuMenuItem, this.ramMenuItem, this.gpuMenuItem, this.fanControllerMenuItem, this.hddMenuItem}); this.menuItem5.Text = "Hardware"; // // mainboardMenuItem // this.mainboardMenuItem.Index = 0; this.mainboardMenuItem.Text = "Mainboard"; // // cpuMenuItem // this.cpuMenuItem.Index = 1; this.cpuMenuItem.Text = "CPU"; // // ramMenuItem // this.ramMenuItem.Index = 2; this.ramMenuItem.Text = "RAM"; // // gpuMenuItem // this.gpuMenuItem.Index = 3; this.gpuMenuItem.Text = "GPU"; // // fanControllerMenuItem // this.fanControllerMenuItem.Index = 4; this.fanControllerMenuItem.Text = "Fan Controllers"; // // hddMenuItem // this.hddMenuItem.Index = 5; this.hddMenuItem.Text = "Hard Disk Drives"; // // menuItem6 // this.menuItem6.Index = 5; this.menuItem6.Text = "-"; // // exitMenuItem // this.exitMenuItem.Index = 6; this.exitMenuItem.Text = "Exit"; this.exitMenuItem.Click += new System.EventHandler(this.exitClick); // // viewMenuItem // this.viewMenuItem.Index = 1; this.viewMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.resetMinMaxMenuItem, this.MenuItem3, this.hiddenMenuItem, this.plotMenuItem, this.gadgetMenuItem, this.MenuItem1, this.columnsMenuItem}); this.viewMenuItem.Text = "View"; // // resetMinMaxMenuItem // this.resetMinMaxMenuItem.Index = 0; this.resetMinMaxMenuItem.Text = "Reset Min/Max"; this.resetMinMaxMenuItem.Click += new System.EventHandler(this.resetMinMaxMenuItem_Click); // // MenuItem3 // this.MenuItem3.Index = 1; this.MenuItem3.Text = "-"; // // hiddenMenuItem // this.hiddenMenuItem.Index = 2; this.hiddenMenuItem.Text = "Show Hidden Sensors"; // // plotMenuItem // this.plotMenuItem.Index = 3; this.plotMenuItem.Text = "Show Plot"; // // gadgetMenuItem // this.gadgetMenuItem.Index = 4; this.gadgetMenuItem.Text = "Show Gadget"; // // MenuItem1 // this.MenuItem1.Index = 5; this.MenuItem1.Text = "-"; // // columnsMenuItem // this.columnsMenuItem.Index = 6; this.columnsMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.valueMenuItem, this.minMenuItem, this.maxMenuItem}); this.columnsMenuItem.Text = "Columns"; // // valueMenuItem // this.valueMenuItem.Index = 0; this.valueMenuItem.Text = "Value"; // // minMenuItem // this.minMenuItem.Index = 1; this.minMenuItem.Text = "Min"; // // maxMenuItem // this.maxMenuItem.Index = 2; this.maxMenuItem.Text = "Max"; // // optionsMenuItem // this.optionsMenuItem.Index = 2; this.optionsMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.startMinMenuItem, this.minTrayMenuItem, this.minCloseMenuItem, this.startupMenuItem, this.separatorMenuItem, this.temperatureUnitsMenuItem, this.plotLocationMenuItem, this.logSeparatorMenuItem, this.logSensorsMenuItem, this.loggingIntervalMenuItem, this.webMenuItemSeparator, this.webMenuItem, this.arduinoServerMenuItem}); this.optionsMenuItem.Text = "Options"; // // startMinMenuItem // this.startMinMenuItem.Index = 0; this.startMinMenuItem.Text = "Start Minimized"; // // minTrayMenuItem // this.minTrayMenuItem.Index = 1; this.minTrayMenuItem.Text = "Minimize To Tray"; // // minCloseMenuItem // this.minCloseMenuItem.Index = 2; this.minCloseMenuItem.Text = "Minimize On Close"; // // startupMenuItem // this.startupMenuItem.Index = 3; this.startupMenuItem.Text = "Run On Windows Startup"; // // separatorMenuItem // this.separatorMenuItem.Index = 4; this.separatorMenuItem.Text = "-"; // // temperatureUnitsMenuItem // this.temperatureUnitsMenuItem.Index = 5; this.temperatureUnitsMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.celsiusMenuItem, this.fahrenheitMenuItem}); this.temperatureUnitsMenuItem.Text = "Temperature Unit"; // // celsiusMenuItem // this.celsiusMenuItem.Index = 0; this.celsiusMenuItem.RadioCheck = true; this.celsiusMenuItem.Text = "Celsius"; this.celsiusMenuItem.Click += new System.EventHandler(this.celsiusMenuItem_Click); // // fahrenheitMenuItem // this.fahrenheitMenuItem.Index = 1; this.fahrenheitMenuItem.RadioCheck = true; this.fahrenheitMenuItem.Text = "Fahrenheit"; this.fahrenheitMenuItem.Click += new System.EventHandler(this.fahrenheitMenuItem_Click); // // plotLocationMenuItem // this.plotLocationMenuItem.Index = 6; this.plotLocationMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.plotWindowMenuItem, this.plotBottomMenuItem, this.plotRightMenuItem}); this.plotLocationMenuItem.Text = "Plot Location"; // // plotWindowMenuItem // this.plotWindowMenuItem.Index = 0; this.plotWindowMenuItem.RadioCheck = true; this.plotWindowMenuItem.Text = "Window"; // // plotBottomMenuItem // this.plotBottomMenuItem.Index = 1; this.plotBottomMenuItem.RadioCheck = true; this.plotBottomMenuItem.Text = "Bottom"; // // plotRightMenuItem // this.plotRightMenuItem.Index = 2; this.plotRightMenuItem.RadioCheck = true; this.plotRightMenuItem.Text = "Right"; // // logSeparatorMenuItem // this.logSeparatorMenuItem.Index = 7; this.logSeparatorMenuItem.Text = "-"; // // logSensorsMenuItem // this.logSensorsMenuItem.Index = 8; this.logSensorsMenuItem.Text = "Log Sensors"; // // loggingIntervalMenuItem // this.loggingIntervalMenuItem.Index = 9; this.loggingIntervalMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.log1sMenuItem, this.log2sMenuItem, this.log5sMenuItem, this.log10sMenuItem, this.log30sMenuItem, this.log1minMenuItem, this.log2minMenuItem, this.log5minMenuItem, this.log10minMenuItem, this.log30minMenuItem, this.log1hMenuItem, this.log2hMenuItem, this.log6hMenuItem}); this.loggingIntervalMenuItem.Text = "Logging Interval"; // // log1sMenuItem // this.log1sMenuItem.Index = 0; this.log1sMenuItem.RadioCheck = true; this.log1sMenuItem.Text = "1s"; // // log2sMenuItem // this.log2sMenuItem.Index = 1; this.log2sMenuItem.RadioCheck = true; this.log2sMenuItem.Text = "2s"; // // log5sMenuItem // this.log5sMenuItem.Index = 2; this.log5sMenuItem.RadioCheck = true; this.log5sMenuItem.Text = "5s"; // // log10sMenuItem // this.log10sMenuItem.Index = 3; this.log10sMenuItem.RadioCheck = true; this.log10sMenuItem.Text = "10s"; // // log30sMenuItem // this.log30sMenuItem.Index = 4; this.log30sMenuItem.RadioCheck = true; this.log30sMenuItem.Text = "30s"; // // log1minMenuItem // this.log1minMenuItem.Index = 5; this.log1minMenuItem.RadioCheck = true; this.log1minMenuItem.Text = "1min"; // // log2minMenuItem // this.log2minMenuItem.Index = 6; this.log2minMenuItem.RadioCheck = true; this.log2minMenuItem.Text = "2min"; // // log5minMenuItem // this.log5minMenuItem.Index = 7; this.log5minMenuItem.RadioCheck = true; this.log5minMenuItem.Text = "5min"; // // log10minMenuItem // this.log10minMenuItem.Index = 8; this.log10minMenuItem.RadioCheck = true; this.log10minMenuItem.Text = "10min"; // // log30minMenuItem // this.log30minMenuItem.Index = 9; this.log30minMenuItem.RadioCheck = true; this.log30minMenuItem.Text = "30min"; // // log1hMenuItem // this.log1hMenuItem.Index = 10; this.log1hMenuItem.RadioCheck = true; this.log1hMenuItem.Text = "1h"; // // log2hMenuItem // this.log2hMenuItem.Index = 11; this.log2hMenuItem.RadioCheck = true; this.log2hMenuItem.Text = "2h"; // // log6hMenuItem // this.log6hMenuItem.Index = 12; this.log6hMenuItem.RadioCheck = true; this.log6hMenuItem.Text = "6h"; // // webMenuItemSeparator // this.webMenuItemSeparator.Index = 10; this.webMenuItemSeparator.Text = "-"; // // webMenuItem // this.webMenuItem.Index = 11; this.webMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.runWebServerMenuItem, this.serverPortMenuItem}); this.webMenuItem.Text = "Remote Web Server"; // // runWebServerMenuItem // this.runWebServerMenuItem.Index = 0; this.runWebServerMenuItem.Text = "Run"; // // serverPortMenuItem // this.serverPortMenuItem.Index = 1; this.serverPortMenuItem.Text = "Port"; this.serverPortMenuItem.Click += new System.EventHandler(this.serverPortMenuItem_Click); // // arduinoServerMenuItem // this.arduinoServerMenuItem.Index = 12; this.arduinoServerMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.arduinoReportSensorsMenuItem, this.arduinoConfigurationMenuItem}); this.arduinoServerMenuItem.Text = "Arduino Report"; // // arduinoReportSensorsMenuItem // this.arduinoReportSensorsMenuItem.Index = 0; this.arduinoReportSensorsMenuItem.Text = "Run"; // // arduinoConfigurationMenuItem // this.arduinoConfigurationMenuItem.Index = 1; this.arduinoConfigurationMenuItem.Text = "Configuration"; this.arduinoConfigurationMenuItem.Click += new System.EventHandler(this.arduinoConfigurationMenuItem_Click); // // helpMenuItem // this.helpMenuItem.Index = 3; this.helpMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.aboutMenuItem}); this.helpMenuItem.Text = "Help"; // // aboutMenuItem // this.aboutMenuItem.Index = 0; this.aboutMenuItem.Text = "About"; this.aboutMenuItem.Click += new System.EventHandler(this.aboutMenuItem_Click); // // saveFileDialog // this.saveFileDialog.DefaultExt = "txt"; this.saveFileDialog.FileName = "OpenHardwareMonitor.Report.txt"; this.saveFileDialog.Filter = "Text Documents|*.txt|All Files|*.*"; this.saveFileDialog.RestoreDirectory = true; this.saveFileDialog.Title = "Save Report As"; // // timer // this.timer.Interval = 1000; this.timer.Tick += new System.EventHandler(this.timer_Tick); // // splitContainer // this.splitContainer.Border3DStyle = System.Windows.Forms.Border3DStyle.Raised; this.splitContainer.Color = System.Drawing.SystemColors.Control; this.splitContainer.Cursor = System.Windows.Forms.Cursors.Default; this.splitContainer.Location = new System.Drawing.Point(16, 15); this.splitContainer.Margin = new System.Windows.Forms.Padding(4); this.splitContainer.Name = "splitContainer"; this.splitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer.Panel1 // this.splitContainer.Panel1.Controls.Add(this.treeView); // // splitContainer.Panel2 // this.splitContainer.Panel2.Cursor = System.Windows.Forms.Cursors.Default; this.splitContainer.Size = new System.Drawing.Size(515, 594); this.splitContainer.SplitterDistance = 435; this.splitContainer.SplitterWidth = 6; this.splitContainer.TabIndex = 3; // // treeView // this.treeView.BackColor = System.Drawing.SystemColors.Window; this.treeView.BorderStyle = System.Windows.Forms.BorderStyle.None; this.treeView.Columns.Add(this.sensor); this.treeView.Columns.Add(this.value); this.treeView.Columns.Add(this.min); this.treeView.Columns.Add(this.max); this.treeView.DefaultToolTipProvider = null; this.treeView.Dock = System.Windows.Forms.DockStyle.Fill; this.treeView.DragDropMarkColor = System.Drawing.Color.Black; this.treeView.FullRowSelect = true; this.treeView.GridLineStyle = Aga.Controls.Tree.GridLineStyle.Horizontal; this.treeView.LineColor = System.Drawing.SystemColors.ControlDark; this.treeView.Location = new System.Drawing.Point(0, 0); this.treeView.Margin = new System.Windows.Forms.Padding(4); this.treeView.Model = null; this.treeView.Name = "treeView"; this.treeView.NodeControls.Add(this.nodeImage); this.treeView.NodeControls.Add(this.nodeCheckBox); this.treeView.NodeControls.Add(this.nodeTextBoxText); this.treeView.NodeControls.Add(this.nodeTextBoxValue); this.treeView.NodeControls.Add(this.nodeTextBoxMin); this.treeView.NodeControls.Add(this.nodeTextBoxMax); this.treeView.SelectedNode = null; this.treeView.Size = new System.Drawing.Size(515, 435); this.treeView.TabIndex = 0; this.treeView.Text = "treeView"; this.treeView.UseColumns = true; this.treeView.NodeMouseDoubleClick += new System.EventHandler<Aga.Controls.Tree.TreeNodeAdvMouseEventArgs>(this.treeView_NodeMouseDoubleClick); this.treeView.Click += new System.EventHandler(this.treeView_Click); this.treeView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView_MouseDown); this.treeView.MouseMove += new System.Windows.Forms.MouseEventHandler(this.treeView_MouseMove); this.treeView.MouseUp += new System.Windows.Forms.MouseEventHandler(this.treeView_MouseUp); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(557, 682); this.Controls.Add(this.splitContainer); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(4); this.Menu = this.mainMenu; this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Open Hardware Monitor"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed); this.Load += new System.EventHandler(this.MainForm_Load); this.ResizeEnd += new System.EventHandler(this.MainForm_MoveOrResize); this.Move += new System.EventHandler(this.MainForm_MoveOrResize); this.splitContainer.Panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).EndInit(); this.splitContainer.ResumeLayout(false); this.ResumeLayout(false); } #endregion private Aga.Controls.Tree.TreeViewAdv treeView; private System.Windows.Forms.MainMenu mainMenu; private System.Windows.Forms.MenuItem fileMenuItem; private System.Windows.Forms.MenuItem exitMenuItem; private Aga.Controls.Tree.TreeColumn sensor; private Aga.Controls.Tree.TreeColumn value; private Aga.Controls.Tree.TreeColumn min; private Aga.Controls.Tree.TreeColumn max; private Aga.Controls.Tree.NodeControls.NodeIcon nodeImage; private Aga.Controls.Tree.NodeControls.NodeTextBox nodeTextBoxText; private Aga.Controls.Tree.NodeControls.NodeTextBox nodeTextBoxValue; private Aga.Controls.Tree.NodeControls.NodeTextBox nodeTextBoxMin; private Aga.Controls.Tree.NodeControls.NodeTextBox nodeTextBoxMax; private SplitContainerAdv splitContainer; private System.Windows.Forms.MenuItem viewMenuItem; private System.Windows.Forms.MenuItem plotMenuItem; private Aga.Controls.Tree.NodeControls.NodeCheckBox nodeCheckBox; private System.Windows.Forms.MenuItem helpMenuItem; private System.Windows.Forms.MenuItem aboutMenuItem; private System.Windows.Forms.MenuItem saveReportMenuItem; private System.Windows.Forms.MenuItem optionsMenuItem; private System.Windows.Forms.MenuItem hddMenuItem; private System.Windows.Forms.MenuItem minTrayMenuItem; private System.Windows.Forms.MenuItem separatorMenuItem; private System.Windows.Forms.ContextMenu treeContextMenu; private System.Windows.Forms.MenuItem startMinMenuItem; private System.Windows.Forms.MenuItem startupMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.Timer timer; private System.Windows.Forms.MenuItem hiddenMenuItem; private System.Windows.Forms.MenuItem MenuItem1; private System.Windows.Forms.MenuItem columnsMenuItem; private System.Windows.Forms.MenuItem valueMenuItem; private System.Windows.Forms.MenuItem minMenuItem; private System.Windows.Forms.MenuItem maxMenuItem; private System.Windows.Forms.MenuItem temperatureUnitsMenuItem; private System.Windows.Forms.MenuItem webMenuItemSeparator; private System.Windows.Forms.MenuItem celsiusMenuItem; private System.Windows.Forms.MenuItem fahrenheitMenuItem; private System.Windows.Forms.MenuItem sumbitReportMenuItem; private System.Windows.Forms.MenuItem MenuItem2; private System.Windows.Forms.MenuItem resetMinMaxMenuItem; private System.Windows.Forms.MenuItem MenuItem3; private System.Windows.Forms.MenuItem gadgetMenuItem; private System.Windows.Forms.MenuItem minCloseMenuItem; private System.Windows.Forms.MenuItem resetMenuItem; private System.Windows.Forms.MenuItem menuItem6; private System.Windows.Forms.MenuItem plotLocationMenuItem; private System.Windows.Forms.MenuItem plotWindowMenuItem; private System.Windows.Forms.MenuItem plotBottomMenuItem; private System.Windows.Forms.MenuItem plotRightMenuItem; private System.Windows.Forms.MenuItem webMenuItem; private System.Windows.Forms.MenuItem runWebServerMenuItem; private System.Windows.Forms.MenuItem serverPortMenuItem; private System.Windows.Forms.MenuItem menuItem5; private System.Windows.Forms.MenuItem mainboardMenuItem; private System.Windows.Forms.MenuItem cpuMenuItem; private System.Windows.Forms.MenuItem gpuMenuItem; private System.Windows.Forms.MenuItem fanControllerMenuItem; private System.Windows.Forms.MenuItem ramMenuItem; private System.Windows.Forms.MenuItem logSensorsMenuItem; private System.Windows.Forms.MenuItem logSeparatorMenuItem; private System.Windows.Forms.MenuItem loggingIntervalMenuItem; private System.Windows.Forms.MenuItem log1sMenuItem; private System.Windows.Forms.MenuItem log2sMenuItem; private System.Windows.Forms.MenuItem log5sMenuItem; private System.Windows.Forms.MenuItem log10sMenuItem; private System.Windows.Forms.MenuItem log30sMenuItem; private System.Windows.Forms.MenuItem log1minMenuItem; private System.Windows.Forms.MenuItem log2minMenuItem; private System.Windows.Forms.MenuItem log5minMenuItem; private System.Windows.Forms.MenuItem log10minMenuItem; private System.Windows.Forms.MenuItem log30minMenuItem; private System.Windows.Forms.MenuItem log1hMenuItem; private System.Windows.Forms.MenuItem log2hMenuItem; private System.Windows.Forms.MenuItem log6hMenuItem; private System.Windows.Forms.MenuItem arduinoServerMenuItem; private System.Windows.Forms.MenuItem arduinoReportSensorsMenuItem; private System.Windows.Forms.MenuItem arduinoConfigurationMenuItem; } }
45.855346
156
0.59199
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
pechurc/OpenHardwareMonitorArduino
GUI/MainForm.Designer.cs
36,458
C#
using SmartCardApi.Infrastructure; using SmartCardApi.Infrastructure.Interfaces; namespace SmartCardApi.ISO7816.ResponseAPDU { public interface IResponseApdu { IBinary Body(); IBinary Trailer(); } }
20.727273
45
0.723684
[ "MIT" ]
iQweex/MRTD.NET
SmartCardApi/ISO7816/ResponseAPDU/IReponseAPDU.cs
230
C#
using MailCheck.Common.Environment.Abstractions; namespace MailCheck.Dkim.Evaluator.Config { public interface IDkimEvaluatorConfig { string SnsTopicArn { get; } } public class DkimEvaluatorConfig : IDkimEvaluatorConfig { public DkimEvaluatorConfig(IEnvironmentVariables environmentVariables) { SnsTopicArn = environmentVariables.Get("SnsTopicArn"); } public string SnsTopicArn { get; } } }
24.684211
78
0.686567
[ "Apache-2.0" ]
ukncsc/MailCheck.Public.Dkim
src/MailCheck.Dkim.Evaluator/Config/DkimEvaluatorConfig.cs
471
C#
using System.Reflection; using System.Runtime.Serialization; using System.Linq; namespace KnimeNet.CommandLine.Types.Enums { /// <summary> /// Represents the type of the variable /// </summary> public enum VariableType { /// <summary> /// The variable is of type string. /// </summary> [EnumMember(Value = "String")] String, /// <summary> /// The variable is of type integer. /// </summary> [EnumMember(Value = "int")] Integer, /// <summary> /// The variable is of type double. /// </summary> [EnumMember(Value = "double")] Double } internal static class ParameterTypeExtensions { /// <summary> /// Gets the enum member value of <see cref="VariableType"/> /// </summary> /// <param name="type">The type.</param> /// <returns></returns> internal static string ToParameterTypeString(this VariableType type) { return type.GetType() .GetRuntimeField(type.ToString()) .GetCustomAttributes(typeof(EnumMemberAttribute), true) .Select(a => ((EnumMemberAttribute)a).Value).FirstOrDefault(); } } }
28.244444
78
0.554681
[ "MIT" ]
stevenengland/KnimeNet
KnimeNet/CommandLine/Types/Enums/VariableType.cs
1,273
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using StackExchange.Redis; namespace mvc104 { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder().UseUrls("http://*:8765") .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
22.357143
68
0.554313
[ "Apache-2.0" ]
FinchYang/ao
cars/encarmanagement/Program.cs
628
C#
using System.Collections.Concurrent; using Verse; namespace RimThreaded { public static class FullPool_Patch<T> where T : IFullPoolable, new() { private static readonly ConcurrentStack<T> FreeItems = new ConcurrentStack<T>(); public static T Get() { return !FreeItems.TryPop(out T freeItem) ? new T() : freeItem; } public static void Return(T item) { item.Reset(); FreeItems.Push(item); } } }
23.47619
88
0.598377
[ "MIT" ]
BlackJack1155/RimThreaded
Source/FullPool_Patch.cs
495
C#
namespace EtlLib.Logging { public class NullLoggerAdapter : ILoggingAdapter { public static NullLoggerAdapter Instance; static NullLoggerAdapter() { Instance = new NullLoggerAdapter(); } public ILogger CreateLogger(string name) { return NullLogger.Instance; } } public class NullLogger : ILogger { public static NullLogger Instance; static NullLogger() { Instance = new NullLogger(); } public void Trace(string s) { } public void Debug(string s) { } public void Info(string s) { } public void Warn(string s) { } public void Error(string s) { } } }
18.531915
53
0.476464
[ "MIT" ]
dabaus/EtlLib
src/EtlLib/Logging/NullLoggingAdapter.cs
873
C#
namespace Stumps.Rules { using System; using System.Collections.Generic; /// <summary> /// A class representing a Stump rule that evaluates the HTTP method of an HTTP request. /// </summary> public class HttpMethodRule : IStumpRule { private const string HttpMethodSetting = "httpmethod.value"; private string _textMatchValue; private TextMatch _textMatch; /// <summary> /// Initializes a new instance of the <see cref="HttpMethodRule"/> class. /// </summary> public HttpMethodRule() { } /// <summary> /// Initializes a new instance of the <see cref="HttpMethodRule"/> class. /// </summary> /// <param name="httpMethod">The HTTP method for the rule.</param> public HttpMethodRule(string httpMethod) { InitializeRule(httpMethod); } /// <summary> /// Gets the text match rule for the HTTP method. /// </summary> /// <value> /// The text match rule for the HTTP method. /// </value> public string HttpMethodTextMatch { get => _textMatchValue; } /// <summary> /// Gets a value indicating whether the rule is initialized. /// </summary> /// <value> /// <c>true</c> if the rule is initialized; otherwise, <c>false</c>. /// </value> public bool IsInitialized { get; private set; } /// <summary> /// Gets an enumerable list of <see cref="RuleSetting" /> objects used to represent the current instance. /// </summary> /// <returns> /// An enumerable list of <see cref="RuleSetting" /> objects used to represent the current instance. /// </returns> public IEnumerable<RuleSetting> GetRuleSettings() { var settings = new[] { new RuleSetting { Name = HttpMethodRule.HttpMethodSetting, Value = _textMatchValue } }; return settings; } /// <summary> /// Initializes a rule from an enumerable list of <see cref="RuleSetting" /> objects. /// </summary> /// <param name="settings">The enumerable list of <see cref="RuleSetting" /> objects.</param> public void InitializeFromSettings(IEnumerable<RuleSetting> settings) { settings = settings ?? throw new ArgumentNullException(nameof(settings)); if (this.IsInitialized) { throw new InvalidOperationException(BaseResources.BodyRuleAlreadyInitializedError); } var helper = new RuleSettingsHelper(settings); var httpMethod = helper.FindString(HttpMethodRule.HttpMethodSetting, string.Empty); InitializeRule(httpMethod); } /// <summary> /// Determines whether the specified request matches the rule. /// </summary> /// <param name="request">The <see cref="IStumpsHttpRequest" /> to evaluate.</param> /// <returns> /// <c>true</c> if the <paramref name="request" /> matches the rule, otherwise, <c>false</c>. /// </returns> public bool IsMatch(IStumpsHttpRequest request) { if (request == null) { return false; } var match = _textMatch.IsMatch(request.HttpMethod); return match; } /// <summary> /// Initializes the rule. /// </summary> /// <param name="httpMethod">The HTTP method for the rule.</param> public void InitializeRule(string httpMethod) { _textMatchValue = httpMethod ?? string.Empty; _textMatch = new TextMatch(_textMatchValue, true); this.IsInitialized = true; } } }
32.869919
117
0.540935
[ "Apache-2.0" ]
Pankaj-chhatani/stumps
src/main/dot-net/Stumps.Base/Rules/HttpMethodRule.cs
4,045
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Xunity.ScriptableVariables; namespace Xunity.Authorization { [Serializable] public class AuthorizedSources { [SerializeField] bool restrictAccess; [SerializeField] List<SerializableMonoscript> authorizedSources; public bool IsAuthorized(object source) { if (!restrictAccess) return true; if (source == null) return false; string sourceType = source.GetType().ToString(); return authorizedSources.Any(_ => _ == sourceType); } } }
24.444444
72
0.630303
[ "Unlicense" ]
ixi150/Xunity
Authorization/AuthorizedSources.cs
660
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.ISO8601; namespace ISO8601.Tests { [TestClass] public class OrdinalDateTimeDurationTests { [TestMethod] public void CanRoundTrip() { // Complete Assert.AreEqual("P1234111T121212", OrdinalDateTimeDuration.Parse("P1234111T121212").ToString(new ISO8601Options { UseComponentSeparators = false })); Assert.AreEqual("P1234-111T12:12:12", OrdinalDateTimeDuration.Parse("P1234-111T12:12:12").ToString()); // Reduced Assert.AreEqual("P1234111T1212", OrdinalDateTimeDuration.Parse("P1234111T1212").ToString(new ISO8601Options { UseComponentSeparators = false })); Assert.AreEqual("P1234-111T12:12", OrdinalDateTimeDuration.Parse("P1234-111T12:12").ToString()); Assert.AreEqual("P1234111T12", OrdinalDateTimeDuration.Parse("P1234111T12").ToString(new ISO8601Options { UseComponentSeparators = false })); // Fractional Assert.AreEqual("P1234111T121212,12", OrdinalDateTimeDuration.Parse("P1234111T121212,12").ToString(new ISO8601Options { UseComponentSeparators = false, FractionLength = 2 })); Assert.AreEqual("P1234-111T12:12:12.12", OrdinalDateTimeDuration.Parse("P1234-111T12:12:12.12").ToString(new ISO8601Options { FractionLength = 2, DecimalSeparator = '.' })); Assert.AreEqual("P1234111T1212,12", OrdinalDateTimeDuration.Parse("P1234111T1212,12").ToString(new ISO8601Options { UseComponentSeparators = false, FractionLength = 2 })); Assert.AreEqual("P1234-111T12:12.12", OrdinalDateTimeDuration.Parse("P1234-111T12:12.12").ToString(new ISO8601Options { FractionLength = 2, DecimalSeparator = '.' })); Assert.AreEqual("P1234111T12,12", OrdinalDateTimeDuration.Parse("P1234111T12,12").ToString(new ISO8601Options { UseComponentSeparators = false, FractionLength = 2 })); // Expanded Assert.AreEqual("P+1234111T121212", OrdinalDateTimeDuration.Parse("P+1234111T121212").ToString(new ISO8601Options { UseComponentSeparators = false, IsExpanded = true })); Assert.AreEqual("P+11234-111T12:12:12", OrdinalDateTimeDuration.Parse("P+11234-111T12:12:12", 5).ToString(new ISO8601Options { IsExpanded = true, YearLength = 5 })); Assert.AreEqual("P+1234111T1212", OrdinalDateTimeDuration.Parse("P+1234111T1212").ToString(new ISO8601Options { UseComponentSeparators = false, IsExpanded = true })); Assert.AreEqual("P+11234-111T12:12", OrdinalDateTimeDuration.Parse("P+11234-111T12:12", 5).ToString(new ISO8601Options { IsExpanded = true, YearLength = 5 })); Assert.AreEqual("P+1234111T12", OrdinalDateTimeDuration.Parse("P+1234111T12").ToString(new ISO8601Options { UseComponentSeparators = false, IsExpanded = true })); Assert.AreEqual("P-11234111T121212,12", OrdinalDateTimeDuration.Parse("P-11234111T121212,12", 5).ToString(new ISO8601Options { UseComponentSeparators = false, IsExpanded = true, YearLength = 5, FractionLength = 2 })); Assert.AreEqual("P-1234-111T12:12:12.12", OrdinalDateTimeDuration.Parse("P-1234-111T12:12:12.12").ToString(new ISO8601Options { IsExpanded = true, FractionLength = 2, DecimalSeparator = '.' })); Assert.AreEqual("P-11234111T1212,12", OrdinalDateTimeDuration.Parse("P-11234111T1212,12", 5).ToString(new ISO8601Options { UseComponentSeparators = false, IsExpanded = true, YearLength = 5, FractionLength = 2 })); Assert.AreEqual("P-1234-111T12:12.12", OrdinalDateTimeDuration.Parse("P-1234-111T12:12.12").ToString(new ISO8601Options { IsExpanded = true, FractionLength = 2, DecimalSeparator = '.' })); Assert.AreEqual("P-11234111T12,12", OrdinalDateTimeDuration.Parse("P-11234111T12,12", 5).ToString(new ISO8601Options { UseComponentSeparators = false, IsExpanded = true, YearLength = 5, FractionLength = 2 })); } } }
96.146341
229
0.717402
[ "MIT" ]
nharren/ISO-8601
src/ISO8601.Tests/OrdinalDateTimeDurationTests.cs
3,944
C#
using NWN.Core; namespace Anvil.API { public enum Ability { Strength = NWScript.ABILITY_STRENGTH, Dexterity = NWScript.ABILITY_DEXTERITY, Constitution = NWScript.ABILITY_CONSTITUTION, Intelligence = NWScript.ABILITY_INTELLIGENCE, Wisdom = NWScript.ABILITY_WISDOM, Charisma = NWScript.ABILITY_CHARISMA, } }
22.466667
49
0.747774
[ "MIT" ]
Aschent89/Anvil
NWN.Anvil/src/main/API/Constants/Ability.cs
337
C#
using CSVDataConverter.Infrastructure.Services; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace CSVDataConverter.UnitTests { public class Expando_CsvDataFormatConverter_ConvertToExpando { [Theory] [MemberData(nameof(Data))] public void GroupsHeadings(string input, int expected) { //Arrange var demoStringData = input; var dataFormatConverter = new Expando_CsvDataFormatConverter(); //Act var expandoDataObject = dataFormatConverter.ConvertToExpando(demoStringData); //Assert int count = ((IDictionary<string, object>)expandoDataObject.First()).Count; Assert.Equal(expected, count); } public static IEnumerable<object[]> Data = new List<object[]> { new object[] { "Name,Surname,Address_Line1,Address_Line2" + Environment.NewLine + "Dave,Jenkins,1 Hall Road,Bradford", 3 }, new object[] { "Name_FirstName,Name_Surname,Address_Line1,Address_Line2" + Environment.NewLine + "Dave,Jenkins,1 Hall Road,Bradford", 2 }, }; } }
34.147059
150
0.657192
[ "MIT" ]
samuelwine/CSVDataConverter
tests/CSVDataConverter.UnitTests/Expando_CsvDataFormatConverter_ConvertToExpando.cs
1,161
C#
/* Copyright 2010-present MongoDB Inc. * * 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 MongoDB.Bson; using MongoDB.Bson.Serialization; using Xunit; namespace MongoDB.Bson.Tests.IO { // these tests use the BsonDocument object model to create a BSON document in memory // and then serialize it back and forth between byte arrays to make sure nothing is lost in serialization/deserialization public class BsonRoundTripTests { [Fact] public void TestHelloWorld() { BsonDocument document = new BsonDocument { { "hello", "world" } }; byte[] bytes1 = document.ToBson(); byte[] bytes2 = BsonSerializer.Deserialize<BsonDocument>(bytes1).ToBson(); Assert.Equal(bytes1, bytes2); } [Fact] public void TestBsonIsAwesome() { BsonDocument document = new BsonDocument { { "BSON", new BsonArray { "awesome", 5.05, 1986} } }; byte[] bytes1 = document.ToBson(); byte[] bytes2 = BsonSerializer.Deserialize<BsonDocument>(bytes1).ToBson(); Assert.Equal(bytes1, bytes2); } [Fact] public void TestAllTypes() { BsonDocument document = new BsonDocument { { "double", 1.23 }, { "string", "rosebud" }, { "document", new BsonDocument { { "hello", "world" } } }, { "array", new BsonArray { 1, 2, 3 } }, { "binary", new byte[] { 1, 2, 3 } }, { "objectid", new ObjectId(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 }) }, { "boolean1", false }, { "boolean2", true } }; byte[] bytes1 = document.ToBson(); byte[] bytes2 = BsonSerializer.Deserialize<BsonDocument>(bytes1).ToBson(); Assert.Equal(bytes1, bytes2); } } }
35.014085
125
0.574014
[ "Apache-2.0" ]
591094733/mongo-csharp-driver
tests/MongoDB.Bson.Tests/IO/BsonRoundTripTests.cs
2,488
C#
#region Copyright // Copyright Hitachi Consulting // // 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 System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.File; using Microsoft.WindowsAzure.Storage.Queue; using Microsoft.WindowsAzure.Storage.RetryPolicies; using Microsoft.WindowsAzure.Storage.Table; namespace Xigadee { /// <summary> /// This connector uses the Azure Queue for event writing. /// </summary> public class AzureStorageConnectorQueue: AzureStorageConnectorBase<QueueRequestOptions, AzureStorageBinary> { /// <summary> /// This is the queue client. /// </summary> public CloudQueueClient Client { get; set; } /// <summary> /// This is the queue. /// </summary> public CloudQueue Queue { get; set; } /// <summary> /// This method writes to the incoming event to the underlying storage technology. /// </summary> /// <param name="e">The event.</param> /// <param name="id">The microservice metadata.</param> /// <returns> /// This is an async task. /// </returns> public override async Task Write(EventHolder e, MicroserviceId id) { var output = Serializer(e, id); //Encrypt the payload when required. if (EncryptionPolicy != AzureStorageEncryption.None && Encryptor != null) { //The checks for always encrypt are done externally. output.Blob = Encryptor(output.Blob); } // Create a message and add it to the queue. CloudQueueMessage message = new CloudQueueMessage(output.Blob); // Async enqueue the message await Queue.AddMessageAsync(message); } /// <summary> /// This method initializes the connector. /// </summary> public override void Initialize() { Client = StorageAccount.CreateCloudQueueClient(); if (RequestOptionsDefault != null) Client.DefaultRequestOptions = RequestOptionsDefault; if (ContainerId == null) ContainerId = AzureStorageHelper.GetEnum<DataCollectionSupport>(Support).StringValue; ContainerId = StorageServiceBase.ValidateAzureContainerName(ContainerId); Queue = Client.GetQueueReference(ContainerId); Queue.CreateIfNotExists(); } /// <summary> /// This method is used to check that the specific event should be written to the underlying storage. /// </summary> /// <param name="e">The event.</param> /// <returns> /// Returns true if the event should be written. /// </returns> public override bool ShouldWrite(EventHolder e) { return Options.IsSupported(AzureStorageBehaviour.Queue, e); } } }
36.45
111
0.642524
[ "Apache-2.0" ]
xigadee/Microservice
Src/Xigadee.Azure/DataCollection/Storage/Connector/Queue.cs
3,647
C#
using System; using System.Collections; namespace EulerSolver.Solvers { public class Solver7 : ISolver { public long FindSolution() { int numPrimes = 0; long counter = 2; long result = 0; while(numPrimes <= 10001) { if(this.isPrime(counter)) { numPrimes++; result = counter; } counter++; } return result; } public bool isPrime(long num) { bool result = true; for (long i = 2; i < num / 2; i++) { if (num % i == 0) { result = false; return result; } } return result; } string ISolver.Solve() { throw new NotImplementedException(); } } }
17.263158
48
0.372967
[ "MIT" ]
ilyanaDev/ProjectEuler
EulerSolver/Solvers/Solver7.cs
986
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("HFTrader")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("HFTrader")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("4738a549-cbad-4c0f-82a2-8666dddf8bf2")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.810811
59
0.717277
[ "MIT" ]
SebastianChu/InterPlatformTradingMaster
AutoTrader/Properties/AssemblyInfo.cs
1,306
C#
namespace Nezaboodka.Nevod.LanguageServer { public enum TextDocumentSyncKind { None, Full, Incremental } public class TextDocumentSyncOptions { public bool? OpenClose { get; set; } public TextDocumentSyncKind? Change { get; set; } public bool? WillSave { get; set; } public bool? WillSaveWaitUntil { get; set; } public bool? Save { get; set; } } public class DidOpenTextDocumentParams { public TextDocumentItem TextDocument { get; set; } public DidOpenTextDocumentParams(TextDocumentItem textDocument) => TextDocument = textDocument; } public class DidChangeTextDocumentParams { public VersionedTextDocumentIdentifier TextDocument { get; set; } public TextDocumentContentChangeEvent[] ContentChanges { get; set; } public DidChangeTextDocumentParams(VersionedTextDocumentIdentifier textDocument, TextDocumentContentChangeEvent[] contentChanges) { TextDocument = textDocument; ContentChanges = contentChanges; } } public class TextDocumentContentChangeEvent { public Range? Range { get; set; } public int? RangeLength { get; set; } public string Text { get; set; } public TextDocumentContentChangeEvent(string text) => Text = text; } public class DidCloseTextDocumentParams { public TextDocumentIdentifier TextDocument { get; set; } public DidCloseTextDocumentParams(TextDocumentIdentifier textDocument) => TextDocument = textDocument; } public class TextDocumentSyncClientCapabilities { public bool? DynamicRegistration { get; set; } public bool? WillSave { get; set; } public bool? WillSaveWaitUntil { get; set; } public bool? DidSave { get; set; } } }
30.177419
137
0.662213
[ "Apache-2.0" ]
nezaboodka/nevod-vscode
source/server/LanguageServer/Data/TextSynchronization.cs
1,871
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; namespace ecsfc { public class fphub : Hub { public void Hello() { Clients.All.hello(); } public void addGroup(string GroupID) { Groups.Add(Context.ConnectionId, GroupID); } } }
19.95
55
0.56391
[ "MIT" ]
Wunzack/tp01
fphub.cs
401
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("PHPFunctionsParser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Prout")] [assembly: AssemblyProduct("PHPFunctionsParser")] [assembly: AssemblyCopyright("Copyright © Prout 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("91a7055c-6489-42f9-ad77-77b4eb785021")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42
104
0.736808
[ "MIT" ]
Acidburn0zzz/flashdevelop
External/Tools/PHPFunctionsParser/PHPFunctionsParser/Properties/AssemblyInfo.cs
1,543
C#
using Nurse.Common.helper; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nurse.Common.CM { /// <summary> /// yyjk配置 /// </summary> public class YYJKConfig { /// <summary> /// 接口提供方 /// </summary> public static string YYJK_WebapiUrl { get { return ConfigureHelper.GetConfigureValue("YYJK_WebapiUrl", ""); } } /// <summary> /// 接口提供方 /// </summary> public static string YYJK_Provider { get { return ConfigureHelper.GetConfigureValue("YYJK_Provider", "捷通科技"); } } /// <summary> /// yyjk中配置的系统code /// </summary> public static string YYJK_SystemCode { get { return ConfigureHelper.GetConfigureValue("YYJK_SystemCode", ""); } } /// <summary> /// yyjk中配置的机器标识 /// </summary> public static string YYJK_MachineCode { get { return ConfigureHelper.GetConfigureValue("YYJK_MachineCode", ""); } } /// <summary> /// yyjk中配置的心跳监控项名称 ,默认为beat /// </summary> public static string YYJK_CollectItemKey { get { return ConfigureHelper.GetConfigureValue("YYJK_CollectItemKey", "beat"); } } /// <summary> /// yyjk中配置的主机IP /// </summary> public static string YYJK_HostIp { get { return ConfigureHelper.GetConfigureValue("YYJK_HostIp", ComputerInfo.GetIPAddress()); } } } }
31.622222
138
0.612087
[ "MIT" ]
aceunlonely/Nurse
Nurse.Common/CM/YYJKConfig.cs
1,527
C#
namespace UCS.Core.Web { using System; using System.Diagnostics; using System.Net; using System.Threading; using Newtonsoft.Json.Linq; internal class VersionChecker { public static string GetVersionString() { try { var Version = new WebClient().DownloadString(new Uri("https://clashoflights.xyz/UCS/version.json")); var obj = JObject.Parse(Version); return (string) obj["version"]; } catch (Exception) { return "Error"; } } public static string LatestBBVersion() { try { return (string)JObject.Parse(new WebClient().DownloadString("http://carreto.pt/tools/android-store-version/?package=com.supercell.boombeach"))["version"]; } catch (Exception) { return "Couldn't get last BB Version."; } } } }
27.486486
170
0.514258
[ "MIT" ]
antzsmt/Ultrapowa-Boom-Beach-Server
Ultrapowa Boom Beach Server/Core/Checker/VersionChecker.cs
1,017
C#
using UnityEngine; using System.Collections; using UnityEngine.Events; public class Pellet : Powerup { public void Awake() { action = delegate { // disable some components GetComponent<Collider>().enabled = false; GetComponent<Renderer>().enabled = false; ((Behaviour)gameObject.GetComponent("Halo")).enabled = false; // play sfx // picked-up animation? // add points GameManager gameManager = GameManager.Instance; gameManager.robertData.score += Score.Pellet; ++gameManager.levelData.pelletsEaten; GameObject.FindGameObjectWithTag("Pacman").GetComponent<RobertSounds>().pelletEaten(); }; } }
26
89
0.680473
[ "MIT" ]
team01010101/QuestForTheCure
Assets/Scripts/Powerups/Pellet.cs
678
C#
namespace _01.Students_Results___Lab { using System; public class StudentsResults { public static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); Console.WriteLine(string.Format("{0, -10}|{1,7}|{2,7}|{3,7}|{4,7}|", "Name", "CAdv", "COOP", "AdvOOP", "Average")); for (int i = 0; i < n; i++) { var input = Console.ReadLine() .Split(new[] { ' ', '-', ',' }, StringSplitOptions.RemoveEmptyEntries); var name = input[0]; var grade1 = double.Parse(input[1]); var grade2 = double.Parse(input[2]); var grade3 = double.Parse(input[3]); var gradeAvr = (grade1 + grade2 + grade3) / 3; Console.WriteLine("{0, -10}|{1,7:f2}|{2,7:f2}|{3,7:f2}|{4,7:f4}|", name, grade1, grade2, grade3, gradeAvr); } } } }
33.758621
104
0.465781
[ "MIT" ]
alexandrateneva/CSharp-Fundamentals-SoftUni
CSharp Advanced/Manual String Processing/01. Students Results - Lab/StudentsResults.cs
981
C#
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { public enum EAttenuationShape:byte { Sphere=0, Capsule=1, Box=2, Cone=3, EAttenuationShape_MAX=4, } }
13.882353
38
0.745763
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile/EAttenuationShape.cs
236
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoLibrary { public class ListWithExtras<TItem>: List<TItem> { private readonly IGenericMethods genericMethods; public ListWithExtras(IGenericMethods genericMethods) { this.genericMethods = genericMethods; } public TItem GetRandom() { return genericMethods.GetRandom(this); } // Generic method with two type arguments public TOutput GetRandomAs<TOutput>() where TOutput : class { return genericMethods.GetRandomAs<TItem, TOutput>(this); } // Useful to test a method having 'Of' inside it's name public List<TOutput> ProjectAllItemsOfList<TOutput>(Func<TItem, TOutput> projection) where TOutput : class { return genericMethods.ProjectAllItemsOfList(this, projection); } } }
26.578947
92
0.636634
[ "MIT" ]
molinch/kickmstest
Demo/DemoLibrary/ListWithExtras.cs
1,012
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Deployment.Internal.InternalActivationContextHelper.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Deployment.Internal { static public partial class InternalActivationContextHelper { #region Methods and constructors public static Object GetActivationContextData(ActivationContext appInfo) { Contract.Requires(appInfo != null); return default(Object); } public static Object GetApplicationComponentManifest(ActivationContext appInfo) { Contract.Requires(appInfo != null); return default(Object); } public static byte[] GetApplicationManifestBytes(ActivationContext appInfo) { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } public static Object GetDeploymentComponentManifest(ActivationContext appInfo) { Contract.Requires(appInfo != null); return default(Object); } public static byte[] GetDeploymentManifestBytes(ActivationContext appInfo) { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } public static bool IsFirstRun(ActivationContext appInfo) { Contract.Requires(appInfo != null); return default(bool); } public static void PrepareForExecution(ActivationContext appInfo) { Contract.Requires(appInfo != null); } #endregion } }
35.537634
463
0.74584
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/MsCorlib/Sources/System.Deployment.Internal.InternalActivationContextHelper.cs
3,305
C#
namespace TrafficManager.State { using TrafficManager.UI.Helpers; using TrafficManager.UI; public static class PoliciesTab { internal static void MakeSettings_VehicleRestrictions(ExtUITabstrip tabStrip) { UIHelper tab = tabStrip.AddTabPage(Translation.Options.Get("Tab:Policies & Restrictions")); PoliciesTab_AtJunctionsGroup.AddUI(tab); PoliciesTab_OnRoadsGroup.AddUI(tab); PoliciesTab_OnHighwaysGroup.AddUI(tab); PoliciesTab_InEmergenciesGroup.AddUI(tab); PoliciesTab_PriorityRoadsGroup.AddUI(tab); PoliciesTab_RoundaboutsGroup.AddUI(tab); } } }
26.92
103
0.68945
[ "MIT" ]
Elesbaan70/TMPE
TLM/TLM/State/OptionsTabs/PoliciesTab.cs
673
C#
using Microsoft.Extensions.Logging; using System; namespace Wirehome.Core.Diagnostics.Log { public class LogServiceLogger : ILogger { readonly LogService _logService; readonly string _categoryName; public LogServiceLogger(LogService logService, string categoryName) { _logService = logService ?? throw new ArgumentNullException(nameof(logService)); _categoryName = categoryName; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (!IsEnabled(logLevel)) { return; } _logService.Publish(DateTime.UtcNow, logLevel, _categoryName, formatter(state, exception), exception); } public bool IsEnabled(LogLevel logLevel) { return logLevel >= LogLevel.Information; } public IDisposable BeginScope<TState>(TState state) { return null; } } }
28.170732
145
0.624242
[ "Apache-2.0" ]
Analysers/Wirehome.Core
Wirehome.Core/Diagnostics/Log/LogServiceLogger.cs
1,157
C#
/* * Copyright(c) 2016 - 2018 Puma Security, LLC (https://www.pumascan.com) * * Project Leader: Eric Johnson (eric.johnson@pumascan.com) * Lead Developer: Eric Mead (eric.mead@pumascan.com) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Puma.Security.Rules.Common; namespace Puma.Security.Rules.Analyzer.Validation.Path.Core { internal interface IMvcFileResultExpressionAnalyzer { bool IsVulnerable(SemanticModel model, ObjectCreationExpressionSyntax syntax, DiagnosticId ruleId); SyntaxNode Source { get; set; } } }
31.92
107
0.734336
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
denmilu/puma-scan_code-realtime-scan
Rules/Analyzer/Validation/Path/Core/IMvcFileResultExpressionAnalyzer.cs
798
C#
using System; using System.Windows; using System.Windows.Data; using System.Globalization; namespace Rhit.Applications.ViewModel.Converters { public class BoolToVisibilityConverter : IValueConverter { public BoolToVisibilityConverter() { TrueValue = Visibility.Visible; FalseValue = Visibility.Collapsed; } public Visibility TrueValue { get; set; } public Visibility FalseValue { get; set; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool val = System.Convert.ToBoolean(value); return val ? TrueValue : FalseValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return TrueValue.Equals(value) ? true : false; } } }
34.24
105
0.670561
[ "Apache-2.0" ]
mboutell/Mobile
wp7/Rhit Mobile App/Rhit.Applications.Mobile.ViewModel.WP7/Converters/BoolToVisibilityConverter.cs
858
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码已从模板生成。 // // 手动更改此文件可能导致应用程序出现意外的行为。 // 如果重新生成代码,将覆盖对此文件的手动更改。 // </auto-generated> //------------------------------------------------------------------------------ namespace iVlog.Models { using System; using System.Collections.Generic; public partial class FAVORITE { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public FAVORITE() { this.HAS_VIDEO = new HashSet<HAS_VIDEO>(); } public string FAVORITE_ID { get; set; } public string FAVORITE_NAME { get; set; } public Nullable<byte> VIDEO_NUM { get; set; } public virtual HAS_FAVORITES HAS_FAVORITES { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<HAS_VIDEO> HAS_VIDEO { get; set; } } }
33.46875
128
0.560224
[ "MIT" ]
Easonrust/iVlog
program/iVlog/Models/FAVORITE.cs
1,181
C#
using UnityEngine; namespace TSW { namespace Camera { public class FollowTop : MonoBehaviour { public Transform _target; public float _height; // Update is called once per frame private void Update() { if (_target) { Vector3 pos = _target.position; pos.y += _height; transform.position = pos; transform.rotation = _target.rotation; transform.Rotate(90, 0, 0); } } } } }
16.148148
43
0.630734
[ "MIT" ]
vthem/PolyRace
Assets/Scripts/TSW.GameLib/Camera/FollowTop.cs
436
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #if !NO_PERF using System.Collections.Generic; using System.Reactive.Disposables; #if !NO_TPL using System.Threading; using System.Threading.Tasks; #endif namespace System.Reactive.Linq.ObservableImpl { class SelectMany<TSource, TCollection, TResult> : Producer<TResult> { private readonly IObservable<TSource> _source; private readonly Func<TSource, IObservable<TCollection>> _collectionSelector; private readonly Func<TSource, int, IObservable<TCollection>> _collectionSelectorI; private readonly Func<TSource, IEnumerable<TCollection>> _collectionSelectorE; private readonly Func<TSource, int, IEnumerable<TCollection>> _collectionSelectorEI; private readonly Func<TSource, TCollection, TResult> _resultSelector; private readonly Func<TSource, int, TCollection, int, TResult> _resultSelectorI; public SelectMany(IObservable<TSource> source, Func<TSource, IObservable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { _source = source; _collectionSelector = collectionSelector; _resultSelector = resultSelector; } public SelectMany(IObservable<TSource> source, Func<TSource, int, IObservable<TCollection>> collectionSelector, Func<TSource, int, TCollection, int, TResult> resultSelector) { _source = source; _collectionSelectorI = collectionSelector; _resultSelectorI = resultSelector; } public SelectMany(IObservable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { _source = source; _collectionSelectorE = collectionSelector; _resultSelector = resultSelector; } public SelectMany(IObservable<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, int, TCollection, int, TResult> resultSelector) { _source = source; _collectionSelectorEI = collectionSelector; _resultSelectorI = resultSelector; } #if !NO_TPL private readonly Func<TSource, CancellationToken, Task<TCollection>> _collectionSelectorT; private readonly Func<TSource, int, CancellationToken, Task<TCollection>> _collectionSelectorTI; private readonly Func<TSource, int, TCollection, TResult> _resultSelectorTI; public SelectMany(IObservable<TSource> source, Func<TSource, CancellationToken, Task<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { _source = source; _collectionSelectorT = collectionSelector; _resultSelector = resultSelector; } public SelectMany(IObservable<TSource> source, Func<TSource, int, CancellationToken, Task<TCollection>> collectionSelector, Func<TSource, int, TCollection, TResult> resultSelector) { _source = source; _collectionSelectorTI = collectionSelector; _resultSelectorTI = resultSelector; } #endif protected override IDisposable Run(IObserver<TResult> observer, IDisposable cancel, Action<IDisposable> setSink) { if (_collectionSelector != null) { var sink = new _(this, observer, cancel); setSink(sink); return sink.Run(); } else if (_collectionSelectorI != null) { var sink = new IndexSelectorImpl(this, observer, cancel); setSink(sink); return sink.Run(); } #if !NO_TPL else if (_collectionSelectorT != null) { var sink = new SelectManyImpl(this, observer, cancel); setSink(sink); return sink.Run(); } else if (_collectionSelectorTI != null) { var sink = new Sigma(this, observer, cancel); setSink(sink); return sink.Run(); } #endif else if (_collectionSelectorE != null) { var sink = new NoSelectorImpl(this, observer, cancel); setSink(sink); return _source.SubscribeSafe(sink); } else { var sink = new Omega(this, observer, cancel); setSink(sink); return _source.SubscribeSafe(sink); } } class _ : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TCollection, TResult> _parent; public _(SelectMany<TSource, TCollection, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private bool _isStopped; private CompositeDisposable _group; private SingleAssignmentDisposable _sourceSubscription; public IDisposable Run() { _gate = new object(); _isStopped = false; _group = new CompositeDisposable(); _sourceSubscription = new SingleAssignmentDisposable(); _group.Add(_sourceSubscription); _sourceSubscription.Disposable = _parent._source.SubscribeSafe(this); return _group; } public void OnNext(TSource value) { var collection = default(IObservable<TCollection>); try { collection = _parent._collectionSelector(value); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } var innerSubscription = new SingleAssignmentDisposable(); _group.Add(innerSubscription); innerSubscription.Disposable = collection.SubscribeSafe(new Iter(this, value, innerSubscription)); } public void OnError(Exception error) { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } public void OnCompleted() { _isStopped = true; if (_group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } else { _sourceSubscription.Dispose(); } } class Iter : IObserver<TCollection> { private readonly _ _parent; private readonly TSource _value; private readonly IDisposable _self; public Iter(_ parent, TSource value, IDisposable self) { _parent = parent; _value = value; _self = self; } public void OnNext(TCollection value) { var res = default(TResult); try { res = _parent._parent._resultSelector(_value, value); } catch (Exception ex) { lock (_parent._gate) { _parent._observer.OnError(ex); _parent.Dispose(); } return; } lock (_parent._gate) _parent._observer.OnNext(res); } public void OnError(Exception error) { lock (_parent._gate) { _parent._observer.OnError(error); _parent.Dispose(); } } public void OnCompleted() { _parent._group.Remove(_self); if (_parent._isStopped && _parent._group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_parent._gate) { _parent._observer.OnCompleted(); _parent.Dispose(); } } } } } class IndexSelectorImpl : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TCollection, TResult> _parent; public IndexSelectorImpl(SelectMany<TSource, TCollection, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private bool _isStopped; private CompositeDisposable _group; private SingleAssignmentDisposable _sourceSubscription; private int _index; public IDisposable Run() { _gate = new object(); _isStopped = false; _group = new CompositeDisposable(); _sourceSubscription = new SingleAssignmentDisposable(); _group.Add(_sourceSubscription); _sourceSubscription.Disposable = _parent._source.SubscribeSafe(this); return _group; } public void OnNext(TSource value) { var index = checked(_index++); var collection = default(IObservable<TCollection>); try { collection = _parent._collectionSelectorI(value, index); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } var innerSubscription = new SingleAssignmentDisposable(); _group.Add(innerSubscription); innerSubscription.Disposable = collection.SubscribeSafe(new Iter(this, value, index, innerSubscription)); } public void OnError(Exception error) { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } public void OnCompleted() { _isStopped = true; if (_group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } else { _sourceSubscription.Dispose(); } } class Iter : IObserver<TCollection> { private readonly IndexSelectorImpl _parent; private readonly TSource _value; private readonly int _valueIndex; private readonly IDisposable _self; public Iter(IndexSelectorImpl parent, TSource value, int index, IDisposable self) { _parent = parent; _value = value; _valueIndex = index; _self = self; } private int _index; public void OnNext(TCollection value) { var res = default(TResult); try { res = _parent._parent._resultSelectorI(_value, _valueIndex, value, checked(_index++)); } catch (Exception ex) { lock (_parent._gate) { _parent._observer.OnError(ex); _parent.Dispose(); } return; } lock (_parent._gate) _parent._observer.OnNext(res); } public void OnError(Exception error) { lock (_parent._gate) { _parent._observer.OnError(error); _parent.Dispose(); } } public void OnCompleted() { _parent._group.Remove(_self); if (_parent._isStopped && _parent._group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_parent._gate) { _parent._observer.OnCompleted(); _parent.Dispose(); } } } } } class NoSelectorImpl : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TCollection, TResult> _parent; public NoSelectorImpl(SelectMany<TSource, TCollection, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } public void OnNext(TSource value) { var xs = default(IEnumerable<TCollection>); try { xs = _parent._collectionSelectorE(value); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } var e = default(IEnumerator<TCollection>); try { e = xs.GetEnumerator(); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } try { var hasNext = true; while (hasNext) { hasNext = false; var current = default(TResult); try { hasNext = e.MoveNext(); if (hasNext) current = _parent._resultSelector(value, e.Current); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } if (hasNext) base._observer.OnNext(current); } } finally { if (e != null) e.Dispose(); } } public void OnError(Exception error) { base._observer.OnError(error); base.Dispose(); } public void OnCompleted() { base._observer.OnCompleted(); base.Dispose(); } } class Omega : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TCollection, TResult> _parent; public Omega(SelectMany<TSource, TCollection, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private int _index; public void OnNext(TSource value) { var index = checked(_index++); var xs = default(IEnumerable<TCollection>); try { xs = _parent._collectionSelectorEI(value, index); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } var e = default(IEnumerator<TCollection>); try { e = xs.GetEnumerator(); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } try { var eIndex = 0; var hasNext = true; while (hasNext) { hasNext = false; var current = default(TResult); try { hasNext = e.MoveNext(); if (hasNext) current = _parent._resultSelectorI(value, index, e.Current, checked(eIndex++)); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } if (hasNext) base._observer.OnNext(current); } } finally { if (e != null) e.Dispose(); } } public void OnError(Exception error) { base._observer.OnError(error); base.Dispose(); } public void OnCompleted() { base._observer.OnCompleted(); base.Dispose(); } } #if !NO_TPL #pragma warning disable 0420 class SelectManyImpl : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TCollection, TResult> _parent; public SelectManyImpl(SelectMany<TSource, TCollection, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private CancellationDisposable _cancel; private volatile int _count; public IDisposable Run() { _gate = new object(); _cancel = new CancellationDisposable(); _count = 1; return new CompositeDisposable(_parent._source.SubscribeSafe(this), _cancel); } public void OnNext(TSource value) { var task = default(Task<TCollection>); try { Interlocked.Increment(ref _count); task = _parent._collectionSelectorT(value, _cancel.Token); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } if (task.IsCompleted) { OnCompletedTask(value, task); } else { AttachContinuation(value, task); } } private void AttachContinuation(TSource value, Task<TCollection> task) { // // Separate method to avoid closure in synchronous completion case. // task.ContinueWith(t => OnCompletedTask(value, t)); } private void OnCompletedTask(TSource value, Task<TCollection> task) { switch (task.Status) { case TaskStatus.RanToCompletion: { var res = default(TResult); try { res = _parent._resultSelector(value, task.Result); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } lock (_gate) base._observer.OnNext(res); OnCompleted(); } break; case TaskStatus.Faulted: { lock (_gate) { base._observer.OnError(task.Exception.InnerException); base.Dispose(); } } break; case TaskStatus.Canceled: { if (!_cancel.IsDisposed) { lock (_gate) { base._observer.OnError(new TaskCanceledException(task)); base.Dispose(); } } } break; } } public void OnError(Exception error) { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } public void OnCompleted() { if (Interlocked.Decrement(ref _count) == 0) { lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } } } class Sigma : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TCollection, TResult> _parent; public Sigma(SelectMany<TSource, TCollection, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private CancellationDisposable _cancel; private volatile int _count; private int _index; public IDisposable Run() { _gate = new object(); _cancel = new CancellationDisposable(); _count = 1; return new CompositeDisposable(_parent._source.SubscribeSafe(this), _cancel); } public void OnNext(TSource value) { var index = checked(_index++); var task = default(Task<TCollection>); try { Interlocked.Increment(ref _count); task = _parent._collectionSelectorTI(value, index, _cancel.Token); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } if (task.IsCompleted) { OnCompletedTask(value, index, task); } else { AttachContinuation(value, index, task); } } private void AttachContinuation(TSource value, int index, Task<TCollection> task) { // // Separate method to avoid closure in synchronous completion case. // task.ContinueWith(t => OnCompletedTask(value, index, t)); } private void OnCompletedTask(TSource value, int index, Task<TCollection> task) { switch (task.Status) { case TaskStatus.RanToCompletion: { var res = default(TResult); try { res = _parent._resultSelectorTI(value, index, task.Result); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } lock (_gate) base._observer.OnNext(res); OnCompleted(); } break; case TaskStatus.Faulted: { lock (_gate) { base._observer.OnError(task.Exception.InnerException); base.Dispose(); } } break; case TaskStatus.Canceled: { if (!_cancel.IsDisposed) { lock (_gate) { base._observer.OnError(new TaskCanceledException(task)); base.Dispose(); } } } break; } } public void OnError(Exception error) { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } public void OnCompleted() { if (Interlocked.Decrement(ref _count) == 0) { lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } } } #pragma warning restore 0420 #endif } class SelectMany<TSource, TResult> : Producer<TResult> { private readonly IObservable<TSource> _source; private readonly Func<TSource, IObservable<TResult>> _selector; private readonly Func<TSource, int, IObservable<TResult>> _selectorI; private readonly Func<Exception, IObservable<TResult>> _selectorOnError; private readonly Func<IObservable<TResult>> _selectorOnCompleted; private readonly Func<TSource, IEnumerable<TResult>> _selectorE; private readonly Func<TSource, int, IEnumerable<TResult>> _selectorEI; public SelectMany(IObservable<TSource> source, Func<TSource, IObservable<TResult>> selector) { _source = source; _selector = selector; } public SelectMany(IObservable<TSource> source, Func<TSource, int, IObservable<TResult>> selector) { _source = source; _selectorI = selector; } public SelectMany(IObservable<TSource> source, Func<TSource, IObservable<TResult>> selector, Func<Exception, IObservable<TResult>> selectorOnError, Func<IObservable<TResult>> selectorOnCompleted) { _source = source; _selector = selector; _selectorOnError = selectorOnError; _selectorOnCompleted = selectorOnCompleted; } public SelectMany(IObservable<TSource> source, Func<TSource, int, IObservable<TResult>> selector, Func<Exception, IObservable<TResult>> selectorOnError, Func<IObservable<TResult>> selectorOnCompleted) { _source = source; _selectorI = selector; _selectorOnError = selectorOnError; _selectorOnCompleted = selectorOnCompleted; } public SelectMany(IObservable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { _source = source; _selectorE = selector; } public SelectMany(IObservable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector) { _source = source; _selectorEI = selector; } #if !NO_TPL private readonly Func<TSource, CancellationToken, Task<TResult>> _selectorT; private readonly Func<TSource, int, CancellationToken, Task<TResult>> _selectorTI; public SelectMany(IObservable<TSource> source, Func<TSource, CancellationToken, Task<TResult>> selector) { _source = source; _selectorT = selector; } public SelectMany(IObservable<TSource> source, Func<TSource, int, CancellationToken, Task<TResult>> selector) { _source = source; _selectorTI = selector; } #endif protected override IDisposable Run(IObserver<TResult> observer, IDisposable cancel, Action<IDisposable> setSink) { if (_selector != null) { var sink = new _(this, observer, cancel); setSink(sink); return sink.Run(); } else if (_selectorI != null) { var sink = new IndexSelectorImpl(this, observer, cancel); setSink(sink); return sink.Run(); } #if !NO_TPL else if (_selectorT != null) { var sink = new SelectManyImpl(this, observer, cancel); setSink(sink); return sink.Run(); } else if (_selectorTI != null) { var sink = new Sigma(this, observer, cancel); setSink(sink); return sink.Run(); } #endif else if (_selectorE != null) { var sink = new NoSelectorImpl(this, observer, cancel); setSink(sink); return _source.SubscribeSafe(sink); } else { var sink = new Omega(this, observer, cancel); setSink(sink); return _source.SubscribeSafe(sink); } } class _ : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TResult> _parent; public _(SelectMany<TSource, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private bool _isStopped; private CompositeDisposable _group; private SingleAssignmentDisposable _sourceSubscription; public IDisposable Run() { _gate = new object(); _isStopped = false; _group = new CompositeDisposable(); _sourceSubscription = new SingleAssignmentDisposable(); _group.Add(_sourceSubscription); _sourceSubscription.Disposable = _parent._source.SubscribeSafe(this); return _group; } public void OnNext(TSource value) { var inner = default(IObservable<TResult>); try { inner = _parent._selector(value); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } SubscribeInner(inner); } public void OnError(Exception error) { if (_parent._selectorOnError != null) { var inner = default(IObservable<TResult>); try { inner = _parent._selectorOnError(error); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } SubscribeInner(inner); Final(); } else { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } } public void OnCompleted() { if (_parent._selectorOnCompleted != null) { var inner = default(IObservable<TResult>); try { inner = _parent._selectorOnCompleted(); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } SubscribeInner(inner); } Final(); } private void Final() { _isStopped = true; if (_group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } else { _sourceSubscription.Dispose(); } } private void SubscribeInner(IObservable<TResult> inner) { var innerSubscription = new SingleAssignmentDisposable(); _group.Add(innerSubscription); innerSubscription.Disposable = inner.SubscribeSafe(new Iter(this, innerSubscription)); } class Iter : IObserver<TResult> { private readonly _ _parent; private readonly IDisposable _self; public Iter(_ parent, IDisposable self) { _parent = parent; _self = self; } public void OnNext(TResult value) { lock (_parent._gate) _parent._observer.OnNext(value); } public void OnError(Exception error) { lock (_parent._gate) { _parent._observer.OnError(error); _parent.Dispose(); } } public void OnCompleted() { _parent._group.Remove(_self); if (_parent._isStopped && _parent._group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_parent._gate) { _parent._observer.OnCompleted(); _parent.Dispose(); } } } } } class IndexSelectorImpl : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TResult> _parent; public IndexSelectorImpl(SelectMany<TSource, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private bool _isStopped; private CompositeDisposable _group; private SingleAssignmentDisposable _sourceSubscription; private int _index; public IDisposable Run() { _gate = new object(); _isStopped = false; _group = new CompositeDisposable(); _sourceSubscription = new SingleAssignmentDisposable(); _group.Add(_sourceSubscription); _sourceSubscription.Disposable = _parent._source.SubscribeSafe(this); return _group; } public void OnNext(TSource value) { var inner = default(IObservable<TResult>); try { inner = _parent._selectorI(value, checked(_index++)); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } SubscribeInner(inner); } public void OnError(Exception error) { if (_parent._selectorOnError != null) { var inner = default(IObservable<TResult>); try { inner = _parent._selectorOnError(error); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } SubscribeInner(inner); Final(); } else { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } } public void OnCompleted() { if (_parent._selectorOnCompleted != null) { var inner = default(IObservable<TResult>); try { inner = _parent._selectorOnCompleted(); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } SubscribeInner(inner); } Final(); } private void Final() { _isStopped = true; if (_group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } else { _sourceSubscription.Dispose(); } } private void SubscribeInner(IObservable<TResult> inner) { var innerSubscription = new SingleAssignmentDisposable(); _group.Add(innerSubscription); innerSubscription.Disposable = inner.SubscribeSafe(new Iter(this, innerSubscription)); } class Iter : IObserver<TResult> { private readonly IndexSelectorImpl _parent; private readonly IDisposable _self; public Iter(IndexSelectorImpl parent, IDisposable self) { _parent = parent; _self = self; } public void OnNext(TResult value) { lock (_parent._gate) _parent._observer.OnNext(value); } public void OnError(Exception error) { lock (_parent._gate) { _parent._observer.OnError(error); _parent.Dispose(); } } public void OnCompleted() { _parent._group.Remove(_self); if (_parent._isStopped && _parent._group.Count == 1) { // // Notice there can be a race between OnCompleted of the source and any // of the inner sequences, where both see _group.Count == 1, and one is // waiting for the lock. There won't be a double OnCompleted observation // though, because the call to Dispose silences the observer by swapping // in a NopObserver<T>. // lock (_parent._gate) { _parent._observer.OnCompleted(); _parent.Dispose(); } } } } } class NoSelectorImpl : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TResult> _parent; public NoSelectorImpl(SelectMany<TSource, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } public void OnNext(TSource value) { var xs = default(IEnumerable<TResult>); try { xs = _parent._selectorE(value); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } var e = default(IEnumerator<TResult>); try { e = xs.GetEnumerator(); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } try { var hasNext = true; while (hasNext) { hasNext = false; var current = default(TResult); try { hasNext = e.MoveNext(); if (hasNext) current = e.Current; } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } if (hasNext) base._observer.OnNext(current); } } finally { if (e != null) e.Dispose(); } } public void OnError(Exception error) { base._observer.OnError(error); base.Dispose(); } public void OnCompleted() { base._observer.OnCompleted(); base.Dispose(); } } class Omega : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TResult> _parent; public Omega(SelectMany<TSource, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private int _index; public void OnNext(TSource value) { var xs = default(IEnumerable<TResult>); try { xs = _parent._selectorEI(value, checked(_index++)); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } var e = default(IEnumerator<TResult>); try { e = xs.GetEnumerator(); } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } try { var hasNext = true; while (hasNext) { hasNext = false; var current = default(TResult); try { hasNext = e.MoveNext(); if (hasNext) current = e.Current; } catch (Exception exception) { base._observer.OnError(exception); base.Dispose(); return; } if (hasNext) base._observer.OnNext(current); } } finally { if (e != null) e.Dispose(); } } public void OnError(Exception error) { base._observer.OnError(error); base.Dispose(); } public void OnCompleted() { base._observer.OnCompleted(); base.Dispose(); } } #if !NO_TPL #pragma warning disable 0420 class SelectManyImpl : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TResult> _parent; public SelectManyImpl(SelectMany<TSource, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private CancellationDisposable _cancel; private volatile int _count; public IDisposable Run() { _gate = new object(); _cancel = new CancellationDisposable(); _count = 1; return new CompositeDisposable(_parent._source.SubscribeSafe(this), _cancel); } public void OnNext(TSource value) { var task = default(Task<TResult>); try { Interlocked.Increment(ref _count); task = _parent._selectorT(value, _cancel.Token); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } if (task.IsCompleted) { OnCompletedTask(task); } else { task.ContinueWith(OnCompletedTask); } } private void OnCompletedTask(Task<TResult> task) { switch (task.Status) { case TaskStatus.RanToCompletion: { lock (_gate) base._observer.OnNext(task.Result); OnCompleted(); } break; case TaskStatus.Faulted: { lock (_gate) { base._observer.OnError(task.Exception.InnerException); base.Dispose(); } } break; case TaskStatus.Canceled: { if (!_cancel.IsDisposed) { lock (_gate) { base._observer.OnError(new TaskCanceledException(task)); base.Dispose(); } } } break; } } public void OnError(Exception error) { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } public void OnCompleted() { if (Interlocked.Decrement(ref _count) == 0) { lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } } } class Sigma : Sink<TResult>, IObserver<TSource> { private readonly SelectMany<TSource, TResult> _parent; public Sigma(SelectMany<TSource, TResult> parent, IObserver<TResult> observer, IDisposable cancel) : base(observer, cancel) { _parent = parent; } private object _gate; private CancellationDisposable _cancel; private volatile int _count; private int _index; public IDisposable Run() { _gate = new object(); _cancel = new CancellationDisposable(); _count = 1; return new CompositeDisposable(_parent._source.SubscribeSafe(this), _cancel); } public void OnNext(TSource value) { var task = default(Task<TResult>); try { Interlocked.Increment(ref _count); task = _parent._selectorTI(value, checked(_index++), _cancel.Token); } catch (Exception ex) { lock (_gate) { base._observer.OnError(ex); base.Dispose(); } return; } if (task.IsCompleted) { OnCompletedTask(task); } else { task.ContinueWith(OnCompletedTask); } } private void OnCompletedTask(Task<TResult> task) { switch (task.Status) { case TaskStatus.RanToCompletion: { lock (_gate) base._observer.OnNext(task.Result); OnCompleted(); } break; case TaskStatus.Faulted: { lock (_gate) { base._observer.OnError(task.Exception.InnerException); base.Dispose(); } } break; case TaskStatus.Canceled: { if (!_cancel.IsDisposed) { lock (_gate) { base._observer.OnError(new TaskCanceledException(task)); base.Dispose(); } } } break; } } public void OnError(Exception error) { lock (_gate) { base._observer.OnError(error); base.Dispose(); } } public void OnCompleted() { if (Interlocked.Decrement(ref _count) == 0) { lock (_gate) { base._observer.OnCompleted(); base.Dispose(); } } } } #pragma warning restore 0420 #endif } } #endif
33.650374
208
0.412899
[ "Apache-2.0" ]
Distrotech/mono
external/rx/Rx/NET/Source/System.Reactive.Linq/Reactive/Linq/Observable/SelectMany.cs
58,520
C#
using System.Collections.Generic; using System.Threading.Tasks; using TutteeFrame2.Model; using TutteeFrame2.DataAccess; using TutteeFrame2.View; namespace TutteeFrame2.Controller { class ScheduleController { public List<Subject> subject; readonly Schedule schedule; public string scheduleID; public List<Session> sessions; public List<Class> classes; public ScheduleController(Schedule schedule) { this.schedule = schedule; } public async void FetchData() { await Task.Delay(600); await Task.Run(() => { subject = SubjectDA.Instance.GetSubjects(); }); schedule.GetSubject(); } public async void GetSchedule(string lop, int hk, int nam) { //await Task.Delay(600); await Task.Run(() => { scheduleID = ScheduleDA.Instance.GetSchedule(lop, hk, nam); }); schedule.GetSchedule(); } public async void FetchSchedule(string scheduleid) { //await Task.Delay(600); await Task.Run(() => { sessions = ScheduleDA.Instance.GetSessions(scheduleid); }); schedule.FetchSchedule(); } public async void Add(Session s, string scheduleid) { await Task.Delay(600); await Task.Run(() => { ScheduleDA.Instance.AddSession(s, scheduleid); }); } public async void Detele(string id) { await Task.Delay(600); await Task.Run(() => { ScheduleDA.Instance.Delete(id); }); } public async void GetClass(string grade) { schedule.homeView.SetLoad(true, "Đang tải danh sách lớp..."); await Task.Delay(600); await Task.Run(() => { classes = ClassDA.Instance.GetClasses(grade); }); schedule.AddClasses(); schedule.homeView.SetLoad(false); } } }
28.881579
75
0.513895
[ "MIT" ]
princ3od/TutteeFrame-2.0
TutteeFrame2/Controller/ScheduleController.cs
2,203
C#
using UnityEngine; using TMPro; public class LoginPresenter : MonoBehaviour { #region Script Parameters public TMP_InputField Username; public TMP_InputField Password; public GameObject errorText; #endregion #region Methods public void Login() { UserController.sInstance.Login(Username.text, Password.text); } #endregion }
18.75
69
0.706667
[ "MIT" ]
si-bada/tower-defense
Assets/Scripts/Presenters/LoginPresenter.cs
377
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using SplitBillsBackend.Data; namespace SplitBillsBackend.Migrations { [DbContext(typeof(SplitBillsDbContext))] partial class SplitBillsDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.0-rtm-30799") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("RoleId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("RoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<int>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("UserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<int>("UserId"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("UserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b => { b.Property<int>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("UserTokens"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Bill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("CreatorId"); b.Property<DateTime>("Date"); b.Property<string>("Description"); b.Property<int?>("SubcategoryId"); b.Property<decimal>("TotalAmount") .HasColumnType("decimal(7, 2)"); b.HasKey("Id"); b.HasIndex("CreatorId"); b.HasIndex("SubcategoryId"); b.ToTable("Bills"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Categories"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Friend", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("FirstFriendId"); b.Property<int?>("SecondFriendId"); b.HasKey("Id"); b.HasIndex("FirstFriendId"); b.HasIndex("SecondFriendId"); b.ToTable("Friends"); }); modelBuilder.Entity("SplitBillsBackend.Entities.History", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("BillId"); b.Property<int?>("CreatorId"); b.Property<DateTime>("Date"); b.Property<string>("Description"); b.Property<int>("HistoryType"); b.HasKey("Id"); b.HasIndex("BillId"); b.HasIndex("CreatorId"); b.ToTable("History"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Note", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("BillId"); b.Property<string>("Text"); b.HasKey("Id"); b.HasIndex("BillId"); b.ToTable("Notes"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("Roles"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Subcategory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("CategoryId"); b.Property<string>("Name"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.ToTable("Subcategories"); }); modelBuilder.Entity("SplitBillsBackend.Entities.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<bool>("Connected"); b.Property<string>("ConnectionId"); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("Enabled"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<DateTime>("RegisterDate"); b.Property<string>("SecurityStamp"); b.Property<string>("Surname"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("Users"); }); modelBuilder.Entity("SplitBillsBackend.Entities.UserBill", b => { b.Property<int>("UserId"); b.Property<int>("BillId"); b.Property<decimal>("Amount") .HasColumnType("decimal(7, 2)"); b.Property<bool>("Settled"); b.HasKey("UserId", "BillId"); b.HasIndex("BillId"); b.ToTable("UserBills"); }); modelBuilder.Entity("SplitBillsBackend.Entities.UserRole", b => { b.Property<int>("UserId"); b.Property<int>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("UserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<int>", b => { b.HasOne("SplitBillsBackend.Entities.Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<int>", b => { b.HasOne("SplitBillsBackend.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<int>", b => { b.HasOne("SplitBillsBackend.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<int>", b => { b.HasOne("SplitBillsBackend.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SplitBillsBackend.Entities.Bill", b => { b.HasOne("SplitBillsBackend.Entities.User", "Creator") .WithMany("Bills") .HasForeignKey("CreatorId"); b.HasOne("SplitBillsBackend.Entities.Subcategory", "Subcategory") .WithMany("Bills") .HasForeignKey("SubcategoryId"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Friend", b => { b.HasOne("SplitBillsBackend.Entities.User", "FirstFriend") .WithMany("Friends") .HasForeignKey("FirstFriendId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("SplitBillsBackend.Entities.User", "SecondFriend") .WithMany("OtherFriends") .HasForeignKey("SecondFriendId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("SplitBillsBackend.Entities.History", b => { b.HasOne("SplitBillsBackend.Entities.Bill", "Bill") .WithMany() .HasForeignKey("BillId"); b.HasOne("SplitBillsBackend.Entities.User", "Creator") .WithMany() .HasForeignKey("CreatorId"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Note", b => { b.HasOne("SplitBillsBackend.Entities.Bill", "Bill") .WithMany("Notes") .HasForeignKey("BillId"); }); modelBuilder.Entity("SplitBillsBackend.Entities.Subcategory", b => { b.HasOne("SplitBillsBackend.Entities.Category", "Category") .WithMany("Subcategories") .HasForeignKey("CategoryId"); }); modelBuilder.Entity("SplitBillsBackend.Entities.UserBill", b => { b.HasOne("SplitBillsBackend.Entities.Bill", "Bill") .WithMany("UserBills") .HasForeignKey("BillId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("SplitBillsBackend.Entities.User", "User") .WithMany("UserBills") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SplitBillsBackend.Entities.UserRole", b => { b.HasOne("SplitBillsBackend.Entities.Role", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("SplitBillsBackend.Entities.User", "User") .WithMany("UserRoles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.742009
125
0.471446
[ "MIT" ]
piters3/SplitBillsBackend
SplitBillsBackend/Migrations/SplitBillsDbContextModelSnapshot.cs
15,219
C#
using Academy.Core.Contracts; using System; namespace Academy.Core.Providers { public class ConsoleLogger : ILogger { public void Log(string message) { Console.WriteLine(message); } } }
18.076923
40
0.617021
[ "MIT" ]
Camyul/Modul_2_CSharp
Design-Patterns/Live Demo/Academy/After/Academy.Framework/Core/Providers/ConsoleLogger.cs
237
C#
using System; using System.Linq; using EventStore.Core.Data; using EventStore.Core.Tests; using EventStore.Projections.Core.Messages; using NUnit.Framework; using ResolvedEvent = EventStore.Projections.Core.Services.Processing.ResolvedEvent; using EventStore.Projections.Core.Services; namespace EventStore.Projections.Core.Tests.Services.core_projection { [TestFixture(typeof(LogFormat.V2), typeof(string))] [TestFixture(typeof(LogFormat.V3), typeof(uint))] public class when_the_state_handler_fails_to_load_state_the_projection_should<TLogFormat, TStreamId> : TestFixtureWithCoreProjectionStarted<TLogFormat, TStreamId> { protected override void Given() { ExistingEvent( "$projections-projection-result", "Result", @"{""c"": 100, ""p"": 50}", "{}"); ExistingEvent( "$projections-projection-checkpoint", ProjectionEventTypes.ProjectionCheckpoint, @"{""c"": 100, ""p"": 50}", "{}"); NoStream("$projections-projection-order"); AllWritesToSucceed("$projections-projection-order"); } protected override FakeProjectionStateHandler GivenProjectionStateHandler() { return new FakeProjectionStateHandler(failOnLoad: true); } protected override void When() { //projection subscribes here _bus.Publish( EventReaderSubscriptionMessage.CommittedEventReceived.Sample( new ResolvedEvent( "/event_category/1", -1, "/event_category/1", -1, false, new TFPos(120, 110), Guid.NewGuid(), "handle_this_type", false, "data", "metadata"), _subscriptionId, 0)); } [Test] public void should_publish_faulted_message() { Assert.AreEqual(1, _consumer.HandledMessages.OfType<CoreProjectionStatusMessage.Faulted>().Count()); } [Test] public void not_emit_a_state_updated_event() { Assert.AreEqual(0, _writeEventHandler.HandledMessages.OfEventType("StateUpdate").Count()); } } }
37
153
0.751351
[ "Apache-2.0", "CC0-1.0" ]
BearerPipelineTest/EventStore
src/EventStore.Projections.Core.Tests/Services/core_projection/when_the_state_handler_fails_to_load_state_the_projection_should.cs
1,850
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.Elb { public static class GetHostedZoneId { /// <summary> /// Use this data source to get the HostedZoneId of the AWS Elastic Load Balancing HostedZoneId /// in a given region for the purpose of using in an AWS Route53 Alias. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var main = Output.Create(Aws.Elb.GetHostedZoneId.InvokeAsync()); /// var www = new Aws.Route53.Record("www", new Aws.Route53.RecordArgs /// { /// ZoneId = aws_route53_zone.Primary.Zone_id, /// Name = "example.com", /// Type = "A", /// Aliases = /// { /// new Aws.Route53.Inputs.RecordAliasArgs /// { /// Name = aws_elb.Main.Dns_name, /// ZoneId = main.Apply(main =&gt; main.Id), /// EvaluateTargetHealth = true, /// }, /// }, /// }); /// } /// /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Task<GetHostedZoneIdResult> InvokeAsync(GetHostedZoneIdArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetHostedZoneIdResult>("aws:elb/getHostedZoneId:getHostedZoneId", args ?? new GetHostedZoneIdArgs(), options.WithDefaults()); /// <summary> /// Use this data source to get the HostedZoneId of the AWS Elastic Load Balancing HostedZoneId /// in a given region for the purpose of using in an AWS Route53 Alias. /// /// {{% examples %}} /// ## Example Usage /// {{% example %}} /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var main = Output.Create(Aws.Elb.GetHostedZoneId.InvokeAsync()); /// var www = new Aws.Route53.Record("www", new Aws.Route53.RecordArgs /// { /// ZoneId = aws_route53_zone.Primary.Zone_id, /// Name = "example.com", /// Type = "A", /// Aliases = /// { /// new Aws.Route53.Inputs.RecordAliasArgs /// { /// Name = aws_elb.Main.Dns_name, /// ZoneId = main.Apply(main =&gt; main.Id), /// EvaluateTargetHealth = true, /// }, /// }, /// }); /// } /// /// } /// ``` /// {{% /example %}} /// {{% /examples %}} /// </summary> public static Output<GetHostedZoneIdResult> Invoke(GetHostedZoneIdInvokeArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.Invoke<GetHostedZoneIdResult>("aws:elb/getHostedZoneId:getHostedZoneId", args ?? new GetHostedZoneIdInvokeArgs(), options.WithDefaults()); } public sealed class GetHostedZoneIdArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the region whose AWS ELB HostedZoneId is desired. /// Defaults to the region from the AWS provider configuration. /// </summary> [Input("region")] public string? Region { get; set; } public GetHostedZoneIdArgs() { } } public sealed class GetHostedZoneIdInvokeArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the region whose AWS ELB HostedZoneId is desired. /// Defaults to the region from the AWS provider configuration. /// </summary> [Input("region")] public Input<string>? Region { get; set; } public GetHostedZoneIdInvokeArgs() { } } [OutputType] public sealed class GetHostedZoneIdResult { /// <summary> /// The provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; public readonly string? Region; [OutputConstructor] private GetHostedZoneIdResult( string id, string? region) { Id = id; Region = region; } } }
34.557047
180
0.488056
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/Elb/GetHostedZoneId.cs
5,149
C#
using System; using System.Buffers; namespace Orleans.Networking.Shared { public class SocketConnectionOptions { /// <summary> /// The number of I/O queues used to process requests. Set to 0 to directly schedule I/O to the ThreadPool. /// </summary> /// <remarks> /// Defaults to <see cref="Environment.ProcessorCount" /> rounded down and clamped between 1 and 16. /// </remarks> public int IOQueueCount { get; set; } = Math.Min(Environment.ProcessorCount, 16); public bool NoDelay { get; set; } = true; internal Func<MemoryPool<byte>> MemoryPoolFactory { get; set; } = () => KestrelMemoryPool.Create(); } }
33.095238
115
0.633094
[ "MIT" ]
Abramalin/orleans
src/Orleans.Core/Networking/Shared/SocketConnectionOptions.cs
695
C#
// The MIT License(MIT) // // Copyright(c) 2021 Alberto Rodriguez Orozco & LiveCharts Contributors // // 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 System; namespace LiveChartsCore.Drawing.Common { /// <summary> /// The Transition builder class helps to build transitions using fluent synstax. /// </summary> public class TransitionBuilder { private readonly string[] _properties; private readonly IAnimatable _target; /// <summary> /// Initializes a new instance of the <see cref="TransitionBuilder"/> class. /// </summary> /// <param name="target">The target.</param> /// <param name="properties">The properties.</param> public TransitionBuilder(IAnimatable target, string[] properties) { _target = target; _properties = properties; } /// <summary> /// Sets the animation. /// </summary> /// <param name="animation">The animation.</param> /// <returns>The transition</returns> public TransitionBuilder WithAnimation(Animation animation) { _target.SetPropertiesTransitions(animation, _properties); return this; } /// <summary> /// Sets the animation. /// </summary> /// <param name="animationBuilder">The animation builder.</param> /// <returns>The transition</returns> public TransitionBuilder WithAnimation(Action<Animation> animationBuilder) { var animation = new Animation(); animationBuilder(animation); return WithAnimation(animation); } /// <summary> /// Sets the current transitions. /// </summary> /// <returns>The transition</returns> public TransitionBuilder CompleteCurrentTransitions() { _target.CompleteTransitions(_properties); return this; } } }
37.024691
85
0.655552
[ "MIT" ]
bbmmcodegirl/LiveCharts2
src/LiveChartsCore/Drawing/TransitionBuilder.cs
3,001
C#
using Jasper.Attributes; using Jasper.Http.Routing; using Shouldly; using Xunit; namespace Jasper.Http.Testing.Routing { public class special_routing_determination_rules { [Fact] public void homeendpoint() { JasperRoute.Build<HomeEndpoint>(x => x.Get()).MethodAndPatternShouldBe("GET", ""); JasperRoute.Build<HomeEndpoint>(x => x.Put()).MethodAndPatternShouldBe("PUT", ""); JasperRoute.Build<HomeEndpoint>(x => x.Delete()).MethodAndPatternShouldBe("DELETE", ""); } [Fact] public void serviceendpoint() { JasperRoute.Build<ServiceEndpoint>(x => x.Index()).MethodAndPatternShouldBe("GET", ""); JasperRoute.Build<ServiceEndpoint>(x => x.Get()).MethodAndPatternShouldBe("GET", ""); JasperRoute.Build<ServiceEndpoint>(x => x.Put()).MethodAndPatternShouldBe("PUT", ""); JasperRoute.Build<ServiceEndpoint>(x => x.Delete()).MethodAndPatternShouldBe("DELETE", ""); } } public static class RouteSpecificationExtensions { public static void MethodAndPatternShouldBe(this JasperRoute route, string method, string pattern) { route.HttpMethod.ShouldBe(method); route.Pattern.ShouldBe(pattern); } } public class HomeEndpoint { // Responds to GET: / public string Get() { return "Hello, world!"; } // Responds to PUT: / public void Put() { } // Responds to DELETE: / public void Delete() { } } [JasperIgnore] // SAMPLE: ServiceEndpoint public class ServiceEndpoint { // GET: / public string Index() { return "Hello, world"; } // GET: / public string Get() { return "Hello, world"; } // PUT: / public string Put() { return "Hello, world"; } // DELETE: / public string Delete() { return "Hello, world"; } } // ENDSAMPLE }
23.736264
106
0.541204
[ "MIT" ]
CodingGorilla/jasper
src/Jasper.Http.Testing/Routing/special_routing_determination_rules.cs
2,162
C#
using System; using System.ComponentModel; namespace Tools.CSharp.DataTable.CompositeObjects { //------------------------------------------------------------------------- public interface IContainedObjectCollection : IDisposable { //--------------------------------------------------------------------- int Count { get; } //--------------------------------------------------------------------- event ListChangedEventHandler Changed; //--------------------------------------------------------------------- } //------------------------------------------------------------------------- public interface IContainedObjectCollection<out TContainedObject> : IContainedObjectCollection { //--------------------------------------------------------------------- TContainedObject this[int index] { get; } //--------------------------------------------------------------------- } //------------------------------------------------------------------------- }
45.478261
98
0.282983
[ "MIT" ]
zveruger/csharp_tools
src/Tools.CSharp.DataTable/CompositeObjects/Interfaces/IContainedObjectCollection.cs
1,046
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Jil.Common; namespace Jil.Deserialize { static class SetterLookup<ForType> { public static Dictionary<string, int> Lookup; static SetterLookup() { var setters = GetSetters(); var asList = setters.Select(s => s.Key).OrderBy(_ => _).ToList(); Lookup = asList.ToDictionary(d => d, d => asList.IndexOf(d)); } public static Dictionary<string, MemberInfo> GetSetters() { var forType = typeof(ForType); var fields = forType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); var props = forType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public).Where(p => p.SetMethod != null); var members = fields.Cast<MemberInfo>().Concat(props.Cast<MemberInfo>()); return members.ToDictionary(m => m.GetSerializationName(), m => m); } } }
31.628571
151
0.644083
[ "MIT" ]
lovewitty/Jil
Jil/Deserialize/SetterLookup.cs
1,109
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("JobScheduler.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JobScheduler.Core")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("54a65be7-e322-4b5e-8e7c-081c6cd08cb2")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.810811
56
0.715183
[ "Apache-2.0" ]
lnO4X/JobScheduler
JobScheduler.Core/Properties/AssemblyInfo.cs
1,306
C#
using Android.App; using Android.Content.PM; namespace CustomHandlerDemo { [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)] public class MainActivity : MauiAppCompatActivity { } }
37.9
235
0.783641
[ "MIT" ]
AlejandroRuiz/MauiHandlersNetConfLatam
src/CustomHandlerDemo/Platforms/Android/MainActivity.cs
381
C#
namespace CoreWiki.Web.Configurations { using Data; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Models.Identity; public static partial class ConfigurationExtensions { public static IServiceCollection ConfigureIdentity(this IServiceCollection service) { service.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 1; options.User.RequireUniqueEmail = true; }) .AddDefaultUI() .AddDefaultTokenProviders() .AddEntityFrameworkStores<CoreWikiContext>(); return service; } } }
34.428571
91
0.631743
[ "MIT" ]
stoyanov7/CoreWiki
src/CoreWiki.Web/Configurations/ConfigureIdentity.cs
966
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Zergatul.Cryptography.Asymmetric; using Zergatul.Network.Tls.Messages; namespace Zergatul.Network.Tls { internal class ECDHKeyExchange : AbstractTlsKeyExchange { public override MessageInfo ServerCertificateMessage => MessageInfo.Required; public override MessageInfo ServerKeyExchangeMessage => MessageInfo.Forbidden; public override MessageInfo CertificateRequestMessage { get { throw new NotImplementedException(); } } public override MessageInfo ClientCertificateMessage { get { throw new NotImplementedException(); } } public override MessageInfo CertificateverifyMessage { get { throw new NotImplementedException(); } } #region ServerKeyExchange public override ServerKeyExchange GenerateServerKeyExchange() { throw new InvalidOperationException(); } public override ServerKeyExchange ReadServerKeyExchange(BinaryReader reader) { throw new InvalidOperationException(); } public override void WriteServerKeyExchange(ServerKeyExchange message, BinaryWriter writer) { throw new InvalidOperationException(); } #endregion #region ClientKeyExchange public override ClientKeyExchange GenerateClientKeyExchange() { var message = new ClientKeyExchange(); var algo = SecurityParameters.ServerCertificate.PublicKey.ResolveAlgorithm(); var ecdhServer = (ECPDiffieHellman)algo.ToKeyExchange(); var ecdhClient = new ECPDiffieHellman(); ecdhClient.Random = Random; ecdhClient.Parameters = ecdhServer.Parameters; ecdhClient.GenerateKeyPair(0); message.ECDH_Yc = ecdhClient.PublicKey.Point.ToUncompressed(); var secret = ecdhClient.CalculateSharedSecret(ecdhServer.PublicKey); PreMasterSecret = ByteArray.SubArray(secret, 1, secret.Length - 1); return message; } public override ClientKeyExchange ReadClientKeyExchange(BinaryReader reader) { var message = new ClientKeyExchange(); message.ECDH_Yc = reader.ReadBytes(reader.ReadByte()); var algo = SecurityParameters.ServerCertificate.PrivateKey.ResolveAlgorithm(); var ecdh = (ECPDiffieHellman)algo.ToKeyExchange(); var secret = ecdh.CalculateSharedSecret(new ECPPublicKey(ECPointGeneric.Parse(message.ECDH_Yc, ecdh.Parameters.Curve).PFECPoint)); PreMasterSecret = ByteArray.SubArray(secret, 1, secret.Length - 1); return message; } public override void WriteClientKeyExchange(ClientKeyExchange message, BinaryWriter writer) { writer.WriteByte((byte)message.ECDH_Yc.Length); writer.WriteBytes(message.ECDH_Yc); } #endregion } }
32.16
142
0.643035
[ "MIT" ]
Zergatul/ZergatulLib
Zergatul/Network/Tls/ECDHKeyExchange.cs
3,218
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Tests.Visual; using osuTK; using osuTK.Input; namespace osu.Game.Rulesets.Osu.Tests.Editor { public class TestSceneSliderPlacementBlueprint : PlacementBlueprintTestScene { [SetUp] public void Setup() => Schedule(() => { HitObjectContainer.Clear(); ResetPlacement(); }); [Test] public void TestBeginPlacementWithoutFinishing() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); assertPlaced(false); } [Test] public void TestPlaceWithoutMovingMouse() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addClickStep(MouseButton.Right); assertPlaced(true); assertLength(0); assertControlPointType(0, PathType.Linear); } [Test] public void TestPlaceWithMouseMovement() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400, 200)); addClickStep(MouseButton.Right); assertPlaced(true); assertLength(200); assertControlPointCount(2); assertControlPointType(0, PathType.Linear); } [Test] public void TestPlaceNormalControlPoint() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(3); assertControlPointPosition(1, new Vector2(100, 0)); assertControlPointType(0, PathType.PerfectCurve); } [Test] public void TestPlaceTwoNormalControlPoints() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400, 300)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(4); assertControlPointPosition(1, new Vector2(100, 0)); assertControlPointPosition(2, new Vector2(100, 100)); assertControlPointType(0, PathType.Bezier); } [Test] public void TestPlaceSegmentControlPoint() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(3); assertControlPointPosition(1, new Vector2(100, 0)); assertControlPointType(0, PathType.Linear); assertControlPointType(1, PathType.Linear); } [Test] public void TestMoveToPerfectCurveThenPlaceLinear() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300)); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(2); assertControlPointType(0, PathType.Linear); assertLength(100); } [Test] public void TestMoveToBezierThenPlacePerfectCurve() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400, 300)); addMovementStep(new Vector2(300)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(3); assertControlPointType(0, PathType.PerfectCurve); } [Test] public void TestMoveToFourthOrderBezierThenPlaceThirdOrderBezier() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400, 300)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400)); addMovementStep(new Vector2(400, 300)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(4); assertControlPointType(0, PathType.Bezier); } [Test] public void TestPlaceLinearSegmentThenPlaceLinearSegment() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 300)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(3); assertControlPointPosition(1, new Vector2(100, 0)); assertControlPointPosition(2, new Vector2(100)); assertControlPointType(0, PathType.Linear); assertControlPointType(1, PathType.Linear); } [Test] public void TestPlaceLinearSegmentThenPlacePerfectCurveSegment() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 300)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400, 300)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(4); assertControlPointPosition(1, new Vector2(100, 0)); assertControlPointPosition(2, new Vector2(100)); assertControlPointType(0, PathType.Linear); assertControlPointType(1, PathType.PerfectCurve); } [Test] public void TestPlacePerfectCurveSegmentThenPlacePerfectCurveSegment() { addMovementStep(new Vector2(200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 200)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(300, 300)); addClickStep(MouseButton.Left); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400, 300)); addClickStep(MouseButton.Left); addMovementStep(new Vector2(400)); addClickStep(MouseButton.Right); assertPlaced(true); assertControlPointCount(5); assertControlPointPosition(1, new Vector2(100, 0)); assertControlPointPosition(2, new Vector2(100)); assertControlPointPosition(3, new Vector2(200, 100)); assertControlPointPosition(4, new Vector2(200)); assertControlPointType(0, PathType.PerfectCurve); assertControlPointType(2, PathType.PerfectCurve); } [Test] public void TestBeginPlacementWithoutReleasingMouse() { addMovementStep(new Vector2(200)); AddStep("press left button", () => InputManager.PressButton(MouseButton.Left)); addMovementStep(new Vector2(400, 200)); AddStep("release left button", () => InputManager.ReleaseButton(MouseButton.Left)); addClickStep(MouseButton.Right); assertPlaced(true); assertLength(200); assertControlPointCount(2); assertControlPointType(0, PathType.Linear); } private void addMovementStep(Vector2 position) => AddStep($"move mouse to {position}", () => InputManager.MoveMouseTo(InputManager.ToScreenSpace(position))); private void addClickStep(MouseButton button) { AddStep($"press {button}", () => InputManager.PressButton(button)); AddStep($"release {button}", () => InputManager.ReleaseButton(button)); } private void assertPlaced(bool expected) => AddAssert($"slider {(expected ? "placed" : "not placed")}", () => (getSlider() != null) == expected); private void assertLength(double expected) => AddAssert($"slider length is {expected}", () => Precision.AlmostEquals(expected, getSlider().Distance, 1)); private void assertControlPointCount(int expected) => AddAssert($"has {expected} control points", () => getSlider().Path.ControlPoints.Count == expected); private void assertControlPointType(int index, PathType type) => AddAssert($"control point {index} is {type}", () => getSlider().Path.ControlPoints[index].Type.Value == type); private void assertControlPointPosition(int index, Vector2 position) => AddAssert($"control point {index} at {position}", () => Precision.AlmostEquals(position, getSlider().Path.ControlPoints[index].Position.Value, 1)); private Slider getSlider() => HitObjectContainer.Count > 0 ? (Slider)((DrawableSlider)HitObjectContainer[0]).HitObject : null; protected override DrawableHitObject CreateHitObject(HitObject hitObject) => new DrawableSlider((Slider)hitObject); protected override PlacementBlueprint CreateBlueprint() => new SliderPlacementBlueprint(); } }
36.315789
184
0.604348
[ "MIT" ]
AaqibAhamed/osu
osu.Game.Rulesets.Osu.Tests/Editor/TestSceneSliderPlacementBlueprint.cs
10,737
C#
using System; namespace XMPPEngineer.Im { /// <summary> /// Represents a privacy rule pertaining to a group. /// </summary> public class GroupPrivacyRule : PrivacyRule { /// <summary> /// The name of the group the privacy rule applies to. /// </summary> public string Group { get; private set; } /// <summary> /// Initializes a new instance of the PrivacyRule class. /// </summary> /// <param name="group">The group the privacy rule applies to.</param> /// <param name="allow">True to allow entities affected by this rule; Otherwise /// false.</param> /// <param name="order">The order of the privacy rule.</param> /// <param name="granularity">Specifies which kinds of stanzas should be /// allowed or blocked, respectively.</param> /// <exception cref="ArgumentNullException">The group parameter is null.</exception> public GroupPrivacyRule(string group, bool allow, uint order, PrivacyGranularity granularity = 0) : base(allow, order, granularity) { group.ThrowIfNull("group"); Group = group; } } }
33.837838
92
0.577476
[ "MIT" ]
ParamountVentures/Sharp.Xmpp
Im/GroupPrivacyRule.cs
1,254
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("Snake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Snake")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("a1a447b7-c3f3-4fed-9e8c-2e69cba7c58d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.378378
84
0.742589
[ "MIT" ]
RadSt/Snake
Snake/Snake/Properties/AssemblyInfo.cs
1,386
C#
 namespace Xendor.Data.MySql { public class MySqlConnection : UnitOfWorkConnection { [Connection("server")] public string Server { get; set; } [Connection("user id")] public string UserId { get; set; } [Connection("database")] public string DataBase { get; set; } [Connection("Pwd")] public string Pwd { get; set; } [Connection("Unicode")] public bool Unicode { get; set; } [Connection("port")] public int Port { get; set; } [Connection("license key")] public string LicenseKey { get; set; } } }
25.16
55
0.554849
[ "MIT" ]
amolines/cqrs
src/Xendor.Data.MySql/MySqlConnection.cs
631
C#
using System; using System.Net; using System.Threading.Tasks; using SFA.DAS.SharedOuterApi.Interfaces; using SFA.DAS.SharedOuterApi.Models; namespace SFA.DAS.SharedOuterApi.Infrastructure.Services { public class ReliableCacheStorageService<TConfiguration> : IReliableCacheStorageService where TConfiguration : IApiConfiguration { private readonly IGetApiClient<TConfiguration> _client; private readonly ICacheStorageService _cacheStorageService; public ReliableCacheStorageService (IGetApiClient<TConfiguration> client, ICacheStorageService cacheStorageService) { _client = client; _cacheStorageService = cacheStorageService; } public async Task<T> GetData<T>(IGetApiRequest request, string cacheKey, Func<ApiResponse<T>, bool> requestCheck) { var cachedItem = await _cacheStorageService.RetrieveFromCache<T>(cacheKey); if (cachedItem != null) { return cachedItem; } var requestData = await _client.GetWithResponseCode<T>(request); if (requestData.StatusCode == HttpStatusCode.NotFound || !requestCheck(requestData)) { return default; } if ((int)requestData.StatusCode < 200 || (int)requestData.StatusCode > 300) { var longCachedItem = await _cacheStorageService.RetrieveFromCache<T>($"{cacheKey}_extended"); await _cacheStorageService.SaveToCache(cacheKey, longCachedItem, TimeSpan.FromMinutes(5)); return longCachedItem; } var shortCacheTask = _cacheStorageService.SaveToCache(cacheKey, requestData.Body, TimeSpan.FromMinutes(5)); var longCacheTask = _cacheStorageService.SaveToCache($"{cacheKey}_extended", requestData.Body, TimeSpan.FromDays(180)); await Task.WhenAll(shortCacheTask, longCacheTask); return requestData.Body; } } }
40.82
132
0.660951
[ "MIT" ]
SkillsFundingAgency/das-apim-endpoints
src/SFA.DAS.SharedOuterApi/Infrastructure/Services/ReliableCacheStorageService.cs
2,043
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Web.Api.Core.Dto.UseCaseRequests; using Web.Api.Core.Dto.UseCaseResponses; using Web.Api.Core.Interfaces; using Web.Api.Core.Interfaces.Gateways.Repositories; using Web.Api.Core.Interfaces.Services; using Web.Api.Core.Interfaces.UseCases; namespace Web.Api.Core.UseCases.Request { public class GetEachRequestUseCase : IGetEachRequestUseCase { private readonly IRequestRepository _requestRepository; private Domain.Entities.User _currentUser; public GetEachRequestUseCase(IRequestRepository requestRepository, IAuthService authService) { _requestRepository = requestRepository; _currentUser = authService.GetCurrentUser(); } public async Task<bool> Handle(GetEachRequestRequest message, IOutputPort<GetEachRequestResponse> outputPort) { var request = _requestRepository.getEachRequest(message.RequestId, _currentUser.Role.Name); outputPort.Handle(new GetEachRequestResponse(request, true)); return true; } } }
34.909091
117
0.739583
[ "MIT" ]
tdtrung17693/gdpr-system-backend
src/Web.Api.Core/UseCases/Request/GetEachRequestUseCase.cs
1,154
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("FreeFoundationsFreeSoil")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FreeFoundationsFreeSoil")] [assembly: AssemblyCopyright("Copyright © 2021")] [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("63fb8f6b-cb6e-4114-8063-99e455442c81")] // 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.2.3")] [assembly: AssemblyFileVersion("1.2.3")]
38.108108
84
0.752482
[ "BSD-3-Clause" ]
WaGi-Coding/Taki_DSP-Mods
FreeFoundationsFreeSoil/Properties/AssemblyInfo.cs
1,413
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Text; using Microsoft.AspNetCore.Blazor.Hosting; using Microsoft.Extensions.DependencyInjection; namespace HWDnGCI.Client { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("app"); await builder.Build().RunAsync(); } } }
23.714286
69
0.680723
[ "MIT" ]
pankajk2526/HWDNGCI
Client/Program.cs
500
C#
using LibHac; using LibHac.Common; using LibHac.Ns; namespace Ryujinx.Ui { public struct ApplicationData { public bool Favorite { get; set; } public byte[] Icon { get; set; } public string TitleName { get; set; } public string TitleId { get; set; } public string Developer { get; set; } public string Version { get; set; } public string TimePlayed { get; set; } public string LastPlayed { get; set; } public string FileExtension { get; set; } public string FileSize { get; set; } public string Path { get; set; } public string SaveDataPath { get; set; } public BlitStruct<ApplicationControlProperty> ControlHolder { get; set; } } }
33.625
81
0.570012
[ "MIT" ]
AidanXu/Ryujinx
Ryujinx/Ui/ApplicationData.cs
809
C#
using System; using h73.Elastic.Core.Enums; using Newtonsoft.Json; namespace h73.Elastic.Core.Search.Queries { /// <summary> /// Matches documents with fields that have terms within a certain range. /// The type of the Lucene query depends on the field type, for string fields, the TermRangeQuery, while for number/date fields, the query is a NumericRangeQuery. /// </summary> /// <typeparam name="T">Type of T</typeparam> /// <seealso cref="h73.Elastic.Core.Search.Queries.QueryInit" /> [Serializable] public class RangeQuery<T> : QueryInit { /// <summary> /// Initializes a new instance of the <see cref="RangeQuery{T}"/> class. /// </summary> public RangeQuery() { } /// <summary> /// Initializes a new instance of the <see cref="RangeQuery{T}"/> class. /// </summary> /// <param name="value">The value.</param> /// <param name="field">The field.</param> /// <param name="type">The type.</param> /// <param name="boost">Boost</param> public RangeQuery(T value, string field, RangeQueryType type, double? boost = null) { switch (type) { case RangeQueryType.GreaterThan: Range = new RangeQueryItem<T> { [field] = new RangeQueryValue<T> { GreaterThan = value, Boost = boost } }; break; case RangeQueryType.LesserThan: Range = new RangeQueryItem<T> { [field] = new RangeQueryValue<T> { LesserThan = value, Boost = boost } }; break; case RangeQueryType.GreaterThanEqual: Range = new RangeQueryItem<T> { [field] = new RangeQueryValue<T> { GreaterThanOrEqual = value, Boost = boost } }; break; case RangeQueryType.LesserThanEqual: Range = new RangeQueryItem<T> { [field] = new RangeQueryValue<T> { LesserThanOrEqual = value, Boost = boost } }; break; } } /// <summary> /// Initializes a new instance of the <see cref="RangeQuery{T}"/> class. /// </summary> /// <param name="greaterThan">The greater than.</param> /// <param name="lesserThan">The lesser than.</param> /// <param name="field">The field.</param> /// <param name="type">The type.</param> public RangeQuery(T greaterThan, T lesserThan, string field, RangeQueryType type, double? boost = null) { switch (type) { case RangeQueryType.GreaterLesserThan: Range = new RangeQueryItem<T> { [field] = new RangeQueryValue<T> { GreaterThan = greaterThan, LesserThan = lesserThan, Boost = boost } }; break; case RangeQueryType.GreaterLesserThanEqual: Range = new RangeQueryItem<T> { [field] = new RangeQueryValue<T> { GreaterThanOrEqual = greaterThan, LesserThanOrEqual = lesserThan, Boost = boost } }; break; } } /// <summary> /// Gets or sets the range. /// </summary> /// <value> /// The range. /// </value> [JsonProperty("range")] public RangeQueryItem<T> Range { get; set; } } }
38.56701
166
0.49853
[ "MIT" ]
henskjold73/h73.Elastic.Core
h73.Elastic.Core/Search/Queries/RangeQuery`1.cs
3,743
C#
using System; using System.ComponentModel; using System.Windows.Forms; namespace Epi.Windows { /// <summary> /// Container that encapsulates and tracks components of the module /// </summary> public class ModuleContainer : Container { IServiceProvider serviceProvider = null; /// <summary> /// The default container /// </summary> /// <param name="provider">The service provider</param> public ModuleContainer(IServiceProvider provider) { this.serviceProvider = provider; } /// <summary> /// Gets the service for a specified type /// </summary> /// <returns>An object that represents a service for the specified type </returns> [System.Diagnostics.DebuggerStepThrough()] protected override object GetService(Type serviceType) { // first look in epi info object service = serviceProvider.GetService(serviceType); if (service == null) { // call into .net framework if service wasn't found service = base.GetService(serviceType); } return service; } } }
32.25
91
0.556589
[ "Apache-2.0" ]
Epi-Info/Epi-Info-Community-Edition
Epi.Windows/ModuleContainer.cs
1,290
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview { using Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="AzureFileServiceDataSourceProperties" /// /> /// </summary> public partial class AzureFileServiceDataSourcePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="AzureFileServiceDataSourceProperties" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="AzureFileServiceDataSourceProperties" /> type, otherwise /// <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="AzureFileServiceDataSourceProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="AzureFileServiceDataSourceProperties" />.</param> /// <returns> /// an instance of <see cref="AzureFileServiceDataSourceProperties" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IAzureFileServiceDataSourceProperties ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IAzureFileServiceDataSourceProperties).IsAssignableFrom(type)) { return sourceValue; } try { return AzureFileServiceDataSourceProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return AzureFileServiceDataSourceProperties.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return AzureFileServiceDataSourceProperties.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
53.040268
253
0.602303
[ "MIT" ]
Agazoth/azure-powershell
src/Purview/Purviewdata.Autorest/generated/api/Models/Api20211001Preview/AzureFileServiceDataSourceProperties.TypeConverter.cs
7,755
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.EventHubs { using System; /// <summary> /// The exception that is thrown when a server is busy. Callers should wait a while and retry the operation. /// </summary> public sealed class ServerBusyException : EventHubsException { internal ServerBusyException(string message) : this(message, null) { } internal ServerBusyException(string message, Exception innerException) : base(true, message, innerException) { } } }
29.041667
113
0.658537
[ "MIT" ]
0xced/azure-sdk-for-net
sdk/eventhub/Microsoft.Azure.EventHubs/src/Primitives/ServerBusyException.cs
699
C#
#region ---------- File Info ---------- /// ********************************************************************** /// Copyright (C) 2018 DarkRabbit(ZhangHan) /// /// File Name: SwapTextureCache.cs /// Author: DarkRabbit /// Create Time: Thu, 01 Feb 2018 00:45:12 GMT /// Modifier: /// Module Description: /// Version: V1.0.0 /// ********************************************************************** #endregion ---------- File Info ---------- using System.Collections.Generic; using UnityEngine; namespace DR.Book.SRPG_Dev.ColorPalette { /// <summary> /// SwapTexture缓存 /// </summary> public static class SwapTextureCache { /// <summary> /// 缓存数据唯一标识 /// </summary> private struct CacheKey { /// <summary> /// Color Chart的名字 /// </summary> public string chartName; /// <summary> /// 源Texture的名字 /// </summary> public string textureName; } /// <summary> /// 缓存Dictionary /// </summary> private static Dictionary<CacheKey, Texture2D> s_CacheDict; /// <summary> /// 缓存Texture的数量 /// </summary> public static int count { get { if (s_CacheDict == null) { return 0; } return s_CacheDict.Count; } } /// <summary> /// 尝试获取缓存数据 /// </summary> /// <param name="chartName"></param> /// <param name="textureName"></param> /// <param name="cache"></param> /// <returns></returns> public static bool TryGetTexture2D(string chartName, string textureName, out Texture2D cache) { cache = null; if (s_CacheDict == null) { return false; } if (string.IsNullOrEmpty(chartName) || string.IsNullOrEmpty(textureName)) { return false; } CacheKey key = new CacheKey() { chartName = chartName, textureName = textureName }; if(!s_CacheDict.TryGetValue(key, out cache)) { return false; } // 如果为null,成功取出,但在别处意外的被Destroy了,删除缓存 if (cache == null) { s_CacheDict.Remove(key); return false; } return true; } /// <summary> /// 将SwapTexture添加进缓存 /// </summary> /// <param name="chartName"></param> /// <param name="textureName"></param> /// <param name="swapTexture"></param> /// <returns></returns> public static bool AddTexture2D(string chartName, string textureName, Texture2D swapTexture) { if (string.IsNullOrEmpty(chartName) || string.IsNullOrEmpty(textureName) || swapTexture == null) { return false; } CacheKey key = new CacheKey() { chartName = chartName, textureName = textureName }; if (s_CacheDict == null) { s_CacheDict = new Dictionary<CacheKey, Texture2D>(); } if (s_CacheDict.ContainsKey(key)) { return false; } s_CacheDict.Add(key, swapTexture); return true; } /// <summary> /// 清理缓存 /// </summary> public static void Clear() { if (s_CacheDict == null) { return; } Texture2D[] caches = new Texture2D[count]; s_CacheDict.Values.CopyTo(caches, 0); s_CacheDict = null; for (int i = 0; i < caches.Length; i++) { if (caches[i] != null) { Texture2D.Destroy(caches[i]); } } //List<CacheKey> keys = new List<CacheKey>(s_CacheDict.Keys); //foreach (CacheKey key in keys) //{ // if (s_CacheDict[key] != null) // { // Texture2D.Destroy(s_CacheDict[key]); // } // s_CacheDict.Remove(key); //} //if (s_CacheDict.Count == 0) //{ // s_CacheDict = null; //} } } }
26.80117
108
0.426795
[ "Apache-2.0" ]
Coreffy/book_srpg_dev
Ch7_Pathfinding_and_Map_Object/Ch7_Final/Assets/SRPG_Dev/Script/ColorPalette/SwapTextureCache.cs
4,715
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.Datadoghq.V1Alpha1 { [OutputType] public sealed class DatadogAgentSpecClusterChecksRunnerConfigVolumesFc { /// <summary> /// Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. TODO: how do we prevent errors in the filesystem from compromising the machine /// </summary> public readonly string FsType; /// <summary> /// Optional: FC target lun number /// </summary> public readonly int Lun; /// <summary> /// Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. /// </summary> public readonly bool ReadOnly; /// <summary> /// Optional: FC target worldwide names (WWNs) /// </summary> public readonly ImmutableArray<string> TargetWWNs; /// <summary> /// Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously. /// </summary> public readonly ImmutableArray<string> Wwids; [OutputConstructor] private DatadogAgentSpecClusterChecksRunnerConfigVolumesFc( string fsType, int lun, bool readOnly, ImmutableArray<string> targetWWNs, ImmutableArray<string> wwids) { FsType = fsType; Lun = lun; ReadOnly = readOnly; TargetWWNs = targetWWNs; Wwids = wwids; } } }
34.508772
258
0.632944
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/datadog-operator/dotnet/Kubernetes/Crds/Operators/DatadogOperator/Datadoghq/V1Alpha1/Outputs/DatadogAgentSpecClusterChecksRunnerConfigVolumesFc.cs
1,967
C#
// Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Xunit; namespace UnitsNet.Serialization.JsonNet.Tests { public sealed class UnitsNetBaseJsonConverterTest { private readonly TestConverter _sut; public UnitsNetBaseJsonConverterTest() { _sut = new TestConverter(); } [Fact] public void UnitsNetBaseJsonConverter_ConvertIQuantity_works_with_double_type() { var result = _sut.Test_ConvertDoubleIQuantity(Length.FromMeters(10.2365)); Assert.Equal("LengthUnit.Meter", result.Unit); Assert.Equal(10.2365, result.Value); } [Fact] public void UnitsNetBaseJsonConverter_ConvertIQuantity_works_with_decimal_type() { var result = _sut.Test_ConvertDecimalIQuantity(Power.FromWatts(10.2365m)); Assert.Equal("PowerUnit.Watt", result.Unit); Assert.Equal(10.2365m, result.Value); } [Fact] public void UnitsNetBaseJsonConverter_ConvertIQuantity_throws_ArgumentNullException_when_quantity_is_NULL() { var result = Assert.Throws<ArgumentNullException>(() => _sut.Test_ConvertDoubleIQuantity(null)); Assert.Equal($"Value cannot be null.{Environment.NewLine}Parameter name: quantity", result.Message); } [Fact] public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_as_expected() { var result = _sut.Test_ConvertDecimalValueUnit("PowerUnit.Watt", 10.2365m); Assert.NotNull(result); Assert.IsType<Power>(result); Assert.True(Power.FromWatts(10.2365m).Equals((Power)result, 1E-5, ComparisonType.Absolute)); } [Fact] public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_with_NULL_value() { var result = _sut.Test_ConvertValueUnit(); Assert.Null(result); } [Fact] public void UnitsNetBaseJsonConverter_ConvertValueUnit_throws_UnitsNetException_when_unit_does_not_exist() { var result = Assert.Throws<UnitsNetException>(() => _sut.Test_ConvertDoubleValueUnit("SomeImaginaryUnit.Watt", 10.2365D)); Assert.Equal("Unable to find enum type.", result.Message); Assert.True(result.Data.Contains("type")); Assert.Equal("UnitsNet.Units.SomeImaginaryUnit,UnitsNet", result.Data["type"]); } [Fact] public void UnitsNetBaseJsonConverter_ConvertValueUnit_throws_UnitsNetException_when_unit_is_in_unexpected_format() { var result = Assert.Throws<UnitsNetException>(() => _sut.Test_ConvertDecimalValueUnit("PowerUnit Watt", 10.2365m)); Assert.Equal("\"PowerUnit Watt\" is not a valid unit.", result.Message); Assert.True(result.Data.Contains("type")); Assert.Equal("PowerUnit Watt", result.Data["type"]); } [Fact] public void UnitsNetBaseJsonConverter_CreateLocalSerializer_works_as_expected() { //Possible improvement: Set all possible settings and test each one. But the main goal of CreateLocalSerializer is that the current serializer is left out. var serializer = JsonSerializer.Create(new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Arrays, Converters = new List<JsonConverter>() { new BinaryConverter(), _sut, new DataTableConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }); var result = _sut.Test_CreateLocalSerializer(serializer); Assert.Equal(TypeNameHandling.Arrays, result.TypeNameHandling); Assert.Equal(2, result.Converters.Count); Assert.Collection(result.Converters, (converter) => Assert.IsType<BinaryConverter>(converter), (converter) => Assert.IsType<DataTableConverter>(converter)); Assert.IsType<CamelCasePropertyNamesContractResolver>(result.ContractResolver); } [Fact] public void UnitsNetBaseJsonConverter_ReadValueUnit_works_with_double_quantity() { var token = new JObject {{"Unit", "LengthUnit.Meter"}, {"Value", 10.2365}}; var result = _sut.Test_ReadDoubleValueUnit(token); Assert.NotNull(result); Assert.Equal("LengthUnit.Meter", result?.Unit); Assert.Equal(10.2365, result?.Value); } [Fact] public void UnitsNetBaseJsonConverter_ReadValueUnit_works_with_decimal_quantity() { var token = new JObject {{"Unit", "PowerUnit.Watt"}, {"Value", 10.2365m}, {"ValueString", "10.2365"}, {"ValueType", "decimal"}}; var result = _sut.Test_ReadDecimalValueUnit(token); Assert.NotNull(result); Assert.Equal("PowerUnit.Watt", result?.Unit); Assert.Equal(10.2365m, result?.Value); } [Fact] public void UnitsNetBaseJsonConverter_ReadValueUnit_returns_null_when_value_is_a_string() { var token = new JObject {{"Unit", "PowerUnit.Watt"}, {"Value", "10.2365"}}; var result = _sut.Test_ReadDecimalValueUnit(token); Assert.Null(result); } [Fact] public void UnitsNetBaseJsonConverter_ReadValueUnit_returns_null_when_value_type_is_not_a_string() { var token = new JObject {{"Unit", "PowerUnit.Watt"}, {"Value", 10.2365}, {"ValueType", 123}}; var result = _sut.Test_ReadDecimalValueUnit(token); Assert.Null(result); } [Fact] public void UnitsNetBaseJsonConverter_ReadDoubleValueUnit_works_with_empty_token() { var token = new JObject(); var result = _sut.Test_ReadDoubleValueUnit(token); Assert.Null(result); } [Theory] [InlineData(false, true)] [InlineData(true, false)] public void UnitsNetBaseJsonConverter_ReadValueUnit_returns_null_when_unit_or_value_is_missing(bool withUnit, bool withValue) { var token = new JObject(); if (withUnit) { token.Add("Unit", "PowerUnit.Watt"); } if (withValue) { token.Add("Value", 10.2365m); } var result = _sut.Test_ReadDecimalValueUnit(token); Assert.Null(result); } [Theory] [InlineData("Unit", "Value", "ValueString", "ValueType")] [InlineData("unit", "Value", "ValueString", "ValueType")] [InlineData("Unit", "value", "valueString", "valueType")] [InlineData("unit", "value", "valueString", "valueType")] [InlineData("unIT", "vAlUe", "vAlUeString", "vAlUeType")] public void UnitsNetBaseJsonConverter_ReadValueUnit_works_case_insensitive( string unitPropertyName, string valuePropertyName, string valueStringPropertyName, string valueTypePropertyName) { var token = new JObject { {unitPropertyName, "PowerUnit.Watt"}, {valuePropertyName, 10.2365m}, {valueStringPropertyName, 10.2365m.ToString(CultureInfo.InvariantCulture)}, {valueTypePropertyName, "decimal"} }; var result = _sut.Test_ReadDecimalValueUnit(token); Assert.NotNull(result); Assert.Equal("PowerUnit.Watt", result?.Unit); Assert.Equal(10.2365m, result?.Value); } /// <summary> /// Dummy converter, used to access protected methods on abstract UnitsNetBaseJsonConverter{T} /// </summary> private class TestConverter : UnitsNetBaseJsonConverter<string> { public override bool CanRead => false; public override bool CanWrite => false; public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer) => throw new NotImplementedException(); public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); public (string Unit, double Value) Test_ConvertDoubleIQuantity(IQuantity value) { var result = ConvertIQuantity(value); return (result.Unit, result.Value); } public (string Unit, decimal Value) Test_ConvertDecimalIQuantity(IQuantity value) { var result = ConvertIQuantity(value); if (result is ExtendedValueUnit {ValueType: "decimal"} decimalResult) { return (result.Unit, decimal.Parse(decimalResult.ValueString)); } throw new ArgumentException("The quantity does not have a decimal value", nameof(value)); } public IQuantity Test_ConvertDoubleValueUnit(string unit, double value) => Test_ConvertValueUnit(new ValueUnit {Unit = unit, Value = value}); public IQuantity Test_ConvertDecimalValueUnit(string unit, decimal value) => Test_ConvertValueUnit(new ExtendedValueUnit { Unit = unit, Value = (double) value, ValueString = value.ToString(CultureInfo.InvariantCulture), ValueType = "decimal" }); public IQuantity Test_ConvertValueUnit() => Test_ConvertValueUnit(null); private IQuantity Test_ConvertValueUnit(ValueUnit valueUnit) => ConvertValueUnit(valueUnit); public JsonSerializer Test_CreateLocalSerializer(JsonSerializer serializer) => CreateLocalSerializer(serializer, this); public (string Unit, double Value)? Test_ReadDoubleValueUnit(JToken jsonToken) { var result = ReadValueUnit(jsonToken); if (result == null) { return null; } return (result.Unit, result.Value); } public (string Unit, decimal Value)? Test_ReadDecimalValueUnit(JToken jsonToken) { var result = ReadValueUnit(jsonToken); if (result is ExtendedValueUnit {ValueType: "decimal"} decimalResult) { return (result.Unit, decimal.Parse(decimalResult.ValueString)); } return null; } } } }
38.534965
191
0.622357
[ "MIT-feh" ]
CallumECameron/UnitsNet
UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs
11,023
C#
namespace Content.Shared.GameObjects.Components.Mobs.State { public abstract class SharedDeadMobState : BaseMobState { protected override DamageState DamageState => DamageState.Dead; public override bool CanInteract() { return false; } public override bool CanMove() { return false; } public override bool CanUse() { return false; } public override bool CanThrow() { return false; } public override bool CanSpeak() { return false; } public override bool CanDrop() { return false; } public override bool CanPickup() { return false; } public override bool CanEmote() { return false; } public override bool CanAttack() { return false; } public override bool CanEquip() { return false; } public override bool CanUnequip() { return false; } public override bool CanChangeDirection() { return false; } public bool CanShiver() { return false; } public bool CanSweat() { return false; } } }
18.230769
71
0.471871
[ "MIT" ]
BananaFlambe/space-station-14
Content.Shared/GameObjects/Components/Mobs/State/SharedDeadMobState.cs
1,424
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CleanupObject : MonoBehaviour { [SerializeField] private Collider coll; [SerializeField] private CabinetBase laminarCabinet, secondPassThroughCabinet; private TriggerInteractableContainer roomItems; private bool startedCleanup; private bool finished; private void Start() { roomItems = coll.gameObject.AddComponent<TriggerInteractableContainer>(); Events.SubscribeToEvent(ItemLiftedFromFloor, this, EventType.ItemLiftedOffFloor); Events.SubscribeToEvent(ItemDroppedInTrash, this, EventType.ItemDroppedInTrash); } public static CleanupObject GetCleanup() { return GameObject.FindObjectOfType<CleanupObject>(); } private void ItemLiftedFromFloor(CallbackData data) { GeneralItem item = (GeneralItem)data.DataObject; if (G.Instance.Progress.CurrentPackage.name == PackageName.EquipmentSelection) { return; } if (!startedCleanup && !item.IsClean) { Task.CreateTaskMistake(TaskType.ScenarioOneCleanUp, "Siivoa lattialla olevat esineet vasta lopuksi", 1); } } private void ItemDroppedInTrash(CallbackData data) { GeneralItem g = (GeneralItem)data.DataObject; if (G.Instance.Progress.CurrentPackage.name == PackageName.EquipmentSelection) { return; } if (g.ObjectType == ObjectType.Bottle || g.ObjectType == ObjectType.Medicine) { Task.CreateTaskMistake(TaskType.ScenarioOneCleanUp, "Pulloa ei saa heittää roskikseen", 1); } if (g.ObjectType == ObjectType.SterileBag) { Task.CreateTaskMistake(TaskType.ScenarioOneCleanUp, "Steriilipussia ei saa heittää roskikseen", 1); } } private void Update() { if (startedCleanup && !finished) { if (RoomGeneralItemCount() <= 1) { finished = true; G.Instance.Progress.ForceCloseTask(TaskType.ScenarioOneCleanUp, false); } } } private int RoomGeneralItemCount() { int count = 0; foreach (Interactable i in roomItems.Objects) { if (i as GeneralItem is var g && g != null) { if (g.ObjectType == ObjectType.Bottle || g.ObjectType == ObjectType.SterileBag || g.ObjectType == ObjectType.Medicine) { continue; } if (g.Rigidbody == null || g.Rigidbody.isKinematic) { continue; } count++; } } return count; } public void EnableCleanup() { ObjectFactory.DestroyAllFactories(true); foreach (Interactable i in secondPassThroughCabinet.GetContainedItems()) { i.DestroyInteractable(); } foreach (ItemSpawner i in GameObject.FindObjectsOfType<ItemSpawner>()) { Destroy(i.gameObject); } startedCleanup = true; } }
32.010526
136
0.628741
[ "MIT" ]
MikkoHimanka/farmasia-vr
Assets/Scripts/RoomFunctions/CleanupObject.cs
3,047
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Diagnostics; namespace System.Globalization { /// <remarks> /// Calendar support range: /// Calendar Minimum Maximum /// ========== ========== ========== /// Gregorian 1900/04/30 2077/05/13 /// UmAlQura 1318/01/01 1500/12/30 /// </remarks> public partial class UmAlQuraCalendar : Calendar { private const int MinCalendarYear = 1318; private const int MaxCalendarYear = 1500; private struct DateMapping { internal DateMapping(int MonthsLengthFlags, int GYear, int GMonth, int GDay) { HijriMonthsLengthFlags = MonthsLengthFlags; GregorianDate = new DateTime(GYear, GMonth, GDay); } internal int HijriMonthsLengthFlags; internal DateTime GregorianDate; } private static readonly DateMapping[] s_hijriYearInfo = InitDateMapping(); private static DateMapping[] InitDateMapping() { short[] rawData = new short[] { //These data is taken from Tables/Excel/UmAlQura.xls please make sure that the two places are in sync /* DaysPerM GY GM GD D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 1318*/0x02EA, 1900, 4, 30,/* 0 1 0 1 0 1 1 1 0 1 0 0 4/30/1900 1319*/0x06E9, 1901, 4, 19,/* 1 0 0 1 0 1 1 1 0 1 1 0 4/19/1901 1320*/0x0ED2, 1902, 4, 9,/* 0 1 0 0 1 0 1 1 0 1 1 1 4/9/1902 1321*/0x0EA4, 1903, 3, 30,/* 0 0 1 0 0 1 0 1 0 1 1 1 3/30/1903 1322*/0x0D4A, 1904, 3, 18,/* 0 1 0 1 0 0 1 0 1 0 1 1 3/18/1904 1323*/0x0A96, 1905, 3, 7,/* 0 1 1 0 1 0 0 1 0 1 0 1 3/7/1905 1324*/0x0536, 1906, 2, 24,/* 0 1 1 0 1 1 0 0 1 0 1 0 2/24/1906 1325*/0x0AB5, 1907, 2, 13,/* 1 0 1 0 1 1 0 1 0 1 0 1 2/13/1907 1326*/0x0DAA, 1908, 2, 3,/* 0 1 0 1 0 1 0 1 1 0 1 1 2/3/1908 1327*/0x0BA4, 1909, 1, 23,/* 0 0 1 0 0 1 0 1 1 1 0 1 1/23/1909 1328*/0x0B49, 1910, 1, 12,/* 1 0 0 1 0 0 1 0 1 1 0 1 1/12/1910 1329*/0x0A93, 1911, 1, 1,/* 1 1 0 0 1 0 0 1 0 1 0 1 1/1/1911 1330*/0x052B, 1911, 12, 21,/* 1 1 0 1 0 1 0 0 1 0 1 0 12/21/1911 1331*/0x0A57, 1912, 12, 9,/* 1 1 1 0 1 0 1 0 0 1 0 1 12/9/1912 1332*/0x04B6, 1913, 11, 29,/* 0 1 1 0 1 1 0 1 0 0 1 0 11/29/1913 1333*/0x0AB5, 1914, 11, 18,/* 1 0 1 0 1 1 0 1 0 1 0 1 11/18/1914 1334*/0x05AA, 1915, 11, 8,/* 0 1 0 1 0 1 0 1 1 0 1 0 11/8/1915 1335*/0x0D55, 1916, 10, 27,/* 1 0 1 0 1 0 1 0 1 0 1 1 10/27/1916 1336*/0x0D2A, 1917, 10, 17,/* 0 1 0 1 0 1 0 0 1 0 1 1 10/17/1917 1337*/0x0A56, 1918, 10, 6,/* 0 1 1 0 1 0 1 0 0 1 0 1 10/6/1918 1338*/0x04AE, 1919, 9, 25,/* 0 1 1 1 0 1 0 1 0 0 1 0 9/25/1919 1339*/0x095D, 1920, 9, 13,/* 1 0 1 1 1 0 1 0 1 0 0 1 9/13/1920 1340*/0x02EC, 1921, 9, 3,/* 0 0 1 1 0 1 1 1 0 1 0 0 9/3/1921 1341*/0x06D5, 1922, 8, 23,/* 1 0 1 0 1 0 1 1 0 1 1 0 8/23/1922 1342*/0x06AA, 1923, 8, 13,/* 0 1 0 1 0 1 0 1 0 1 1 0 8/13/1923 1343*/0x0555, 1924, 8, 1,/* 1 0 1 0 1 0 1 0 1 0 1 0 8/1/1924 1344*/0x04AB, 1925, 7, 21,/* 1 1 0 1 0 1 0 1 0 0 1 0 7/21/1925 1345*/0x095B, 1926, 7, 10,/* 1 1 0 1 1 0 1 0 1 0 0 1 7/10/1926 1346*/0x02BA, 1927, 6, 30,/* 0 1 0 1 1 1 0 1 0 1 0 0 6/30/1927 1347*/0x0575, 1928, 6, 18,/* 1 0 1 0 1 1 1 0 1 0 1 0 6/18/1928 1348*/0x0BB2, 1929, 6, 8,/* 0 1 0 0 1 1 0 1 1 1 0 1 6/8/1929 1349*/0x0764, 1930, 5, 29,/* 0 0 1 0 0 1 1 0 1 1 1 0 5/29/1930 1350*/0x0749, 1931, 5, 18,/* 1 0 0 1 0 0 1 0 1 1 1 0 5/18/1931 1351*/0x0655, 1932, 5, 6,/* 1 0 1 0 1 0 1 0 0 1 1 0 5/6/1932 1352*/0x02AB, 1933, 4, 25,/* 1 1 0 1 0 1 0 1 0 1 0 0 4/25/1933 1353*/0x055B, 1934, 4, 14,/* 1 1 0 1 1 0 1 0 1 0 1 0 4/14/1934 1354*/0x0ADA, 1935, 4, 4,/* 0 1 0 1 1 0 1 1 0 1 0 1 4/4/1935 1355*/0x06D4, 1936, 3, 24,/* 0 0 1 0 1 0 1 1 0 1 1 0 3/24/1936 1356*/0x0EC9, 1937, 3, 13,/* 1 0 0 1 0 0 1 1 0 1 1 1 3/13/1937 1357*/0x0D92, 1938, 3, 3,/* 0 1 0 0 1 0 0 1 1 0 1 1 3/3/1938 1358*/0x0D25, 1939, 2, 20,/* 1 0 1 0 0 1 0 0 1 0 1 1 2/20/1939 1359*/0x0A4D, 1940, 2, 9,/* 1 0 1 1 0 0 1 0 0 1 0 1 2/9/1940 1360*/0x02AD, 1941, 1, 28,/* 1 0 1 1 0 1 0 1 0 1 0 0 1/28/1941 1361*/0x056D, 1942, 1, 17,/* 1 0 1 1 0 1 1 0 1 0 1 0 1/17/1942 1362*/0x0B6A, 1943, 1, 7,/* 0 1 0 1 0 1 1 0 1 1 0 1 1/7/1943 1363*/0x0B52, 1943, 12, 28,/* 0 1 0 0 1 0 1 0 1 1 0 1 12/28/1943 1364*/0x0AA5, 1944, 12, 16,/* 1 0 1 0 0 1 0 1 0 1 0 1 12/16/1944 1365*/0x0A4B, 1945, 12, 5,/* 1 1 0 1 0 0 1 0 0 1 0 1 12/5/1945 1366*/0x0497, 1946, 11, 24,/* 1 1 1 0 1 0 0 1 0 0 1 0 11/24/1946 1367*/0x0937, 1947, 11, 13,/* 1 1 1 0 1 1 0 0 1 0 0 1 11/13/1947 1368*/0x02B6, 1948, 11, 2,/* 0 1 1 0 1 1 0 1 0 1 0 0 11/2/1948 1369*/0x0575, 1949, 10, 22,/* 1 0 1 0 1 1 1 0 1 0 1 0 10/22/1949 1370*/0x0D6A, 1950, 10, 12,/* 0 1 0 1 0 1 1 0 1 0 1 1 10/12/1950 1371*/0x0D52, 1951, 10, 2,/* 0 1 0 0 1 0 1 0 1 0 1 1 10/2/1951 1372*/0x0A96, 1952, 9, 20,/* 0 1 1 0 1 0 0 1 0 1 0 1 9/20/1952 1373*/0x092D, 1953, 9, 9,/* 1 0 1 1 0 1 0 0 1 0 0 1 9/9/1953 1374*/0x025D, 1954, 8, 29,/* 1 0 1 1 1 0 1 0 0 1 0 0 8/29/1954 1375*/0x04DD, 1955, 8, 18,/* 1 0 1 1 1 0 1 1 0 0 1 0 8/18/1955 1376*/0x0ADA, 1956, 8, 7,/* 0 1 0 1 1 0 1 1 0 1 0 1 8/7/1956 1377*/0x05D4, 1957, 7, 28,/* 0 0 1 0 1 0 1 1 1 0 1 0 7/28/1957 1378*/0x0DA9, 1958, 7, 17,/* 1 0 0 1 0 1 0 1 1 0 1 1 7/17/1958 1379*/0x0D52, 1959, 7, 7,/* 0 1 0 0 1 0 1 0 1 0 1 1 7/7/1959 1380*/0x0AAA, 1960, 6, 25,/* 0 1 0 1 0 1 0 1 0 1 0 1 6/25/1960 1381*/0x04D6, 1961, 6, 14,/* 0 1 1 0 1 0 1 1 0 0 1 0 6/14/1961 1382*/0x09B6, 1962, 6, 3,/* 0 1 1 0 1 1 0 1 1 0 0 1 6/3/1962 1383*/0x0374, 1963, 5, 24,/* 0 0 1 0 1 1 1 0 1 1 0 0 5/24/1963 1384*/0x0769, 1964, 5, 12,/* 1 0 0 1 0 1 1 0 1 1 1 0 5/12/1964 1385*/0x0752, 1965, 5, 2,/* 0 1 0 0 1 0 1 0 1 1 1 0 5/2/1965 1386*/0x06A5, 1966, 4, 21,/* 1 0 1 0 0 1 0 1 0 1 1 0 4/21/1966 1387*/0x054B, 1967, 4, 10,/* 1 1 0 1 0 0 1 0 1 0 1 0 4/10/1967 1388*/0x0AAB, 1968, 3, 29,/* 1 1 0 1 0 1 0 1 0 1 0 1 3/29/1968 1389*/0x055A, 1969, 3, 19,/* 0 1 0 1 1 0 1 0 1 0 1 0 3/19/1969 1390*/0x0AD5, 1970, 3, 8,/* 1 0 1 0 1 0 1 1 0 1 0 1 3/8/1970 1391*/0x0DD2, 1971, 2, 26,/* 0 1 0 0 1 0 1 1 1 0 1 1 2/26/1971 1392*/0x0DA4, 1972, 2, 16,/* 0 0 1 0 0 1 0 1 1 0 1 1 2/16/1972 1393*/0x0D49, 1973, 2, 4,/* 1 0 0 1 0 0 1 0 1 0 1 1 2/4/1973 1394*/0x0A95, 1974, 1, 24,/* 1 0 1 0 1 0 0 1 0 1 0 1 1/24/1974 1395*/0x052D, 1975, 1, 13,/* 1 0 1 1 0 1 0 0 1 0 1 0 1/13/1975 1396*/0x0A5D, 1976, 1, 2,/* 1 0 1 1 1 0 1 0 0 1 0 1 1/2/1976 1397*/0x055A, 1976, 12, 22,/* 0 1 0 1 1 0 1 0 1 0 1 0 12/22/1976 1398*/0x0AD5, 1977, 12, 11,/* 1 0 1 0 1 0 1 1 0 1 0 1 12/11/1977 1399*/0x06AA, 1978, 12, 1,/* 0 1 0 1 0 1 0 1 0 1 1 0 12/1/1978 1400*/0x0695, 1979, 11, 20,/* 1 0 1 0 1 0 0 1 0 1 1 0 11/20/1979 1401*/0x052B, 1980, 11, 8,/* 1 1 0 1 0 1 0 0 1 0 1 0 11/8/1980 1402*/0x0A57, 1981, 10, 28,/* 1 1 1 0 1 0 1 0 0 1 0 1 10/28/1981 1403*/0x04AE, 1982, 10, 18,/* 0 1 1 1 0 1 0 1 0 0 1 0 10/18/1982 1404*/0x0976, 1983, 10, 7,/* 0 1 1 0 1 1 1 0 1 0 0 1 10/7/1983 1405*/0x056C, 1984, 9, 26,/* 0 0 1 1 0 1 1 0 1 0 1 0 9/26/1984 1406*/0x0B55, 1985, 9, 15,/* 1 0 1 0 1 0 1 0 1 1 0 1 9/15/1985 1407*/0x0AAA, 1986, 9, 5,/* 0 1 0 1 0 1 0 1 0 1 0 1 9/5/1986 1408*/0x0A55, 1987, 8, 25,/* 1 0 1 0 1 0 1 0 0 1 0 1 8/25/1987 1409*/0x04AD, 1988, 8, 13,/* 1 0 1 1 0 1 0 1 0 0 1 0 8/13/1988 1410*/0x095D, 1989, 8, 2,/* 1 0 1 1 1 0 1 0 1 0 0 1 8/2/1989 1411*/0x02DA, 1990, 7, 23,/* 0 1 0 1 1 0 1 1 0 1 0 0 7/23/1990 1412*/0x05D9, 1991, 7, 12,/* 1 0 0 1 1 0 1 1 1 0 1 0 7/12/1991 1413*/0x0DB2, 1992, 7, 1,/* 0 1 0 0 1 1 0 1 1 0 1 1 7/1/1992 1414*/0x0BA4, 1993, 6, 21,/* 0 0 1 0 0 1 0 1 1 1 0 1 6/21/1993 1415*/0x0B4A, 1994, 6, 10,/* 0 1 0 1 0 0 1 0 1 1 0 1 6/10/1994 1416*/0x0A55, 1995, 5, 30,/* 1 0 1 0 1 0 1 0 0 1 0 1 5/30/1995 1417*/0x02B5, 1996, 5, 18,/* 1 0 1 0 1 1 0 1 0 1 0 0 5/18/1996 1418*/0x0575, 1997, 5, 7,/* 1 0 1 0 1 1 1 0 1 0 1 0 5/7/1997 1419*/0x0B6A, 1998, 4, 27,/* 0 1 0 1 0 1 1 0 1 1 0 1 4/27/1998 1420*/0x0BD2, 1999, 4, 17,/* 0 1 0 0 1 0 1 1 1 1 0 1 4/17/1999 1421*/0x0BC4, 2000, 4, 6,/* 0 0 1 0 0 0 1 1 1 1 0 1 4/6/2000 1422*/0x0B89, 2001, 3, 26,/* 1 0 0 1 0 0 0 1 1 1 0 1 3/26/2001 1423*/0x0A95, 2002, 3, 15,/* 1 0 1 0 1 0 0 1 0 1 0 1 3/15/2002 1424*/0x052D, 2003, 3, 4,/* 1 0 1 1 0 1 0 0 1 0 1 0 3/4/2003 1425*/0x05AD, 2004, 2, 21,/* 1 0 1 1 0 1 0 1 1 0 1 0 2/21/2004 1426*/0x0B6A, 2005, 2, 10,/* 0 1 0 1 0 1 1 0 1 1 0 1 2/10/2005 1427*/0x06D4, 2006, 1, 31,/* 0 0 1 0 1 0 1 1 0 1 1 0 1/31/2006 1428*/0x0DC9, 2007, 1, 20,/* 1 0 0 1 0 0 1 1 1 0 1 1 1/20/2007 1429*/0x0D92, 2008, 1, 10,/* 0 1 0 0 1 0 0 1 1 0 1 1 1/10/2008 1430*/0x0AA6, 2008, 12, 29,/* 0 1 1 0 0 1 0 1 0 1 0 1 12/29/2008 1431*/0x0956, 2009, 12, 18,/* 0 1 1 0 1 0 1 0 1 0 0 1 12/18/2009 1432*/0x02AE, 2010, 12, 7,/* 0 1 1 1 0 1 0 1 0 1 0 0 12/7/2010 1433*/0x056D, 2011, 11, 26,/* 1 0 1 1 0 1 1 0 1 0 1 0 11/26/2011 1434*/0x036A, 2012, 11, 15,/* 0 1 0 1 0 1 1 0 1 1 0 0 11/15/2012 1435*/0x0B55, 2013, 11, 4,/* 1 0 1 0 1 0 1 0 1 1 0 1 11/4/2013 1436*/0x0AAA, 2014, 10, 25,/* 0 1 0 1 0 1 0 1 0 1 0 1 10/25/2014 1437*/0x094D, 2015, 10, 14,/* 1 0 1 1 0 0 1 0 1 0 0 1 10/14/2015 1438*/0x049D, 2016, 10, 2,/* 1 0 1 1 1 0 0 1 0 0 1 0 10/2/2016 1439*/0x095D, 2017, 9, 21,/* 1 0 1 1 1 0 1 0 1 0 0 1 9/21/2017 1440*/0x02BA, 2018, 9, 11,/* 0 1 0 1 1 1 0 1 0 1 0 0 9/11/2018 1441*/0x05B5, 2019, 8, 31,/* 1 0 1 0 1 1 0 1 1 0 1 0 8/31/2019 1442*/0x05AA, 2020, 8, 20,/* 0 1 0 1 0 1 0 1 1 0 1 0 8/20/2020 1443*/0x0D55, 2021, 8, 9,/* 1 0 1 0 1 0 1 0 1 0 1 1 8/9/2021 1444*/0x0A9A, 2022, 7, 30,/* 0 1 0 1 1 0 0 1 0 1 0 1 7/30/2022 1445*/0x092E, 2023, 7, 19,/* 0 1 1 1 0 1 0 0 1 0 0 1 7/19/2023 1446*/0x026E, 2024, 7, 7,/* 0 1 1 1 0 1 1 0 0 1 0 0 7/7/2024 1447*/0x055D, 2025, 6, 26,/* 1 0 1 1 1 0 1 0 1 0 1 0 6/26/2025 1448*/0x0ADA, 2026, 6, 16,/* 0 1 0 1 1 0 1 1 0 1 0 1 6/16/2026 1449*/0x06D4, 2027, 6, 6,/* 0 0 1 0 1 0 1 1 0 1 1 0 6/6/2027 1450*/0x06A5, 2028, 5, 25,/* 1 0 1 0 0 1 0 1 0 1 1 0 5/25/2028 1451*/0x054B, 2029, 5, 14,/* 1 1 0 1 0 0 1 0 1 0 1 0 5/14/2029 1452*/0x0A97, 2030, 5, 3,/* 1 1 1 0 1 0 0 1 0 1 0 1 5/3/2030 1453*/0x054E, 2031, 4, 23,/* 0 1 1 1 0 0 1 0 1 0 1 0 4/23/2031 1454*/0x0AAE, 2032, 4, 11,/* 0 1 1 1 0 1 0 1 0 1 0 1 4/11/2032 1455*/0x05AC, 2033, 4, 1,/* 0 0 1 1 0 1 0 1 1 0 1 0 4/1/2033 1456*/0x0BA9, 2034, 3, 21,/* 1 0 0 1 0 1 0 1 1 1 0 1 3/21/2034 1457*/0x0D92, 2035, 3, 11,/* 0 1 0 0 1 0 0 1 1 0 1 1 3/11/2035 1458*/0x0B25, 2036, 2, 28,/* 1 0 1 0 0 1 0 0 1 1 0 1 2/28/2036 1459*/0x064B, 2037, 2, 16,/* 1 1 0 1 0 0 1 0 0 1 1 0 2/16/2037 1460*/0x0CAB, 2038, 2, 5,/* 1 1 0 1 0 1 0 1 0 0 1 1 2/5/2038 1461*/0x055A, 2039, 1, 26,/* 0 1 0 1 1 0 1 0 1 0 1 0 1/26/2039 1462*/0x0B55, 2040, 1, 15,/* 1 0 1 0 1 0 1 0 1 1 0 1 1/15/2040 1463*/0x06D2, 2041, 1, 4,/* 0 1 0 0 1 0 1 1 0 1 1 0 1/4/2041 1464*/0x0EA5, 2041, 12, 24,/* 1 0 1 0 0 1 0 1 0 1 1 1 12/24/2041 1465*/0x0E4A, 2042, 12, 14,/* 0 1 0 1 0 0 1 0 0 1 1 1 12/14/2042 1466*/0x0A95, 2043, 12, 3,/* 1 0 1 0 1 0 0 1 0 1 0 1 12/3/2043 1467*/0x052D, 2044, 11, 21,/* 1 0 1 1 0 1 0 0 1 0 1 0 11/21/2044 1468*/0x0AAD, 2045, 11, 10,/* 1 0 1 1 0 1 0 1 0 1 0 1 11/10/2045 1469*/0x036C, 2046, 10, 31,/* 0 0 1 1 0 1 1 0 1 1 0 0 10/31/2046 1470*/0x0759, 2047, 10, 20,/* 1 0 0 1 1 0 1 0 1 1 1 0 10/20/2047 1471*/0x06D2, 2048, 10, 9,/* 0 1 0 0 1 0 1 1 0 1 1 0 10/9/2048 1472*/0x0695, 2049, 9, 28,/* 1 0 1 0 1 0 0 1 0 1 1 0 9/28/2049 1473*/0x052D, 2050, 9, 17,/* 1 0 1 1 0 1 0 0 1 0 1 0 9/17/2050 1474*/0x0A5B, 2051, 9, 6,/* 1 1 0 1 1 0 1 0 0 1 0 1 9/6/2051 1475*/0x04BA, 2052, 8, 26,/* 0 1 0 1 1 1 0 1 0 0 1 0 8/26/2052 1476*/0x09BA, 2053, 8, 15,/* 0 1 0 1 1 1 0 1 1 0 0 1 8/15/2053 1477*/0x03B4, 2054, 8, 5,/* 0 0 1 0 1 1 0 1 1 1 0 0 8/5/2054 1478*/0x0B69, 2055, 7, 25,/* 1 0 0 1 0 1 1 0 1 1 0 1 7/25/2055 1479*/0x0B52, 2056, 7, 14,/* 0 1 0 0 1 0 1 0 1 1 0 1 7/14/2056 1480*/0x0AA6, 2057, 7, 3,/* 0 1 1 0 0 1 0 1 0 1 0 1 7/3/2057 1481*/0x04B6, 2058, 6, 22,/* 0 1 1 0 1 1 0 1 0 0 1 0 6/22/2058 1482*/0x096D, 2059, 6, 11,/* 1 0 1 1 0 1 1 0 1 0 0 1 6/11/2059 1483*/0x02EC, 2060, 5, 31,/* 0 0 1 1 0 1 1 1 0 1 0 0 5/31/2060 1484*/0x06D9, 2061, 5, 20,/* 1 0 0 1 1 0 1 1 0 1 1 0 5/20/2061 1485*/0x0EB2, 2062, 5, 10,/* 0 1 0 0 1 1 0 1 0 1 1 1 5/10/2062 1486*/0x0D54, 2063, 4, 30,/* 0 0 1 0 1 0 1 0 1 0 1 1 4/30/2063 1487*/0x0D2A, 2064, 4, 18,/* 0 1 0 1 0 1 0 0 1 0 1 1 4/18/2064 1488*/0x0A56, 2065, 4, 7,/* 0 1 1 0 1 0 1 0 0 1 0 1 4/7/2065 1489*/0x04AE, 2066, 3, 27,/* 0 1 1 1 0 1 0 1 0 0 1 0 3/27/2066 1490*/0x096D, 2067, 3, 16,/* 1 0 1 1 0 1 1 0 1 0 0 1 3/16/2067 1491*/0x0D6A, 2068, 3, 5,/* 0 1 0 1 0 1 1 0 1 0 1 1 3/5/2068 1492*/0x0B54, 2069, 2, 23,/* 0 0 1 0 1 0 1 0 1 1 0 1 2/23/2069 1493*/0x0B29, 2070, 2, 12,/* 1 0 0 1 0 1 0 0 1 1 0 1 2/12/2070 1494*/0x0A93, 2071, 2, 1,/* 1 1 0 0 1 0 0 1 0 1 0 1 2/1/2071 1495*/0x052B, 2072, 1, 21,/* 1 1 0 1 0 1 0 0 1 0 1 0 1/21/2072 1496*/0x0A57, 2073, 1, 9,/* 1 1 1 0 1 0 1 0 0 1 0 1 1/9/2073 1497*/0x0536, 2073, 12, 30,/* 0 1 1 0 1 1 0 0 1 0 1 0 12/30/2073 1498*/0x0AB5, 2074, 12, 19,/* 1 0 1 0 1 1 0 1 0 1 0 1 12/19/2074 1499*/0x06AA, 2075, 12, 9,/* 0 1 0 1 0 1 0 1 0 1 1 0 12/9/2075 1500*/0x0E93, 2076, 11, 27,/* 1 1 0 0 1 0 0 1 0 1 1 1 11/27/2076 1501*/ 0, 2077, 11, 17,/* 0 0 0 0 0 0 0 0 0 0 0 0 11/17/2077 */ }; // Direct inline initialization of DateMapping array would produce a lot of code bloat. // We take advantage of C# compiler compiles inline initialization of primitive type array into very compact code. // So we start with raw data stored in primitive type array, and initialize the DateMapping out of it DateMapping[] mapping = new DateMapping[rawData.Length / 4]; for (int i = 0; i < mapping.Length; i++) mapping[i] = new DateMapping(rawData[i * 4], rawData[i * 4 + 1], rawData[i * 4 + 2], rawData[i * 4 + 3]); return mapping; } public const int UmAlQuraEra = 1; private const int DatePartYear = 0; private const int DatePartDayOfYear = 1; private const int DatePartMonth = 2; private const int DatePartDay = 3; private static readonly DateTime s_minDate = new DateTime(1900, 4, 30); private static readonly DateTime s_maxDate = new DateTime((new DateTime(2077, 11, 16, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar; public UmAlQuraCalendar() { } internal override CalendarId BaseCalendarID => CalendarId.HIJRI; internal override CalendarId ID => CalendarId.UMALQURA; protected override int DaysInYearBeforeMinSupportedYear { get { // HijriCalendar has same number of days as UmAlQuraCalendar for any given year // HijriCalendar says year 1317 has 355 days. return 355; } } private static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, out int yg, out int mg, out int dg) { Debug.Assert((HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range."); Debug.Assert(HijriMonth >= 1, "Hijri month is out of range."); Debug.Assert(HijriDay >= 1, "Hijri day is out of range."); int nDays = HijriDay - 1; int index = HijriYear - MinCalendarYear; DateTime dt = s_hijriYearInfo[index].GregorianDate; int b = s_hijriYearInfo[index].HijriMonthsLengthFlags; for (int m = 1; m < HijriMonth; m++) { // Add the months lengths before mh nDays = nDays + 29 + (b & 1); b = b >> 1; } dt = dt.AddDays(nDays); dt.GetDatePart(out yg, out mg, out dg); } private static long GetAbsoluteDateUmAlQura(int year, int month, int day) { ConvertHijriToGregorian(year, month, day, out int yg, out int mg, out int dg); return GregorianCalendar.GetAbsoluteDate(yg, mg, dg); } internal static void CheckTicksRange(long ticks) { if (ticks < s_minDate.Ticks || ticks > s_maxDate.Ticks) { throw new ArgumentOutOfRangeException( "time", ticks, SR.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, s_minDate, s_maxDate)); } } internal static void CheckEraRange(int era) { if (era != CurrentEra && era != UmAlQuraEra) { throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue); } } internal static void CheckYearRange(int year, int era) { CheckEraRange(era); if (year < MinCalendarYear || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(year), year, SR.Format(SR.ArgumentOutOfRange_Range, MinCalendarYear, MaxCalendarYear)); } } internal static void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month); } } private static void ConvertGregorianToHijri(DateTime time, out int HijriYear, out int HijriMonth, out int HijriDay) { Debug.Assert((time.Ticks >= s_minDate.Ticks) && (time.Ticks <= s_maxDate.Ticks), "Gregorian date is out of range."); // Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo. // A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index. int index = (int)((time.Ticks - s_minDate.Ticks) / Calendar.TicksPerDay) / 355; do { } while (time.CompareTo(s_hijriYearInfo[++index].GregorianDate) > 0); //while greater if (time.CompareTo(s_hijriYearInfo[index].GregorianDate) != 0) { index--; } TimeSpan ts = time.Subtract(s_hijriYearInfo[index].GregorianDate); int yh1 = index + MinCalendarYear; int mh1 = 1; int dh1 = 1; double nDays = ts.TotalDays; int b = s_hijriYearInfo[index].HijriMonthsLengthFlags; int daysPerThisMonth = 29 + (b & 1); while (nDays >= daysPerThisMonth) { nDays -= daysPerThisMonth; b = b >> 1; daysPerThisMonth = 29 + (b & 1); mh1++; } dh1 += (int)nDays; HijriDay = dh1; HijriMonth = mh1; HijriYear = yh1; } /// <summary> /// First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks. /// Use the formula (((AbsoluteDate - 226894) * 33) / (33 * 365 + 8)) + 1, we can a rough value for the UmAlQura year. /// In order to get the exact UmAlQura year, we compare the exact absolute date for UmAlQuraYear and (UmAlQuraYear + 1). /// From here, we can get the correct UmAlQura year. /// </summary> private int GetDatePart(DateTime time, int part) { long ticks = time.Ticks; CheckTicksRange(ticks); ConvertGregorianToHijri(time, out int UmAlQuraYear, out int UmAlQuraMonth, out int UmAlQuraDay); if (part == DatePartYear) { return UmAlQuraYear; } if (part == DatePartMonth) { return UmAlQuraMonth; } if (part == DatePartDay) { return UmAlQuraDay; } if (part == DatePartDayOfYear) { return (int)(GetAbsoluteDateUmAlQura(UmAlQuraYear, UmAlQuraMonth, UmAlQuraDay) - GetAbsoluteDateUmAlQura(UmAlQuraYear, 1, 1) + 1); } // Incorrect part value. throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } // Get the date in UmAlQura calendar. int y = GetDatePart(time, DatePartYear); int m = GetDatePart(time, DatePartMonth); int d = GetDatePart(time, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } if (d > 29) { int days = GetDaysInMonth(y, m); if (d > days) { d = days; } } CheckYearRange(y, UmAlQuraEra); DateTime dt = new DateTime(GetAbsoluteDateUmAlQura(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay); Calendar.CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return dt; } public override DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } public override int GetDayOfMonth(DateTime time) { return GetDatePart(time, DatePartDay); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7); } public override int GetDayOfYear(DateTime time) { return GetDatePart(time, DatePartDayOfYear); } public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); if ((s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags & (1 << month - 1)) == 0) { return 29; } else { return 30; } } internal static int RealGetDaysInYear(int year) { int days = 0; Debug.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range."); int b = s_hijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags; for (int m = 1; m <= 12; m++) { days = days + 29 + (b & 1); /* Add the months lengths before mh */ b = b >> 1; } Debug.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days."); return days; } public override int GetDaysInYear(int year, int era) { CheckYearRange(year, era); return RealGetDaysInYear(year); } public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return UmAlQuraEra; } public override int[] Eras => new int[] { UmAlQuraEra }; public override int GetMonth(DateTime time) { return GetDatePart(time, DatePartMonth); } public override int GetMonthsInYear(int year, int era) { CheckYearRange(year, era); return 12; } public override int GetYear(DateTime time) { return GetDatePart(time, DatePartYear); } public override bool IsLeapDay(int year, int month, int day, int era) { if (day >= 1 && day <= 29) { CheckYearMonthRange(year, month, era); return false; } // The year/month/era value checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } return false; } public override int GetLeapMonth(int year, int era) { CheckYearRange(year, era); return 0; } public override bool IsLeapMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); return false; } public override bool IsLeapYear(int year, int era) { CheckYearRange(year, era); return RealGetDaysInYear(year) == 355; } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (day >= 1 && day <= 29) { CheckYearMonthRange(year, month, era); goto DayInRang; } // The year/month/era value checking is done in GetDaysInMonth(). int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } DayInRang: long lDate = GetAbsoluteDateUmAlQura(year, month, day); if (lDate < 0) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } return new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)); } private const int DefaultTwoDigitYearMax = 1451; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DefaultTwoDigitYearMax); } return _twoDigitYearMax; } set { if (value != 99 && (value < MinCalendarYear || value > MaxCalendarYear)) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.ArgumentOutOfRange_Range, MinCalendarYear, MaxCalendarYear)); } VerifyWritable(); // We allow year 99 to be set so that one can make ToFourDigitYearMax a no-op by setting TwoDigitYearMax to 99. _twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return base.ToFourDigitYear(year); } if (year < MinCalendarYear || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( nameof(year), year, SR.Format(SR.ArgumentOutOfRange_Range, MinCalendarYear, MaxCalendarYear)); } return year; } } }
59.893939
146
0.389223
[ "MIT" ]
AfsanehR-zz/corefx
src/Common/src/CoreLib/System/Globalization/UmAlQuraCalendar.cs
39,530
C#
using UnityEngine; using UnityEngine.SceneManagement; public class EntryMenuSceneLoader : MonoBehaviour { public void LoadFreeDrive() { SceneManager.LoadScene("__FreeDrive"); SceneManager.UnloadSceneAsync("__EntryScene"); } public void LoadBrakingProblem() { SceneManager.LoadScene("__SceneManager_BrakingProblem"); SceneManager.UnloadSceneAsync("__EntryScene"); } }
27.8
64
0.729017
[ "MIT" ]
TheAlexDev23/Car-Physics-Simulation
Car-Physics-Simulation/Assets/src/Scene Managment/EntryMenuSceneLoader.cs
417
C#
//===================================================================================== // Developed by Kallebe Lins (kallebe.santos@outlook.com) // Teacher, Architect, Consultant and Project Leader // Virtual Card: https://www.linkedin.com/in/kallebelins //===================================================================================== // Reproduction or sharing is free! Contribute to a better world! //===================================================================================== using NLog; using NLog.Config; using NLog.LayoutRenderers; using System.Globalization; using System.Text; namespace Mvp24Hours.Infrastructure.Logging.Renderer { /// <summary> /// /// </summary> [LayoutRenderer("utc_date")] public class UtcDateRenderer : LayoutRenderer { public UtcDateRenderer() { Format = "G"; Culture = CultureInfo.InvariantCulture; } /// <summary> /// /// </summary> protected int GetEstimatedBufferSize(LogEventInfo ev) { return 10; } /// <summary> /// /// </summary> public CultureInfo Culture { get; set; } /// <summary> /// /// </summary> [DefaultParameter] public string Format { get; set; } /// <summary> /// /// </summary> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(logEvent.TimeStamp.ToUniversalTime().ToString(Format, Culture)); } } }
27.929825
91
0.48304
[ "MIT" ]
rafaelcorazzi/mvp24hours-netcore
src/Mvp24Hours.Infrastructure/Logging/Renderer/UtcDateRenderer.cs
1,592
C#
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; namespace LoggerMessage.Shared.Services { public class LocalEventGroupService : IEventGroupService { public bool Connected => true; //public Microsoft.CodeAnalysis.Solution Solution { get; set; } private List<EventGroupLocal> _groups; private readonly string filePath; private JsonSerializerSettings _settings = new JsonSerializerSettings() {Formatting = Formatting.Indented}; public LocalEventGroupService(string configFolder) { filePath = Path.Combine(configFolder, Constants.GroupsFile); if (File.Exists(filePath)) _groups = JsonConvert.DeserializeObject<List<EventGroupLocal>>(File.ReadAllText(filePath), _settings); else _groups = new List<EventGroupLocal>(); } public Task<bool> IsAbbrExistAsync(string abbr) { return Task.FromResult(_groups.Any(e => e.Abbreviation == abbr)); } public Task<IEnumerable<IEventGroup>> GetEventGroupsAsync() { return Task.FromResult(_groups .OrderBy(e => e.Abbreviation) .Select(e => new EventGroupViewObject() { Abbreviation = e.Abbreviation, Description = e.Description }).Cast<IEventGroup>()); } public async Task<bool> TryAddEventGroupAsync(EventGroupViewObject newEventGroupViewObject) { if (await IsAbbrExistAsync(newEventGroupViewObject.Abbreviation)) return true; _groups.Add(new EventGroupLocal() { Abbreviation = newEventGroupViewObject.Abbreviation, Description = newEventGroupViewObject.Description }); File.WriteAllText(filePath, JsonConvert.SerializeObject(_groups, _settings)); return true; } public Task<IEventGroup> GetEventGroupAsync(string abbr) { var group = _groups.FirstOrDefault(g => g.Abbreviation == abbr); var groupLocal = new EventGroupLocal() { Abbreviation = group.Abbreviation, Description = group.Description }; return Task.FromResult(groupLocal as IEventGroup); } } }
33.486486
118
0.60573
[ "MIT" ]
klebanandrey/LoggerMessage.Tools
src/LoggerMessage.Shared/Services/LocalEventGroupService.cs
2,480
C#
// ---------------------------------------------------------------- // Copyright ©2022 ZhaiFanhua All Rights Reserved. // FileName:IBlogTagService // Guid:e8c119bb-b7ae-29f6-0db5-da415d8eaefb // Author:zhaifanhua // Email:me@zhaifanhua.com // CreateTime:2021-12-28 下午 11:16:38 // ---------------------------------------------------------------- using ZhaiFanhuaBlog.IServices.Bases; using ZhaiFanhuaBlog.Models.Blogs; namespace ZhaiFanhuaBlog.IService.Blogs; public interface IBlogTagService : IBaseService<BlogTag> { }
30.764706
68
0.590822
[ "MIT" ]
zhaifanhua/zhaifanhuaBlog
backend/ZhaiFanhuaBlog.IServices/Blogs/IBlogTagService.cs
530
C#
using System; using System.IO; namespace NerdyMishka.Search.IO { public abstract class FileStorageProvider : IFileProvider { /// <summary> /// Lists all the files in storage. /// </summary> /// <returns>An array of file names.</returns> public abstract string[] ListAll(); /// <summary> /// Determines if a file exists. /// </summary> /// <param name="name">The name of the file.</param> /// <returns><c>True</c> if the file exists; otherwise, <c>False</c></returns> public abstract bool Exists(string name); public abstract long GetLastModifiedDate(string name); /// <summary> /// Deletes an existing file in the directory /// </summary> /// <param name="file">the file delete.</param> public abstract void Delete(string file); /// <summary> /// Moves an existing file withing the directory. If a file /// file already exists, it is replace if overwrite is true. /// </summary> /// <param name="source">The file to move.</param> /// <param name="destination">The destinatio for the file.</param> public abstract void Move(string source, string destination, bool overwrite = true); /// <summary> /// Gets the length of a file. /// </summary> /// <param name="name">The name of the file</param> /// <returns>The file length in bytes.</returns> public abstract long GetFileLength(string name); /// <summary> /// Creates a new empty file in the directory and returns /// a stream for writing data to the file. /// </summary> /// <param name="name">The name of the new file to create</param> /// <returns>The <see cref="System.IO.Stream" /></returns> public abstract System.IO.Stream OpenWrite(string name); /// <summary> /// Creates a stream for reading an existing file. /// </summary> /// <param name="name">The name of the file to open.</param> /// <returns>The <see cref="System.IO.Stream" /></returns> public abstract System.IO.Stream OpenRead(string name); /// <summary> /// Closes and the disposes of the blob storage resources. /// </summary> public abstract void Dispose(); } }
37.3125
92
0.582915
[ "Apache-2.0" ]
nerdymishka/gainz
dotnet/src/Api/Search.Core/IO/FileStorageProvider.cs
2,388
C#
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("Xlent.Lever.CapabilityTemplate.Bll")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Xlent.Lever.CapabilityTemplate.Bll")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("79be6a98-3047-4a03-96d5-2754f025fefd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.805556
84
0.748031
[ "MIT" ]
xlent-fulcrum/fulcrum-examples
Xlent.Lever.CapabilityTemplate/src/Bll/Properties/AssemblyInfo.cs
1,400
C#
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; 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. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ namespace Apache.Ignite.Core.Tests.Services { using Apache.Ignite.Core.Services; /// <summary> /// Services async tests. /// </summary> public class ServicesTestAsync : ServicesTest { /** <inheritdoc /> */ protected override IServices Services { get { return new ServicesAsyncWrapper(Grid1.GetServices()); } } } }
44.42
101
0.725799
[ "Apache-2.0", "CC0-1.0" ]
DirectXceriD/gridgain
modules/platforms/dotnet/Apache.Ignite.Core.Tests/Services/ServicesTestAsync.cs
2,233
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Humanizer; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore; using osu.Framework; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Threading; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.IPC; using osu.Game.Overlays.Notifications; using osu.Game.Utils; using SharpCompress.Archives.Zip; using SharpCompress.Common; using FileInfo = osu.Game.IO.FileInfo; namespace osu.Game.Database { /// <summary> /// Encapsulates a model store class to give it import functionality. /// Adds cross-functionality with <see cref="FileStore"/> to give access to the central file store for the provided model. /// </summary> /// <typeparam name="TModel">The model type.</typeparam> /// <typeparam name="TFileModel">The associated file join type.</typeparam> public abstract class ArchiveModelManager<TModel, TFileModel> : ICanAcceptFiles, IModelManager<TModel> where TModel : class, IHasFiles<TFileModel>, IHasPrimaryKey, ISoftDelete where TFileModel : class, INamedFileInfo, new() { private const int import_queue_request_concurrency = 1; /// <summary> /// A singleton scheduler shared by all <see cref="ArchiveModelManager{TModel,TFileModel}"/>. /// </summary> /// <remarks> /// This scheduler generally performs IO and CPU intensive work so concurrency is limited harshly. /// It is mainly being used as a queue mechanism for large imports. /// </remarks> private static readonly ThreadedTaskScheduler import_scheduler = new ThreadedTaskScheduler(import_queue_request_concurrency, nameof(ArchiveModelManager<TModel, TFileModel>)); /// <summary> /// Set an endpoint for notifications to be posted to. /// </summary> public Action<Notification> PostNotification { protected get; set; } /// <summary> /// Fired when a new or updated <typeparamref name="TModel"/> becomes available in the database. /// This is not guaranteed to run on the update thread. /// </summary> public IBindable<WeakReference<TModel>> ItemUpdated => itemUpdated; private readonly Bindable<WeakReference<TModel>> itemUpdated = new Bindable<WeakReference<TModel>>(); /// <summary> /// Fired when a <typeparamref name="TModel"/> is removed from the database. /// This is not guaranteed to run on the update thread. /// </summary> public IBindable<WeakReference<TModel>> ItemRemoved => itemRemoved; private readonly Bindable<WeakReference<TModel>> itemRemoved = new Bindable<WeakReference<TModel>>(); public virtual string[] HandledExtensions => new[] { ".zip" }; public virtual bool SupportsImportFromStable => RuntimeInfo.IsDesktop; protected readonly FileStore Files; protected readonly IDatabaseContextFactory ContextFactory; protected readonly MutableDatabaseBackedStore<TModel> ModelStore; // ReSharper disable once NotAccessedField.Local (we should keep a reference to this so it is not finalised) private ArchiveImportIPCChannel ipc; private readonly Storage exportStorage; protected ArchiveModelManager(Storage storage, IDatabaseContextFactory contextFactory, MutableDatabaseBackedStoreWithFileIncludes<TModel, TFileModel> modelStore, IIpcHost importHost = null) { ContextFactory = contextFactory; ModelStore = modelStore; ModelStore.ItemUpdated += item => handleEvent(() => itemUpdated.Value = new WeakReference<TModel>(item)); ModelStore.ItemRemoved += item => handleEvent(() => itemRemoved.Value = new WeakReference<TModel>(item)); exportStorage = storage.GetStorageForDirectory("exports"); Files = new FileStore(contextFactory, storage); if (importHost != null) ipc = new ArchiveImportIPCChannel(importHost, this); ModelStore.Cleanup(); } /// <summary> /// Import one or more <typeparamref name="TModel"/> items from filesystem <paramref name="paths"/>. /// This will post notifications tracking progress. /// </summary> /// <param name="paths">One or more archive locations on disk.</param> public Task Import(params string[] paths) { var notification = new ProgressNotification { State = ProgressNotificationState.Active }; PostNotification?.Invoke(notification); return Import(notification, paths); } protected async Task<IEnumerable<TModel>> Import(ProgressNotification notification, params string[] paths) { notification.Progress = 0; notification.Text = $"{HumanisedModelName.Humanize(LetterCasing.Title)} import is initialising..."; int current = 0; var imported = new List<TModel>(); await Task.WhenAll(paths.Select(async path => { notification.CancellationToken.ThrowIfCancellationRequested(); try { var model = await Import(path, notification.CancellationToken); lock (imported) { if (model != null) imported.Add(model); current++; notification.Text = $"Imported {current} of {paths.Length} {HumanisedModelName}s"; notification.Progress = (float)current / paths.Length; } } catch (TaskCanceledException) { throw; } catch (Exception e) { Logger.Error(e, $@"Could not import ({Path.GetFileName(path)})", LoggingTarget.Database); } })); if (imported.Count == 0) { notification.Text = $"{HumanisedModelName.Humanize(LetterCasing.Title)} import failed!"; notification.State = ProgressNotificationState.Cancelled; } else { notification.CompletionText = imported.Count == 1 ? $"Imported {imported.First()}!" : $"Imported {imported.Count} {HumanisedModelName}s!"; if (imported.Count > 0 && PresentImport != null) { notification.CompletionText += " Click to view."; notification.CompletionClickAction = () => { PresentImport?.Invoke(imported); return true; }; } notification.State = ProgressNotificationState.Completed; } return imported; } /// <summary> /// Import one <typeparamref name="TModel"/> from the filesystem and delete the file on success. /// </summary> /// <param name="path">The archive location on disk.</param> /// <param name="cancellationToken">An optional cancellation token.</param> /// <returns>The imported model, if successful.</returns> public async Task<TModel> Import(string path, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); TModel import; using (ArchiveReader reader = getReaderFrom(path)) import = await Import(reader, cancellationToken); // We may or may not want to delete the file depending on where it is stored. // e.g. reconstructing/repairing database with items from default storage. // Also, not always a single file, i.e. for LegacyFilesystemReader // TODO: Add a check to prevent files from storage to be deleted. try { if (import != null && File.Exists(path) && ShouldDeleteArchive(path)) File.Delete(path); } catch (Exception e) { LogForModel(import, $@"Could not delete original file after import ({Path.GetFileName(path)})", e); } return import; } /// <summary> /// Fired when the user requests to view the resulting import. /// </summary> public Action<IEnumerable<TModel>> PresentImport; /// <summary> /// Import an item from an <see cref="ArchiveReader"/>. /// </summary> /// <param name="archive">The archive to be imported.</param> /// <param name="cancellationToken">An optional cancellation token.</param> public Task<TModel> Import(ArchiveReader archive, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); TModel model = null; try { model = CreateModel(archive); if (model == null) return Task.FromResult<TModel>(null); } catch (TaskCanceledException) { throw; } catch (Exception e) { LogForModel(model, $"Model creation of {archive.Name} failed.", e); return null; } return Import(model, archive, cancellationToken); } /// <summary> /// Any file extensions which should be included in hash creation. /// Generally should include all file types which determine the file's uniqueness. /// Large files should be avoided if possible. /// </summary> protected abstract string[] HashableFileTypes { get; } internal static void LogForModel(TModel model, string message, Exception e = null) { string prefix = $"[{(model?.Hash ?? "?????").Substring(0, 5)}]"; if (e != null) Logger.Error(e, $"{prefix} {message}", LoggingTarget.Database); else Logger.Log($"{prefix} {message}", LoggingTarget.Database); } /// <summary> /// Create a SHA-2 hash from the provided archive based on file content of all files matching <see cref="HashableFileTypes"/>. /// </summary> /// <remarks> /// In the case of no matching files, a hash will be generated from the passed archive's <see cref="ArchiveReader.Name"/>. /// </remarks> private string computeHash(TModel item, ArchiveReader reader = null) { // for now, concatenate all .osu files in the set to create a unique hash. MemoryStream hashable = new MemoryStream(); foreach (TFileModel file in item.Files.Where(f => HashableFileTypes.Any(f.Filename.EndsWith)).OrderBy(f => f.Filename)) { using (Stream s = Files.Store.GetStream(file.FileInfo.StoragePath)) s.CopyTo(hashable); } if (hashable.Length > 0) return hashable.ComputeSHA2Hash(); if (reader != null) return reader.Name.ComputeSHA2Hash(); return item.Hash; } /// <summary> /// Import an item from a <typeparamref name="TModel"/>. /// </summary> /// <param name="item">The model to be imported.</param> /// <param name="archive">An optional archive to use for model population.</param> /// <param name="cancellationToken">An optional cancellation token.</param> public async Task<TModel> Import(TModel item, ArchiveReader archive = null, CancellationToken cancellationToken = default) => await Task.Factory.StartNew(async () => { cancellationToken.ThrowIfCancellationRequested(); delayEvents(); void rollback() { if (!Delete(item)) { // We may have not yet added the model to the underlying table, but should still clean up files. LogForModel(item, "Dereferencing files for incomplete import."); Files.Dereference(item.Files.Select(f => f.FileInfo).ToArray()); } } try { LogForModel(item, "Beginning import..."); item.Files = archive != null ? createFileInfos(archive, Files) : new List<TFileModel>(); item.Hash = computeHash(item, archive); await Populate(item, archive, cancellationToken); using (var write = ContextFactory.GetForWrite()) // used to share a context for full import. keep in mind this will block all writes. { try { if (!write.IsTransactionLeader) throw new InvalidOperationException($"Ensure there is no parent transaction so errors can correctly be handled by {this}"); var existing = CheckForExisting(item); if (existing != null) { if (CanReuseExisting(existing, item)) { Undelete(existing); LogForModel(item, $"Found existing {HumanisedModelName} for {item} (ID {existing.ID}) – skipping import."); // existing item will be used; rollback new import and exit early. rollback(); flushEvents(true); return existing; } Delete(existing); ModelStore.PurgeDeletable(s => s.ID == existing.ID); } PreImport(item); // import to store ModelStore.Add(item); } catch (Exception e) { write.Errors.Add(e); throw; } } LogForModel(item, "Import successfully completed!"); } catch (Exception e) { if (!(e is TaskCanceledException)) LogForModel(item, "Database import or population failed and has been rolled back.", e); rollback(); flushEvents(false); throw; } flushEvents(true); return item; }, cancellationToken, TaskCreationOptions.HideScheduler, import_scheduler).Unwrap(); /// <summary> /// Exports an item to a legacy (.zip based) package. /// </summary> /// <param name="item">The item to export.</param> public void Export(TModel item) { var retrievedItem = ModelStore.ConsumableItems.FirstOrDefault(s => s.ID == item.ID); if (retrievedItem == null) throw new ArgumentException("Specified model could not be found", nameof(item)); using (var archive = ZipArchive.Create()) { foreach (var file in retrievedItem.Files) archive.AddEntry(file.Filename, Files.Storage.GetStream(file.FileInfo.StoragePath)); using (var outputStream = exportStorage.GetStream($"{getValidFilename(item.ToString())}{HandledExtensions.First()}", FileAccess.Write, FileMode.Create)) archive.SaveTo(outputStream); exportStorage.OpenInNativeExplorer(); } } /// <summary> /// Update an existing file, or create a new entry if not already part of the <paramref name="model"/>'s files. /// </summary> /// <param name="model">The item to operate on.</param> /// <param name="file">The file model to be updated or added.</param> /// <param name="contents">The new file contents.</param> public void UpdateFile(TModel model, TFileModel file, Stream contents) { using (var usage = ContextFactory.GetForWrite()) { // Dereference the existing file info, since the file model will be removed. if (file.FileInfo != null) { Files.Dereference(file.FileInfo); // Remove the file model. usage.Context.Set<TFileModel>().Remove(file); } // Add the new file info and containing file model. model.Files.Remove(file); model.Files.Add(new TFileModel { Filename = file.Filename, FileInfo = Files.Add(contents) }); Update(model); } } /// <summary> /// Perform an update of the specified item. /// TODO: Support file additions/removals. /// </summary> /// <param name="item">The item to update.</param> public void Update(TModel item) { using (ContextFactory.GetForWrite()) { item.Hash = computeHash(item); ModelStore.Update(item); } } /// <summary> /// Delete an item from the manager. /// Is a no-op for already deleted items. /// </summary> /// <param name="item">The item to delete.</param> /// <returns>false if no operation was performed</returns> public bool Delete(TModel item) { using (ContextFactory.GetForWrite()) { // re-fetch the model on the import context. var foundModel = queryModel().Include(s => s.Files).ThenInclude(f => f.FileInfo).FirstOrDefault(s => s.ID == item.ID); if (foundModel == null || foundModel.DeletePending) return false; if (ModelStore.Delete(foundModel)) Files.Dereference(foundModel.Files.Select(f => f.FileInfo).ToArray()); return true; } } /// <summary> /// Delete multiple items. /// This will post notifications tracking progress. /// </summary> public void Delete(List<TModel> items, bool silent = false) { if (items.Count == 0) return; var notification = new ProgressNotification { Progress = 0, Text = $"Preparing to delete all {HumanisedModelName}s...", CompletionText = $"Deleted all {HumanisedModelName}s!", State = ProgressNotificationState.Active, }; if (!silent) PostNotification?.Invoke(notification); int i = 0; foreach (var b in items) { if (notification.State == ProgressNotificationState.Cancelled) // user requested abort return; notification.Text = $"Deleting {HumanisedModelName}s ({++i} of {items.Count})"; Delete(b); notification.Progress = (float)i / items.Count; } notification.State = ProgressNotificationState.Completed; } /// <summary> /// Restore multiple items that were previously deleted. /// This will post notifications tracking progress. /// </summary> public void Undelete(List<TModel> items, bool silent = false) { if (!items.Any()) return; var notification = new ProgressNotification { CompletionText = "Restored all deleted items!", Progress = 0, State = ProgressNotificationState.Active, }; if (!silent) PostNotification?.Invoke(notification); int i = 0; foreach (var item in items) { if (notification.State == ProgressNotificationState.Cancelled) // user requested abort return; notification.Text = $"Restoring ({++i} of {items.Count})"; Undelete(item); notification.Progress = (float)i / items.Count; } notification.State = ProgressNotificationState.Completed; } /// <summary> /// Restore an item that was previously deleted. Is a no-op if the item is not in a deleted state, or has its protected flag set. /// </summary> /// <param name="item">The item to restore</param> public void Undelete(TModel item) { using (var usage = ContextFactory.GetForWrite()) { usage.Context.ChangeTracker.AutoDetectChangesEnabled = false; if (!ModelStore.Undelete(item)) return; Files.Reference(item.Files.Select(f => f.FileInfo).ToArray()); usage.Context.ChangeTracker.AutoDetectChangesEnabled = true; } } /// <summary> /// Create all required <see cref="FileInfo"/>s for the provided archive, adding them to the global file store. /// </summary> private List<TFileModel> createFileInfos(ArchiveReader reader, FileStore files) { var fileInfos = new List<TFileModel>(); string prefix = reader.Filenames.GetCommonPrefix(); if (!(prefix.EndsWith("/") || prefix.EndsWith("\\"))) prefix = string.Empty; // import files to manager foreach (string file in reader.Filenames) { using (Stream s = reader.GetStream(file)) { fileInfos.Add(new TFileModel { Filename = file.Substring(prefix.Length).ToStandardisedPath(), FileInfo = files.Add(s) }); } } return fileInfos; } #region osu-stable import /// <summary> /// Set a storage with access to an osu-stable install for import purposes. /// </summary> public Func<Storage> GetStableStorage { private get; set; } /// <summary> /// Denotes whether an osu-stable installation is present to perform automated imports from. /// </summary> public bool StableInstallationAvailable => GetStableStorage?.Invoke() != null; /// <summary> /// The relative path from osu-stable's data directory to import items from. /// </summary> protected virtual string ImportFromStablePath => null; /// <summary> /// Select paths to import from stable. Default implementation iterates all directories in <see cref="ImportFromStablePath"/>. /// </summary> protected virtual IEnumerable<string> GetStableImportPaths(Storage stableStoage) => stableStoage.GetDirectories(ImportFromStablePath); /// <summary> /// Whether this specified path should be removed after successful import. /// </summary> /// <param name="path">The path for consideration. May be a file or a directory.</param> /// <returns>Whether to perform deletion.</returns> protected virtual bool ShouldDeleteArchive(string path) => false; /// <summary> /// This is a temporary method and will likely be replaced by a full-fledged (and more correctly placed) migration process in the future. /// </summary> public Task ImportFromStableAsync() { var stable = GetStableStorage?.Invoke(); if (stable == null) { Logger.Log("No osu!stable installation available!", LoggingTarget.Information, LogLevel.Error); return Task.CompletedTask; } if (!stable.ExistsDirectory(ImportFromStablePath)) { // This handles situations like when the user does not have a Skins folder Logger.Log($"No {ImportFromStablePath} folder available in osu!stable installation", LoggingTarget.Information, LogLevel.Error); return Task.CompletedTask; } return Task.Run(async () => await Import(GetStableImportPaths(GetStableStorage()).Select(f => stable.GetFullPath(f)).ToArray())); } #endregion /// <summary> /// Create a barebones model from the provided archive. /// Actual expensive population should be done in <see cref="Populate"/>; this should just prepare for duplicate checking. /// </summary> /// <param name="archive">The archive to create the model for.</param> /// <returns>A model populated with minimal information. Returning a null will abort importing silently.</returns> protected abstract TModel CreateModel(ArchiveReader archive); /// <summary> /// Populate the provided model completely from the given archive. /// After this method, the model should be in a state ready to commit to a store. /// </summary> /// <param name="model">The model to populate.</param> /// <param name="archive">The archive to use as a reference for population. May be null.</param> /// <param name="cancellationToken">An optional cancellation token.</param> protected virtual Task Populate(TModel model, [CanBeNull] ArchiveReader archive, CancellationToken cancellationToken = default) => Task.CompletedTask; /// <summary> /// Perform any final actions before the import to database executes. /// </summary> /// <param name="model">The model prepared for import.</param> protected virtual void PreImport(TModel model) { } /// <summary> /// Check whether an existing model already exists for a new import item. /// </summary> /// <param name="model">The new model proposed for import.</param> /// <returns>An existing model which matches the criteria to skip importing, else null.</returns> protected TModel CheckForExisting(TModel model) => model.Hash == null ? null : ModelStore.ConsumableItems.FirstOrDefault(b => b.Hash == model.Hash); /// <summary> /// After an existing <typeparamref name="TModel"/> is found during an import process, the default behaviour is to use/restore the existing /// item and skip the import. This method allows changing that behaviour. /// </summary> /// <param name="existing">The existing model.</param> /// <param name="import">The newly imported model.</param> /// <returns>Whether the existing model should be restored and used. Returning false will delete the existing and force a re-import.</returns> protected virtual bool CanReuseExisting(TModel existing, TModel import) => // for the best or worst, we copy and import files of a new import before checking whether // it is a duplicate. so to check if anything has changed, we can just compare all FileInfo IDs. getIDs(existing.Files).SequenceEqual(getIDs(import.Files)) && getFilenames(existing.Files).SequenceEqual(getFilenames(import.Files)); private IEnumerable<long> getIDs(List<TFileModel> files) { foreach (var f in files.OrderBy(f => f.Filename)) yield return f.FileInfo.ID; } private IEnumerable<string> getFilenames(List<TFileModel> files) { foreach (var f in files.OrderBy(f => f.Filename)) yield return f.Filename; } private DbSet<TModel> queryModel() => ContextFactory.Get().Set<TModel>(); protected virtual string HumanisedModelName => $"{typeof(TModel).Name.Replace("Info", "").ToLower()}"; /// <summary> /// Creates an <see cref="ArchiveReader"/> from a valid storage path. /// </summary> /// <param name="path">A file or folder path resolving the archive content.</param> /// <returns>A reader giving access to the archive's content.</returns> private ArchiveReader getReaderFrom(string path) { if (ZipUtils.IsZipArchive(path)) return new ZipArchiveReader(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read), Path.GetFileName(path)); if (Directory.Exists(path)) return new LegacyDirectoryArchiveReader(path); if (File.Exists(path)) return new LegacyFileArchiveReader(path); throw new InvalidFormatException($"{path} is not a valid archive"); } #region Event handling / delaying private readonly List<Action> queuedEvents = new List<Action>(); /// <summary> /// Allows delaying of outwards events until an operation is confirmed (at a database level). /// </summary> private bool delayingEvents; /// <summary> /// Begin delaying outwards events. /// </summary> private void delayEvents() => delayingEvents = true; /// <summary> /// Flush delayed events and disable delaying. /// </summary> /// <param name="perform">Whether the flushed events should be performed.</param> private void flushEvents(bool perform) { Action[] events; lock (queuedEvents) { events = queuedEvents.ToArray(); queuedEvents.Clear(); } if (perform) { foreach (var a in events) a.Invoke(); } delayingEvents = false; } private void handleEvent(Action a) { if (delayingEvents) { lock (queuedEvents) queuedEvents.Add(a); } else a.Invoke(); } #endregion private string getValidFilename(string filename) { foreach (char c in Path.GetInvalidFileNameChars()) filename = filename.Replace(c, '_'); return filename; } } }
40.931525
198
0.556548
[ "MIT" ]
byspeece/ArchOSU
osu.Game/Database/ArchiveModelManager.cs
30,910
C#
using System; namespace MemeTV.BusinessLogic { public class ConsoleLogger : ILogger { private readonly object mutex = new object(); public void Debug(string msg) { Write(msg, LogSeverity.Debug); } public void Error(string msg) { Write(msg, LogSeverity.Error); } public void Message(string msg) { Write(msg, LogSeverity.Message); } public void Warning(string msg) { Write(msg, LogSeverity.Warning); } private void Write(string msg, LogSeverity severity) { lock (mutex) { var color = ConsoleColor.Gray; switch (severity) { case LogSeverity.Debug: color = ConsoleColor.Cyan; break; case LogSeverity.Message: color = ConsoleColor.White; break; case LogSeverity.Warning: color = ConsoleColor.Yellow; break; case LogSeverity.Error: color = ConsoleColor.Red; break; } var oldForeground = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Gray; Console.Write("["); Console.ForegroundColor = ConsoleColor.White; Console.Write($"{DateTime.Now.ToShortTimeString()}"); Console.ForegroundColor = ConsoleColor.Gray; Console.Write("] "); Console.ForegroundColor = color; Console.WriteLine("(" + severity + "): " + msg); Console.ForegroundColor = oldForeground; } } } }
30.079365
69
0.470712
[ "MIT" ]
zerratar/meme-tv
src/MemeTV.BusinessLogic/ConsoleLogger.cs
1,897
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WotTools { public static class WotPkg { public static bool TryExtractFile(string packagePath, string filePath, Action<Stream> readFile, bool verbose = true, bool caseSensitive = false) { if(!File.Exists(packagePath)) { return verbose ? throw new FileNotFoundException("Package file not found") : false; } if(string.IsNullOrWhiteSpace(filePath)) { return verbose ? throw new ArgumentNullException("File path is requried") : false; } using (var zipFile = System.IO.Compression.ZipFile.Open(packagePath, System.IO.Compression.ZipArchiveMode.Read)) { var fileEntry = caseSensitive ? zipFile.Entries.FirstOrDefault(i => i.FullName == filePath) : zipFile.Entries.FirstOrDefault(i => string.Equals(i.FullName, filePath, StringComparison.InvariantCultureIgnoreCase)) ; if(fileEntry == null) { return verbose ? throw new ArgumentException("Invalid file path") : false; } var stream = fileEntry.Open(); readFile(stream); } return true; } public static bool TryExtractDirectory(string packagePath, string directoryPath, Action<Stream, System.IO.Compression.ZipArchiveEntry> readFile, bool verbose = true, bool caseSensitive = false) { if (!File.Exists(packagePath)) { return verbose ? throw new FileNotFoundException("Package file not found") : false; } if (string.IsNullOrWhiteSpace(directoryPath)) { return verbose ? throw new ArgumentNullException("Directory path is requried") : false; } using (var zipFile = System.IO.Compression.ZipFile.Open(packagePath, System.IO.Compression.ZipArchiveMode.Read)) { var fileEntries = caseSensitive ? zipFile.Entries.Where(i => i.FullName.StartsWith(directoryPath)) : zipFile.Entries.Where(i => i.FullName.StartsWith(directoryPath, StringComparison.InvariantCultureIgnoreCase)) ; if (!fileEntries.Any()) { return verbose ? throw new ArgumentException("Invalid directory path, or directory is empty") : false; } foreach (var fileEntry in fileEntries) { var stream = fileEntry.Open(); readFile(stream, fileEntry); } } return true; } } }
36.45679
201
0.557738
[ "MIT" ]
PTwr/WotTools
WotTools/WotPkg.cs
2,955
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public class b19896 { public static int Main(string[] args) { int retVal = 200; try { try { throw new Exception(); } catch { Type.GetType("System.Foo", true); } } catch (System.TypeLoadException) { Console.WriteLine("TEST PASSED"); retVal = 100; } return retVal; } } //EOF
19.151515
71
0.481013
[ "MIT" ]
belav/runtime
src/tests/baseservices/exceptions/regressions/v1.0/19896.cs
632
C#
using System.ComponentModel; using System.Threading; using System.Threading.Tasks; namespace BuildIt { /// <summary> /// Provides a wrapper that handles when the Data property changes on an entity /// Instead of propagating a change to the entire entity, the wrapper does a deep /// update, only raising PropertyChanged for properties that have changed. /// </summary> /// <typeparam name="TData">The type of data property to wrap.</typeparam> public class ImmutableDataWrapper<TData> : NotifyBase where TData : class { /// <summary> /// Tracks whether ChangeData is running. /// </summary> private int isRunningChangeData; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDataWrapper{TData}"/> class. /// Constru. /// </summary> /// <param name="entityWithData">The entity that has a Data property to wrap.</param> /// <param name="uiContext">The UI context.</param> public ImmutableDataWrapper(IHasImmutableData<TData> entityWithData, IUIExecutionContext uiContext) { ExecutionContext = uiContext; ChangeData(entityWithData.Data); entityWithData.PropertyChanged += DataPropertyChanged; } /// <summary> /// Gets or sets the current data. /// </summary> public TData Data { get; set; } /// <summary> /// Gets or sets a value indicating whether indicates whether ChangeData needs to be run again. /// </summary> private bool RunChangeData { get; set; } /// <summary> /// Gets or sets the next data to be used in ChangeData. /// </summary> private TData NextData { get; set; } private IUIExecutionContext ExecutionContext { get; } /// <summary> /// Handles when the data property on the entity changes. /// </summary> /// <param name="sender">The entity.</param> /// <param name="e">The property that has changed.</param> private async void DataPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(Data)) { // This does check to make sure on UI thread and runs on ui thread if required #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously await ExecutionContext.RunAsync(async () => { var data = (sender as IHasImmutableData<TData>)?.Data; ChangeData(data); }); #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously } } /// <summary> /// Updates Data with the new data by doing a deep update on all properties. /// </summary> /// <param name="nextData">The data to update to.</param> private async void ChangeData(TData nextData) { RunChangeData = true; NextData = nextData; if (Interlocked.CompareExchange(ref isRunningChangeData, 0, 1) == 1) { return; } RunChangeData = false; try { var oldData = Data; var newData = NextData; if (oldData == null) { if (newData != null && oldData != newData) { // There was no old data, so simply set the new data to be the current Data // and raise PropertyChanged Data = newData; OnPropertyChanged(nameof(Data)); } // Nothing more to do, so just return; return; } if (newData == null) { Data = newData; OnPropertyChanged(nameof(Data)); return; } UpdateData(oldData, newData); } finally { Interlocked.Exchange(ref isRunningChangeData, 0); } await Task.Yield(); if (RunChangeData) { ChangeData(NextData); } } private void UpdateData(object oldData, object newData) { var typeHelper = TypeHelper.RetrieveHelperForType(oldData.GetType()); typeHelper.DeepUpdater(oldData, newData); } } }
35.523077
107
0.538978
[ "MIT" ]
builttoroam/BuildIt
src/BuildIt.General/BuildIt.General/ImmutableDataWrapper.cs
4,620
C#
// Animancer // https://kybernetik.com.au/animancer // Copyright 2021 Kybernetik // #if UNITY_EDITOR using System; using UnityEditor; using UnityEngine; namespace Animancer.Editor { partial class AnimancerToolsWindow { /// <summary>[Editor-Only] [Pro-Only] A base <see cref="Panel"/> for modifying <see cref="AnimationClip"/>s.</summary> /// <remarks> /// Documentation: <see href="https://kybernetik.com.au/animancer/docs/manual/tools">Animancer Tools</see> /// </remarks> /// https://kybernetik.com.au/animancer/api/Animancer.Editor/AnimationModifierPanel /// [Serializable] public abstract class AnimationModifierPanel : Panel { /************************************************************************************************************************/ [SerializeField] private AnimationClip _Animation; /// <summary>The currently selected <see cref="AnimationClip"/> asset.</summary> public AnimationClip Animation => _Animation; /************************************************************************************************************************/ /// <inheritdoc/> public override void OnEnable(int index) { base.OnEnable(index); OnAnimationChanged(); } /************************************************************************************************************************/ /// <inheritdoc/> public override void OnSelectionChanged() { if (Selection.activeObject is AnimationClip animation) { _Animation = animation; OnAnimationChanged(); } } /************************************************************************************************************************/ /// <summary>Called whenever the selected <see cref="Animation"/> changes.</summary> protected virtual void OnAnimationChanged() { } /************************************************************************************************************************/ /// <inheritdoc/> public override void DoBodyGUI() { BeginChangeCheck(); var animation = (AnimationClip)EditorGUILayout.ObjectField("Animation", _Animation, typeof(AnimationClip), false); if (EndChangeCheck(ref _Animation, animation)) OnAnimationChanged(); } /************************************************************************************************************************/ /// <summary>Calls <see cref="Panel.SaveModifiedAsset"/> on the animation.</summary> protected bool SaveAs() { AnimancerGUI.Deselect(); if (SaveModifiedAsset( "Save Modified Animation", "Where would you like to save the new animation?", _Animation, Modify)) { _Animation = null; OnAnimationChanged(); return true; } else return false; } /************************************************************************************************************************/ /// <summary>Override this to apply the desired modifications to the `animation` before it is saved.</summary> protected virtual void Modify(AnimationClip animation) { } /************************************************************************************************************************/ } } } #endif
39.272727
134
0.390947
[ "MIT" ]
malering/ET
Unity/Assets/VCFrame/EngineCode/ThirdParty/Animancer/Internal/Editor/Animancer Tools/AnimancerToolsWindow.AnimationModifierPanel.cs
3,888
C#
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Shapes; using Avalonia.Markup.Xaml; namespace Frontend.Views { //https://github.com/FrankenApps/Avalonia-CustomTitleBarTemplate public class WindowControlsView : UserControl { private Window? window; private Button? minimizeButton; private Button? maximizeButton; private Button? closeButton; private Path? maximizeIcon; private ToolTip? maximizeToolTip; public WindowControlsView() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } protected override void OnInitialized() { base.OnInitialized(); minimizeButton = this.FindControl<Button>("MinimizeButton"); maximizeButton = this.FindControl<Button>("MaximizeButton"); closeButton = this.FindControl<Button>("CloseButton"); maximizeIcon = this.FindControl<Path>("MaximizeIcon"); maximizeToolTip = this.FindControl<ToolTip>("MaximizeToolTip"); minimizeButton.Click += MinimizeWindow; maximizeButton.Click += MaximizeWindow; closeButton.Click += CloseWindow; window = (Window)this.VisualRoot; SubscribeToWindowState(); } private void CloseWindow(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { window!.Close(); } private void MaximizeWindow(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { if (window!.WindowState == WindowState.Normal) { window.WindowState = WindowState.Maximized; return; } window.WindowState = WindowState.Normal; } private void MinimizeWindow(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { window!.WindowState = WindowState.Minimized; } private void SubscribeToWindowState() { window! .GetObservable(Window.WindowStateProperty) .Subscribe(windowState => { if (windowState != WindowState.Maximized) { maximizeIcon!.Data = Avalonia.Media.Geometry.Parse( "M2048 2048v-2048h-2048v2048h2048zM1843 1843h-1638v-1638h1638v1638z"); window!.Padding = new Thickness(0, 0, 0, 0); maximizeToolTip!.Content = "Maximize"; } if (windowState == WindowState.Maximized) { maximizeIcon!.Data = Avalonia.Media.Geometry.Parse( "M2048 1638h-410v410h-1638v-1638h410v-410h1638v1638zm-614-1024h-1229v1229h1229v-1229zm409-409h-1229v205h1024v1024h205v-1229z"); window!.Padding = new Thickness(7, 7, 7, 7); maximizeToolTip!.Content = "Restore Down"; } }); } } }
30.703704
134
0.726578
[ "MIT" ]
p-barski/TodoListApp
Frontend/Views/WindowControlsView.axaml.cs
2,487
C#