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
//----------------------------------------------------------------------- // <auto-generated /> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks; using FlubuCore.Tasks.Process; namespace FlubuCore.Tasks.Docker.Container { public partial class DockerContainerExecTask : ExternalProcessTaskBase<int, DockerContainerExecTask> { private string _container; private string _command; private string[] _arg; public DockerContainerExecTask(string container, string command, params string[] arg) { ExecutablePath = "docker"; WithArguments("container exec"); _container = container; _command = command; _arg = arg; } protected override string Description { get; set; } /// <summary> /// Detached mode: run command in the background /// </summary> public DockerContainerExecTask Detach() { WithArguments("detach"); return this; } /// <summary> /// Override the key sequence for detaching a container /// </summary> public DockerContainerExecTask DetachKeys(string detachKeys) { WithArgumentsValueRequired("detach-keys", detachKeys.ToString()); return this; } /// <summary> /// Set environment variables /// </summary> public DockerContainerExecTask Env(string env) { WithArgumentsValueRequired("env", env.ToString()); return this; } /// <summary> /// Keep STDIN open even if not attached /// </summary> public DockerContainerExecTask Interactive() { WithArguments("interactive"); return this; } /// <summary> /// Give extended privileges to the command /// </summary> public DockerContainerExecTask Privileged() { WithArguments("privileged"); return this; } /// <summary> /// Allocate a pseudo-TTY /// </summary> public DockerContainerExecTask Tty() { WithArguments("tty"); return this; } /// <summary> /// Username or UID (format: <name|uid>[:<group|gid>]) /// </summary> public DockerContainerExecTask User(string user) { WithArgumentsValueRequired("user", user.ToString()); return this; } /// <summary> /// Working directory inside the container /// </summary> public DockerContainerExecTask Workdir(string workdir) { WithArgumentsValueRequired("workdir", workdir.ToString()); return this; } protected override int DoExecute(ITaskContextInternal context) { WithArguments(_container); WithArguments(_command); WithArguments(_arg); return base.DoExecute(context); } } }
27.286957
105
0.545252
[ "BSD-2-Clause" ]
0xflotus/FlubuCore
FlubuCore/Tasks/Docker/Container/DockerContainerExecTask.cs
3,138
C#
using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using BlGrid.Api.Infrastructure.QueryHelpers.FilterHelpers; namespace BlGrid.Api.Infrastructure.QueryHelpers.FilterTypes { internal interface IBaseFilter<TEntity> { FilterPredicate GetPredicateExpression( IQueryable<TEntity> query, AdvancedFilterModel filter, ParameterExpression accessExpression ); Expression GetSingleFilterPredicateExpression( AdvancedFilterModel filter, ParameterExpression accessExpression ); } }
27.636364
60
0.717105
[ "MIT" ]
amuste/BlGridExamples
samples/BlGrid.Api/Infrastructure/QueryHelpers/FilterTypes/BaseFilter.cs
610
C#
//***************************************************************************** //* Code Factory SDK //* Copyright (c) 2020 CodeFactory, LLC //***************************************************************************** using System.Collections.Generic; namespace CodeFactory.DotNet { /// <summary> /// Definition that determines if the .net model implements generics. /// </summary> public interface IDotNetGeneric { /// <summary> /// Flag the determines if this item supports generics /// </summary> bool IsGeneric { get; } /// <summary> /// List of the generic parameters assigned. /// </summary> IReadOnlyList<IDotNetGenericParameter> GenericParameters { get; } /// <summary> /// Flag that determines if the generics implementation has strong types passed in to the generics implementation. /// </summary> bool HasStrongTypesInGenerics { get; } /// <summary> /// Enumeration of the strong types that are implemented for each generic parameter. This will be an empty list when there is no generic types implemented. /// </summary> IReadOnlyList<IDotNetType> GenericTypes { get; } } }
34.135135
167
0.545527
[ "MIT" ]
CodeFactoryLLC/CodeFactory
src/CodeFactoryVisualStudio/CodeFactory.DotNet/IDotNetGeneric.cs
1,265
C#
using System; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Test.MonkeyCache.UWP { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> private void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
35.544444
95
0.674273
[ "MIT" ]
DamianSuess/Test.XamMonkeyCache
Test.MonkeyCache/Test.MonkeyCache.UWP/App.xaml.cs
3,201
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CiscoCLIParsers.Model { public class CiscoInterfaceId { public EInterfaceType InterfaceType { get; set; } public CiscoInterfaceNumber InterfaceNumber { get; set; } public override string ToString() { return InterfaceType.ToString() + InterfaceNumber.ToString(); } } }
23.05
73
0.683297
[ "MIT" ]
darrenstarr/CiscoCLIParsers
CiscoCLIParsers/Model/CiscoInterfaceId.cs
463
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using AccessibilityInsights.CommonUxComponents.Controls; using Axe.Windows.Desktop.UIAutomation.EventHandlers; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Input; namespace AccessibilityInsights.SharedUx.Controls { /// <summary> /// Interaction logic for EventDetailControl.xaml /// </summary> public partial class EventDetailControl : UserControl { protected override AutomationPeer OnCreateAutomationPeer() { return new CustomControlOverridingAutomationPeer(this, "pane"); } public EventDetailControl() { InitializeComponent(); } public void SetEventMessage(EventMessage msg) { if (msg != null && msg.Properties != null) { dgEvents.ItemsSource = msg.Properties; } else { dgEvents.ItemsSource = null; } } public void Clear() { dgEvents.ItemsSource = null; } /// <summary> /// Fix datagrid keyboard nav behavior /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgEvents_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { var dg = sender as DataGrid; if (dg.Items != null && !dg.Items.IsEmpty && !(e.OldFocus is DataGridCell)) { if (dg.SelectedIndex == -1) { dg.SelectedIndex = 0; dg.CurrentCell = new DataGridCellInfo(dg.Items[0], dg.Columns[0]); } else { dg.CurrentCell = new DataGridCellInfo(dg.Items[dg.SelectedIndex], dg.Columns[0]); } } } } }
31.746269
102
0.535496
[ "MIT" ]
RobGallo/accessibility-insights-windows
src/AccessibilityInsights.SharedUx/Controls/EventDetailControl.xaml.cs
2,061
C#
// Copyright © Amer Koleci and Contributors. // Licensed under the MIT License (MIT). See LICENSE in the repository root for more information. using Vortice.DXGI; namespace Vortice.Direct3D11; public partial class ID3D11VideoDevice { public Guid CheckCryptoKeyExchange(Guid cryptoType, Guid? decoderProfile, int index) { CheckCryptoKeyExchange(cryptoType, decoderProfile, index, out Guid keyExchangeType).CheckError(); return keyExchangeType; } public bool CheckVideoDecoderFormat(Guid decoderProfile, Format format) { CheckVideoDecoderFormat(decoderProfile, format, out RawBool supported).CheckError(); return supported; } public ID3D11AuthenticatedChannel CreateAuthenticatedChannel(AuthenticatedChannelType channelType) { CreateAuthenticatedChannel(channelType, out ID3D11AuthenticatedChannel authenticatedChannel).CheckError(); return authenticatedChannel; } public ID3D11CryptoSession CreateCryptoSession(Guid cryptoType, Guid? decoderProfile, Guid keyExchangeType) { CreateCryptoSession(cryptoType, decoderProfile, keyExchangeType, out ID3D11CryptoSession cryptoSession).CheckError(); return cryptoSession; } public ID3D11VideoDecoder CreateVideoDecoder(VideoDecoderDescription description, VideoDecoderConfig config) { CreateVideoDecoder(description, config, out ID3D11VideoDecoder decoder).CheckError(); return decoder; } public ID3D11VideoDecoderOutputView CreateVideoDecoderOutputView(ID3D11Resource resource, VideoDecoderOutputViewDescription description) { CreateVideoDecoderOutputView(resource, description, out ID3D11VideoDecoderOutputView view).CheckError(); return view; } public ID3D11VideoProcessor CreateVideoProcessor(ID3D11VideoProcessorEnumerator enumerator, int rateConversionIndex) { CreateVideoProcessor(enumerator, rateConversionIndex, out ID3D11VideoProcessor videoProcessor).CheckError(); return videoProcessor; } public ID3D11VideoProcessorEnumerator CreateVideoProcessorEnumerator(VideoProcessorContentDescription description) { CreateVideoProcessorEnumerator(ref description, out ID3D11VideoProcessorEnumerator enumerator).CheckError(); return enumerator; } public Result CreateVideoProcessorEnumerator(VideoProcessorContentDescription description, out ID3D11VideoProcessorEnumerator enumerator) { return CreateVideoProcessorEnumerator(ref description, out enumerator); } public T CreateVideoProcessorEnumerator<T>(VideoProcessorContentDescription description) where T : ID3D11VideoProcessorEnumerator { using ID3D11VideoProcessorEnumerator enumerator = CreateVideoProcessorEnumerator(description); return enumerator.QueryInterface<T>(); } public ID3D11VideoProcessorInputView CreateVideoProcessorInputView(ID3D11Resource resource, ID3D11VideoProcessorEnumerator enumerator, VideoProcessorInputViewDescription description) { CreateVideoProcessorInputView(resource, enumerator, description, out ID3D11VideoProcessorInputView view).CheckError(); return view; } public ID3D11VideoProcessorOutputView CreateVideoProcessorOutputView(ID3D11Resource resource, ID3D11VideoProcessorEnumerator enumerator, VideoProcessorOutputViewDescription description) { CreateVideoProcessorOutputView(resource, enumerator, description, out ID3D11VideoProcessorOutputView view).CheckError(); return view; } public VideoContentProtectionCaps GetContentProtectionCaps(Guid? cryptoType, Guid? decoderProfile) { GetContentProtectionCaps(cryptoType, decoderProfile, out VideoContentProtectionCaps caps).CheckError(); return caps; } public VideoDecoderConfig GetVideoDecoderConfig(VideoDecoderDescription description, int index) { GetVideoDecoderConfig(ref description, index, out VideoDecoderConfig config).CheckError(); return config; } public Result GetVideoDecoderConfig(VideoDecoderDescription description, int index, out VideoDecoderConfig config) { return GetVideoDecoderConfig(ref description, index, out config); } public int GetVideoDecoderConfigCount(VideoDecoderDescription description) { GetVideoDecoderConfigCount(ref description, out int count).CheckError(); return count; } public Result GetVideoDecoderConfigCount(VideoDecoderDescription description, out int count) { return GetVideoDecoderConfigCount(ref description, out count); } public Guid GetVideoDecoderProfile(int index) { GetVideoDecoderProfile(index, out Guid decoderProfile).CheckError(); return decoderProfile; } }
41.704348
189
0.776689
[ "MIT" ]
Terricide/Vortice.Windows
src/Vortice.Direct3D11/ID3D11VideoDevice.cs
4,799
C#
using System; using System.Management.Automation; using Microsoft.SharePoint.Client; using PnP.PowerShell.Commands.Base.PipeBinds; using System.Collections; namespace PnP.PowerShell.Commands.Fields { [Cmdlet(VerbsCommon.Set, "PnPField")] public class SetField : PnPWebCmdlet { [Parameter(Mandatory = false, ValueFromPipeline = true)] public ListPipeBind List; [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] public FieldPipeBind Identity = new FieldPipeBind(); [Parameter(Mandatory = true)] public Hashtable Values; [Parameter(Mandatory = false)] public SwitchParameter UpdateExistingLists; protected override void ExecuteCmdlet() { const string allowDeletionPropertyKey = "AllowDeletion"; Field field = null; if (List != null) { var list = List.GetList(CurrentWeb); if (list == null) { throw new ArgumentException("Unable to retrieve the list specified using the List parameter", "List"); } if (Identity.Id != Guid.Empty) { field = list.Fields.GetById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Name)) { field = list.Fields.GetByInternalNameOrTitle(Identity.Name); } if (field == null) { throw new ArgumentException("Unable to retrieve field with id, name or the field instance provided through Identity on the specified List", "Identity"); } } else { if (Identity.Id != Guid.Empty) { field = ClientContext.Web.Fields.GetById(Identity.Id); } else if (!string.IsNullOrEmpty(Identity.Name)) { field = ClientContext.Web.Fields.GetByInternalNameOrTitle(Identity.Name); } else if (Identity.Field != null) { field = Identity.Field; } if (field == null) { throw new ArgumentException("Unable to retrieve field with id, name or the field instance provided through Identity on the current web", "Identity"); } } if (Values.ContainsKey(allowDeletionPropertyKey)) { ClientContext.Load(field, f => f.SchemaXmlWithResourceTokens); } else { ClientContext.Load(field); } ClientContext.ExecuteQueryRetry(); // Get a reference to the type-specific object to allow setting type-specific properties, i.e. LookupList and LookupField for Microsoft.SharePoint.Client.FieldLookup var typeSpecificField = field.TypedObject; foreach (string key in Values.Keys) { var value = Values[key]; var property = typeSpecificField.GetType().GetProperty(key); bool isAllowDeletionProperty = string.Equals(key, allowDeletionPropertyKey, StringComparison.Ordinal); if (property == null && !isAllowDeletionProperty) { WriteWarning($"No property '{key}' found on this field. Value will be ignored."); } else { try { if (isAllowDeletionProperty) { field.SetAllowDeletion(value as bool?); } else { property.SetValue(typeSpecificField, value); } } catch (Exception e) { WriteWarning($"Setting property '{key}' to '{value}' failed with exception '{e.Message}'. Value will be ignored."); } } } field.UpdateAndPushChanges(UpdateExistingLists); ClientContext.ExecuteQueryRetry(); } } }
36.316667
177
0.50849
[ "MIT" ]
AndersRask/powershell
src/Commands/Fields/SetField.cs
4,360
C#
#region License, Terms and Author(s) // // Mannex - Extension methods for .NET // Copyright (c) 2009 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion #if ASPNET namespace Mannex.Web { #region Imports using System; using System.Web; #endregion /// <summary> /// Extension methods for <see cref="Uri"/>. /// </summary> static partial class UriExtensions { /// <summary> /// Randomizes the URL by adding a query string parameter /// named <c>__rnd</c> and whose value is a newly generated GUID. /// </summary> public static Uri Randomize(this Uri url) { return Randomize(url, null); } /// <summary> /// Randomizes the URL by adding a query string parameter /// named <c>__rnd</c> and whose random value component /// is the string representation of <paramref name="value"/>. /// </summary> public static Uri Randomize(this Uri url, object value) { return Randomize(url, null, value ?? Guid.NewGuid().ToString("N")); } /// <summary> /// Randomizes the URL by adding a query string parameter /// named as <paramref name="key"/> and whose random value /// component is the string representation of /// <paramref name="value"/>. /// </summary> public static Uri Randomize(this Uri url, string key, object value) { if (url == null) throw new ArgumentNullException(nameof(url)); var builder = new UriBuilder(url); var qs = HttpUtility.ParseQueryString(builder.Query); qs[string.IsNullOrEmpty(key) ? "__rnd" : key] = value.ToString(); builder.Query = qs.ToString(); return builder.Uri; } } } #endif // ASPNET
29.939024
79
0.615886
[ "Apache-2.0" ]
atifaziz/Mannex
src/Web/Uri.cs
2,455
C#
using System; using Tesseract.Core.Math; namespace Tesseract.Core.Graphics.Accelerated { /// <summary> /// A texture layout determines how the content of a texture /// are internally stored and how it may be used in this layout. /// </summary> public enum TextureLayout { /// <summary> /// An undefined layout that is not usable for anything other than initialization. /// </summary> Undefined, /// <summary> /// A layout that may be used for any purpose, but may be less efficient than /// a specially-optimized format. /// </summary> General, /// <summary> /// A layout optimized for use as a color attachment. /// </summary> ColorAttachment, /// <summary> /// A layout optimized for use as a depth/stencil attachment. /// </summary> DepthStencilAttachment, /// <summary> /// A layout optimized for use as a depth/stencil attachment which will also be sampled. /// </summary> DepthStencilSampled, /// <summary> /// A layout optimized for use as a sampled image. /// </summary> ShaderSampled, /// <summary> /// A layout optimized as a source for plain image copies. /// </summary> TransferSrc, /// <summary> /// A layout optimized as a destination for plain image copies. /// </summary> TransferDst, /// <summary> /// A layout optimized as a source for presentation. /// </summary> PresentSrc } /// <summary> /// A bitmask of different aspects of a texture. Texture formats may have different /// aspects with distinct purposes such as color, depth, and stencil values. /// </summary> [Flags] public enum TextureAspect { Color = 0x01, Depth = 0x02, Stencil = 0x04 } /// <summary> /// Enumeration of texture filtering modes. /// </summary> public enum TextureFilter { /// <summary> /// The value of the nearest texel is selected. /// </summary> Nearest, /// <summary> /// The values of the nearest adjacent texels are selected and linearly blended based on the /// position of the sampling relative to the postion of the texels. /// </summary> Linear } /// <summary> /// Enumeration of texture dimensions. /// </summary> public enum TextureDimension { /// <summary> /// 1-dimensional texture. /// </summary> Dim1D, /// <summary> /// 2-dimensional texture. /// </summary> Dim2D, /// <summary> /// 3-dimensional texture. /// </summary> Dim3D } /// <summary> /// Enumeration of types of textures. /// </summary> public enum TextureType { /// <summary> /// 1-dimensional texture. /// </summary> Texture1D, /// <summary> /// 1-dimensional array texture. /// </summary> Texture1DArray, /// <summary> /// 2-dimensional texture. /// </summary> Texture2D, /// <summary> /// 2-dimensional cubemap texture. /// </summary> Texture2DCube, /// <summary> /// 2-dimensional array texture. /// </summary> Texture2DArray, /// <summary> /// 2-dimensional cubemap array texture. /// </summary> Texture2DCubeArray, /// <summary> /// 3-dimensional texture. /// </summary> Texture3D } /// <summary> /// Bitmask of usages of textures. /// </summary> [Flags] public enum TextureUsage { /// <summary> /// The texture can be the source for transfer operations. /// </summary> TransferSrc = 0x0001, /// <summary> /// The texture can be the destination for transfer operations. /// </summary> TransferDst = 0x0002, /// <summary> /// The texture can be sampled by a shader program. /// </summary> Sampled = 0x0004, /// <summary> /// The texture can be used as a storage image by a shader program. /// </summary> Storage = 0x0008, /// <summary> /// The texture can be used as a color attachment. /// </summary> ColorAttachment = 0x0010, /// <summary> /// The texture can be used as a depth and/or stencil attachment. /// </summary> DepthStencilAttachment = 0x0020, /// <summary> /// The texture may use lazily allocated memory when used as an attachment. /// </summary> TransientAttachment = 0x0040, /// <summary> /// The texture can be used as an input attachment. /// </summary> InputAttachment = 0x0080, /// <summary> /// The texture can have sub-views created from it. /// </summary> SubView = 0x1000 } /// <summary> /// A texture is a multidimensional structure for storing /// </summary> public interface ITexture : IDisposable, ISwapchainImage { /// <summary> /// Gets the dimensions of the given texture type. /// </summary> /// <param name="type">Texture type</param> /// <returns>Dimensions of texture type</returns> public static TextureDimension GetTypeDimension(TextureType type) => type switch { TextureType.Texture1D => TextureDimension.Dim1D, TextureType.Texture1DArray => TextureDimension.Dim2D, TextureType.Texture2D => TextureDimension.Dim2D, TextureType.Texture2DCube => TextureDimension.Dim3D, TextureType.Texture2DArray => TextureDimension.Dim3D, TextureType.Texture2DCubeArray => TextureDimension.Dim3D, TextureType.Texture3D => TextureDimension.Dim3D, _ => throw new ArgumentException($"No such dimension for texture type \"{type}\"", nameof(type)) }; /// <summary> /// The type of this texture. /// </summary> public TextureType Type { get; } /// <summary> /// The pixel format of this texture. /// </summary> public PixelFormat Format { get; } /// <summary> /// The size of this texture. /// </summary> public Vector3i Size { get; } /// <summary> /// The number of mipmap levels in this texture. /// </summary> public uint MipLevels { get; } /// <summary> /// The number of array layers in this texture. /// </summary> public uint ArrayLayers { get; } /// <summary> /// The number of multisample samples the texture uses. /// </summary> public uint Samples { get; } /// <summary> /// The bitmask of usages for this texture. /// </summary> public TextureUsage Usage { get; } /// <summary> /// The memory binding for this texture. /// </summary> public IMemoryBinding? MemoryBinding { get; } } /// <summary> /// Texture creation information. /// </summary> public record TextureCreateInfo { /// <summary> /// The type of texture to create. /// </summary> public TextureType Type { get; init; } /// <summary> /// The pixel format of the texture. /// </summary> public PixelFormat Format { get; init; } = null!; /// <summary> /// The size of the texture. /// </summary> public Vector3i Size { get; init; } /// <summary> /// The number of mipmap levels in the texture. /// </summary> public uint MipLevels { get; init; } /// <summary> /// The number of array layers in the texture. If the texture is a type of /// cubemap this must be a multiple of 6. /// </summary> public uint ArrayLayers { get; init; } /// <summary> /// The number of multisampling samples the texture will use. /// </summary> public uint Samples { get; init; } /// <summary> /// The initial layout of the texture. /// </summary> public TextureLayout InitialLayout { get; init; } /// <summary> /// Bitmask of usages expected for this texture. /// </summary> public TextureUsage Usage { get; init; } /// <summary> /// Explicit memory binding information for the texture, or <c>null</c> to let the backend /// decide how memory should be bound for the texture. /// </summary> public IMemoryBinding? MemoryBinding { get; init; } } /// <summary> /// Structure defining a texture subresource targeting a single mipmap level and a range of layers. /// </summary> public struct TextureSubresourceLayers { /// <summary> /// Bitmask of the texture aspects contained in this subresource. /// </summary> public TextureAspect Aspects; /// <summary> /// The mip level contained in this subresource. /// </summary> public uint MipLevel; /// <summary> /// The first array layer in the subresource. /// </summary> public uint BaseArrayLayer; /// <summary> /// The number of array layers in the subresource. /// </summary> public uint LayerCount; } /// <summary> /// Structure defining a texture subresource targeting a range of mipmap levels and layers. /// </summary> public struct TextureSubresourceRange { /// <summary> /// Bitmask of the texture aspects contained in this subresource. /// </summary> public TextureAspect Aspects; /// <summary> /// The first mip level in the subresource. /// </summary> public uint BaseMipLevel; /// <summary> /// The number of mip levels in this subresource. /// </summary> public uint MipLevelCount; /// <summary> /// The first array layer in the subresource. /// </summary> public uint BaseArrayLayer; /// <summary> /// The number of array layers in the subresource. /// </summary> public uint ArrayLayerCount; } /// <summary> /// A texture view provides a view of a subset of a texture, and is used to link a texture to other resources /// such as framebuffers and bind sets. /// </summary> public interface ITextureView : IDisposable { /// <summary> /// The type of texture viewed by the texture view. This may differ from the texture type of /// the underlying texture referenced by this view. /// </summary> public TextureType Type { get; } /// <summary> /// The pixel format the texture view uses. The format of the texture view may differ from that of the original /// texture, so long as the formats are binary compatible; each texel must be of the same size in both formats /// such that the memory locations for texels are not different between formats. Only the interpretation of /// the bits of each texel may change between the texture and its view. /// </summary> public PixelFormat Format { get; } /// <summary> /// A mapping of components as they are read from the format of the texture view. /// </summary> public ComponentMapping Mapping { get; } /// <summary> /// The subresource range of the source texture that the view provides. /// </summary> public TextureSubresourceRange SubresourceRange { get; } } /// <summary> /// Texture view creation information. /// </summary> public record TextureViewCreateInfo { /// <summary> /// The source texture for the texture view. /// </summary> public ITexture Texture { get; init; } = null!; /// <summary> /// The type of texture view to create. /// </summary> public TextureType Type { get; init; } /// <summary> /// The pixel format of the texture view. /// </summary> public PixelFormat Format { get; init; } = null!; /// <summary> /// The component mapping of the texture view. /// </summary> public ComponentMapping Mapping { get; init; } /// <summary> /// The subresource range of the texture view within the source texture. /// </summary> public TextureSubresourceRange SubresourceRange { get; init; } } }
26.53753
113
0.657208
[ "Apache-2.0" ]
Zekrom64/TesseractEngine
TesseractEngine-Core/Core/Graphics/Accelerated/Texture.cs
10,962
C#
using Unity.VisualScripting; using UnityEngine; namespace DNode { public abstract class DTexUnaryUnit : DTexUnit { [DoNotSerialize][PortLabelHidden] public ValueInput Input; [DoNotSerialize] public ValueInput Bypass; [Inspectable] public TextureSizeSource SizeSource = TextureSizeSource.Source; [DoNotSerialize] [PortLabelHidden] public ValueOutput result; protected override void Definition() { Input = ValueInput<DFrameTexture>(nameof(Input)); Bypass = ValueInput<bool>(nameof(Bypass), false); DFrameTexture ComputeFromFlow(Flow flow) { Texture texture = GetTextureInput(flow, Input, Texture2D.blackTexture); if (flow.GetValue<bool>(Bypass)) { return new DFrameTexture { Texture = texture }; } TextureSizeSource sizeSource = SizeSource; RenderTexture output = DScriptMachine.CurrentInstance.RenderTextureCache.Allocate(texture, sizeSource); Compute(flow, texture, output); BlitToDebugCaptureTexture(output); return new DFrameTexture { Texture = output }; } result = ValueOutput<DFrameTexture>("result", DNodeUtils.CachePerFrame(ComputeFromFlow)); } protected abstract void Compute(Flow flow, Texture input, RenderTexture output); } }
37.714286
112
0.697727
[ "MIT" ]
nattos/dnode
Assets/DNode/Scripts/Texture/DTexUnaryUnit.cs
1,322
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Text; namespace MythMaker.Rendering { class Fonts { #region font settings public class FontSettings { public string Mason { get { var str = Properties.Settings.Default["FontsMasonSans"] as string; return str == "" ? null : str; } } public string HelCn { get { var str = Properties.Settings.Default["FontsHelveticaNeueCn"] as string; return str == "" ? null : str; } } public string HelMdCn { get { var str = Properties.Settings.Default["FontsHelveticaNeueMdCn"] as string; return str == "" ? null : str; } } public void Update(string mason, string helCn, string helMdCn) { Properties.Settings.Default["FontsMasonSans"] = mason; Properties.Settings.Default["FontsHelveticaNeueCn"] = helCn; Properties.Settings.Default["FontsHelveticaNeueMdCn"] = helMdCn; Properties.Settings.Default.Save(); } } #endregion private static PrivateFontCollection fontCollection; public static FontSettings Settings { get; } = new FontSettings(); private static System.Drawing.Font[] myth; public static System.Drawing.Font[] Myth { get { if (myth == null) loadFonts(); return myth; } } private static System.Drawing.Font[] helCn, helCnO, helMdCnO, helBdCn; public static bool Validate() { return Validate(Settings.Mason, Settings.HelCn, Settings.HelMdCn); } public static bool Validate(string mason, string helCn, string helMdCn) { // test mason System.Drawing.Font font = new System.Drawing.Font(mason, 10.0f, System.Drawing.FontStyle.Regular); if (font.Name != mason) return false; // test helvetica regular, italic, bold font = new System.Drawing.Font(helCn, 10.0f, System.Drawing.FontStyle.Regular); if (font.Name != helCn) return false; font = new System.Drawing.Font(helCn, 10.0f, System.Drawing.FontStyle.Italic); if (font.Name != helCn) return false; font = new System.Drawing.Font(helCn, 10.0f, System.Drawing.FontStyle.Bold); if (font.Name != helCn) return false; // test helvetica medium italic font = new System.Drawing.Font(helMdCn, 10.0f, System.Drawing.FontStyle.Italic); if (font.Name != helMdCn) return false; return true; } public static void Reset() { myth = null; } private static void loadFonts() { fontCollection = new PrivateFontCollection(); fontCollection.AddFontFile(System.IO.Path.GetFullPath(@"resources/Myth.ttf")); // make sure fontCollection is kept alive, otherwise the fonts will be unloaded var mythFamily = fontCollection.Families[0]; myth = new System.Drawing.Font[] { new System.Drawing.Font(mythFamily, 7.6f, System.Drawing.FontStyle.Regular), new System.Drawing.Font(mythFamily, 6.0f, System.Drawing.FontStyle.Regular) }; helCn = new System.Drawing.Font[] { new System.Drawing.Font(Settings.HelCn, 5.82f, System.Drawing.FontStyle.Regular), new System.Drawing.Font(Settings.HelCn, 4.83f, System.Drawing.FontStyle.Regular) }; helCnO = new System.Drawing.Font[] { new System.Drawing.Font(Settings.HelCn, 5.82f, System.Drawing.FontStyle.Italic), new System.Drawing.Font(Settings.HelCn, 4.83f, System.Drawing.FontStyle.Italic) }; helMdCnO = new System.Drawing.Font[] { new System.Drawing.Font(Settings.HelMdCn, 5.82f, System.Drawing.FontStyle.Italic), new System.Drawing.Font(Settings.HelMdCn, 4.83f, System.Drawing.FontStyle.Italic) }; helBdCn = new System.Drawing.Font[] { new System.Drawing.Font(Settings.HelCn, 5.82f, System.Drawing.FontStyle.Bold), new System.Drawing.Font(Settings.HelCn, 4.83f, System.Drawing.FontStyle.Bold) }; } } }
36.824427
111
0.545605
[ "MIT" ]
jakobharder/mythmaker
MythMakerWPF/Rendering/Fonts.cs
4,826
C#
// borrowed shamelessly and enhanced from Bag of Tricks https://www.nexusmods.com/pathfinderkingmaker/mods/26, which is under the MIT License using HarmonyLib; using Kingmaker; using Kingmaker.Blueprints.Classes; //using Kingmaker.Controllers.GlobalMap; using Kingmaker.EntitySystem.Entities; //using Kingmaker.UI._ConsoleUI.Models; //using Kingmaker.UI.RestCamp; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Class.LevelUp; using Kingmaker.UnitLogic.Class.LevelUp.Actions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; //using Kingmaker.UI._ConsoleUI.GroupChanger; using UnityModManager = UnityModManagerNet.UnityModManager; using ModKit.Utility; using ModKit; using Kingmaker.UI.MVVM._PCView.CharGen.Phases.Class; using TMPro; using UnityEngine; using UnityEngine.UI; using Kingmaker.UI; using Kingmaker.UI.MVVM._VM.CharGen.Phases.Class; using Kingmaker.PubSubSystem; using Kingmaker.UI.MVVM._PCView.ServiceWindows.CharacterInfo.Sections.Progression.Main; using Kingmaker.UI.MVVM._PCView.CharGen; using Kingmaker.UI.MVVM._VM.CharGen.Phases.Mythic; using Kingmaker.UI.MVVM._VM.Party; using Kingmaker.Blueprints.Root; using Kingmaker.Blueprints; using Kingmaker.DLC; using Kingmaker.UI.MVVM._VM.Other.NestedSelectionGroup; namespace ToyBox.Multiclass { public static partial class MultipleClasses { #region Class Level & Archetype [HarmonyPatch(typeof(LevelUpController), nameof(LevelUpController.UpdatePreview))] private static class LevelUpController_UpdatePreview_Patch { private static void Prefix(LevelUpController __instance) { if (IsAvailable()) { // This is the critical place that gets called once before we go through all the level computations for setting up the level up screen Mod.Debug("LevelUpController_UpdatePreview_Patch"); //Main.multiclassMod.AppliedMulticlassSet.Clear(); //Main.multiclassMod.UpdatedProgressions.Clear(); } } } [HarmonyPatch(typeof(SelectClass), nameof(SelectClass.Apply), new Type[] { typeof(LevelUpState), typeof(UnitDescriptor) })] private static class SelectClass_Apply_Patch { [HarmonyPostfix] private static void Postfix(LevelUpState state, UnitDescriptor unit) { if (!settings.toggleMulticlass) return; if (!unit.IsPartyOrPet()) return; //if (Mod.IsCharGen()) Main.Log($"stack: {System.Environment.StackTrace}"); if (IsAvailable()) { Main.multiclassMod.AppliedMulticlassSet.Clear(); Main.multiclassMod.UpdatedProgressions.Clear(); // Some companions have predefined levels so in some cases we get called iteratively for each level so we will make sure we only apply multiclass on the last level if (unit.TryGetPartyMemberForLevelUpVersion(out var ch) && ch.TryGetClass(state.SelectedClass, out var cl) && unit != ch.Descriptor && state.NextClassLevel <= cl.Level ) { Mod.Debug($"SelectClass_Apply_Patch, unit: {unit.CharacterName.orange()} isCH: {unit == ch.Descriptor}) - skip - lvl:{state.NextClassLevel} vs {cl.Level} ".green()); return; } // get multi-class setting bool useDefaultMulticlassOptions = state.IsCharGen(); var options = MulticlassOptions.Get(useDefaultMulticlassOptions ? null : unit); Mod.Trace($"SelectClass_Apply_Patch, unit: {unit.CharacterName.orange()} useDefaultMulticlassOptions: {useDefaultMulticlassOptions} isCharGen: {state.IsCharGen()} is1stLvl: {state.IsFirstCharacterLevel} isPHChar: {unit.CharacterName == "Player Character"} level: {state.NextClassLevel.ToString().yellow()}".cyan().bold()); if (options == null || options.Count == 0) return; Mod.Trace($" selected options: {options}".orange()); //selectedMulticlassSet.ForEach(cl => Main.Log($" {cl}")); // applying classes var selectedClass = state.SelectedClass; StateReplacer stateReplacer = new(state); foreach (var characterClass in Main.multiclassMod.AllClasses) { if (characterClass.IsMythic != selectedClass.IsMythic) continue; if (Main.multiclassMod.AppliedMulticlassSet.Contains(characterClass)) { Mod.Warn($"SelectClass_Apply_Patch - duplicate application of multiclass detected: {characterClass.name.yellow()}"); continue; } if (options.Contains(characterClass)) { Mod.Trace($" checking {characterClass.HashKey()} {characterClass.GetDisplayName()} "); } if (characterClass != stateReplacer.SelectedClass && characterClass.IsMythic == state.IsMythicClassSelected && options.Contains(characterClass) ) { stateReplacer.Replace(null, 0); // TODO - figure out and document what this is doing Mod.Trace($" {characterClass.Name} matches".cyan()); //stateReplacer.Replace(characterClass, unit.Progression.GetClassLevel(characterClass)); if (new SelectClass(characterClass).Check(state, unit)) { Mod.Trace($" - {nameof(SelectClass)}.{nameof(SelectClass.Apply)}*({characterClass}, {unit})".cyan()); unit.Progression.AddClassLevel_NotCharacterLevel(characterClass); //state.NextClassLevel = unit.Progression.GetClassLevel(characterClass); //state.SelectedClass = characterClass; characterClass.RestrictPrerequisites(unit, state); //EventBus.RaiseEvent<ILevelUpSelectClassHandler>(h => h.HandleSelectClass(unit, state)); Main.multiclassMod.AppliedMulticlassSet.Add(characterClass); } } } stateReplacer.Restore(); Mod.Trace($" checking archetypes for {unit.CharacterName}".cyan()); // applying archetypes ForEachAppliedMulticlass(state, unit, () => { Mod.Trace($" {state.SelectedClass.HashKey()} SelectClass-ForEachApplied".cyan().bold()); var selectedClass = state.SelectedClass; var archetypeOptions = options.ArchetypeOptions(selectedClass); foreach (var archetype in state.SelectedClass.Archetypes) { // here is where we need to start supporting multiple archetypes of the same class if (archetypeOptions.Contains(archetype)) { Mod.Trace($" adding archetype: ${archetype.Name}".cyan().bold()); AddArchetype addArchetype = new(state.SelectedClass, archetype); unit.SetClassIsGestalt(addArchetype.CharacterClass, true); if (addArchetype.Check(state, unit)) { addArchetype.Apply(state, unit); } } } }); } } } #endregion #region Skills & Features [HarmonyPatch(typeof(LevelUpController))] [HarmonyPatch("ApplyLevelup")] private static class LevelUpController_ApplyLevelup_Patch { private static void Prefix(LevelUpController __instance, UnitEntityData unit) { if (!settings.toggleMulticlass) return; if (unit == __instance.Preview) { Mod.Trace($"Unit Preview = {unit.CharacterName}"); Mod.Trace("levelup action:"); foreach (var action in __instance.LevelUpActions) { Mod.Trace($"{action.GetType()}"); } } } } [HarmonyPatch(typeof(ApplyClassMechanics), nameof(ApplyClassMechanics.Apply), new Type[] { typeof(LevelUpState), typeof(UnitDescriptor) })] private static class ApplyClassMechanics_Apply_Patch { [HarmonyPostfix] private static void Postfix(ApplyClassMechanics __instance, LevelUpState state, UnitDescriptor unit) { if (!settings.toggleMulticlass) return; if (IsAvailable()) { Mod.Debug($"ApplyClassMechanics_Apply_Patch - unit: {unit} {unit.CharacterName} class:{state.SelectedClass}"); if (state.SelectedClass != null) { ForEachAppliedMulticlass(state, unit, () => { unit.SetClassIsGestalt(state.SelectedClass, true); //Main.Log($" - {nameof(ApplyClassMechanics)}.{nameof(ApplyClassMechanics.Apply)}*({state.SelectedClass}{state.SelectedClass.Archetypes}[{state.NextClassLevel}], {unit}) mythic: {state.IsMythicClassSelected} vs {state.SelectedClass.IsMythic}"); __instance.Apply_NoStatsAndHitPoints(state, unit); }); } var allAppliedClasses = Main.multiclassMod.AppliedMulticlassSet.ToList(); Mod.Debug($"ApplyClassMechanics_Apply_Patch - {String.Join(" ", allAppliedClasses.Select(cl => cl.Name))}".orange()); allAppliedClasses.Add(state.SelectedClass); SavesBAB.ApplySaveBAB(unit, state, allAppliedClasses.ToArray()); HPDice.ApplyHPDice(unit, state, allAppliedClasses.ToArray()); } } } [HarmonyPatch(typeof(SelectFeature), nameof(SelectFeature.Apply), new Type[] { typeof(LevelUpState), typeof(UnitDescriptor) })] private static class SelectFeature_Apply_Patch { [HarmonyPrefix, HarmonyPriority(Priority.First)] private static void Prefix(SelectFeature __instance, LevelUpState state, UnitDescriptor unit, ref StateReplacer __state) { if (!settings.toggleMulticlass) return; if (IsAvailable()) { if (__instance.Item != null) { var selectionState = ReflectionCache.GetMethod<SelectFeature, Func<SelectFeature, LevelUpState, FeatureSelectionState>> ("GetSelectionState")(__instance, state); if (selectionState != null) { var sourceClass = selectionState.SourceFeature?.GetSourceClass(unit); if (sourceClass != null) { __state = new StateReplacer(state); __state.Replace(sourceClass, unit.Progression.GetClassLevel(sourceClass)); } } } } } [HarmonyPostfix, HarmonyPriority(Priority.Last)] private static void Postfix(SelectFeature __instance, ref StateReplacer __state) { if (!settings.toggleMulticlass) return; if (__state != null) { __state.Restore(); } } } [HarmonyPatch(typeof(SelectFeature), nameof(SelectFeature.Check), new Type[] { typeof(LevelUpState), typeof(UnitDescriptor) })] private static class SelectFeature_Check_Patch { [HarmonyPrefix, HarmonyPriority(Priority.First)] private static void Prefix(SelectFeature __instance, LevelUpState state, UnitDescriptor unit, ref StateReplacer __state) { if (!settings.toggleMulticlass) return; if (IsAvailable()) { if (__instance.Item != null) { var selectionState = ReflectionCache.GetMethod<SelectFeature, Func<SelectFeature, LevelUpState, FeatureSelectionState>> ("GetSelectionState")(__instance, state); if (selectionState != null) { var sourceClass = selectionState.SourceFeature?.GetSourceClass(unit); if (sourceClass != null) { __state = new StateReplacer(state); __state.Replace(sourceClass, unit.Progression.GetClassLevel(sourceClass)); } } } } } [HarmonyPostfix, HarmonyPriority(Priority.Last)] private static void Postfix(SelectFeature __instance, ref StateReplacer __state) { if (!settings.toggleMulticlass) return; if (__state != null) { __state.Restore(); } } } #endregion #region Spellbook [HarmonyPatch(typeof(ApplySpellbook), nameof(ApplySpellbook.Apply), new Type[] { typeof(LevelUpState), typeof(UnitDescriptor) })] private static class ApplySpellbook_Apply_Patch { [HarmonyPostfix] private static void Postfix(MethodBase __originalMethod, ApplySpellbook __instance, LevelUpState state, UnitDescriptor unit) { if (!settings.toggleMulticlass) return; if (IsAvailable() && !Main.multiclassMod.LockedPatchedMethods.Contains(__originalMethod)) { Main.multiclassMod.LockedPatchedMethods.Add(__originalMethod); ForEachAppliedMulticlass(state, unit, () => { __instance.Apply(state, unit); }); Main.multiclassMod.LockedPatchedMethods.Remove(__originalMethod); } } } #endregion #region Commit [HarmonyPatch(typeof(LevelUpController), nameof(LevelUpController.Commit))] private static class LevelUpController_Commit_Patch { [HarmonyPostfix] private static void Postfix(LevelUpController __instance) { if (!settings.toggleMulticlass) return; if (IsAvailable()) { var isCharGen = __instance.State.IsCharGen(); var ch = __instance.Unit; var options = MulticlassOptions.Get(isCharGen ? null : ch); if (isCharGen && __instance.Unit.IsCustomCompanion() && options.Count > 0) { Mod.Trace($"LevelUpController_Commit_Patch - {ch} - {options}"); MulticlassOptions.Set(ch, options); } } } } #endregion [HarmonyPatch(typeof(UnitProgressionData), nameof(UnitProgressionData.SetupLevelsIfNecessary))] private static class UnitProgressionData_SetupLevelsIfNecessary_Patch { private static bool Prefix(UnitProgressionData __instance) { if (__instance.m_CharacterLevel.HasValue && __instance.m_MythicLevel.HasValue) return false; __instance.UpdateLevelsForGestalt(); return false; } } [HarmonyPatch(typeof(CharGenClassPhaseVM), nameof(CharGenClassPhaseVM.CreateClassListSelector))] private static class CharGenClassPhaseVM_CreateClassListSelector_Patch { private static bool Prefix(CharGenClassPhaseVM __instance) { if (settings.toggleMulticlass || settings.toggleIgnoreClassAndFeatRestrictions) { var progression = Game.Instance.BlueprintRoot.Progression; __instance.m_ClassesVMs = (__instance.LevelUpController.State.Mode == LevelUpState.CharBuildMode.Mythic ? __instance.GetMythicClasses() : (__instance.LevelUpController.Unit.IsPet ? progression.PetClasses.Concat(progression.CharacterClasses.OrderBy(cl => cl.Name)) : progression.CharacterClasses) ) .Where(cls => { if (cls.IsDlcRestricted()) return false; return CharGenClassPhaseVM.MeetsPrerequisites(__instance.LevelUpController, cls) || !cls.HideIfRestricted; }) .Select(cls => new CharGenClassSelectorItemVM( cls, null, __instance.LevelUpController, __instance, __instance.SelectedArchetypeVM, __instance.ReactiveTooltipTemplate, CharGenClassPhaseVM.IsClassAvailable(__instance.LevelUpController, cls), true, false)) .ToList<CharGenClassSelectorItemVM>(); __instance.ClassSelector = new NestedSelectionGroupRadioVM<CharGenClassSelectorItemVM>((INestedListSource)__instance); return false; } return true; } } public static class MulticlassCheckBoxHelper { public static void UpdateCheckbox(CharGenClassSelectorItemPCView instance) { if (instance == null) return; var multicheckbox = instance.transform?.Find("MulticlassCheckbox-ToyBox"); if (multicheckbox == null) return; var toggle = multicheckbox.GetComponent<ToggleWorkaround>(); if (toggle == null) return; var viewModel = instance.ViewModel; if (viewModel == null) return; var ch = Main.IsInGame ? viewModel.LevelUpController.Unit : null; var cl = viewModel.Class; var image = multicheckbox.Find("Background").GetComponent<Image>(); var canSelect = MulticlassOptions.CanSelectClassAsMulticlass(ch, cl); image.CrossFadeAlpha(canSelect ? 1.0f : 0f, 0, true); var options = MulticlassOptions.Get(ch); var shouldSelect = options.Contains(cl) && (!viewModel.IsArchetype || options.ArchetypeOptions(cl).Contains(viewModel.Archetype)); toggle.SetIsOnWithoutNotify(shouldSelect); toggle.onValueChanged.RemoveAllListeners(); toggle.onValueChanged.AddListener(v => MulticlassCheckBoxChanged(v, instance)); } public static void MulticlassCheckBoxChanged(bool value, CharGenClassSelectorItemPCView instance) { if (instance == null) return; var viewModel = instance.ViewModel; if (viewModel == null) return; var ch = Main.IsInGame ? viewModel.LevelUpController.Unit : null; var cl = viewModel.Class; if (!MulticlassOptions.CanSelectClassAsMulticlass(ch, cl)) return; var options = MulticlassOptions.Get(ch); var cd = ch?.Progression.GetClassData(cl); var chArchetype = cd?.Archetypes.FirstOrDefault<BlueprintArchetype>(); var archetypeOptions = options.ArchetypeOptions(cl); if (value) archetypeOptions = options.Add(cl); else options.Remove(cl); if (options.Contains(cl)) { if (viewModel.IsArchetype) { if (value) archetypeOptions.AddExclusive(viewModel.Archetype); else archetypeOptions.Remove(viewModel.Archetype); } else if (chArchetype != null) { // this is the case where the user clicks on the class and the character already has an archetype in this class if (value) archetypeOptions.AddExclusive(chArchetype); else archetypeOptions.Remove(chArchetype); } options.SetArchetypeOptions(cl, archetypeOptions); } MulticlassOptions.Set(ch, options); Mod.Debug($"ch: {ch?.CharacterName.ToString().orange() ?? "null"} class: {cl?.name ?? "null"} isArch: {viewModel.IsArchetype} arch: {viewModel.Archetype} chArchetype:{chArchetype} - options: {options}"); var canvas = Game.Instance.UI.Canvas; var transform = canvas != null ? canvas.transform : Game.Instance.UI.MainMenu.transform; var charGemClassPhaseDetailedView = transform.Find("ChargenPCView/ContentWrapper/DetailedViewZone/PhaseClassDetaildPCView"); var phaseClassDetailView = charGemClassPhaseDetailedView.GetComponent<Kingmaker.UI.MVVM._PCView.CharGen.Phases.Class.CharGenClassPhaseDetailedPCView>(); var charGenClassPhaseVM = phaseClassDetailView.ViewModel; var selectedClassVM = charGenClassPhaseVM.SelectedClassVM.Value; charGenClassPhaseVM.OnSelectorClassChanged(viewModel); if (viewModel.IsArchetype) { charGenClassPhaseVM.OnSelectorArchetypeChanged(viewModel.Archetype); } else { charGenClassPhaseVM.LevelUpController.RemoveArchetype(viewModel.Archetype); charGenClassPhaseVM.UpdateClassInformation(); } charGenClassPhaseVM.OnSelectorClassChanged(selectedClassVM); } } [HarmonyPatch(typeof(CharGenClassSelectorItemPCView), nameof(CharGenClassSelectorItemPCView.BindViewImplementation))] private static class CharGenClassSelectorItemPCView_BindViewImplementation_Patch { private static void Postfix(CharGenClassSelectorItemPCView __instance) { //Mod.Warn("CharGenClassSelectorItemPCView_CharGenClassSelectorItemPCView_Patch"); var multicheckbox = __instance.transform.Find("MulticlassCheckbox-ToyBox"); if (multicheckbox != null) { if (!settings.toggleMulticlass) { GameObject.Destroy(multicheckbox.gameObject); } } if (!settings.toggleMulticlass) return; if (multicheckbox == null) { var checkbox = Game.Instance.UI.FadeCanvas.transform.Find("TutorialView/BigWindow/Window/Content/Footer/Toggle"); //var checkbox = Game.Instance.UI.Canvas.transform.Find("ServiceWindowsPCView/SpellbookView/SpellbookScreen/MainContainer/KnownSpells/Toggle"); var sibling = __instance.transform.Find("CollapseButton"); var textContainer = __instance.transform.Find("TextContainer"); var textLayout = textContainer.GetComponent<LayoutElement>(); textLayout.preferredWidth = 1; var siblingIndex = sibling.transform.GetSiblingIndex(); multicheckbox = GameObject.Instantiate(checkbox, __instance.transform); multicheckbox.transform.SetSiblingIndex(1); multicheckbox.name = "MulticlassCheckbox-ToyBox"; multicheckbox.GetComponentInChildren<TextMeshProUGUI>().text = ""; multicheckbox.gameObject.SetActive(true); MulticlassCheckBoxHelper.UpdateCheckbox(__instance); PerSaveSettings.observers += (perSave) => MulticlassCheckBoxHelper.UpdateCheckbox(__instance); } else { multicheckbox.gameObject.SetActive(true); MulticlassCheckBoxHelper.UpdateCheckbox(__instance); } } } //[HarmonyPatch(typeof(CharGenClassSelectorItemPCView), nameof(CharGenClassSelectorItemPCView.RefreshView))] //private static class CharGenClassSelectorItemPCView_RefreshView_Patch { // private static void Postfix(CharGenClassSelectorItemPCView __instance) { // if (!settings.toggleMulticlass) return; // MulticlassCheckBoxHelper.UpdateCheckbox(__instance); // } //} private static String class_selection_text_initial = null; [HarmonyPatch(typeof(CharGenClassPhaseDetailedPCView), nameof(CharGenClassPhaseDetailedPCView.BindViewImplementation))] private static class CharGenClassPhaseDetailedPCView_BindViewImplementation_Patch { private static void Postfix(CharGenClassPhaseDetailedPCView __instance) { var chooseClass = __instance.transform.Find("ClassSelecotrPlace/Selector/HeaderH2/Label"); if (class_selection_text_initial == null) { class_selection_text_initial = chooseClass.GetComponentInChildren<TextMeshProUGUI>().text; } chooseClass.GetComponentInChildren<TextMeshProUGUI>().text = settings.toggleMulticlass ? "Choose Class <size=67%>(Checkbox for multiclass)</size>" : class_selection_text_initial; } } } }
57.838852
342
0.580627
[ "MIT" ]
NordicRest/ToyBox
ToyBox/classes/MonkeyPatchin/Multiclass/MultipleClasses.cs
26,205
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PerformanceMonitor.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PerformanceMonitor.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.75
184
0.615357
[ "MIT" ]
GridEx/PerformanceMonitor
src/Properties/Resources.Designer.cs
2,802
C#
using LogBins.Base; using Ninject.Modules; using System; using System.Collections.Generic; using System.Text; namespace Logs.Server.Core.SimpleBuckets { public class Module : NinjectModule { public override void Load() { Kernel.Bind<IBucketFactory>() .To<LogBins.Simple.BucketFactory>(); } } }
20
52
0.638889
[ "MIT" ]
arkhivania/LogsML
Logs.Server.Core/SimpleBuckets/Module.cs
362
C#
namespace ResXManager.Infrastructure { public static class RegionId { public const string Main = "Main"; public const string Shell = "Shell"; public const string Content = "Content"; public const string Configuration = "Configuration"; public const string ProjectListContextMenu = "ProjectListContextMenu"; public const string ResourceTableContextMenu = "ResourceTableContextMenu"; public const string ResourceTableItemContextMenu = "ResourceTableItemContextMenu"; public const string ProjectListItemDecorator = "ProjectListItemDecorator"; } }
37.588235
91
0.70266
[ "MIT" ]
Dalagh/ResXResourceManager
src/ResXManager.Infrastructure/RegionId.cs
641
C#
using System; using System.Linq; using static TensorShaderCudaBackend.ArrayManipulation; namespace TensorShaderCudaBackend.Shaders.Quaternion.Convolution { /// <summary>カーネル積</summary> public sealed class KernelProduct2D : Shader { /// <summary>入力チャネル数</summary> public uint InChannels { private set; get; } /// <summary>出力チャネル数</summary> public uint OutChannels { private set; get; } /// <summary>フィルタサイズ</summary> public uint KernelWidth { private set; get; } /// <summary>フィルタサイズ</summary> public uint KernelHeight { private set; get; } /// <summary>転置</summary> public bool Transpose { private set; get; } /// <summary>実行あたりの積数(2^29=536870912)</summary> public static ulong MulPerExecute => 0x20000000; /// <summary>実行あたりのポイント数(2^14=16384‬)</summary> public static uint PointsPerExecute => 0x4000; /// <summary>ブロックサイズ</summary> public (uint x, uint y) BlockSize { private set; get; } /// <summary>1スレッドで処理する対象ピクセル数</summary> private static uint BatchPixels => 16; /// <summary>識別子</summary> public override sealed string Signature => $"{GetType().Name.Split(',').Last()} {nameof(InChannels)} = {InChannels} {nameof(OutChannels)} = {OutChannels} " + $"{nameof(KernelWidth)} = {KernelWidth} {nameof(KernelHeight)} = {KernelHeight} {nameof(Transpose)} = {Transpose}"; /// <summary>コンストラクタ</summary> public KernelProduct2D(uint inchannels, uint outchannels, uint kwidth, uint kheight, bool transpose) { if (!Limits.CheckChannels(inchannels, outchannels) || !Limits.CheckMultipleNum(multiple: 4, inchannels, outchannels)) { throw new ArgumentException($"{nameof(inchannels)}, {nameof(outchannels)}"); } if (!Limits.CheckKernelSize(kwidth, kheight)) { throw new ArgumentException($"{nameof(kwidth)}, {nameof(kheight)}"); } this.InChannels = inchannels / 4; this.OutChannels = outchannels / 4; this.KernelWidth = kwidth; this.KernelHeight = kheight; this.Transpose = transpose; this.BlockSize = Kernel.MinimizeGridsBlockSize((InChannels, OutChannels)); string code = $@" {Defines.CtorFloat4} {Defines.FloatFloatFma} {Defines.FloatFloatFms} {Defines.FloatFloatHiLoAdd} {Defines.Quaternion.KernelProd} {Defines.Quaternion.AtomicAdd} __global__ void quaternion_kernelproduct_2d(const float4* __restrict__ inmap, const float4* __restrict__ outmap, float4* __restrict__ filter, unsigned int oy_offset, unsigned int xsets, unsigned int inwidth, unsigned int outwidth) {{ unsigned int inch = {Defines.IndexX}, outch = {Defines.IndexY}; unsigned int ox_offset = ({Defines.BlockIndexZ} % xsets) * {BatchPixels}; unsigned int oy = oy_offset + {Defines.BlockIndexZ} / xsets; unsigned int tidx = {Defines.ThreadIdX}, tidy = {Defines.ThreadIdY}; __shared__ float4 us[{BlockSize.x}], vs[{BlockSize.y}]; for(unsigned int ky = 0, iy = oy; ky < {KernelHeight}; ky++, iy++){{ for(unsigned int kx = 0; kx < {KernelWidth}; kx++){{ unsigned int filter_index = (inch + {InChannels} * (outch + {OutChannels} * (kx + {KernelWidth} * ky))) * 2; float4 uv_hi = ctor_float4(0.0, 0.0, 0.0, 0.0), uv_lo = ctor_float4(0.0, 0.0, 0.0, 0.0); for(unsigned int ox = ox_offset, ix = ox + kx; ox < ox_offset + {BatchPixels} && ox < outwidth; ox++, ix++){{ { (OutChannels % BlockSize.y != 0 ? $"if(tidx == 0 && outch < {OutChannels}){{" : "if(tidx == 0){") } vs[tidy] = outmap[outch + {OutChannels} * (ox + outwidth * oy)]; }} { (InChannels % BlockSize.x != 0 ? $"if(tidy == 0 && inch < {InChannels}){{" : "if(tidy == 0){") } us[tidx] = inmap[inch + {InChannels} * (ix + inwidth * iy)]; }} __syncthreads(); { (InChannels % BlockSize.x != 0 ? $"if(inch < {InChannels}){{" : "") } { (OutChannels % BlockSize.y != 0 ? $"if(outch < {OutChannels}){{" : "") } float4 u = us[tidx]; float4 v = vs[tidy]; quaternion_kernelprod(uv_hi, uv_lo, {(Transpose ? "v, u" : "u, v")}); { (InChannels % BlockSize.x != 0 ? "}" : "") } { (OutChannels % BlockSize.y != 0 ? "}" : "") } __syncthreads(); }} { (InChannels % BlockSize.x != 0 ? $"if(inch < {InChannels}){{" : "") } { (OutChannels % BlockSize.y != 0 ? $"if(outch < {OutChannels}){{" : "") } floatfloat_atomicadd(filter + filter_index, uv_hi, uv_lo); { (InChannels % BlockSize.x != 0 ? "}" : "") } { (OutChannels % BlockSize.y != 0 ? "}" : "") } }} }} }}"; this.Kernel = new Kernel(code, "quaternion_kernelproduct_2d"); } /// <summary>実行</summary> public override void Execute(Stream stream, params object[] args) { CheckArgument(args); CudaArray<float> inmap = args[0] as CudaArray<float>; CudaArray<float> outmap = args[1] as CudaArray<float>; CudaArray<float> filter = args[2] as CudaArray<float>; uint inwidth = (args[3] as uint?).Value; uint inheight = (args[4] as uint?).Value; uint batches = (args[5] as uint?).Value; uint outwidth = inwidth + 1 - KernelWidth; uint outheight = inheight + 1 - KernelHeight; CudaArray<float> dfloat_filter = WorkspaceReserver<float>.Request(stream, inmap.DeviceID, index: 0, InChannels * OutChannels * KernelWidth * KernelHeight * 8); dfloat_filter.ZerosetAsync(stream, InChannels * OutChannels * KernelWidth * KernelHeight * 8); ulong mul_per_line = (ulong)InChannels * OutChannels * KernelWidth * KernelHeight * outwidth * 16; uint lines_per_execute_mul = (uint)(MulPerExecute / mul_per_line + 1); uint lines_per_execute_pixels = (PointsPerExecute + outwidth - 1) / outwidth; uint lines_per_execute = Math.Min(lines_per_execute_mul, lines_per_execute_pixels); uint xsets = (outwidth + BatchPixels - 1) / BatchPixels; for (uint th = 0; th < batches; th++) { for (uint oy_offset = 0; oy_offset < outheight; oy_offset += lines_per_execute) { uint lines = Math.Min(lines_per_execute, outheight - oy_offset); Kernel.Execute( indexes: (InChannels, OutChannels, xsets * lines), block: (BlockSize.x, BlockSize.y, 1), dynamic_shared_memory_bytes: 0, stream, inmap.ElementPtr(th * InChannels * inwidth * inheight * 4), outmap.ElementPtr(th * OutChannels * outwidth * outheight * 4), dfloat_filter, oy_offset, xsets, inwidth, outwidth ); } } HorizontalAdd(InChannels * OutChannels * KernelWidth * KernelHeight * 4, dfloat_filter, filter, stream); } /// <summary>引数チェック</summary> protected override void CheckArgument(params object[] args) { if (args is null || args.Length != 6) { throw new ArgumentException(nameof(args)); } if (!(args[3] is uint inwidth) || !Limits.CheckWidth(inwidth, KernelWidth)) { throw new ArgumentException(nameof(inwidth)); } if (!(args[4] is uint inheight) || !Limits.CheckHeight(inheight, KernelHeight)) { throw new ArgumentException(nameof(inheight)); } if (!(args[5] is uint batches) || !Limits.CheckBatches(batches)) { throw new ArgumentException(nameof(batches)); } uint outwidth = inwidth + 1 - KernelWidth; uint outheight = inheight + 1 - KernelHeight; if (!(args[0] is CudaArray<float> inmap) || inmap.Length < InChannels * inwidth * inheight * batches * 4) { throw new ArgumentException(nameof(inmap)); } if (!(args[1] is CudaArray<float> outmap) || outmap.Length < OutChannels * outwidth * outheight * batches * 4) { throw new ArgumentException(nameof(outmap)); } if (!(args[2] is CudaArray<float> filter) || filter.Length < InChannels * OutChannels * KernelWidth * KernelHeight * 4) { throw new ArgumentException(nameof(filter)); } } } }
45.509524
153
0.526944
[ "MIT" ]
tk-yoshimura/TensorShader
TensorShaderCudaBackend/Shaders/Quaternion/Convolution/KernelProduct2D.cs
9,751
C#
using System.Collections.Generic; using System.Linq; using Chronic.Core.System; using Chronic.Core.Tags; using Chronic.Core.Tags.Repeaters; namespace Chronic.Core.Handlers { public class SdRmnHandler : IHandler { public Span Handle(IList<Token> tokens, Options options) { var month = tokens[1].GetTag<RepeaterMonthName>(); var day = tokens[0].GetTag<ScalarDay>().Value; if (Time.IsMonthOverflow(options.Clock().Year, (int)month.Value, day)) { return null; } return Utils.HandleMD(month, day, tokens.Skip(2).ToList(), options); } } }
29.863636
82
0.616438
[ "MIT" ]
chadbengen/nChronic.Core
src/Chronic.Core/Handlers/SdRmnHandler.cs
657
C#
using System; using System.Collections.Generic; using System.Text; internal class ExceptionsHomework { public static T[] Subsequence<T>(T[] arr, int startIndex, int count) { if (arr == null) { throw new NullReferenceException("Missing sequence"); } if (arr.Length == 0) { throw new ArgumentOutOfRangeException("Empty sequence"); } if (startIndex + count > arr.Length) { throw new ArgumentOutOfRangeException("Count is too Big"); } List<T> result = new List<T>(); for (int i = startIndex; i < startIndex + count; i++) { result.Add(arr[i]); } return result.ToArray(); } public static string ExtractEnding(string str, int count) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException("String cannot be null or Empty!"); } if (count > str.Length) { throw new ArgumentOutOfRangeException("Invalid count!"); } StringBuilder result = new StringBuilder(); for (int i = str.Length - count; i < str.Length; i++) { result.Append(str[i]); } return result.ToString(); } public static void CheckPrime(int number) { bool isPrime = true; for (int divisor = 2; divisor <= Math.Sqrt(number); divisor++) { if (number % divisor == 0) { Console.WriteLine(string.Format("{0} is not prime!", number)); isPrime = false; break; } } if (isPrime) { Console.WriteLine(string.Format("{0} is prime.", number)); } } internal static void Main() { var substr = Subsequence("Hello!".ToCharArray(), 2, 3); Console.WriteLine(substr); var subarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 2); Console.WriteLine(string.Join(" ", subarr)); var allarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 4); Console.WriteLine(string.Join(" ", allarr)); var emptyarr = Subsequence(new int[] { -1, 3, 2, 1 }, 0, 0); Console.WriteLine(string.Join(" ", emptyarr)); Console.WriteLine(ExtractEnding("I love C#", 2)); Console.WriteLine(ExtractEnding("Nakov", 4)); Console.WriteLine(ExtractEnding("beer", 4)); ////Console.WriteLine(ExtractEnding("Hi", 100)); CheckPrime(23); CheckPrime(33); List<Exam> peterExams = new List<Exam>() { new SimpleMathExam(2), new CSharpExam(55), new CSharpExam(100), new SimpleMathExam(1), new CSharpExam(0), }; Student peter = new Student("Peter", "Petrov", peterExams); double peterAverageResult = peter.CalcAverageExamResultInPercents(); Console.WriteLine("Average results = {0:p0}", peterAverageResult); } }
28.027778
79
0.537496
[ "MIT" ]
Camyul/Modul_2_CSharp
High-Quality-Code-Part-2/01. Defensive-Programming-and-Exceptions/Exceptions-Homework/ExceptionsHomework.cs
3,029
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("03. Slot Machine")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03. Slot Machine")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("00181287-900e-4ba0-af1c-3ac88d986f85")] // 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.837838
84
0.745
[ "MIT" ]
GalinP87/Programming-Basics-May2018
Lesson8_Exam-Preparations/08. Exam-Preparation-May-Exercises/03. Slot Machine/Properties/AssemblyInfo.cs
1,403
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.ExcelApi; namespace NetOffice.ExcelApi.Behind { /// <summary> /// IDrawing /// </summary> [SyntaxBypass] public class IDrawing_ : COMObject, NetOffice.ExcelApi.IDrawing_ { #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public IDrawing_() : base() { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <param name="start">optional object start</param> /// <param name="length">optional object length</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public virtual NetOffice.ExcelApi.Characters get_Characters(object start, object length) { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Characters>(this, "Characters", typeof(NetOffice.ExcelApi.Characters), start, length); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Alias for get_Characters /// </summary> /// <param name="start">optional object start</param> /// <param name="length">optional object length</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16), Redirect("get_Characters")] public virtual NetOffice.ExcelApi.Characters Characters(object start, object length) { return get_Characters(start, length); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <param name="start">optional object start</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public virtual NetOffice.ExcelApi.Characters get_Characters(object start) { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Characters>(this, "Characters", typeof(NetOffice.ExcelApi.Characters), start); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Alias for get_Characters /// </summary> /// <param name="start">optional object start</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16), Redirect("get_Characters")] public virtual NetOffice.ExcelApi.Characters Characters(object start) { return get_Characters(start); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <param name="index1">optional object index1</param> /// <param name="index2">optional object index2</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public virtual object get_Vertices(object index1, object index2) { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Vertices", index1, index2); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Alias for get_Vertices /// </summary> /// <param name="index1">optional object index1</param> /// <param name="index2">optional object index2</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16), Redirect("get_Vertices")] public virtual object Vertices(object index1, object index2) { return get_Vertices(index1, index2); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <param name="index1">optional object index1</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public virtual object get_Vertices(object index1) { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Vertices", index1); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Alias for get_Vertices /// </summary> /// <param name="index1">optional object index1</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16), Redirect("get_Vertices")] public virtual object Vertices(object index1) { return get_Vertices(index1); } #endregion #region Methods #endregion } /// <summary> /// Interface IDrawing /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] [EntityType(EntityType.IsInterface)] public class IDrawing : NetOffice.ExcelApi.Behind.IDrawing_, NetOffice.ExcelApi.IDrawing { #pragma warning disable #region Type Information /// <summary> /// Contract Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type ContractType { get { if(null == _contractType) _contractType = typeof(NetOffice.ExcelApi.IDrawing); return _contractType; } } private static Type _contractType; /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IDrawing); return _type; } } #endregion #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public IDrawing() : base() { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Application Application { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", typeof(NetOffice.ExcelApi.Application)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Enums.XlCreator Creator { get { return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16), ProxyResult] public virtual object Parent { get { return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Range BottomRightCell { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Range>(this, "BottomRightCell", typeof(NetOffice.ExcelApi.Range)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool Enabled { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Enabled"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Enabled", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual Double Height { get { return InvokerService.InvokeInternal.ExecuteDoublePropertyGet(this, "Height"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Height", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual Int32 Index { get { return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "Index"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual Double Left { get { return InvokerService.InvokeInternal.ExecuteDoublePropertyGet(this, "Left"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Left", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool Locked { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Locked"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Locked", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual string Name { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "Name"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Name", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public virtual string OnAction { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "OnAction"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "OnAction", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Placement { get { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Placement"); } set { InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "Placement", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool PrintObject { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "PrintObject"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "PrintObject", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual Double Top { get { return InvokerService.InvokeInternal.ExecuteDoublePropertyGet(this, "Top"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Top", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Range TopLeftCell { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Range>(this, "TopLeftCell", typeof(NetOffice.ExcelApi.Range)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool Visible { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Visible"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Visible", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual Double Width { get { return InvokerService.InvokeInternal.ExecuteDoublePropertyGet(this, "Width"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Width", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual Int32 ZOrder { get { return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "ZOrder"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.ShapeRange ShapeRange { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.ShapeRange>(this, "ShapeRange", typeof(NetOffice.ExcelApi.ShapeRange)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool AddIndent { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "AddIndent"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "AddIndent", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object AutoScaleFont { get { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "AutoScaleFont"); } set { InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "AutoScaleFont", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool AutoSize { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "AutoSize"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "AutoSize", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual string Caption { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "Caption"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Caption", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Characters Characters { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Characters>(this, "Characters", typeof(NetOffice.ExcelApi.Characters)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Font Font { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Font>(this, "Font", typeof(NetOffice.ExcelApi.Font)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual string Formula { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "Formula"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Formula", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object HorizontalAlignment { get { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "HorizontalAlignment"); } set { InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "HorizontalAlignment", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool LockedText { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "LockedText"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "LockedText", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Orientation { get { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Orientation"); } set { InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "Orientation", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual string Text { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "Text"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Text", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object VerticalAlignment { get { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "VerticalAlignment"); } set { InvokerService.InvokeInternal.ExecuteVariantPropertySet(this, "VerticalAlignment", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual Int32 ReadingOrder { get { return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "ReadingOrder"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ReadingOrder", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Border Border { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Border>(this, "Border", typeof(NetOffice.ExcelApi.Border)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual NetOffice.ExcelApi.Interior Interior { get { return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Interior>(this, "Interior", typeof(NetOffice.ExcelApi.Interior)); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual bool Shadow { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Shadow"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Shadow", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Vertices { get { return InvokerService.InvokeInternal.ExecuteVariantPropertyGet(this, "Vertices"); } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object BringToFront() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "BringToFront"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Copy() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Copy"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="appearance">optional NetOffice.ExcelApi.Enums.XlPictureAppearance Appearance = 2</param> /// <param name="format">optional NetOffice.ExcelApi.Enums.XlCopyPictureFormat Format = -4147</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CopyPicture(object appearance, object format) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CopyPicture", appearance, format); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CopyPicture() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CopyPicture"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="appearance">optional NetOffice.ExcelApi.Enums.XlPictureAppearance Appearance = 2</param> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CopyPicture(object appearance) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CopyPicture", appearance); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Cut() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Cut"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Delete() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Delete"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Duplicate() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Duplicate"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="replace">optional object replace</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Select(object replace) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Select", replace); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Select() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Select"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object SendToBack() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "SendToBack"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="customDictionary">optional object customDictionary</param> /// <param name="ignoreUppercase">optional object ignoreUppercase</param> /// <param name="alwaysSuggest">optional object alwaysSuggest</param> /// <param name="spellLang">optional object spellLang</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CheckSpelling(object customDictionary, object ignoreUppercase, object alwaysSuggest, object spellLang) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CheckSpelling", customDictionary, ignoreUppercase, alwaysSuggest, spellLang); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CheckSpelling() { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CheckSpelling"); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="customDictionary">optional object customDictionary</param> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CheckSpelling(object customDictionary) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CheckSpelling", customDictionary); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="customDictionary">optional object customDictionary</param> /// <param name="ignoreUppercase">optional object ignoreUppercase</param> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CheckSpelling(object customDictionary, object ignoreUppercase) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CheckSpelling", customDictionary, ignoreUppercase); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="customDictionary">optional object customDictionary</param> /// <param name="ignoreUppercase">optional object ignoreUppercase</param> /// <param name="alwaysSuggest">optional object alwaysSuggest</param> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object CheckSpelling(object customDictionary, object ignoreUppercase, object alwaysSuggest) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "CheckSpelling", customDictionary, ignoreUppercase, alwaysSuggest); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="left">Double left</param> /// <param name="top">Double top</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object AddVertex(Double left, Double top) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "AddVertex", left, top); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="vertex">Int32 vertex</param> /// <param name="insert">bool insert</param> /// <param name="left">optional object left</param> /// <param name="top">optional object top</param> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Reshape(Int32 vertex, bool insert, object left, object top) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Reshape", vertex, insert, left, top); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="vertex">Int32 vertex</param> /// <param name="insert">bool insert</param> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Reshape(Int32 vertex, bool insert) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Reshape", vertex, insert); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="vertex">Int32 vertex</param> /// <param name="insert">bool insert</param> /// <param name="left">optional object left</param> [CustomMethod] [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public virtual object Reshape(Int32 vertex, bool insert, object left) { return InvokerService.InvokeInternal.ExecuteVariantMethodGet(this, "Reshape", vertex, insert, left); } #endregion #pragma warning restore } }
34.640609
187
0.544562
[ "MIT" ]
igoreksiz/NetOffice
Source/Excel/Behind/Interfaces/IDrawing.cs
34,123
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Loader : MonoBehaviour { public GameObject gameManager; public GameObject healthManager; public GameObject soundManager; // Start is called before the first frame update void Awake() { if (GameManager.instance == null) { Instantiate(gameManager); } if (HealthManager.instance == null) { Instantiate(healthManager); } if (SoundManager.instance == null) { Instantiate(soundManager); } } }
21.344828
52
0.605816
[ "MIT" ]
Clovisindo/GameJam2021
GamJamJan2021/Assets/Scripts/Loader.cs
621
C#
// <copyright file="Actions.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you 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. // </copyright> using System; using System.Collections.Generic; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Interactions { /// <summary> /// Provides a mechanism for building advanced interactions with the browser. /// </summary> public class Actions : IAction { private IWebDriver driver; private ActionBuilder actionBuilder = new ActionBuilder(); private PointerInputDevice defaultMouse = new PointerInputDevice(PointerKind.Mouse, "default mouse"); private KeyInputDevice defaultKeyboard = new KeyInputDevice("default keyboard"); private IKeyboard keyboard; private IMouse mouse; private CompositeAction action = new CompositeAction(); /// <summary> /// Initializes a new instance of the <see cref="Actions"/> class. /// </summary> /// <param name="driver">The <see cref="IWebDriver"/> object on which the actions built will be performed.</param> public Actions(IWebDriver driver) { this.driver = driver; IHasInputDevices inputDevicesDriver = driver as IHasInputDevices; if (inputDevicesDriver == null) { IWrapsDriver wrapper = driver as IWrapsDriver; while (wrapper != null) { inputDevicesDriver = wrapper.WrappedDriver as IHasInputDevices; if (inputDevicesDriver != null) { this.driver = wrapper.WrappedDriver; break; } wrapper = wrapper.WrappedDriver as IWrapsDriver; } } if (inputDevicesDriver == null) { throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IHasInputDevices.", "driver"); } this.keyboard = inputDevicesDriver.Keyboard; this.mouse = inputDevicesDriver.Mouse; } /// <summary> /// Sends a modifier key down message to the browser. /// </summary> /// <param name="theKey">The key to be sent.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> /// <exception cref="ArgumentException">If the key sent is not is not one /// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, or <see cref="Keys.Alt"/>.</exception> public Actions KeyDown(string theKey) { return this.KeyDown(null, theKey); } /// <summary> /// Sends a modifier key down message to the specified element in the browser. /// </summary> /// <param name="element">The element to which to send the key command.</param> /// <param name="theKey">The key to be sent.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> /// <exception cref="ArgumentException">If the key sent is not is not one /// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, or <see cref="Keys.Alt"/>.</exception> public Actions KeyDown(IWebElement element, string theKey) { if (string.IsNullOrEmpty(theKey)) { throw new ArgumentException("The key value must not be null or empty", "theKey"); } ILocatable target = GetLocatableFromElement(element); this.action.AddAction(new KeyDownAction(this.keyboard, this.mouse, target, theKey)); if (element != null) { this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, TimeSpan.FromMilliseconds(250))); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left)); } this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(theKey[0])); this.actionBuilder.AddAction(new PauseInteraction(this.defaultKeyboard, TimeSpan.FromMilliseconds(100))); return this; } /// <summary> /// Sends a modifier key up message to the browser. /// </summary> /// <param name="theKey">The key to be sent.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> /// <exception cref="ArgumentException">If the key sent is not is not one /// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, or <see cref="Keys.Alt"/>.</exception> public Actions KeyUp(string theKey) { return this.KeyUp(null, theKey); } /// <summary> /// Sends a modifier up down message to the specified element in the browser. /// </summary> /// <param name="element">The element to which to send the key command.</param> /// <param name="theKey">The key to be sent.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> /// <exception cref="ArgumentException">If the key sent is not is not one /// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, or <see cref="Keys.Alt"/>.</exception> public Actions KeyUp(IWebElement element, string theKey) { if (string.IsNullOrEmpty(theKey)) { throw new ArgumentException("The key value must not be null or empty", "theKey"); } ILocatable target = GetLocatableFromElement(element); this.action.AddAction(new KeyUpAction(this.keyboard, this.mouse, target, theKey)); if (element != null) { this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, TimeSpan.FromMilliseconds(250))); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left)); } this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(theKey[0])); return this; } /// <summary> /// Sends a sequence of keystrokes to the browser. /// </summary> /// <param name="keysToSend">The keystrokes to send to the browser.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions SendKeys(string keysToSend) { return this.SendKeys(null, keysToSend); } /// <summary> /// Sends a sequence of keystrokes to the specified element in the browser. /// </summary> /// <param name="element">The element to which to send the keystrokes.</param> /// <param name="keysToSend">The keystrokes to send to the browser.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions SendKeys(IWebElement element, string keysToSend) { if (string.IsNullOrEmpty(keysToSend)) { throw new ArgumentException("The key value must not be null or empty", "keysToSend"); } ILocatable target = GetLocatableFromElement(element); this.action.AddAction(new SendKeysAction(this.keyboard, this.mouse, target, keysToSend)); if (element != null) { this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, TimeSpan.FromMilliseconds(250))); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left)); } foreach (char key in keysToSend) { this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(key)); this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(key)); } return this; } /// <summary> /// Clicks and holds the mouse button down on the specified element. /// </summary> /// <param name="onElement">The element on which to click and hold.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions ClickAndHold(IWebElement onElement) { this.MoveToElement(onElement).ClickAndHold(); return this; } /// <summary> /// Clicks and holds the mouse button at the last known mouse coordinates. /// </summary> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions ClickAndHold() { this.action.AddAction(new ClickAndHoldAction(this.mouse, null)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left)); return this; } /// <summary> /// Releases the mouse button on the specified element. /// </summary> /// <param name="onElement">The element on which to release the button.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions Release(IWebElement onElement) { this.MoveToElement(onElement).Release(); return this; } /// <summary> /// Releases the mouse button at the last known mouse coordinates. /// </summary> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions Release() { this.action.AddAction(new ButtonReleaseAction(this.mouse, null)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left)); return this; } /// <summary> /// Clicks the mouse on the specified element. /// </summary> /// <param name="onElement">The element on which to click.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions Click(IWebElement onElement) { this.MoveToElement(onElement).Click(); return this; } /// <summary> /// Clicks the mouse at the last known mouse coordinates. /// </summary> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions Click() { this.action.AddAction(new ClickAction(this.mouse, null)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left)); return this; } /// <summary> /// Double-clicks the mouse on the specified element. /// </summary> /// <param name="onElement">The element on which to double-click.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions DoubleClick(IWebElement onElement) { this.MoveToElement(onElement).DoubleClick(); return this; } /// <summary> /// Double-clicks the mouse at the last known mouse coordinates. /// </summary> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions DoubleClick() { this.action.AddAction(new DoubleClickAction(this.mouse, null)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left)); return this; } /// <summary> /// Moves the mouse to the specified element. /// </summary> /// <param name="toElement">The element to which to move the mouse.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions MoveToElement(IWebElement toElement) { if (toElement == null) { throw new ArgumentException("MoveToElement cannot move to a null element with no offset.", "toElement"); } ILocatable target = GetLocatableFromElement(toElement); this.action.AddAction(new MoveMouseAction(this.mouse, target)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, 0, 0, TimeSpan.FromMilliseconds(250))); return this; } /// <summary> /// Moves the mouse to the specified offset of the top-left corner of the specified element. /// </summary> /// <param name="toElement">The element to which to move the mouse.</param> /// <param name="offsetX">The horizontal offset to which to move the mouse.</param> /// <param name="offsetY">The vertical offset to which to move the mouse.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY) { ILocatable target = GetLocatableFromElement(toElement); this.action.AddAction(new MoveToOffsetAction(this.mouse, target, offsetX, offsetY)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, offsetX, offsetY, TimeSpan.FromMilliseconds(250))); return this; } /// <summary> /// Moves the mouse to the specified offset of the last known mouse coordinates. /// </summary> /// <param name="offsetX">The horizontal offset to which to move the mouse.</param> /// <param name="offsetY">The vertical offset to which to move the mouse.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions MoveByOffset(int offsetX, int offsetY) { this.action.AddAction(new MoveToOffsetAction(this.mouse, null, offsetX, offsetY)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(CoordinateOrigin.Pointer, offsetX, offsetY, TimeSpan.FromMilliseconds(250))); return this; } /// <summary> /// Right-clicks the mouse on the specified element. /// </summary> /// <param name="onElement">The element on which to right-click.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions ContextClick(IWebElement onElement) { this.MoveToElement(onElement).ContextClick(); return this; } /// <summary> /// Right-clicks the mouse at the last known mouse coordinates. /// </summary> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions ContextClick() { this.action.AddAction(new ContextClickAction(this.mouse, null)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Right)); this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Right)); return this; } /// <summary> /// Performs a drag-and-drop operation from one element to another. /// </summary> /// <param name="source">The element on which the drag operation is started.</param> /// <param name="target">The element on which the drop is performed.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions DragAndDrop(IWebElement source, IWebElement target) { this.ClickAndHold(source).MoveToElement(target).Release(target); return this; } /// <summary> /// Performs a drag-and-drop operation on one element to a specified offset. /// </summary> /// <param name="source">The element on which the drag operation is started.</param> /// <param name="offsetX">The horizontal offset to which to move the mouse.</param> /// <param name="offsetY">The vertical offset to which to move the mouse.</param> /// <returns>A self-reference to this <see cref="Actions"/>.</returns> public Actions DragAndDropToOffset(IWebElement source, int offsetX, int offsetY) { this.ClickAndHold(source).MoveByOffset(offsetX, offsetY).Release(); return this; } /// <summary> /// Builds the sequence of actions. /// </summary> /// <returns>A composite <see cref="IAction"/> which can be used to perform the actions.</returns> public IAction Build() { return this; } /// <summary> /// Performs the currently built action. /// </summary> public void Perform() { IActionExecutor actionExecutor = this.driver as IActionExecutor; if (actionExecutor.IsActionExecutor) { actionExecutor.PerformActions(this.actionBuilder.ToActionSequenceList()); } else { this.action.Perform(); } } /// <summary> /// Gets the <see cref="ILocatable"/> instance of the specified <see cref="IWebElement"/>. /// </summary> /// <param name="element">The <see cref="IWebElement"/> to get the location of.</param> /// <returns>The <see cref="ILocatable"/> of the <see cref="IWebElement"/>.</returns> protected static ILocatable GetLocatableFromElement(IWebElement element) { if (element == null) { return null; } ILocatable target = element as ILocatable; if (target == null) { IWrapsElement wrapper = element as IWrapsElement; while (wrapper != null) { target = wrapper.WrappedElement as ILocatable; if (target != null) { break; } wrapper = wrapper.WrappedElement as IWrapsElement; } } if (target == null) { throw new ArgumentException("The IWebElement object must implement or wrap an element that implements ILocatable.", "element"); } return target; } /// <summary> /// Adds an action to current list of actions to be performed. /// </summary> /// <param name="actionToAdd">The <see cref="IAction"/> to be added.</param> protected void AddAction(IAction actionToAdd) { this.action.AddAction(actionToAdd); } } }
44.210643
154
0.60344
[ "Apache-2.0" ]
AksharaBhanu/selenium
dotnet/src/webdriver/Interactions/Actions.cs
19,941
C#
using Moq; using Namespace2Xml.Formatters; using Namespace2Xml.Scheme; using NUnit.Framework; using Shouldly; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Unity; namespace Namespace2Xml.Tests { public class ProgramTests { private Mock<IStreamFactory> streamFactory; private MemoryStream output; [SetUp] public void Setup() { streamFactory = new Mock<IStreamFactory>(); output = new MemoryStream(); streamFactory .Setup(f => f.CreateInputStream("input.properties")) .Returns<string>(_ => new MemoryStream(Encoding.UTF8.GetBytes("a.x=1"))); streamFactory .Setup(f => f.CreateInputStream("scheme.properties")) .Returns<string>(_ => new MemoryStream(Encoding.UTF8.GetBytes("a.output=yaml"))); streamFactory .Setup(f => f.CreateOutputStream("a.yml", It.IsAny<OutputType>())) .Returns(output); Program.Container .RegisterType<IProfileReader, ProfileReader>() .RegisterInstance(streamFactory.Object); } [Test] public async Task ShouldRun() { var exitCode = await Program.Main(new[] { "-i", "input.properties", "-s", "scheme.properties" }); exitCode.ShouldBe(0); Encoding.UTF8.GetString(output.ToArray()) .Trim() .ShouldBe("x: 1"); } [Test] public async Task ShouldLogUnexpectedError() { var exitCode = await Program.Main(new[] { "-i", "invalid.properties", "-s", "scheme.properties" }); exitCode.ShouldBe(1); output.Length.ShouldBe(0); } [Test] public async Task ShouldReturnOneUnexpectedError() { var reader = new Mock<IProfileReader>(); reader.Setup(r => r.ReadFiles(It.IsAny<IEnumerable<string>>(), default)) .Throws<TestException>(); Program.Container.RegisterInstance(reader.Object); var exitCode = await Program.Main(new[] { "-i", "input.properties", "-s", "scheme.properties" }); exitCode.ShouldBe(1); output.Length.ShouldBe(0); } private class TestException : Exception { } } }
27.326316
97
0.53698
[ "Apache-2.0" ]
isap-team/namespace2xml
tests/ProgramTests.cs
2,598
C#
using System; using System.Text; using System.Text.Json; using Xunit; namespace JsonWebToken.Tests { public abstract class AlgorithmTests<T> where T : class, IAlgorithm { public abstract bool TryParse(ReadOnlySpan<byte> value, out T algorithm); public virtual void TryParse_Success(T expected) { var parsed = TryParse(expected.Utf8Name, out var algorithm); Assert.True(parsed); Assert.NotNull(algorithm); Assert.Same(expected, algorithm); } public abstract bool TryParseSlow(ref Utf8JsonReader reader, out T algorithm); public virtual void TryParseSlow_Success(T expected) { var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes("\"" + expected.Name + "\"")); reader.Read(); var parsed = TryParseSlow(ref reader, out var algorithm); Assert.True(parsed); Assert.NotNull(algorithm); Assert.Same(expected, algorithm); } [Fact] public void TryParseEmpty_ThrowException() { var parsed = TryParse(ReadOnlySpan<byte>.Empty, out var algorithm); Assert.False(parsed); Assert.Null(algorithm); } } }
31.475
97
0.613185
[ "MIT" ]
lochgeo/Jwt
test/JsonWebToken.Tests/AlgorithmTests.cs
1,261
C#
using System; using System.Collections.Generic; using System.Text; using PretWorks.Helpers.Result.Interfaces; namespace PretWorks.Helpers.Result.Models { public abstract class ResultModel : IResult { protected ResultModel(bool success) { Success = success; Failed = !success; } public bool Success { get; set; } public bool Failed { get; set; } public List<string> Messages { get; set; } = new List<string>(); public override string ToString() { return ToDelimitedString(""); } public string ToDelimitedString(string delimiter) { var builder = new StringBuilder(); foreach (var message in Messages) { builder.AppendFormat("{0}{1}", message, delimiter); } return builder.ToString(); } public Dictionary<string, string> Keys { get; set; } = new Dictionary<string, string>(); public Exception Exception { get; set; } } public abstract class ResultModel<TValue> : ResultModel, IResult<TValue> { protected ResultModel(bool success) : base(success) { } public TValue Value { get; set; } = default(TValue); } }
24.923077
96
0.577932
[ "MIT" ]
XGNPreTender/PretWorks.Helpers.Result
PretWorks.Helpers.Result/Models/ResultModel.cs
1,298
C#
using System; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; namespace BlazorBattles.Client.Services { public class BananaService : IBananaService { private readonly HttpClient _http; public event Action OnChange; public int Bananas { get; set; } public BananaService(HttpClient http) { _http = http; } public void EatBananas(int amount) { Bananas -= amount; BananasChanged(); } void BananasChanged() => OnChange.Invoke(); public async Task AddBananas(int amount) { var result = await _http.PutAsJsonAsync("api/User/AddBananas", amount); Bananas = await result.Content.ReadFromJsonAsync<int>(); BananasChanged(); } public async Task GetBananas() { Bananas = await _http.GetFromJsonAsync<int>("api/User/GetBananas"); BananasChanged(); } } }
23.181818
83
0.586275
[ "MIT" ]
WeekendWarrior/BlazorBattles
BlazorBattles/Client/Services/BananaService.cs
1,022
C#
// ----------------------------------------------------------------------- // <once-generated> // 这个文件只生成一次,再次生成不会被覆盖。 // 可以在此类进行继承重写来扩展基类 CashLogControllerBase // </once-generated> // // <copyright file="CashLog.cs"> // KaPai©2019 Microsoft Corporation. All rights reserved. // </copyright> // <site></site> // <last-editor>KaPai</last-editor> // ----------------------------------------------------------------------- using System; using System.Threading.Tasks; using OSharp.Filter; using KaPai.Pay.CashMoney; using KaPai.Pay.CashMoney.Dtos; using KaPai.Pay.Identity.Entities; using Microsoft.AspNetCore.Identity; using OSharp.AspNetCore.UI; using OSharp.Data; namespace KaPai.Pay.Web.Areas.Admin.Controllers { /// <summary> /// 管理控制器: 提现记录信息 /// </summary> public class CashLogController : CashLogControllerBase { protected readonly UserManager<User> UserManager; /// <summary> /// 初始化一个<see cref="CashLogController"/>类型的新实例 /// </summary> public CashLogController(ICashMoneyContract cashMoneyContract, IFilterService filterService, UserManager<User> userManager) : base(cashMoneyContract, filterService) { this.UserManager = userManager; } public override async Task<AjaxResult> Create(MerchantCashInputLimit[] dtos) { // 此方法留给管理使用 Check.NotNull(dtos, nameof(dtos)); if (User.IsInRole("商户")) { int userid = Convert.ToInt32(UserManager.GetUserId(User)); OperationResult result = await CashMoneyContract.CreateCashLogs(userid, dtos[0]); return result.ToAjaxResult(); } return new OperationResult(OperationResultType.Error).ToAjaxResult(); } } }
30.04918
97
0.59138
[ "Apache-2.0" ]
a952135763/osharp
samples/kapai/KaPai.Pay.Web/Areas/Admin/Controllers/CashMoney/CashLogController.cs
1,972
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; using Verse.AI; namespace WallStuff { class JoyGiver_WatchWallBuilding : JoyGiver_WatchBuilding { private static List<Thing> tmpCandidates = new List<Thing>(); public override Job TryGiveJob(Pawn pawn) { //jcLog.Warning(pawn.Name + " Try Give job"); Thing thing = this.FindBestGame(pawn, false, IntVec3.Invalid); if (thing != null) { //jcLog.Warning(pawn.Name + " Found Thing"); return this.TryGivePlayJob(pawn, thing); } return null; } public override Job TryGiveJobWhileInBed(Pawn pawn) { //jcLog.Warning(pawn.Name + " Try Give job in bed"); Thing thing = this.FindBestGame(pawn, true, IntVec3.Invalid); if (thing != null) { //jcLog.Warning(pawn.Name + " Found Thing"); return this.TryGivePlayJobWhileInBed(pawn, thing); } return null; } private Thing FindBestGame(Pawn pawn, bool inBed, IntVec3 partySpot) { //jcLog.Warning(pawn.Name + " Find Best"); tmpCandidates.Clear(); this.GetSearchSet(pawn, tmpCandidates); if (tmpCandidates.Count == 0) { return null; } Predicate<Thing> predicate = (Thing t) => this.CanInteractWith(pawn, t, inBed); if (partySpot.IsValid) { Predicate<Thing> oldValidator = predicate; predicate = ((Thing x) => GatheringsUtility.InGatheringArea(x.Position, partySpot, pawn.Map) && oldValidator(x)); } IntVec3 position = pawn.Position; Map map = pawn.Map; List<Thing> searchSet = tmpCandidates; Predicate<Thing> validator = predicate; Thing thing = searchSet[0]; Thing result = GenClosest.ClosestThing_Global(position, searchSet, 9999f, validator, null); tmpCandidates.Clear(); return result; } protected override void GetSearchSet(Pawn pawn, List<Thing> outCandidates) { outCandidates.Clear(); if (this.def.thingDefs == null) { return; } if (this.def.thingDefs.Count == 1) { outCandidates.AddRange(pawn.Map.listerThings.ThingsOfDef(this.def.thingDefs[0])); } else { for (int i = 0; i < this.def.thingDefs.Count; i++) { ThingDef thingDef = this.def.thingDefs[i]; List<Thing> thingsFound = pawn.Map.listerThings.ThingsOfDef(thingDef); outCandidates.AddRange(thingsFound); } } } protected override bool CanInteractWith(Pawn pawn, Thing t, bool inBed) { //jcLog.Warning(pawn.Name + " Can Pawn interact with thing ??"); if (!CanInteractCheck(pawn, t, inBed)) { //jcLog.Warning(pawn.Name + " No :("); return false; } if (inBed) { //jcLog.Warning(pawn.Name + " In Bed"); Building_Bed bed = pawn.CurrentBed(); if (t.def.building.isEdifice) { //jcLog.Warning(pawn.Name + " is ediface"); return WatchBuildingUtility.CanWatchFromBed(pawn, bed, t); } else { //jcLog.Warning(pawn.Name + " is not ediface"); return WatchWallBuildingUtility.CanWatchFromBed(pawn, bed, t); } } return true; } private bool CanInteractCheck(Pawn pawn, Thing t, bool inBed) { //jcLog.Warning(pawn.Name + " is building ediface ?"); if (t.def.building.isEdifice) { //jcLog.Warning(pawn.Name + " yes"); return base.CanInteractWith(pawn, t, inBed); } else { //jcLog.Warning(pawn.Name + " no"); return CanInteractWithCheck(pawn, t, inBed); } } private bool CanInteractWithCheck(Pawn pawn, Thing t, bool inBed) { //jcLog.Warning(pawn.Name + " Can Pawn reserve thing ?"); if (!pawn.CanReserve(t, this.def.jobDef.joyMaxParticipants, -1, null, false)) { return false; } //jcLog.Warning(pawn.Name + " Is thing forbidden ?"); if (t.IsForbidden(pawn)) { return false; } //jcLog.Warning(pawn.Name + " Is it socially proper ?"); if (!t.IsSociallyProper(pawn)) { return false; } //jcLog.Warning(pawn.Name + " Politically ?"); if (!t.IsPoliticallyProper(pawn)) { return false; } CompPowerTrader compPowerTrader = t.TryGetComp<CompPowerTrader>(); //jcLog.Warning("1" + (compPowerTrader == null)); //jcLog.Warning("2" + (compPowerTrader.PowerOn)); //jcLog.Warning("3" + (!this.def.unroofedOnly)); //jcLog.Warning("4" + (!WatchWallBuildingUtility.GetAdjustedCenter(t).Roofed(t.Map))); //jcLog.Warning("5" + ((compPowerTrader == null || compPowerTrader.PowerOn))); //jcLog.Warning("6" + ((!this.def.unroofedOnly || !WatchWallBuildingUtility.GetAdjustedCenter(t).Roofed(t.Map)))); return (compPowerTrader == null || compPowerTrader.PowerOn) && (!this.def.unroofedOnly || !WatchWallBuildingUtility.GetAdjustedCenter(t).Roofed(t.Map)); } protected override Job TryGivePlayJob(Pawn pawn, Thing t) { //jcLog.Warning(pawn.Name + " Try Give play job"); IntVec3 c; Building t2; if (t.def.building.isEdifice) { //jcLog.Warning(pawn.Name + " It's An Ediface"); if (!WatchWallBuildingUtility.TryFindBestWatchCell(t, pawn, this.def.desireSit, out c, out t2)) { return null; } } else { //jcLog.Warning(pawn.Name + " It's NOT An Ediface"); if (!WatchBuildingUtility.TryFindBestWatchCell(t, pawn, this.def.desireSit, out c, out t2)) { return null; } } //jcLog.Warning(pawn.Name + " Return a job !"); return new Job(this.def.jobDef, t, c, t2); } } }
37.407609
164
0.510243
[ "Unlicense" ]
JohnCannon87/RimworldWallStuff
1.1/Source/Television/JoyGiver_WatchWallBuilding.cs
6,885
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Steeltoe.Common; using Steeltoe.Common.Hosting; using Steeltoe.Extensions.Configuration.Kubernetes; using Steeltoe.Management.Kubernetes; namespace Kubernetes { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureAppConfiguration((context, builder) => { builder.AddKubernetes(loggerFactory: GetLoggerFactory()); if (Platform.IsKubernetes) { } }) .AddKubernetesActuators(); private static ILoggerFactory GetLoggerFactory() { IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace)); serviceCollection.AddLogging(builder => builder.AddConsole((opts) => { opts.DisableColors = true; })); serviceCollection.AddLogging(builder => builder.AddDebug()); return serviceCollection.BuildServiceProvider().GetService<ILoggerFactory>(); } } }
34.553191
93
0.607759
[ "Apache-2.0" ]
SteeltoeOSS/Samples
Configuration/src/Kubernetes/Program.cs
1,624
C#
using System.Collections.Generic; using Mobile.BuildTools.Configuration; namespace E2EApp.Views { public partial class AppConfig { private const string Default = nameof(Default); public AppConfig() { InitializeComponent(); } protected override void OnAppearing() { var environments = new List<string> { Default }; environments.AddRange(ConfigurationManager.Environments); environmentsPicker.ItemsSource = environments; environmentsPicker.SelectedItem = Default; UpdateLabels(); } private void Button_Clicked(object sender, System.EventArgs e) { var selectedItem = (string)environmentsPicker.SelectedItem; if (selectedItem == Default) { ConfigurationManager.Reset(); } else { ConfigurationManager.Transform(selectedItem); } UpdateLabels(); } private void UpdateLabels() { fooLabel.Text = $"foo: {ConfigurationManager.AppSettings["foo"]}"; barLabel.Text = $"bar: {ConfigurationManager.AppSettings["bar"]}"; environmentLabel.Text = $"Environment: {ConfigurationManager.AppSettings["Environment"]}"; barLabel.Text = $"test: {ConfigurationManager.ConnectionStrings["test"].ConnectionString}"; } } }
31.787234
104
0.578983
[ "MIT" ]
T3zler/Mobile.BuildTools
E2E/E2EApp/E2EApp/Views/AppConfig.xaml.cs
1,496
C#
using System; using System.IO; using System.Net; using System.Net.Sockets; using FreeRDP; using Gtk; using System.Threading; namespace Screenary.Client { public partial class CreateSessionDialog : Gtk.Dialog { private IUserAction observer; public CreateSessionDialog(IUserAction observer) { this.Build(); this.observer = observer; } /** * Send user information to OnUserCreateSession **/ protected void OnButtonCreateClicked(object sender, System.EventArgs e) { string username; string password; username = txtUsername.Text; password = txtPassword.Text; observer.OnUserCreateSession(username, password); this.Destroy(); } protected void OnButtonCancelClicked(object sender, System.EventArgs e) { this.Destroy(); } } }
18.295455
73
0.709317
[ "Apache-2.0" ]
Screenary/Screenary
Client/Widgets/CreateSessionDialog.cs
805
C#
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text.RegularExpressions; namespace Verlite { /// <summary> /// A semantic version. /// </summary> public struct SemVer : IComparable<SemVer>, IEquatable<SemVer> { /// <summary> /// The major component of the version. /// </summary> public int Major { readonly get; set; } /// <summary> /// The minor component of the version. /// </summary> public int Minor { readonly get; set; } /// <summary> /// The patch component of the version. /// </summary> public int Patch { readonly get; set; } /// <summary> /// The prerelease component of the version. /// </summary> public string? Prerelease { readonly get; set; } /// <summary> /// The build metadata component of the version. /// </summary> public string? BuildMetadata { readonly get; set; } /// <summary> /// The version without any prerelease or metadata, for which a prerelease would be working toward. /// </summary> public SemVer DestinedVersion => new(Major, Minor, Patch); /// <summary> /// Initializes a new instance of the <see cref="SemVer"/> class. /// </summary> /// <param name="major">The major component.</param> /// <param name="minor">The minor component.</param> /// <param name="patch">The patch component.</param> /// <param name="prerelease">The prerelease component.</param> /// <param name="buildMetadata">The build metadata component.</param> /// <exception cref="ArgumentException">Prerelease contains an invalid character</exception> /// <exception cref="ArgumentException">Build metadata contains an invalid character</exception> public SemVer(int major, int minor, int patch, string? prerelease = null, string? buildMetadata = null) { if (prerelease is not null && !IsValidIdentifierString(prerelease)) throw new ArgumentException("Prerelease contains an invalid character", nameof(prerelease)); if (buildMetadata is not null && !IsValidIdentifierString(buildMetadata)) throw new ArgumentException("Build metadata contains an invalid character", nameof(buildMetadata)); Major = major; Minor = minor; Patch = patch; Prerelease = prerelease; BuildMetadata = buildMetadata; } private static readonly Regex VersionRegex = new( @"^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.Multiline); /// <summary> /// Attempt to parse a semantic version from a string. /// </summary> /// <param name="input">A string possibly containing only a semantic version.</param> /// <param name="version">If successful, the parsed version.</param> /// <returns>If parsing was successful.</returns> public static bool TryParse(string input, [NotNullWhen(true)] out SemVer? version) { version = null; var match = VersionRegex.Match(input); if (!match.Success) return false; bool majorGood = TryParseInt(match.Groups["major"].Value, out int major); bool minorGood = TryParseInt(match.Groups["minor"].Value, out int minor); bool patchGood = TryParseInt(match.Groups["patch"].Value, out int patch); Debug.Assert(majorGood && minorGood && patchGood); string? prerelease = match.Groups["prerelease"].Value; string? buildMetadata = match.Groups["buildmetadata"].Value; if (string.IsNullOrEmpty(prerelease)) prerelease = null; else Debug.Assert(IsValidIdentifierString(prerelease)); if (string.IsNullOrEmpty(buildMetadata)) buildMetadata = null; else Debug.Assert(IsValidIdentifierString(buildMetadata)); version = new SemVer(major, minor, patch, prerelease, buildMetadata); return true; } /// <summary> /// Parse a semantic version from a string. /// </summary> /// <param name="input">A string containing only a semantic version.</param> /// <exception cref="FormatException">The input was not in the expected format.</exception> /// <returns>A semantic version read from the string.</returns> public static SemVer Parse(string input) { if (!TryParse(input, out SemVer? version)) throw new FormatException("The input was not in the expected format."); return version.Value; } /// <summary> /// Describes whether a char is a valid build/tag character. /// </summary> /// <param name="input">The input char to test.</param> /// <returns>If input is valid.</returns> public static bool IsValidIdentifierCharacter(char input) { return input switch { >= '0' and <= '9' => true, >= 'a' and <= 'z' => true, >= 'A' and <= 'Z' => true, '.' => true, '-' => true, _ => false, }; } /// <summary> /// Describes whether a string contains only valid build/tag characters. /// </summary> /// <param name="input">The input string to test.</param> /// <returns>If input is valid.</returns> public static bool IsValidIdentifierString(string input) { if (string.IsNullOrEmpty(input)) return false; foreach (char c in input) if (!IsValidIdentifierCharacter(c)) return false; return true; } private static (int value, int charCount) SelectOrdinals(string input) { int got = 0; for (int i = 0; i < input.Length; i++) { if (!char.IsDigit(input[i])) break; got++; } int value = int.Parse(input.Substring(0, got), NumberStyles.Integer, CultureInfo.InvariantCulture); return (value, got); } private static bool TryParseInt(string input, out int ret) { return int.TryParse(input, NumberStyles.Integer, CultureInfo.InvariantCulture, out ret); } /// <summary> /// Compares the prerelease taking into account ordinals within the string. /// </summary> /// <returns><c>-1</c> if <paramref name="left"/> precedes <paramref name="right"/>, <c>0</c> if they have the same precedence, and <c>1</c> if <paramref name="right"/> precedes the <paramref name="left"/>.</returns> public static int ComparePrerelease(string left, string right) { int minLen = Math.Min(left.Length, right.Length); for (int i = 0; i < minLen; i++) { char l = left[i]; char r = right[i]; if (char.IsDigit(l) && char.IsDigit(r)) { var (leftOrdinal, leftOrdinalLength) = SelectOrdinals(left.Substring(i)); var (rightOrdinal, rightOrdinalLength) = SelectOrdinals(right.Substring(i)); int cmpOrdinal = leftOrdinal.CompareTo(rightOrdinal); if (cmpOrdinal != 0) return cmpOrdinal; Debug.Assert(leftOrdinalLength == rightOrdinalLength); i += leftOrdinalLength - 1; } if (l != r) return l.CompareTo(r); } return left.Length.CompareTo(right.Length); } /// <summary> /// Return the sematic version formatted as a string. /// </summary> public override string ToString() { string ret = $"{Major}.{Minor}.{Patch}"; if (Prerelease is not null) ret += $"-{Prerelease}"; if (BuildMetadata is not null) ret += $"+{BuildMetadata}"; return ret; } /// <summary> /// Gets the hash code. /// </summary> [ExcludeFromCodeCoverage] public override int GetHashCode() => Major.GetHashCode() ^ Minor.GetHashCode() ^ Patch.GetHashCode() ^ (Prerelease?.GetHashCode() ?? 0) ^ (BuildMetadata?.GetHashCode() ?? 0); /// <summary> /// Describes the equality to another version, including <see cref="Prerelease"/> and <see cref="BuildMetadata"/> components. /// </summary> public override bool Equals(object? obj) => obj is SemVer ver && this == ver; /// <summary> /// Describes the equality to another version, including <see cref="Prerelease"/> and <see cref="BuildMetadata"/> components. /// </summary> public bool Equals(SemVer other) => this == other; /// <summary> /// Describes the equality to another version, including <see cref="Prerelease"/> and <see cref="BuildMetadata"/> components. /// </summary> public static bool operator ==(SemVer left, SemVer right) => left.Major == right.Major && left.Minor == right.Minor && left.Patch == right.Patch && left.Prerelease == right.Prerelease && left.BuildMetadata == right.BuildMetadata; /// <summary> /// Describes the inequality to another version, including <see cref="Prerelease"/> and <see cref="BuildMetadata"/> components. /// </summary> public static bool operator !=(SemVer left, SemVer right) => !(left == right); /// <summary> /// Compares one version to the other for determining precedence. /// Does not take into account the <see cref="BuildMetadata"/> component. /// </summary> public int CompareTo(SemVer other) { static bool areDifferent(int left, int right, out int result) { result = left.CompareTo(right); return result != 0; } if (areDifferent(Major, other.Major, out int compareResult)) return compareResult; if (areDifferent(Minor, other.Minor, out compareResult)) return compareResult; if (areDifferent(Patch, other.Patch, out compareResult)) return compareResult; if (Prerelease is null && other.Prerelease is null) return 0; else if (other.Prerelease is null) return -1; else if (Prerelease is null) return 1; else return ComparePrerelease(Prerelease, other.Prerelease); } /// <summary> /// Compares one version to the other for determining precedence. /// Does not take into account the <see cref="BuildMetadata"/> component. /// </summary> public static bool operator <(SemVer left, SemVer right) => left.CompareTo(right) < 0; /// <summary> /// Compares one version to the other for determining precedence. /// Does not take into account the <see cref="BuildMetadata"/> component. /// </summary> public static bool operator <=(SemVer left, SemVer right) => left.CompareTo(right) <= 0; /// <summary> /// Compares one version to the other for determining precedence. /// Does not take into account the <see cref="BuildMetadata"/> component. /// </summary> public static bool operator >(SemVer left, SemVer right) => left.CompareTo(right) > 0; /// <summary> /// Compares one version to the other for determining precedence. /// Does not take into account the <see cref="BuildMetadata"/> component. /// </summary> public static bool operator >=(SemVer left, SemVer right) => left.CompareTo(right) >= 0; } }
35.843537
239
0.669672
[ "MIT" ]
AshleighAdams/Verlite
src/Verlite.Core/SemVer.cs
10,538
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Minerva { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmSplash()); } } }
22.173913
65
0.611765
[ "MIT" ]
ahnaylor93/Minerva
Minerva/Minerva/Program.cs
512
C#
namespace Alpaca.Markets; /// <summary> /// Exchanges supported by Alpaca REST API. /// </summary> [JsonConverter(typeof(ExchangeEnumConverter))] [SuppressMessage("ReSharper", "StringLiteralTypo")] public enum Exchange { /// <summary> /// Unknown exchange (i.e. one not supported by this version of SDK). /// </summary> [UsedImplicitly] [EnumMember(Value = "UNKNOWN")] Unknown, /// <summary> /// NYSE American Stock Exchange. /// </summary> [UsedImplicitly] [EnumMember(Value = "NYSEMKT")] NyseMkt, /// <summary> /// NYSE Arca Stock Exchange. /// </summary> [UsedImplicitly] [EnumMember(Value = "NYSEARCA")] NyseArca, /// <summary> /// New York Stock Exchange (NYSE) /// </summary> [UsedImplicitly] [EnumMember(Value = "NYSE")] Nyse, /// <summary> /// Nasdaq Stock Market. /// </summary> [UsedImplicitly] [EnumMember(Value = "NASDAQ")] Nasdaq, /// <summary> /// BATS Global Market. /// </summary> [UsedImplicitly] [EnumMember(Value = "BATS")] Bats, /// <summary> /// American Stock Exchange (AMEX) /// </summary> [UsedImplicitly] [EnumMember(Value = "AMEX")] Amex, /// <summary> /// Archipelago Stock Exchange (ARCA). /// </summary> [UsedImplicitly] [EnumMember(Value = "ARCA")] Arca, /// <summary> /// International Exchange (IEX). /// </summary> [UsedImplicitly] [EnumMember(Value = "IEX")] Iex, /// <summary> /// Over the counter (OTC). /// </summary> [UsedImplicitly] [EnumMember(Value = "OTC")] Otc }
20.7125
73
0.570308
[ "Apache-2.0" ]
OlegRa/alpaca-trade-api-csharp
Alpaca.Markets/Enums/Exchange.cs
1,659
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.Yandex.Inputs { public sealed class ComputeDiskDiskPlacementPolicyGetArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies Disk Placement Group id. /// </summary> [Input("diskPlacementGroupId", required: true)] public Input<string> DiskPlacementGroupId { get; set; } = null!; public ComputeDiskDiskPlacementPolicyGetArgs() { } } }
28.615385
88
0.680108
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-yandex
sdk/dotnet/Inputs/ComputeDiskDiskPlacementPolicyGetArgs.cs
744
C#
using System; using System.IO; using System.Windows.Forms; using com.dyndns_server.yo3explorer.yo3explorer.Archive; using DiscUtils; using DiscUtils.Fat; using DiscUtils.Iso9660; using DiscUtils.Udf; using libazusax360; using moe.yo3explorer.azusa.Control.DatabaseIO; using moe.yo3explorer.azusa.Control.FilesystemMetadata.Entity; using moe.yo3explorer.azusa.MediaLibrary.Entity; using moe.yo3explorer.azusa.Utilities.FolderMapper.Control; namespace moe.yo3explorer.azusa.Control.FilesystemMetadata.Boundary { internal static class FilesystemMetadataGatherer { private static readonly byte[] cdromSyncBytes = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, }; public static void Gather(Media medium, Stream infile) { string failed = ""; XboxISOFileSource xboxIso = XboxISOFileSource.TryOpen(infile); if (xboxIso != null) { XDvdFsFileSystemEntry xdvdfs = xboxIso.GetFileSystem(); Gather(medium, xdvdfs, null); infile.Dispose(); return; } failed += "XDVDFS\n"; if (CDReader.Detect(infile)) { CDReader cdReader = new CDReader(infile, true, false); Gather(medium, cdReader.Root, null); infile.Dispose(); return; } failed += "ISO9660\n"; if (UdfReader.Detect(infile)) { UdfReader udfReader = new UdfReader(infile); if (udfReader != null) { try { Gather(medium, udfReader.Root, null); return; } catch (Exception) { AzusaContext.GetInstance().DatabaseDriver.ForgetFilesystemContents(medium.Id); } } } failed += "UDF\n"; if (FatFileSystem.Detect(infile)) { FatFileSystem fat = new FatFileSystem(infile); Gather(medium, fat.Root, null); infile.Dispose(); return; } failed += "FAT32\n"; if (infile.Length < 3200) { FileStream fileStream = infile as FileStream; if (fileStream != null) { fileStream.Dispose(); FileInfo fi = new FileInfo(fileStream.Name); Stream gdRomStream = GDROMReader.BuildGdRomStream(fi); if (CDReader.Detect(gdRomStream)) { CDReader cdReader = new CDReader(gdRomStream, true, false); Gather(medium, cdReader.Root, null); infile.Dispose(); return; } } } failed += "GD-ROM\n"; infile.Position = 0; byte[] firstSector = new byte[2352]; if (infile.Read(firstSector, 0, firstSector.Length) == firstSector.Length) { byte[] firstSectorSync = new byte[cdromSyncBytes.Length]; Array.Copy(firstSector, firstSectorSync, cdromSyncBytes.Length); if (memcmp(cdromSyncBytes,firstSectorSync)) { byte mode = firstSector[15]; if (mode == 1 || mode == 2) { infile.Position = 0; RawCdRomStream rawCdRomStream = new RawCdRomStream(infile); Gather(medium, rawCdRomStream); return; } } } failed += "RAW CD-ROM"; MessageBox.Show("Konnte kein Dateisystem erkennen. Versucht wurden:" + failed); } private static bool memcmp(byte[] l, byte[] r) { if (l.Length != r.Length) return false; for (int i = 0; i < l.Length; i++) { if (l[i] != r[i]) return false; } return true; } public static void Gather(Media medium, DriveInfo driveInfo) { Gather(medium, driveInfo.RootDirectory,null); } private static void Gather(Media medium, XDvdFsFileSystemEntry entry, FilesystemMetadataEntity parent) { IDatabaseDriver dbDriver = AzusaContext.GetInstance().DatabaseDriver; FilesystemMetadataEntity dirEntity = new FilesystemMetadataEntity(); dirEntity.FullName = entry.FullPath; dirEntity.IsDirectory = entry.IsFolder; dirEntity.MediaId = medium.Id; dirEntity.Modified = null; dirEntity.ParentId = parent != null ? parent.Id : -1; if (entry.IsFolder) { dbDriver.AddFilesystemInfo(dirEntity); foreach (XDvdFsFileSystemEntry subfile in entry.Files) { Gather(medium, subfile, dirEntity); } } else { int readSize = (int)Math.Min(2048, entry.LogicalFileSize); byte[] buffer = new byte[readSize]; Stream inStream = entry.GetStream(); readSize = inStream.Read(buffer, 0, readSize); inStream.Close(); Array.Resize(ref buffer, readSize); dirEntity.Header = buffer; dbDriver.AddFilesystemInfo(dirEntity); } } private static void Gather(Media medium, DiscDirectoryInfo ddi, FilesystemMetadataEntity parent) { IDatabaseDriver dbDriver = AzusaContext.GetInstance().DatabaseDriver; FilesystemMetadataEntity dirEntity = new FilesystemMetadataEntity(); dirEntity.FullName = ddi.FullName; dirEntity.IsDirectory = true; dirEntity.MediaId = medium.Id; dirEntity.Modified = ddi.LastWriteTime; dirEntity.ParentId = parent != null ? parent.Id : -1; dbDriver.AddFilesystemInfo(dirEntity); foreach (DiscDirectoryInfo subdir in ddi.GetDirectories()) { Gather(medium, subdir, dirEntity); } foreach (DiscFileInfo file in ddi.GetFiles()) { FilesystemMetadataEntity fileEntity = new FilesystemMetadataEntity(); fileEntity.FullName = file.FullName; fileEntity.IsDirectory = false; fileEntity.MediaId = medium.Id; fileEntity.Modified = file.LastWriteTime; fileEntity.ParentId = dirEntity.Id; fileEntity.Size = file.Length; int readSize = (int)Math.Min(2048, file.Length); byte[] buffer = new byte[readSize]; Stream inStream = file.OpenRead(); readSize = inStream.Read(buffer, 0, readSize); inStream.Close(); Array.Resize(ref buffer, readSize); fileEntity.Header = buffer; dbDriver.AddFilesystemInfo(fileEntity); } } private static void Gather(Media medium, DirectoryInfo di, FilesystemMetadataEntity parent) { IDatabaseDriver dbDriver = AzusaContext.GetInstance().DatabaseDriver; FilesystemMetadataEntity dirEntity = new FilesystemMetadataEntity(); dirEntity.FullName = di.FullName.Replace(di.Root.FullName, ""); dirEntity.IsDirectory = true; dirEntity.MediaId = medium.Id; dirEntity.Modified = di.LastWriteTime; dirEntity.ParentId = parent != null ? parent.Id : -1; dbDriver.AddFilesystemInfo(dirEntity); foreach (DirectoryInfo subdir in di.GetDirectories()) { Gather(medium, subdir, dirEntity); } foreach (FileInfo file in di.GetFiles()) { FilesystemMetadataEntity fileEntity = new FilesystemMetadataEntity(); fileEntity.FullName = file.FullName; fileEntity.IsDirectory = false; fileEntity.MediaId = medium.Id; fileEntity.Modified = file.LastWriteTime; fileEntity.ParentId = dirEntity.Id; fileEntity.Size = file.Length; int readSize = (int)Math.Min(2048, file.Length); byte[] buffer = new byte[readSize]; Stream inStream = file.OpenRead(); readSize = inStream.Read(buffer, 0, readSize); inStream.Close(); Array.Resize(ref buffer, readSize); fileEntity.Header = buffer; dbDriver.AddFilesystemInfo(fileEntity); } } } }
36.979675
110
0.525888
[ "BSD-2-Clause" ]
feyris-tan/azusa
AzusaERP/Control/FilesystemMetadata/FilesystemMetadataGatherer.cs
9,099
C#
using System; using System.IO; namespace RogueBackup { class Program { static void Main(string[] args) { #if !DEBUG MainImpl(args); #else WriteLineDelegate log = Console.WriteLine; try { MainImpl(args); } catch (BoringException e) { // for exceptions that may happen before core loop log($"Error: {e.Message}"); log("Press any key to exit."); Console.ReadKey(); } catch (Exception e) { log(); log("*** Crash log ***"); log(); log(e.ToString()); log(); log("Program has crashed. Press any key to exit."); Console.ReadKey(); throw; } #endif } static void MainImpl(string[] args) { var userIO = new ConsoleUserIO(); var config = new Config(); CommandLine.Parse(args, config); var service = new Service(config); var mainMenu = new MainMenu(userIO, config, service); mainMenu.Welcome(); var interpreter = mainMenu as Repl; while (interpreter != null) { try { interpreter = interpreter.Step(); } catch (Exception e) when (e is IOException) { userIO.WriteLine($"System error: {e.Message}"); } catch (BoringException e) { userIO.WriteLine($"Error: {e.Message}"); } } } } }
26.761194
67
0.415505
[ "MIT" ]
ShadowsInRain/RogueBackup
src/RogueBackup/Program.cs
1,795
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.Maui.Controls.Internals; using static System.String; namespace Microsoft.Maui.Controls.Internals { [EditorBrowsable(EditorBrowsableState.Never)] public static class NativeBindingHelpers { public static void SetBinding<TNativeView>(TNativeView target, string targetProperty, BindingBase bindingBase, string updateSourceEventName = null) where TNativeView : class { var binding = bindingBase as Binding; //This will allow setting bindings from Xaml by reusing the MarkupExtension if (IsNullOrEmpty(updateSourceEventName) && binding != null && !IsNullOrEmpty(binding.UpdateSourceEventName)) updateSourceEventName = binding.UpdateSourceEventName; INotifyPropertyChanged eventWrapper = null; if (!IsNullOrEmpty(updateSourceEventName)) eventWrapper = new EventWrapper(target, targetProperty, updateSourceEventName); SetBinding(target, targetProperty, bindingBase, eventWrapper); } public static void SetBinding<TNativeView>(TNativeView target, string targetProperty, BindingBase bindingBase, INotifyPropertyChanged propertyChanged) where TNativeView : class { if (target == null) throw new ArgumentNullException(nameof(target)); if (IsNullOrEmpty(targetProperty)) throw new ArgumentNullException(nameof(targetProperty)); var binding = bindingBase as Binding; var proxy = BindableObjectProxy<TNativeView>.BindableObjectProxies.GetValue(target, (TNativeView key) => new BindableObjectProxy<TNativeView>(key)); BindableProperty bindableProperty = null; propertyChanged = propertyChanged ?? target as INotifyPropertyChanged; var propertyType = target.GetType().GetProperty(targetProperty)?.PropertyType; var defaultValue = target.GetType().GetProperty(targetProperty)?.GetMethod.Invoke(target, new object[] { }); bindableProperty = CreateBindableProperty<TNativeView>(targetProperty, propertyType, defaultValue); if (binding != null && binding.Mode != BindingMode.OneWay && propertyChanged != null) propertyChanged.PropertyChanged += (sender, e) => { if (e.PropertyName != targetProperty) return; SetValueFromNative<TNativeView>(sender as TNativeView, targetProperty, bindableProperty); //we need to keep the listener around he same time we have the proxy proxy.NativeINPCListener = propertyChanged; }; if (binding != null && binding.Mode != BindingMode.OneWay) SetValueFromNative(target, targetProperty, bindableProperty); proxy.SetBinding(bindableProperty, bindingBase); } static BindableProperty CreateBindableProperty<TNativeView>(string targetProperty, Type propertyType = null, object defaultValue = null) where TNativeView : class { propertyType = propertyType ?? typeof(object); defaultValue = defaultValue ?? (propertyType.GetTypeInfo().IsValueType ? Activator.CreateInstance(propertyType) : null); return BindableProperty.Create( targetProperty, propertyType, typeof(BindableObjectProxy<TNativeView>), defaultValue: defaultValue, defaultBindingMode: BindingMode.Default, propertyChanged: (bindable, oldValue, newValue) => { TNativeView nativeView; if ((bindable as BindableObjectProxy<TNativeView>).TargetReference.TryGetTarget(out nativeView)) SetNativeValue(nativeView, targetProperty, newValue); } ); } static void SetNativeValue<TNativeView>(TNativeView target, string targetProperty, object newValue) where TNativeView : class { var mi = target.GetType().GetProperty(targetProperty)?.SetMethod; if (mi == null) throw new InvalidOperationException(Format("Native Binding on {0}.{1} failed due to missing or inaccessible property", target.GetType(), targetProperty)); mi.Invoke(target, new[] { newValue }); } static void SetValueFromNative<TNativeView>(TNativeView target, string targetProperty, BindableProperty bindableProperty) where TNativeView : class { BindableObjectProxy<TNativeView> proxy; if (!BindableObjectProxy<TNativeView>.BindableObjectProxies.TryGetValue(target, out proxy)) return; SetValueFromRenderer(proxy, bindableProperty, target.GetType().GetProperty(targetProperty)?.GetMethod.Invoke(target, new object[] { })); } static void SetValueFromRenderer(BindableObject bindable, BindableProperty property, object value) { bindable.SetValueCore(property, value); } public static void SetBinding<TNativeView>(TNativeView target, BindableProperty targetProperty, BindingBase binding) where TNativeView : class { if (target == null) throw new ArgumentNullException(nameof(target)); if (targetProperty == null) throw new ArgumentNullException(nameof(targetProperty)); if (binding == null) throw new ArgumentNullException(nameof(binding)); var proxy = BindableObjectProxy<TNativeView>.BindableObjectProxies.GetValue(target, (TNativeView key) => new BindableObjectProxy<TNativeView>(key)); proxy.BindingsBackpack.Add(new KeyValuePair<BindableProperty, BindingBase>(targetProperty, binding)); } public static void SetValue<TNativeView>(TNativeView target, BindableProperty targetProperty, object value) where TNativeView : class { if (target == null) throw new ArgumentNullException(nameof(target)); if (targetProperty == null) throw new ArgumentNullException(nameof(targetProperty)); var proxy = BindableObjectProxy<TNativeView>.BindableObjectProxies.GetValue(target, (TNativeView key) => new BindableObjectProxy<TNativeView>(key)); proxy.ValuesBackpack.Add(new KeyValuePair<BindableProperty, object>(targetProperty, value)); } public static void SetBindingContext<TNativeView>(TNativeView target, object bindingContext, Func<TNativeView, IEnumerable<TNativeView>> getChild = null) where TNativeView : class { if (target == null) throw new ArgumentNullException(nameof(target)); var proxy = BindableObjectProxy<TNativeView>.BindableObjectProxies.GetValue(target, (TNativeView key) => new BindableObjectProxy<TNativeView>(key)); proxy.BindingContext = bindingContext; if (getChild == null) return; var children = getChild(target); if (children == null) return; foreach (var child in children) if (child != null) SetBindingContext(child, bindingContext, getChild); } public static void TransferBindablePropertiesToWrapper<TNativeView, TNativeWrapper>(TNativeView nativeView, TNativeWrapper wrapper) where TNativeView : class where TNativeWrapper : View { BindableObjectProxy<TNativeView> proxy; if (!BindableObjectProxy<TNativeView>.BindableObjectProxies.TryGetValue(nativeView, out proxy)) return; proxy.TransferAttachedPropertiesTo(wrapper); } class EventWrapper : INotifyPropertyChanged { string TargetProperty { get; set; } static readonly MethodInfo s_handlerinfo = typeof(EventWrapper).GetRuntimeMethods().Single(mi => mi.Name == "OnPropertyChanged" && mi.IsPublic == false); public EventWrapper(object target, string targetProperty, string updateSourceEventName) { TargetProperty = targetProperty; Delegate handlerDelegate = null; EventInfo updateSourceEvent = null; try { updateSourceEvent = target.GetType().GetRuntimeEvent(updateSourceEventName); handlerDelegate = s_handlerinfo.CreateDelegate(updateSourceEvent.EventHandlerType, this); } catch (Exception) { throw new ArgumentException(Format("No declared or accessible event {0} on {1}", updateSourceEventName, target.GetType()), nameof(updateSourceEventName)); } if (updateSourceEvent != null && handlerDelegate != null) updateSourceEvent.AddEventHandler(target, handlerDelegate); } [Preserve] void OnPropertyChanged(object sender, EventArgs e) { PropertyChanged?.Invoke(sender, new PropertyChangedEventArgs(TargetProperty)); } public event PropertyChangedEventHandler PropertyChanged; } //This needs to be internal for testing purposes internal class BindableObjectProxy<TNativeView> : BindableObject where TNativeView : class { public static ConditionalWeakTable<TNativeView, BindableObjectProxy<TNativeView>> BindableObjectProxies { get; } = new ConditionalWeakTable<TNativeView, BindableObjectProxy<TNativeView>>(); public WeakReference<TNativeView> TargetReference { get; set; } public IList<KeyValuePair<BindableProperty, BindingBase>> BindingsBackpack { get; } = new List<KeyValuePair<BindableProperty, BindingBase>>(); public IList<KeyValuePair<BindableProperty, object>> ValuesBackpack { get; } = new List<KeyValuePair<BindableProperty, object>>(); public INotifyPropertyChanged NativeINPCListener; public BindableObjectProxy(TNativeView target) { TargetReference = new WeakReference<TNativeView>(target); } public void TransferAttachedPropertiesTo(View wrapper) { foreach (var kvp in BindingsBackpack) wrapper.SetBinding(kvp.Key, kvp.Value); foreach (var kvp in ValuesBackpack) wrapper.SetValue(kvp.Key, kvp.Value); } } } }
44.393204
192
0.767195
[ "MIT" ]
3DSX/maui
src/Controls/src/Core/NativeBindingHelpers.cs
9,145
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("AWSSDK.Account")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Account. This release of the Account Management API enables customers to manage the alternate contacts for their AWS accounts. For more information, see https://docs.aws.amazon.com/accounts/latest/reference/accounts-welcome.html")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.7.0.29")]
49.15625
312
0.755245
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/Account/Properties/AssemblyInfo.cs
1,573
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("Palette Controller")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Palette Controller")] [assembly: AssemblyCopyright("Copyright © 2019 - 2020")] [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("c0a19dfb-b380-4705-bcf0-7c5639e3553f")] // 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("5.470.53.0")] [assembly: AssemblyFileVersion("5.470.53.0")]
38.297297
84
0.748765
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470
Source/Krypton Toolkit Suite Extended/Shared/Palette Controller/Properties/AssemblyInfo.cs
1,420
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using FASTER.core; using System; using System.Buffers; using System.Diagnostics; namespace StoreVarLenTypes { /// <summary> /// Callback functions for FASTER sum operations over SpanByte (non-negative ASCII numbers). /// </summary> public sealed class AsciiSumSpanByteFunctions : SpanByteFunctions<long> { /// <inheritdoc/> public AsciiSumSpanByteFunctions(MemoryPool<byte> memoryPool = null, bool locking = false) : base(memoryPool, locking) { } /// <inheritdoc/> public override void InitialUpdater(ref SpanByte key, ref SpanByte input, ref SpanByte value) { input.CopyTo(ref value); } /// <inheritdoc/> public override bool InPlaceUpdater(ref SpanByte key, ref SpanByte input, ref SpanByte value) { long curr = Utils.BytesToLong(value.AsSpan()); long next = curr + Utils.BytesToLong(input.AsSpan()); if (Utils.NumDigits(next) > value.Length) return false; Utils.LongToBytes(next, value.AsSpan()); return true; } /// <inheritdoc/> public override void CopyUpdater(ref SpanByte key, ref SpanByte input, ref SpanByte oldValue, ref SpanByte newValue) { long curr = Utils.BytesToLong(oldValue.AsSpan()); long next = curr + Utils.BytesToLong(input.AsSpan()); Debug.Assert(Utils.NumDigits(next) == newValue.Length, "Unexpected destination length in CopyUpdater"); Utils.LongToBytes(next, newValue.AsSpan()); } } /// <summary> /// Callback for length computation based on value and input. /// </summary> public class AsciiSumVLS : IVariableLengthStruct<SpanByte, SpanByte> { /// <summary> /// Initial length of value, when populated using given input number. /// We include sizeof(int) for length header. /// </summary> public int GetInitialLength(ref SpanByte input) => sizeof(int) + input.Length; /// <summary> /// Length of resulting object when doing RMW with given value and input. /// For ASCII sum, output is one digit longer than the max of input and old value. /// </summary> public int GetLength(ref SpanByte t, ref SpanByte input) { long curr = Utils.BytesToLong(t.AsSpan()); long next = curr + Utils.BytesToLong(input.AsSpan()); return sizeof(int) + Utils.NumDigits(next); } } }
38.820896
130
0.629758
[ "MIT" ]
DavidNepozitek/FASTER
cs/samples/StoreVarLenTypes/AsciiSumSpanByteFunctions.cs
2,603
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Text; using System.Threading.Tasks; using Roguelike.World; using SFML.Window; namespace Roguelike.Logic { public class EntityLogic { private Vector2i pos; public Map Map { get; set; } public event EventHandler<Vector2i> PosUpdate; public Vector2i Pos { get { return pos; } set { if (!Map.IsPassable(value.X, value.Y)) return; pos = value; PosUpdate(this, pos); } } } }
20.84375
54
0.545727
[ "MIT" ]
MarcusVoelker/Roguelike
Roguelike/Logic/Logic.cs
669
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.SqlServer; using Microsoft.Extensions.Configuration; namespace SqlServerCacheSample { /// <summary> /// This sample requires setting up a Microsoft SQL Server based cache database. /// 1. Install the .NET Core sql-cache tool globally by installing the dotnet-sql-cache package. /// 2. Create a new database in the SQL Server or use an existing one. /// 3. Run the command "dotnet sql-cache create <connectionstring> <schemaName> <tableName>" to setup the table and indexes. /// 4. Run this sample by doing "dotnet run" /// </summary> public class Program { public static void Main() { RunSampleAsync().Wait(); } public static async Task RunSampleAsync() { var configurationBuilder = new ConfigurationBuilder(); var configuration = configurationBuilder .AddJsonFile("config.json") .AddEnvironmentVariables() .Build(); var key = Guid.NewGuid().ToString(); var message = "Hello, World!"; var value = Encoding.UTF8.GetBytes(message); Console.WriteLine("Connecting to cache"); var cache = new SqlServerCache(new SqlServerCacheOptions() { ConnectionString = configuration["ConnectionString"], SchemaName = configuration["SchemaName"], TableName = configuration["TableName"] }); Console.WriteLine("Connected"); Console.WriteLine("Cache item key: {0}", key); Console.WriteLine($"Setting value '{message}' in cache"); await cache.SetAsync( key, value, new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(10))); Console.WriteLine("Set"); Console.WriteLine("Getting value from cache"); value = await cache.GetAsync(key); if (value != null) { Console.WriteLine("Retrieved: " + Encoding.UTF8.GetString(value, 0, value.Length)); } else { Console.WriteLine("Not Found"); } Console.WriteLine("Refreshing value in cache"); await cache.RefreshAsync(key); Console.WriteLine("Refreshed"); Console.WriteLine("Removing value from cache"); await cache.RemoveAsync(key); Console.WriteLine("Removed"); Console.WriteLine("Getting value from cache again"); value = await cache.GetAsync(key); if (value != null) { Console.WriteLine("Retrieved: " + Encoding.UTF8.GetString(value, 0, value.Length)); } else { Console.WriteLine("Not Found"); } Console.ReadLine(); } } }
35.615385
128
0.581919
[ "Apache-2.0" ]
188867052/Extensions
src/Caching/samples/SqlServerCacheSample/Program.cs
3,241
C#
using MobaHeros; using System; [Serializable] public class AutoTestSetting { public string testServer; public bool enablePlayerAI; public AutoTestTag testLevel; }
13.923077
31
0.745856
[ "MIT" ]
corefan/mobahero_src
AutoTestSetting.cs
181
C#
namespace ClassLib113 { public class Class015 { public static string Property => "ClassLib113"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib113/Class015.cs
120
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Media.Imaging; using Hillinworks.TiledImage.Extensions; namespace Hillinworks.TiledImage.Imaging.Sources { partial class WebImageSource { /// <inheritdoc /> /// <summary> /// Manages a single web image download task. /// If the task is in progress, ILoadTileTasks can observe this task. The observers /// will be notified about the download progress and result. /// If all the observers have cancelled their load tasks, the download task will be /// cancelled. /// If the download task is already done, an observer will be fed with the downloaded /// image immediately. /// </summary> private partial class DownloadImageTask : IDisposable { public DownloadImageTask(WebImageSource owner, TileIndex.Full index, string url) { this.Owner = owner; this.TileIndex = index; this.Url = url; this.WebClient = new WebClient(); Task.Run(() => { if (!this.TryLoadCache()) { this.StartDownloading(); } }); } public TaskCompletionSource<BitmapSource> CompletionSource { get; } = new TaskCompletionSource<BitmapSource>(); private HashSet<Observer> Observers { get; } = new HashSet<Observer>(); private WebImageSource Owner { get; } private WebClient WebClient { get; } public TileIndex.Full TileIndex { get; } private string Url { get; } public LoadTileStatus Status { get; private set; } private double LoadProgress { get; set; } public void Dispose() { this.WebClient.Dispose(); GC.SuppressFinalize(this); } private string GetCachePath() { var crypt = new SHA256Managed(); var hashBuilder = new StringBuilder(); var crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(this.Url)); foreach (var @byte in crypto) { hashBuilder.Append(@byte.ToString("x2")); } var hash = hashBuilder.ToString(); // use a git-like path return Path.Combine(this.Owner.LocalCachePath, hash.Substring(0, 2), hash.Substring(2, 2), hashBuilder + ".png"); } private bool TryLoadCache() { if (!this.Owner.AllowLocalCache) { return false; } var path = this.GetCachePath(); if (!File.Exists(path)) { return false; } try { var bitmap = new BitmapImage(); var directory = Path.GetDirectoryName(path); Debug.Assert(directory != null); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (var file = File.OpenRead(path)) { bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = file; bitmap.EndInit(); bitmap.Freeze(); } this.Status = LoadTileStatus.Succeed; this.CompletionSource.SetResult(bitmap); return true; } catch (Exception) { return false; } } private void SaveCache(BitmapImage bitmap) { if (!this.Owner.AllowLocalCache) { return; } Debug.Assert(this.Status == LoadTileStatus.Succeed); Debug.Assert(bitmap != null); var path = this.GetCachePath(); var directory = Path.GetDirectoryName(path); Debug.Assert(directory != null); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } bitmap.SaveAsPng(path); } private void StartDownloading() { this.WebClient.DownloadProgressChanged += this.WebClient_DownloadProgressChanged; this.WebClient.DownloadDataCompleted += this.WebClient_DownloadDataCompleted; this.WebClient.DownloadDataAsync(new Uri(this.Url)); } private void ClearObservers() { foreach (var observer in this.Observers) { observer.Dispose(); } this.Observers.Clear(); } private void WebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { Debug.Assert(this.Status == LoadTileStatus.Loading); lock (this.Observers) { this.ClearObservers(); } if (e.Cancelled) { this.Owner.RemoveDownloadTask(this); this.Status = LoadTileStatus.Canceled; this.CompletionSource.SetCanceled(); } else if (e.Error != null) { this.Owner.RemoveDownloadTask(this); this.Status = LoadTileStatus.Failed; this.CompletionSource.SetException(e.Error); } else { this.Status = LoadTileStatus.Succeed; var buffer = e.Result; var bitmap = new BitmapImage(); using (var stream = new MemoryStream(buffer)) { bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; bitmap.EndInit(); bitmap.Freeze(); } this.SaveCache(bitmap); this.CompletionSource.SetResult(bitmap); } } private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { if (!this.Status.IsAlive()) { return; } Observer[] observers; lock (this.Observers) { observers = this.Observers.ToArray(); } this.LoadProgress = e.ProgressPercentage / 100.0; foreach (var observer in observers) { observer.Progress.Report(this.LoadProgress); } } public void HandleObserver(IProgress<double> progress, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } switch (this.Status) { case LoadTileStatus.Loading: var observer = new Observer(progress, cancellationToken); observer.CancellationTokenRegistration = cancellationToken.Register(this.OnObserverCancelled, observer); lock (this.Observers) { this.Observers.Add(observer); } progress.Report(this.LoadProgress); break; case LoadTileStatus.Succeed: break; default: throw new InvalidOperationException("Invalid state for DownloadImageTask"); } } private void OnObserverCancelled(object userState) { var cancelledObserver = (Observer) userState; lock (this.Observers) { cancelledObserver.Dispose(); this.Observers.Remove(cancelledObserver); if (this.Observers.All(t => t.CancellationToken.IsCancellationRequested)) { // WebClient.CancelAsync can be expensive. Run it asynchronously. Task.Run(this.WebClient.CancelAsync); this.ClearObservers(); } } } } } }
32.559028
109
0.46902
[ "MIT" ]
hillinworks/TiledImageView
Hillinworks.TiledImage.Core/Imaging/Sources/WebImageSource.DownloadImageTask.cs
9,379
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ConsoleUi { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); }); } }
25.36
70
0.621451
[ "MIT" ]
melihercan/Track
UserInterfaces/ConsoleUi/Program.cs
634
C#
/** * Copyright 2015 Canada Health Infoway, 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Domainvalue { public interface EmployeeJob : Code { } }
37.5
83
0.710476
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03_imm/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_imm/Domainvalue/EmployeeJob.cs
1,050
C#
using System; using System.Linq; using Telerik.JustDecompiler.Languages; namespace Telerik.JustDecompiler.Decompiler.MemberRenamingServices { public class WinRTRenamingService : DefaultMemberRenamingService { private const string CLRPrefix = "<CLR>"; public WinRTRenamingService(ILanguage language, bool renameInvalidMembers) : base(language, renameInvalidMembers) { } protected override string GetActualTypeName(string typeName) { return base.GetActualTypeName(typeName.StartsWith(CLRPrefix) ? typeName.Substring(CLRPrefix.Length) : typeName); } } }
30.363636
125
0.687126
[ "ECL-2.0", "Apache-2.0" ]
Bebere/JustDecompileEngine
Cecil.Decompiler/Decompiler/MemberRenamingServices/WinRTRenamingService.cs
670
C#
using IntegrationContainers.API.Tests.Extensions; using IntegrationContainers.API.Tests.Fixtures; using IntegrationContainers.Data.Models; using System.Net; using System.Threading.Tasks; using Xunit; namespace IntegrationContainers.API.Tests { [Collection("Integration containers collection")] public class UsersControllerTests : ControllerTestsBase { public UsersControllerTests(IntegrationContainersAppFactory integrationContainersFixture) : base(integrationContainersFixture) { } [Fact] public async Task GetUsers_NoUsers_ShouldReturnOk() { var response = await Client.GetAsync("api/users"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Fact] public async Task GetUsers_UsersInDb_ShouldReturnAddedUsers() { var user = new User { FirstName = "Sam", LastName = "Jonson" }; Context.Add(user); Context.SaveChanges(); var users = await Client.GetAsync("api/users").DeserializeResponseAsync<User[]>(); Assert.Single(users); } } }
30.105263
97
0.666084
[ "MIT" ]
nazimkov/testcontainers-aspnet-integration-tests
tests/IntegrationContainers.API.Tests/UsersControllelTests.cs
1,144
C#
// // ElementBadge.cs: defines the Badge Element. // // Author: // Miguel de Icaza (miguel@gnome.org) // // Copyright 2010, Novell, Inc. // // Code licensed under the MIT X11 license // using System; using System.Collections; using System.Collections.Generic; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using System.Drawing; using MonoTouch.Foundation; namespace MWC.iOS.UI.CustomElements { /// <summary> /// Lifted this code from MT.D source, so it could be customized /// </summary> public class CustomBadgeElement { public CustomBadgeElement () { } public static UIImage MakeCalendarBadge (UIImage template, string smallText, string bigText) { using (var cs = CGColorSpace.CreateDeviceRGB ()){ using (var context = new CGBitmapContext (IntPtr.Zero, 59, 58, 8, 59*4, cs, CGImageAlphaInfo.PremultipliedLast)){ //context.ScaleCTM (0.5f, -1); context.TranslateCTM (0, 0); context.DrawImage (new RectangleF (0, 0, 59, 58), template.CGImage); context.SetFillColor (0, 0, 0, 1); // The _small_ string context.SelectFont ("Helvetica-Bold", 14f, CGTextEncoding.MacRoman); // Pretty lame way of measuring strings, as documented: var start = context.TextPosition.X; context.SetTextDrawingMode (CGTextDrawingMode.Invisible); context.ShowText (smallText); var width = context.TextPosition.X - start; context.SetTextDrawingMode (CGTextDrawingMode.Fill); context.ShowTextAtPoint ((59-width)/2, 10, smallText); // was 46 // The BIG string context.SelectFont ("Helvetica-Bold", 32, CGTextEncoding.MacRoman); start = context.TextPosition.X; context.SetTextDrawingMode (CGTextDrawingMode.Invisible); context.ShowText (bigText); width = context.TextPosition.X - start; context.SetFillColor (0, 0, 0, 1); context.SetTextDrawingMode (CGTextDrawingMode.Fill); context.ShowTextAtPoint ((59-width)/2, 25, bigText); // was 9 context.StrokePath (); return UIImage.FromImage (context.ToImage ()); } } } public static UIImage MakeCalendarBadgeSmall (UIImage template, string smallText, string bigText) { int imageWidth=30, imageHeight=29; int smallTextY=5, bigTextY=12; float smallTextSize=7f, bigTextSize=16f; using (var cs = CGColorSpace.CreateDeviceRGB ()) { using (var context = new CGBitmapContext (IntPtr.Zero , imageWidth, imageHeight, 8, imageWidth*4, cs , CGImageAlphaInfo.PremultipliedLast)) { //context.ScaleCTM (0.5f, -1); context.TranslateCTM (0, 0); context.DrawImage (new RectangleF (0, 0, imageWidth, imageHeight), template.CGImage); context.SetFillColor (0, 0, 0, 1); // The _small_ string context.SelectFont ("Helvetica-Bold", smallTextSize, CGTextEncoding.MacRoman); // Pretty lame way of measuring strings, as documented: var start = context.TextPosition.X; context.SetTextDrawingMode (CGTextDrawingMode.Invisible); context.ShowText (smallText); var width = context.TextPosition.X - start; context.SetTextDrawingMode (CGTextDrawingMode.Fill); context.ShowTextAtPoint ((imageWidth-width)/2, smallTextY, smallText); // The BIG string context.SelectFont ("Helvetica-Bold", bigTextSize, CGTextEncoding.MacRoman); start = context.TextPosition.X; context.SetTextDrawingMode (CGTextDrawingMode.Invisible); context.ShowText (bigText); width = context.TextPosition.X - start; context.SetFillColor (0, 0, 0, 1); context.SetTextDrawingMode (CGTextDrawingMode.Fill); context.ShowTextAtPoint ((imageWidth-width)/2, bigTextY, bigText); context.StrokePath (); return UIImage.FromImage (context.ToImage ()); } } } } }
33.938053
117
0.684224
[ "Apache-2.0" ]
Eg-Virus/mobile-samples
MWC/MWC.iOS/UI/CustomElements/CustomBadgeElement.cs
3,835
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace Programming4_Lab04_WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18
42
0.702614
[ "Apache-2.0" ]
mbdevpl/wut-bsc-programming-in-graphical-environment
Programming4_Lab04_WPF/App.xaml.cs
308
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server * for more information concerning the license and the contributors participating to this project. */ using AspNet.Security.OpenIdConnect.Primitives; using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Notifications; namespace Owin.Security.OpenIdConnect.Server { /// <summary> /// Represents the context class associated with the /// <see cref="OpenIdConnectServerProvider.ApplyTokenResponse"/> event. /// </summary> public class ApplyTokenResponseContext : BaseNotification<OpenIdConnectServerOptions> { /// <summary> /// Creates a new instance of the <see cref="ApplyTokenResponseContext"/> class. /// </summary> public ApplyTokenResponseContext( IOwinContext context, OpenIdConnectServerOptions options, AuthenticationTicket ticket, OpenIdConnectRequest request, OpenIdConnectResponse response) : base(context, options) { Ticket = ticket; Request = request; Response = response; } /// <summary> /// Gets the token request. /// </summary> /// <remarks> /// Note: this property may be null if an error occurred while /// extracting the token request from the HTTP request. /// </remarks> public new OpenIdConnectRequest Request { get; } /// <summary> /// Gets the token response. /// </summary> public new OpenIdConnectResponse Response { get; } /// <summary> /// Gets the authentication ticket. /// </summary> public AuthenticationTicket Ticket { get; } /// <summary> /// Gets the error code returned to the client application. /// When the response indicates a successful response, /// this property returns <c>null</c>. /// </summary> public string Error => Response.Error; } }
34.253968
98
0.628823
[ "Apache-2.0" ]
AspNet-OpenIdConnect-Server/Owin.Security.OpenIdConnect.Server
src/Owin.Security.OpenIdConnect.Server/Events/ApplyTokenResponseContext.cs
2,160
C#
using System; using Server.Mobiles; namespace Server.Mobiles { [CorpseName( "Un corps d'alligator" )] public class Alligator : BaseCreature { [Constructable] public Alligator() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 ) { Name = "Un alligator"; Body = 0xCA; BaseSoundID = 660; SetStr( 76, 100 ); SetDex( 6, 25 ); SetInt( 11, 20 ); SetHits( 46, 60 ); SetStam( 46, 65 ); SetMana( 0 ); SetDamage( 5, 15 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 25, 35 ); SetResistance( ResistanceType.Fire, 5, 10 ); SetResistance( ResistanceType.Poison, 5, 10 ); SetSkill( SkillName.MagicResist, 25.1, 40.0 ); SetSkill( SkillName.Tactics, 40.1, 60.0 ); SetSkill( SkillName.Wrestling, 40.1, 60.0 ); Fame = 600; Karma = -600; VirtualArmor = 30; Tamable = true; ControlSlots = 1; MinTameSkill = 47.1; } public override int Meat{ get{ return 1; } } public override int Hides{ get{ return 12; } } public override HideType HideType{ get{ return HideType.Spined; } } public override FoodType FavoriteFood{ get{ return FoodType.Meat | FoodType.Fish; } } public Alligator(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int) 0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); if ( BaseSoundID == 0x5A ) BaseSoundID = 660; } } }
21.638889
87
0.656611
[ "BSD-2-Clause" ]
greeduomacro/vivre-uo
Scripts/Mobiles/Animals/Reptiles/Alligator.cs
1,558
C#
using System; using System.Threading.Tasks; using Tizen.System; namespace SystemSettingsUnitTest { //[TestFixture] //[Description("Tizen.System.SoundNotificationChangedEventArgs Tests")] public static class SoundNotificationChangedEventArgsTests { private static bool s_soundNotificationCallbackCalled = false; private static readonly string s_soundNotificationValue = SystemSettingsTestInput.GetStringValue((int)Tizen.System.SystemSettingsKeys.SoundNotification); ////[Test] //[Category("P1")] //[Description("Check SoundNotificationChangedEventArgs Value property")] //[Property("SPEC", "Tizen.System.SoundNotificationChangedEventArgs.Value A")] //[Property("SPEC_URL", "-")] //[Property("CRITERIA", "PRO")] //[Property("AUTHOR", "Aditya Aswani, a.aswani@samsung.com")] public static async Task Value_PROPERTY_READ_ONLY() { try { LogUtils.StartTest(); /* * PRECONDITION * 1. Assign event handler */ Tizen.System.SystemSettings.SoundNotificationChanged += OnSoundNotificationChangedValue; string preValue = Tizen.System.SystemSettings.SoundNotification; Tizen.System.SystemSettings.SoundNotification = s_soundNotificationValue; await Task.Delay(2000); Assert.IsTrue(s_soundNotificationCallbackCalled, "Value_PROPERTY_READ_ONLY: EventHandler added. Not getting called"); /* * POSTCONDITION * 1. Reset callback called flag * 2. Remove event handler * 3. Reset property value */ Tizen.System.SystemSettings.SoundNotificationChanged -= OnSoundNotificationChangedValue; Tizen.System.SystemSettings.SoundNotification = preValue; s_soundNotificationCallbackCalled = false; LogUtils.WriteOK(); } catch (NotSupportedException) { bool isSupport = true; Information.TryGetValue<bool>("tizen.org/feature/systemsetting.incoming_call", out isSupport); Assert.IsTrue(isSupport == false, "Invalid NotSupportedException"); Tizen.Log.Debug("CS-SYSTEM-SETTINGS", ">>>>>> NotSupport(tizen.org/feature/systemsetting.incoming_call)"); LogUtils.NotSupport(); } } private static void OnSoundNotificationChangedValue(object sender, Tizen.System.SoundNotificationChangedEventArgs e) { s_soundNotificationCallbackCalled = true; /* TEST CODE */ Assert.IsInstanceOf<string>(e.Value, "OnSoundNotificationChangedValue: SoundNotification not an instance of string"); Assert.IsTrue(s_soundNotificationValue.CompareTo(e.Value) == 0, "OnSoundNotificationChangedValue: The callback should receive the latest value for the property."); } } }
46.636364
175
0.633853
[ "Apache-2.0", "MIT" ]
AchoWang/TizenFX
test/Tizen.System.SystemSettings.UnitTest/SystemSettings.UnitTest/test/TSSoundNotificationChangedEventArgs.cs
3,078
C#
//Programmed by Alan Thorn 2015 //------------------------------ using UnityEngine; using System.Collections; //------------------------------ public class ScoreOnDestroy : MonoBehaviour { //------------------------------ public int ScoreValue = 50; //------------------------------ void OnDestroy() { GameController.Score += ScoreValue; } //------------------------------ } //------------------------------
24.529412
43
0.393285
[ "MIT" ]
PacktPublishing/Unity-2018-By-Example-Second-Edition
Chapter04/End/Assets/Scripts/ScoreOnDestroy.cs
419
C#
using Harmony; using Multiplayer.Common; using RimWorld; using RimWorld.Planet; using Steamworks; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Xml.Linq; using Verse; namespace Multiplayer.Client { [MpPatch(typeof(Dialog_DebugActionsMenu), nameof(Dialog_DebugActionsMenu.DoListingItems))] [HotSwappable] static class MpDebugTools { static void Postfix(Dialog_DebugActionsMenu __instance) { var menu = __instance; if (MpVersion.IsDebug) { menu.DoLabel("Entry tools"); menu.DebugAction("Entry action", EntryAction); } if (Current.ProgramState != ProgramState.Playing) return; menu.DoLabel("Local"); menu.DebugAction("Save game", SaveGameLocal); menu.DebugAction("Print static fields", PrintStaticFields); if (MpVersion.IsDebug) { menu.DebugAction("Queue incident", QueueIncident); menu.DebugAction("Blocking long event", BlockingLongEvent); } if (Multiplayer.Client == null) return; if (MpVersion.IsDebug) { menu.DoLabel("Multiplayer"); menu.DebugAction("Save game for everyone", SaveGameCmd); menu.DebugAction("Advance time", AdvanceTime); if(Multiplayer.game?.sync?.currentOpinion != null) menu.DebugAction("Force Desync", ForceDesync); } } //No sync method here :) private static void ForceDesync() { Multiplayer.game.sync.TryAddStackTraceForDesyncLog("DebugDesync"); Multiplayer.game.sync.currentOpinion.GetRandomStatesForMap(0).Add((uint) Rand.Value >> 32); } public static void EntryAction() { Log.Message( GenDefDatabase.GetAllDefsInDatabaseForDef(typeof(TerrainDef)) .Select(def => $"{def.modContentPack?.Name} {def} {def.shortHash} {def.index}") .Join(delimiter: "\n") ); } [SyncMethod] [SyncDebugOnly] static void SaveGameCmd() { Map map = Find.Maps[0]; byte[] mapData = ScribeUtil.WriteExposable(Current.Game, "map", true); File.WriteAllBytes($"map_0_{Multiplayer.username}.xml", mapData); } [SyncMethod] [SyncDebugOnly] static void AdvanceTime() { File.WriteAllLines($"{Multiplayer.username}_all_static.txt", new string[] { AllModStatics() }); int to = 322 * 1000; if (Find.TickManager.TicksGame < to) { //Find.TickManager.ticksGameInt = to; //Find.Maps[0].AsyncTime().mapTicks = to; } } static void SaveGameLocal() { byte[] data = ScribeUtil.WriteExposable(Current.Game, "game", true); File.WriteAllBytes($"game_0_{Multiplayer.username}.xml", data); } static void PrintStaticFields() { Log.Message(StaticFieldsToString(typeof(Game).Assembly, type => type.Namespace.StartsWith("RimWorld") || type.Namespace.StartsWith("Verse"))); } public static string AllModStatics() { var builder = new StringBuilder(); foreach (var mod in LoadedModManager.RunningModsListForReading) { builder.AppendLine("======== ").Append(mod.Name).AppendLine(); foreach (var asm in mod.assemblies.loadedAssemblies) { builder.AppendLine(StaticFieldsToString(asm, t => !t.Namespace.StartsWith("Harmony") && !t.Namespace.StartsWith("Multiplayer"))); } } return builder.ToString(); } public static string StaticFieldsToString(Assembly asm, Predicate<Type> typeValidator) { var builder = new StringBuilder(); object FieldValue(FieldInfo field) { var value = field.GetValue(null); if (value is ICollection col) return col.Count; if (field.Name.ToLowerInvariant().Contains("path") && value is string path && (path.Contains("/") || path.Contains("\\"))) return "[x]"; return value; } foreach (var type in asm.GetTypes()) if (!type.IsGenericTypeDefinition && type.Namespace != null && typeValidator(type) && !type.HasAttribute<DefOf>() && !type.HasAttribute<CompilerGeneratedAttribute>()) foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly)) if (!field.IsLiteral && !field.IsInitOnly && !field.HasAttribute<CompilerGeneratedAttribute>()) builder.AppendLine($"{field.FieldType} {type}::{field.Name}: {FieldValue(field)}"); return builder.ToString(); } static void QueueIncident() { Find.Storyteller.incidentQueue.Add(IncidentDefOf.TraderCaravanArrival, Find.TickManager.TicksGame + 600, new IncidentParms() { target = Find.CurrentMap }); } static void BlockingLongEvent() { LongEventHandler.QueueLongEvent(() => Thread.Sleep(60 * 1000), "Blocking", false, null); } public static int currentPlayer; public static int currentHash; public static void HandleCmd(ByteReader data) { currentPlayer = data.ReadInt32(); var source = (DebugSource)data.ReadInt32(); int cursorX = data.ReadInt32(); int cursorZ = data.ReadInt32(); if (Multiplayer.MapContext != null) MouseCellPatch.result = new IntVec3(cursorX, 0, cursorZ); else MouseTilePatch.result = cursorX; currentHash = data.ReadInt32(); var state = Multiplayer.game.playerDebugState.GetOrAddNew(currentPlayer); var prevTool = DebugTools.curTool; DebugTools.curTool = state.tool; List<object> prevSelected = Find.Selector.selected; List<WorldObject> prevWorldSelected = Find.WorldSelector.selected; Find.Selector.selected = new List<object>(); Find.WorldSelector.selected = new List<WorldObject>(); int selectedId = data.ReadInt32(); if (Multiplayer.MapContext != null) { var thing = ThingsById.thingsById.GetValueSafe(selectedId); if (thing != null) Find.Selector.selected.Add(thing); } else { var obj = Find.WorldObjects.AllWorldObjects.FirstOrDefault(w => w.ID == selectedId); if (obj != null) Find.WorldSelector.selected.Add(obj); } Log.Message($"Debug tool {source} ({cursorX}, {cursorZ}) {currentHash}"); try { if (source == DebugSource.ListingMap) { new Dialog_DebugActionsMenu().DoListingItems_MapActions(); new Dialog_DebugActionsMenu().DoListingItems_MapTools(); } else if (source == DebugSource.ListingWorld) { new Dialog_DebugActionsMenu().DoListingItems_World(); } else if (source == DebugSource.ListingPlay) { new Dialog_DebugActionsMenu().DoListingItems_AllModePlayActions(); } else if (source == DebugSource.Lister) { var options = (state.window as List<DebugMenuOption>) ?? new List<DebugMenuOption>(); new Dialog_DebugOptionListLister(options).DoListingItems(); } else if (source == DebugSource.Tool) { DebugTools.curTool?.clickAction(); } else if (source == DebugSource.FloatMenu) { (state.window as List<FloatMenuOption>)?.FirstOrDefault(o => o.Hash() == currentHash)?.action(); } } finally { if (TickPatch.currentExecutingCmdIssuedBySelf && DebugTools.curTool != null && DebugTools.curTool != state.tool) { var map = Multiplayer.MapContext; prevTool = new DebugTool(DebugTools.curTool.label, () => { SendCmd(DebugSource.Tool, 0, map); }, DebugTools.curTool.onGUIAction); } state.tool = DebugTools.curTool; DebugTools.curTool = prevTool; MouseCellPatch.result = null; MouseTilePatch.result = null; Find.Selector.selected = prevSelected; Find.WorldSelector.selected = prevWorldSelected; } } public static void SendCmd(DebugSource source, int hash, Map map) { var writer = new ByteWriter(); int cursorX = 0, cursorZ = 0; if (map != null) { cursorX = UI.MouseCell().x; cursorZ = UI.MouseCell().z; } else { cursorX = GenWorld.MouseTile(false); } writer.WriteInt32(Multiplayer.session.playerId); writer.WriteInt32((int)source); writer.WriteInt32(cursorX); writer.WriteInt32(cursorZ); writer.WriteInt32(hash); if (map != null) writer.WriteInt32(Find.Selector.SingleSelectedThing?.thingIDNumber ?? -1); else writer.WriteInt32(Find.WorldSelector.SingleSelectedObject?.ID ?? -1); var mapId = map?.uniqueID ?? ScheduledCommand.Global; Multiplayer.Client.SendCommand(CommandType.DebugTools, mapId, writer.ToArray()); } public static DebugSource ListingSource() { if (ListingWorldMarker.drawing) return DebugSource.ListingWorld; else if (ListingMapMarker.drawing) return DebugSource.ListingMap; else if (ListingPlayMarker.drawing) return DebugSource.ListingPlay; return DebugSource.None; } } public class PlayerDebugState { public object window; public DebugTool tool; } public enum DebugSource { None, ListingWorld, ListingMap, ListingPlay, Lister, Tool, FloatMenu, } [HarmonyPatch(typeof(Dialog_DebugActionsMenu), nameof(Dialog_DebugActionsMenu.DoListingItems_AllModePlayActions))] static class ListingPlayMarker { public static bool drawing; static void Prefix() => drawing = true; static void Postfix() => drawing = false; } [HarmonyPatch(typeof(Dialog_DebugActionsMenu), nameof(Dialog_DebugActionsMenu.DoListingItems_World))] static class ListingWorldMarker { public static bool drawing; static void Prefix() => drawing = true; static void Postfix() => drawing = false; } [MpPatch(typeof(Dialog_DebugActionsMenu), nameof(Dialog_DebugActionsMenu.DoIncidentDebugAction))] [MpPatch(typeof(Dialog_DebugActionsMenu), nameof(Dialog_DebugActionsMenu.DoIncidentWithPointsAction))] static class ListingIncidentMarker { public static IIncidentTarget target; static void Prefix(IIncidentTarget target) => ListingIncidentMarker.target = target; static void Postfix() => target = null; } [MpPatch(typeof(Dialog_DebugActionsMenu), nameof(Dialog_DebugActionsMenu.DoListingItems_MapActions))] [MpPatch(typeof(Dialog_DebugActionsMenu), nameof(Dialog_DebugActionsMenu.DoListingItems_MapTools))] static class ListingMapMarker { public static bool drawing; static void Prefix() => drawing = true; static void Postfix() => drawing = false; } [MpPatch(typeof(Dialog_DebugOptionLister), nameof(Dialog_DebugOptionLister.DoGap))] [MpPatch(typeof(Dialog_DebugOptionLister), nameof(Dialog_DebugOptionLister.DoLabel))] static class CancelDebugDrawing { static bool Prefix() => !Multiplayer.ExecutingCmds; } [HarmonyPatch(typeof(Dialog_DebugOptionLister), nameof(Dialog_DebugOptionLister.DebugAction))] [HotSwappable] static class DebugActionPatch { static bool Prefix(Dialog_DebugOptionLister __instance, string label, ref Action action) { if (Multiplayer.Client == null) return true; if (Current.ProgramState == ProgramState.Playing && !Multiplayer.WorldComp.debugMode) return true; var originalAction = (action.Target as DebugListerContext)?.originalAction ?? action; int hash = Gen.HashCombineInt( GenText.StableStringHash(originalAction.Method.MethodDesc()), GenText.StableStringHash(label) ); if (Multiplayer.ExecutingCmds) { if (hash == MpDebugTools.currentHash) action(); return false; } if (__instance is Dialog_DebugActionsMenu) { var source = MpDebugTools.ListingSource(); if (source == DebugSource.None) return true; Map map = source == DebugSource.ListingMap ? Find.CurrentMap : null; if (ListingIncidentMarker.target != null) map = ListingIncidentMarker.target as Map; action = () => MpDebugTools.SendCmd(source, hash, map); } if (__instance is Dialog_DebugOptionListLister) { var context = (DebugListerContext)action.Target; action = () => MpDebugTools.SendCmd(DebugSource.Lister, hash, context.map); } return true; } } [MpPatch(typeof(Dialog_DebugOptionLister), nameof(Dialog_DebugOptionLister.DebugToolMap))] [MpPatch(typeof(Dialog_DebugOptionLister), nameof(Dialog_DebugOptionLister.DebugToolWorld))] static class DebugToolPatch { static bool Prefix(Dialog_DebugOptionLister __instance, string label, Action toolAction, ref Container<DebugTool>? __state) { if (Multiplayer.Client == null) return true; if (Current.ProgramState == ProgramState.Playing && !Multiplayer.WorldComp.debugMode) return true; if (Multiplayer.ExecutingCmds) { int hash = Gen.HashCombineInt(GenText.StableStringHash(toolAction.Method.MethodDesc()), GenText.StableStringHash(label)); if (hash == MpDebugTools.currentHash) DebugTools.curTool = new DebugTool(label, toolAction); return false; } __state = DebugTools.curTool; return true; } static void Postfix(Dialog_DebugOptionLister __instance, string label, Action toolAction, Container<DebugTool>? __state) { // New tool chosen if (__state != null && DebugTools.curTool != __state?.Inner) { var originalAction = (toolAction.Target as DebugListerContext)?.originalAction ?? toolAction; int hash = Gen.HashCombineInt(GenText.StableStringHash(originalAction.Method.MethodDesc()), GenText.StableStringHash(label)); if (__instance is Dialog_DebugActionsMenu) { var source = MpDebugTools.ListingSource(); if (source == DebugSource.None) return; Map map = source == DebugSource.ListingMap ? Find.CurrentMap : null; MpDebugTools.SendCmd(source, hash, map); DebugTools.curTool = null; } if (__instance is Dialog_DebugOptionListLister lister) { var context = (DebugListerContext)toolAction.Target; MpDebugTools.SendCmd(DebugSource.Lister, hash, context.map); DebugTools.curTool = null; } } } } public class DebugListerContext { public Map map; public Action originalAction; public void Do() { } } [HarmonyPatch(typeof(WindowStack), nameof(WindowStack.Add))] static class DebugListerAddPatch { static bool Prefix(Window window) { if (Multiplayer.Client == null) return true; if (!Multiplayer.ExecutingCmds) return true; if (!Multiplayer.WorldComp.debugMode) return true; bool keepOpen = TickPatch.currentExecutingCmdIssuedBySelf; var map = Multiplayer.MapContext; if (window is Dialog_DebugOptionListLister lister) { var options = lister.options; if (keepOpen) { lister.options = new List<DebugMenuOption>(); foreach (var option in options) { var copy = option; copy.method = new DebugListerContext() { map = map, originalAction = copy.method }.Do; lister.options.Add(copy); } } Multiplayer.game.playerDebugState.GetOrAddNew(MpDebugTools.currentPlayer).window = options; return keepOpen; } if (window is FloatMenu menu) { var options = menu.options; if (keepOpen) { menu.options = new List<FloatMenuOption>(); foreach (var option in options) { var copy = new FloatMenuOption(option.labelInt, option.action); int hash = copy.Hash(); copy.action = () => MpDebugTools.SendCmd(DebugSource.FloatMenu, hash, map); menu.options.Add(copy); } } Multiplayer.game.playerDebugState.GetOrAddNew(MpDebugTools.currentPlayer).window = options; return keepOpen; } return true; } public static int Hash(this FloatMenuOption opt) { return Gen.HashCombineInt(GenText.StableStringHash(opt.action.Method.MethodDesc()), GenText.StableStringHash(opt.labelInt)); } } }
36.032075
182
0.570456
[ "MIT" ]
XeroCold/Multiplayer
Source/Client/DebugTools.cs
19,099
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Dolittle. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using Dolittle.Concepts; using Dolittle.Runtime.Events; namespace Concepts.Improvements { /// <summary> /// Encapsulates a Unique Identifier /// </summary> public class ImprovementId : ConceptAs<Guid> { /// <summary> /// An empty / not set Id /// </summary> public static ImprovementId Empty { get; } = Guid.Empty; /// <summary> /// Instantiates an instance of an <see cref="ImprovementId" /> with the specified value /// </summary> /// <param name="value"></param> public ImprovementId(Guid value) => Value = value; /// <summary> /// Create an instance of an <see cref="ImprovementId" /> with a generated value /// </summary> /// <returns></returns> public static ImprovementId New() => Guid.NewGuid(); /// <summary> /// Implicitly convert Guid to an ImprovementId /// </summary> /// <param name="value"></param> public static implicit operator ImprovementId(Guid value) => new ImprovementId(value); /// <summary> /// Implicitly convert EventSourceId to an ImprovementId /// </summary> /// <param name="value"></param> public static implicit operator ImprovementId(EventSourceId value) => new ImprovementId(value); /// <summary> /// Implicitly convert ImprovmentId to an EventSourceId /// </summary> /// <param name="value"></param> public static implicit operator EventSourceId(ImprovementId value) => new EventSourceId(value); } }
38.490196
103
0.545593
[ "MIT" ]
dolittle-platform/ContinuousImprovement
Source/Concepts/Improvements/ImprovementId.cs
1,963
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ContainerRegistry.V20190501.Outputs { [OutputType] public sealed class EventResponseResult { /// <summary> /// The event request message sent to the service URI. /// </summary> public readonly Outputs.EventRequestMessageResponseResult? EventRequestMessage; /// <summary> /// The event response message received from the service URI. /// </summary> public readonly Outputs.EventResponseMessageResponseResult? EventResponseMessage; /// <summary> /// The event ID. /// </summary> public readonly string? Id; [OutputConstructor] private EventResponseResult( Outputs.EventRequestMessageResponseResult? eventRequestMessage, Outputs.EventResponseMessageResponseResult? eventResponseMessage, string? id) { EventRequestMessage = eventRequestMessage; EventResponseMessage = eventResponseMessage; Id = id; } } }
31.372093
89
0.662713
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/ContainerRegistry/V20190501/Outputs/EventResponseResult.cs
1,349
C#
using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Analyzers.Constants; using NUnit.Analyzers.IgnoreCaseUsage; using NUnit.Framework; namespace NUnit.Analyzers.Tests.IgnoreCaseUsage { public class IgnoreCaseUsageAnalyzerTests { private static readonly DiagnosticAnalyzer analyzer = new IgnoreCaseUsageAnalyzer(); private static readonly ExpectedDiagnostic expectedDiagnostic = ExpectedDiagnostic.Create(AnalyzerIdentifiers.IgnoreCaseUsage); [Test] public void AnalyzeWhenIgnoreCaseUsedForNonStringEqualToArgument() { var testCode = TestUtility.WrapInTestMethod(@" Assert.That(1, Is.EqualTo(1).↓IgnoreCase);"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [TestCase(nameof(Is.EqualTo))] [TestCase(nameof(Is.EquivalentTo))] [TestCase(nameof(Is.SubsetOf))] [TestCase(nameof(Is.SupersetOf))] public void AnalyzeWhenIgnoreCaseUsedForNonStringCollection(string constraintMethod) { var testCode = TestUtility.WrapInTestMethod($@" var actual = new[] {{1,2,3}}; var expected = new[] {{3,2,1}}; Assert.That(actual, Is.{constraintMethod}(expected).↓IgnoreCase);"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [Test] public void AnalyzeWhenDictionaryWithNonStringValueProvided() { var testCode = TestUtility.WrapInTestMethod(@" var actual = new[] {""a"",""b""}; var expected = new System.Collections.Generic.Dictionary<string, int> { [""key1""] = 1 }; Assert.That(actual, Is.EqualTo(expected).↓IgnoreCase);"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [Test] public void AnalyzeWhenValueTupleWithNoStringMemberProvided() { var testCode = TestUtility.WrapInTestMethod(@" var actual = (1, 2, false); Assert.That(actual, Is.EqualTo((1, 2, false)).↓IgnoreCase);"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [Test] public void AnalyzeWhenTupleWithNoStringMemberProvided() { var testCode = TestUtility.WrapInTestMethod(@" var actual = System.Tuple.Create(1, 2); var expected = System.Tuple.Create(1, 2); Assert.That(actual, Is.EqualTo(expected).↓IgnoreCase);"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [Test] public void AnalyzeWhenNonStringKeyValuePairProvided() { var testCode = TestUtility.WrapInTestMethod(@" var expected = new System.Collections.Generic.KeyValuePair<bool, int>(false, 1); var actual = new System.Collections.Generic.KeyValuePair<bool, int>(true, 1); Assert.That(actual, Is.EqualTo(expected).↓IgnoreCase);"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [Test] public void AnalyzeWhenNonStringRecurseGenericArgumentProvided() { var testCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@" class RecurseClass : System.Collections.Generic.List<RecurseClass> { } [Test] public void TestMethod() { var actual = new RecurseClass(); var expected = new RecurseClass(); Assert.That(actual, Is.EqualTo(expected).↓IgnoreCase); }"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [Test] public void AnalyzeWhenIgnoreCaseUsedInConstraintCombinedByOperators() { var testCode = TestUtility.WrapInTestMethod(@" Assert.That(1, Is.EqualTo(1).↓IgnoreCase | Is.EqualTo(true).↓IgnoreCase);"); AnalyzerAssert.Diagnostics(analyzer, expectedDiagnostic, testCode); } [Test] public void ValidWhenIgnoreCaseUsedForStringEqualToArgument() { var testCode = TestUtility.WrapInTestMethod(@" Assert.That(""A"", Is.EqualTo(""a"").IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [TestCase(nameof(Is.EqualTo))] [TestCase(nameof(Is.EquivalentTo))] [TestCase(nameof(Is.SubsetOf))] [TestCase(nameof(Is.SupersetOf))] public void ValidWhenIgnoreCaseUsedForStringCollection(string constraintMethod) { var testCode = TestUtility.WrapInTestMethod($@" var actual = new[] {{""a"",""b"",""c""}}; var expected = new[] {{""A"",""C"",""B""}}; Assert.That(actual, Is.{constraintMethod}(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidWhenNonGenericIEnumerableProvided() { var testCode = TestUtility.WrapInTestMethod(@" var actual = new[] {""a"",""b"",""c""}; System.Collections.IEnumerable expected = new[] {""A"",""C"",""B""}; Assert.That(actual, Is.EqualTo(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidWhenDictionaryWithStringValueProvided() { var testCode = TestUtility.WrapInTestMethod(@" var actual = new[] {""a"",""b""}; var expected = new System.Collections.Generic.Dictionary<int, string> { [1] = ""value1"" }; Assert.That(actual, Is.EqualTo(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidForValueTupleWithStringMember() { var testCode = TestUtility.WrapInTestMethod(@" var actual = (""a"", 2, false); Assert.That(actual, Is.EqualTo((""A"", 2, false)).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidForTupleWithStringMember() { var testCode = TestUtility.WrapInTestMethod(@" var actual = System.Tuple.Create(1, ""a""); var expected = System.Tuple.Create(1, ""A""); Assert.That(actual, Is.EqualTo(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidForKeyValuePairWithStringKey() { var testCode = TestUtility.WrapInTestMethod(@" var expected = new System.Collections.Generic.KeyValuePair<string, int>(""a"", 1); var actual = new System.Collections.Generic.KeyValuePair<string, int>(""A"", 1); Assert.That(actual, Is.EqualTo(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidForKeyValuePairWithStringValue() { var testCode = TestUtility.WrapInTestMethod(@" var expected = new System.Collections.Generic.KeyValuePair<int, string>(1, ""a""); var actual = new System.Collections.Generic.KeyValuePair<int, string>(1, ""A""); Assert.That(actual, Is.EqualTo(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidForDictionaryEntry() { var testCode = TestUtility.WrapInTestMethod(@" var expected = new System.Collections.DictionaryEntry(1, ""a""); var actual = new System.Collections.DictionaryEntry(1, ""A""); Assert.That(actual, Is.EqualTo(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } [Test] public void ValidForDeepNesting() { var testCode = TestUtility.WrapInTestMethod(@" var actual = (1, new[] { new[] { ""a"" } }); var expected = (1, new[] { new[] { ""A"" } }); Assert.That(actual, Is.EqualTo(expected).IgnoreCase);"); AnalyzerAssert.NoAnalyzerDiagnostics(analyzer, testCode); } } }
38.808889
98
0.587838
[ "MIT" ]
SeanKilleen/nunit.analyzers
src/nunit.analyzers.tests/IgnoreCaseUsage/IgnoreCaseUsageAnalyzerTests.cs
8,750
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17929 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AH.ModuleController.UI.ACMS.Reports.ReportUI { using System; using System.ComponentModel; using CrystalDecisions.Shared; using CrystalDecisions.ReportSource; using CrystalDecisions.CrystalReports.Engine; public class rptAccessControlGroup : ReportClass { public rptAccessControlGroup() { } public override string ResourceName { get { return "rptAccessControlGroup.rpt"; } set { // Do nothing } } public override bool NewGenerator { get { return true; } set { // Do nothing } } public override string FullResourceName { get { return "AH.ModuleController.UI.ACMS.Reports.ReportUI.rptAccessControlGroup.rpt"; } set { // Do nothing } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section1 { get { return this.ReportDefinition.Sections[0]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section2 { get { return this.ReportDefinition.Sections[1]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection1 { get { return this.ReportDefinition.Sections[2]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection2 { get { return this.ReportDefinition.Sections[3]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section3 { get { return this.ReportDefinition.Sections[4]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection2 { get { return this.ReportDefinition.Sections[5]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection1 { get { return this.ReportDefinition.Sections[6]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section4 { get { return this.ReportDefinition.Sections[7]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section5 { get { return this.ReportDefinition.Sections[8]; } } } [System.Drawing.ToolboxBitmapAttribute(typeof(CrystalDecisions.Shared.ExportOptions), "report.bmp")] public class CachedrptAccessControlGroup : Component, ICachedReport { public CachedrptAccessControlGroup() { } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool IsCacheable { get { return true; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool ShareDBLogonInfo { get { return false; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual System.TimeSpan CacheTimeOut { get { return CachedReportConstants.DEFAULT_TIMEOUT; } set { // } } public virtual CrystalDecisions.CrystalReports.Engine.ReportDocument CreateReport() { rptAccessControlGroup rpt = new rptAccessControlGroup(); rpt.Site = this.Site; return rpt; } public virtual string GetCustomizedCacheKey(RequestContext request) { String key = null; // // The following is the code used to generate the default // // cache key for caching report jobs in the ASP.NET Cache. // // Feel free to modify this code to suit your needs. // // Returning key == null causes the default cache key to // // be generated. // // key = RequestContext.BuildCompleteCacheKey( // request, // null, // sReportFilename // this.GetType(), // this.ShareDBLogonInfo ); return key; } } }
35.247312
112
0.573368
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/ACMS/Reports/ReportUI/rptAccessControlGroup1.cs
6,558
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("FsTreeHelper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FsTreeHelper")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("12e36dce-8ff4-477d-9feb-b55f3f2b2a08")] // 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.756757
84
0.745168
[ "MIT" ]
em7/FsTreeHelper
FsTreeHelper/Properties/AssemblyInfo.cs
1,400
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; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal abstract class NamedTypeSymbol : TypeSymbol, INamedTypeSymbol { private ImmutableArray<ITypeSymbol> _lazyTypeArguments; public NamedTypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation = CodeAnalysis.NullableAnnotation.None) : base(nullableAnnotation) { } internal abstract Symbols.NamedTypeSymbol UnderlyingNamedTypeSymbol { get; } int INamedTypeSymbol.Arity { get { return UnderlyingNamedTypeSymbol.Arity; } } ImmutableArray<IMethodSymbol> INamedTypeSymbol.InstanceConstructors { get { return UnderlyingNamedTypeSymbol.InstanceConstructors.GetPublicSymbols(); } } ImmutableArray<IMethodSymbol> INamedTypeSymbol.StaticConstructors { get { return UnderlyingNamedTypeSymbol.StaticConstructors.GetPublicSymbols(); } } ImmutableArray<IMethodSymbol> INamedTypeSymbol.Constructors { get { return UnderlyingNamedTypeSymbol.Constructors.GetPublicSymbols(); } } IEnumerable<string> INamedTypeSymbol.MemberNames { get { return UnderlyingNamedTypeSymbol.MemberNames; } } ImmutableArray<ITypeParameterSymbol> INamedTypeSymbol.TypeParameters { get { return UnderlyingNamedTypeSymbol.TypeParameters.GetPublicSymbols(); } } ImmutableArray<ITypeSymbol> INamedTypeSymbol.TypeArguments { get { if (_lazyTypeArguments.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeArguments, UnderlyingNamedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.GetPublicSymbols(), default); } return _lazyTypeArguments; } } ImmutableArray<CodeAnalysis.NullableAnnotation> INamedTypeSymbol.TypeArgumentNullableAnnotations { get { return UnderlyingNamedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.ToPublicAnnotations(); } } ImmutableArray<CustomModifier> INamedTypeSymbol.GetTypeArgumentCustomModifiers(int ordinal) { return UnderlyingNamedTypeSymbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[ordinal].CustomModifiers; } INamedTypeSymbol INamedTypeSymbol.OriginalDefinition { get { return UnderlyingNamedTypeSymbol.OriginalDefinition.GetPublicSymbol(); } } IMethodSymbol INamedTypeSymbol.DelegateInvokeMethod { get { return UnderlyingNamedTypeSymbol.DelegateInvokeMethod.GetPublicSymbol(); } } INamedTypeSymbol INamedTypeSymbol.EnumUnderlyingType { get { return UnderlyingNamedTypeSymbol.EnumUnderlyingType.GetPublicSymbol(); } } INamedTypeSymbol INamedTypeSymbol.ConstructedFrom { get { return UnderlyingNamedTypeSymbol.ConstructedFrom.GetPublicSymbol(); } } INamedTypeSymbol INamedTypeSymbol.Construct(params ITypeSymbol[] typeArguments) { return UnderlyingNamedTypeSymbol.Construct(ConstructTypeArguments(typeArguments), unbound: false).GetPublicSymbol(); } INamedTypeSymbol INamedTypeSymbol.Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation> typeArgumentNullableAnnotations) { return UnderlyingNamedTypeSymbol.Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations), unbound: false).GetPublicSymbol(); } INamedTypeSymbol INamedTypeSymbol.ConstructUnboundGenericType() { return UnderlyingNamedTypeSymbol.ConstructUnboundGenericType().GetPublicSymbol(); } ISymbol INamedTypeSymbol.AssociatedSymbol { get { return null; } } /// <summary> /// Returns fields that represent tuple elements for types that are tuples. /// /// If this type is not a tuple, then returns default. /// </summary> ImmutableArray<IFieldSymbol> INamedTypeSymbol.TupleElements { get { return UnderlyingNamedTypeSymbol.TupleElements.GetPublicSymbols(); } } /// <summary> /// If this is a tuple type symbol, returns the symbol for its underlying type. /// Otherwise, returns null. /// </summary> INamedTypeSymbol INamedTypeSymbol.TupleUnderlyingType { get { return UnderlyingNamedTypeSymbol.TupleUnderlyingType.GetPublicSymbol(); } } bool INamedTypeSymbol.IsComImport => UnderlyingNamedTypeSymbol.IsComImport; bool INamedTypeSymbol.IsGenericType => UnderlyingNamedTypeSymbol.IsGenericType; bool INamedTypeSymbol.IsUnboundGenericType => UnderlyingNamedTypeSymbol.IsUnboundGenericType; bool INamedTypeSymbol.IsScriptClass => UnderlyingNamedTypeSymbol.IsScriptClass; bool INamedTypeSymbol.IsImplicitClass => UnderlyingNamedTypeSymbol.IsImplicitClass; bool INamedTypeSymbol.MightContainExtensionMethods => UnderlyingNamedTypeSymbol.MightContainExtensionMethods; bool INamedTypeSymbol.IsSerializable => UnderlyingNamedTypeSymbol.IsSerializable; #region ISymbol Members protected sealed override void Accept(SymbolVisitor visitor) { visitor.VisitNamedType(this); } protected sealed override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitNamedType(this); } #endregion } }
32.226601
196
0.634668
[ "Apache-2.0" ]
20chan/roslyn
src/Compilers/CSharp/Portable/Symbols/PublicModel/NamedTypeSymbol.cs
6,544
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace WebApi { /// <summary> /// /// </summary> public class Program { /// <summary> /// /// </summary> /// <param name="args"></param> public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } /// <summary> /// /// </summary> /// <param name="args"></param> /// <returns></returns> public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.289474
70
0.555671
[ "Apache-2.0" ]
satishchatap/zellar
WebApi/Program.cs
961
C#
using ASM.Hardware_Components; using ASM.Models; using System; using System.Collections.Generic; using System.Text; namespace ASM.Opcode_Instructions { public class LDX : OpcodeInstructionBase { public override Hex OPCODE { get; } = new Hex("C"); public override void Invoke(Machine machine, Instruction instruction) { machine.registers[instruction.Index_FlagInt() - 1].SetValue(machine.memory.GetAddress(instruction.AddressInt())); machine.memory.IncrementBuffer(); } } }
26.095238
125
0.686131
[ "MIT" ]
BlakeHastings/ASC
ASM_Library/Opcode_Instructions/Instructions/LDX.cs
550
C#
using System.Collections.Generic; namespace TreeOfAKind.Infrastructure.FileStorage { public class AzureBlobStorageSettings { public string ConnectionString { get; set; } public IDictionary<string,string> Metadata { get; set; } } }
23.727273
64
0.712644
[ "MIT" ]
TreeOfAKind/TreeOfAKind
backend/TreeOfAKind.Infrastructure/FileStorage/AzureBlobStorageSettings.cs
263
C#
// Copyright 2021 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.DataCatalog.V1Beta1.Snippets { using Google.Cloud.DataCatalog.V1Beta1; using Google.Protobuf.WellKnownTypes; public sealed partial class GeneratedDataCatalogClientStandaloneSnippets { /// <summary>Snippet for UpdateTagTemplate</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void UpdateTagTemplateRequestObject() { // Create client DataCatalogClient dataCatalogClient = DataCatalogClient.Create(); // Initialize request argument(s) UpdateTagTemplateRequest request = new UpdateTagTemplateRequest { TagTemplate = new TagTemplate(), UpdateMask = new FieldMask(), }; // Make the request TagTemplate response = dataCatalogClient.UpdateTagTemplate(request); } } }
37.704545
89
0.678722
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/datacatalog/v1beta1/google-cloud-datacatalog-v1beta1-csharp/Google.Cloud.DataCatalog.V1Beta1.StandaloneSnippets/DataCatalogClient.UpdateTagTemplateRequestObjectSnippet.g.cs
1,659
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Camera.Gles { // Metadata.xml XPath class reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']" [global::Android.Runtime.Register ("com/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/camera/gles/Sprite2d", DoNotGenerateAcw=true)] public sealed partial class Sprite2d : global::Java.Lang.Object { static readonly JniPeerMembers _members = new XAPeerMembers ("com/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/camera/gles/Sprite2d", typeof (Sprite2d)); internal static IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } internal Sprite2d (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) { } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/constructor[@name='Sprite2d' and count(parameter)=1 and parameter[1][@type='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles.Drawable2d']]" [Register (".ctor", "(Lcom/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/camera/gles/Drawable2d;)V", "")] public unsafe Sprite2d (global::Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Camera.Gles.Drawable2d drawable) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Lcom/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/camera/gles/Drawable2d;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((drawable == null) ? IntPtr.Zero : ((global::Java.Lang.Object) drawable).Handle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (drawable); } } public unsafe float PositionX { // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='getPositionX' and count(parameter)=0]" [Register ("getPositionX", "()F", "")] get { const string __id = "getPositionX.()F"; try { var __rm = _members.InstanceMethods.InvokeAbstractSingleMethod (__id, this, null); return __rm; } finally { } } } public unsafe float PositionY { // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='getPositionY' and count(parameter)=0]" [Register ("getPositionY", "()F", "")] get { const string __id = "getPositionY.()F"; try { var __rm = _members.InstanceMethods.InvokeAbstractSingleMethod (__id, this, null); return __rm; } finally { } } } public unsafe float Rotation { // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='getRotation' and count(parameter)=0]" [Register ("getRotation", "()F", "")] get { const string __id = "getRotation.()F"; try { var __rm = _members.InstanceMethods.InvokeAbstractSingleMethod (__id, this, null); return __rm; } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='setRotation' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setRotation", "(F)V", "")] set { const string __id = "setRotation.(F)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (value); _members.InstanceMethods.InvokeAbstractVoidMethod (__id, this, __args); } finally { } } } public unsafe float ScaleX { // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='getScaleX' and count(parameter)=0]" [Register ("getScaleX", "()F", "")] get { const string __id = "getScaleX.()F"; try { var __rm = _members.InstanceMethods.InvokeAbstractSingleMethod (__id, this, null); return __rm; } finally { } } } public unsafe float ScaleY { // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='getScaleY' and count(parameter)=0]" [Register ("getScaleY", "()F", "")] get { const string __id = "getScaleY.()F"; try { var __rm = _members.InstanceMethods.InvokeAbstractSingleMethod (__id, this, null); return __rm; } finally { } } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='draw' and count(parameter)=2 and parameter[1][@type='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles.Texture2dProgram'] and parameter[2][@type='float[]']]" [Register ("draw", "(Lcom/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/camera/gles/Texture2dProgram;[F)V", "")] public unsafe void Draw (global::Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Camera.Gles.Texture2dProgram program, float[] projectionMatrix) { const string __id = "draw.(Lcom/paytabs/paytabscardrecognizer/cards/pay/paycardsrecognizer/sdk/camera/gles/Texture2dProgram;[F)V"; IntPtr native_projectionMatrix = JNIEnv.NewArray (projectionMatrix); try { JniArgumentValue* __args = stackalloc JniArgumentValue [2]; __args [0] = new JniArgumentValue ((program == null) ? IntPtr.Zero : ((global::Java.Lang.Object) program).Handle); __args [1] = new JniArgumentValue (native_projectionMatrix); _members.InstanceMethods.InvokeAbstractVoidMethod (__id, this, __args); } finally { if (projectionMatrix != null) { JNIEnv.CopyArray (native_projectionMatrix, projectionMatrix); JNIEnv.DeleteLocalRef (native_projectionMatrix); } global::System.GC.KeepAlive (program); global::System.GC.KeepAlive (projectionMatrix); } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='getColor' and count(parameter)=0]" [Register ("getColor", "()[F", "")] public unsafe float[] GetColor () { const string __id = "getColor.()[F"; try { var __rm = _members.InstanceMethods.InvokeAbstractObjectMethod (__id, this, null); return (float[]) JNIEnv.GetArray (__rm.Handle, JniHandleOwnership.TransferLocalRef, typeof (float)); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='getModelViewMatrix' and count(parameter)=0]" [Register ("getModelViewMatrix", "()[F", "")] public unsafe float[] GetModelViewMatrix () { const string __id = "getModelViewMatrix.()[F"; try { var __rm = _members.InstanceMethods.InvokeAbstractObjectMethod (__id, this, null); return (float[]) JNIEnv.GetArray (__rm.Handle, JniHandleOwnership.TransferLocalRef, typeof (float)); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='setColor' and count(parameter)=3 and parameter[1][@type='float'] and parameter[2][@type='float'] and parameter[3][@type='float']]" [Register ("setColor", "(FFF)V", "")] public unsafe void SetColor (float red, float green, float blue) { const string __id = "setColor.(FFF)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [3]; __args [0] = new JniArgumentValue (red); __args [1] = new JniArgumentValue (green); __args [2] = new JniArgumentValue (blue); _members.InstanceMethods.InvokeAbstractVoidMethod (__id, this, __args); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='setPosition' and count(parameter)=2 and parameter[1][@type='float'] and parameter[2][@type='float']]" [Register ("setPosition", "(FF)V", "")] public unsafe void SetPosition (float posX, float posY) { const string __id = "setPosition.(FF)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [2]; __args [0] = new JniArgumentValue (posX); __args [1] = new JniArgumentValue (posY); _members.InstanceMethods.InvokeAbstractVoidMethod (__id, this, __args); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='setScale' and count(parameter)=2 and parameter[1][@type='float'] and parameter[2][@type='float']]" [Register ("setScale", "(FF)V", "")] public unsafe void SetScale (float scaleX, float scaleY) { const string __id = "setScale.(FF)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [2]; __args [0] = new JniArgumentValue (scaleX); __args [1] = new JniArgumentValue (scaleY); _members.InstanceMethods.InvokeAbstractVoidMethod (__id, this, __args); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.paytabs.paytabscardrecognizer.cards.pay.paycardsrecognizer.sdk.camera.gles']/class[@name='Sprite2d']/method[@name='setTexture' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("setTexture", "(I)V", "")] public unsafe void SetTexture (int textureId) { const string __id = "setTexture.(I)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (textureId); _members.InstanceMethods.InvokeAbstractVoidMethod (__id, this, __args); } finally { } } } }
49.781513
373
0.726536
[ "MIT" ]
amr-Magdy-PT/xamarin-paytabs-binding
android/CardScanBindingLib/obj/Debug/generated/src/Com.Paytabs.Paytabscardrecognizer.Cards.Pay.Paycardsrecognizer.Sdk.Camera.Gles.Sprite2d.cs
11,848
C#
//Copyright (c) 2007-2012, Adolfo Marinucci //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 Adolfo Marinucci 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.Linq; using System.Text; using System.Windows; namespace AvalonDock.Controls { internal interface IOverlayWindowHost { bool HitTest(Point dragPoint); IOverlayWindow ShowOverlayWindow(LayoutFloatingWindowControl draggingWindow); void HideOverlayWindow(); IEnumerable<IDropArea> GetDropAreas(LayoutFloatingWindowControl draggingWindow); DockingManager Manager { get; } } }
46.727273
129
0.76751
[ "MIT" ]
Kiho/mongo-edi
AvalonDock/Controls/IOverlayWindowHost.cs
2,058
C#
using Ereceipt.Application.Services.Interfaces; using Ereceipt.Application.ViewModels.Authentication; using Ereceipt.Web.Responses; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace Ereceipt.Web.Controllers.V1 { public class IdentityController : ApiBaseController { private readonly IAuthenticationService _authenticationService; public IdentityController(IAuthenticationService authenticationService) => _authenticationService = authenticationService; [HttpPost("login")] public async Task<IActionResult> Login([FromBody] LoginModel model) { var result = await _authenticationService.LoginAsync(model); return Ok(result.Data); } [HttpPost("register")] public async Task<IActionResult> Register([FromBody] RegisterModel model, [FromServices] IWebHostEnvironment _webHostEnvironment) { var photoId = Guid.NewGuid().ToString("N"); model.Photo = _webHostEnvironment.WebRootPath + @$"\Images\{photoId}.png"; var result = await _authenticationService.RegisterAsync(model); if (result.IsSuccessed) return Ok(new APIOKResponse("Successed registered!")); return BadRequest(new APIBadRequestResponse(result.Error)); } } }
40.588235
137
0.707246
[ "MIT" ]
Yaroslav08/Echack
Ereceipt/Ereceipt.Web/Controllers/V1/IdentityController.cs
1,382
C#
using System; using System.Threading.Tasks; using Abp; using Abp.Domain.Services; using YMApp.ECommerce.ProductAttributes; namespace YMApp.ECommerce.ProductAttributes.DomainService { public interface IProductAttributeManager : IDomainService { /// <summary> /// 初始化方法 ///</summary> void InitProductAttribute(); } }
13.892857
62
0.645244
[ "MIT" ]
yannis123/YMApp
src/ymapp-aspnet-core/src/YMApp.Core/ECommerce/ProductAttributes/DomainService/IProductAttributeManager.cs
399
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.Storage.Fluent.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// The restriction because of which SKU cannot be used. /// </summary> public partial class Restriction { /// <summary> /// Initializes a new instance of the Restriction class. /// </summary> public Restriction() { CustomInit(); } /// <summary> /// Initializes a new instance of the Restriction class. /// </summary> /// <param name="type">The type of restrictions. As of now only /// possible value for this is location.</param> /// <param name="values">The value of restrictions. If the restriction /// type is set to location. This would be different locations where /// the SKU is restricted.</param> /// <param name="reasonCode">The reason for the restriction. As of now /// this can be “QuotaId” or “NotAvailableForSubscription”. Quota Id is /// set when the SKU has requiredQuotas parameter as the subscription /// does not belong to that quota. The “NotAvailableForSubscription” is /// related to capacity at DC. Possible values include: 'QuotaId', /// 'NotAvailableForSubscription'</param> public Restriction(string type = default(string), IList<string> values = default(IList<string>), string reasonCode = default(string)) { Type = type; Values = values; ReasonCode = reasonCode; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets the type of restrictions. As of now only possible value for /// this is location. /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; private set; } /// <summary> /// Gets the value of restrictions. If the restriction type is set to /// location. This would be different locations where the SKU is /// restricted. /// </summary> [JsonProperty(PropertyName = "values")] public IList<string> Values { get; private set; } /// <summary> /// Gets or sets the reason for the restriction. As of now this can be /// “QuotaId” or “NotAvailableForSubscription”. Quota Id is set when /// the SKU has requiredQuotas parameter as the subscription does not /// belong to that quota. The “NotAvailableForSubscription” is related /// to capacity at DC. Possible values include: 'QuotaId', /// 'NotAvailableForSubscription' /// </summary> [JsonProperty(PropertyName = "reasonCode")] public string ReasonCode { get; set; } } }
38.738095
141
0.62016
[ "MIT" ]
AntoineGa/azure-libraries-for-net
src/ResourceManagement/Storage/Generated/Models/Restriction.cs
3,278
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace CenturiesToMinutes { class Program { static void Main(string[] args) { checked { decimal centuries = decimal.Parse(Console.ReadLine()); decimal years = centuries * 100m; decimal days = Math.Round(years * 365.2422m); decimal hours = days * 24m; decimal minutes = hours * 60m; Console.WriteLine($"{centuries} centuries = {years} years = {days} days = {hours} hours = {minutes} minutes"); } } } }
27.884615
126
0.554483
[ "MIT" ]
Radostta/Programming-Basics-And-Fundamentals-SoftUni
DataTypesAndVariables/CenturiesToMinutes/Program.cs
727
C#
public class Char2InputElementEnumerator : InputElementEnumerator, System.Collections.IEnumerator { protected int colno = 1; protected int lineno = 1; protected int startColumn = 0; protected string file; protected int fileOffset; protected CharEnumerator ce; private bool success; private bool atEOI; // private bool yieldEOF; private InputElement buffered = null; protected System.Text.StringBuilder tmp = new System.Text.StringBuilder(); public Char2InputElementEnumerator(CharEnumerator ce, string file) { this.ce = ce; this.file = file; success = false; // yieldEOF = false; atEOI = !ce.MoveNext(); } protected bool ret(string tag) { return ret(tag, tag); } protected bool ret(string tag, string str) { _current = new InputElement(tag, str, file, lineno, colno, file, fileOffset); success = true; return true; } protected bool ret(string tag, System.Text.StringBuilder buf) { return ret(tag, buf.ToString()); } protected bool malformed(string tag, string str) { _current = new MalformedInputElement(new InputElement(tag, str, file, lineno, colno, file, fileOffset)); success = true; return true; } protected bool malformed(string tag, System.Text.StringBuilder buf) { return malformed(tag, buf.ToString()); } public override bool MoveNext() { string str; if (buffered != null) { _current = buffered; buffered = null; return true; } if (atEOI) { // if (yieldEOF) { // return success = false; // } // yieldEOF = true; return ret("<EOF>"); } colno = ce.Location - startColumn + 1; fileOffset = ce.Location; tmp.Length = 0; switch (ce.Current) { case '#': return preproc(); case '"': tmp.Append('"'); return stringLiteral(); case '\'': tmp.Append('\''); return characterLiteral(); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return number(); case '\u0009': nextchar(); return ret("WHITESPACE", "\u0009"); case '\u000b': nextchar(); return ret("WHITESPACE", "\u000b"); case '\u000c': nextchar(); return ret("WHITESPACE", "\u000c"); case '\u001a': nextchar(); return ret("WHITESPACE", "\u001a"); case '\u000d': str = "\u000d"; if (nextchar()) { if (ce.Current == '\u000a') { str = "\u000d\u000a"; nextchar(); } } startColumn = ce.Location; lineno++; return ret("NEWLINE", str); case '\u000a': nextchar(); startColumn = ce.Location; lineno++; return ret("NEWLINE", "\u000a"); case '\u2028': nextchar(); startColumn = ce.Location; lineno++; return ret("NEWLINE", "\u2028"); case '\u2029': nextchar(); startColumn = ce.Location; lineno++; return ret("NEWLINE", "\u2029"); case '/': if (!nextchar()) { return ret("/"); } if (ce.Current == '=') { nextchar(); return ret("/="); } tmp.Append("/"); if (ce.Current == '/') { // begin "//" comment tmp.Append('/'); return slashslashComment(); } if (ce.Current == '*') { // begin "/*" comment tmp.Append('*'); return slashstarComment(); } return ret("/"); case '.': if (!nextchar()) { return ret("."); } if (ce.Current < '0' || ce.Current > '9') { return ret("."); } tmp.Append("."); while (nextchar() && ce.Current >= '0' && ce.Current <= '9') { tmp.Append(ce.Current); } return dotRealLiteral(); case '+': if (!nextchar()) { return ret("+"); } switch (ce.Current) { case '+': nextchar(); return ret("++"); case '=': nextchar(); return ret("+="); default: return ret("+"); } case ';': nextchar(); return ret(";"); case '[': nextchar(); return ret("["); case '{': nextchar(); return ret("{"); case '(': nextchar(); return ret("("); case '%': if (!nextchar()) { return ret("%"); } switch (ce.Current) { case '=': nextchar(); return ret("%="); default: return ret("%"); } case '-': if (!nextchar()) { return ret("-"); } switch (ce.Current) { case '-': nextchar(); return ret("--"); case '=': nextchar(); return ret("-="); case '>': nextchar(); return ret("->"); default: return ret("-"); } case '=': if (!nextchar()) { return ret("="); } switch (ce.Current) { case '=': nextchar(); return ret("=="); default: return ret("="); } case ']': nextchar(); return ret("]"); case '}': nextchar(); return ret("}"); case '*': if (!nextchar()) { return ret("*"); } switch (ce.Current) { case '=': nextchar(); return ret("*="); default: return ret("*"); } case ':': if (!nextchar()) { return ret(":"); } switch (ce.Current) { case ':': nextchar(); return ret("::"); default: return ret(":"); } case '?': nextchar(); return ret("?"); case ',': nextchar(); return ret(","); case '<': if (!nextchar()) { return ret("<"); } switch (ce.Current) { case '=': nextchar(); return ret("<="); case '<': if (!nextchar()) { return ret("<<"); } switch (ce.Current) { case '=': nextchar(); return ret("<<="); default: return ret("<<"); } default: return ret("<"); } case '|': if (!nextchar()) { return ret("|"); } switch (ce.Current) { case '=': nextchar(); return ret("|="); case '|': nextchar(); return ret("||"); default: return ret("|"); } case '!': if (!nextchar()) { return ret("!"); } switch (ce.Current) { case '=': nextchar(); return ret("!="); default: return ret("!"); } case ')': nextchar(); return ret(")"); case '&': if (!nextchar()) { return ret("&"); } switch (ce.Current) { case '=': nextchar(); return ret("&="); case '&': nextchar(); return ret("&&"); default: return ret("&"); } case '>': if (!nextchar()) { return ret(">"); } switch (ce.Current) { case '=': nextchar(); return ret(">="); default: return ret(">"); } case '^': if (!nextchar()) { return ret("^"); } switch (ce.Current) { case '=': nextchar(); return ret("^="); default: return ret("^"); } case '~': nextchar(); return ret("~"); } if (UnicodeHelp.isZs(ce.Current)) { string t = ce.Current.ToString(); t = System.String.Intern(t); nextchar(); return ret("WHITESPACE", t); } // identifier, keyword, verbatim identifier, or verbatim string if (ce.Current == '@') { tmp.Append('@'); if (!nextchar()) { return ret("UNRECOGNIZED", "@"); } tmp.Append(ce.Current); if (ce.Current == '"') { return verbatimString(); } return id_key(true); } if (UnicodeHelp.isLetterCharacter(ce.Current) || ce.Current == '_') { tmp.Append(ce.Current); return id_key(false); } str = ce.Current.ToString(); nextchar(); return ret("UNRECOGNIZED", str); } private bool verbatimString() { int lineno = this.lineno; for (;;) { if (!nextchar()) { return malformed("string-literal", tmp.ToString()); } tmp.Append(ce.Current); CONT: switch (ce.Current) { default: break; case '"': if (!nextchar() || ce.Current != '"') { bool b = ret("string-literal", tmp.ToString()); this.lineno = lineno; return b; } tmp.Append(ce.Current); break; case '\u000d': if (!nextchar()) { lineno++; startColumn = ce.Location+1; bool b = malformed("string-literal", tmp); this.lineno = lineno; return b; } tmp.Append(ce.Current); if (ce.Current != '\u000a') { // count new-line on the \u000a of \u000d\u000a lineno++; startColumn = ce.Location+1; } goto CONT; // evil, evil, evil! case '\u000a': case '\u2028': case '\u2029': lineno++; startColumn = ce.Location+1; break; } } } private bool dotRealLiteral() { // START cut-n-paste if (ce.Current == 'e' || ce.Current == 'E') { tmp.Append(ce.Current); if (!nextchar()) { return malformed("real-literal", tmp.ToString()); } if (ce.Current == '-' || ce.Current == '+') { tmp.Append(ce.Current); if (!nextchar()) { return malformed("real-literal", tmp); } } if (ce.Current < '0' || ce.Current > '9') { return malformed("real-literal", tmp); } tmp.Append(ce.Current); while (nextchar() && ce.Current >= '0' && ce.Current <= '9') { tmp.Append(ce.Current); } } realSuffix(); return ret("real-literal", tmp); // END cut-n-paste } // identifier, verbatim identifier, or keyword private bool id_key(bool verbatimFlag) { bool errorFlag; while (nextchar()) { if (UnicodeHelp.isIdentifierPartCharacter(ce.Current)) { tmp.Append(ce.Current); continue; } if (ce.Current == '\\') { tmp.Append(ce.Current); if (!nextchar()) { return malformed("identifier", tmp); } tmp.Append(ce.Current); errorFlag = true; char ch = unicodeEscape(ref errorFlag); if (errorFlag) { return malformed("identifier", tmp); } verbatimFlag = true; continue; } break; } if (verbatimFlag) { return ret("identifier", tmp); } string str = System.String.Intern(tmp.ToString()); string t = keyword(str); if (t != null) { return ret(t, t); } return ret("identifier", str); } protected virtual string keyword(string s) { return KeywordHelp.keywordTag(s); } private bool slashstarComment() { while (nextchar()) { CONT: tmp.Append(ce.Current); while (ce.Current == '*') { // evil if (!nextchar()) { return malformed("COMMENT", tmp); } tmp.Append(ce.Current); if (ce.Current == '/') { nextchar(); return ret("COMMENT", tmp); } } switch (ce.Current) { case '\u000d': if (!nextchar()) { lineno++; startColumn = ce.Location; return malformed("COMMENT", tmp); } if (ce.Current != '\u000a') { // count new-line on the \u000a of \u000d\u000a lineno++; startColumn = ce.Location; } goto CONT; // evil, evil, evil case '\u000a': case '\u2028': case '\u2029': lineno++; startColumn = ce.Location; break; } } return malformed("COMMENT", tmp); } private bool slashslashComment() { while (nextchar()) { switch (ce.Current) { case '\u000d': case '\u000a': case '\u2028': case '\u2029': return ret("COMMENT", tmp); } tmp.Append(ce.Current); } return ret("COMMENT", tmp); } private bool characterLiteral() { bool errorFlag; char tmpChar; if (!nextchar()) { return malformed("character-literal", tmp); } tmp.Append(ce.Current); switch (ce.Current) { case '\x0027': return malformed("character-literal", tmp); case '\u000d': case '\u000a': case '\u2028': case '\u2029': return malformed("character-literal", tmp); case '\\': errorFlag = false; tmpChar = escapeChar(ref errorFlag); if (errorFlag) { return malformed("character-literal", tmp); } // tmp.Append(tmpChar); if (atEOI) { return malformed("character-literal", tmp); } if (ce.Current != '\'') { return malformed("character-literal", tmp); } tmp.Append(ce.Current); nextchar(); return ret("character-literal", tmp); default: if (!nextchar()) { return malformed("character-literal", tmp); } if (ce.Current != '\'') { return malformed("character-literal", tmp); } tmp.Append(ce.Current); nextchar(); return ret("character-literal", tmp); } } protected virtual bool stringLiteral() { bool errorFlag; char tmpChar; if (!nextchar()) { return malformed("string-literal", tmp); } for (;;) { tmp.Append(ce.Current); switch (ce.Current) { case '\u000d': case '\u000a': case '\u2028': case '\u2029': return malformed("string-literal", tmp); case '\\': errorFlag = false; tmpChar = escapeChar(ref errorFlag); if (errorFlag) { return malformed("string-literal", tmp); } // tmp.Append(tmpChar); break; case '"': nextchar(); return ret("string-literal", tmp); default: if (!nextchar()) { return malformed("string-literal", tmp); } break; } } } private bool preproc() { while (nextchar()) { tmp.Append(ce.Current); switch (ce.Current) { case '\u000a': case '\u2028': case '\u2029': nextchar(); startColumn = ce.Location; lineno++; return ret("PREPROC", tmp); case '\u000d': if (nextchar()) { if (ce.Current == '\u000a') { tmp.Append(ce.Current); nextchar(); } } startColumn = ce.Location; lineno++; return ret("PREPROC", tmp); } } return ret("PREPROC", tmp); } private bool number() { if (ce.Current == '0') { tmp.Append(ce.Current); if (!nextchar()) { // just zero return ret("integer-literal", tmp); } if (ce.Current == 'x' || ce.Current == 'X') { // hex literal tmp.Append(ce.Current); while (nextchar()) { if ((ce.Current >= '0' && ce.Current <= '9') || (ce.Current >= 'a' && ce.Current <= 'f') || (ce.Current >= 'A' && ce.Current <= 'F')) { tmp.Append(ce.Current); continue; } break; } integerSuffix(); return ret("integer-literal", tmp); } } while (ce.Current >= '0' && ce.Current <= '9') { tmp.Append(ce.Current); if (!nextchar()) { return ret("integer-literal", tmp); } } if (integerSuffix()) { return ret("integer-literal", tmp); } if (realSuffix()) { return ret("real-literal", tmp); } if (ce.Current == '.') { if (!nextchar()) { buffered = new InputElement(".", ".", file, lineno, colno, file, fileOffset); return ret("integer-literal", tmp); } if (ce.Current < '0' || ce.Current > '9') { buffered = new InputElement(".", ".", file, lineno, colno, file, fileOffset); return ret("integer-literal", tmp); } tmp.Append('.'); tmp.Append(ce.Current); while (nextchar() && ce.Current >= '0' && ce.Current <= '9') { tmp.Append(ce.Current); } // START cut-n-paste if (ce.Current == 'e' || ce.Current == 'E') { tmp.Append(ce.Current); if (!nextchar()) { return malformed("real-literal", tmp); } if (ce.Current == '-' || ce.Current == '+') { tmp.Append(ce.Current); if (!nextchar()) { return malformed("real-literal", tmp); } } if (ce.Current < '0' || ce.Current > '9') { return malformed("real-literal", tmp); } tmp.Append(ce.Current); while (nextchar() && ce.Current >= '0' && ce.Current <= '9') { tmp.Append(ce.Current); } } realSuffix(); return ret("real-literal", tmp); // END cut-n-paste } // START cut-n-paste if (ce.Current == 'e' || ce.Current == 'E') { tmp.Append(ce.Current); if (!nextchar()) { return malformed("real-literal", tmp); } if (ce.Current == '-' || ce.Current == '+') { tmp.Append(ce.Current); if (!nextchar()) { return malformed("real-literal", tmp); } } if (ce.Current < '0' || ce.Current > '9') { return malformed("real-literal", tmp); } tmp.Append(ce.Current); while (nextchar() && ce.Current >= '0' && ce.Current <= '9') { tmp.Append(ce.Current); } realSuffix(); return ret("real-literal", tmp); } // END cut-n-paste almost return ret("integer-literal", tmp); } private bool integerSuffix() { if (ce.Current == 'u' || ce.Current == 'U') { tmp.Append(ce.Current); if (nextchar() && (ce.Current == 'l' || ce.Current == 'L')) { tmp.Append(ce.Current); nextchar(); return true; } return true; } if (ce.Current == 'l' || ce.Current == 'L') { tmp.Append(ce.Current); if (nextchar() && (ce.Current == 'u' || ce.Current == 'U')) { tmp.Append(ce.Current); nextchar(); return true; } return true; } return false; } private bool realSuffix() { switch (ce.Current) { case 'M': case 'm': case 'D': case 'd': case 'F': case 'f': tmp.Append(ce.Current); nextchar(); return true; } return false; } private char escapeChar(ref bool errorFlag) { if (ce.Current != '\\') { errorFlag = true; return '\xffff'; } if (!nextchar()) { errorFlag = true; return '\xffff'; } tmp.Append(ce.Current); switch (ce.Current) { default: errorFlag = true; nextchar(); return '\xffff'; case '\'': errorFlag = false; nextchar(); return '\''; case '\"': errorFlag = false; nextchar(); return '\"'; case '\\': errorFlag = false; nextchar(); return '\\'; case '0': errorFlag = false; nextchar(); return '\0'; case 'a': errorFlag = false; nextchar(); return '\a'; case 'b': errorFlag = false; nextchar(); return '\b'; case 'f': errorFlag = false; nextchar(); return '\f'; case 'n': errorFlag = false; nextchar(); return '\n'; case 'r': errorFlag = false; nextchar(); return '\r'; case 't': errorFlag = false; nextchar(); return '\t'; case 'v': errorFlag = false; nextchar(); return '\v'; case 'x': errorFlag = false; return hexEscape(ref errorFlag); case 'u': case 'U': errorFlag = false; char t = unicodeEscape(ref errorFlag); nextchar(); return t; } } private char hexEscape(ref bool errorFlag) { if (ce.Current != 'x') { errorFlag = true; return '\uffff'; } int acc = 0; int count; for (count = 0; nextchar() && count < 4; count++) { switch (ce.Current) { default: break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': tmp.Append(ce.Current); acc = (acc << 4) + ce.Current - '0'; continue; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': tmp.Append(ce.Current); acc = (acc << 4) + ce.Current - 'a' + 10; continue; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': tmp.Append(ce.Current); acc = (acc << 4) + ce.Current - 'A' + 10; continue; } break; } if (count > 0) { errorFlag = false; return (char)acc; } errorFlag = true; return '\uffff'; } private char unicodeEscape(ref bool errorFlag) { if (ce.Current != 'u' && ce.Current != 'U') { errorFlag = true; return '\uffff'; } int len; if (ce.Current == 'U') { len = 8; } else { len = 4; } int acc = 0; for (int i = 0; i < len; i++) { if (!nextchar()) { errorFlag = true; return '\uffff'; } tmp.Append(ce.Current); switch (ce.Current) { default: errorFlag = true; return '\uffff'; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': acc = (acc << 4) + ce.Current - '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': acc = (acc << 4) + ce.Current - 'a' + 10; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': acc = (acc << 4) + ce.Current - 'A' + 10; break; } } errorFlag = false; return (char)acc; } protected bool nextchar() { if (ce.MoveNext()) { return true; } else { atEOI = true; return false; } } private InputElement _current; public override InputElement Current { get { if (success) { return _current; } else { throw new System.InvalidOperationException(); } } } object System.Collections.IEnumerator.Current { get { return Current; } } public virtual void Reset() { } } public class PreprocessorInputElementEnumerator : Char2InputElementEnumerator { public PreprocessorInputElementEnumerator(CharEnumerator ce, string file) : base(ce, file) { // do nothing special } protected override string keyword(string s) { return PPKeywordHelp.keywordTag(s); } override protected bool stringLiteral() { for (;;) { if (!nextchar()) { return malformed("string-literal", tmp); } switch (ce.Current) { case '\u000d': case '\u000a': case '\u2028': case '\u2029': return malformed("string-literal", tmp); case '"': nextchar(); return ret("string-literal", tmp); default: tmp.Append(ce.Current); break; } } } }
20.102639
106
0.544761
[ "MIT" ]
pmache/singularityrdk
SOURCE/base/Windows/csic/parser/lexer.cs
20,565
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; namespace osu.Game.Tests.NonVisual { [TestFixture] public class DifficultyAdjustmentModCombinationsTest { [Test] public void TestNoMods() { var combinations = new TestDifficultyCalculator().CreateDifficultyAdjustmentModCombinations(); Assert.AreEqual(1, combinations.Length); Assert.IsTrue(combinations[0] is NoModMod); } [Test] public void TestSingleMod() { var combinations = new TestDifficultyCalculator(new ModA()).CreateDifficultyAdjustmentModCombinations(); Assert.AreEqual(2, combinations.Length); Assert.IsTrue(combinations[0] is NoModMod); Assert.IsTrue(combinations[1] is ModA); } [Test] public void TestDoubleMod() { var combinations = new TestDifficultyCalculator(new ModA(), new ModB()).CreateDifficultyAdjustmentModCombinations(); Assert.AreEqual(4, combinations.Length); Assert.IsTrue(combinations[0] is NoModMod); Assert.IsTrue(combinations[1] is ModA); Assert.IsTrue(combinations[2] is MultiMod); Assert.IsTrue(combinations[3] is ModB); Assert.IsTrue(((MultiMod)combinations[2]).Mods[0] is ModA); Assert.IsTrue(((MultiMod)combinations[2]).Mods[1] is ModB); } [Test] public void TestIncompatibleMods() { var combinations = new TestDifficultyCalculator(new ModA(), new ModIncompatibleWithA()).CreateDifficultyAdjustmentModCombinations(); Assert.AreEqual(3, combinations.Length); Assert.IsTrue(combinations[0] is NoModMod); Assert.IsTrue(combinations[1] is ModA); Assert.IsTrue(combinations[2] is ModIncompatibleWithA); } [Test] public void TestDoubleIncompatibleMods() { var combinations = new TestDifficultyCalculator(new ModA(), new ModB(), new ModIncompatibleWithA(), new ModIncompatibleWithAAndB()).CreateDifficultyAdjustmentModCombinations(); Assert.AreEqual(8, combinations.Length); Assert.IsTrue(combinations[0] is NoModMod); Assert.IsTrue(combinations[1] is ModA); Assert.IsTrue(combinations[2] is MultiMod); Assert.IsTrue(combinations[3] is ModB); Assert.IsTrue(combinations[4] is MultiMod); Assert.IsTrue(combinations[5] is ModIncompatibleWithA); Assert.IsTrue(combinations[6] is MultiMod); Assert.IsTrue(combinations[7] is ModIncompatibleWithAAndB); Assert.IsTrue(((MultiMod)combinations[2]).Mods[0] is ModA); Assert.IsTrue(((MultiMod)combinations[2]).Mods[1] is ModB); Assert.IsTrue(((MultiMod)combinations[4]).Mods[0] is ModB); Assert.IsTrue(((MultiMod)combinations[4]).Mods[1] is ModIncompatibleWithA); Assert.IsTrue(((MultiMod)combinations[6]).Mods[0] is ModIncompatibleWithA); Assert.IsTrue(((MultiMod)combinations[6]).Mods[1] is ModIncompatibleWithAAndB); } [Test] public void TestIncompatibleThroughBaseType() { var combinations = new TestDifficultyCalculator(new ModAofA(), new ModIncompatibleWithAofA()).CreateDifficultyAdjustmentModCombinations(); Assert.AreEqual(3, combinations.Length); Assert.IsTrue(combinations[0] is NoModMod); Assert.IsTrue(combinations[1] is ModAofA); Assert.IsTrue(combinations[2] is ModIncompatibleWithAofA); } private class ModA : Mod { public override string Name => nameof(ModA); public override string ShortenedName => nameof(ModA); public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModIncompatibleWithA), typeof(ModIncompatibleWithAAndB) }; } private class ModB : Mod { public override string Name => nameof(ModB); public override string ShortenedName => nameof(ModB); public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModIncompatibleWithAAndB) }; } private class ModIncompatibleWithA : Mod { public override string Name => $"Incompatible With {nameof(ModA)}"; public override string ShortenedName => $"Incompatible With {nameof(ModA)}"; public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModA) }; } private class ModAofA : ModA { } private class ModIncompatibleWithAofA : ModIncompatibleWithA { // Incompatible through base type } private class ModIncompatibleWithAAndB : Mod { public override string Name => $"Incompatible With {nameof(ModA)} and {nameof(ModB)}"; public override string ShortenedName => $"Incompatible With {nameof(ModA)} and {nameof(ModB)}"; public override double ScoreMultiplier => 1; public override Type[] IncompatibleMods => new[] { typeof(ModA), typeof(ModB) }; } private class TestDifficultyCalculator : DifficultyCalculator { public TestDifficultyCalculator(params Mod[] mods) : base(null, null) { DifficultyAdjustmentMods = mods; } protected override Mod[] DifficultyAdjustmentMods { get; } protected override DifficultyAttributes Calculate(IBeatmap beatmap, Mod[] mods, double timeRate) => throw new NotImplementedException(); } } }
40.594771
189
0.61858
[ "MIT" ]
AtomCrafty/osu
osu.Game.Tests/NonVisual/DifficultyAdjustmentModCombinationsTest.cs
6,061
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ZumtenSoft.Linq2ObsCollection.Samples.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ZumtenSoft.Linq2ObsCollection.Samples.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.34375
203
0.619098
[ "Apache-2.0" ]
zumten/dotnet-linq-to-observable-collection
src/Linq2ObsCollection.Samples/Properties/Resources.Designer.cs
2,840
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using Game; namespace Game.Tests { [TestClass] public class ScrabbleScoreTest { [TestMethod] public void GetSetWord_GetsSetsUserWord_True() { ScrabbleScore newGame = new ScrabbleScore(); string word = "noob"; newGame.SetWord(word); Assert.AreEqual(word, newGame.GetWord()); } [TestMethod] public void GetSetTotalScore_GetsSetsTotalScore_True() { ScrabbleScore newGame = new ScrabbleScore(); int score = 1; newGame.SetTotalScore(score); Assert.AreEqual(score, newGame.GetTotalScore()); } [TestMethod] public void GetSetWord_GetsSetsUserWordToLowerCase_True() { ScrabbleScore newGame = new ScrabbleScore(); newGame.SetWord("NOOB"); Assert.AreEqual("noob", newGame.GetWord()); } [TestMethod] public void GetCreateLetterScore_CreatesAndGetsLetterScore_True() { ScrabbleScore newGame = new ScrabbleScore(); newGame.CreateLetterScores(); Assert.AreEqual(1, newGame.GetLetterScore('n')); } [TestMethod] public void WordToLetters_TurnsWordIntoLetters_True() { ScrabbleScore newGame = new ScrabbleScore(); newGame.SetWord("noob"); char[] wordSplit = { 'n', 'o', 'o', 'b' }; CollectionAssert.AreEqual(wordSplit, newGame.WordToLetters(newGame.GetWord())); } [TestMethod] public void SumScore_SumsValueOfLettersInWord_Int() { ScrabbleScore newGame = new ScrabbleScore(); newGame.SetWord("noob"); newGame.SumScore(); Assert.AreEqual(6, newGame.GetTotalScore()); } } }
30.203125
91
0.593378
[ "MIT" ]
atrotter0/scrabble-score
Game.Tests/ModelTests/ScrabbleScore.Tests.cs
1,933
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("IntergerHelper")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("IntergerHelper")] [assembly: System.Reflection.AssemblyTitleAttribute("IntergerHelper")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.333333
80
0.65121
[ "MIT" ]
SamB1990/IntegerHelper
src/obj/Debug/netstandard2.0/IntergerHelper.AssemblyInfo.cs
992
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Lime.Protocol.Client; namespace Lime.Protocol.Network.Modules.Resend { public class ResendMessagesChannelModule : IChannelModule<Message>, IChannelModule<Notification>, IDisposable { const string RESENT_COUNT_METADATA_KEY = "#resentCount"; const string RESENT_SESSION_KEY = "#resentSession"; const string RESENT_CHANNEL_ROLE_METADATA_KEY = "#resentChannelRole"; private readonly IChannel _channel; private readonly IMessageStorage _messageStorage; private readonly IKeyProvider _keyProvider; private readonly IDeadMessageHandler _deadMessageHandler; private readonly int _maxResendCount; private readonly TimeSpan _resendWindow; private readonly Event[] _eventsToRemovePendingMessage; private readonly object _syncRoot = new object(); private readonly Func<Exception, IChannel, Message, Task> _resendExceptionHandler; private string _channelKey; private Task _resendTask; private CancellationTokenSource _cts; private bool _disposing; public ResendMessagesChannelModule( IChannel channel, IMessageStorage messageStorage, IKeyProvider keyProvider, IDeadMessageHandler deadMessageHandler, int maxResendCount, TimeSpan resendWindow, Event[] eventsToRemovePendingMessage = null, Func<Exception, IChannel, Message, Task> resendExceptionHandler = null) { _channel = channel ?? throw new ArgumentNullException(nameof(channel)); _messageStorage = messageStorage ?? throw new ArgumentNullException(nameof(messageStorage)); _keyProvider = keyProvider ?? throw new ArgumentNullException(nameof(keyProvider)); _deadMessageHandler = deadMessageHandler ?? throw new ArgumentNullException(nameof(deadMessageHandler)); _maxResendCount = maxResendCount; _resendWindow = resendWindow; if (eventsToRemovePendingMessage != null && eventsToRemovePendingMessage.Length == 0) { throw new ArgumentException("At least one event must be provided", nameof(eventsToRemovePendingMessage)); } _eventsToRemovePendingMessage = eventsToRemovePendingMessage; _resendExceptionHandler = resendExceptionHandler; } public virtual void OnStateChanged(SessionState state) { lock (_syncRoot) { if (state == SessionState.Established) { if (_resendTask == null) StartResendTask(); } else if (state > SessionState.Established) { if (_resendTask != null) StopResendTask(); } } } public virtual async Task<Message> OnSendingAsync(Message envelope, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(envelope.Id)) return envelope; var messageKey = _keyProvider.GetMessageKey(envelope, _channel); var resendCount = GetMessageResendCount(envelope); await _messageStorage.AddAsync( _channelKey, messageKey, envelope, DateTimeOffset.UtcNow.AddTicks(_resendWindow.Ticks * (resendCount + 1)), cancellationToken); return envelope; } public virtual async Task<Notification> OnReceivingAsync(Notification envelope, CancellationToken cancellationToken) { if (_eventsToRemovePendingMessage != null && !_eventsToRemovePendingMessage.Contains(envelope.Event)) { return envelope; } var messageKey = _keyProvider.GetMessageKey(envelope, _channel); await _messageStorage.RemoveAsync(_channelKey, messageKey, cancellationToken); return envelope; } public virtual Task<Notification> OnSendingAsync(Notification envelope, CancellationToken cancellationToken) => envelope.AsCompletedTask(); public virtual Task<Message> OnReceivingAsync(Message envelope, CancellationToken cancellationToken) => envelope.AsCompletedTask(); /// <summary> /// RegisterDocument the module to the specified channel. /// </summary> /// <param name="channel"></param> public virtual void RegisterTo(IChannel channel) { if (channel == null) throw new ArgumentNullException(nameof(channel)); channel.MessageModules.Add(this); channel.NotificationModules.Add(this); } public static ResendMessagesChannelModule CreateAndRegister( IChannel channel, int maxResendCount, TimeSpan resendWindow, IMessageStorage messageStorage = null, IKeyProvider keyProvider = null, IDeadMessageHandler deadMessageHandler = null, Event[] eventsToRemovePendingMessage = null) { var resendMessagesChannelModule = new ResendMessagesChannelModule( channel, messageStorage ?? new MemoryMessageStorage(), keyProvider ?? KeyProvider.Instance, deadMessageHandler ?? DiscardDeadMessageHandler.Instance, maxResendCount, resendWindow, eventsToRemovePendingMessage); resendMessagesChannelModule.RegisterTo(channel); return resendMessagesChannelModule; } private void StartResendTask() { _channelKey = _keyProvider.GetChannelKey(_channel); _cts = new CancellationTokenSource(); _resendTask = Task.Run(() => ResendExpiredMessagesAsync(_cts.Token)); } private void StopResendTask() { try { _cts?.CancelIfNotRequested(); _resendTask?.GetAwaiter().GetResult(); _cts?.Dispose(); _resendTask = null; } catch (ObjectDisposedException) { } } private async Task ResendExpiredMessagesAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested && _channel.IsEstablished()) { try { await Task.Delay(_resendWindow, cancellationToken); var expiredMessageKeys = await _messageStorage.GetMessagesToResendKeysAsync(_channelKey, DateTimeOffset.UtcNow, cancellationToken); foreach (var expiredMessageKey in expiredMessageKeys) { cancellationToken.ThrowIfCancellationRequested(); var expiredMessage = await _messageStorage.RemoveAsync(_channelKey, expiredMessageKey, cancellationToken); if (expiredMessage == null) continue; // It may be already removed var resendCount = GetMessageResendCount(expiredMessage); // Check the message resend limit if (resendCount < _maxResendCount) { // Set the metadata key resendCount++; SetMessageResendCount(expiredMessage, resendCount); try { await _channel.SendMessageAsync(expiredMessage, cancellationToken); } catch (Exception ex) { if (_resendExceptionHandler != null) { await _resendExceptionHandler(ex, _channel, expiredMessage); } else { Trace.TraceError( "Error resending a message with id {0} on channel {1}: {2}", expiredMessage.Id, _channel.SessionId, ex); } // Create a new CTS because the exception can be caused by the cancellation of the method token using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); try { // If any error occurs when resending the message, put the expired message // back into the storage before throwing the exception. await _messageStorage.AddAsync( _channelKey, expiredMessageKey, expiredMessage, DateTimeOffset.UtcNow.Add(_resendWindow), cts.Token); } catch (OperationCanceledException) { } throw; } } else { await _deadMessageHandler.HandleDeadMessageAsync(expiredMessage, _channel, cancellationToken); } } } catch (ObjectDisposedException) when (_disposing) { break; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { break; } catch (Exception ex) { if (_resendExceptionHandler != null) { await _resendExceptionHandler(ex, _channel, null); } else { Trace.TraceError( "An unhandled exception occurred on ResendMessagesChannelModule on channel {0}: {1}", _channel.SessionId, ex); } } } } private static int GetMessageResendCount(Message expiredMessage) { if (expiredMessage.Metadata != null && expiredMessage.Metadata.TryGetValue(RESENT_COUNT_METADATA_KEY, out var resendCountValue) && int.TryParse(resendCountValue, out var resendCount)) return resendCount; return 0; } private void SetMessageResendCount(Message expiredMessage, int resendCount) { if (expiredMessage.Metadata == null) expiredMessage.Metadata = new Dictionary<string, string>(); expiredMessage.Metadata[RESENT_COUNT_METADATA_KEY] = resendCount.ToString(); expiredMessage.Metadata[RESENT_SESSION_KEY] = _channel.SessionId; expiredMessage.Metadata[RESENT_CHANNEL_ROLE_METADATA_KEY] = _channel is IClientChannel ? "Client" : "Server"; } public void Dispose() { _disposing = true; StopResendTask(); } } }
42.896057
127
0.538185
[ "Apache-2.0" ]
JoaoCMotaJr/lime-csharp
src/Lime.Protocol/Network/Modules/Resend/ResendMessagesChannelModule.cs
11,970
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Portions derived from React Native: // Copyright (c) 2015-present, Facebook, Inc. // Licensed under the MIT License. using Newtonsoft.Json.Linq; namespace ReactNative.Bridge { class Promise : IPromise { private const string DefaultError = "EUNSPECIFIED"; private readonly ICallback _resolve; private readonly ICallback _reject; public Promise(ICallback resolve, ICallback reject) { _resolve = resolve; _reject = reject; } public void Resolve(object value) { _resolve?.Invoke(value); } public void Reject(string code, string message, string stack, JToken userInfo) { _reject?.Invoke(new JObject { { "code", code ?? DefaultError }, { "message", message }, { "stack", stack }, { "userInfo", userInfo }, }); } } }
25.6
86
0.561523
[ "MIT" ]
05340836108/react-native-windows
current/ReactWindows/ReactNative.Shared/Bridge/Promise.cs
1,024
C#
using System; using UnityEngine; namespace RASM.FSM { [Serializable] public sealed class FSMState { [SerializeField] private string name; [SerializeReference, SerializeReferenceButton] private FSMTask[] tasks; [SerializeField, HideInInspector] private float elapsedTime; [SerializeField, HideInInspector] private string guid = Guid.NewGuid().ToString(); [NonSerialized] private StateMachine _owner; /// <summary> /// Unique name of the state. /// </summary> public string Name => name; /// <summary> /// Owner of the /// </summary> public StateMachine Owner => _owner; public float ElapsedTime => elapsedTime; public bool IsFinished => Array.TrueForAll(tasks, task => task.IsFinished); public void Awake(StateMachine owner) { _owner = owner; foreach (FSMTask fsmTask in tasks) { fsmTask?.Awake(owner, this); } } public void OnEnter() { elapsedTime = 0f; foreach (FSMTask fsmTask in tasks) { fsmTask.OnEnter(); } } public void OnExit() { foreach (FSMTask fsmTask in tasks) { fsmTask.OnExit(); } } public void Update(float dt) { elapsedTime += dt; foreach (FSMTask fsmTask in tasks) { fsmTask.Update(dt); } } } }
22.589041
83
0.500303
[ "MIT" ]
h-sigma/rasm
RASM/FSM/FSMState.cs
1,651
C#
// --------------------------------------------------------------------------------- // <copyright file="ReceiveBadgeMessageComposer.cs" company="https://github.com/sant0ro/Yupi"> // Copyright (c) 2016 Claudio Santoro, TheDoctor // </copyright> // <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. // </license> // --------------------------------------------------------------------------------- namespace Yupi.Messages.Contracts { using Yupi.Protocol.Buffers; public abstract class ReceiveBadgeMessageComposer : AbstractComposer<string> { #region Methods public override void Compose(Yupi.Protocol.ISender session, string badgeId) { // Do nothing by default. } #endregion Methods } }
45.525
94
0.655135
[ "MIT" ]
TheDoct0r11/Yupi
Yupi.Messages.Contracts/Composer/User/ReceiveBadgeMessageComposer.cs
1,823
C#
//----------------------------------------------------------------------- // <copyright file="RetainingMultiReaderBufferSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Akka.Streams.Implementation; using FluentAssertions; using FluentAssertions.Execution; using Xunit; namespace Akka.Streams.Tests.Implementation { public class RetainingMultiReaderBufferSpec { [Theory] [InlineData(2, 4, 1, "0 0 (size=0, cursors=1)")] [InlineData(4, 4, 3, "0 0 0 0 (size=0, cursors=3)")] public void A_RetainingMultiReaderBufferSpec_should_initially_be_empty(int iSize, int mSize, int cursorCount, string expected) { var test = new Test(iSize, mSize, cursorCount); test.Inspect().Should().Be(expected); } [Fact] public void A_RetainingMultiReaderBufferSpec_should_fail_reads_if_nothing_can_be_read() { var test = new Test(4, 4, 3); test.Write(1).Should().BeTrue(); test.Write(2).Should().BeTrue(); test.Write(3).Should().BeTrue(); test.Inspect().Should().Be("1 2 3 0 (size=3, cursors=3)"); test.Read(0).Should().Be(1); test.Read(0).Should().Be(2); test.Read(1).Should().Be(1); test.Inspect().Should().Be("1 2 3 0 (size=3, cursors=3)"); test.Read(0).Should().Be(3); test.Read(0).Should().Be(null); test.Read(1).Should().Be(2); test.Inspect().Should().Be("1 2 3 0 (size=3, cursors=3)"); test.Read(2).Should().Be(1); test.Inspect().Should().Be("1 2 3 0 (size=3, cursors=3)"); test.Read(1).Should().Be(3); test.Read(1).Should().Be(null); test.Read(2).Should().Be(2); test.Read(2).Should().Be(3); test.Inspect().Should().Be("1 2 3 0 (size=3, cursors=3)"); } [Fact] public void A_RetainingMultiReaderBufferSpec_should_automatically_grow_if_possible() { var test = new Test(2, 8, 2); test.Write(1).Should().BeTrue(); test.Inspect().Should().Be("1 0 (size=1, cursors=2)"); test.Write(2).Should().BeTrue(); test.Inspect().Should().Be("1 2 (size=2, cursors=2)"); test.Write(3).Should().BeTrue(); test.Inspect().Should().Be("1 2 3 0 (size=3, cursors=2)"); test.Write(4).Should().BeTrue(); test.Inspect().Should().Be("1 2 3 4 (size=4, cursors=2)"); test.Read(0).Should().Be(1); test.Read(0).Should().Be(2); test.Read(0).Should().Be(3); test.Read(1).Should().Be(1); test.Read(1).Should().Be(2); test.Write(5).Should().BeTrue(); test.Inspect().Should().Be("1 2 3 4 5 0 0 0 (size=5, cursors=2)"); test.Write(6).Should().BeTrue(); test.Inspect().Should().Be("1 2 3 4 5 6 0 0 (size=6, cursors=2)"); test.Write(7).Should().BeTrue(); test.Inspect().Should().Be("1 2 3 4 5 6 7 0 (size=7, cursors=2)"); test.Read(0).Should().Be(4); test.Read(0).Should().Be(5); test.Read(0).Should().Be(6); test.Read(0).Should().Be(7); test.Read(0).Should().Be(null); test.Read(1).Should().Be(3); test.Read(1).Should().Be(4); test.Read(1).Should().Be(5); test.Read(1).Should().Be(6); test.Read(1).Should().Be(7); test.Read(1).Should().Be(null); test.Inspect().Should().Be("1 2 3 4 5 6 7 0 (size=7, cursors=2)"); } [Fact] public void A_RetainingMultiReaderBufferSpec_should_pass_the_stress_test() { // create 100 buffers with an initialSize of 1 and a maxSize of 1 to 64, // for each one attach 1 to 8 cursors and randomly try reading and writing to the buffer; // in total 200 elements need to be written to the buffer and read in the correct order by each cursor var MAXSIZEBIT_LIMIT = 6; // 2 ^ (this number) var COUNTER_LIMIT = 200; var LOG = false; var sb = new StringBuilder(); var log = new Action<string>(s => { if (LOG) sb.Append(s); }); var random = new Random(); for (var bit = 1; bit <= MAXSIZEBIT_LIMIT; bit++) for (var n = 1; n <= 2; n++) { var counter = 1; var activeCoursors = Enumerable.Range(0, random.Next(8) + 1) .Select(i => new StressTestCursor(i, 1 << bit, log, COUNTER_LIMIT, sb)) .ToList(); var stillWriting = 2;// give writing a slight bias, so as to somewhat "stretch" the buffer var buf = new TestBuffer(1, 1 << bit, new SimpleCursors(activeCoursors)); sb.Clear(); while (activeCoursors.Count != 0) { log($"Buf: {buf.Inspect()}\n"); var activeCursorCount = activeCoursors.Count; var index = random.Next(activeCursorCount + stillWriting); if (index >= activeCursorCount) { log($" Writing {counter}: "); if (buf.Write(counter)) { log("OK\n"); counter++; } else { log("FAILED\n"); if (counter == COUNTER_LIMIT) stillWriting = 0; } } else { var cursor = activeCoursors[index]; if (cursor.TryReadAndReturnTrueIfDone(buf)) activeCoursors = activeCoursors.Where(c => c != cursor).ToList(); } } } } private class TestBuffer : RetainingMultiReaderBuffer<int?> { public ICursors UnderlyingCursors { get; } public TestBuffer(int initialSize, int maxSize, ICursors cursors) : base(initialSize, maxSize, cursors) { UnderlyingCursors = cursors; } public string Inspect() { return Buffer.Select(x => x ?? 0).Aggregate("", (s, i) => s + i + " ") + ToString().SkipWhile(c => c != '(').Aggregate("", (s, c) => s + c); } } private class Test : TestBuffer { public Test(int initialSize, int maxSize, int cursorCount) : base(initialSize, maxSize, new SimpleCursors(cursorCount)) { } public int? Read(int cursorIx) { try { return Read(Cursors.Cursors.ElementAt(cursorIx)); } catch (NothingToReadException) { return null; } } } private class SimpleCursors : ICursors { public SimpleCursors(IEnumerable<ICursor> cursors) { Cursors = cursors; } public SimpleCursors(int cursorCount) { Cursors = Enumerable.Range(0, cursorCount).Select(_ => new SimpleCursor()).ToList(); } public IEnumerable<ICursor> Cursors { get; } } private class SimpleCursor : ICursor { public long Cursor { get; set; } } private class StressTestCursor : ICursor { private readonly int _cursorNr; private readonly int _run; private readonly Action<string> _log; private readonly int _counterLimit; private readonly StringBuilder _sb; private int _counter = 1; public StressTestCursor(int cursorNr, int run, Action<string> log, int counterLimit, StringBuilder sb) { _cursorNr = cursorNr; _run = run; _log = log; _counterLimit = counterLimit; _sb = sb; } public bool TryReadAndReturnTrueIfDone(TestBuffer buf) { _log($" Try reading of {this}: "); try { var x = buf.Read(this); _log("OK\n"); if (x != _counter) { throw new AssertionFailedException( $@"|Run {_run}, cursorNr {_cursorNr}, counter {_counter}: got unexpected {x} | Buf: {buf.Inspect()} | Cursors: {buf.UnderlyingCursors.Cursors.Aggregate(" ", (s, cursor) => s + cursor + "\n ")} |Log: {_sb} "); } _counter++; return _counter == _counterLimit; } catch (NothingToReadException) { _log("FAILED\n"); return false; // ok, we currently can't read, try again later } } public long Cursor { get; set; } public override string ToString() => $"cursorNr {_cursorNr}, ix {Cursor}, counter {_counter}"; } } }
39.669261
138
0.465718
[ "Apache-2.0" ]
Aaronontheweb/akka.net
src/core/Akka.Streams.Tests/Implementation/RetainingMultiReaderBufferSpec.cs
10,197
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("Round")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Round")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("553ad516-010a-407e-bc45-b89e1c101f15")] // 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.243243
84
0.745283
[ "MIT" ]
StepanTuchin98/XT-2018Q4
Lection3/Epam.StudentPractice.Lection3.Task1.Round/Properties/AssemblyInfo.cs
1,381
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AutoPoco.Engine; namespace Nest.Tests.MockData.DataSources { public class LongSource : DatasourceBase<long> { private Random mRandom = new Random(1337); public override long Next(IGenerationSession session) { long f = (long)((mRandom.NextDouble() * 2.0 - 1.0) * long.MaxValue); ; return f; } } }
21.421053
73
0.722359
[ "Apache-2.0" ]
NickCraver/NEST
src/Tests/Nest.Tests.MockData/DataSources/LongSource.cs
409
C#
using NBitcoin; using ReactiveUI; using System; using System.Globalization; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using WalletWasabi.Gui.Models; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Models; using WalletWasabi.Models.ChaumianCoinJoin; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class CoinViewModel : ViewModelBase { public CompositeDisposable Disposables { get; set; } private bool _isSelected; private SmartCoinStatus _status; private ObservableAsPropertyHelper<bool> _coinJoinInProgress; private ObservableAsPropertyHelper<bool> _unspent; private ObservableAsPropertyHelper<bool> _confirmed; private ObservableAsPropertyHelper<bool> _unavailable; private CoinListViewModel _owner; public Global Global => _owner.Global; public CoinViewModel(CoinListViewModel owner, SmartCoin model) { Model = model; _owner = owner; } public void SubscribeEvents() { if (Disposables != null) { throw new Exception("Please report to Dan"); } Disposables = new CompositeDisposable(); //TODO defer subscription to when accessed (will be faster in ui.) _coinJoinInProgress = Model.WhenAnyValue(x => x.CoinJoinInProgress) .ToProperty(this, x => x.CoinJoinInProgress, scheduler: RxApp.MainThreadScheduler) .DisposeWith(Disposables); _unspent = Model.WhenAnyValue(x => x.Unspent) .ToProperty(this, x => x.Unspent, scheduler: RxApp.MainThreadScheduler) .DisposeWith(Disposables); _confirmed = Model.WhenAnyValue(x => x.Confirmed) .ToProperty(this, x => x.Confirmed, scheduler: RxApp.MainThreadScheduler) .DisposeWith(Disposables); _unavailable = Model.WhenAnyValue(x => x.Unavailable) .ToProperty(this, x => x.Unavailable, scheduler: RxApp.MainThreadScheduler) .DisposeWith(Disposables); this.WhenAnyValue(x => x.Status) .Subscribe(_ => this.RaisePropertyChanged(nameof(ToolTip))); this.WhenAnyValue(x => x.Confirmed, x => x.CoinJoinInProgress, x => x.Confirmations) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => RefreshSmartCoinStatus()); this.WhenAnyValue(x => x.IsSelected) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => _owner.OnCoinIsSelectedChanged(this)); this.WhenAnyValue(x => x.Status) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => _owner.OnCoinStatusChanged()); this.WhenAnyValue(x => x.Unspent) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => _owner.OnCoinUnspentChanged(this)); Model.WhenAnyValue(x => x.IsBanned, x => x.SpentAccordingToBackend) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => RefreshSmartCoinStatus()) .DisposeWith(Disposables); Observable.FromEventPattern( Global.ChaumianClient, nameof(Global.ChaumianClient.StateUpdated)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => { RefreshSmartCoinStatus(); }).DisposeWith(Disposables); Global.BitcoinStore.HashChain.WhenAnyValue(x => x.ServerTipHeight) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => { this.RaisePropertyChanged(nameof(Confirmations)); }).DisposeWith(Disposables); Global.UiConfig.WhenAnyValue(x => x.LurkingWifeMode) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(_ => { this.RaisePropertyChanged(nameof(AmountBtc)); this.RaisePropertyChanged(nameof(Clusters)); }).DisposeWith(Disposables); } public void UnsubscribeEvents() { Disposables.Dispose(); Disposables = null; } public SmartCoin Model { get; } public bool Confirmed => _confirmed?.Value ?? false; public bool CoinJoinInProgress => _coinJoinInProgress?.Value ?? false; public bool Unavailable => _unavailable?.Value ?? false; public bool Unspent => _unspent?.Value ?? false; public string Address => Model.ScriptPubKey.GetDestinationAddress(Global.Network).ToString(); public int Confirmations => Model.Height.Type == HeightType.Chain ? Global.BitcoinStore.HashChain.TipHeight - Model.Height.Value + 1 : 0; public bool IsSelected { get => _isSelected; set => this.RaiseAndSetIfChanged(ref _isSelected, value); } public string ToolTip { get { switch (Status) { case SmartCoinStatus.Confirmed: return "This coin is confirmed."; case SmartCoinStatus.Unconfirmed: return "This coin is unconfirmed."; case SmartCoinStatus.MixingOnWaitingList: return "This coin is waiting for its turn to be coinjoined."; case SmartCoinStatus.MixingBanned: return $"The coordinator banned this coin from participation until {Model?.BannedUntilUtc?.ToString("yyyy - MM - dd HH: mm", CultureInfo.InvariantCulture)}."; case SmartCoinStatus.MixingInputRegistration: return "This coin is registered for coinjoin."; case SmartCoinStatus.MixingConnectionConfirmation: return "This coin is currently in Connection Confirmation phase."; case SmartCoinStatus.MixingOutputRegistration: return "This coin is currently in Output Registration phase."; case SmartCoinStatus.MixingSigning: return "This coin is currently in Signing phase."; case SmartCoinStatus.SpentAccordingToBackend: return "According to the Backend, this coin is spent. Wallet state will be corrected after confirmation."; case SmartCoinStatus.MixingWaitingForConfirmation: return "Coinjoining unconfirmed coins is not allowed, unless the coin is a coinjoin output itself."; default: return "This is impossible."; } } } public Money Amount => Model.Amount; public string AmountBtc => Model.Amount.ToString(false, true); public string Label => Model.Label; public int Height => Model.Height; public string TransactionId => Model.TransactionId.ToString(); public uint OutputIndex => Model.Index; public int AnonymitySet => Model.AnonymitySet; public string InCoinJoin => Model.CoinJoinInProgress ? "Yes" : "No"; public string Clusters => string.IsNullOrEmpty(Model.Clusters) ? "" : Model.Clusters; //If the value is null the bind do not update the view. It shows the previous state for example: ##### even if PrivMode false. public string PubKey => Model.HdPubKey.PubKey.ToString(); public string KeyPath => Model.HdPubKey.FullKeyPath.ToString(); public SmartCoinStatus Status { get => _status; set => this.RaiseAndSetIfChanged(ref _status, value); } private void RefreshSmartCoinStatus() { Status = GetSmartCoinStatus(); } private SmartCoinStatus GetSmartCoinStatus() { if (Model.IsBanned) { return SmartCoinStatus.MixingBanned; } CcjClientState clientState = Global.ChaumianClient.State; if (Model.CoinJoinInProgress) { foreach (long roundId in clientState.GetAllMixingRounds()) { CcjClientRound round = clientState.GetSingleOrDefaultRound(roundId); if (round != default) { if (round.CoinsRegistered.Contains(Model)) { if (round.State.Phase == CcjRoundPhase.InputRegistration) { return SmartCoinStatus.MixingInputRegistration; } else if (round.State.Phase == CcjRoundPhase.ConnectionConfirmation) { return SmartCoinStatus.MixingConnectionConfirmation; } else if (round.State.Phase == CcjRoundPhase.OutputRegistration) { return SmartCoinStatus.MixingOutputRegistration; } else if (round.State.Phase == CcjRoundPhase.Signing) { return SmartCoinStatus.MixingSigning; } } } } } if (Model.SpentAccordingToBackend) { return SmartCoinStatus.SpentAccordingToBackend; } if (Model.Confirmed) { if (Model.CoinJoinInProgress) { return SmartCoinStatus.MixingOnWaitingList; } else { return SmartCoinStatus.Confirmed; } } else // Unconfirmed { if (Model.CoinJoinInProgress) { return SmartCoinStatus.MixingWaitingForConfirmation; } else { return SmartCoinStatus.Unconfirmed; } } } } }
30.834615
214
0.722465
[ "MIT" ]
SeppPenner/WalletWasabi
WalletWasabi.Gui/Controls/WalletExplorer/CoinViewModel.cs
8,017
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IOnPremisesPublishingProfileRequestBuilder. /// </summary> public partial interface IOnPremisesPublishingProfileRequestBuilder : IEntityRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> new IOnPremisesPublishingProfileRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> new IOnPremisesPublishingProfileRequest Request(IEnumerable<Option> options); /// <summary> /// Gets the request builder for AgentGroups. /// </summary> /// <returns>The <see cref="IOnPremisesPublishingProfileAgentGroupsCollectionRequestBuilder"/>.</returns> IOnPremisesPublishingProfileAgentGroupsCollectionRequestBuilder AgentGroups { get; } /// <summary> /// Gets the request builder for Agents. /// </summary> /// <returns>The <see cref="IOnPremisesPublishingProfileAgentsCollectionRequestBuilder"/>.</returns> IOnPremisesPublishingProfileAgentsCollectionRequestBuilder Agents { get; } /// <summary> /// Gets the request builder for ConnectorGroups. /// </summary> /// <returns>The <see cref="IOnPremisesPublishingProfileConnectorGroupsCollectionRequestBuilder"/>.</returns> IOnPremisesPublishingProfileConnectorGroupsCollectionRequestBuilder ConnectorGroups { get; } /// <summary> /// Gets the request builder for Connectors. /// </summary> /// <returns>The <see cref="IOnPremisesPublishingProfileConnectorsCollectionRequestBuilder"/>.</returns> IOnPremisesPublishingProfileConnectorsCollectionRequestBuilder Connectors { get; } /// <summary> /// Gets the request builder for PublishedResources. /// </summary> /// <returns>The <see cref="IOnPremisesPublishingProfilePublishedResourcesCollectionRequestBuilder"/>.</returns> IOnPremisesPublishingProfilePublishedResourcesCollectionRequestBuilder PublishedResources { get; } } }
43.090909
153
0.645921
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IOnPremisesPublishingProfileRequestBuilder.cs
2,844
C#
using Asp_Workshop.Abstarction; using Asp_Workshop.Models; namespace Asp_Workshop.Business { public class StudentBusiness : IPersonBusiness { private readonly IScoreBusiness scoreBusiness; public StudentBusiness (IScoreBusiness scoreBusiness) { this.scoreBusiness = scoreBusiness; } public Person Get (int id) { return new Student () { Id = id, FirstName = "محمد حسین", LastName = "مستمند", Scores = scoreBusiness.GetScoreByStudentId (id) }; } } }
29.047619
67
0.577049
[ "MIT" ]
AshkanShakiba/codestar-internship
Projects/Phase11-Web/Asp Workshop/Business/StudentBusiness.cs
624
C#
using ProjectSnowshoes.Properties; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ImageProcessor; using System.Net; using System.Text.RegularExpressions; using System.Runtime.InteropServices; using Transitions; namespace ProjectSnowshoes { public partial class Space : Form { String nP1, nP2, nP3, nP4, nP5, nP6, nP7; String currentBGPath; [DllImport("user32")] static extern bool AnimateWindow(IntPtr hwnd, int time, int flags); // We were going to need this user32.dll, after all...hm. [DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); // Former constructed by the aid of Paedow's answer on StackOverflow: http://stackoverflow.com/questions/13139181/how-to-programmatically-set-the-system-volume // In this specific line, all of the variable names were kept in case necessary (which they should not be, yet they do refer to what is actually going on). // Library usage learned from help of StackOverflow and link to GeekPedia, seemingly written for older implementations. // Let's hope this still works, anyway...here we go! [DllImport("winmm.dll")] public static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume); [DllImport("winmm.dll")] public static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume); [DllImport("winmm.dll")] public static extern IntPtr SetMasterVolumeLevel(float fLevelDB, IntPtr pguidEventContext); public Space() { InitializeComponent(); spaceRightClick.Renderer = new MenuContextRenderer(); rightClickDevStrip.Renderer = new MenuContextRenderer(); this.AllowTransparency = true; Properties.Settings.Default.runTimes = true; Properties.Settings.Default.Save(); } private void Space_Load(object sender, EventArgs e) { try { // Set size of elements based on screen resolution goFixTheResYas(); // Repair flickering by turning up instead this.BackgroundImage = null; this.BackgroundImageLayout = ImageLayout.Stretch; DoubleBufferManipulation.SetDoubleBuffered(panel1); DoubleBufferManipulation.SetDoubleBuffered(spaceForIcons); // Bottom Bar Load /*ThisMayFixTransparency prelimBar = new ThisMayFixTransparency(this.Height); prelimBar.Show(); prelimBar.BringToFront();*/ /*BottomBar newBotBar = new BottomBar(this.Height); newBotBar.Show(); newBotBar.BringToFront();*/ BottomBar_Concept124 newBotBar = new BottomBar_Concept124(this.Height); newBotBar.Show(); newBotBar.BringToFront(); // Font Family Setting Load timeSpaceContinuum.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 11); // Space Background Load this.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); panel1.BackgroundImage = Image.FromFile(Properties.Settings.Default.space_back_path[Properties.Settings.Default.whoIsThisCrazyDoge]); currentBGPath = Properties.Settings.Default.space_back_path[Properties.Settings.Default.whoIsThisCrazyDoge]; // Top Left Account Information accountImg.Image = Image.FromFile(Properties.Settings.Default.userimgacc_path[Properties.Settings.Default.whoIsThisCrazyDoge]); name.Text = Properties.Settings.Default.nickname[Properties.Settings.Default.whoIsThisCrazyDoge]; // Custom Color Integration name.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); panel3.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); date.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); time.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); // Notification Loader Portion for (int index = 0; index <= Properties.Settings.Default.notificationapps.Count - 1; index++) { String nameThatFile = Settings.Default.notificationapps[index]; Process.Start(nameThatFile); } System.IO.File.WriteAllText("C:\\ProjectSnowshoes\\notification.txt", Properties.Settings.Default.notificationtext); //Application.DoEvents(); // Load apps goGenerateTilesFriendship(); //Application.DoEvents(); // Load processes // goGenerateProcessesFriendship(); // Aw yeah even more spaces // Time to do work, or in other words, free the spaceForProcesses from the taskbar so that hover functionality can work // (even though I still have to make the hover functionality Robert do you know what you are doing) // (no) /*panel1.Controls.Add(spaceForProcesses); bottomPanel.Controls.Remove(spaceForProcesses);*/ //Transition.run(this, "Opacity", 0, 1, new TransitionType_EaseInEaseOut(14)); BackgroundFunctionManager bfm = new BackgroundFunctionManager(); bfm.Show(); } catch (Exception ex) { TheScreenIsBlue tsib = new TheScreenIsBlue(ex.HResult + ": " + ex.Message); tsib.Show(); tsib.BringToFront(); this.Close(); } } private void accountImg_Click(object sender, EventArgs e) { /* New menu implementation in The Bridge Build replaces original design. (11/24/2014) * * accountImg.Left = 300; name.Left = 300; sidebar.Left = 0;*/ SlidingMenuBarPostEG whatIsGoingOn = new SlidingMenuBarPostEG(); whatIsGoingOn.Show(); whatIsGoingOn.BringToFront(); } private void timeTimer_Tick(object sender, EventArgs e) { time.Text = System.DateTime.Now.ToShortTimeString(); timeSpaceContinuum.Text = System.DateTime.Now.ToShortTimeString(); // Not for time, but come on now I'm not organized like wow // Actually wait this may not be the best move right now because tiles do not work with this code here // I mean this works but to a point and graphics get turnt but yeah // Never mind we are going to try this again wow make up your mind /*int i = 0; foreach (var theProcess in Process.GetProcesses()) { if (theProcess.MainWindowTitle != "") { i++; } } if (i != spaceForProcesses.Controls.Count) { spaceForProcesses.Controls.Clear(); goGenerateProcessesFriendship(); } Application.DoEvents();*/ } private void dateTimer_Tick(object sender, EventArgs e) { date.Text = System.DateTime.Today.ToShortDateString(); } private void exitWindows_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("explorer"); Application.Exit(); } private void exitWindowsText_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("explorer"); Application.Exit(); } private void notificationTimer_Tick(object sender, EventArgs e) { if (System.IO.File.ReadAllText("C:\\ProjectSnowshoes\\notification.txt") != Properties.Settings.Default.notificationtext) { String turntUp = System.IO.File.ReadAllText("C:\\ProjectSnowshoes\\notification.txt").Split('\n')[0]; String turntUpA = System.IO.File.ReadAllText("C:\\ProjectSnowshoes\\notification.txt").Split('\n')[1]; String turntUpAA = System.IO.File.ReadAllText("C:\\ProjectSnowshoes\\notification.txt").Split('\n')[2]; Notification notif = new Notification(turntUp, turntUpA, Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png")); notif.Show(); notif.BringToFront(); Properties.Settings.Default.notificationtext = System.IO.File.ReadAllText("C:\\ProjectSnowshoes\\notification.txt"); Properties.Settings.Default.Save(); if (n1a.Visible == false) { n1a.Visible = true; n1b.Visible = true; n1c.Visible = true; n1a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n1b.Text = turntUp; n1c.Text = turntUpA; nP1 = turntUpAA; } else if (n2a.Visible == false) { n2a.Visible = true; n2b.Visible = true; n2c.Visible = true; n2a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n2b.Text = turntUp; n2c.Text = turntUpA; nP2 = turntUpAA; } else if (n3a.Visible == false) { n3a.Visible = true; n3b.Visible = true; n3c.Visible = true; n3a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n3b.Text = turntUp; n3c.Text = turntUpA; nP3 = turntUpAA; } else if (n4a.Visible == false) { n4a.Visible = true; n4b.Visible = true; n4c.Visible = true; n4a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n4b.Text = turntUp; n4c.Text = turntUpA; nP4 = turntUpAA; } else if (n5a.Visible == false) { n5a.Visible = true; n5b.Visible = true; n5c.Visible = true; n5a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n5b.Text = turntUp; n5c.Text = turntUpA; nP5 = turntUpAA; } else if (n6a.Visible == false) { n6a.Visible = true; n6b.Visible = true; n6c.Visible = true; n6a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n6b.Text = turntUp; n6c.Text = turntUpA; nP6 = turntUpAA; } else if (n7a.Visible == false) { n7a.Visible = true; n7b.Visible = true; n7c.Visible = true; n7a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n7b.Text = turntUp; n7c.Text = turntUpA; nP7 = turntUpAA; } else { n1a.Image = Image.FromFile("C:\\ProjectSnowshoes\\notificationIcon.png"); n1b.Text = turntUp; n1c.Text = turntUpA; nP1 = turntUpAA; } } } private void panel1_Paint(object sender, PaintEventArgs e) { } private void sidebar_Paint(object sender, PaintEventArgs e) { } private void n7c_Click(object sender, EventArgs e) { } private void n5c_Click(object sender, EventArgs e) { } private void n7b_Click(object sender, EventArgs e) { } private void n5b_Click(object sender, EventArgs e) { } private void n7a_Click(object sender, EventArgs e) { } private void n5a_Click(object sender, EventArgs e) { } private void n6c_Click(object sender, EventArgs e) { } private void n4c_Click(object sender, EventArgs e) { } private void n6b_Click(object sender, EventArgs e) { } private void n4b_Click(object sender, EventArgs e) { } private void n6a_Click(object sender, EventArgs e) { } private void n4a_Click(object sender, EventArgs e) { } private void n3c_Click(object sender, EventArgs e) { } private void n3b_Click(object sender, EventArgs e) { } private void n3a_Click(object sender, EventArgs e) { } private void n2c_Click(object sender, EventArgs e) { } private void n2b_Click(object sender, EventArgs e) { } private void n2a_Click(object sender, EventArgs e) { } private void n1c_Click(object sender, EventArgs e) { } private void powerText_Click(object sender, EventArgs e) { } private void n1b_Click(object sender, EventArgs e) { } private void powerOff_Click(object sender, EventArgs e) { } private void n1a_Click(object sender, EventArgs e) { } private void panel3_Paint(object sender, PaintEventArgs e) { } private void date_Click(object sender, EventArgs e) { } private void time_Click(object sender, EventArgs e) { } private void name_Click(object sender, EventArgs e) { } private void changeBackgroundToolStripMenuItem_Click(object sender, EventArgs e) { ChangeBackground chromebook = new ChangeBackground(); chromebook.Show(); chromebook.BringToFront(); } private void changeBackgroundToolStripMenuItem_Hover(object sender, EventArgs e) { // Future Reference: Sender cannot be passed in like this. // sender.ForeColor = Color.White; } private void bgTimer_Tick(object sender, EventArgs e) { /*if (currentBGPath != Properties.Settings.Default.space_back_path[Properties.Settings.Default.whoIsThisCrazyDoge]) { this.BackgroundImage = Image.FromFile(Properties.Settings.Default.space_back_path[Properties.Settings.Default.whoIsThisCrazyDoge]); currentBGPath = Properties.Settings.Default.space_back_path[Properties.Settings.Default.whoIsThisCrazyDoge]; }*/ } private void changeColorToolStripMenuItem_Click(object sender, EventArgs e) { ColorDialog cdlg = new ColorDialog(); if (cdlg.ShowDialog() == DialogResult.OK) { Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge] = cdlg.Color.Name; Properties.Settings.Default.Save(); Space spaaaaaaaaaaaaaaaaaaace1 = new Space(); spaaaaaaaaaaaaaaaaaaace1.Show(); spaaaaaaaaaaaaaaaaaaace1.Show(); } } private void toolStripMenuItem2_Click(object sender, EventArgs e) { ObviouslyTurnUpOnLogIn turntturnt = new ObviouslyTurnUpOnLogIn(); turntturnt.Show(); turntturnt.BringToFront(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutSnowshoes aboutA = new AboutSnowshoes(); aboutA.Show(); aboutA.BringToFront(); } private void logincsToolStripMenuItem_Click(object sender, EventArgs e) { Login loginOld = new Login(); loginOld.Show(); loginOld.BringToFront(); } private void goFixTheResYas() { //if (Screen.PrimaryScreen.Bounds.Width == 3200 && Screen.PrimaryScreen.Bounds.Height == 1800) //{ accountImg.Height = 145; accountImg.Width = 145; accountImg.Top = Screen.PrimaryScreen.Bounds.Height - 145 - bottomPanel.Height; //name.Top = 100; //name.Height = 25; //name.Width = 100; name.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14); name.Width = 145; panel3.Height = 125; panel3.Top = 0; bottomPanel.Height = this.Height - Screen.PrimaryScreen.WorkingArea.Height; //} } private void goGenerateProcessesFriendship() { spaceForProcesses.Left = 150; spaceForProcesses.Width = spaceForProcesses.Width - 150; spaceForProcesses.Top = bottomPanel.Top; spaceForProcesses.Height = bottomPanel.Height; spaceForProcesses.Invalidate(); foreach (var theProcess in Process.GetProcesses()) { Label hmGreatJobFantasticAmazing = new Label(); // hmGreatJobFantasticAmazing.BackgroundImageLayout = ImageLayout.Center; if (theProcess.MainWindowTitle != "") { //hmGreatJobFantasticAmazing.Text = theProcess.MainWindowTitle; hmGreatJobFantasticAmazing.Margin = new Padding(6,0,6,0); hmGreatJobFantasticAmazing.Visible = true; // hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 13, FontStyle.Italic); Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap().Save(@"C:\ProjectSnowshoes\temptaskico.png"); DualImageForm thanksVKLines = new DualImageForm(); thanksVKLines.pic = Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap(); thanksVKLines.analyze(); thanksVKLines.pic2.Save(@"C:\ProjectSnowshoes\newtemptaskico.png"); ImageFactory grayify = new ImageFactory(); grayify.Load(@"C:\ProjectSnowshoes\temptaskico.png"); //grayify.Tint(Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge])); //grayify.Tint(Color.FromName("Gray")); hmGreatJobFantasticAmazing.Image = grayify.Image; Label areYouSeriouslyStillDoingThisLetItGo = new Label(); hmGreatJobFantasticAmazing.Click += (sender, args) => { System.Diagnostics.Process.Start(theProcess.Modules[0].FileName); }; hmGreatJobFantasticAmazing.MouseHover += (sender, args) => { int recordNao = hmGreatJobFantasticAmazing.Left; //hmGreatJobFantasticAmazing.BackgroundImageLayout = ImageLayout.Zoom; //hmGreatJobFantasticAmazing.Height = 75; /*hmGreatJobFantasticAmazing.ImageAlign = ContentAlignment.MiddleLeft; hmGreatJobFantasticAmazing.AutoEllipsis = true; hmGreatJobFantasticAmazing.Width = 250; hmGreatJobFantasticAmazing.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular); hmGreatJobFantasticAmazing.ForeColor = Color.White; hmGreatJobFantasticAmazing.TextAlign = ContentAlignment.MiddleLeft; hmGreatJobFantasticAmazing.Text = " " + theProcess.MainWindowTitle;*/ hmGreatJobFantasticAmazing.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); areYouSeriouslyStillDoingThisLetItGo.Left = recordNao + 150; areYouSeriouslyStillDoingThisLetItGo.Text = theProcess.MainWindowTitle; areYouSeriouslyStillDoingThisLetItGo.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); areYouSeriouslyStillDoingThisLetItGo.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular); areYouSeriouslyStillDoingThisLetItGo.ForeColor = Color.White; areYouSeriouslyStillDoingThisLetItGo.TextAlign = ContentAlignment.MiddleLeft; panel1.Controls.Add(areYouSeriouslyStillDoingThisLetItGo); //Measuring string turnt-up-edness was guided by an answer on Stack Overflow by Tom Anderson. Graphics heyGuessWhatGraphicsYeahThatsRight = Graphics.FromImage(new Bitmap(1,1)); SizeF sure = heyGuessWhatGraphicsYeahThatsRight.MeasureString(theProcess.MainWindowTitle, new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular, GraphicsUnit.Point)); Size sureAgain = sure.ToSize(); if (sureAgain.Width >= 300) { areYouSeriouslyStillDoingThisLetItGo.Width = sureAgain.Width + 10; } else { areYouSeriouslyStillDoingThisLetItGo.Width = 300; } areYouSeriouslyStillDoingThisLetItGo.Height = bottomPanel.Height; areYouSeriouslyStillDoingThisLetItGo.Top = Screen.PrimaryScreen.WorkingArea.Height - bottomPanel.Height; areYouSeriouslyStillDoingThisLetItGo.Show(); areYouSeriouslyStillDoingThisLetItGo.Visible = true; areYouSeriouslyStillDoingThisLetItGo.BringToFront(); areYouSeriouslyStillDoingThisLetItGo.Invalidate(); //hmGreatJobFantasticAmazing.BringToFront(); //panel1.Controls.Add(hmGreatJobFantasticAmazing); //hmGreatJobFantasticAmazing.Top = bottomPanel.Top - 40; //hmGreatJobFantasticAmazing.Left = recordNao + 150; //hmGreatJobFantasticAmazing.BringToFront(); //hmGreatJobFantasticAmazing.Invalidate(); /*hmGreatJobFantasticAmazing.Height = 100; hmGreatJobFantasticAmazing.Width = 100;*/ }; hmGreatJobFantasticAmazing.MouseLeave += (sender, args) => { /*hmGreatJobFantasticAmazing.ImageAlign = ContentAlignment.MiddleCenter; hmGreatJobFantasticAmazing.AutoEllipsis = false; hmGreatJobFantasticAmazing.Width = 40; hmGreatJobFantasticAmazing.BackColor = Color.Transparent; //hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular); //hmGreatJobFantasticAmazing.ForeColor = Color.White; hmGreatJobFantasticAmazing.TextAlign = ContentAlignment.MiddleLeft; hmGreatJobFantasticAmazing.Text = "";*/ panel1.Controls.Remove(areYouSeriouslyStillDoingThisLetItGo); hmGreatJobFantasticAmazing.BackColor = Color.Transparent; }; openFileToolTip.SetToolTip(hmGreatJobFantasticAmazing, theProcess.MainWindowTitle); //hmGreatJobFantasticAmazing.BackgroundImage = Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap(); hmGreatJobFantasticAmazing.Height = bottomPanel.Height; hmGreatJobFantasticAmazing.Width = 40; spaceForProcesses.Controls.Add(hmGreatJobFantasticAmazing); } } } private void goGenerateTilesFriendship() { String pathPlease = @"C:\ProjectSnowshoes\User\" + Properties.Settings.Default.username[Properties.Settings.Default.whoIsThisCrazyDoge] + @"\Space"; for (int i = 0; i < Directory.GetFiles(pathPlease,"*.*",SearchOption.TopDirectoryOnly).Length; i++) { FileInfo fiInf = new FileInfo(Directory.GetFiles(pathPlease, "*.*", SearchOption.TopDirectoryOnly)[i]); String fiInfStr = fiInf.Name; String fiInfStillWIthExt = fiInfStr; fiInfStr = fiInfStr.Split('.')[0]; // if (fiInfStillWIthExt != "desktop.ini" || if ((fiInf.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) { String panelname = "app" + i; Panel app1 = new Panel(); app1.Show(); app1.BackColor = Color.Transparent; app1.Width = 150; app1.Height = 150; app1.Margin = new Padding(20); app1.BackgroundImageLayout = ImageLayout.Stretch; iconMatch(Directory.GetFiles(pathPlease, "*.*", SearchOption.TopDirectoryOnly)[i]); DoubleBufferManipulation.SetDoubleBuffered(app1); spaceForIcons.Controls.Add(app1); Panel turnip = new Panel(); turnip.Show(); turnip.BackColor = Color.Transparent; turnip.Width = 150; turnip.Height = 150; turnip.BackgroundImageLayout = ImageLayout.Zoom; IconManager areYouForRealRightNowLikeReallyRealVSWow = new IconManager(); app1.BackColor = Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge]); //app1.BackgroundImage = Properties.Resources._20pertrans_lighterGray; turnip.BackgroundImage = areYouForRealRightNowLikeReallyRealVSWow.icoExtReturner(fiInf.FullName, fiInfStr, true); DoubleBufferManipulation.SetDoubleBuffered(turnip); app1.Controls.Add(turnip); turnip.Left = 0; turnip.Top = 0; Label whatEvenIsThis = new Label(); whatEvenIsThis.BackColor = Color.Transparent; whatEvenIsThis.Show(); /*ImageFactory imga = new ImageFactory(); Properties.Resources.TheOpacityIsAlmostReal.Save("C:\\ProjectSnowshoes\\loginbacktempAA.png"); imga.Load("C:\\ProjectSnowshoes\\loginbacktempAA.png"); imga.Tint(Color.FromName(Properties.Settings.Default.custColor[Properties.Settings.Default.whoIsThisCrazyDoge])); whatEvenIsThis.BackgroundImage = imga.Image;*/ whatEvenIsThis.BackgroundImage = Image.FromFile("C:\\ProjectSnowshoes\\loginbacktempAA.png"); whatEvenIsThis.Width = 150; whatEvenIsThis.Height = 40; /* whatEvenIsThis.Text = Directory.GetFiles(pathPlease, "*.*", SearchOption.TopDirectoryOnly)[i]; FileInfo fiInf = new FileInfo(Directory.GetFiles(pathPlease, "*.*", SearchOption.TopDirectoryOnly)[i]); String fiInfStr = fiInf.Name; fiInfStr = fiInfStr.Split('.')[0]; */ whatEvenIsThis.AutoSize = false; whatEvenIsThis.TextAlign = ContentAlignment.MiddleCenter; whatEvenIsThis.Text = fiInfStr; whatEvenIsThis.ForeColor = Color.White; whatEvenIsThis.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 10); turnip.Controls.Add(whatEvenIsThis); whatEvenIsThis.BringToFront(); DoubleBufferManipulation.SetDoubleBuffered(whatEvenIsThis); whatEvenIsThis.Left = 0; whatEvenIsThis.Top = 110; /* app1.Click += hmThatIsAReallyInterestingActionWow; turnip.Click += hmThatIsAReallyInterestingActionWow; whatEvenIsThis.Click += hmThatIsAReallyInterestingActionWow; */ // Yes, I had to refer to StackOverflow in order to remember how to do this following portion. // Yes, I'm doing that a lot. // Yes, you and my doge are judging me harshly right now. app1.Click += (sender, args) => { System.Diagnostics.Process.Start(fiInf.FullName); }; turnip.Click += (sender, args) => { System.Diagnostics.Process.Start(fiInf.FullName); }; whatEvenIsThis.Click += (sender, args) => { System.Diagnostics.Process.Start(fiInf.FullName); }; } } // Transition.run(spaceForIcons, "Visible", false, true, new TransitionType_EaseInEaseOut(150)); spaceForIcons.Visible = true; } /* * Deprecated for now on the hopes that some code that was found/integrated actually turns up. * * private void hmThatIsAReallyInterestingActionWow(object sender, EventArgs e) { System.Diagnostics.Process.Start("explorer"); } */ private void iconMatch(string path) { } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void timeSpaceContinuum_Click(object sender, EventArgs e) { // In the references document, make sure you credit this one to Henry Fidel Bradley Post. UserSettings snoopdoge = new UserSettings(); snoopdoge.Show(); snoopdoge.BringToFront(); } private void pictureBox1_Click(object sender, EventArgs e) { /* * UserSettings backInTheUssettings = new UserSettings(); backInTheUssettings.Show(); backInTheUssettings.BringToFront(); * */ MinervaIntegrated minervuh = new MinervaIntegrated(); minervuh.Show(); minervuh.BringToFront(); } private void spaceForProcesses_Paint(object sender, PaintEventArgs e) { /*spaceForProcesses.Left = 150; spaceForProcesses.Width = spaceForProcesses.Width - 150; spaceForProcesses.Top = 850;*/ spaceForProcesses.BringToFront(); //spaceForProcesses.Height = bottomPanel.Height; } // Well then...looks like we assigned more items here private const int APPCOMMAND_VOLUME_MUTE = 0x80000; private const int APPCOMMAND_VOLUME_UP = 0xA0000; private const int APPCOMMAND_VOLUME_DOWN = 0x90000; private const int WM_APPCOMMAND = 0x319; private void takeTheLongKeyHome(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Up) { /* Robert, does this look like the times of XP anymore? uint meowingDoges; waveOutGetVolume(IntPtr.Zero, out meowingDoges); meowingDoges = meowingDoges & 0x0000ffff; MessageBox.Show(meowingDoges.ToString());*/ //waveOutSetVolume(this.Handle, 0x0000); //MessageBox.Show(waveOutSetVolume(this.Handle, 0x0000).ToString()); // So, just so I remember this doesn't work...THIS DOESN'T WORK, and requires Explorer open. //SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE); } } private void virtualKeyboardsForScienceToolStripMenuItem_Click(object sender, EventArgs e) { VirtualKeyboardsForScience viktorForScience = new VirtualKeyboardsForScience(); viktorForScience.Show(); viktorForScience.BringToFront(); } private void thanksScn9AToolStripMenuItem_Click(object sender, EventArgs e) { ThanksScn9A t = new ThanksScn9A(); t.Show(); t.BringToFront(); } private void toolStripMenuItem1_Click(object sender, EventArgs e) { BattCritical battCriticalHm = new BattCritical(); battCriticalHm.Show(); battCriticalHm.BringToFront(); } private void spaceRightClick_Opening(object sender, CancelEventArgs e) { } private void aboutSnowshoesToolStripMenuItem_Click(object sender, EventArgs e) { AboutSnowshoes aboutBox = new AboutSnowshoes(); aboutBox.Show(); aboutBox.BringToFront(); } private void battLowToolStripMenuItem_Click(object sender, EventArgs e) { BattLow battLowA = new BattLow(); battLowA.Show(); battLowA.BringToFront(); } private void customSearchImplementationOneToolStripMenuItem_Click(object sender, EventArgs e) { // Call supposed to be made from SlidingMenuBar here CustomSearchImplementationOne yeahThat = new CustomSearchImplementationOne(this.Width); yeahThat.Show(); yeahThat.BringToFront(); } private void rightClickDevStrip_Opening(object sender, CancelEventArgs e) { } private void slidingMenuBarToolStripMenuItem_Click(object sender, EventArgs e) { SlidingMenuBar smbagain = new SlidingMenuBar(); smbagain.Show(); smbagain.BringToFront(); } public void youMayWantToRepaint() { this.Refresh(); } private void lockScreenTrueColorsV2ToolStripMenuItem_Click(object sender, EventArgs e) { LockScreen_TrueColors_V2 lstcv2 = new LockScreen_TrueColors_V2(); lstcv2.Show(); lstcv2.BringToFront(); } } }
38.135025
278
0.560765
[ "Apache-2.0" ]
IndigoBox/ProjectSnowshoes
ProjectSnowshoes/Space.cs
37,565
C#
using System; namespace FlubuCore.Tasks.Solution { public interface IFetchBuildVersionTask : ITask { } }
14.75
51
0.711864
[ "BSD-2-Clause" ]
0xflotus/FlubuCore
FlubuCore/Tasks/Versioning/IFetchBuildVersionTask.cs
120
C#
namespace UblTr.Common { [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] [System.Xml.Serialization.XmlRootAttribute("PrintQualifier", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)] public partial class PrintQualifierType : TextType1 { } }
52.083333
169
0.7712
[ "MIT" ]
canyener/Ubl-Tr
Ubl-Tr/Common/CommonBasicComponents/PrintQualifierType.cs
625
C#
using GameEstate.AC.Formats.Entity; using GameEstate.AC.Formats.Props; using GameEstate.Explorer; using GameEstate.Formats; using System.Collections.Generic; using System.IO; using System.Linq; namespace GameEstate.AC.Formats.FileTypes { /// <summary> /// These are client_portal.dat files starting with 0x10. /// It contains information on an items model, texture changes, available palette(s) and icons for that item. /// </summary> /// <remarks> /// Thanks to Steven Nygard and his work on the Mac program ACDataTools that were used to help debug & verify some of this data. /// </remarks> [PakFileType(PakFileType.Clothing)] public class ClothingTable : FileType, IGetExplorerInfo { /// <summary> /// Key is the setup model id /// </summary> public readonly Dictionary<uint, ClothingBaseEffect> ClothingBaseEffects; /// <summary> /// Key is PaletteTemplate /// </summary> public readonly Dictionary<uint, CloSubPalEffect> ClothingSubPalEffects; public ClothingTable(BinaryReader r) { Id = r.ReadUInt32(); ClothingBaseEffects = r.ReadL16Many<uint, ClothingBaseEffect>(sizeof(uint), x => new ClothingBaseEffect(x), offset: 2); ClothingSubPalEffects = r.ReadL16Many<uint, CloSubPalEffect>(sizeof(uint), x => new CloSubPalEffect(x), offset: 2); } //: FileTypes.ClothingTable List<ExplorerInfoNode> IGetExplorerInfo.GetInfoNodes(ExplorerManager resource, FileMetadata file, object tag) { var nodes = new List<ExplorerInfoNode> { new ExplorerInfoNode($"{nameof(ClothingTable)}: {Id:X8}", items: new List<ExplorerInfoNode> { new ExplorerInfoNode("Base Effects", items: ClothingBaseEffects.Select(x => new ExplorerInfoNode($"{x.Key:X8}", items: (x.Value as IGetExplorerInfo).GetInfoNodes(), clickable: true))), new ExplorerInfoNode("SubPalette Effects", items: ClothingSubPalEffects.OrderBy(i => i.Key).Select(x => new ExplorerInfoNode($"{x.Key} - {(PaletteTemplate)x.Key}", items: (x.Value as IGetExplorerInfo).GetInfoNodes()))), }) }; return nodes; } public uint GetIcon(uint palEffectIdx) => ClothingSubPalEffects.TryGetValue(palEffectIdx, out CloSubPalEffect result) ? result.Icon : 0; /// <summary> /// Calculates the ClothingPriority of an item based on the actual coverage. So while an Over-Robe may just be "Chest", we want to know it covers everything but head & arms. /// </summary> /// <param name="setupId">Defaults to HUMAN_MALE if not set, which is good enough</param> /// <returns></returns> public CoverageMask? GetVisualPriority(uint setupId = 0x02000001) { if (!ClothingBaseEffects.TryGetValue(setupId, out var clothingBaseEffect)) return null; CoverageMask visualPriority = 0; foreach (var t in clothingBaseEffect.CloObjectEffects) switch (t.Index) { case 0: // HUMAN_ABDOMEN; visualPriority |= CoverageMask.OuterwearAbdomen; break; case 1: // HUMAN_LEFT_UPPER_LEG; case 5: // HUMAN_RIGHT_UPPER_LEG; visualPriority |= CoverageMask.OuterwearUpperLegs; break; case 2: // HUMAN_LEFT_LOWER_LEG; case 6: // HUMAN_RIGHT_LOWER_LEG; visualPriority |= CoverageMask.OuterwearLowerLegs; break; case 3: // HUMAN_LEFT_FOOT; case 4: // HUMAN_LEFT_TOE; case 7: // HUMAN_RIGHT_FOOT; case 8: // HUMAN_RIGHT_TOE; visualPriority |= CoverageMask.Feet; break; case 9: // HUMAN_CHEST; visualPriority |= CoverageMask.OuterwearChest; break; case 10: // HUMAN_LEFT_UPPER_ARM; case 13: // HUMAN_RIGHT_UPPER_ARM; visualPriority |= CoverageMask.OuterwearUpperArms; break; case 11: // HUMAN_LEFT_LOWER_ARM; case 14: // HUMAN_RIGHT_LOWER_ARM; visualPriority |= CoverageMask.OuterwearLowerArms; break; case 12: // HUMAN_LEFT_HAND; case 15: // HUMAN_RIGHT_HAND; visualPriority |= CoverageMask.Hands; break; case 16: // HUMAN_HEAD; visualPriority |= CoverageMask.Head; break; default: break; // Lots of things we don't care about } return visualPriority; } } }
51.526316
240
0.588151
[ "MIT" ]
bclnet/GameEstate
src/Estates/AC/GameEstate.AC/Formats/FileTypes/ClothingTable.cs
4,895
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.Security.Cryptography.AesCryptoServiceProvider.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.Security.Cryptography { sealed public partial class AesCryptoServiceProvider : Aes { #region Methods and constructors public AesCryptoServiceProvider() { Contract.Ensures(this.FeedbackSizeValue == 8); } public override ICryptoTransform CreateDecryptor(byte[] key, byte[] iv) { return default(ICryptoTransform); } public override ICryptoTransform CreateDecryptor() { return default(ICryptoTransform); } public override ICryptoTransform CreateEncryptor(byte[] key, byte[] iv) { return default(ICryptoTransform); } public override ICryptoTransform CreateEncryptor() { return default(ICryptoTransform); } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } #endregion #region Properties and indexers public override byte[] Key { get { return default(byte[]); } set { } } public override int KeySize { get { return default(int); } set { } } #endregion } }
30.046729
463
0.715708
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.Core/Sources/System.Security.Cryptography.AesCryptoServiceProvider.cs
3,215
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AdminTicket { using System.Data.Linq; using System.Data.Linq.Mapping; using System.Data; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Linq.Expressions; using System.ComponentModel; using System; public partial class TicketDataContext : System.Data.Linq.DataContext { private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource(); #region Extensibility Method Definitions partial void OnCreated(); partial void InsertPassenger(Passenger instance); partial void UpdatePassenger(Passenger instance); partial void DeletePassenger(Passenger instance); partial void InsertCoach(Coach instance); partial void UpdateCoach(Coach instance); partial void DeleteCoach(Coach instance); partial void InsertTicket(Ticket instance); partial void UpdateTicket(Ticket instance); partial void DeleteTicket(Ticket instance); #endregion public TicketDataContext() : base(global::AdminTicket.Properties.Settings.Default.TicketConnection, mappingSource) { OnCreated(); } public TicketDataContext(string connection) : base(connection, mappingSource) { OnCreated(); } public TicketDataContext(System.Data.IDbConnection connection) : base(connection, mappingSource) { OnCreated(); } public TicketDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public TicketDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource) { OnCreated(); } public System.Data.Linq.Table<Passenger> Passengers { get { return this.GetTable<Passenger>(); } } public System.Data.Linq.Table<Coach> Coaches { get { return this.GetTable<Coach>(); } } public System.Data.Linq.Table<Ticket> Tickets { get { return this.GetTable<Ticket>(); } } } [global::System.Data.Linq.Mapping.TableAttribute(Name="")] public partial class Passenger : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _Id; private string _FirstName; private string _LastName; private string _Phone; private string _Email; private System.Nullable<System.DateTime> _RegisterDate; private EntitySet<Ticket> _Tickets; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnIdChanging(int value); partial void OnIdChanged(); partial void OnFirstNameChanging(string value); partial void OnFirstNameChanged(); partial void OnLastNameChanging(string value); partial void OnLastNameChanged(); partial void OnPhoneChanging(string value); partial void OnPhoneChanged(); partial void OnEmailChanging(string value); partial void OnEmailChanged(); partial void OnRegisterDateChanging(System.Nullable<System.DateTime> value); partial void OnRegisterDateChanged(); #endregion public Passenger() { this._Tickets = new EntitySet<Ticket>(new Action<Ticket>(this.attach_Tickets), new Action<Ticket>(this.detach_Tickets)); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", IsPrimaryKey=true)] public int Id { get { return this._Id; } set { if ((this._Id != value)) { this.OnIdChanging(value); this.SendPropertyChanging(); this._Id = value; this.SendPropertyChanged("Id"); this.OnIdChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FirstName", CanBeNull=false)] public string FirstName { get { return this._FirstName; } set { if ((this._FirstName != value)) { this.OnFirstNameChanging(value); this.SendPropertyChanging(); this._FirstName = value; this.SendPropertyChanged("FirstName"); this.OnFirstNameChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_LastName")] public string LastName { get { return this._LastName; } set { if ((this._LastName != value)) { this.OnLastNameChanging(value); this.SendPropertyChanging(); this._LastName = value; this.SendPropertyChanged("LastName"); this.OnLastNameChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Phone", CanBeNull=false)] public string Phone { get { return this._Phone; } set { if ((this._Phone != value)) { this.OnPhoneChanging(value); this.SendPropertyChanging(); this._Phone = value; this.SendPropertyChanged("Phone"); this.OnPhoneChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Email")] public string Email { get { return this._Email; } set { if ((this._Email != value)) { this.OnEmailChanging(value); this.SendPropertyChanging(); this._Email = value; this.SendPropertyChanged("Email"); this.OnEmailChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RegisterDate")] public System.Nullable<System.DateTime> RegisterDate { get { return this._RegisterDate; } set { if ((this._RegisterDate != value)) { this.OnRegisterDateChanging(value); this.SendPropertyChanging(); this._RegisterDate = value; this.SendPropertyChanged("RegisterDate"); this.OnRegisterDateChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="Passenger_Ticket", Storage="_Tickets", ThisKey="Id", OtherKey="PassengerId")] public EntitySet<Ticket> Tickets { get { return this._Tickets; } set { this._Tickets.Assign(value); } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private void attach_Tickets(Ticket entity) { this.SendPropertyChanging(); entity.Passenger = this; } private void detach_Tickets(Ticket entity) { this.SendPropertyChanging(); entity.Passenger = null; } } [global::System.Data.Linq.Mapping.TableAttribute(Name="")] public partial class Coach : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _Id; private string _Name; private string _Router; private string _Type; private System.DateTime _StartDate; private string _StartHour; private int _NumberSeat; private EntitySet<Ticket> _Tickets; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnIdChanging(int value); partial void OnIdChanged(); partial void OnNameChanging(string value); partial void OnNameChanged(); partial void OnRouterChanging(string value); partial void OnRouterChanged(); partial void OnTypeChanging(string value); partial void OnTypeChanged(); partial void OnStartDateChanging(System.DateTime value); partial void OnStartDateChanged(); partial void OnStartHourChanging(string value); partial void OnStartHourChanged(); partial void OnNumberSeatChanging(int value); partial void OnNumberSeatChanged(); #endregion public Coach() { this._Tickets = new EntitySet<Ticket>(new Action<Ticket>(this.attach_Tickets), new Action<Ticket>(this.detach_Tickets)); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Id", IsPrimaryKey=true)] public int Id { get { return this._Id; } set { if ((this._Id != value)) { this.OnIdChanging(value); this.SendPropertyChanging(); this._Id = value; this.SendPropertyChanged("Id"); this.OnIdChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Name")] public string Name { get { return this._Name; } set { if ((this._Name != value)) { this.OnNameChanging(value); this.SendPropertyChanging(); this._Name = value; this.SendPropertyChanged("Name"); this.OnNameChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Router", CanBeNull=false)] public string Router { get { return this._Router; } set { if ((this._Router != value)) { this.OnRouterChanging(value); this.SendPropertyChanging(); this._Router = value; this.SendPropertyChanged("Router"); this.OnRouterChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Type")] public string Type { get { return this._Type; } set { if ((this._Type != value)) { this.OnTypeChanging(value); this.SendPropertyChanging(); this._Type = value; this.SendPropertyChanged("Type"); this.OnTypeChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_StartDate")] public System.DateTime StartDate { get { return this._StartDate; } set { if ((this._StartDate != value)) { this.OnStartDateChanging(value); this.SendPropertyChanging(); this._StartDate = value; this.SendPropertyChanged("StartDate"); this.OnStartDateChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_StartHour", CanBeNull=false)] public string StartHour { get { return this._StartHour; } set { if ((this._StartHour != value)) { this.OnStartHourChanging(value); this.SendPropertyChanging(); this._StartHour = value; this.SendPropertyChanged("StartHour"); this.OnStartHourChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_NumberSeat")] public int NumberSeat { get { return this._NumberSeat; } set { if ((this._NumberSeat != value)) { this.OnNumberSeatChanging(value); this.SendPropertyChanging(); this._NumberSeat = value; this.SendPropertyChanged("NumberSeat"); this.OnNumberSeatChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="Coach_Ticket", Storage="_Tickets", ThisKey="Id", OtherKey="CoachId")] public EntitySet<Ticket> Tickets { get { return this._Tickets; } set { this._Tickets.Assign(value); } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private void attach_Tickets(Ticket entity) { this.SendPropertyChanging(); entity.Coach = this; } private void detach_Tickets(Ticket entity) { this.SendPropertyChanging(); entity.Coach = null; } } [global::System.Data.Linq.Mapping.TableAttribute(Name="")] public partial class Ticket : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _PassengerId; private int _CoachId; private int _SeatId; private string _Status; private System.Nullable<bool> _isNew; private System.DateTime _CreationDate; private EntityRef<Passenger> _Passenger; private EntityRef<Coach> _Coach; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnPassengerIdChanging(int value); partial void OnPassengerIdChanged(); partial void OnCoachIdChanging(int value); partial void OnCoachIdChanged(); partial void OnSeatIdChanging(int value); partial void OnSeatIdChanged(); partial void OnStatusChanging(string value); partial void OnStatusChanged(); partial void OnisNewChanging(System.Nullable<bool> value); partial void OnisNewChanged(); partial void OnCreationDateChanging(System.DateTime value); partial void OnCreationDateChanged(); #endregion public Ticket() { this._Passenger = default(EntityRef<Passenger>); this._Coach = default(EntityRef<Coach>); OnCreated(); } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_PassengerId", IsPrimaryKey=true)] public int PassengerId { get { return this._PassengerId; } set { if ((this._PassengerId != value)) { if (this._Passenger.HasLoadedOrAssignedValue) { throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); } this.OnPassengerIdChanging(value); this.SendPropertyChanging(); this._PassengerId = value; this.SendPropertyChanged("PassengerId"); this.OnPassengerIdChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CoachId", IsPrimaryKey=true)] public int CoachId { get { return this._CoachId; } set { if ((this._CoachId != value)) { if (this._Coach.HasLoadedOrAssignedValue) { throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); } this.OnCoachIdChanging(value); this.SendPropertyChanging(); this._CoachId = value; this.SendPropertyChanged("CoachId"); this.OnCoachIdChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_SeatId", IsPrimaryKey=true)] public int SeatId { get { return this._SeatId; } set { if ((this._SeatId != value)) { this.OnSeatIdChanging(value); this.SendPropertyChanging(); this._SeatId = value; this.SendPropertyChanged("SeatId"); this.OnSeatIdChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Status")] public string Status { get { return this._Status; } set { if ((this._Status != value)) { this.OnStatusChanging(value); this.SendPropertyChanging(); this._Status = value; this.SendPropertyChanged("Status"); this.OnStatusChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_isNew")] public System.Nullable<bool> isNew { get { return this._isNew; } set { if ((this._isNew != value)) { this.OnisNewChanging(value); this.SendPropertyChanging(); this._isNew = value; this.SendPropertyChanged("isNew"); this.OnisNewChanged(); } } } [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_CreationDate")] public System.DateTime CreationDate { get { return this._CreationDate; } set { if ((this._CreationDate != value)) { this.OnCreationDateChanging(value); this.SendPropertyChanging(); this._CreationDate = value; this.SendPropertyChanged("CreationDate"); this.OnCreationDateChanged(); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="Passenger_Ticket", Storage="_Passenger", ThisKey="PassengerId", OtherKey="Id", IsForeignKey=true)] public Passenger Passenger { get { return this._Passenger.Entity; } set { Passenger previousValue = this._Passenger.Entity; if (((previousValue != value) || (this._Passenger.HasLoadedOrAssignedValue == false))) { this.SendPropertyChanging(); if ((previousValue != null)) { this._Passenger.Entity = null; previousValue.Tickets.Remove(this); } this._Passenger.Entity = value; if ((value != null)) { value.Tickets.Add(this); this._PassengerId = value.Id; } else { this._PassengerId = default(int); } this.SendPropertyChanged("Passenger"); } } } [global::System.Data.Linq.Mapping.AssociationAttribute(Name="Coach_Ticket", Storage="_Coach", ThisKey="CoachId", OtherKey="Id", IsForeignKey=true)] public Coach Coach { get { return this._Coach.Entity; } set { Coach previousValue = this._Coach.Entity; if (((previousValue != value) || (this._Coach.HasLoadedOrAssignedValue == false))) { this.SendPropertyChanging(); if ((previousValue != null)) { this._Coach.Entity = null; previousValue.Tickets.Remove(this); } this._Coach.Entity = value; if ((value != null)) { value.Tickets.Add(this); this._CoachId = value.Id; } else { this._CoachId = default(int); } this.SendPropertyChanged("Coach"); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } } #pragma warning restore 1591
24.232962
162
0.640724
[ "MIT" ]
leminhthanh0612/Admin-Ticket
AdminTicket/Ticket.designer.cs
19,558
C#
using System.IO; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using System.Linq; using System.Threading.Tasks; using System; using Newtonsoft.Json.Linq; using Microsoft.Extensions.Logging; using System.Security.Cryptography; namespace DurableFunctionsMonitor.DotNetBackend { public static class ServeStatics { private const string StaticsRoute = "{p1?}/{p2?}/{p3?}"; // A simple statics hosting solution [FunctionName(nameof(DfmServeStaticsFunction))] public static async Task<IActionResult> DfmServeStaticsFunction( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = StaticsRoute)] HttpRequest req, string p1, string p2, string p3, ExecutionContext context, ILogger log ) { return await req.HandleErrors(log, async () => { // Checking nonce, if it was set as an env variable. // Don't care about return value of this method here. Auth.IsNonceSetAndValid(req.Headers); // Two bugs away. Making sure none of these segments ever contain any path separators and/or relative paths string path = Path.Join(Path.GetFileName(p1), Path.GetFileName(p2), Path.GetFileName(p3)); string root = Path.Join(context.FunctionAppDirectory, "DfmStatics"); var contentType = FileMap.FirstOrDefault((kv => path.StartsWith(kv[0]))); if (contentType != null) { string fullPath = Path.Join(root, path); if (!File.Exists(fullPath)) { return new NotFoundResult(); } return new FileStreamResult(File.OpenRead(fullPath), contentType[1]) { LastModified = File.GetLastWriteTimeUtc(fullPath) }; } // Adding anti-forgery token using(var generator = RandomNumberGenerator.Create()) { var bytes = new byte[64]; generator.GetBytes(bytes); string token = Convert.ToBase64String(bytes); req.HttpContext.Response.Cookies .Append(Globals.XsrfTokenCookieAndHeaderName, token, new CookieOptions { HttpOnly = false }); } // Returning index.html by default, to support client routing return await ReturnIndexHtml(context, log, root, p1); }); } private const string DefaultContentSecurityPolicyMeta = "<meta http-equiv=\"Content-Security-Policy " + "content=\"base-uri 'self'; " + "block-all-mixed-content; " + "default-src 'self'; " + "img-src data: 'self' vscode-resource:; " + "object-src 'none'; " + "script-src 'self' 'unsafe-inline' vscode-resource:; " + "connect-src 'self' https://login.microsoftonline.com; " + "frame-src 'self' https://login.microsoftonline.com; " + "style-src 'self' 'unsafe-inline' vscode-resource: https://fonts.googleapis.com; " + "font-src 'self' 'unsafe-inline' https://fonts.gstatic.com; " + "upgrade-insecure-requests;\" " + ">"; private static readonly string[][] FileMap = new string[][] { new [] {Path.Join("static", "css"), "text/css; charset=utf-8"}, new [] {Path.Join("static", "js"), "application/javascript; charset=UTF-8"}, new [] {"manifest.json", "application/json; charset=UTF-8"}, new [] {"favicon.png", "image/png"}, new [] {"logo.svg", "image/svg+xml; charset=UTF-8"}, }; private static string RoutePrefix = null; // Gets routePrefix setting from host.json (since there seems to be no other place to take it from) private static string GetRoutePrefixFromHostJson(ExecutionContext context, ILogger log) { if (RoutePrefix != null) { return RoutePrefix; } try { string hostJsonFileName = Path.Combine(context.FunctionAppDirectory, "host.json"); dynamic hostJson = JObject.Parse(File.ReadAllText(hostJsonFileName)); RoutePrefix = hostJson.extensions.http.routePrefix; } catch (Exception ex) { log.LogError(ex, "Failed to get RoutePrefix from host.json, using default value ('api')"); RoutePrefix = "api"; } return RoutePrefix; } private static string DfmRoutePrefix = null; // Gets DfmRoutePrefix from our function.json file, but only if that file wasn't modified by our build task. private static string GetDfmRoutePrefixFromFunctionJson(ExecutionContext context, ILogger log) { if (DfmRoutePrefix != null) { return DfmRoutePrefix; } DfmRoutePrefix = string.Empty; try { string functionJsonFileName = Path.Combine(context.FunctionAppDirectory, nameof(DfmServeStaticsFunction), "function.json"); dynamic functionJson = JObject.Parse(File.ReadAllText(functionJsonFileName)); string route = functionJson.bindings[0].route; // if it wasn't modified by our build task, then doing nothing if(route != StaticsRoute) { DfmRoutePrefix = route.Substring(0, route.IndexOf("/" + StaticsRoute)); } } catch (Exception ex) { log.LogError(ex, "Failed to get DfmRoutePrefix from function.json, using default value (empty string)"); } return DfmRoutePrefix; } // Populates index.html template and serves it private static async Task<ContentResult> ReturnIndexHtml(ExecutionContext context, ILogger log, string root, string connAndHubName) { string indexHtmlPath = Path.Join(root, "index.html"); string html = await File.ReadAllTextAsync(indexHtmlPath); // Replacing our custom meta tag with customized code from Storage or with default Content Security Policy string customMetaTagCode = (await CustomTemplates.GetCustomMetaTagCodeAsync()) ?? DefaultContentSecurityPolicyMeta; html = html.Replace("<meta name=\"durable-functions-monitor-meta\">", customMetaTagCode); // Calculating routePrefix string routePrefix = GetRoutePrefixFromHostJson(context, log); string dfmRoutePrefix = GetDfmRoutePrefixFromFunctionJson(context, log); if (!string.IsNullOrEmpty(dfmRoutePrefix)) { routePrefix = string.IsNullOrEmpty(routePrefix) ? dfmRoutePrefix : routePrefix + "/" + dfmRoutePrefix; } // Applying routePrefix, if it is set to something other than empty string if (!string.IsNullOrEmpty(routePrefix)) { html = html.Replace("<script>var DfmRoutePrefix=\"\"</script>", $"<script>var DfmRoutePrefix=\"{routePrefix}\"</script>"); html = html.Replace("href=\"/", $"href=\"/{routePrefix}/"); html = html.Replace("src=\"/", $"src=\"/{routePrefix}/"); } // Applying client config, if any string clientConfigString = Environment.GetEnvironmentVariable(EnvVariableNames.DFM_CLIENT_CONFIG); if (!string.IsNullOrEmpty(clientConfigString)) { dynamic clientConfig = JObject.Parse(clientConfigString); html = html.Replace("<script>var DfmClientConfig={}</script>", "<script>var DfmClientConfig=" + clientConfig.ToString() + "</script>"); } // Mentioning whether Function Map is available for this Task Hub. if (!string.IsNullOrEmpty(connAndHubName)) { // Two bugs away. Validating that the incoming Task Hub name looks like a Task Hub name Auth.ThrowIfTaskHubNameHasInvalidSymbols(connAndHubName); Globals.SplitConnNameAndHubName(connAndHubName, out var connName, out var hubName); string functionMap = (await CustomTemplates.GetFunctionMapsAsync()).GetFunctionMap(hubName); if (!string.IsNullOrEmpty(functionMap)) { html = html.Replace("<script>var IsFunctionGraphAvailable=0</script>", "<script>var IsFunctionGraphAvailable=1</script>"); } } return new ContentResult() { Content = html, ContentType = "text/html; charset=UTF-8" }; } } }
43.985577
151
0.577659
[ "MIT" ]
amazi-labs/DurableFunctionsMonitor
durablefunctionsmonitor.dotnetbackend/Functions/ServeStatics.cs
9,149
C#
// // System.Runtime.Remoting.Services.TrackingServices.cs // // Author: // Jaime Anguiano Olarra (jaime@gnome.org) // Patrik Torstensson // // (C) 2002, Jaime Anguiano Olarra // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // 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.Collections; using System.Runtime.Remoting; #if NET_2_0 using System.Runtime.InteropServices; #endif namespace System.Runtime.Remoting.Services { #if NET_2_0 [ComVisible (true)] #endif public class TrackingServices { static ArrayList _handlers = new ArrayList(); public TrackingServices () { } public static void RegisterTrackingHandler (ITrackingHandler handler) { if (null == handler) throw new ArgumentNullException("handler"); lock (_handlers.SyncRoot) { if (-1 != _handlers.IndexOf(handler)) throw new RemotingException("handler already registered"); _handlers.Add(handler); } } public static void UnregisterTrackingHandler (ITrackingHandler handler) { if (null == handler) throw new ArgumentNullException("handler"); lock (_handlers.SyncRoot) { int idx = _handlers.IndexOf(handler); if (idx == -1) throw new RemotingException("handler is not registered"); _handlers.RemoveAt(idx); } } public static ITrackingHandler[] RegisteredHandlers { get { lock (_handlers.SyncRoot) { if (_handlers.Count == 0) return new ITrackingHandler[0]; return (ITrackingHandler[]) _handlers.ToArray (typeof(ITrackingHandler)); } } } internal static void NotifyMarshaledObject(Object obj, ObjRef or) { ITrackingHandler[] handlers; lock (_handlers.SyncRoot) { if (_handlers.Count == 0) return; handlers = (ITrackingHandler[]) _handlers.ToArray (typeof(ITrackingHandler)); } for(int i = 0; i < handlers.Length; i++) { handlers[i].MarshaledObject (obj, or); } } internal static void NotifyUnmarshaledObject(Object obj, ObjRef or) { ITrackingHandler[] handlers; lock (_handlers.SyncRoot) { if (_handlers.Count == 0) return; handlers = (ITrackingHandler[]) _handlers.ToArray (typeof(ITrackingHandler)); } for(int i = 0; i < handlers.Length; i++) { handlers[i].UnmarshaledObject (obj, or); } } internal static void NotifyDisconnectedObject(Object obj) { ITrackingHandler[] handlers; lock (_handlers.SyncRoot) { if (_handlers.Count == 0) return; handlers = (ITrackingHandler[]) _handlers.ToArray (typeof(ITrackingHandler)); } for(int i = 0; i < handlers.Length; i++) { handlers[i].DisconnectedObject (obj); } } } }
27.804511
81
0.703083
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/corlib/System.Runtime.Remoting.Services/TrackingServices.cs
3,698
C#
using System; namespace HodStudio.EntityFrameworkDiffLog.Model { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class LoggedEntityAttribute : Attribute { public const string DefaultIdPropertyName = "Id"; /// <summary> /// Defines that the entity will be logged when using the EntityFrameworkDiffLog. /// It will use the default id property name ("Id"), with case sensitive. /// If your class has a different id property name, use the overload, where you can provide the Id property name. /// </summary> public LoggedEntityAttribute() : this(DefaultIdPropertyName) { } /// <summary> /// Defines that the entity will be logged when using the EntityFrameworkDiffLog. /// Please, pay attention to the fact that the property name is case sensitive. /// Recommendation: use nameof(property) to avoid problems /// </summary> /// <param name="idPropertyName">Id Property name to get the id from the entity</param> public LoggedEntityAttribute(string idPropertyName) => IdPropertyName = idPropertyName; public string IdPropertyName { get; set; } } }
43.714286
121
0.680556
[ "MIT" ]
HodStudio/EfDiffLog
src/HodStudio.EntityFrameworkDiffLog/Model/LoggedEntityAttribute.cs
1,226
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace ImgStoApi.Areas.HelpPage.ModelDescriptions { public class ParameterDescription { public ParameterDescription() { Annotations = new Collection<ParameterAnnotation>(); } public Collection<ParameterAnnotation> Annotations { get; private set; } public string Documentation { get; set; } public string Name { get; set; } public ModelDescription TypeDescription { get; set; } } }
25.714286
80
0.675926
[ "MIT" ]
BugInTheAir/ImgGallery
ImgStoApi/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs
540
C#
using UnityEngine; /// <summary> /// /// </summary> public class HitStopManager : MonoBehaviour { #region Variables private const float REDUCED_TIME_SCALE = 0.05f; private const float NORMAL_TIME_SCALE = 1f; private const float SMALL_INCREASE = 0.15f; private const float BIG_INCREASE = 0.7f; private float linear = 0; private float quad = 0; private float targetTimeScale = 1f; private float prevTimeScale = 1f; [SerializeField] private float timeScale = 1; private float lerpTime = 0.2f; private float lerpTimer = 0f; #endregion ^ Variables #region Properties private float LerpValue => lerpTimer / lerpTime; public bool TimeStopped { get; private set; } #endregion ^ Properties #region Unity Methods private void Update() { if (TimeStopped) return; // Lerp time scale if (lerpTimer > 0) { lerpTimer = Mathf.Clamp(lerpTimer - Time.unscaledDeltaTime, 0, lerpTime); //Time.timeScale = Mathf.Lerp(prevTimeScale, targetTimeScale, 1 - LerpValue); if (lerpTimer <= 0) { Time.timeScale = NORMAL_TIME_SCALE; } } if (linear <= 0) return; linear = Mathf.Clamp01(linear - Time.unscaledDeltaTime); quad = linear * linear; //quad = Mathf.Clamp01(quad - Time.unscaledDeltaTime); Time.timeScale = 1 - quad; //timeScale = Time.timeScale; //if (quad <= 0) // SetTargetScale(NORMAL_TIME_SCALE); } #endregion ^ Unity Methods #region Public Methods public void SmallHit() { SetQuad(SMALL_INCREASE); } public void BigHit() { SetQuad(BIG_INCREASE); } public void StopTime() { TimeStopped = true; Time.timeScale = 0; } public void ResetTimeScale() { Time.timeScale = NORMAL_TIME_SCALE; TimeStopped = false; } #endregion ^ Public Methods #region Helper Methods private void SetQuad(float amount) { //if (quad <= 0) { // SetTargetScale(REDUCED_TIME_SCALE); //} linear = Mathf.Clamp01(linear + amount); quad = amount * amount; SetTargetScale(REDUCED_TIME_SCALE, quad); } private void SetTargetScale(float targetScale, float time) { prevTimeScale = Time.timeScale; Time.timeScale = targetScale; //targetTimeScale = target; lerpTime = time; lerpTimer = lerpTime; } #endregion ^ Helper Methods }
19.610619
80
0.700361
[ "MIT" ]
maxartDanny/GDDi0000_Roll-a-Ball_Danny
Assets/Scripts/GameManagers/HitStopManager.cs
2,218
C#