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 |
|---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Runtime Version: 1.1.4322.573
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
namespace MbUnit.Framework.Tests.Asserts
{
using System;
using System.Collections;
using System.Reflection;
using MbUnit.Core.Framework;
using MbUnit.Framework;
using MbUnit.Core;
using MbUnit.Core.Exceptions;
#region dummy test classes
internal class FailClass
{
public FailClass(int i)
{ }
}
internal class NoPublicConstructor
{
private NoPublicConstructor() { }
}
internal sealed class SuccessClass
{
public string PublicField="public";
private string privateField="private";
public SuccessClass()
{
}
public SuccessClass(string s)
{ }
public string Prop
{
get
{
return privateField;
}
set
{ }
}
public void Method()
{ }
public void Method(string s)
{ }
}
#endregion
[TestFixture("Assertion test")]
[FixtureCategory("Framework.Assertions")]
public class ReflectionAssertTest
{
#region IsSealed
[Test]
public void IsSealed()
{
ReflectionAssert.IsSealed(typeof(SuccessClass));
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void IsSealedFail()
{
ReflectionAssert.IsSealed(typeof(FailClass));
}
#endregion
#region HasConstructor
[Test]
public void HasConstructorNoParamter()
{
ReflectionAssert.HasConstructor(typeof(SuccessClass));
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void HasConstructorNoParamterFail()
{
ReflectionAssert.HasConstructor(typeof(FailClass));
}
[Test]
public void HasConstructorStringParamter()
{
ReflectionAssert.HasConstructor(typeof(SuccessClass),typeof(string));
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void HasConstructorStringParameterFail()
{
ReflectionAssert.HasConstructor(typeof(FailClass),typeof(string));
}
[Test]
public void HasConstructorPrivate()
{
ReflectionAssert.HasConstructor(typeof(NoPublicConstructor),
BindingFlags.Instance | BindingFlags.NonPublic);
}
#endregion
#region HasDefaultConstructor
[Test]
public void HasDefaultConstructor()
{
ReflectionAssert.HasDefaultConstructor(typeof(SuccessClass));
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void HasDefaultConstructorFail()
{
ReflectionAssert.HasDefaultConstructor(typeof(FailClass));
}
#endregion
#region NotCreatable
[Test]
public void NotCreatable()
{
ReflectionAssert.NotCreatable(typeof(NoPublicConstructor));
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void NotCreatableFail()
{
ReflectionAssert.NotCreatable(typeof(SuccessClass));
}
#endregion
#region HasField
[Test]
public void HasField()
{
ReflectionAssert.HasField(typeof(SuccessClass),"PublicField");
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void HasFieldFail()
{
ReflectionAssert.HasField(typeof(FailClass), "PublicField");
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void HasPrivateFieldFail()
{
ReflectionAssert.HasField(typeof(SuccessClass), "privateField");
}
#endregion
#region HasMethod
[Test]
public void HasMethod()
{
ReflectionAssert.HasMethod(typeof(SuccessClass), "Method");
}
[Test]
public void HasMethodOneParameter()
{
ReflectionAssert.HasMethod(typeof(SuccessClass), "Method",typeof(string));
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void HasMethodFail()
{
ReflectionAssert.HasMethod(typeof(FailClass), "Method");
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void HasMethodOneParameterFail()
{
ReflectionAssert.HasMethod(typeof(FailClass), "Method",typeof(string));
}
#endregion
#region IsAssignableFrom
[Test]
public void ObjectIsAssignableFromString()
{
ReflectionAssert.IsAssignableFrom(typeof(Object), typeof(string));
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void StringIsNotAssignableFromObject()
{
ReflectionAssert.IsAssignableFrom(typeof(string),typeof(Object));
}
#endregion
#region IsInstanceOf
[Test]
public void IsInstanceOf()
{
ReflectionAssert.IsInstanceOf(typeof(string), "hello");
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void IsInstanceOfFail()
{
ReflectionAssert.IsInstanceOf(typeof(string), 1);
}
#endregion
#region ReadOnlyProperty
[Test]
public void ReadOnlyProperty()
{
ReflectionAssert.ReadOnlyProperty(typeof(string), "Length");
}
[Test]
[ExpectedException(typeof(AssertionException))]
public void ReadOnlyPropertyFail()
{
ReflectionAssert.ReadOnlyProperty(typeof(SuccessClass), "Prop");
}
#endregion
}
}
| 28.473684 | 91 | 0.548829 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v2 | src/mbunit/MbUnit.Framework.Tests/Asserts/ReflectionAssertTest.cs | 6,494 | C# |
namespace Bitfinex.Client.Websocket.Messages;
public enum MessageType
{
Undefined,
Info,
Auth,
Error,
Ping,
Pong,
Conf,
Subscribe,
Subscribed,
Unsubscribe,
Unsubscribed
} | 13.5 | 46 | 0.634259 | [
"Apache-2.0"
] | shaynevanasperen/bitfinex-client-websocket | src/Bitfinex.Client.Websocket/Messages/MessageType.cs | 218 | C# |
using System.Net;
using System.Net.Sockets;
namespace Fcm.Socketing
{
public interface ISocketEventListener
{
void ConnectionFailed(EndPoint remoteEndPoint, SocketError state);
void ConnectionEstablished();
void ConnectionShutdown(SocketError state);
}
}
| 19.6 | 74 | 0.721088 | [
"MIT"
] | felixwan-git/fcm.net | Fcm/Socketing/ISocketEventListener.cs | 294 | C# |
using ConsoleGUI.Api;
using ConsoleGUI.Buffering;
using ConsoleGUI.Common;
using ConsoleGUI.Controls;
using ConsoleGUI.Data;
using ConsoleGUI.Input;
using ConsoleGUI.Space;
using ConsoleGUI.Utils;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleGUI
{
public static class ConsoleManager
{
private class ConsoleManagerDrawingContextListener : IDrawingContextListener
{
void IDrawingContextListener.OnRedraw(DrawingContext drawingContext)
{
if (_freezeLock.IsFrozen) return;
Redraw();
}
void IDrawingContextListener.OnUpdate(DrawingContext drawingContext, Rect rect)
{
if (_freezeLock.IsFrozen) return;
Update(rect);
}
}
private static readonly ConsoleBuffer _buffer = new ConsoleBuffer();
private static FreezeLock _freezeLock;
private static DrawingContext _contentContext = DrawingContext.Dummy;
private static DrawingContext ContentContext
{
get => _contentContext;
set => Setter
.SetDisposable(ref _contentContext, value)
.Then(Initialize);
}
private static IControl _content;
public static IControl Content
{
get => _content;
set => Setter
.Set(ref _content, value)
.Then(BindContent);
}
private static IConsole _console = new StandardConsole();
public static IConsole Console
{
get => _console;
set => Setter
.Set(ref _console, value)
.Then(Initialize);
}
private static Position? _mousePosition;
public static Position? MousePosition
{
get => _mousePosition;
set => Setter
.Set(ref _mousePosition, value)
.Then(UpdateMouseContext);
}
private static bool _mouseDown;
public static bool MouseDown
{
get => _mouseDown;
set
{
if (_mouseDown && !value)
MouseContext?.MouseListener?.OnMouseUp(MouseContext.Value.RelativePosition);
if (!_mouseDown && value)
MouseContext?.MouseListener?.OnMouseDown(MouseContext.Value.RelativePosition);
_mouseDown = value;
}
}
private static MouseContext? _mouseContext;
private static MouseContext? MouseContext
{
get => _mouseContext;
set
{
if (value?.MouseListener != _mouseContext?.MouseListener)
{
_mouseContext?.MouseListener.OnMouseLeave();
value?.MouseListener.OnMouseEnter();
value?.MouseListener.OnMouseMove(value.Value.RelativePosition);
}
else if (value.HasValue && value.Value.RelativePosition != _mouseContext?.RelativePosition)
{
value.Value.MouseListener.OnMouseMove(value.Value.RelativePosition);
}
_mouseContext = value;
}
}
public static Size WindowSize => Console.Size;
public static Size BufferSize => _buffer.Size;
private static void Initialize()
{
var consoleSize = BufferSize;
Console.Initialize();
_freezeLock.Freeze();
ContentContext.SetLimits(consoleSize, consoleSize);
_freezeLock.Unfreeze();
Redraw();
}
private static void Redraw()
{
Update(ContentContext.Size.AsRect());
}
private static void Update(Rect rect)
{
Console.OnRefresh();
rect = Rect.Intersect(rect, Rect.OfSize(BufferSize));
rect = Rect.Intersect(rect, Rect.OfSize(WindowSize));
for (int y = rect.Top; y <= rect.Bottom; y++)
{
for (int x = rect.Left; x <= rect.Right; x++)
{
var position = new Position(x, y);
var cell = ContentContext[position];
if (!_buffer.Update(position, cell)) continue;
try
{
Console.Write(position, cell.Character);
}
catch (ArgumentOutOfRangeException)
{
rect = Rect.Intersect(rect, Rect.OfSize(WindowSize));
}
}
}
}
public static void Setup()
{
Resize(WindowSize);
}
public static void Resize(in Size size)
{
Console.Size = size;
_buffer.Initialize(size);
Initialize();
}
public static void AdjustBufferSize()
{
if (WindowSize != BufferSize)
Resize(WindowSize);
}
public static void AdjustWindowSize()
{
if (WindowSize != BufferSize)
Resize(BufferSize);
}
public static void ReadInput(IReadOnlyCollection<IInputListener> controls)
{
while (Console.KeyAvailable)
{
var key = Console.ReadKey();
var inputEvent = new InputEvent(key);
foreach (var control in controls)
{
control?.OnInput(inputEvent);
if (inputEvent.Handled) break;
}
}
}
private static void BindContent()
{
ContentContext = new DrawingContext(new ConsoleManagerDrawingContextListener(), Content);
}
private static void UpdateMouseContext()
{
MouseContext = MousePosition.HasValue
? _buffer.GetMouseContext(MousePosition.Value)
: null;
}
}
}
| 22.023697 | 95 | 0.694427 | [
"MIT"
] | ittennull/C-sharp-console-gui-framework | ConsoleGUI/ConsoleManager.cs | 4,649 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Web.V20201001.Outputs
{
[OutputType]
public sealed class EnabledConfigResponse
{
/// <summary>
/// True if configuration is enabled, false if it is disabled and null if configuration is not set.
/// </summary>
public readonly bool? Enabled;
[OutputConstructor]
private EnabledConfigResponse(bool? enabled)
{
Enabled = enabled;
}
}
}
| 27 | 107 | 0.667989 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Web/V20201001/Outputs/EnabledConfigResponse.cs | 756 | C# |
////////////////////////////////
//
// Copyright 2018 Battelle Energy Alliance, LLC
//
//
////////////////////////////////
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataLayer
{
using System;
using System.Collections.Generic;
public partial class USER_DETAIL_INFORMATION
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public USER_DETAIL_INFORMATION()
{
this.ADDRESSes = new HashSet<ADDRESS>();
this.FINDING_CONTACT = new HashSet<FINDING_CONTACT>();
this.USERS = new HashSet<USER>();
}
public System.Guid Id { get; set; }
public string CellPhone { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string HomePhone { get; set; }
public string OfficePhone { get; set; }
public string ImagePath { get; set; }
public string JobTitle { get; set; }
public string Organization { get; set; }
public string PrimaryEmail { get; set; }
public string SecondaryEmail { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ADDRESS> ADDRESSes { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<FINDING_CONTACT> FINDING_CONTACT { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<USER> USERS { get; set; }
}
}
| 40.90566 | 128 | 0.601937 | [
"MIT"
] | Harshilpatel134/cisagovdocker | CSETWebApi/CSETWeb_Api/DataLayer/USER_DETAIL_INFORMATION.cs | 2,168 | C# |
using System;
using System.Threading.Tasks;
using MiniTwit.Entities;
namespace MiniTwit.Models.Tests
{
internal static class Utility
{
public static async Task Add_dummy_data(UserRepository userRepository, MessageRepository messageRepository)
{
var extraUser = new User();
for (var i = 1; i < 10; i++)
{
var user1 = new User
{
UserName = "user" + i,
Email = "user" + i + "@kanban.com"
};
var message1 = new Message
{
Author = user1,
PubDate = new DateTime(2019, 1, i),
Text = "waddup" + i
};
extraUser = user1;
await userRepository.CreateAsync(user1);
await messageRepository.CreateAsync(message1);
}
var extraMessage = new Message
{
Author = extraUser,
PubDate = new DateTime(2018, 1, 1),
Text = "waddup"
};
await messageRepository.CreateAsync(extraMessage);
var extraMessage2 = new Message
{
Author = extraUser,
PubDate = new DateTime(2018, 1, 2),
Text = "waddup",
Flagged = 1
};
await messageRepository.CreateAsync(extraMessage2);
}
}
} | 31.446809 | 115 | 0.467524 | [
"MIT"
] | jlndk/devoops | MiniTwit.Models.Test/TestUtils.cs | 1,480 | C# |
namespace OnlineShop.Models.Products.Components
{
public class RandomAccessMemory : Component
{
private const double OverallPerfomance_Multiplier = 1.20;
public RandomAccessMemory(int id, string manufacturer,
string model, decimal price, double overallPerformance, int generation)
: base(id, manufacturer, model, price, overallPerformance, generation)
{
}
public override double OverallPerformance
=> base.OverallPerformance * OverallPerfomance_Multiplier;
}
}
| 32.470588 | 83 | 0.690217 | [
"MIT"
] | ivaylo-R/CSharp-OOP-Exams | Exam 16 August 2020/OnlineShop-Skeleton/OnlineShop/Models/Products/Components/RandomAccessMemory.cs | 554 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from include/vulkan/vulkan_core.h in the KhronosGroup/Vulkan-Headers repository for tag v1.2.198
// Original source is Copyright © 2015-2021 The Khronos Group Inc.
namespace TerraFX.Interop.Vulkan
{
public unsafe partial struct VkPhysicalDeviceVulkan11Features
{
public VkStructureType sType;
public void* pNext;
public VkBool32 storageBuffer16BitAccess;
public VkBool32 uniformAndStorageBuffer16BitAccess;
public VkBool32 storagePushConstant16;
public VkBool32 storageInputOutput16;
public VkBool32 multiview;
public VkBool32 multiviewGeometryShader;
public VkBool32 multiviewTessellationShader;
public VkBool32 variablePointersStorageBuffer;
public VkBool32 variablePointers;
public VkBool32 protectedMemory;
public VkBool32 samplerYcbcrConversion;
public VkBool32 shaderDrawParameters;
}
}
| 27.897436 | 145 | 0.742647 | [
"MIT"
] | tannergooding/terrafx.interop.vulkan | sources/Interop/Vulkan/Vulkan/vulkan/vulkan_core/VkPhysicalDeviceVulkan11Features.cs | 1,090 | C# |
using System.Threading.Tasks;
using IdentityInfo.Core.Swedish.Requests.CoordinationNumbers;
using IdentityInfo.Web.Areas.Swedish.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace IdentityInfo.Web.Areas.Swedish.Controllers
{
[Area(SwedishAreaConfiguration.AreaName)]
[Route("coordinationnumber")]
public class CoordinationNumberController : Controller
{
private readonly IMediator _meditator;
public CoordinationNumberController(IMediator meditator)
{
_meditator = meditator;
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
[HttpGet("validate")]
public async Task<IActionResult> Validate([FromQuery] Validate.Query query)
{
if (query.Number != null && query.Number.Length > 50)
{
return new BadRequestResult();
}
var result = await _meditator.Send(query);
return View(result);
}
[HttpGet("randomize")]
public async Task<IActionResult> Randomize([FromQuery] Randomize.Query query)
{
if (query.Count != null && (query.Count < 1 || query.Count > 10))
{
return new BadRequestResult();
}
var result = await _meditator.Send(query);
return View(result);
}
[HttpGet("testdata")]
public async Task<IActionResult> TestDataList([FromQuery] GetTestdataList.Query query)
{
if (query.Limit > 1000)
{
return new BadRequestResult();
}
var result = await _meditator.Send(query);
var viewModel = new SwedishCoordinationNumberTestdataListViewModel(query, result);
return View(viewModel);
}
[HttpGet("/api/swedish/coordinationnumber/testdata/json")]
public async Task<IActionResult> TestDataListApi([FromQuery] GetTestdataList.ApiQuery query)
{
var result = await _meditator.Send(query);
return Json(result);
}
}
}
| 30.070423 | 100 | 0.594848 | [
"MIT"
] | PeterOrneholm/IdentityInfo.net | src/IdentityInfo.Web/Areas/Swedish/Controllers/CoordinationNumberController.cs | 2,135 | C# |
using System;
using System.IO;
using System.Net;
using Cassandra.DistributedLock.Tests.Logging;
using NUnit.Framework;
using SkbKontur.Cassandra.Local;
using SkbKontur.Cassandra.ThriftClient.Abstractions;
using SkbKontur.Cassandra.ThriftClient.Clusters;
using SkbKontur.Cassandra.ThriftClient.Schema;
namespace Cassandra.DistributedLock.Tests
{
[SetUpFixture]
public class SingleCassandraNodeSetUpFixture
{
[OneTimeSetUp]
public static void SetUp()
{
Log4NetConfiguration.InitializeOnce();
var templateDirectory = Path.Combine(FindCassandraTemplateDirectory(AppDomain.CurrentDomain.BaseDirectory), @"v3.11.x");
var deployDirectory = Path.Combine(Path.GetTempPath(), "deployed_cassandra_v3.11.x");
node = new LocalCassandraNode(templateDirectory, deployDirectory)
{
RpcPort = 9360,
CqlPort = 9343,
JmxPort = 7399,
GossipPort = 7400,
};
node.Restart(timeout : TimeSpan.FromMinutes(1));
var logger = Log4NetConfiguration.RootLogger.ForContext(nameof(SingleCassandraNodeSetUpFixture));
cassandraCluster = new CassandraCluster(CreateCassandraClusterSettings(), logger);
var cassandraSchemaActualizer = new CassandraSchemaActualizer(cassandraCluster, eventListener : null, logger);
cassandraSchemaActualizer.ActualizeKeyspaces(new[]
{
new KeyspaceSchema
{
Name = RemoteLockKeyspace,
Configuration = new KeyspaceConfiguration
{
ReplicationStrategy = SimpleReplicationStrategy.Create(replicationFactor : 1),
ColumnFamilies = new[]
{
new ColumnFamily
{
Name = RemoteLockColumnFamily,
Caching = ColumnFamilyCaching.KeysOnly
}
}
}
}
}, changeExistingKeyspaceMetadata : false);
}
[OneTimeTearDown]
public static void TearDown()
{
node.Stop();
}
public static ICassandraClusterSettings CreateCassandraClusterSettings(int attempts = 5, TimeSpan? timeout = null)
{
return new SingleNodeCassandraClusterSettings(new IPEndPoint(IPAddress.Parse(node.RpcAddress), node.RpcPort))
{
ClusterName = node.ClusterName,
Attempts = attempts,
Timeout = (int)(timeout ?? TimeSpan.FromSeconds(6)).TotalMilliseconds,
};
}
public static void TruncateAllColumnFamilies()
{
cassandraCluster.RetrieveColumnFamilyConnection(RemoteLockKeyspace, RemoteLockColumnFamily).Truncate();
}
private static string FindCassandraTemplateDirectory(string currentDir)
{
if (currentDir == null)
throw new Exception("Невозможно найти каталог с Cassandra-шаблонами");
var cassandraTemplateDirectory = Path.Combine(currentDir, cassandraTemplates);
return Directory.Exists(cassandraTemplateDirectory) ? cassandraTemplateDirectory : FindCassandraTemplateDirectory(Path.GetDirectoryName(currentDir));
}
public const string RemoteLockKeyspace = "TestRemoteLockKeyspace";
public const string RemoteLockColumnFamily = "TestRemoteLockCf";
private const string cassandraTemplates = @"cassandra-local\cassandra";
private static LocalCassandraNode node;
private static CassandraCluster cassandraCluster;
}
} | 42.333333 | 161 | 0.580217 | [
"MIT"
] | skbkontur/cassandra-distributed-lock | Cassandra.DistributedLock.Tests/SingleCassandraNodeSetUpFixture.cs | 4,096 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BackgroundProgram")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BackgroundProgram")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3058e9af-f435-4ddc-92a8-690eef9044ca")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.746979 | [
"MIT"
] | ZoeyZolotova/app-as-wallpaper | BackgroundProgram/Properties/AssemblyInfo.cs | 1,410 | C# |
using Magellan.ComponentModel;
using Magellan.Utilities;
namespace Magellan.Controls.Conventions.Editors
{
/// <summary>
/// Represents a collection of <see cref="IEditorStrategy">editor strategies</see>.
/// </summary>
public class EditorStrategyCollection : Set<IEditorStrategy>
{
private readonly IEditorStrategy fallback;
/// <summary>
/// Initializes a new instance of the <see cref="EditorStrategyCollection"/> class.
/// </summary>
/// <param name="fallback">The fallback.</param>
public EditorStrategyCollection(IEditorStrategy fallback)
{
Guard.ArgumentNotNull(fallback, "fallback");
this.fallback = fallback;
}
/// <summary>
/// Asks each <see cref="IEditorStrategy">editor strategy</see> in the list whether it can create a
/// control for editing the given field, returning the first non-null result. If none of the editors
/// can provide an editor, the fallback editor is asked.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public object GetEditor(FieldContext context)
{
foreach (var selector in this)
{
var editor = selector.CreateEditor(context);
if (editor != null)
{
return editor;
}
}
return fallback.CreateEditor(context);
}
/// <summary>
/// Inserts an item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="item">The item.</param>
public void Insert(int index, IEditorStrategy item)
{
Edit(x =>
{
if (x.Count == 0)
x.Add(item);
else x.Insert(index, item);
});
}
}
} | 35.568966 | 110 | 0.521086 | [
"MIT"
] | CADbloke/magellan-framework | src/Magellan/Controls/Conventions/Editors/EditorStrategyCollection.cs | 2,065 | C# |
using Newtonsoft.Json;
namespace PlenBotLogUploader.Aleeva
{
public class AleevaServer
{
[JsonProperty("id")]
public string ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("avatar")]
public string Avatar { get; set; }
public override string ToString() => $"{Name} ({ID})";
}
}
| 20.473684 | 62 | 0.573265 | [
"MIT"
] | DelusionalElitists/PlenBotLogUploader | Aleeva/AleevaServer.cs | 391 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Special;
using Grasshopper.Kernel.Types;
using RhinoInside.Revit.External.DB.Extensions;
using DB = Autodesk.Revit.DB;
namespace RhinoInside.Revit.GH.Parameters.Input
{
#region DocumentValuePicker
public abstract class DocumentValuePicker : GH_ValueList, Kernel.IGH_ElementIdParam
{
#region IGH_ElementIdParam
protected virtual DB.ElementFilter ElementFilter => null;
public virtual bool PassesFilter(DB.Document document, Autodesk.Revit.DB.ElementId id)
{
return ElementFilter?.PassesFilter(document, id) ?? true;
}
bool Kernel.IGH_ElementIdParam.NeedsToBeExpired
(
DB.Document doc,
ICollection<DB.ElementId> added,
ICollection<DB.ElementId> deleted,
ICollection<DB.ElementId> modified
)
{
// If anything of that type is added we need to update ListItems
if (added.Where(id => PassesFilter(doc, id)).Any())
return true;
// If selected items are modified we need to expire dependant components
foreach (var data in VolatileData.AllData(true).OfType<Types.IGH_ElementId>())
{
if (!data.IsValid)
continue;
if (modified.Contains(data.Id))
return true;
}
// If an item in ListItems is deleted we need to update ListItems
foreach (var item in ListItems.Select(x => x.Value).OfType<Grasshopper.Kernel.Types.GH_Integer>())
{
var id = new DB.ElementId(item.Value);
if (deleted.Contains(id))
return true;
}
return false;
}
#endregion
}
public abstract class DocumentCategoriesPicker : DocumentValuePicker
{
public override GH_Exposure Exposure => GH_Exposure.hidden;
public override bool PassesFilter(DB.Document document, DB.ElementId id) => id.IsCategoryId(document);
protected abstract bool CategoryIsInSet(DB.Category category);
protected abstract DB.BuiltInCategory DefaultBuiltInCategory { get; }
public DocumentCategoriesPicker()
{
Category = "Revit";
SubCategory = "Input";
NickName = "Document";
MutableNickName = false;
Name = $"{NickName} Categories Picker";
Description = $"Provides a {NickName} Category picker";
ListMode = GH_ValueListMode.DropDown;
}
protected override void CollectVolatileData_Custom()
{
var selectedItems = ListItems.Where(x => x.Selected).Select(x => x.Expression).ToList();
ListItems.Clear();
if (Revit.ActiveDBDocument is object)
{
foreach (var group in Revit.ActiveDBDocument.Settings.Categories.Cast<DB.Category>().GroupBy(x => x.CategoryType).OrderBy(x => x.Key))
{
foreach (var category in group.OrderBy(x => x.Name).Where(x => CategoryIsInSet(x)))
{
if (!category.Id.IsBuiltInId())
continue;
if (category.CategoryType == DB.CategoryType.Invalid)
continue;
var item = new GH_ValueListItem(category.Name, category.Id.IntegerValue.ToString());
item.Selected = selectedItems.Contains(item.Expression);
ListItems.Add(item);
}
}
if (selectedItems.Count == 0 && ListMode != GH_ValueListMode.CheckList)
{
foreach (var item in ListItems)
item.Selected = item.Expression == ((int) DefaultBuiltInCategory).ToString();
}
}
base.CollectVolatileData_Custom();
}
}
[Obsolete("Since 2021-06-10. Please use 'Built-In Categories'")]
public class ModelCategoriesPicker : DocumentCategoriesPicker
{
public override Guid ComponentGuid => new Guid("EB266925-F1AA-4729-B5C0-B978937F51A3");
public override string NickName => MutableNickName ? base.NickName : "Model";
protected override DB.BuiltInCategory DefaultBuiltInCategory => DB.BuiltInCategory.OST_GenericModel;
protected override bool CategoryIsInSet(DB.Category category) => !category.IsTagCategory && category.CategoryType == DB.CategoryType.Model;
public ModelCategoriesPicker() { }
}
[Obsolete("Since 2021-06-10. Please use 'Built-In Categories'")]
public class AnnotationCategoriesPicker : DocumentCategoriesPicker
{
public override Guid ComponentGuid => new Guid("B1D1CA45-3771-49CA-8540-9A916A743C1B");
public override string NickName => MutableNickName ? base.NickName : "Annotation";
protected override DB.BuiltInCategory DefaultBuiltInCategory => DB.BuiltInCategory.OST_GenericAnnotation;
protected override bool CategoryIsInSet(DB.Category category) => !category.IsTagCategory && category.CategoryType == DB.CategoryType.Annotation;
public AnnotationCategoriesPicker() { }
}
[Obsolete("Since 2021-06-10. Please use 'Built-In Categories'")]
public class TagCategoriesPicker : DocumentCategoriesPicker
{
public override Guid ComponentGuid => new Guid("30F6DA06-35F9-4E83-AE9E-080AF26C8326");
public override string NickName => MutableNickName ? base.NickName : "Tag";
protected override DB.BuiltInCategory DefaultBuiltInCategory => DB.BuiltInCategory.OST_GenericModelTags;
protected override bool CategoryIsInSet(DB.Category category) => category.IsTagCategory;
public TagCategoriesPicker() { }
}
[Obsolete("Since 2021-06-10. Please use 'Built-In Categories'")]
public class AnalyticalCategoriesPicker : DocumentCategoriesPicker
{
public override Guid ComponentGuid => new Guid("4120C5ED-4329-4F42-B8D3-FA518E6E6807");
public override string NickName => MutableNickName ? base.NickName : "Analytical";
protected override DB.BuiltInCategory DefaultBuiltInCategory => DB.BuiltInCategory.OST_AnalyticalNodes;
protected override bool CategoryIsInSet(DB.Category category) => !category.IsTagCategory && category.CategoryType == DB.CategoryType.AnalyticalModel;
public AnalyticalCategoriesPicker() { }
}
#endregion
#region DocumentElementPicker
public abstract class DocumentElementPicker<T> : Grasshopper.Special.ValueSet<T>,
Kernel.IGH_ElementIdParam
where T : class, IGH_Goo
{
protected DocumentElementPicker(string name, string nickname, string description, string category, string subcategory) :
base(name, nickname, description, category, subcategory)
{
IconDisplayMode = GH_IconDisplayMode.icon;
}
protected override System.Drawing.Bitmap Icon =>
((System.Drawing.Bitmap) Properties.Resources.ResourceManager.GetObject(GetType().Name)) ??
base.Icon;
#region IGH_ElementIdParam
protected virtual DB.ElementFilter ElementFilter => null;
public virtual bool PassesFilter(DB.Document document, DB.ElementId id)
{
return ElementFilter?.PassesFilter(document, id) ?? true;
}
bool Kernel.IGH_ElementIdParam.NeedsToBeExpired
(
DB.Document doc,
ICollection<DB.ElementId> added,
ICollection<DB.ElementId> deleted,
ICollection<DB.ElementId> modified
)
{
// If selected items are modified we need to expire dependant components
foreach (var data in VolatileData.AllData(true).OfType<Types.IGH_ElementId>())
{
if (!doc.IsEquivalent(data.Document))
continue;
if (modified.Contains(data.Id) || deleted.Contains(data.Id))
return true;
}
if (SourceCount == 0)
{
// If an element that pass the filter is added we need to update ListItems
var updateListItems = added.Where(id => PassesFilter(doc, id)).Any();
if (!updateListItems)
{
// If an item in ListItems is deleted we need to update ListItems
foreach (var item in ListItems.Select(x => x.Value).OfType<Types.IGH_ElementId>())
{
if (!doc.IsEquivalent(item.Document))
continue;
if (modified.Contains(item.Id) || deleted.Contains(item.Id))
{
updateListItems = true;
break;
}
}
}
if (updateListItems)
{
ClearData();
CollectData();
ComputeData();
OnDisplayExpired(false);
}
}
return false;
}
#endregion
}
public class DocumentLevelsPicker : DocumentElementPicker<Types.Level>
{
public override Guid ComponentGuid => new Guid("BD6A74F3-8C46-4506-87D9-B34BD96747DA");
public override GH_Exposure Exposure => GH_Exposure.secondary;
protected override DB.ElementFilter ElementFilter => new DB.ElementClassFilter(typeof(DB.Level));
public DocumentLevelsPicker() : base
(
name: "Levels Picker",
nickname: "Levels",
description: "Provides a Level picker",
category: "Revit",
subcategory: "Input"
)
{}
protected override void LoadVolatileData()
{
if (SourceCount == 0)
{
m_data.Clear();
if (Document.TryGetCurrentDocument(this, out var doc))
{
using (var collector = new DB.FilteredElementCollector(doc.Value))
{
m_data.AppendRange(collector.OfClass(typeof(DB.Level)).Cast<DB.Level>().Select(x => new Types.Level(x)));
}
}
}
base.LoadVolatileData();
}
protected override void SortItems()
{
// Show elements sorted Alphabetically.
ListItems.Sort((x, y) =>
{
var result = (int) (x.Value.Value.GetHeight() - y.Value.Value.GetHeight());
return result == 0 ? string.CompareOrdinal(x.Name, y.Name) : result;
});
}
}
public class DocumentFamiliesPicker : DocumentElementPicker<Types.Family>
{
public override Guid ComponentGuid => new Guid("45CEE087-4194-4E55-AA20-9CC5D2193CE0");
public override GH_Exposure Exposure => GH_Exposure.secondary;
protected override DB.ElementFilter ElementFilter => new DB.ElementClassFilter(typeof(DB.Family));
public DocumentFamiliesPicker() : base
(
name: "Component Families Picker",
nickname: "Component Families",
description: "Provides a Family picker",
category: "Revit",
subcategory : "Input"
)
{}
protected override void LoadVolatileData()
{
if (SourceCount == 0)
{
m_data.Clear();
if (Document.TryGetCurrentDocument(this, out var doc))
{
using (var collector = new DB.FilteredElementCollector(doc.Value))
{
m_data.AppendRange(collector.OfClass(typeof(DB.Family)).Cast<DB.Family>().Select(x => new Types.Family(x)));
}
}
}
base.LoadVolatileData();
}
}
#endregion
}
| 35.038339 | 154 | 0.652321 | [
"MIT"
] | japhyw/rhino.inside-revit | src/RhinoInside.Revit.GH/Parameters/Input/DocumentPicker.cs | 10,967 | C# |
/******************************************************************************
* Copyright (C) Ultraleap, Inc. 2011-2020. *
* Ultraleap proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Ultraleap and you, your company or other organization. *
******************************************************************************/
using Leap.Unity.Query;
using UnityEngine;
using UnityEngine.Events;
namespace Leap.Unity.Interaction.Examples {
/// <summary>
/// This simple example script disables the InteractionHand script and has event
/// outputs to drive hiding Leap hand renderers when it detects that an
/// InteractionXRController is tracked and moving (e.g. it has been picked up).
///
/// It also does some basic checks with hand distance so that you can see your hands
/// when you put the controller down and you hide the hands when they're obviously
/// holding the controller (e.g. tracked as very close to the controller).
/// </summary>
public class HideInteractionHandWhenControllerMoving : MonoBehaviour {
public InteractionXRController intCtrl;
public InteractionHand intHand;
public UnityEvent OnInteractionHandEnabled;
public UnityEvent OnInteractionHandDisabled;
private float _handSeparationDistance = 0.23f;
private float _handHoldingDistance = 0.18f;
private void Reset() {
if (intCtrl == null) {
intCtrl = GetComponent<InteractionXRController>();
}
if (intCtrl != null && intHand == null && this.transform.parent != null) {
intHand = this.transform.parent.GetChildren().Query()
.Select(t => t.GetComponent<InteractionHand>())
.Where(h => h != null)
.FirstOrDefault(h => h.isLeft == intCtrl.isLeft);
}
}
private void Update() {
if (intCtrl != null && intCtrl.isActiveAndEnabled && intHand != null) {
var shouldIntHandBeEnabled = !intCtrl.isBeingMoved;
if (intCtrl.isTracked) {
var handPos = intHand.position;
var ctrlPos = intCtrl.position;
var handControllerDistanceSqr = (handPos - ctrlPos).sqrMagnitude;
// Also allow the hand to be active if it's far enough away from the controller.
if (handControllerDistanceSqr > _handSeparationDistance * _handSeparationDistance) {
shouldIntHandBeEnabled = true;
}
// Prevent the hand from being active if it's very close to the controller.
if (handControllerDistanceSqr < _handHoldingDistance * _handHoldingDistance) {
shouldIntHandBeEnabled = false;
}
}
if (shouldIntHandBeEnabled && !intHand.enabled) {
intHand.enabled = true;
OnInteractionHandEnabled.Invoke();
}
if (!shouldIntHandBeEnabled && intHand.enabled) {
intHand.enabled = false;
OnInteractionHandDisabled.Invoke();
}
}
}
}
}
| 39.105882 | 95 | 0.586342 | [
"MIT"
] | HyperLethalVector/ProjectEsky-UnityIntegration | Assets/Plugins/LeapMotion/Modules/InteractionEngine/Scripts/Utility/HideInteractionHandWhenControllerMoving.cs | 3,324 | C# |
using System;
public class Student
{
public Student()
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<double> Marks { get; set; }
public double Mark => this.Marks.Average();
public Dictionary<string, double> Strengths { get; set; }
}
}
//using System.Collections.Generic;
//using System.Linq;
//public class Student
//{
// public string FirstName { get; set; }
// public string LastName { get; set; }
// public List<double> Marks { get; set; }
// public double Mark => this.Marks.Average();
// public Dictionary<string, double> Strengths { get; set; }
//}
| 24.961538 | 63 | 0.637904 | [
"MIT"
] | petiatodorova/CSharpAdvancedExercises | Sets/Student.cs | 651 | C# |
using Aiursoft.Scanner.Interfaces;
namespace Kahla.SDK.Services
{
public class KahlaLocation : ISingletonDependency
{
private string _kahlaRoot = "https://server.kahla.app";
public override string ToString()
{
return _kahlaRoot;
}
public void UseKahlaServer(string kahlaServerRootPath)
{
_kahlaRoot = kahlaServerRootPath;
}
}
}
| 21.2 | 63 | 0.620283 | [
"MIT"
] | JTOne123/Kahla | Kahla.SDK/Services/KahlaLocation.cs | 426 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Calculator.Account {
public partial class Confirm {
/// <summary>
/// successPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder successPanel;
/// <summary>
/// login control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink login;
/// <summary>
/// errorPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder errorPanel;
}
}
| 32.159091 | 84 | 0.506007 | [
"MIT"
] | muhammadbaiquni/calculator-aspnet | Calculator/Account/Confirm.aspx.designer.cs | 1,417 | C# |
namespace Limit.OfficialSite.Domain.Entities
{
/// <summary>
/// 定义基本实体类型的接口。系统中的所有实体都必须实现此接口
/// </summary>
/// <typeparam name="TPrimaryKey">实体的主键的类型</typeparam>
public interface IEntity<TPrimaryKey>
{
/// <summary>
/// 此实体的唯一标识符
/// </summary>
TPrimaryKey Id { get; set; }
}
} | 24.285714 | 58 | 0.579412 | [
"MIT"
] | Jokwcs/OfficialWebsite-master | src/Common/Limit.OfficialSite/Domain/Entities/IEntityOfTPrimaryKey.cs | 432 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// 組件的一般資訊是由下列的屬性集控制。
// 變更這些屬性的值即可修改組件的相關
// 資訊。
[assembly: AssemblyTitle("TurnBased")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TurnBased")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 將 ComVisible 設為 false 可對 COM 元件隱藏
// 組件中的類型。若必須從 COM 存取此組件中的類型,
// 的類型,請在該類型上將 ComVisible 屬性設定為 true。
[assembly: ComVisible(false)]
// 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID
[assembly: Guid("30ef7fe3-e17b-463d-921f-e610ba654f9b")]
// 組件的版本資訊由下列四個值所組成:
//
// 主要版本
// 次要版本
// 組建編號
// 修訂編號
//
// 您可以指定所有的值,或將組建編號或修訂編號設為預設值
//方法是使用 '*',如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3.*")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: SecurityTransparent]
[assembly: SecurityRules(SecurityRuleSet.Level2, SkipVerificationInFullTrust = true)]
| 26.418605 | 85 | 0.735035 | [
"MIT"
] | michalnh/KingmakerTurnBasedMod | TurnBased/Properties/AssemblyInfo.cs | 1,473 | C# |
using HDF.PInvoke;
using HDF5CSharp.DataTypes;
using HDF5CSharp.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace HDF5CSharp
{
public class Hdf5Dataset : IHdf5ReaderWriter
{
public (bool success, Array result) ReadToArray<T>(long groupId, string name, string alternativeName)
{
return Hdf5.ReadDatasetToArray<T>(groupId, name, alternativeName);
}
public (int success, long CreatedgroupId) WriteFromArray<T>(long groupId, string name, Array dset)
{
return Hdf5.WriteDatasetFromArray<T>(groupId, name, dset);
}
public (int success, long CreatedgroupId) WriteStrings(long groupId, string name, IEnumerable<string> collection, string datasetName = null)
{
return Hdf5.WriteStrings(groupId, name, (string[])collection);
}
public Array ReadStructs<T>(long groupId, string name, string alternativeName) where T : struct
{
return Hdf5.ReadCompounds<T>(groupId, name, alternativeName).ToArray();
}
public (bool success, IEnumerable<string>) ReadStrings(long groupId, string name, string alternativeName)
{
return Hdf5.ReadStrings(groupId, name, alternativeName);
}
}
public static partial class Hdf5
{
static Hdf5ReaderWriter dsetRW = new Hdf5ReaderWriter(new Hdf5Dataset());
public static bool DatasetExists(long groupId, string datasetName) => Hdf5Utils.ItemExists(groupId, datasetName, Hdf5ElementType.Dataset);
/// <summary>
/// Reads an n-dimensional dataset.
/// </summary>
/// <typeparam name="T">Generic parameter strings or primitive type</typeparam>
/// <param name="groupId">id of the group. Can also be a file Id</param>
/// <param name="name">name of the dataset</param>
/// <param name="alternativeName">Alternative name</param>
/// <returns>The n-dimensional dataset</returns>
public static (bool success, Array result) ReadDatasetToArray<T>(long groupId, string name, string alternativeName = "") //where T : struct
{
var (valid, datasetName) = Hdf5Utils.GetRealName(groupId, name, alternativeName);
if (!valid)
{
Hdf5Utils.LogError?.Invoke($"Error reading {groupId}. Name:{name}. AlternativeName:{alternativeName}");
return (false, Array.Empty<T>());
}
var datasetId = H5D.open(groupId, datasetName);
var datatype = GetDatatype(typeof(T));
var spaceId = H5D.get_space(datasetId);
int rank = H5S.get_simple_extent_ndims(spaceId);
long count = H5S.get_simple_extent_npoints(spaceId);
Array dset;
Type type = typeof(T);
if (rank >= 0 && count >= 0)
{
int rankChunk;
ulong[] maxDims = new ulong[rank];
ulong[] dims = new ulong[rank];
ulong[] chunkDims = new ulong[rank];
long memId = H5S.get_simple_extent_dims(spaceId, dims, maxDims);
long[] lengths = dims.Select(d => Convert.ToInt64(d)).ToArray();
dset = Array.CreateInstance(type, lengths);
//var typeId = H5D.get_type(datasetId);
//var mem_type = H5T.copy(datatype);
if (datatype == H5T.C_S1)
{
H5T.set_size(datatype, new IntPtr(2));
}
var propId = H5D.get_create_plist(datasetId);
if (H5D.layout_t.CHUNKED == H5P.get_layout(propId))
{
rankChunk = H5P.get_chunk(propId, rank, chunkDims);
}
memId = H5S.create_simple(rank, dims, maxDims);
GCHandle hnd = GCHandle.Alloc(dset, GCHandleType.Pinned);
H5D.read(datasetId, datatype, memId, spaceId,
H5P.DEFAULT, hnd.AddrOfPinnedObject());
hnd.Free();
}
else
{
dset = Array.CreateInstance(type, new long[1] { 0 });
}
H5D.close(datasetId);
H5S.close(spaceId);
return (true, dset);
}
/// <summary>
/// Reads part of a two dimensional dataset.
/// </summary>
/// <typeparam name="T">Generic parameter strings or primitive type</typeparam>
/// <param name="groupId">id of the group. Can also be a file Id</param>
/// <param name="name">name of the dataset</param>
/// <param name="beginIndex">The index of the first row to be read</param>
/// <param name="endIndex">The index of the last row to be read</param>
/// <returns>The two dimensional dataset</returns>
public static T[,] ReadDataset<T>(long groupId, string name, ulong beginIndex, ulong endIndex) //where T : struct
{
ulong[] start = { 0, 0 }, stride = null, count = { 0, 0 },
block = null, offsetOut = { 0, 0 };
var datatype = GetDatatype(typeof(T));
var datasetId = H5D.open(groupId, Hdf5Utils.NormalizedName(name));
var spaceId = H5D.get_space(datasetId);
int rank = H5S.get_simple_extent_ndims(spaceId);
ulong[] maxDims = new ulong[rank];
ulong[] dims = new ulong[rank];
ulong[] chunkDims = new ulong[rank];
var memId_n = H5S.get_simple_extent_dims(spaceId, dims, maxDims);
start[0] = beginIndex;
start[1] = 0;
count[0] = endIndex - beginIndex + 1;
count[1] = dims[1];
var status = H5S.select_hyperslab(spaceId, H5S.seloper_t.SET, start, stride, count, block);
// Define the memory dataspace.
T[,] dset = new T[count[0], count[1]];
var memId = H5S.create_simple(rank, count, null);
// Define memory hyperslab.
status = H5S.select_hyperslab(memId, H5S.seloper_t.SET, offsetOut, null,
count, null);
// Read data from hyperslab in the file into the hyperslab in
// memory and display.
GCHandle hnd = GCHandle.Alloc(dset, GCHandleType.Pinned);
H5D.read(datasetId, datatype, memId, spaceId,
H5P.DEFAULT, hnd.AddrOfPinnedObject());
hnd.Free();
H5D.close(datasetId);
H5S.close(spaceId);
H5S.close(memId);
return dset;
}
/// <summary>
/// Reads part of a two dimensional dataset.
/// </summary>
/// <typeparam name="T">Generic parameter strings or primitive type</typeparam>
/// <param name="groupId">id of the group. Can also be a file Id</param>
/// <param name="name">name of the dataset</param>
/// <param name="beginIndex">The index of the first row to be read</param>
/// <param name="endIndex">The index of the last row to be read</param>
/// <returns>The two dimensional dataset</returns>
public static T[] ReadRowsFromDataset<T>(long groupId, string name, ulong beginIndex, ulong endIndex)
{
ulong[] start = { 0, 0 }, stride = null, count = { 0 },
block = null, offsetOut = { 0, 0 };
Type type = typeof(T);
var typeId = CreateType(type);
string normalizedName = Hdf5Utils.NormalizedName(name);
var datasetId = H5D.open(groupId, normalizedName);
var spaceId = H5D.get_space(datasetId);
int rank = H5S.get_simple_extent_ndims(spaceId);
ulong[] maxDims = new ulong[rank];
ulong[] dims = new ulong[rank];
ulong[] chunkDims = new ulong[rank];
var memId_n = H5S.get_simple_extent_dims(spaceId, dims, maxDims);
start[0] = beginIndex;
start[1] = 0;
count[0] = endIndex - beginIndex + 1;
var status = H5S.select_hyperslab(spaceId, H5S.seloper_t.SET, start, stride, count, block);
var memId = H5S.create_simple(rank, count, null);
// Define memory hyperslab.
status = H5S.select_hyperslab(memId, H5S.seloper_t.SET, offsetOut, null,
count, null);
// Define the memory dataspace.
int msgSize = Marshal.SizeOf(type) * (int)count[0];
IntPtr ptr = Marshal.AllocHGlobal(msgSize);
// Read data from hyperslab in the file into the hyperslab in
// memory and display.
H5D.read(datasetId, typeId, memId, spaceId,
H5P.DEFAULT, ptr);
T[] msg = new T[count[0]];
for (int i = 0; i < (int)count[0]; i++)
{
IntPtr ins = new IntPtr(ptr.ToInt64() + i * Marshal.SizeOf(type));
msg[i] = Marshal.PtrToStructure<T>(ins);
}
H5D.close(datasetId);
H5S.close(spaceId);
H5S.close(memId);
return msg;
}
/// <summary>
/// Reads a dataset or string array with one value in it
/// </summary>
/// <typeparam name="T">Generic parameter strings or primitive type</typeparam>
/// <param name="groupId">id of the group. Can also be a file Id</param>
/// <param name="name">name of the dataset</param>
/// <param name="alternativeName"></param>
/// <returns>One value or string</returns>
public static T ReadOneValue<T>(long groupId, string name, string alternativeName = "") //where T : struct
{
var dset = dsetRW.ReadArray<T>(groupId, name, alternativeName);
int[] first = new int[dset.result.Rank].Select(f => 0).ToArray();
T result = (T)dset.result.GetValue(first);
return result;
}
public static (bool success, Array result) ReadDataset<T>(long groupId, string name, string alternativeName = "")
{
return dsetRW.ReadArray<T>(groupId, name, alternativeName);
}
/// <summary>
/// Writes one value to a hdf5 file
/// </summary>
/// <typeparam name="T">Generic parameter strings or primitive type</typeparam>
/// <param name="groupId">id of the group. Can also be a file Id</param>
/// <param name="name">name of the dataset</param>
/// <param name="dset">The dataset</param>
/// <returns>status of the write method</returns>
public static (int success, long CreatedgroupId) WriteOneValue<T>(long groupId, string name, T dset, Dictionary<string, List<string>> attributes)
{
if (typeof(T) == typeof(string))
//WriteStrings(groupId, name, new string[] { dset.ToString() });
{
return dsetRW.WriteArray(groupId, name, new T[1] { dset }, attributes);
}
Array oneVal = new T[1, 1] { { dset } };
return dsetRW.WriteArray(groupId, name, oneVal, attributes);
}
public static void WriteDataset(long groupId, string name, Array collection)
{
dsetRW.WriteArray(groupId, name, collection, new Dictionary<string, List<string>>());
}
public static (int success, long CreatedgroupId) WriteDatasetFromArray<T>(long groupId, string name, Array dset) //where T : struct
{
int rank = dset.Rank;
ulong[] dims = Enumerable.Range(0, rank).Select(i => { return (ulong)dset.GetLength(i); }).ToArray();
ulong[] maxDims = null;
var spaceId = H5S.create_simple(rank, dims, maxDims);
var datatype = GetDatatype(typeof(T));
var typeId = H5T.copy(datatype);
if (datatype == H5T.C_S1)
{
H5T.set_size(datatype, new IntPtr(2));
}
string normalizedName = Hdf5Utils.NormalizedName(name);
var datasetId = Hdf5Utils.GetDatasetId(groupId, normalizedName, datatype, spaceId, H5P.DEFAULT);
if (datasetId == -1L)
{
return (-1, -1L);
}
GCHandle hnd = GCHandle.Alloc(dset, GCHandleType.Pinned);
var result = H5D.write(datasetId, datatype, H5S.ALL, H5S.ALL, H5P.DEFAULT,
hnd.AddrOfPinnedObject());
hnd.Free();
H5D.close(datasetId);
H5S.close(spaceId);
H5T.close(typeId);
return (result, datasetId);
}
/// <summary>
/// Appends a dataset to a hdf5 file. If called the first time a dataset is created
/// </summary>
/// <typeparam name="T">Generic parameter only primitive types are allowed</typeparam>
/// <param name="groupId">id of the group. Can also be a file Id</param>
/// <param name="name">name of the dataset</param>
/// <param name="dset">The dataset</param>
/// <returns>status of the write method</returns>
public static long AppendDataset<T>(long groupId, string name, Array dset, ulong chunkX = 200) where T : struct
{
var rank = dset.Rank;
ulong[] dimsExtend = Enumerable.Range(0, rank).Select(i =>
{ return (ulong)dset.GetLength(i); }).ToArray();
ulong[] maxDimsExtend = null;
ulong[] dimsChunk = new[] { chunkX }.Concat(dimsExtend.Skip(1)).ToArray();
ulong[] zeros = Enumerable.Range(0, rank).Select(z => (ulong)0).ToArray();
long status, spaceId, datasetId;
// name = ToHdf5Name(name);
var datatype = GetDatatype(typeof(T));
var typeId = H5T.copy(datatype);
var datasetExists = H5L.exists(groupId, Hdf5Utils.NormalizedName(name)) > 0;
/* Create a new dataset within the file using chunk
creation properties. */
if (!datasetExists)
{
spaceId = H5S.create_simple(dset.Rank, dimsExtend, maxDimsExtend);
datasetId = Hdf5Utils.GetDatasetId(groupId, Hdf5Utils.NormalizedName(name), typeId, spaceId, H5P.DEFAULT);
var propId = H5P.create(H5P.DATASET_CREATE);
status = H5P.set_chunk(propId, rank, dimsChunk);
/* Write data to dataset */
GCHandle hnd = GCHandle.Alloc(dset, GCHandleType.Pinned);
status = H5D.write(datasetId, datatype, H5S.ALL, H5S.ALL, H5P.DEFAULT,
hnd.AddrOfPinnedObject());
hnd.Free();
H5P.close(propId);
}
else
{
datasetId = H5D.open(groupId, Hdf5Utils.NormalizedName(name));
spaceId = H5D.get_space(datasetId);
var rank_old = H5S.get_simple_extent_ndims(spaceId);
ulong[] maxDims = new ulong[rank_old];
ulong[] dims = new ulong[rank_old];
var memId1 = H5S.get_simple_extent_dims(spaceId, dims, maxDims);
ulong[] oldChunk = null;
int chunkDims = 0;
var propId = H5P.create(H5P.DATASET_ACCESS);
status = H5P.get_chunk(propId, chunkDims, oldChunk);
/* Extend the dataset. */
var size = new[] { dims[0] + dimsExtend[0] }.Concat(dims.Skip(1)).ToArray();
status = H5D.set_extent(datasetId, size);
/* Select a hyperslab in extended portion of dataset */
var filespaceId = H5D.get_space(datasetId);
var offset = new[] { dims[0] }.Concat(zeros.Skip(1)).ToArray();
status = H5S.select_hyperslab(filespaceId, H5S.seloper_t.SET, offset, null,
dimsExtend, null);
/* Define memory space */
var memId2 = H5S.create_simple(rank, dimsExtend, null);
/* Write the data to the extended portion of dataset */
GCHandle hnd = GCHandle.Alloc(dset, GCHandleType.Pinned);
status = H5D.write(datasetId, datatype, memId2, spaceId,
H5P.DEFAULT, hnd.AddrOfPinnedObject());
hnd.Free();
H5S.close(memId1);
H5S.close(memId2);
H5D.close(filespaceId);
}
//todo: close?
H5T.close(datatype);
H5D.close(datasetId);
H5S.close(spaceId);
return status;
}
}
}
| 43.923483 | 153 | 0.562324 | [
"MIT"
] | DavidSabbah/HDF5-CSharp | HDF5-CSharp/Hdf5Dataset.cs | 16,649 | C# |
using UnityEngine;
using System.Collections;
/// <summary>
/// Components to permits rotation of a game object in a specified angle
/// </summary>
public class RotateAroundPivot : MonoBehaviour {
[SerializeField] GameObject pivot;
[SerializeField] float rotateAngle;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
/// <summary>
/// Rotation under the z axes using Quaternion.Euler
/// </summary>
/// <param name="z">The angle with the z axes</param>
public void RotationZ(float z, float distOfPivot){
//We rotate the game object
transform.rotation = Quaternion.Euler(0,0,z);
//then we put it at the correct position
float rad = (z+rotateAngle) * Mathf.Deg2Rad;
transform.position = pivot.transform.position + distOfPivot * new Vector3(Mathf.Sin (rad), -Mathf.Cos (rad));
}
}
| 25.470588 | 111 | 0.704388 | [
"MIT"
] | SneakyRedSnake/rogue-shield | Assets/Scripts/RotateAroundPivot.cs | 868 | C# |
#region
using LoESoft.Core;
using LoESoft.GameServer.realm.terrain;
using System;
#endregion
namespace LoESoft.GameServer.realm.mapsetpiece
{
internal class Pentaract : MapSetPiece
{
private static readonly string Floor = "Scorch Blend";
private static readonly byte[,] Circle =
{
{0, 0, 1, 1, 1, 0, 0},
{0, 1, 1, 1, 1, 1, 0},
{1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1, 0},
{0, 0, 1, 1, 1, 0, 0}
};
public override int Size => 41;
public override void RenderSetPiece(World world, IntPoint pos)
{
int[,] t = new int[41, 41];
for (int i = 0; i < 5; i++)
{
double angle = (360 / 5 * i) * (float)Math.PI / 180;
int x_ = (int)(Math.Cos(angle) * 15 + 20 - 3);
int y_ = (int)(Math.Sin(angle) * 15 + 20 - 3);
for (int x = 0; x < 7; x++)
for (int y = 0; y < 7; y++)
{
t[x_ + x, y_ + y] = Circle[x, y];
}
t[x_ + 3, y_ + 3] = 2;
}
t[20, 20] = 3;
EmbeddedData data = GameServer.Manager.GameData;
for (int x = 0; x < 40; x++)
for (int y = 0; y < 40; y++)
{
if (t[x, y] == 1)
{
WmapTile tile = world.Map[x + pos.X, y + pos.Y].Clone();
tile.TileId = data.IdToTileType[Floor];
tile.ObjType = 0;
world.Map[x + pos.X, y + pos.Y] = tile;
}
else if (t[x, y] == 2)
{
WmapTile tile = world.Map[x + pos.X, y + pos.Y].Clone();
tile.TileId = data.IdToTileType[Floor];
tile.ObjType = 0;
world.Map[x + pos.X, y + pos.Y] = tile;
Entity penta = Entity.Resolve(0x0d5e);
penta.Move(pos.X + x + .5f, pos.Y + y + .5f);
world.EnterWorld(penta);
}
else if (t[x, y] == 3)
{
Entity penta = Entity.Resolve("Pentaract");
penta.Move(pos.X + x + .5f, pos.Y + y + .5f);
world.EnterWorld(penta);
}
}
}
}
} | 33.205128 | 80 | 0.365251 | [
"MIT"
] | Devwarlt/LOE-V7-SERVER | gameserver/realm/mapsetpiece/setpieces/Pentaract.cs | 2,592 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Z3Data
{
public class Timeline
{
string _dataDir = null;
ArrayList _rows = null;
Dictionary<string, int> _col2inx = new Dictionary<string, int>();
public Timeline(string dir, string dataDir, string filename)
{
_dataDir = dataDir;
Load(dir, filename);
}
public Dictionary<string, CategoryStatistics> Categories
{
get { return _cats; }
}
public SortedSet<string> CategoryNames
{
get { return _catnames; }
}
public Job Job(uint id)
{
return new Job(_dataDir, id);
}
public Job LastJob
{
get { return Job(LastJobId); }
}
public Summary LastSummary
{
get { return new Summary(_dataDir, LastJob); }
}
public uint LastJobId
{
get { return _lastJobId; }
}
public int CategoryCount
{
get { return _cats.Count; }
}
public int RowCount
{
get { return _rows.Count; }
}
public string Lookup(int row, string cat)
{
int inx = _col2inx[cat];
return ((string[])_rows[row])[inx];
}
protected void Load(string dir, string filename)
{
_cats = new Dictionary<string, CategoryStatistics>();
_catnames = new SortedSet<string>();
StreamReader f = new StreamReader(Path.IsPathRooted(filename) ? filename : dir + "\\" + filename);
string line = f.ReadLine();
if (line == null)
return;
int colcount = 0;
string[] a = line.Split(',');
foreach (string s in a)
{
string ss = s.Trim('"');
_col2inx[ss] = colcount++;
int del_inx = ss.IndexOf('|');
if (del_inx < 0)
continue;
string cat = ss.Substring(0, del_inx);
if (!_cats.ContainsKey(cat))
{
_cats.Add(cat, new CategoryStatistics());
_catnames.Add(cat);
}
}
_rows = new ArrayList();
while (!f.EndOfStream)
{
line = f.ReadLine();
a = line.Split(',');
if (a.Length > 2)
{
uint id = Convert.ToUInt32(a[1]);
if (id > _lastJobId)
_lastJobId = id;
string[] b = new string[a.Count()];
for (uint i = 0; i < a.Count(); i++)
b[i] = a[i].Trim('"');
_rows.Add(b);
}
}
}
public static void Make(StreamWriter f, ref Jobs jobs)
{
int[] codes = { 0, 1, 2, 3, 4, 6, 5, 7, 8, 9, 98, 99 };
string[] codenames = { "SAT", "UNSAT", "UNKNOWN", "BUG", "ERROR", "MEMORY", "TIMEOUT", "SATTIME", "UNSATTIME", "INFERR", "OVERPERF", "UNDERPERF" };
f.Write("Date,ID");
HashSet<string> categories = new HashSet<string>();
foreach (Job j in jobs)
{
foreach (string cat in j.Summary.Categories)
if (!categories.Contains(cat))
categories.Add(cat);
}
foreach (string c in categories)
for (int i = 0; i < codes.Length; i++)
f.Write(",\"" + c + "|" + codenames[i] + "\"");
f.WriteLine();
foreach (Job j in jobs)
{
f.Write("\"" + j.MetaData.SubmissionTime.ToString(Global.culture) + "\",");
f.Write(j.MetaData.Id.ToString());
foreach (string category in categories)
{
Summary s = j.Summary;
for (int i = 0; i < codes.Length; i++)
{
int code = codes[i];
string name = codenames[i];
if (!s.ContainsKey(category))
{
f.Write(",0");
}
else
{
CategoryStatistics cs = s[category];
switch (code)
{
case 0: f.Write("," + cs.SAT.ToString()); break;
case 1: f.Write("," + cs.UNSAT.ToString()); break;
case 2: f.Write("," + cs.UNKNOWN.ToString()); break;
case 3: f.Write("," + cs.Bugs.ToString()); break;
case 4: f.Write("," + cs.Errors.ToString()); break;
case 5: f.Write("," + cs.Timeout.ToString()); break;
case 6: f.Write("," + cs.Memout.ToString()); break;
case 7: f.Write("," + cs.TimeSAT.ToString()); break;
case 8: f.Write("," + cs.TimeUNSAT.ToString()); break;
case 9: f.Write("," + cs.InfrastructureErrors.ToString()); break;
case 98: f.Write("," + cs.Overperformers.ToString()); break;
case 99: f.Write("," + cs.UnderPerformers.ToString()); break;
}
}
}
}
f.WriteLine();
}
}
// Cached stuff.
Dictionary<string, CategoryStatistics> _cats = null;
SortedSet<string> _catnames = null;
uint _lastJobId = 0;
}
}
| 31.376963 | 159 | 0.417654 | [
"MIT"
] | 0152la/z3test | ClusterExperiment/Z3Data/Timeline.cs | 5,995 | C# |
using System;
using System.Collections.Generic;
namespace Separation.Core.Models
{
public partial class Reports
{
public Reports()
{
BarCodeNumbers = new HashSet<BarCodeNumbers>();
FollowUps = new HashSet<FollowUps>();
}
public int ReportId { get; set; }
public int? ClientId { get; set; }
public int? IncidentId { get; set; }
public int? SuspendId { get; set; }
public DateTime? IncidentDate { get; set; }
public string Summary { get; set; }
public string PoliceCaseNum { get; set; }
public int? StaffId { get; set; }
public DateTime? ReturnDate { get; set; }
public string FollowUpSummary { get; set; }
public DateTime? FollowUpDate { get; set; }
public DateTime? ReportDate { get; set; }
public string ReportPage { get; set; }
public int? DepartmentId { get; set; }
public DateTime? ReturnDateSundown { get; set; }
public virtual Clients Client { get; set; }
public virtual Departments Department { get; set; }
public virtual Incidents Incident { get; set; }
public virtual Staff Staff { get; set; }
public virtual SuspendTimes Suspend { get; set; }
public virtual ICollection<BarCodeNumbers> BarCodeNumbers { get; set; }
public virtual ICollection<FollowUps> FollowUps { get; set; }
}
}
| 36.692308 | 79 | 0.612159 | [
"MIT"
] | JoshuaEmery/Separation | Separation/Separation.Core/Models/Reports.cs | 1,433 | C# |
#region License
/* FNA - XNA4 Reimplementation for Desktop Platforms
* Copyright 2009-2018 Ethan Lee and the MonoGame Team
*
* Released under the Microsoft Public License.
* See LICENSE for details.
*/
#endregion
#region Using Statements
using System;
#endregion
namespace Microsoft.Xna.Framework.Input.Touch
{
// https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.touch.gesturetype.aspx
[Flags]
public enum GestureType
{
None = 0x000,
Tap = 0x001,
DoubleTap = 0x002,
Hold = 0x004,
HorizontalDrag = 0x008,
VerticalDrag = 0x010,
FreeDrag = 0x020,
Pinch = 0x040,
Flick = 0x080,
DragComplete = 0x100,
PinchComplete = 0x200
}
}
| 21.030303 | 97 | 0.711816 | [
"MIT"
] | Genobreaker/Myra | deps/FNA/src/Input/Touch/GestureType.cs | 694 | C# |
using Newtonsoft.Json;
namespace DGP.Genshin.MiHoYoAPI.UserInfo
{
public class UserFuncStatus
{
[JsonProperty("enable_history_view")] public bool EnableHistoryView { get; set; }
[JsonProperty("enable_recommend")] public bool EnableRecommend { get; set; }
[JsonProperty("enable_mention")] public bool EnableMention { get; set; }
}
}
| 30.833333 | 89 | 0.697297 | [
"MIT"
] | ICMYS/KeqingNiuza | src/KeqingNiuza.RealtimeNotes/DGP.Genshin/MiHoYoAPI/UserInfo/UserFuncStatus.cs | 372 | 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.live.Transform;
using Aliyun.Acs.live.Transform.V20161101;
namespace Aliyun.Acs.live.Model.V20161101
{
public class DescribeLiveDomainRealTimeTrafficDataRequest : RpcAcsRequest<DescribeLiveDomainRealTimeTrafficDataResponse>
{
public DescribeLiveDomainRealTimeTrafficDataRequest()
: base("live", "2016-11-01", "DescribeLiveDomainRealTimeTrafficData", "live", "openAPI")
{
}
private string locationNameEn;
private string startTime;
private string ispNameEn;
private string domainName;
private string endTime;
private long? ownerId;
public string LocationNameEn
{
get
{
return locationNameEn;
}
set
{
locationNameEn = value;
DictionaryUtil.Add(QueryParameters, "LocationNameEn", value);
}
}
public string StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
DictionaryUtil.Add(QueryParameters, "StartTime", value);
}
}
public string IspNameEn
{
get
{
return ispNameEn;
}
set
{
ispNameEn = value;
DictionaryUtil.Add(QueryParameters, "IspNameEn", value);
}
}
public string DomainName
{
get
{
return domainName;
}
set
{
domainName = value;
DictionaryUtil.Add(QueryParameters, "DomainName", value);
}
}
public string EndTime
{
get
{
return endTime;
}
set
{
endTime = value;
DictionaryUtil.Add(QueryParameters, "EndTime", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public override DescribeLiveDomainRealTimeTrafficDataResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DescribeLiveDomainRealTimeTrafficDataResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 22.827068 | 125 | 0.662055 | [
"Apache-2.0"
] | fossabot/aliyun-openapi-net-sdk | aliyun-net-sdk-live/Live/Model/V20161101/DescribeLiveDomainRealTimeTrafficDataRequest.cs | 3,036 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 套餐包管理模块
* 套餐包管理模块
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using JDCloudSDK.Core.Client;
using JDCloudSDK.Core.Http;
using System;
using System.Collections.Generic;
using System.Text;
namespace JDCloudSDK.Starshield.Client
{
/// <summary>
/// 套餐包列表查询
/// </summary>
public class DescribePackagesExecutor : JdcloudExecutor
{
/// <summary>
/// 套餐包列表查询接口的Http 请求方法
/// </summary>
public override string Method
{
get {
return "GET";
}
}
/// <summary>
/// 套餐包列表查询接口的Http资源请求路径
/// </summary>
public override string Url
{
get {
return "/regions/{regionId}/packages";
}
}
}
}
| 24.266667 | 76 | 0.623626 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Starshield/Client/DescribePackagesExecutor.cs | 1,558 | C# |
using Hudl.FFmpeg.Command.BaseTypes;
using Hudl.FFmpeg.Command.Models;
using Hudl.FFmpeg.Settings;
using Hudl.FFmpeg.Settings.Interfaces;
using Hudl.FFmpeg.Settings.Serialization;
namespace Hudl.FFprobe.Command
{
internal class FFprobeCommandBuilder : FFCommandBuilderBase, ICommandBuilder
{
public void WriteCommand(ICommand command)
{
WriteCommand((FFprobeCommand)command);
}
public void WriteCommand(FFprobeCommand command)
{
var inputResource = new Input(command.Resource);
BuilderBase.Append(" ");
BuilderBase.Append(SettingSerializer.Serialize(inputResource));
command.Settings.ForEach(WriteSerializerSpecifier);
}
public void WriteSerializerSpecifier(ISetting setting)
{
BuilderBase.Append(" ");
BuilderBase.Append(SettingSerializer.Serialize(setting));
}
}
}
| 30.290323 | 80 | 0.675186 | [
"Apache-2.0"
] | alex6dj/HudlFfmpeg | Hudl.FFprobe/Command/FFprobeCommandBuilder.cs | 941 | C# |
using System;
using System.Web.Mvc;
using System.Linq;
using System.Linq.Expressions;
using Ext.Scheduler.Models;
using System.Web.Script.Serialization;
namespace Controllers {
public class AssignmentsController : Controller
{
readonly DataClasses1DataContext _db = new DataClasses1DataContext();
public JsonResult Get()
{
return this.Json(new { assignmentdata = _db.Assignments,
resources = _db.Resources }, JsonRequestBehavior.AllowGet);
}
public JsonResult Delete(string assignmentdata)
{
var deps = (Assignment[])new JavaScriptSerializer().Deserialize<Assignment[]>(assignmentdata);
foreach (Assignment d in deps)
{
Assignment dep = _db.Assignments.SingleOrDefault(b => b.Id == d.Id);
if (dep != null)
{
_db.Assignments.DeleteOnSubmit(dep);
}
}
_db.SubmitChanges();
return this.Json(new { success = true });
}
public JsonResult Create(string assignmentdata)
{
var vals = (Assignment[])new JavaScriptSerializer().Deserialize<Assignment[]>(assignmentdata);
foreach (Assignment dep in vals)
{
if (vals != null)
{
_db.Assignments.InsertOnSubmit(dep);
}
}
_db.SubmitChanges();
return this.Json(new { success = true, assignmentdata = vals});
}
}
}
| 29.981132 | 106 | 0.553178 | [
"MIT"
] | ww362034710/Gannt | public/gantt/gantt2.5.1/examples/ASP.NET MVC2 demo/Ext Gantt + ASP.NET MVC/Controllers/AssignmentsController.cs | 1,589 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Kmd.Studica.Programmes.Client
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for StudentActivityReportsExternal.
/// </summary>
public static partial class StudentActivityReportsExternalExtensions
{
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='periodFrom'>
/// Beginning of period for activity report quarters.
/// The {PeriodFrom} parameter must be a date that is on or before given
/// activity report period
/// to include the desired report in the output.
/// E.g. if specifying PeriodFrom as 2021-01-01 and PeriodTo as 2021-06-30
/// you will only get the activity report for 2nd period of 2021 (March 16 to
/// June 15)
/// </param>
/// <param name='periodTo'>
/// End of period for activity report quarters. The {PeriodTo} parameter must
/// fully encompass
/// the end date of a given activity report quarter to include the desired
/// report in the output.
/// E.g. to get all activity reports for 2020 the PeriodFrom could be
/// 2019-12-15
/// and PeriodTo could be 2020-12-30
/// </param>
/// <param name='schoolCode'>
/// The school code for which to get data.
/// </param>
public static IList<ActivityGroupDto> Get(this IStudentActivityReportsExternal operations, System.DateTime periodFrom, System.DateTime periodTo, string schoolCode)
{
return operations.GetAsync(periodFrom, periodTo, schoolCode).GetAwaiter().GetResult();
}
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='periodFrom'>
/// Beginning of period for activity report quarters.
/// The {PeriodFrom} parameter must be a date that is on or before given
/// activity report period
/// to include the desired report in the output.
/// E.g. if specifying PeriodFrom as 2021-01-01 and PeriodTo as 2021-06-30
/// you will only get the activity report for 2nd period of 2021 (March 16 to
/// June 15)
/// </param>
/// <param name='periodTo'>
/// End of period for activity report quarters. The {PeriodTo} parameter must
/// fully encompass
/// the end date of a given activity report quarter to include the desired
/// report in the output.
/// E.g. to get all activity reports for 2020 the PeriodFrom could be
/// 2019-12-15
/// and PeriodTo could be 2020-12-30
/// </param>
/// <param name='schoolCode'>
/// The school code for which to get data.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<ActivityGroupDto>> GetAsync(this IStudentActivityReportsExternal operations, System.DateTime periodFrom, System.DateTime periodTo, string schoolCode, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(periodFrom, periodTo, schoolCode, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 46.523256 | 258 | 0.591602 | [
"MIT"
] | kmdstudica/external-api-examples | src/ExternalApiExamples/Clients/Programmes/StudentActivityReportsExternalExtensions.cs | 4,001 | C# |
namespace JsonBuilder.Tests
{
using NUnit.Framework;
public class WhenAnObjectContainsTwoObjects : JsonSpecificationBase
{
private string parentName = "parent";
private string firstChildName = "firstChildName";
private string secondChildName = "secondChildName";
public override void Given()
{
var rootObject = this.SUT.WithObject(this.parentName);
rootObject.ContainingObject(this.firstChildName).WithValue("firstChildValue", "actualValue");
rootObject.ContainingObject(this.secondChildName).WithValue("firstChildValue", "actualValue");
}
[Test]
public void ThenTheNameOfTheFirstChildMustExistInTheResultJson()
{
StringAssert.Contains(this.firstChildName, this.result);
}
[Test]
public void ThenTheNameOfTheSecondChildMustExistInTheResultJson()
{
StringAssert.Contains(this.secondChildName, this.result);
}
[Test]
public void ThenTheObjectsMustNotBeListedAsACollection()
{
StringAssert.DoesNotContain("[", this.result);
StringAssert.DoesNotContain("]", this.result);
}
}
}
| 30.65 | 106 | 0.651713 | [
"MIT"
] | HerrLoesch/JSonBuilder | JsonBuilder.Tests/JsonBuilder.Tests/WhenAnObjectContainsTwoObjects.cs | 1,228 | C# |
using Bankos.DB;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bankos.Repository.Repository
{
public class BankosRepository<TEntity> : IBankosRepository<TEntity> where TEntity : class
{
private readonly MainContext _context;
private readonly DbSet<TEntity> _dbSet;
public BankosRepository(MainContext context)
{
_context = context;
_dbSet = _context.Set<TEntity>();
}
public async Task<TEntity> Add(TEntity entity)
{
try
{
return (await _dbSet.AddAsync(entity)).Entity;
}
catch
{
throw;
}
}
}
}
| 24.787879 | 93 | 0.59291 | [
"MIT"
] | MinaMaherNicola/Bankos | Bankos.Repository/Repository/BankosRepository.cs | 820 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IdentityServer3.Core.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Scopes {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Scopes() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("IdentityServer3.Core.Resources.Scopes", typeof(Scopes).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Your postal address.
/// </summary>
public static string address_DisplayName {
get {
return ResourceManager.GetString("address_DisplayName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to All user information.
/// </summary>
public static string all_claims_DisplayName {
get {
return ResourceManager.GetString("all_claims_DisplayName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your email address.
/// </summary>
public static string email_DisplayName {
get {
return ResourceManager.GetString("email_DisplayName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Offline access.
/// </summary>
public static string offline_access_DisplayName {
get {
return ResourceManager.GetString("offline_access_DisplayName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your user identifier.
/// </summary>
public static string openid_DisplayName {
get {
return ResourceManager.GetString("openid_DisplayName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your phone number.
/// </summary>
public static string phone_DisplayName {
get {
return ResourceManager.GetString("phone_DisplayName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Your user profile information (first name, last name, etc.).
/// </summary>
public static string profile_Description {
get {
return ResourceManager.GetString("profile_Description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User profile.
/// </summary>
public static string profile_DisplayName {
get {
return ResourceManager.GetString("profile_DisplayName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User roles.
/// </summary>
public static string roles_DisplayName {
get {
return ResourceManager.GetString("roles_DisplayName", resourceCulture);
}
}
}
}
| 38.662069 | 179 | 0.57492 | [
"Apache-2.0"
] | AppliedSystems/IdentityServer3 | source/Core/Resources/Scopes.Designer.cs | 5,608 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.UI
{
[CustomEditor(typeof(InteractableReceiverList))]
public class InteractableReceiverListInspector : UnityEditor.Editor
{
private static readonly GUIContent InteractableLabel = new GUIContent("Interactable", "The Interactable that will be monitored");
private static readonly GUIContent SearchScopeLabel = new GUIContent("Search Scope", "Where to look for an Interactable if one is not assigned");
public override void OnInspectorGUI()
{
serializedObject.Update();
RenderInspectorHeader();
SerializedProperty events = serializedObject.FindProperty("Events");
if (events.arraySize < 1)
{
AddEvent(0);
}
else
{
for (int i = 0; i < events.arraySize; i++)
{
SerializedProperty eventItem = events.GetArrayElementAtIndex(i);
bool canRemove = i > 0;
if (InteractableEventInspector.RenderEvent(eventItem, canRemove))
{
events.DeleteArrayElementAtIndex(i);
// If removed, skip rendering rest of list till next redraw
break;
}
}
if (GUILayout.Button(new GUIContent("Add Event")))
{
AddEvent(events.arraySize);
}
}
serializedObject.ApplyModifiedProperties();
}
protected virtual void RenderInspectorHeader()
{
SerializedProperty interactable = serializedObject.FindProperty("Interactable");
SerializedProperty searchScope = serializedObject.FindProperty("InteractableSearchScope");
EditorGUILayout.PropertyField(interactable, InteractableLabel);
EditorGUILayout.PropertyField(searchScope, SearchScopeLabel);
}
protected virtual void AddEvent(int index)
{
SerializedProperty events = serializedObject.FindProperty("Events");
events.InsertArrayElementAtIndex(events.arraySize);
}
}
}
| 34.925373 | 153 | 0.597009 | [
"MIT"
] | AdrianaMusic/MixedRealityToolkit-Unity | Assets/MRTK/SDK/Editor/Inspectors/UX/Interactable/InteractableReceiverListInspector.cs | 2,342 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AirSpace.Win32.User32
{
/// <summary>
/// Class field offsets for GetClassLong
/// </summary>
public enum GCL : int
{
MENUNAME = -8,
HBRBACKGROUND = -10,
HCURSOR = -12,
HICON = -14,
HMODULE = -16,
CBWNDEXTRA = -18,
CBCLSEXTRA = -20,
WNDPROC = -24,
STYLE = -26,
HICONSM = -34
}
}
| 19.4 | 48 | 0.531959 | [
"MIT"
] | bswanson58/NoiseMusicSystem | MilkBottle/AirSpace/Win32/User32/GCL.cs | 487 | C# |
using Multilinks.Core.Infrastructure;
using Newtonsoft.Json;
namespace Multilinks.Core.Models
{
public class EndpointsResponse : PagedCollection<EndpointViewModel>, IEtaggable
{
public string GetEtag()
{
var serialized = JsonConvert.SerializeObject(this);
return Md5Hash.ForString(serialized);
}
}
}
| 23.133333 | 82 | 0.706052 | [
"MIT"
] | andym-2iV/MultilinksCore | Multilinks.Core/Models/EndpointsResponse.cs | 349 | C# |
using DaemonEngine.OpenGL.DllImport;
namespace DaemonEngine.Graphics.OpenGL.DllImport.Enums;
public enum GLPolygonMode : uint
{
Fill = GLConstants.GL_FILL,
Line = GLConstants.GL_LINE,
Point = GLConstants.GL_POINT
}
| 20.909091 | 55 | 0.765217 | [
"MIT"
] | daemon-engine/DaemonEngine | DaemonEngine.Graphics.OpenGL.DllImport/Enums/GLPolygonMode.cs | 232 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleEnums;
using UnityEditor.Experimental.UIElements;
using UnityEditor.VFX;
using UnityEditor.VFX.UIElements;
using Object = UnityEngine.Object;
using Type = System.Type;
using EnumField = UnityEditor.VFX.UIElements.VFXEnumField;
using VFXVector2Field = UnityEditor.VFX.UIElements.VFXVector2Field;
using VFXVector4Field = UnityEditor.VFX.UIElements.VFXVector4Field;
namespace UnityEditor.VFX.UI
{
class EnumPropertyRM : SimplePropertyRM<int>
{
public EnumPropertyRM(IPropertyRMProvider controller, float labelWidth) : base(controller, labelWidth)
{
}
public override float GetPreferredControlWidth()
{
return 120;
}
public override ValueControl<int> CreateField()
{
return new EnumField(m_Label, m_Provider.portType);
}
}
class Vector4PropertyRM : SimpleVFXUIPropertyRM<VFXVector4Field, Vector4>
{
public Vector4PropertyRM(IPropertyRMProvider controller, float labelWidth) : base(controller, labelWidth)
{
}
public override float GetPreferredControlWidth()
{
return 180;
}
}
class Matrix4x4PropertyRM : SimpleVFXUIPropertyRM<VFXMatrix4x4Field, Matrix4x4>
{
public Matrix4x4PropertyRM(IPropertyRMProvider controller, float labelWidth) : base(controller, labelWidth)
{
}
public override float GetPreferredControlWidth()
{
return 260;
}
}
class Vector2PropertyRM : SimpleVFXUIPropertyRM<VFXVector2Field, Vector2>
{
public Vector2PropertyRM(IPropertyRMProvider controller, float labelWidth) : base(controller, labelWidth)
{
}
public override float GetPreferredControlWidth()
{
return 100;
}
}
class FlipBookPropertyRM : SimpleVFXUIPropertyRM<VFXFlipBookField, FlipBook>
{
public FlipBookPropertyRM(IPropertyRMProvider controller, float labelWidth) : base(controller, labelWidth)
{
}
public override float GetPreferredControlWidth()
{
return 100;
}
}
}
| 28.120482 | 115 | 0.682948 | [
"BSD-2-Clause"
] | 1-10/VisualEffectGraphSample | GitHub/com.unity.visualeffectgraph/Editor/GraphView/Views/Properties/SimplePropertiesRM.cs | 2,334 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1318
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace newtelligence.DasBlog.Web {
/// <summary>
/// ClickThroughs class.
/// </summary>
/// <remarks>
/// Auto-generated class.
/// </remarks>
public partial class ClickThroughs {
/// <summary>
/// contentPlaceHolder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder contentPlaceHolder;
}
}
| 30.25 | 84 | 0.494835 | [
"MIT"
] | garethhubball/dasblog-core | source/newtelligence.DasBlog.Web/ClickThroughs.aspx.designer.cs | 968 | C# |
using System;
using System.Collections.Generic;
namespace Parse.Core.Internal
{
public class PointerOrLocalIdEncoder : ParseEncoder
{
public static PointerOrLocalIdEncoder Instance { get; } = new PointerOrLocalIdEncoder();
protected override IDictionary<string, object> EncodeParseObject(ParseObject value)
{
// TODO: Handle local identifier.
if (value.ObjectId == null)
throw new ArgumentException("Cannot create a pointer to an object without an objectId");
return new Dictionary<string, object>
{
["__type"] = "Pointer",
["className"] = value.ClassName,
["objectId"] = value.ObjectId
};
}
}
}
| 30.68 | 104 | 0.601043 | [
"BSD-3-Clause"
] | naosoft/Parse-SDK-dotNET | Parse/Internal/Encoding/PointerOrLocalIdEncoder.cs | 767 | C# |
using System;
namespace Master_Services_Portal_ASP.NET_mvc.Areas.HelpPage.ModelDescriptions
{
public class ParameterAnnotation
{
public Attribute AnnotationAttribute { get; set; }
public string Documentation { get; set; }
}
} | 23.181818 | 77 | 0.721569 | [
"Apache-2.0"
] | XdieselX/Master-Services-Portal-ASP.NET-mvc | Master-Services-Portal-ASP.NET-mvc/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs | 255 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;
namespace Microsoft.Identity.Client.Instance
{
internal class B2CAuthority : AadAuthority
{
public const string Prefix = "tfp"; // The http path of B2C authority looks like "/tfp/<your_tenant_name>/..."
public const string B2CCanonicalAuthorityTemplate = "https://{0}/{1}/{2}/{3}/";
internal B2CAuthority(IServiceBundle serviceBundle, AuthorityInfo authorityInfo)
: base(serviceBundle, authorityInfo)
{
}
internal override string GetTenantId()
{
return new Uri(AuthorityInfo.CanonicalAuthority).Segments[2].TrimEnd('/');
}
internal override string GetTenantedAuthority(string tenantId)
{
// For B2C, tenant is not changeble
return AuthorityInfo.CanonicalAuthority;
}
}
}
| 31.323529 | 118 | 0.675117 | [
"MIT"
] | davidjohnoliver/microsoft-authentication-library-for-dotnet | src/client/Microsoft.Identity.Client/Instance/B2CAuthority.cs | 1,067 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 這段程式碼是由工具產生的。
// 執行階段版本:4.0.30319.42000
//
// 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼,
// 變更將會遺失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace MiniSasHd4Dot0DcTest.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.3.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 36.740741 | 151 | 0.570565 | [
"Apache-2.0"
] | truelight-corporation/c_sharp_application | project/MiniSasHd4.0DcTest/Properties/Settings.Designer.cs | 1,112 | C# |
/*
* Copyright © 2012-2016 VMware, 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Foundation;
using AppKit;
using Vmware.Tools.RestSsoAdminSnapIn.Dto;
using Vmware.Tools.RestSsoAdminSnapIn.Core.Extensions;
using Vmware.Tools.RestSsoAdminSnapIn.DataSource;
using Vmware.Tools.RestSsoAdminSnapIn.Helpers;
using Vmware.Tools.RestSsoAdminSnapIn;
using VmIdentity.CommonUtils.Utilities;
namespace RestSsoAdminSnapIn
{
public partial class AddNewExternalIdentityProviderController : NSWindowController
{
public ExternalIdentityProviderDto ExternalIdentityProviderDto{ get; set; }
public ServerDto ServerDto { get; set; }
public string TenantName { get; set; }
public AddNewExternalIdentityProviderController (IntPtr handle) : base (handle)
{
}
[Export ("initWithCoder:")]
public AddNewExternalIdentityProviderController (NSCoder coder) : base (coder)
{
}
public AddNewExternalIdentityProviderController () : base ("AddNewExternalIdentityProvider")
{
}
public override void AwakeFromNib ()
{
base.AwakeFromNib ();
if (ExternalIdentityProviderDto == null) {
ExternalIdentityProviderDto = new ExternalIdentityProviderDto () {
NameIDFormats = new List<string> (),
SubjectFormats = new Dictionary<string, string> (),
SsoServices = new List<ServiceEndpointDto> (),
SloServices = new List<ServiceEndpointDto> (),
SigningCertificates = new CertificateChainDto {
Certificates = new List<CertificateDto> ()
}
};
} else {
DtoToView ();
}
// Name Id formats
BtnAddNameIdFormat.Activated += (object sender, EventArgs e) => {
if(string.IsNullOrEmpty(TxtNameIdFormat.StringValue))
{
UIErrorHelper.ShowAlert ("Name Id format cannot be empty", "Alert");
return;
}
ExternalIdentityProviderDto.NameIDFormats.Add(TxtNameIdFormat.StringValue);
ReloadTableView(LstNameIdFormat, ExternalIdentityProviderDto.NameIDFormats);
TxtNameIdFormat.StringValue = (NSString)string.Empty;
};
BtnRemoveNameIdFormat.Activated += (object sender, EventArgs e) => {
if (LstNameIdFormat.SelectedRows.Count > 0) {
foreach (var row in LstNameIdFormat.SelectedRows) {
ExternalIdentityProviderDto.NameIDFormats.RemoveAt((int)row);
}
ReloadTableView(LstNameIdFormat, ExternalIdentityProviderDto.NameIDFormats);
}
};
ReloadTableView(LstNameIdFormat, ExternalIdentityProviderDto.NameIDFormats);
// Subject formats
BtnAddSubjectFormat.Activated += (object sender, EventArgs e) => {
if(string.IsNullOrEmpty(TxtSubjectFormatName.StringValue))
{
UIErrorHelper.ShowAlert ("Subject format name cannot be empty", "Alert");
return;
}
if(string.IsNullOrEmpty(TxtSubjectFormatValue.StringValue))
{
UIErrorHelper.ShowAlert ("Subject format value cannot be empty", "Alert");
return;
}
if(ExternalIdentityProviderDto.SubjectFormats.ContainsKey(TxtSubjectFormatName.StringValue))
{
UIErrorHelper.ShowAlert ("Subject format name already exists", "Alert");
return;
}
ExternalIdentityProviderDto.SubjectFormats.Add(TxtSubjectFormatName.StringValue, TxtSubjectFormatValue.StringValue);
ReloadTableView(LstSubjectFormat, ExternalIdentityProviderDto.SubjectFormats);
TxtSubjectFormatName.StringValue = (NSString)string.Empty;
TxtSubjectFormatValue.StringValue = (NSString)string.Empty;
};
BtnRemoveSubjectFormat.Activated += (object sender, EventArgs e) => {
if (LstSubjectFormat.SelectedRows.Count > 0) {
foreach (var row in LstSubjectFormat.SelectedRows) {
var source = LstSubjectFormat.DataSource as DictionaryDataSource;
var name = source.Entries[(int)row];
ExternalIdentityProviderDto.SubjectFormats.Remove(name);
}
ReloadTableView(LstSubjectFormat, ExternalIdentityProviderDto.SubjectFormats);
}
};
ReloadTableView(LstSubjectFormat, ExternalIdentityProviderDto.SubjectFormats);
// Certificates
BtnAddCertificate.Activated += (object sender, EventArgs e) => {
var openPanel = new NSOpenPanel();
openPanel.ReleasedWhenClosed = true;
openPanel.Prompt = "Select file";
var result = openPanel.RunModal();
if (result == 1)
{
var filePath = Uri.UnescapeDataString (openPanel.Url.AbsoluteString.Replace("file://",string.Empty));
var cert = new X509Certificate2 ();
ActionHelper.Execute (delegate() {
cert.Import (filePath);
var certfificateDto = new CertificateDto { Encoded = cert.ExportToPem(), };
ExternalIdentityProviderDto.SigningCertificates.Certificates.Add(certfificateDto);
ReloadCertificates();
});
}
};
BtnRemoveCertificate.Activated += (object sender, EventArgs e) => {
if (LstCertificates.SelectedRows.Count > 0) {
foreach (var row in LstCertificates.SelectedRows) {
ExternalIdentityProviderDto.SigningCertificates.Certificates.RemoveAt ((int)row);
}
ReloadCertificates();
}
};
ReloadCertificates ();
// Sso Services
BtnAddSso.Activated += OnAddSsoServices;
BtnRemoveSso.Activated += OnRemoveSsoServices;
InitializeSsoServices ();
// Slo Services
BtnAddSlo.Activated += OnAddSloServices;
BtnRemoveSlo.Activated += OnRemoveSloServices;
InitializeSloServices ();
this.BtnSave.Activated += (object sender, EventArgs e) => {
if (string.IsNullOrEmpty (TxtUniqueId.StringValue)) {
UIErrorHelper.ShowAlert ("Please choose a Unique Id", "Alert");
} else if(string.IsNullOrEmpty(TxtAlias.StringValue))
{
UIErrorHelper.ShowAlert ("Alias cannot be empty", "Alert");
} else if (ExternalIdentityProviderDto.NameIDFormats.Count() < 1) {
UIErrorHelper.ShowAlert ("Please choose a Name Id format", "Alert");
} else if (ExternalIdentityProviderDto.SubjectFormats.Count() < 1) {
UIErrorHelper.ShowAlert ("Please choose a Subject Id format", "Alert");
} else if (ExternalIdentityProviderDto.SsoServices.Count() < 1) {
UIErrorHelper.ShowAlert ("Please choose a Sso Service", "Alert");
} else if (ExternalIdentityProviderDto.SloServices.Count() < 1) {
UIErrorHelper.ShowAlert ("Please choose a Slo service", "Alert");
} else if (ExternalIdentityProviderDto.SigningCertificates.Certificates.Count() < 1) {
UIErrorHelper.ShowAlert ("Please choose a certificate", "Alert");
} else {
ExternalIdentityProviderDto.EntityID = TxtUniqueId.StringValue;
ExternalIdentityProviderDto.Alias = TxtAlias.StringValue;
ExternalIdentityProviderDto.JitEnabled = ChkJit.StringValue == "1";
ActionHelper.Execute(delegate {
var auth = SnapInContext.Instance.AuthTokenManager.GetAuthToken(ServerDto.ServerName);
SnapInContext.Instance.ServiceGateway.MacExternalIdentityProviderService.Create(ServerDto,TenantName,ExternalIdentityProviderDto,auth.Token);
this.Close ();
NSApplication.SharedApplication.StopModalWithCode (1);
});
}
};
BtnClose.Activated += (object sender, EventArgs e) => {
this.Close ();
NSApplication.SharedApplication.StopModalWithCode (0);
};
BtnViewCertificate.Activated += (object sender, EventArgs e) =>
{
if (LstCertificates.SelectedRows.Count > 0) {
var row = LstCertificates.SelectedRows.First();
var encoded = ExternalIdentityProviderDto.SigningCertificates.Certificates[(int)row].Encoded;
var bytes = System.Text.Encoding.ASCII.GetBytes (encoded);
var certificate = new X509Certificate2(bytes);
CertificateService.DisplayX509Certificate2(this, certificate);
}
};
}
private void DtoToView(){
TxtUniqueId.StringValue = ExternalIdentityProviderDto.EntityID;
TxtUniqueId.Enabled = false;
TxtAlias.StringValue = ExternalIdentityProviderDto.Alias;
ChkJit.StringValue = ExternalIdentityProviderDto.JitEnabled ? "1" : "0";
}
private void ReloadTableView(NSTableView tableView, List<string> datasource)
{
tableView.Delegate = new TableDelegate ();
var listView = new DefaultDataSource { Entries = datasource };
tableView.DataSource = listView;
tableView.ReloadData ();
}
private void ReloadTableView(NSTableView tableView, Dictionary<string,string> datasource)
{
foreach(NSTableColumn column in tableView.TableColumns())
{
tableView.RemoveColumn (column);
}
tableView.Delegate = new TableDelegate ();
var columnNames = new List<ColumnOptions> {
new ColumnOptions{ Id = "Name", DisplayName = "Name", DisplayOrder = 0, Width = 80 },
new ColumnOptions{ Id = "Value", DisplayName = "Value", DisplayOrder = 1, Width = 200 }
};
var columns = ListViewHelper.ToNSTableColumns (columnNames);
foreach (var column in columns) {
tableView.AddColumn (column);
}
var listView = new DictionaryDataSource { Entries = datasource.Keys.ToList(), Datasource = datasource };
tableView.DataSource = listView;
tableView.ReloadData ();
}
private void ReloadCertificates()
{
foreach(NSTableColumn column in LstCertificates.TableColumns())
{
LstCertificates.RemoveColumn (column);
}
LstCertificates.Delegate = new CertTableDelegate ();
var listView = new TrustedCertificatesDataSource { Entries = ExternalIdentityProviderDto.SigningCertificates.Certificates };
var columnNames = new List<ColumnOptions> {
new ColumnOptions{ Id = "SubjectDn", DisplayName = "Subject DN", DisplayOrder = 1, Width = 120 },
new ColumnOptions{ Id = "IssuedBy", DisplayName = "Issuer", DisplayOrder = 1, Width = 150 },
new ColumnOptions{ Id = "IssuedOn", DisplayName = "Valid From", DisplayOrder = 1, Width = 80 },
new ColumnOptions{ Id = "Expiration", DisplayName = "Valid To", DisplayOrder = 1, Width = 80 },
new ColumnOptions{ Id = "Fingerprint", DisplayName = "FingerPrint", DisplayOrder = 1, Width = 150 }
};
var columns = ListViewHelper.ToNSTableColumns (columnNames);
foreach (var column in columns) {
LstCertificates.AddColumn (column);
}
LstCertificates.DataSource = listView;
LstCertificates.ReloadData ();
}
private void InitializeSsoServices()
{
foreach(NSTableColumn column in LstSso.TableColumns())
{
LstSso.RemoveColumn (column);
}
LstSso.Delegate = new TableDelegate ();
var listView = new ServiceEndpointDataSource { Entries = ExternalIdentityProviderDto.SsoServices };
var columnNames = new List<ColumnOptions> {
new ColumnOptions{ Id = "Name", DisplayName = "Name", DisplayOrder = 1, Width = 150 },
new ColumnOptions{ Id = "Endpoint", DisplayName = "Endpoint", DisplayOrder = 4, Width = 200 },
new ColumnOptions{ Id = "Binding", DisplayName = "Binding", DisplayOrder = 5, Width = 200 }
};
var columns = ListViewHelper.ToNSTableColumns (columnNames);
foreach (var column in columns) {
LstSso.AddColumn (column);
}
LstSso.DataSource = listView;
LstSso.ReloadData ();
}
private void OnAddSsoServices (object sender, EventArgs e)
{
if (IsSsoServiceValid ()) {
var endpointDto = new ServiceEndpointDto {
Name = TxtSsoName.StringValue,
Endpoint = TxtSsoEndpoint.StringValue,
Binding = TxtSsoBinding.StringValue
};
ExternalIdentityProviderDto.SsoServices.Add(endpointDto);
var datasource = new ServiceEndpointDataSource { Entries = ExternalIdentityProviderDto.SsoServices };
LstSso.DataSource = datasource;
LstSso.ReloadData ();
TxtSsoName.StringValue = (NSString)string.Empty;
TxtSsoEndpoint.StringValue = (NSString)string.Empty;
TxtSsoBinding.StringValue = (NSString)string.Empty;
}
}
private bool IsSsoServiceValid()
{
if(string.IsNullOrEmpty(TxtSsoName.StringValue))
{
UIErrorHelper.ShowAlert ("Sso service name cannot be empty", "Alert");
return false;
} else if(string.IsNullOrEmpty(TxtSsoBinding.StringValue))
{
UIErrorHelper.ShowAlert ("Sso service binding cannot be empty", "Alert");
return false;
} else if(string.IsNullOrEmpty(TxtSsoEndpoint.StringValue))
{
UIErrorHelper.ShowAlert ("Sso service endpoint cannot be empty", "Alert");
return false;
}
return true;
}
private void OnRemoveSsoServices (object sender, EventArgs e)
{
if (LstSso.SelectedRows.Count > 0) {
foreach (var row in LstSso.SelectedRows) {
ExternalIdentityProviderDto.SsoServices.RemoveAt ((int)row);
}
var datasource = new ServiceEndpointDataSource { Entries = ExternalIdentityProviderDto.SsoServices };
LstSso.DataSource = datasource;
LstSso.ReloadData ();
}
}
private void InitializeSloServices()
{
foreach(NSTableColumn column in LstSlo.TableColumns())
{
LstSlo.RemoveColumn (column);
}
LstSlo.Delegate = new TableDelegate ();
var listView = new ServiceEndpointDataSource { Entries = ExternalIdentityProviderDto.SloServices };
var columnNames = new List<ColumnOptions> {
new ColumnOptions{ Id = "Name", DisplayName = "Name", DisplayOrder = 1, Width = 150 },
new ColumnOptions{ Id = "Endpoint", DisplayName = "Endpoint", DisplayOrder = 4, Width = 200 },
new ColumnOptions{ Id = "Binding", DisplayName = "Binding", DisplayOrder = 5, Width = 200 }
};
var columns = ListViewHelper.ToNSTableColumns (columnNames);
foreach (var column in columns) {
LstSlo.AddColumn (column);
}
LstSlo.DataSource = listView;
LstSlo.ReloadData ();
}
private void OnAddSloServices (object sender, EventArgs e)
{
if (IsSloServiceValid ()) {
var endpointDto = new ServiceEndpointDto {
Name = TxtSloName.StringValue,
Endpoint = TxtSloEndpoint.StringValue,
Binding = TxtSloBinding.StringValue
};
ExternalIdentityProviderDto.SloServices.Add(endpointDto);
var datasource = new ServiceEndpointDataSource { Entries = ExternalIdentityProviderDto.SloServices };
LstSlo.DataSource = datasource;
LstSlo.ReloadData ();
TxtSloName.StringValue = (NSString)string.Empty;
TxtSloEndpoint.StringValue = (NSString)string.Empty;
TxtSloBinding.StringValue = (NSString)string.Empty;
}
}
private bool IsSloServiceValid()
{
if(string.IsNullOrEmpty(TxtSloName.StringValue))
{
UIErrorHelper.ShowAlert ("Slo service name cannot be empty", "Alert");
return false;
} else if(string.IsNullOrEmpty(TxtSloBinding.StringValue))
{
UIErrorHelper.ShowAlert ("Slo service binding cannot be empty", "Alert");
return false;
} else if(string.IsNullOrEmpty(TxtSloEndpoint.StringValue))
{
UIErrorHelper.ShowAlert ("Slo service endpoint cannot be empty", "Alert");
return false;
}
return true;
}
private void OnRemoveSloServices (object sender, EventArgs e)
{
if (LstSlo.SelectedRows.Count > 0) {
foreach (var row in LstSlo.SelectedRows) {
ExternalIdentityProviderDto.SloServices.RemoveAt ((int)row);
}
var datasource = new ServiceEndpointDataSource { Entries = ExternalIdentityProviderDto.SloServices };
LstSlo.DataSource = datasource;
LstSlo.ReloadData ();
}
}
public new AddNewExternalIdentityProvider Window {
get { return (AddNewExternalIdentityProvider)base.Window; }
}
public class TableDelegate : NSTableViewDelegate
{
public TableDelegate ()
{
}
public override void WillDisplayCell (NSTableView tableView, NSObject cell,
NSTableColumn tableColumn, nint row)
{
ActionHelper.Execute (delegate() {
NSBrowserCell browserCell = cell as NSBrowserCell;
if (browserCell != null) {
browserCell.Leaf = true;
}
});
}
}
public class CertTableDelegate : NSTableViewDelegate
{
public CertTableDelegate ()
{
}
public override void WillDisplayCell (NSTableView tableView, NSObject cell,
NSTableColumn tableColumn, nint row)
{
ActionHelper.Execute (delegate() {
NSBrowserCell browserCell = cell as NSBrowserCell;
if (browserCell != null) {
browserCell.Leaf = true;
if (tableColumn.Identifier == "Name") {
var image = NSImage.ImageNamed ("certificate.png");
browserCell.Image = image;
browserCell.Image.Size = new CoreGraphics.CGSize{ Width = (float)16.0, Height = (float)16.0 };
}
}
});
}
}
}
}
| 37.837472 | 147 | 0.720439 | [
"Apache-2.0"
] | WestCope/lightwave | tools/mac/VMRestSsoSnapIn/VMRestSsoSnapIn/Views/AddNewExternalIdentityProviderController.cs | 16,773 | C# |
using System;
using System.Reflection;
using Exceptionless.Core.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Exceptionless.Core.Serialization {
public class LowerCaseUnderscorePropertyNamesContractResolver : DefaultContractResolver {
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
var property = base.CreateProperty(member, memberSerialization);
var shouldSerialize = property.ShouldSerialize;
property.ShouldSerialize = obj => (shouldSerialize == null || shouldSerialize(obj)) && !property.IsValueEmptyCollection(obj);
return property;
}
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType) {
var contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = propertyName => propertyName;
return contract;
}
protected override string ResolvePropertyName(string propertyName) {
return propertyName.ToLowerUnderscoredWords();
}
}
} | 42.296296 | 137 | 0.728546 | [
"Apache-2.0"
] | ChanneForZM/Exceptionless | src/Exceptionless.Core/Serialization/LowerCaseUnderscorePropertyNamesContractResolver.cs | 1,144 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.ReferenceHighlighting
{
internal abstract class AbstractDocumentHighlightsService : IDocumentHighlightsService
{
public async Task<IEnumerable<DocumentHighlights>> GetDocumentHighlightsAsync(Document document, int position, IEnumerable<Document> documentsToSearch, CancellationToken cancellationToken)
{
// use speculative semantic model to see whether we are on a symbol we can do HR
var span = new TextSpan(position, 0);
var solution = document.Project.Solution;
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, solution.Workspace, cancellationToken: cancellationToken);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
symbol = await GetSymbolToSearchAsync(document, position, semanticModel, symbol, cancellationToken).ConfigureAwait(false);
if (symbol == null)
{
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
// Get unique tags for referenced symbols
return await GetTagsForReferencedSymbolAsync(symbol, ImmutableHashSet.CreateRange(documentsToSearch), solution, cancellationToken).ConfigureAwait(false);
}
private async Task<ISymbol> GetSymbolToSearchAsync(Document document, int position, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken)
{
// see whether we can use the symbol as it is
var currentSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (currentSemanticModel == semanticModel)
{
return symbol;
}
// get symbols from current document again
return SymbolFinder.FindSymbolAtPosition(currentSemanticModel, position, document.Project.Solution.Workspace, cancellationToken: cancellationToken);
}
private async Task<IEnumerable<DocumentHighlights>> GetTagsForReferencedSymbolAsync(
ISymbol symbol,
IImmutableSet<Document> documentsToSearch,
Solution solution,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(symbol);
if (ShouldConsiderSymbol(symbol))
{
var references = await SymbolFinder.FindReferencesAsync(
symbol, solution, progress: null, documents: documentsToSearch, cancellationToken: cancellationToken).ConfigureAwait(false);
return await FilterAndCreateSpansAsync(references, solution, documentsToSearch, symbol, cancellationToken).ConfigureAwait(false);
}
return SpecializedCollections.EmptyEnumerable<DocumentHighlights>();
}
private bool ShouldConsiderSymbol(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Method:
switch (((IMethodSymbol)symbol).MethodKind)
{
case MethodKind.AnonymousFunction:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.EventAdd:
case MethodKind.EventRaise:
case MethodKind.EventRemove:
return false;
default:
return true;
}
default:
return true;
}
}
private async Task<IEnumerable<DocumentHighlights>> FilterAndCreateSpansAsync(
IEnumerable<ReferencedSymbol> references, Solution solution, IImmutableSet<Document> documentsToSearch, ISymbol symbol, CancellationToken cancellationToken)
{
references = references.FilterUnreferencedSyntheticDefinitions();
references = references.FilterNonMatchingMethodNames(solution, symbol);
references = references.FilterToAliasMatches(symbol as IAliasSymbol);
if (symbol.IsConstructor())
{
references = references.Where(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition));
}
var additionalReferences = new List<Location>();
foreach (var document in documentsToSearch)
{
additionalReferences.AddRange(await GetAdditionalReferencesAsync(document, symbol, cancellationToken).ConfigureAwait(false));
}
return await CreateSpansAsync(solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false);
}
private Task<IEnumerable<Location>> GetAdditionalReferencesAsync(
Document document, ISymbol symbol, CancellationToken cancellationToken)
{
var additionalReferenceProvider = document.Project.LanguageServices.GetService<IReferenceHighlightingAdditionalReferenceProvider>();
if (additionalReferenceProvider != null)
{
return additionalReferenceProvider.GetAdditionalReferencesAsync(document, symbol, cancellationToken);
}
return Task.FromResult(SpecializedCollections.EmptyEnumerable<Location>());
}
private async Task<IEnumerable<DocumentHighlights>> CreateSpansAsync(
Solution solution,
ISymbol symbol,
IEnumerable<ReferencedSymbol> references,
IEnumerable<Location> additionalReferences,
IImmutableSet<Document> documentToSearch,
CancellationToken cancellationToken)
{
var spanSet = new HashSet<ValueTuple<Document, TextSpan>>();
var tagMap = new MultiDictionary<Document, HighlightSpan>();
bool addAllDefinitions = true;
// Add definitions
// Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages.
if (symbol.Kind == SymbolKind.Alias &&
symbol.Locations.Length > 0)
{
addAllDefinitions = false;
if (symbol.Locations.First().IsInSource)
{
// For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition.
await AddLocationSpan(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
// Add references and definitions
foreach (var reference in references)
{
if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition))
{
foreach (var location in reference.Definition.Locations)
{
if (location.IsInSource)
{
var document = solution.GetDocument(location.SourceTree);
// GetDocument will return null for locations in #load'ed trees.
// TODO: Remove this check and add logic to fetch the #load'ed tree's
// Document once https://github.com/dotnet/roslyn/issues/5260 is fixed.
if (document == null)
{
Debug.Assert(solution.Workspace.Kind == "Interactive");
continue;
}
if (documentToSearch.Contains(document))
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false);
}
}
}
}
foreach (var referenceLocation in reference.Locations)
{
var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference;
await AddLocationSpan(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false);
}
}
// Add additional references
foreach (var location in additionalReferences)
{
await AddLocationSpan(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false);
}
var list = new List<DocumentHighlights>(tagMap.Count);
foreach (var kvp in tagMap)
{
var spans = new List<HighlightSpan>(kvp.Value.Count);
foreach (var span in kvp.Value)
{
spans.Add(span);
}
list.Add(new DocumentHighlights(kvp.Key, spans));
}
return list;
}
private static bool ShouldIncludeDefinition(ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Namespace:
return false;
case SymbolKind.NamedType:
return !((INamedTypeSymbol)symbol).IsScriptClass;
case SymbolKind.Parameter:
// If it's an indexer parameter, we will have also cascaded to the accessor
// one that actually receives the references
var containingProperty = symbol.ContainingSymbol as IPropertySymbol;
if (containingProperty != null && containingProperty.IsIndexer)
{
return false;
}
break;
}
return true;
}
private async Task AddLocationSpan(Location location, Solution solution, HashSet<ValueTuple<Document, TextSpan>> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken)
{
var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false);
if (span != null && !spanSet.Contains(span.Value))
{
spanSet.Add(span.Value);
tagList.Add(span.Value.Item1, new HighlightSpan(span.Value.Item2, kind));
}
}
private async Task<ValueTuple<Document, TextSpan>?> GetLocationSpanAsync(Solution solution, Location location, CancellationToken cancellationToken)
{
try
{
if (location != null && location.IsInSource)
{
var tree = location.SourceTree;
var document = solution.GetDocument(tree);
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
if (syntaxFacts != null)
{
// Specify findInsideTrivia: true to ensure that we search within XML doc comments.
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true);
return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent)
? ValueTuple.Create(document, token.Span)
: ValueTuple.Create(document, location.SourceSpan);
}
}
}
catch (NullReferenceException e) when (FatalError.ReportWithoutCrash(e))
{
// We currently are seeing a strange null references crash in this code. We have
// a strong belief that this is recoverable, but we'd like to know why it is
// happening. This exception filter allows us to report the issue and continue
// without damaging the user experience. Once we get more crash reports, we
// can figure out the root cause and address appropriately. This is preferable
// to just using conditionl access operators to be resilient (as we won't actually
// know why this is happening).
}
return null;
}
}
}
| 46.423611 | 240 | 0.605236 | [
"Apache-2.0"
] | mseamari/Stuff | src/EditorFeatures/Core/Implementation/ReferenceHighlighting/AbstractDocumentHighlightsService.cs | 13,370 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.IotHub.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// The health data for an endpoint
/// </summary>
public partial class EndpointHealthData
{
/// <summary>
/// Initializes a new instance of the EndpointHealthData class.
/// </summary>
public EndpointHealthData()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the EndpointHealthData class.
/// </summary>
/// <param name="endpointId">Id of the endpoint</param>
/// <param name="healthStatus">Health statuses have following meanings.
/// The 'healthy' status shows that the endpoint is accepting messages
/// as expected. The 'unhealthy' status shows that the endpoint is not
/// accepting messages as expected and IoT Hub is retrying to send data
/// to this endpoint. The status of an unhealthy endpoint will be
/// updated to healthy when IoT Hub has established an eventually
/// consistent state of health. The 'dead' status shows that the
/// endpoint is not accepting messages, after IoT Hub retried sending
/// messages for the retrial period. See IoT Hub metrics to identify
/// errors and monitor issues with endpoints. The 'unknown' status
/// shows that the IoT Hub has not established a connection with the
/// endpoint. No messages have been delivered to or rejected from this
/// endpoint. Possible values include: 'unknown', 'healthy',
/// 'degraded', 'unhealthy', 'dead'</param>
/// <param name="lastKnownError">Last error obtained when a message
/// failed to be delivered to iot hub</param>
/// <param name="lastKnownErrorTime">Time at which the last known error
/// occurred</param>
/// <param name="lastSuccessfulSendAttemptTime">Last time iot hub
/// successfully sent a message to the endpoint</param>
/// <param name="lastSendAttemptTime">Last time iot hub tried to send a
/// message to the endpoint</param>
public EndpointHealthData(string endpointId = default(string), string healthStatus = default(string), string lastKnownError = default(string), System.DateTime? lastKnownErrorTime = default(System.DateTime?), System.DateTime? lastSuccessfulSendAttemptTime = default(System.DateTime?), System.DateTime? lastSendAttemptTime = default(System.DateTime?))
{
EndpointId = endpointId;
HealthStatus = healthStatus;
LastKnownError = lastKnownError;
LastKnownErrorTime = lastKnownErrorTime;
LastSuccessfulSendAttemptTime = lastSuccessfulSendAttemptTime;
LastSendAttemptTime = lastSendAttemptTime;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets id of the endpoint
/// </summary>
[JsonProperty(PropertyName = "endpointId")]
public string EndpointId { get; set; }
/// <summary>
/// Gets or sets health statuses have following meanings. The 'healthy'
/// status shows that the endpoint is accepting messages as expected.
/// The 'unhealthy' status shows that the endpoint is not accepting
/// messages as expected and IoT Hub is retrying to send data to this
/// endpoint. The status of an unhealthy endpoint will be updated to
/// healthy when IoT Hub has established an eventually consistent state
/// of health. The 'dead' status shows that the endpoint is not
/// accepting messages, after IoT Hub retried sending messages for the
/// retrial period. See IoT Hub metrics to identify errors and monitor
/// issues with endpoints. The 'unknown' status shows that the IoT Hub
/// has not established a connection with the endpoint. No messages
/// have been delivered to or rejected from this endpoint. Possible
/// values include: 'unknown', 'healthy', 'degraded', 'unhealthy',
/// 'dead'
/// </summary>
[JsonProperty(PropertyName = "healthStatus")]
public string HealthStatus { get; set; }
/// <summary>
/// Gets or sets last error obtained when a message failed to be
/// delivered to iot hub
/// </summary>
[JsonProperty(PropertyName = "lastKnownError")]
public string LastKnownError { get; set; }
/// <summary>
/// Gets or sets time at which the last known error occurred
/// </summary>
[JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
[JsonProperty(PropertyName = "lastKnownErrorTime")]
public System.DateTime? LastKnownErrorTime { get; set; }
/// <summary>
/// Gets or sets last time iot hub successfully sent a message to the
/// endpoint
/// </summary>
[JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
[JsonProperty(PropertyName = "lastSuccessfulSendAttemptTime")]
public System.DateTime? LastSuccessfulSendAttemptTime { get; set; }
/// <summary>
/// Gets or sets last time iot hub tried to send a message to the
/// endpoint
/// </summary>
[JsonConverter(typeof(DateTimeRfc1123JsonConverter))]
[JsonProperty(PropertyName = "lastSendAttemptTime")]
public System.DateTime? LastSendAttemptTime { get; set; }
}
}
| 46.738462 | 357 | 0.650922 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/iothub/Microsoft.Azure.Management.IotHub/src/Generated/Models/EndpointHealthData.cs | 6,076 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SpyGram
{
class SpyGram
{
static void Main(string[] args)
{
var messages = new Dictionary<string, List<string>>();
string privateKey = Console.ReadLine();
string pattern = @"^TO:\s(?<recipient>[A-Z]+);\sMESSAGE:\s(?<msg>.+);$";
string message;
while ((message = Console.ReadLine()) != "END")
{
Regex regex = new Regex(pattern);
if (regex.IsMatch(message))
{
Match match = regex.Match(message);
string recipient = match.Groups["recipient"].Value;
string msg = match.Groups["msg"].Value;
if (!messages.ContainsKey(recipient))
{
messages[recipient] = new List<string>();
}
int index = 0;
StringBuilder encryptedMsg = new StringBuilder();
foreach (char ch in message)
{
if (index > privateKey.Length - 1)
{
index = 0;
}
var step = int.Parse(privateKey[index++].ToString());
encryptedMsg.Append((char)(ch + step));
}
messages[recipient].Add(encryptedMsg.ToString());
}
}
foreach (var msg in messages.OrderBy(x => x.Key))
{
Console.WriteLine(string.Join(Environment.NewLine, msg.Value));
}
}
}
}
| 29.262295 | 84 | 0.45042 | [
"MIT"
] | AlexanderPetrovv/Tech-Module-SoftUni | Programming Fundamentals - May 2017/ExamPreparation09May2017/SpyGram/SpyGram.cs | 1,787 | C# |
using Entitas;
using UnityEngine;
public class ProcessInputSystem : IExecuteSystem, IInitializeSystem, ISetPool {
Pool _pool;
Group _group;
Group _input;
Vector3 temp = new Vector3();
public void SetPool(Pool pool) {
_pool = pool;
_group = pool.GetGroup(Matcher.MouseInput);
_input = pool.GetGroup(Matcher.Input);
}
public void Initialize() {
createEntity();
}
public void Execute() {
Entity e = _group.GetSingleEntity();
MouseInputComponent component = e.mouseInput;
temp.Set(component.x, component.y, 0);
temp = Camera.main.ScreenToWorldPoint(temp);
InputComponent input = _input.GetSingleEntity().input;
input.x = temp.x;
input.y = temp.y;
input.isDown = component.isDown;
}
void createEntity() {
_pool.CreateEntity()
.AddInput(temp.x, temp.y, false, true);
}
} | 21.945946 | 79 | 0.714286 | [
"MIT"
] | kicholen/GamePrototype | Assets/Source/Src/System/Input/process/ProcessInputSystem.cs | 812 | C# |
namespace Mensa;
public partial class AppShell : Shell
{
public AppShell()
{
InitializeComponent();
}
}
| 11.1 | 37 | 0.702703 | [
"MIT"
] | RobinNunkesser/maui-mensa | Mensa/AppShell.xaml.cs | 113 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Aarthificial.Reanimation.Cels;
using Aarthificial.Reanimation.Common;
using Aarthificial.Reanimation.Nodes;
using UnityEditor;
using UnityEngine;
namespace Aarthificial.Reanimation.Editor.Nodes
{
public class SimpleAnimationNodeSpriteSheetWindow : EditorWindow
{
private int _framesPerClip = 10;
private string _driverName = "driverName";
private bool _autoIncrement = true;
private bool _generateAnimationEvents = false;
private bool _constructSwitch = true;
private string _switchDriverName = "switchDriverName";
private bool _switchAutoIncrement;
public TempDriverDictionary[] tempDriverDictionary = { };
[Serializable]
public class TempDriverDictionary
{
public DriverDictionary dictionary;
public int frame;
}
void OnGUI()
{
GUILayout.Label("Base Settings", EditorStyles.boldLabel);
_framesPerClip = EditorGUILayout.IntField("Frames per clip", _framesPerClip);
_driverName = EditorGUILayout.TextField("Driver Name", _driverName);
_autoIncrement = EditorGUILayout.Toggle("Auto Increment", _autoIncrement);
if (!_autoIncrement)
_generateAnimationEvents = EditorGUILayout.Toggle("Generate Animation Events", _generateAnimationEvents);
_constructSwitch = EditorGUILayout.BeginToggleGroup("Construct Switch", _constructSwitch);
_switchDriverName = EditorGUILayout.TextField("Driver Name", _switchDriverName);
_switchAutoIncrement = EditorGUILayout.Toggle("Auto Increment", _switchAutoIncrement);
SerializedObject so = new SerializedObject(this);
SerializedProperty property = so.FindProperty("tempDriverDictionary");
EditorGUILayout.PropertyField(property, true);
so.ApplyModifiedProperties();
EditorGUILayout.EndToggleGroup();
if (GUILayout.Button("Begin"))
{
CreateAnimationDrivers();
Close();
}
}
private void CreateAnimationDrivers()
{
var trailingNumbersRegex = new Regex(@"(\d+$)");
var texture = Selection.GetFiltered<Texture2D>(SelectionMode.Assets).First();
var path = AssetDatabase.GetAssetPath(texture);
var sprites = AssetDatabase.LoadAllAssetsAtPath(path).OfType<Sprite>();
var baseName = trailingNumbersRegex.Replace(texture.name, "animation_");
var assetPath = Path.Combine(Path.GetDirectoryName(path) ?? Application.dataPath, baseName);
if (!Directory.Exists(assetPath))
Directory.CreateDirectory(assetPath);
var cels = sprites
.OrderBy(
sprite =>
{
var match = trailingNumbersRegex.Match(sprite.name);
return match.Success ? int.Parse(match.Groups[0].Captures[0].ToString()) : 0;
}
)
.Select((sprite, index) =>
{
var relativeFrame = index % _framesPerClip;
var driverDictionary = Array.Find(
tempDriverDictionary,
dictionary => dictionary.frame == relativeFrame
)?.dictionary;
if (_generateAnimationEvents)
{
if (relativeFrame < _framesPerClip - 1)
{
driverDictionary ??= new DriverDictionary();
driverDictionary.keys.Add(_driverName);
driverDictionary.values.Add(relativeFrame + 1);
}
}
return new SimpleCel(sprite, driverDictionary);
})
.ToList();
var animationNodes = new List<ReanimatorNode>();
for (var i = 0; i < cels.Count / _framesPerClip; i++)
{
var asset = SimpleAnimationNode.Create<SimpleAnimationNode>(
cels: cels.GetRange(i * _framesPerClip, _framesPerClip).ToArray(),
driver: new ControlDriver(_driverName, _autoIncrement)
);
asset.name = baseName + i;
AssetDatabase.CreateAsset(asset, Path.Combine(assetPath, asset.name + ".asset"));
animationNodes.Add(asset);
}
if (_constructSwitch)
{
var asset = SwitchNode.Create(
nodes: animationNodes.ToArray(),
driver: new ControlDriver(_switchDriverName, _switchAutoIncrement)
);
asset.name = baseName + "switch";
AssetDatabase.CreateAsset(asset, Path.Combine(assetPath, asset.name + ".asset"));
}
AssetDatabase.SaveAssets();
}
}
} | 36.048276 | 121 | 0.569734 | [
"MIT"
] | maik-mursall/reanimation | Editor/Nodes/SimpleAnimationNodeSpriteSheetWindow.cs | 5,227 | 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;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.vod.Model.V20170321;
namespace Aliyun.Acs.vod.Transform.V20170321
{
public class DeleteImageResponseUnmarshaller
{
public static DeleteImageResponse Unmarshall(UnmarshallerContext context)
{
DeleteImageResponse deleteImageResponse = new DeleteImageResponse();
deleteImageResponse.HttpResponse = context.HttpResponse;
deleteImageResponse.RequestId = context.StringValue("DeleteImage.RequestId");
return deleteImageResponse;
}
}
}
| 35.9 | 82 | 0.733983 | [
"Apache-2.0"
] | fossabot/aliyun-openapi-net-sdk | aliyun-net-sdk-vod/Vod/Transform/V20170321/DeleteImageResponseUnmarshaller.cs | 1,436 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents an automation friendly version of a language-specific project.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")]
[ComVisible(true), CLSCompliant(false)]
public class OAVSProject : VSProject
{
#region fields
private ProjectNode project;
private OAVSProjectEvents events;
#endregion
#region ctors
internal OAVSProject(ProjectNode project)
{
this.project = project;
}
#endregion
#region VSProject Members
public virtual ProjectItem AddWebReference(string bstrUrl)
{
throw new NotImplementedException();
}
public virtual BuildManager BuildManager
{
get
{
throw new NotImplementedException();
//return new OABuildManager(this.project);
}
}
public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword)
{
throw new NotImplementedException();
}
public virtual ProjectItem CreateWebReferencesFolder()
{
throw new NotImplementedException();
}
public virtual DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
public virtual VSProjectEvents Events
{
get
{
if (events == null)
events = new OAVSProjectEvents(this);
return events;
}
}
public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut)
{
throw new NotImplementedException(); ;
}
public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile)
{
throw new NotImplementedException(); ;
}
public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt)
{
throw new NotImplementedException(); ;
}
public virtual Imports Imports
{
get
{
throw new NotImplementedException();
}
}
public virtual EnvDTE.Project Project
{
get
{
return this.project.GetAutomationObject() as EnvDTE.Project;
}
}
public virtual References References
{
get
{
ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode;
if (null == references)
{
return null;
}
return references.Object as References;
}
}
public virtual void Refresh()
{
throw new NotImplementedException();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public virtual string TemplatePath
{
get
{
throw new NotImplementedException();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public virtual ProjectItem WebReferencesFolder
{
get
{
throw new NotImplementedException();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public virtual bool WorkOffline
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
/// <summary>
/// Provides access to language-specific project events
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")]
[ComVisible(true), CLSCompliant(false)]
public class OAVSProjectEvents : VSProjectEvents
{
#region fields
private OAVSProject vsProject;
#endregion
#region ctors
public OAVSProjectEvents(OAVSProject vsProject)
{
this.vsProject = vsProject;
}
#endregion
#region VSProjectEvents Members
public virtual BuildManagerEvents BuildManagerEvents
{
get
{
return vsProject.BuildManager as BuildManagerEvents;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public virtual ImportsEvents ImportsEvents
{
get
{
throw new NotImplementedException();
}
}
public virtual ReferencesEvents ReferencesEvents
{
get
{
return vsProject.References as ReferencesEvents;
}
}
#endregion
}
}
| 30.06422 | 169 | 0.550504 | [
"Apache-2.0"
] | Bhaskers-Blu-Org2/poshtools | PowerShellTools/Project/SharedProject/Automation/VSProject/OAVSProject.cs | 6,554 | C# |
using System.Runtime.Serialization;
namespace ClipboardIndicator
{
[DataContract(Namespace = "", Name = "Setting")]
public class SettingsModel : BindableBase
{
[DataMember(Order = 0)]
public WindowModel Window { get; private set; }
[DataMember(Order = 1)]
public FontModel Font { get; private set; }
[DataMember(Order = 2)]
public ColorModel Color { get; private set; }
protected override void Init()
{
Window = new WindowModel();
Font = new FontModel();
Color = new ColorModel();
}
}
}
| 24.64 | 55 | 0.576299 | [
"MIT"
] | TN8001/ClipboardIndicator | ClipboardIndicator/Models/SettingsModel.cs | 618 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Substring")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Substring")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("84aa0070-95fe-4110-9a4e-a3d380325e36")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.459459 | 84 | 0.746753 | [
"MIT"
] | IvanVillani/Coding | C#/coding/MethodsExercises/Substring/Properties/AssemblyInfo.cs | 1,389 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ImageModeration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ImageModeration")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("236e4279-d3fe-40d7-bec9-e47eed3a8ada")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.756757 | 85 | 0.730126 | [
"MIT"
] | gu-wei/cognitive-services-dotnet-sdk-samples | ContentModerator/ImageModeration/Properties/AssemblyInfo.cs | 1,437 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiQualityTestShieldOrderCreateModel Data Structure.
/// </summary>
public class KoubeiQualityTestShieldOrderCreateModel : AlipayObject
{
/// <summary>
/// 枚举类型 ADD_DISH: C端加菜 DELETE_DISH: C端减菜
/// </summary>
[JsonPropertyName("action_name")]
public string ActionName { get; set; }
/// <summary>
/// 加购单号
/// </summary>
[JsonPropertyName("batch_no")]
public string BatchNo { get; set; }
/// <summary>
/// 菜谱id
/// </summary>
[JsonPropertyName("cook_id")]
public string CookId { get; set; }
/// <summary>
/// 菜品信息
/// </summary>
[JsonPropertyName("dish_list")]
public List<ShieldDishList> DishList { get; set; }
/// <summary>
/// 扩展信息
/// </summary>
[JsonPropertyName("ext_infos")]
public string ExtInfos { get; set; }
/// <summary>
/// 口碑订单号 第一次加购时不填,在后付订单上继续加购时需要传入
/// </summary>
[JsonPropertyName("order_id")]
public string OrderId { get; set; }
/// <summary>
/// 外部业务号
/// </summary>
[JsonPropertyName("out_biz_no")]
public string OutBizNo { get; set; }
/// <summary>
/// 商户ID
/// </summary>
[JsonPropertyName("partner_id")]
public string PartnerId { get; set; }
/// <summary>
/// 点餐类型 ADVANCE_PAYMENT:先付; AFTER_PAYMENT:后付;
/// </summary>
[JsonPropertyName("pay_style")]
public string PayStyle { get; set; }
/// <summary>
/// 口碑门店ID
/// </summary>
[JsonPropertyName("shop_id")]
public string ShopId { get; set; }
/// <summary>
/// 桌码,扫桌码订单必传
/// </summary>
[JsonPropertyName("table_no")]
public string TableNo { get; set; }
}
}
| 26.358974 | 71 | 0.530642 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiQualityTestShieldOrderCreateModel.cs | 2,230 | C# |
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#if EF5
using System.Data.Objects;
#elif EF6
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
#elif EFCORE
using System.Linq;
using Microsoft.EntityFrameworkCore.Query.Internal;
#endif
namespace Z.EntityFramework.Plus
{
/// <summary>Class for query future value.</summary>
/// <typeparam name="T">The type of elements of the query.</typeparam>
#if QUERY_INCLUDEOPTIMIZED
internal class QueryFutureEnumerable<T> : BaseQueryFuture, IEnumerable<T>
#else
public class QueryFutureEnumerable<T> : BaseQueryFuture, IEnumerable<T>
#endif
{
/// <summary>The result of the query future.</summary>
private IEnumerable<T> _result;
/// <summary>Constructor.</summary>
/// <param name="ownerBatch">The batch that owns this item.</param>
/// <param name="query">
/// The query to defer the execution and to add in the batch of future
/// queries.
/// </param>
#if EF5 || EF6
public QueryFutureEnumerable(QueryFutureBatch ownerBatch, ObjectQuery<T> query)
#elif EFCORE
public QueryFutureEnumerable(QueryFutureBatch ownerBatch, IQueryable query)
#endif
{
OwnerBatch = ownerBatch;
Query = query;
}
/// <summary>Gets the enumerator of the query future.</summary>
/// <returns>The enumerator of the query future.</returns>
public IEnumerator<T> GetEnumerator()
{
IEnumerator<T> values;
if (!HasValue)
{
OwnerBatch.ExecuteQueries();
}
if (_result == null)
{
values = new List<T>().GetEnumerator();
}
else
{
values = _result.GetEnumerator();
}
#if EFCORE_3X
if (IsIncludeOptimizedNullCollectionNeeded)
{
QueryIncludeOptimizedNullCollection.NullCollectionToEmpty(_result, Childs);
}
#endif
return values;
}
/// <summary>Gets the enumerator of the query future.</summary>
/// <returns>The enumerator of the query future.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#if NET45
public async Task<List<T>> ToListAsync(CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
if (!HasValue)
{
#if EF6
if (Query.Context.IsInMemoryEffortQueryContext())
{
OwnerBatch.ExecuteQueries();
}
else
{
await OwnerBatch.ExecuteQueriesAsync(cancellationToken).ConfigureAwait(false);
}
#else
await OwnerBatch.ExecuteQueriesAsync(cancellationToken).ConfigureAwait(false);
#endif
}
if (_result == null)
{
return new List<T>();
}
using (var enumerator = _result.GetEnumerator())
{
var list = new List<T>();
while (enumerator.MoveNext())
{
list.Add(enumerator.Current);
}
return list;
}
}
#if NET45
public async Task<T[]> ToArrayAsync(CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
if (!HasValue)
{
#if EF6
if (Query.Context.IsInMemoryEffortQueryContext())
{
OwnerBatch.ExecuteQueries();
}
else
{
await OwnerBatch.ExecuteQueriesAsync(cancellationToken).ConfigureAwait(false);
}
#else
await OwnerBatch.ExecuteQueriesAsync(cancellationToken ).ConfigureAwait(false);
#endif
}
if (_result == null)
{
return new T[0];
}
using (var enumerator = _result.GetEnumerator())
{
var list = new List<T>();
while (enumerator.MoveNext())
{
list.Add(enumerator.Current);
}
return list.ToArray();
}
}
#endif
#endif
/// <summary>Sets the result of the query deferred.</summary>
/// <param name="reader">The reader returned from the query execution.</param>
public override void SetResult(DbDataReader reader)
{
if (reader.GetType().FullName.Contains("Oracle"))
{
var reader2 = new QueryFutureOracleDbReader(reader);
reader = reader2;
}
var enumerator = GetQueryEnumerator<T>(reader);
using (enumerator)
{
SetResult(enumerator);
}
}
public void SetResult(IEnumerator<T> enumerator)
{
// Enumerate on all items
var list = new List<T>();
while (enumerator.MoveNext())
{
list.Add(enumerator.Current);
}
_result = list;
HasValue = true;
}
#if EFCORE
public override void ExecuteInMemory()
{
HasValue = true;
_result = ((IQueryable<T>) Query).ToList();
}
#endif
public override void GetResultDirectly()
{
var query = ((IQueryable<T>)Query);
GetResultDirectly(query);
}
#if NET45
public override Task GetResultDirectlyAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var query = ((IQueryable<T>)Query);
GetResultDirectly(query);
return Task.FromResult(0);
}
#endif
internal void GetResultDirectly(IQueryable<T> query)
{
using (var enumerator = query.GetEnumerator())
{
SetResult(enumerator);
}
}
}
} | 28.814346 | 191 | 0.570655 | [
"MIT"
] | JacksonWang2016/EntityFramework-Plus | src/shared/Z.EF.Plus.QueryFuture.Shared/QueryFutureEnumerable.cs | 6,832 | C# |
using Microsoft.Maui.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using WasteSortingMauiApp.Dtos;
using WasteSortingMauiApp.Models;
using WasteSortingMauiApp.Pages;
namespace WasteSortingMauiApp.ViewModels
{
internal class MainViewModel:BaseViewModel
{
private ObservableCollection<WasteItemViewModel> wasteModels;
public ObservableCollection<WasteItemViewModel> WasteModels
{
get => wasteModels ??= new ObservableCollection<WasteItemViewModel>();
set => SetProperty(ref wasteModels, value);
}
private string title;
public string Title
{
get => title ??= "";
set => SetProperty(ref title, value);
}
private string searchKey;
public string SearchKey
{
get => searchKey ??= "";
set => SetProperty(ref searchKey, value);
}
public ICommand SearchCommand => new Command(async () => await Search());
private async Task Search()
{
Debug.WriteLine("Search =========== " + SearchKey);
await App.Current.MainPage.Navigation.PushAsync(new SuggestListPage(SearchKey));
}
private async Task WasteClicked(WasteModel waste)
{
Debug.WriteLine(" =========== "+waste.Name);
await App.Current.MainPage.Navigation.PushAsync(new WastePage(waste));
}
public async void InitDatas()
{
Title = "垃圾分类助手";
Debug.WriteLine(" === InitDatas === ");
WasteModels.Clear();
var datas = await queryDatas();
var wetWaste = WasteDatas.WasteModelCreate(WasteType.wet);
wetWaste.WasteDatas = datas.Item1;
WasteModels.Add(new WasteItemViewModel{
Number = datas.Item1.Count().ToString(),
ActionTapped = new Action<WasteModel>( async(waste)=> await WasteClicked(waste)),
Waste= wetWaste
});
var dryWaste = WasteDatas.WasteModelCreate(WasteType.dry);
dryWaste.WasteDatas = datas.Item2;
WasteModels.Add(new WasteItemViewModel
{
Number = datas.Item2.Count().ToString(),
ActionTapped = new Action<WasteModel>(async (waste) => await WasteClicked(waste)),
Waste = dryWaste
});
var recyclableWaste = WasteDatas.WasteModelCreate(WasteType.recyclable);
recyclableWaste.WasteDatas = datas.Item3;
WasteModels.Add(new WasteItemViewModel{
Number = datas.Item3.Count().ToString(),
ActionTapped = new Action<WasteModel>(async (waste) => await WasteClicked(waste)),
Waste = recyclableWaste
});
var harmWaste = WasteDatas.WasteModelCreate(WasteType.harmful);
harmWaste.WasteDatas = datas.Item4;
WasteModels.Add(new WasteItemViewModel
{
Number = datas.Item4.Count().ToString(),
ActionTapped = new Action<WasteModel>(async (waste) => await WasteClicked(waste)),
Waste = harmWaste
});
}
private async Task<ValueTuple<List<WasteDto>, List<WasteDto>, List<WasteDto>, List<WasteDto>>> queryDatas()
{
List<WasteDto> wetList = new List<WasteDto>();
List<WasteDto> dryList = new List<WasteDto>();
List<WasteDto> recyList = new List<WasteDto>();
List<WasteDto> harmList = new List<WasteDto>();
await Task.Run(() =>
{
var list = JsonConvert.DeserializeObject<List<WasteDto>>(WasteDatas.datas);
wetList = list.FindAll((waste) => waste.sortId == 3);
dryList = list.FindAll((waste) => waste.sortId == 4);
recyList = list.FindAll((waste) => waste.sortId == 1);
harmList = list.FindAll((waste) => waste.sortId == 2);
});
var result = new ValueTuple<List<WasteDto>, List<WasteDto>, List<WasteDto>, List<WasteDto>>(wetList,dryList,recyList,harmList);
return await Task.FromResult(result);
}
}
}
| 36.278689 | 139 | 0.591279 | [
"MIT"
] | devinZhou102/WasteSortingMauiApp | src/ViewModels/MainViewModel.cs | 4,440 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using Java.Util;
using Android.Annotation;
using Android.Content;
using Android.OS;
using Android.Support.V17.Leanback.Widget;
using Android.Text.Util;
using Android.Util;
namespace TvLeanback
{
public class SearchFragment : Android.Support.V17.Leanback.App.SearchFragment, IOnItemViewClickedListener,
Android.Support.V17.Leanback.App.SearchFragment.ISearchResultProvider
{
private static string TAG = "SearchFragment";
private static int SEARCH_DELAY_MS = 300;
private static readonly CultureInfo unitedStates = new CultureInfo ("en-US", false);
public ArrayObjectAdapter mRowsAdapter {
private set;
get;
}
public ObjectAdapter ResultsAdapter {
get {
return (ObjectAdapter)mRowsAdapter;
}
}
private Handler mHandler = new Handler ();
private SearchRunnable mDelayedLoad;
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
mDelayedLoad = new SearchRunnable (this);
mRowsAdapter = new ArrayObjectAdapter (new ListRowPresenter ());
SetSearchResultProvider (this);
SetOnItemViewClickedListener (this);
}
public void OnItemClicked (Presenter.ViewHolder itemViewHolder, Java.Lang.Object item,
RowPresenter.ViewHolder rowViewHolder, Row row)
{
if (item is Movie) {
var movie = (Movie)item;
var intent = new Intent (this.Activity, typeof(DetailsActivity));
intent.PutExtra (GetString (Resource.String.movie), Utils.Serialize(movie));
StartActivity (intent);
}
}
private void QueryByWords (string words)
{
mRowsAdapter.Clear ();
if (!words.Equals (string.Empty)) {
mDelayedLoad.searchQuery = words;
mHandler.RemoveCallbacks (mDelayedLoad);
mHandler.PostDelayed (mDelayedLoad, SEARCH_DELAY_MS);
}
}
bool SearchFragment.ISearchResultProvider.OnQueryTextChange (string newQuery)
{
Log.Info (TAG, String.Format ("Search Query Text Change %s", newQuery));
QueryByWords (newQuery);
return true;
}
public bool OnQueryTextSubmit (String query)
{
Log.Info (TAG, String.Format ("Search Query Text Submit %s", query));
QueryByWords (query);
return true;
}
protected void LoadRows (String query)
{
Dictionary<string, IList<Movie>> movies = VideoProvider.MovieList;
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter (new CardPresenter ());
foreach (var entry in movies) {
foreach (Movie movie in entry.Value) {
if (movie.Title.ToLower (unitedStates)
.Contains (query.ToLower (unitedStates))
|| movie.Description.ToLower (unitedStates)
.Contains (query.ToLower (unitedStates))) {
listRowAdapter.Add (movie);
}
}
}
HeaderItem header = new HeaderItem (0, Resources.GetString (Resource.String.search_results));
mRowsAdapter.Add (new ListRow (header, listRowAdapter));
}
internal class SearchRunnable : Java.Lang.Object, Java.Lang.IRunnable //Use Java.Lang.Object to use its Dispose and Handle.get methods
{
public string searchQuery {
private get;
set;
}
private readonly SearchFragment owner;
public SearchRunnable (SearchFragment me)
{
owner = me;
}
public void Run ()
{
owner.LoadRows (searchQuery);
}
}
}
} | 27.731092 | 136 | 0.72303 | [
"Apache-2.0"
] | Dmitiry-hub/monodroid-samples | tv/TvLeanback/TvLeanback/SearchFragment.cs | 3,302 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using Ornament.WebSockets.Handlers;
namespace Demo.Web.Demos
{
public class UploadfileDemoHandler : FileHandler
{
public UploadfileDemoHandler(IOptions<WebSocketOptions> options) : base("uploadfiles", options)
{
}
}
}
| 23.611111 | 103 | 0.745882 | [
"MIT"
] | luqizheng/Ornament.WebSocket | Src/Demo.Web/Demos/UploadFile.cs | 427 | C# |
/*
Copyright 2009 Christian Arnold, Uni Duisburg-Essen
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 CrypTool.PluginBase;
using CrypTool.PluginBase.Attributes;
using CrypTool.PluginBase.Miscellaneous;
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace CrypTool.Plugins.Collector
{
[Author("Armin Krauß", "krauss@CrypTool.org", "", "")]
[PluginInfo("Collector.Properties.Resources", "PluginCaption", "PluginTooltip", "Collector/DetailedDescription/doc.xml", new[] { "CrypWin/images/default.png" })]
[AutoAssumeFullEndProgress(false)]
[ComponentCategory(ComponentCategory.ToolsDataflow)]
public class Collector : ICrypComponent
{
#region IPlugin Members
private object _objInput;
private int _size;
private readonly List<object> _arrayOutput = new List<object>();
private bool firstrun;
#region In and Out properties
[PropertyInfo(Direction.InputData, "ObjInputCaption", "ObjInputTooltip", true)]
public object ObjInput
{
get => _objInput;
set => _objInput = value;//if (_arrayOutput.Count < Size)//{// _arrayOutput.Add(value);// OnPropertyChanged("ObjInput");// if (_arrayOutput.Count == Size)// OnPropertyChanged("ArrayOutput");//}
}
[PropertyInfo(Direction.InputData, "SizeCaption", "SizeTooltip", true)]
public int Size
{
get => _size;
set
{
_size = value;
OnPropertyChanged("Size");
}
}
[PropertyInfo(Direction.OutputData, "ArrayOutputCaption", "ArrayOutputTooltip")]
public Array ArrayOutput => _arrayOutput.ToArray();
#endregion
public event StatusChangedEventHandler OnPluginStatusChanged;
public event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
public event PluginProgressChangedEventHandler OnPluginProgressChanged;
public CrypTool.PluginBase.ISettings Settings
{
get => null;
set { }
}
public System.Windows.Controls.UserControl Presentation => null;
public void PreExecution()
{
_arrayOutput.Clear();
firstrun = true;
}
public void Execute()
{
if (firstrun)
{
firstrun = false;
_arrayOutput.Clear();
}
if (Size == null)
{
GuiLogMessage("Please provide the size of the requested array.", NotificationLevel.Error);
return;
}
if (_arrayOutput.Count < Size)
{
_arrayOutput.Add(ObjInput);
if (_arrayOutput.Count == Size)
{
OnPropertyChanged("ArrayOutput");
}
}
ProgressChanged(_arrayOutput.Count, Size);
}
public void PostExecution()
{
}
public void Stop()
{
}
public void Initialize()
{
}
public void Dispose()
{
}
#endregion
#region INotifyPropertyChanged Members
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
EventsHelper.PropertyChanged(PropertyChanged, this, new PropertyChangedEventArgs(name));
}
public event PluginProgressChangedEventHandler OnPluginProcessChanged;
private void ProgressChanged(double value, double max)
{
EventsHelper.ProgressChanged(OnPluginProgressChanged, this, new PluginProgressEventArgs(value, max));
}
private void GuiLogMessage(string p, NotificationLevel notificationLevel)
{
EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(p, this, notificationLevel));
}
#endregion
}
} | 30.284768 | 221 | 0.619068 | [
"Apache-2.0"
] | CrypToolProject/CrypTool-2 | CrypPluginsExperimental/Collector/Collector.cs | 4,576 | C# |
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Pentacorn.Graphics
{
class MeshModel : IVisible
{
public MeshModel(string name, Matrix world)
{
World = world;
Model = Program.Renderer.LeaseModel(name);
}
public void Render(Renderer renderer, IViewProject viewProject)
{
throw new System.NotImplementedException();
}
public Matrix World;
public Model Model;
public IViewProject ProjectorViewProject;
}
}
| 23.64 | 71 | 0.619289 | [
"MIT"
] | JaapSuter/Pentacorn | Backup/Pentacorn/Primitives/MeshModel.cs | 593 | C# |
using AspnetRun.Services.Orders.Application.Models.Base;
using System.Collections.Generic;
namespace AspnetRun.Services.Orders.Application.Models
{
public class OrderModel : BaseModel
{
public string UserName { get; set; }
public AddressModel BillingAddress { get; set; }
public AddressModel ShippingAddress { get; set; }
public PaymentMethodModel PaymentMethod { get; set; }
public OrderStatusModel Status { get; set; }
public decimal GrandTotal { get; set; }
public List<OrderItemModel> Items { get; set; } = new List<OrderItemModel>();
}
public class AddressModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string PhoneNo { get; set; }
public string CompanyName { get; set; }
public string AddressLine { get; set; }
public string Country { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
public enum OrderStatusModel
{
Progress = 1,
OnShipping = 2,
Finished = 3
}
public enum PaymentMethodModel
{
Check = 1,
BankTransfer = 2,
Cash = 3,
Paypal = 4,
Payoneer = 5
}
}
| 28.604167 | 85 | 0.603787 | [
"MIT"
] | nilavanrajamani/ecommerce-microservice | AspnetRun.Services.Orders/Application/Models/OrderModel.cs | 1,375 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace WhereBNB.API.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 20.117647 | 71 | 0.672515 | [
"MIT"
] | ysbakker/WhereBNB | WhereBNB.API/Migrations/20210514114509_Initial.cs | 344 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("2_8_1_Array")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("2_8_1_Array")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("5d1a9c7e-83fa-47b5-b990-9f353850d7ac")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 28.432432 | 56 | 0.698669 | [
"MIT"
] | geongupark/geongupark.github.com | project/01_CSharp_basic/2_8_1_Array/2_8_1_Array/Properties/AssemblyInfo.cs | 1,485 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Interactive;
using Microsoft.VisualStudio.Editor.Interactive;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.CodeAnalysis.Internal.Log;
namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
internal abstract class VsInteractiveWindowProvider
{
private readonly IVsInteractiveWindowFactory _vsInteractiveWindowFactory;
private readonly SVsServiceProvider _vsServiceProvider;
private readonly VisualStudioWorkspace _vsWorkspace;
private readonly IViewClassifierAggregatorService _classifierAggregator;
private readonly IContentTypeRegistryService _contentTypeRegistry;
private readonly IInteractiveWindowCommandsFactory _commandsFactory;
private readonly ImmutableArray<IInteractiveWindowCommand> _commands;
// TODO: support multi-instance windows
// single instance of the Interactive Window
private IVsInteractiveWindow _vsInteractiveWindow;
public VsInteractiveWindowProvider(
SVsServiceProvider serviceProvider,
IVsInteractiveWindowFactory interactiveWindowFactory,
IViewClassifierAggregatorService classifierAggregator,
IContentTypeRegistryService contentTypeRegistry,
IInteractiveWindowCommandsFactory commandsFactory,
IInteractiveWindowCommand[] commands,
VisualStudioWorkspace workspace)
{
_vsServiceProvider = serviceProvider;
_classifierAggregator = classifierAggregator;
_contentTypeRegistry = contentTypeRegistry;
_vsWorkspace = workspace;
_commands = GetApplicableCommands(commands, coreContentType: PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName,
specializedContentType: CSharpVBInteractiveCommandsContentTypes.CSharpVBInteractiveCommandContentTypeName);
_vsInteractiveWindowFactory = interactiveWindowFactory;
_commandsFactory = commandsFactory;
}
protected abstract InteractiveEvaluator CreateInteractiveEvaluator(
SVsServiceProvider serviceProvider,
IViewClassifierAggregatorService classifierAggregator,
IContentTypeRegistryService contentTypeRegistry,
VisualStudioWorkspace workspace);
protected abstract Guid LanguageServiceGuid { get; }
protected abstract Guid Id { get; }
protected abstract string Title { get; }
protected abstract FunctionId InteractiveWindowFunctionId { get; }
protected IInteractiveWindowCommandsFactory CommandsFactory
{
get
{
return _commandsFactory;
}
}
protected ImmutableArray<IInteractiveWindowCommand> Commands
{
get
{
return _commands;
}
}
public void Create(int instanceId)
{
var evaluator = CreateInteractiveEvaluator(_vsServiceProvider, _classifierAggregator, _contentTypeRegistry, _vsWorkspace);
Debug.Assert(_vsInteractiveWindow == null);
// ForceCreate means that the window should be created if the persisted layout indicates that it is visible.
_vsInteractiveWindow = _vsInteractiveWindowFactory.Create(Id, instanceId, Title, evaluator, __VSCREATETOOLWIN.CTW_fForceCreate);
_vsInteractiveWindow.SetLanguage(LanguageServiceGuid, evaluator.ContentType);
if (_vsInteractiveWindow is ToolWindowPane interactiveWindowPane)
{
evaluator.OnBeforeReset += is64bit => interactiveWindowPane.Caption = Title + (is64bit ? " (64-bit)" : " (32-bit)");
}
var window = _vsInteractiveWindow.InteractiveWindow;
window.TextView.Options.SetOptionValue(DefaultTextViewHostOptions.SuggestionMarginId, true);
void closeEventDelegate(object sender, EventArgs e)
{
window.TextView.Closed -= closeEventDelegate;
LogCloseSession(evaluator.SubmissionCount);
evaluator.Dispose();
}
// the tool window now owns the engine:
window.TextView.Closed += closeEventDelegate;
// vsWindow.AutoSaveOptions = true;
// fire and forget:
window.InitializeAsync();
LogSession(LogMessage.Window, LogMessage.Create);
}
public IVsInteractiveWindow Open(int instanceId, bool focus)
{
// TODO: we don't support multi-instance yet
Debug.Assert(instanceId == 0);
if (_vsInteractiveWindow == null)
{
Create(instanceId);
}
_vsInteractiveWindow.Show(focus);
return _vsInteractiveWindow;
}
protected void LogSession(string key, string value)
{
Logger.Log(InteractiveWindowFunctionId, KeyValueLogMessage.Create(m => m.Add(key, value)));
}
private void LogCloseSession(int languageBufferCount)
{
Logger.Log(InteractiveWindowFunctionId,
KeyValueLogMessage.Create(m =>
{
m.Add(LogMessage.Window, LogMessage.Close);
m.Add(LogMessage.LanguageBufferCount, languageBufferCount);
}));
}
private static ImmutableArray<IInteractiveWindowCommand> GetApplicableCommands(IInteractiveWindowCommand[] commands, string coreContentType, string specializedContentType)
{
// get all commands of coreContentType - generic interactive window commands
var interactiveCommands = commands.Where(
c => c.GetType().GetCustomAttributes(typeof(ContentTypeAttribute), inherit: true).Any(
a => ((ContentTypeAttribute)a).ContentTypes == coreContentType)).ToArray();
// get all commands of specializedContentType - smart C#/VB command implementations
var specializedInteractiveCommands = commands.Where(
c => c.GetType().GetCustomAttributes(typeof(ContentTypeAttribute), inherit: true).Any(
a => ((ContentTypeAttribute)a).ContentTypes == specializedContentType)).ToArray();
// We should choose specialized C#/VB commands over generic core interactive window commands
// Build a map of names and associated core command first
var interactiveCommandMap = new Dictionary<string, int>();
for (var i = 0; i < interactiveCommands.Length; i++)
{
foreach (var name in interactiveCommands[i].Names)
{
interactiveCommandMap.Add(name, i);
}
}
// swap core commands with specialized command if both exist
// Command can have multiple names. We need to compare every name to find match.
foreach (var command in specializedInteractiveCommands)
{
foreach (var name in command.Names)
{
if (interactiveCommandMap.TryGetValue(name, out var value))
{
interactiveCommands[value] = command;
break;
}
}
}
return interactiveCommands.ToImmutableArray();
}
}
}
| 43.213904 | 179 | 0.665017 | [
"Apache-2.0"
] | 20chan/roslyn | src/VisualStudio/Core/Def/Interactive/VsInteractiveWindowProvider.cs | 8,083 | C# |
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StormLibSharp.Native
{
internal sealed class MpqFileSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public MpqFileSafeHandle(IntPtr handle)
: base(true)
{
this.SetHandle(handle);
}
public MpqFileSafeHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
return NativeMethods.SFileCloseFile(this.handle);
}
}
}
| 21.107143 | 79 | 0.620981 | [
"MIT"
] | HelloKitty/stormlibsharp | src/StormLibSharp/Native/MpqFileSafeHandle.cs | 593 | 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 rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the RestoreDBInstanceFromDBSnapshot operation.
/// Creates a new DB instance from a DB snapshot. The target database is created from
/// the source database restore point with most of the source's original configuration,
/// including the default security group and DB parameter group. By default, the new DB
/// instance is created as a Single-AZ deployment, except when the instance is a SQL Server
/// instance that has an option group associated with mirroring. In this case, the instance
/// becomes a Multi-AZ deployment, not a Single-AZ deployment.
///
///
/// <para>
/// If you want to replace your original DB instance with the new, restored DB instance,
/// then rename your original DB instance before you call the RestoreDBInstanceFromDBSnapshot
/// action. RDS doesn't allow two DB instances with the same name. After you have renamed
/// your original DB instance with a different identifier, then you can pass the original
/// name of the DB instance as the DBInstanceIdentifier in the call to the RestoreDBInstanceFromDBSnapshot
/// action. The result is that you replace the original DB instance with the DB instance
/// created from the snapshot.
/// </para>
///
/// <para>
/// If you are restoring from a shared manual DB snapshot, the <code>DBSnapshotIdentifier</code>
/// must be the ARN of the shared DB snapshot.
/// </para>
/// <note>
/// <para>
/// This command doesn't apply to Aurora MySQL and Aurora PostgreSQL. For Aurora, use
/// <code>RestoreDBClusterFromSnapshot</code>.
/// </para>
/// </note>
/// </summary>
public partial class RestoreDBInstanceFromDBSnapshotRequest : AmazonRDSRequest
{
private bool? _autoMinorVersionUpgrade;
private string _availabilityZone;
private bool? _copyTagsToSnapshot;
private string _customIamInstanceProfile;
private string _dbInstanceClass;
private string _dbInstanceIdentifier;
private string _dbName;
private string _dbParameterGroupName;
private string _dbSnapshotIdentifier;
private string _dbSubnetGroupName;
private bool? _deletionProtection;
private string _domain;
private string _domainIAMRoleName;
private List<string> _enableCloudwatchLogsExports = new List<string>();
private bool? _enableCustomerOwnedIp;
private bool? _enableIAMDatabaseAuthentication;
private string _engine;
private int? _iops;
private string _licenseModel;
private bool? _multiAZ;
private string _optionGroupName;
private int? _port;
private List<ProcessorFeature> _processorFeatures = new List<ProcessorFeature>();
private bool? _publiclyAccessible;
private string _storageType;
private List<Tag> _tags = new List<Tag>();
private string _tdeCredentialArn;
private string _tdeCredentialPassword;
private bool? _useDefaultProcessorFeatures;
private List<string> _vpcSecurityGroupIds = new List<string>();
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public RestoreDBInstanceFromDBSnapshotRequest() { }
/// <summary>
/// Instantiates RestoreDBInstanceFromDBSnapshotRequest with the parameterized properties
/// </summary>
/// <param name="dbInstanceIdentifier">Name of the DB instance to create from the DB snapshot. This parameter isn't case-sensitive. Constraints: <ul> <li> Must contain from 1 to 63 numbers, letters, or hyphens </li> <li> First character must be a letter </li> <li> Can't end with a hyphen or contain two consecutive hyphens </li> </ul> Example: <code>my-snapshot-id</code> </param>
/// <param name="dbSnapshotIdentifier">The identifier for the DB snapshot to restore from. Constraints: <ul> <li> Must match the identifier of an existing DBSnapshot. </li> <li> If you are restoring from a shared manual DB snapshot, the <code>DBSnapshotIdentifier</code> must be the ARN of the shared DB snapshot. </li> </ul></param>
public RestoreDBInstanceFromDBSnapshotRequest(string dbInstanceIdentifier, string dbSnapshotIdentifier)
{
_dbInstanceIdentifier = dbInstanceIdentifier;
_dbSnapshotIdentifier = dbSnapshotIdentifier;
}
/// <summary>
/// Gets and sets the property AutoMinorVersionUpgrade.
/// <para>
/// A value that indicates whether minor version upgrades are applied automatically to
/// the DB instance during the maintenance window.
/// </para>
///
/// <para>
/// If you restore an RDS Custom DB instance, you must disable this parameter.
/// </para>
/// </summary>
public bool AutoMinorVersionUpgrade
{
get { return this._autoMinorVersionUpgrade.GetValueOrDefault(); }
set { this._autoMinorVersionUpgrade = value; }
}
// Check to see if AutoMinorVersionUpgrade property is set
internal bool IsSetAutoMinorVersionUpgrade()
{
return this._autoMinorVersionUpgrade.HasValue;
}
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// The Availability Zone (AZ) where the DB instance will be created.
/// </para>
///
/// <para>
/// Default: A random, system-chosen Availability Zone.
/// </para>
///
/// <para>
/// Constraint: You can't specify the <code>AvailabilityZone</code> parameter if the DB
/// instance is a Multi-AZ deployment.
/// </para>
///
/// <para>
/// Example: <code>us-east-1a</code>
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property CopyTagsToSnapshot.
/// <para>
/// A value that indicates whether to copy all tags from the restored DB instance to snapshots
/// of the DB instance. By default, tags are not copied.
/// </para>
/// </summary>
public bool CopyTagsToSnapshot
{
get { return this._copyTagsToSnapshot.GetValueOrDefault(); }
set { this._copyTagsToSnapshot = value; }
}
// Check to see if CopyTagsToSnapshot property is set
internal bool IsSetCopyTagsToSnapshot()
{
return this._copyTagsToSnapshot.HasValue;
}
/// <summary>
/// Gets and sets the property CustomIamInstanceProfile.
/// <para>
/// The instance profile associated with the underlying Amazon EC2 instance of an RDS
/// Custom DB instance. The instance profile must meet the following requirements:
/// </para>
/// <ul> <li>
/// <para>
/// The profile must exist in your account.
/// </para>
/// </li> <li>
/// <para>
/// The profile must have an IAM role that Amazon EC2 has permissions to assume.
/// </para>
/// </li> <li>
/// <para>
/// The instance profile name and the associated IAM role name must start with the prefix
/// <code>AWSRDSCustom</code>.
/// </para>
/// </li> </ul>
/// <para>
/// For the list of permissions required for the IAM role, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/custom-setup-orcl.html#custom-setup-orcl.iam-vpc">
/// Configure IAM and your VPC</a> in the <i>Amazon Relational Database Service User Guide</i>.
/// </para>
///
/// <para>
/// This setting is required for RDS Custom.
/// </para>
/// </summary>
public string CustomIamInstanceProfile
{
get { return this._customIamInstanceProfile; }
set { this._customIamInstanceProfile = value; }
}
// Check to see if CustomIamInstanceProfile property is set
internal bool IsSetCustomIamInstanceProfile()
{
return this._customIamInstanceProfile != null;
}
/// <summary>
/// Gets and sets the property DBInstanceClass.
/// <para>
/// The compute and memory capacity of the Amazon RDS DB instance, for example, <code>db.m4.large</code>.
/// Not all DB instance classes are available in all Amazon Web Services Regions, or for
/// all database engines. For the full list of DB instance classes, and availability for
/// your engine, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.DBInstanceClass.html">DB
/// Instance Class</a> in the <i>Amazon RDS User Guide.</i>
/// </para>
///
/// <para>
/// Default: The same DBInstanceClass as the original DB instance.
/// </para>
/// </summary>
public string DBInstanceClass
{
get { return this._dbInstanceClass; }
set { this._dbInstanceClass = value; }
}
// Check to see if DBInstanceClass property is set
internal bool IsSetDBInstanceClass()
{
return this._dbInstanceClass != null;
}
/// <summary>
/// Gets and sets the property DBInstanceIdentifier.
/// <para>
/// Name of the DB instance to create from the DB snapshot. This parameter isn't case-sensitive.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must contain from 1 to 63 numbers, letters, or hyphens
/// </para>
/// </li> <li>
/// <para>
/// First character must be a letter
/// </para>
/// </li> <li>
/// <para>
/// Can't end with a hyphen or contain two consecutive hyphens
/// </para>
/// </li> </ul>
/// <para>
/// Example: <code>my-snapshot-id</code>
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string DBInstanceIdentifier
{
get { return this._dbInstanceIdentifier; }
set { this._dbInstanceIdentifier = value; }
}
// Check to see if DBInstanceIdentifier property is set
internal bool IsSetDBInstanceIdentifier()
{
return this._dbInstanceIdentifier != null;
}
/// <summary>
/// Gets and sets the property DBName.
/// <para>
/// The database name for the restored DB instance.
/// </para>
///
/// <para>
/// This parameter doesn't apply to the MySQL, PostgreSQL, or MariaDB engines. It also
/// doesn't apply to RDS Custom DB instances.
/// </para>
/// </summary>
public string DBName
{
get { return this._dbName; }
set { this._dbName = value; }
}
// Check to see if DBName property is set
internal bool IsSetDBName()
{
return this._dbName != null;
}
/// <summary>
/// Gets and sets the property DBParameterGroupName.
/// <para>
/// The name of the DB parameter group to associate with this DB instance.
/// </para>
///
/// <para>
/// If you don't specify a value for <code>DBParameterGroupName</code>, then RDS uses
/// the default <code>DBParameterGroup</code> for the specified DB engine.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// If supplied, must match the name of an existing DBParameterGroup.
/// </para>
/// </li> <li>
/// <para>
/// Must be 1 to 255 letters, numbers, or hyphens.
/// </para>
/// </li> <li>
/// <para>
/// First character must be a letter.
/// </para>
/// </li> <li>
/// <para>
/// Can't end with a hyphen or contain two consecutive hyphens.
/// </para>
/// </li> </ul>
/// </summary>
public string DBParameterGroupName
{
get { return this._dbParameterGroupName; }
set { this._dbParameterGroupName = value; }
}
// Check to see if DBParameterGroupName property is set
internal bool IsSetDBParameterGroupName()
{
return this._dbParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property DBSnapshotIdentifier.
/// <para>
/// The identifier for the DB snapshot to restore from.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must match the identifier of an existing DBSnapshot.
/// </para>
/// </li> <li>
/// <para>
/// If you are restoring from a shared manual DB snapshot, the <code>DBSnapshotIdentifier</code>
/// must be the ARN of the shared DB snapshot.
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Required=true)]
public string DBSnapshotIdentifier
{
get { return this._dbSnapshotIdentifier; }
set { this._dbSnapshotIdentifier = value; }
}
// Check to see if DBSnapshotIdentifier property is set
internal bool IsSetDBSnapshotIdentifier()
{
return this._dbSnapshotIdentifier != null;
}
/// <summary>
/// Gets and sets the property DBSubnetGroupName.
/// <para>
/// The DB subnet group name to use for the new instance.
/// </para>
///
/// <para>
/// Constraints: If supplied, must match the name of an existing DBSubnetGroup.
/// </para>
///
/// <para>
/// Example: <code>mySubnetgroup</code>
/// </para>
/// </summary>
public string DBSubnetGroupName
{
get { return this._dbSubnetGroupName; }
set { this._dbSubnetGroupName = value; }
}
// Check to see if DBSubnetGroupName property is set
internal bool IsSetDBSubnetGroupName()
{
return this._dbSubnetGroupName != null;
}
/// <summary>
/// Gets and sets the property DeletionProtection.
/// <para>
/// A value that indicates whether the DB instance has deletion protection enabled. The
/// database can't be deleted when deletion protection is enabled. By default, deletion
/// protection is disabled. For more information, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DeleteInstance.html">
/// Deleting a DB Instance</a>.
/// </para>
/// </summary>
public bool DeletionProtection
{
get { return this._deletionProtection.GetValueOrDefault(); }
set { this._deletionProtection = value; }
}
// Check to see if DeletionProtection property is set
internal bool IsSetDeletionProtection()
{
return this._deletionProtection.HasValue;
}
/// <summary>
/// Gets and sets the property Domain.
/// <para>
/// Specify the Active Directory directory ID to restore the DB instance in. The domain/
/// must be created prior to this operation. Currently, you can create only MySQL, Microsoft
/// SQL Server, Oracle, and PostgreSQL DB instances in an Active Directory Domain.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/kerberos-authentication.html">
/// Kerberos Authentication</a> in the <i>Amazon RDS User Guide</i>.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public string Domain
{
get { return this._domain; }
set { this._domain = value; }
}
// Check to see if Domain property is set
internal bool IsSetDomain()
{
return this._domain != null;
}
/// <summary>
/// Gets and sets the property DomainIAMRoleName.
/// <para>
/// Specify the name of the IAM role to be used when making API calls to the Directory
/// Service.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public string DomainIAMRoleName
{
get { return this._domainIAMRoleName; }
set { this._domainIAMRoleName = value; }
}
// Check to see if DomainIAMRoleName property is set
internal bool IsSetDomainIAMRoleName()
{
return this._domainIAMRoleName != null;
}
/// <summary>
/// Gets and sets the property EnableCloudwatchLogsExports.
/// <para>
/// The list of logs that the restored DB instance is to export to CloudWatch Logs. The
/// values in the list depend on the DB engine being used. For more information, see <a
/// href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.html#USER_LogAccess.Procedural.UploadtoCloudWatch">Publishing
/// Database Logs to Amazon CloudWatch Logs</a> in the <i>Amazon RDS User Guide</i>.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public List<string> EnableCloudwatchLogsExports
{
get { return this._enableCloudwatchLogsExports; }
set { this._enableCloudwatchLogsExports = value; }
}
// Check to see if EnableCloudwatchLogsExports property is set
internal bool IsSetEnableCloudwatchLogsExports()
{
return this._enableCloudwatchLogsExports != null && this._enableCloudwatchLogsExports.Count > 0;
}
/// <summary>
/// Gets and sets the property EnableCustomerOwnedIp.
/// <para>
/// A value that indicates whether to enable a customer-owned IP address (CoIP) for an
/// RDS on Outposts DB instance.
/// </para>
///
/// <para>
/// A <i>CoIP</i> provides local or external connectivity to resources in your Outpost
/// subnets through your on-premises network. For some use cases, a CoIP can provide lower
/// latency for connections to the DB instance from outside of its virtual private cloud
/// (VPC) on your local network.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
///
/// <para>
/// For more information about RDS on Outposts, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-on-outposts.html">Working
/// with Amazon RDS on Amazon Web Services Outposts</a> in the <i>Amazon RDS User Guide</i>.
/// </para>
///
/// <para>
/// For more information about CoIPs, see <a href="https://docs.aws.amazon.com/outposts/latest/userguide/outposts-networking-components.html#ip-addressing">Customer-owned
/// IP addresses</a> in the <i>Amazon Web Services Outposts User Guide</i>.
/// </para>
/// </summary>
public bool EnableCustomerOwnedIp
{
get { return this._enableCustomerOwnedIp.GetValueOrDefault(); }
set { this._enableCustomerOwnedIp = value; }
}
// Check to see if EnableCustomerOwnedIp property is set
internal bool IsSetEnableCustomerOwnedIp()
{
return this._enableCustomerOwnedIp.HasValue;
}
/// <summary>
/// Gets and sets the property EnableIAMDatabaseAuthentication.
/// <para>
/// A value that indicates whether to enable mapping of Amazon Web Services Identity and
/// Access Management (IAM) accounts to database accounts. By default, mapping is disabled.
/// </para>
///
/// <para>
/// For more information about IAM database authentication, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html">
/// IAM Database Authentication for MySQL and PostgreSQL</a> in the <i>Amazon RDS User
/// Guide.</i>
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public bool EnableIAMDatabaseAuthentication
{
get { return this._enableIAMDatabaseAuthentication.GetValueOrDefault(); }
set { this._enableIAMDatabaseAuthentication = value; }
}
// Check to see if EnableIAMDatabaseAuthentication property is set
internal bool IsSetEnableIAMDatabaseAuthentication()
{
return this._enableIAMDatabaseAuthentication.HasValue;
}
/// <summary>
/// Gets and sets the property Engine.
/// <para>
/// The database engine to use for the new instance.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
///
/// <para>
/// Default: The same as source
/// </para>
///
/// <para>
/// Constraint: Must be compatible with the engine of the source. For example, you can
/// restore a MariaDB 10.1 DB instance from a MySQL 5.6 snapshot.
/// </para>
///
/// <para>
/// Valid Values:
/// </para>
/// <ul> <li>
/// <para>
/// <code>mariadb</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>mysql</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>oracle-ee</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>oracle-ee-cdb</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>oracle-se2</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>oracle-se2-cdb</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>postgres</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>sqlserver-ee</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>sqlserver-se</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>sqlserver-ex</code>
/// </para>
/// </li> <li>
/// <para>
/// <code>sqlserver-web</code>
/// </para>
/// </li> </ul>
/// </summary>
public string Engine
{
get { return this._engine; }
set { this._engine = value; }
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this._engine != null;
}
/// <summary>
/// Gets and sets the property Iops.
/// <para>
/// Specifies the amount of provisioned IOPS for the DB instance, expressed in I/O operations
/// per second. If this parameter isn't specified, the IOPS value is taken from the backup.
/// If this parameter is set to 0, the new instance is converted to a non-PIOPS instance.
/// The conversion takes additional time, though your DB instance is available for connections
/// before the conversion starts.
/// </para>
///
/// <para>
/// The provisioned IOPS value must follow the requirements for your database engine.
/// For more information, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html#USER_PIOPS">Amazon
/// RDS Provisioned IOPS Storage to Improve Performance</a> in the <i>Amazon RDS User
/// Guide.</i>
/// </para>
///
/// <para>
/// Constraints: Must be an integer greater than 1000.
/// </para>
/// </summary>
public int Iops
{
get { return this._iops.GetValueOrDefault(); }
set { this._iops = value; }
}
// Check to see if Iops property is set
internal bool IsSetIops()
{
return this._iops.HasValue;
}
/// <summary>
/// Gets and sets the property LicenseModel.
/// <para>
/// License model information for the restored DB instance.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
///
/// <para>
/// Default: Same as source.
/// </para>
///
/// <para>
/// Valid values: <code>license-included</code> | <code>bring-your-own-license</code>
/// | <code>general-public-license</code>
/// </para>
/// </summary>
public string LicenseModel
{
get { return this._licenseModel; }
set { this._licenseModel = value; }
}
// Check to see if LicenseModel property is set
internal bool IsSetLicenseModel()
{
return this._licenseModel != null;
}
/// <summary>
/// Gets and sets the property MultiAZ.
/// <para>
/// A value that indicates whether the DB instance is a Multi-AZ deployment.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
///
/// <para>
/// Constraint: You can't specify the <code>AvailabilityZone</code> parameter if the DB
/// instance is a Multi-AZ deployment.
/// </para>
/// </summary>
public bool MultiAZ
{
get { return this._multiAZ.GetValueOrDefault(); }
set { this._multiAZ = value; }
}
// Check to see if MultiAZ property is set
internal bool IsSetMultiAZ()
{
return this._multiAZ.HasValue;
}
/// <summary>
/// Gets and sets the property OptionGroupName.
/// <para>
/// The name of the option group to be used for the restored DB instance.
/// </para>
///
/// <para>
/// Permanent options, such as the TDE option for Oracle Advanced Security TDE, can't
/// be removed from an option group, and that option group can't be removed from a DB
/// instance after it is associated with a DB instance.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public string OptionGroupName
{
get { return this._optionGroupName; }
set { this._optionGroupName = value; }
}
// Check to see if OptionGroupName property is set
internal bool IsSetOptionGroupName()
{
return this._optionGroupName != null;
}
/// <summary>
/// Gets and sets the property Port.
/// <para>
/// The port number on which the database accepts connections.
/// </para>
///
/// <para>
/// Default: The same port as the original DB instance
/// </para>
///
/// <para>
/// Constraints: Value must be <code>1150-65535</code>
/// </para>
/// </summary>
public int Port
{
get { return this._port.GetValueOrDefault(); }
set { this._port = value; }
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this._port.HasValue;
}
/// <summary>
/// Gets and sets the property ProcessorFeatures.
/// <para>
/// The number of CPU cores and the number of threads per core for the DB instance class
/// of the DB instance.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public List<ProcessorFeature> ProcessorFeatures
{
get { return this._processorFeatures; }
set { this._processorFeatures = value; }
}
// Check to see if ProcessorFeatures property is set
internal bool IsSetProcessorFeatures()
{
return this._processorFeatures != null && this._processorFeatures.Count > 0;
}
/// <summary>
/// Gets and sets the property PubliclyAccessible.
/// <para>
/// A value that indicates whether the DB instance is publicly accessible.
/// </para>
///
/// <para>
/// When the DB instance is publicly accessible, its DNS endpoint resolves to the private
/// IP address from within the DB instance's VPC, and to the public IP address from outside
/// of the DB instance's VPC. Access to the DB instance is ultimately controlled by the
/// security group it uses, and that public access is not permitted if the security group
/// assigned to the DB instance doesn't permit it.
/// </para>
///
/// <para>
/// When the DB instance isn't publicly accessible, it is an internal DB instance with
/// a DNS name that resolves to a private IP address.
/// </para>
///
/// <para>
/// For more information, see <a>CreateDBInstance</a>.
/// </para>
/// </summary>
public bool PubliclyAccessible
{
get { return this._publiclyAccessible.GetValueOrDefault(); }
set { this._publiclyAccessible = value; }
}
// Check to see if PubliclyAccessible property is set
internal bool IsSetPubliclyAccessible()
{
return this._publiclyAccessible.HasValue;
}
/// <summary>
/// Gets and sets the property StorageType.
/// <para>
/// Specifies the storage type to be associated with the DB instance.
/// </para>
///
/// <para>
/// Valid values: <code>standard | gp2 | io1</code>
/// </para>
///
/// <para>
/// If you specify <code>io1</code>, you must also include a value for the <code>Iops</code>
/// parameter.
/// </para>
///
/// <para>
/// Default: <code>io1</code> if the <code>Iops</code> parameter is specified, otherwise
/// <code>gp2</code>
/// </para>
/// </summary>
public string StorageType
{
get { return this._storageType; }
set { this._storageType = value; }
}
// Check to see if StorageType property is set
internal bool IsSetStorageType()
{
return this._storageType != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property TdeCredentialArn.
/// <para>
/// The ARN from the key store with which to associate the instance for TDE encryption.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public string TdeCredentialArn
{
get { return this._tdeCredentialArn; }
set { this._tdeCredentialArn = value; }
}
// Check to see if TdeCredentialArn property is set
internal bool IsSetTdeCredentialArn()
{
return this._tdeCredentialArn != null;
}
/// <summary>
/// Gets and sets the property TdeCredentialPassword.
/// <para>
/// The password for the given ARN from the key store in order to access the device.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public string TdeCredentialPassword
{
get { return this._tdeCredentialPassword; }
set { this._tdeCredentialPassword = value; }
}
// Check to see if TdeCredentialPassword property is set
internal bool IsSetTdeCredentialPassword()
{
return this._tdeCredentialPassword != null;
}
/// <summary>
/// Gets and sets the property UseDefaultProcessorFeatures.
/// <para>
/// A value that indicates whether the DB instance class of the DB instance uses its default
/// processor features.
/// </para>
///
/// <para>
/// This setting doesn't apply to RDS Custom.
/// </para>
/// </summary>
public bool UseDefaultProcessorFeatures
{
get { return this._useDefaultProcessorFeatures.GetValueOrDefault(); }
set { this._useDefaultProcessorFeatures = value; }
}
// Check to see if UseDefaultProcessorFeatures property is set
internal bool IsSetUseDefaultProcessorFeatures()
{
return this._useDefaultProcessorFeatures.HasValue;
}
/// <summary>
/// Gets and sets the property VpcSecurityGroupIds.
/// <para>
/// A list of EC2 VPC security groups to associate with this DB instance.
/// </para>
///
/// <para>
/// Default: The default EC2 VPC security group for the DB subnet group's VPC.
/// </para>
/// </summary>
public List<string> VpcSecurityGroupIds
{
get { return this._vpcSecurityGroupIds; }
set { this._vpcSecurityGroupIds = value; }
}
// Check to see if VpcSecurityGroupIds property is set
internal bool IsSetVpcSecurityGroupIds()
{
return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0;
}
}
} | 36.187686 | 389 | 0.556928 | [
"Apache-2.0"
] | MDanialSaleem/aws-sdk-net | sdk/src/Services/RDS/Generated/Model/RestoreDBInstanceFromDBSnapshotRequest.cs | 36,441 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace TJAPlayer3
{
/// <summary>
/// 「トグル」(ON, OFF の2状態)を表すアイテム。
/// </summary>
internal class CItemToggle : CItemBase
{
// プロパティ
public bool bON;
// コンストラクタ
public CItemToggle()
{
base.e種別 = CItemBase.E種別.ONorOFFトグル;
this.bON = false;
}
public CItemToggle( string str項目名, bool b初期状態 )
: this()
{
this.t初期化( str項目名, b初期状態 );
}
public CItemToggle(string str項目名, bool b初期状態, string str説明文jp)
: this() {
this.t初期化(str項目名, b初期状態, str説明文jp);
}
public CItemToggle(string str項目名, bool b初期状態, string str説明文jp, string str説明文en)
: this() {
this.t初期化(str項目名, b初期状態, str説明文jp, str説明文en);
}
public CItemToggle(string str項目名, bool b初期状態, CItemBase.Eパネル種別 eパネル種別)
: this()
{
this.t初期化( str項目名, b初期状態, eパネル種別 );
}
public CItemToggle(string str項目名, bool b初期状態, CItemBase.Eパネル種別 eパネル種別, string str説明文jp)
: this() {
this.t初期化(str項目名, b初期状態, eパネル種別, str説明文jp);
}
public CItemToggle(string str項目名, bool b初期状態, CItemBase.Eパネル種別 eパネル種別, string str説明文jp, string str説明文en)
: this() {
this.t初期化(str項目名, b初期状態, eパネル種別, str説明文jp, str説明文en);
}
// CItemBase 実装
public override void tEnter押下()
{
this.t項目値を次へ移動();
}
public override void t項目値を次へ移動()
{
this.bON = !this.bON;
}
public override void t項目値を前へ移動()
{
this.t項目値を次へ移動();
}
public void t初期化( string str項目名, bool b初期状態 )
{
this.t初期化( str項目名, b初期状態, CItemBase.Eパネル種別.通常 );
}
public void t初期化(string str項目名, bool b初期状態, string str説明文jp) {
this.t初期化(str項目名, b初期状態, CItemBase.Eパネル種別.通常, str説明文jp, str説明文jp);
}
public void t初期化(string str項目名, bool b初期状態, string str説明文jp, string str説明文en) {
this.t初期化(str項目名, b初期状態, CItemBase.Eパネル種別.通常, str説明文jp, str説明文en);
}
public void t初期化(string str項目名, bool b初期状態, CItemBase.Eパネル種別 eパネル種別)
{
this.t初期化(str項目名, b初期状態, eパネル種別, "", "");
}
public void t初期化(string str項目名, bool b初期状態, CItemBase.Eパネル種別 eパネル種別, string str説明文jp) {
this.t初期化(str項目名, b初期状態, eパネル種別, str説明文jp, str説明文jp);
}
public void t初期化(string str項目名, bool b初期状態, CItemBase.Eパネル種別 eパネル種別, string str説明文jp, string str説明文en) {
base.t初期化(str項目名, eパネル種別, str説明文jp, str説明文en);
this.bON = b初期状態;
}
public override object obj現在値()
{
return ( this.bON ) ? "ON" : "OFF";
}
public override int GetIndex()
{
return ( this.bON ) ? 1 : 0;
}
public override void SetIndex( int index )
{
switch ( index )
{
case 0:
this.bON = false;
break;
case 1:
this.bON = true;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
| 23.678571 | 106 | 0.662896 | [
"MIT"
] | 0auBSQ/OpenTaiko | TJAPlayer3/Items/CItemToggle.cs | 3,628 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering.HighDefinition;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Internal;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Legacy;
using UnityEditor.Rendering.HighDefinition.ShaderGraph.Legacy;
using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties;
using static UnityEditor.Rendering.HighDefinition.HDShaderUtils;
namespace UnityEditor.Rendering.HighDefinition.ShaderGraph
{
sealed partial class StackLitSubTarget : LightingSubTarget, ILegacyTarget, IRequiresData<StackLitData>
{
public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary<BlockFieldDescriptor, int> blockMap)
{
blockMap = null;
if(!(masterNode is StackLitMasterNode1 stackLitMasterNode))
return false;
m_MigrateFromOldSG = true;
// Set data
systemData.surfaceType = (SurfaceType)stackLitMasterNode.m_SurfaceType;
systemData.blendMode = HDSubShaderUtilities.UpgradeLegacyAlphaModeToBlendMode((int)stackLitMasterNode.m_AlphaMode);
// Previous master node wasn't having any renderingPass. Assign it correctly now.
systemData.renderQueueType = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent;
systemData.alphaTest = stackLitMasterNode.m_AlphaTest;
systemData.sortPriority = stackLitMasterNode.m_SortPriority;
systemData.doubleSidedMode = stackLitMasterNode.m_DoubleSidedMode;
systemData.transparentZWrite = stackLitMasterNode.m_ZWrite;
systemData.transparentCullMode = stackLitMasterNode.m_transparentCullMode;
systemData.zTest = stackLitMasterNode.m_ZTest;
systemData.dotsInstancing = stackLitMasterNode.m_DOTSInstancing;
systemData.materialNeedsUpdateHash = stackLitMasterNode.m_MaterialNeedsUpdateHash;
builtinData.supportLodCrossFade = stackLitMasterNode.m_SupportLodCrossFade;
builtinData.transparencyFog = stackLitMasterNode.m_TransparencyFog;
builtinData.distortion = stackLitMasterNode.m_Distortion;
builtinData.distortionMode = stackLitMasterNode.m_DistortionMode;
builtinData.distortionDepthTest = stackLitMasterNode.m_DistortionDepthTest;
builtinData.addPrecomputedVelocity = stackLitMasterNode.m_AddPrecomputedVelocity;
builtinData.depthOffset = stackLitMasterNode.m_depthOffset;
builtinData.alphaToMask = stackLitMasterNode.m_AlphaToMask;
lightingData.normalDropOffSpace = stackLitMasterNode.m_NormalDropOffSpace;
lightingData.blendPreserveSpecular = stackLitMasterNode.m_BlendPreserveSpecular;
lightingData.receiveDecals = stackLitMasterNode.m_ReceiveDecals;
lightingData.receiveSSR = stackLitMasterNode.m_ReceiveSSR;
lightingData.receiveSSRTransparent = stackLitMasterNode.m_ReceivesSSRTransparent;
lightingData.overrideBakedGI = stackLitMasterNode.m_overrideBakedGI;
lightingData.specularAA = stackLitMasterNode.m_GeometricSpecularAA;
stackLitData.subsurfaceScattering = stackLitMasterNode.m_SubsurfaceScattering;
stackLitData.transmission = stackLitMasterNode.m_Transmission;
stackLitData.energyConservingSpecular = stackLitMasterNode.m_EnergyConservingSpecular;
stackLitData.baseParametrization = stackLitMasterNode.m_BaseParametrization;
stackLitData.dualSpecularLobeParametrization = stackLitMasterNode.m_DualSpecularLobeParametrization;
stackLitData.anisotropy = stackLitMasterNode.m_Anisotropy;
stackLitData.coat = stackLitMasterNode.m_Coat;
stackLitData.coatNormal = stackLitMasterNode.m_CoatNormal;
stackLitData.dualSpecularLobe = stackLitMasterNode.m_DualSpecularLobe;
stackLitData.capHazinessWrtMetallic = stackLitMasterNode.m_CapHazinessWrtMetallic;
stackLitData.iridescence = stackLitMasterNode.m_Iridescence;
stackLitData.screenSpaceSpecularOcclusionBaseMode = (StackLitData.SpecularOcclusionBaseMode)stackLitMasterNode.m_ScreenSpaceSpecularOcclusionBaseMode;
stackLitData.dataBasedSpecularOcclusionBaseMode = (StackLitData.SpecularOcclusionBaseMode)stackLitMasterNode.m_DataBasedSpecularOcclusionBaseMode;
stackLitData.screenSpaceSpecularOcclusionAOConeSize = (StackLitData.SpecularOcclusionAOConeSize)stackLitMasterNode.m_ScreenSpaceSpecularOcclusionAOConeSize;
stackLitData.screenSpaceSpecularOcclusionAOConeDir = (StackLitData.SpecularOcclusionAOConeDir)stackLitMasterNode.m_ScreenSpaceSpecularOcclusionAOConeDir;
stackLitData.dataBasedSpecularOcclusionAOConeSize = (StackLitData.SpecularOcclusionAOConeSize)stackLitMasterNode.m_DataBasedSpecularOcclusionAOConeSize;
stackLitData.specularOcclusionConeFixupMethod = (StackLitData.SpecularOcclusionConeFixupMethod)stackLitMasterNode.m_SpecularOcclusionConeFixupMethod;
stackLitData.anisotropyForAreaLights = stackLitMasterNode.m_AnisotropyForAreaLights;
stackLitData.recomputeStackPerLight = stackLitMasterNode.m_RecomputeStackPerLight;
stackLitData.honorPerLightMinRoughness = stackLitMasterNode.m_HonorPerLightMinRoughness;
stackLitData.shadeBaseUsingRefractedAngles = stackLitMasterNode.m_ShadeBaseUsingRefractedAngles;
stackLitData.debug = stackLitMasterNode.m_Debug;
stackLitData.devMode = stackLitMasterNode.m_DevMode;
target.customEditorGUI = stackLitMasterNode.m_OverrideEnabled ? stackLitMasterNode.m_ShaderGUIOverride : "";
// Set blockmap
blockMap = new Dictionary<BlockFieldDescriptor, int>();
blockMap.Add(BlockFields.VertexDescription.Position, StackLitMasterNode1.PositionSlotId);
blockMap.Add(BlockFields.VertexDescription.Normal, StackLitMasterNode1.VertexNormalSlotId);
blockMap.Add(BlockFields.VertexDescription.Tangent, StackLitMasterNode1.VertexTangentSlotId);
// Handle mapping of Normal and Tangent block specifically
BlockFieldDescriptor normalBlock;
BlockFieldDescriptor tangentBlock;
switch (lightingData.normalDropOffSpace)
{
case NormalDropOffSpace.Object:
normalBlock = BlockFields.SurfaceDescription.NormalOS;
tangentBlock = HDBlockFields.SurfaceDescription.TangentOS;
break;
case NormalDropOffSpace.World:
normalBlock = BlockFields.SurfaceDescription.NormalWS;
tangentBlock = HDBlockFields.SurfaceDescription.TangentWS;
break;
default:
normalBlock = BlockFields.SurfaceDescription.NormalTS;
tangentBlock = HDBlockFields.SurfaceDescription.TangentTS;
break;
}
blockMap.Add(normalBlock, StackLitMasterNode1.NormalSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.BentNormal, StackLitMasterNode1.BentNormalSlotId);
blockMap.Add(tangentBlock, StackLitMasterNode1.TangentSlotId);
blockMap.Add(BlockFields.SurfaceDescription.BaseColor, StackLitMasterNode1.BaseColorSlotId);
if (stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic)
{
blockMap.Add(BlockFields.SurfaceDescription.Metallic, StackLitMasterNode1.MetallicSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.DielectricIor, StackLitMasterNode1.DielectricIorSlotId);
}
else if (stackLitData.baseParametrization == StackLit.BaseParametrization.SpecularColor)
{
blockMap.Add(BlockFields.SurfaceDescription.Specular, StackLitMasterNode1.SpecularColorSlotId);
}
blockMap.Add(BlockFields.SurfaceDescription.Smoothness, StackLitMasterNode1.SmoothnessASlotId);
if (stackLitData.anisotropy)
{
blockMap.Add(HDBlockFields.SurfaceDescription.Anisotropy, StackLitMasterNode1.AnisotropyASlotId);
}
blockMap.Add(BlockFields.SurfaceDescription.Occlusion, StackLitMasterNode1.AmbientOcclusionSlotId);
if (stackLitData.dataBasedSpecularOcclusionBaseMode == StackLitData.SpecularOcclusionBaseMode.Custom)
{
blockMap.Add(HDBlockFields.SurfaceDescription.SpecularOcclusion, StackLitMasterNode1.SpecularOcclusionSlotId);
}
if (SpecularOcclusionUsesBentNormal(stackLitData) && stackLitData.specularOcclusionConeFixupMethod != StackLitData.SpecularOcclusionConeFixupMethod.Off)
{
blockMap.Add(HDBlockFields.SurfaceDescription.SOFixupVisibilityRatioThreshold, StackLitMasterNode1.SOFixupVisibilityRatioThresholdSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.SOFixupStrengthFactor, StackLitMasterNode1.SOFixupStrengthFactorSlotId);
if (SpecularOcclusionConeFixupMethodModifiesRoughness(stackLitData.specularOcclusionConeFixupMethod))
{
blockMap.Add(HDBlockFields.SurfaceDescription.SOFixupMaxAddedRoughness, StackLitMasterNode1.SOFixupMaxAddedRoughnessSlotId);
}
}
if (stackLitData.coat)
{
blockMap.Add(BlockFields.SurfaceDescription.CoatSmoothness, StackLitMasterNode1.CoatSmoothnessSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.CoatIor, StackLitMasterNode1.CoatIorSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.CoatThickness, StackLitMasterNode1.CoatThicknessSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.CoatExtinction, StackLitMasterNode1.CoatExtinctionSlotId);
if (stackLitData.coatNormal)
{
blockMap.Add(HDBlockFields.SurfaceDescription.CoatNormalTS, StackLitMasterNode1.CoatNormalSlotId);
}
blockMap.Add(BlockFields.SurfaceDescription.CoatMask, StackLitMasterNode1.CoatMaskSlotId);
}
if (stackLitData.dualSpecularLobe)
{
if (stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.Direct)
{
blockMap.Add(HDBlockFields.SurfaceDescription.SmoothnessB, StackLitMasterNode1.SmoothnessBSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.LobeMix, StackLitMasterNode1.LobeMixSlotId);
}
else if (stackLitData.dualSpecularLobeParametrization == StackLit.DualSpecularLobeParametrization.HazyGloss)
{
blockMap.Add(HDBlockFields.SurfaceDescription.Haziness, StackLitMasterNode1.HazinessSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.HazeExtent, StackLitMasterNode1.HazeExtentSlotId);
if (stackLitData.capHazinessWrtMetallic && stackLitData.baseParametrization == StackLit.BaseParametrization.BaseMetallic) // the later should be an assert really
{
blockMap.Add(HDBlockFields.SurfaceDescription.HazyGlossMaxDielectricF0, StackLitMasterNode1.HazyGlossMaxDielectricF0SlotId);
}
}
if (stackLitData.anisotropy)
{
blockMap.Add(HDBlockFields.SurfaceDescription.AnisotropyB, StackLitMasterNode1.AnisotropyBSlotId);
}
}
if (stackLitData.iridescence)
{
blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceMask, StackLitMasterNode1.IridescenceMaskSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceThickness, StackLitMasterNode1.IridescenceThicknessSlotId);
if (stackLitData.coat)
{
blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIR, StackLitMasterNode1.IridescenceCoatFixupTIRSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.IridescenceCoatFixupTIRClamp, StackLitMasterNode1.IridescenceCoatFixupTIRClampSlotId);
}
}
if (stackLitData.subsurfaceScattering)
{
blockMap.Add(HDBlockFields.SurfaceDescription.SubsurfaceMask, StackLitMasterNode1.SubsurfaceMaskSlotId);
}
if (stackLitData.transmission)
{
blockMap.Add(HDBlockFields.SurfaceDescription.Thickness, StackLitMasterNode1.ThicknessSlotId);
}
if (stackLitData.subsurfaceScattering || stackLitData.transmission)
{
blockMap.Add(HDBlockFields.SurfaceDescription.DiffusionProfileHash, StackLitMasterNode1.DiffusionProfileHashSlotId);
}
blockMap.Add(BlockFields.SurfaceDescription.Alpha, StackLitMasterNode1.AlphaSlotId);
if (systemData.alphaTest)
{
blockMap.Add(BlockFields.SurfaceDescription.AlphaClipThreshold, StackLitMasterNode1.AlphaClipThresholdSlotId);
}
blockMap.Add(BlockFields.SurfaceDescription.Emission, StackLitMasterNode1.EmissionSlotId);
if (systemData.surfaceType == SurfaceType.Transparent && builtinData.distortion)
{
blockMap.Add(HDBlockFields.SurfaceDescription.Distortion, StackLitMasterNode1.DistortionSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.DistortionBlur, StackLitMasterNode1.DistortionBlurSlotId);
}
if (lightingData.specularAA)
{
blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAScreenSpaceVariance, StackLitMasterNode1.SpecularAAScreenSpaceVarianceSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.SpecularAAThreshold, StackLitMasterNode1.SpecularAAThresholdSlotId);
}
if (lightingData.overrideBakedGI)
{
blockMap.Add(HDBlockFields.SurfaceDescription.BakedGI, StackLitMasterNode1.LightingSlotId);
blockMap.Add(HDBlockFields.SurfaceDescription.BakedBackGI, StackLitMasterNode1.BackLightingSlotId);
}
if (builtinData.depthOffset)
{
blockMap.Add(HDBlockFields.SurfaceDescription.DepthOffset, StackLitMasterNode1.DepthOffsetSlotId);
}
return true;
}
}
}
| 59.236 | 181 | 0.719292 | [
"MIT"
] | ACBGZM/JasonMaToonRenderPipeline | Packages/com.unity.render-pipelines.high-definition@10.5.0/Editor/Material/StackLit/ShaderGraph/StackLitSubTarget.Migration.cs | 14,809 | C# |
using System.Collections.Concurrent;
using System.Net.WebSockets;
using snake_server.user;
namespace snake_server.websocket
{
public class SocketHandler
{
private static readonly int ErrorRetryCounts = 5;
private static readonly ConcurrentDictionary<string, ChatRoom> Rooms = new ConcurrentDictionary<string, ChatRoom>();
private static readonly ConcurrentDictionary<string, User> Users = new ConcurrentDictionary<string, User>();
public static void HandleProtocol(WebSocket socket, Protocol protocol)
{
switch (protocol.Type)
{
case Protocol.Types.ProtocolType.Chat:
break;
case Protocol.Types.ProtocolType.CreateRoom:
_handleCreateRoom(socket, protocol);
break;
case Protocol.Types.ProtocolType.GameBegin:
break;
case Protocol.Types.ProtocolType.GameEnd:
break;
case Protocol.Types.ProtocolType.JoinRoom:
_handleJoinRoom(socket, protocol);
break;
case Protocol.Types.ProtocolType.LeaveRoom:
break;
case Protocol.Types.ProtocolType.Login:
break;
case Protocol.Types.ProtocolType.Paint:
break;
}
}
private static bool _hasUser(string key)
{
return Users.ContainsKey(key);
}
private static bool _hasRoom(string key)
{
return Rooms.ContainsKey(key);
}
/// <summary>
/// 创建房间
/// </summary>
/// <param name="socket">连接的websocket</param>
/// <param name="protocol">解析后的协议</param>
private static void _handleCreateRoom(WebSocket socket, Protocol protocol)
{
var user = new User(
protocol.Key,
protocol.Name,
socket,
0);
ChatRoom room;
if (_hasRoom(user.Key))
{
Rooms.TryGetValue(user.Key, out room);
}
else
{
room = new ChatRoom(user.Key);
}
if (room.IsFull())
{
// 房间已经满了
return;
}
room.AddUser(user);
}
/// <summary>
/// 加入房间
/// </summary>
/// <param name="socket">连接的websocket</param>
/// <param name="protocol">解析后的协议</param>
private static void _handleJoinRoom(WebSocket socket, Protocol protocol)
{
User user;
if (_hasUser(protocol.Key))
{
Users.TryGetValue(protocol.Key, out user);
}
else
{
user = new User(
protocol.Key,
protocol.Name,
socket,
-1);
}
ChatRoom room;
if (_hasRoom(protocol.RoomKey))
{
Rooms.TryGetValue(protocol.RoomKey, out room);
}
else
{
// 房间还没有被创建,现在创建
room = new ChatRoom(protocol.RoomKey);
}
room.AddUser(user);
}
}
} | 31.107143 | 124 | 0.470723 | [
"Apache-2.0"
] | tornodo/guess_server | snake_server/websocket/SocketHandler.cs | 3,576 | C# |
namespace MassTransit.RabbitMqTransport.Specifications
{
using System.Collections.Generic;
using GreenPipes;
using Pipeline;
public class DelayedExchangeRedeliveryPipeSpecification<TMessage> :
IPipeSpecification<ConsumeContext<TMessage>>
where TMessage : class
{
public void Apply(IPipeBuilder<ConsumeContext<TMessage>> builder)
{
builder.AddFilter(new DelayedExchangeMessageRedeliveryFilter<TMessage>());
}
public IEnumerable<ValidationResult> Validate()
{
yield break;
}
}
}
| 26.73913 | 87 | 0.64878 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/Transports/MassTransit.RabbitMqTransport/Configuration/Specifications/DelayedExchangeRedeliveryPipeSpecification.cs | 617 | C# |
using System.Collections.Generic;
using System.Linq;
using JetBrains.DocumentManagers;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Tests.TestFramework;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TextControl;
using JetBrains.Util.Dotnet.TargetFrameworkIds;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Tests.Unity.AsmDef.Feature.Services.Refactorings
{
[TestUnity]
[TestFileExtension(".asmdef")]
public class AsmDefRenameTests : RenameTestBase
{
protected override string RelativeTestDataPath => @"AsmDef\Refactorings\Rename";
[Test] public void TestSingleFile() { DoNamedTest2(); }
[Test] public void TestCrossFileRename() { DoNamedTest2("CrossFileRename_SecondProject.asmdef"); }
[Test] public void TestRenameFile() { DoNamedTest2(); }
[Test] public void TestGuidReference() { DoNamedTest2("GuidReference.asmdef.meta", "GuidReference_SecondProject.asmdef"); }
protected override void AdditionalTestChecks(ITextControl textControl, IProject project)
{
var solution = project.GetSolution();
foreach (var topLevelProject in solution.GetTopLevelProjects())
{
if (topLevelProject.IsProjectFromUserView() && !Equals(topLevelProject, project))
{
foreach (var projectFile in topLevelProject.GetSubItems().OfType<IProjectFile>())
{
ExecuteWithGold(projectFile, writer =>
{
var document = projectFile.GetDocument();
writer.Write(document.GetText());
});
}
// TODO: Should really recurse into child folders, but not used by these tests
}
}
}
// Sadly, we can't just use DoTestSolution(fileSet, fileSet) here, CodeCompletionTestBase.DoTestSolution(files)
// sets up a CaretPositionsProcessor and processes files. Split the file sets here instead
protected override TestSolutionConfiguration CreateSolutionConfiguration(
ICollection<KeyValuePair<TargetFrameworkId, IEnumerable<string>>> referencedLibraries,
IEnumerable<string> fileSet)
{
var files = fileSet.ToList();
var mainFileSet = files.Where(f => !f.Contains("_SecondProject"));
var secondaryFileSet = files.Where(f => f.Contains("_SecondProject"));
return base.CreateSolutionConfiguration(referencedLibraries,
CreateProjectFileSets(mainFileSet, secondaryFileSet));
}
}
} | 46.344828 | 131 | 0.65253 | [
"Apache-2.0"
] | SirDuke/resharper-unity | resharper/resharper-unity/test/src/Unity.Tests/Unity/AsmDef/Feature/Services/Refactorings/AsmDefRenameTests.cs | 2,690 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Elsa.Dashboard.Areas.Elsa.ViewModels
{
public class WorkflowDefinitionListViewModel
{
public IList<IGrouping<string, WorkflowDefinitionListItemModel>> WorkflowDefinitions { get; set; }
}
} | 27.2 | 106 | 0.768382 | [
"BSD-3-Clause"
] | 1000sprites/elsa-core | src/dashboard/Elsa.Dashboard/Areas/Elsa/ViewModels/WorkflowDefinitionListViewModel.cs | 272 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace PuzzleGraph
{
class XmlFont
{
private Font font_ = SystemFonts.DefaultFont;
public XmlFont() { }
public XmlFont(Font font) { font_ = font; }
public static implicit operator Font(XmlFont x)
{
return x.font_;
}
public static implicit operator XmlFont(Font font)
{
return new XmlFont(font);
}
// Code from https://stackoverflow.com/questions/19263202/how-to-serialize-font
public static string FromFont(Font font)
{
return font.FontFamily.Name
+ ":" + font.Size
+ ":" + font.Style
+ ":" + font.Unit
+ ":" + font.GdiCharSet
+ ":" + font.GdiVerticalFont
;
}
public static Font ToFont(string value)
{
var parts = value.Split(':');
return new Font(
new FontFamily(parts[0]), // FontFamily.Name
float.Parse(parts[1]), // Size
EnumSerializationHelper.FromString<FontStyle>(parts[2]), // Style
EnumSerializationHelper.FromString<GraphicsUnit>(parts[3]), // Unit
byte.Parse(parts[4]), // GdiCharSet
bool.Parse(parts[5]) // GdiVerticalFont
);
}
[XmlText]
public string Default
{
get { return FromFont(font_); }
set { font_ = ToFont(value); }
}
}
[TypeConverter(typeof(EnumConverter))]
static public class EnumSerializationHelper
{
static public T FromString<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
}
}
| 30.112676 | 110 | 0.495323 | [
"MIT"
] | instr3/WitnessVisualizer | PuzzleGraph/XmlFont.cs | 2,140 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ResourceManager
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ProviderResourceTypesOperations operations.
/// </summary>
internal partial class ProviderResourceTypesOperations : IServiceOperations<ResourceManagementClient>, IProviderResourceTypesOperations
{
/// <summary>
/// Initializes a new instance of the ProviderResourceTypesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ProviderResourceTypesOperations(ResourceManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ResourceManagementClient
/// </summary>
public ResourceManagementClient Client { get; private set; }
/// <summary>
/// List the resource types for a specified resource provider.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='expand'>
/// The $expand query parameter. For example, to include property aliases in
/// response, use $expand=resourceTypes/aliases.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ProviderResourceTypeListResult>> ListWithHttpMessagesAsync(string resourceProviderNamespace, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceProviderNamespace == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceProviderNamespace");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("expand", expand);
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/resourceTypes").ToString();
_url = _url.Replace("{resourceProviderNamespace}", System.Uri.EscapeDataString(resourceProviderNamespace));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ProviderResourceTypeListResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ProviderResourceTypeListResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 43.908367 | 295 | 0.577262 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/resources/Microsoft.Azure.Management.Resource/src/Generated/ProviderResourceTypesOperations.cs | 11,021 | 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 ec2-2015-04-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.EC2.Model
{
/// <summary>
/// Container for the parameters to the UnmonitorInstances operation.
/// Disables monitoring for a running instance. For more information about monitoring
/// instances, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html">Monitoring
/// Your Instances and Volumes</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
/// </summary>
public partial class UnmonitorInstancesRequest : AmazonEC2Request
{
private List<string> _instanceIds = new List<string>();
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public UnmonitorInstancesRequest() { }
/// <summary>
/// Instantiates UnmonitorInstancesRequest with the parameterized properties
/// </summary>
/// <param name="instanceIds">One or more instance IDs.</param>
public UnmonitorInstancesRequest(List<string> instanceIds)
{
_instanceIds = instanceIds;
}
/// <summary>
/// Gets and sets the property InstanceIds.
/// <para>
/// One or more instance IDs.
/// </para>
/// </summary>
public List<string> InstanceIds
{
get { return this._instanceIds; }
set { this._instanceIds = value; }
}
// Check to see if InstanceIds property is set
internal bool IsSetInstanceIds()
{
return this._instanceIds != null && this._instanceIds.Count > 0;
}
}
} | 34.479452 | 116 | 0.658323 | [
"Apache-2.0"
] | jasoncwik/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/UnmonitorInstancesRequest.cs | 2,517 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox;
namespace QuadTree
{
//This is the class I am using to generate noise values.
public class SimpleSlerpNoise
{
int seed;
int octaves;
int[] valuesPerGrid;
float[] percentagesPerOctave;
public SimpleSlerpNoise( int seed, int[] valuesPerGrid, float[] percentagesPerOctave)
{
if ( valuesPerGrid.Length != percentagesPerOctave.Length )
{
throw new Exception( "Array sizes must be equal" );
}
this.seed = seed;
this.octaves = valuesPerGrid.Length;
this.valuesPerGrid = valuesPerGrid;
this.percentagesPerOctave = percentagesPerOctave;
}
public float getValue(int x, int y)
{
float accumulation = 0;
for ( int octaveNum = 0; octaveNum < octaves; octaveNum++ )
{
int octaveValuesPerGrid = valuesPerGrid[octaveNum];
int gridX = x / octaveValuesPerGrid;
int gridY = y / octaveValuesPerGrid;
int val00 = getGridValue( gridX, gridY );
int val10 = getGridValue( gridX + 1, gridY );
int val01 = getGridValue( gridX, gridY + 1 );
int val11 = getGridValue( gridX + 1, gridY + 1 );
float offsetX = sCurve( (x - (gridX * octaveValuesPerGrid)) / (float)octaveValuesPerGrid );
float offsetY = sCurve( (y - (gridY * octaveValuesPerGrid)) / (float)octaveValuesPerGrid );
float inverseOffsetX = 1 - offsetX;
float inverseOffsetY = 1 - offsetY;
float val0 = (val00 * inverseOffsetX) + (val10 * offsetX);
float val1 = (val01 * inverseOffsetX) + (val11 * offsetX);
float val = (val0 * inverseOffsetY) + (val1 * offsetY);
//This value will be between [-2147m, 2147m]
val /= int.MaxValue;
//Convert to [-1,1]
accumulation += val * percentagesPerOctave[octaveNum];
}
return accumulation;
}
private int getGridValue(int gridX, int gridY)
{
return lcg( getPositionalSeed( gridX, gridY ) );
}
public int lcg( int seed )
{
//Random prime numbers seem to work
//timer.Start();
int val = lcg( 102191, 0, 3, seed );
//timer.Stop();
return val;
}
//Linear congruent generator
public int lcg( int a, int c, int n, int n0 )
{
if ( n == 0 )
{
return n0;
}
else if(c == 0)
{
//According to one site (which I need to come back and grab)
//this formula can be used to collapse the recursive structure
//as long as c is 0. Based on some tests it seems to be
//random enough for these purposes.
int an = 1;
for(int i = 0; i < n; i++ )
{
an *= a;
}
return an * n0;
}
else
{
return ((a * lcg( a, c, n - 1, n0 )) + c);
}
}
//For inputs between x=[0,1] returns a smooth curve between y=[0,1]
//With x=0 and x=1 having slopes of zero
public float sCurve( float x )
{
return (1 * ((x * (x * 6.0f - 15.0f) + 10.0f) * x * x * x));
}
//Good for getting different values for each position,
//but positions that are close on some axis get similar values,
//so for randomness the LCG must be used as well. with this as a seed.
private int getPositionalSeed( int x, int y )
{
/*
//Used to be an FNV-1 Hash, seems like this new system is fine.
//It will absolutely repeat eventually, but oh well.
//Multiplications were very slow.
timer.Start();
uint h = 2166136261;
h *= 16777619;
h ^= (uint)seed;
h *= 16777619;
h ^= (uint)x;
h *= 16777619;
h ^= (uint)y;
h *= 16777619;
h ^= (uint)z;
timer.Stop();
return (int)h;
*/
uint h = 2166136261;
h ^= (uint)seed;
h ^= (uint) ((x << 0 ) | (x << (32 - 0 )));
h ^= (uint) ((y << 16) | (y << (32 - 16)));
return (int)h;
}
}
}
| 26.948905 | 95 | 0.622156 | [
"MIT"
] | rugg0064/sbox-quadtree | code/SimpleSlerpNoise.cs | 3,694 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Utilities.Common
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using AutoMapper;
using Management.Compute;
using Management;
using Management.Storage;
using ServiceManagement;
using Properties;
using WindowsAzure;
using Management.Network;
using Management.Network.Models;
using System.Threading;
public abstract class ServiceManagementBaseCmdlet : CloudBaseCmdlet<IServiceManagement>
{
private Lazy<Runspace> runspace;
protected ServiceManagementBaseCmdlet()
{
runspace = new Lazy<Runspace>(() => {
var localRunspace = RunspaceFactory.CreateRunspace(this.Host);
localRunspace.Open();
return localRunspace;
});
client = new Lazy<ManagementClient>(CreateClient);
computeClient = new Lazy<ComputeManagementClient>(CreateComputeClient);
storageClient = new Lazy<StorageManagementClient>(CreateStorageClient);
networkClient = new Lazy<NetworkManagementClient>(CreateNetworkClient);
}
public ManagementClient CreateClient()
{
return this.CurrentSubscription.CreateClient<ManagementClient>();
}
public ComputeManagementClient CreateComputeClient()
{
return this.CurrentSubscription.CreateClient<ComputeManagementClient>();
}
public StorageManagementClient CreateStorageClient()
{
return this.CurrentSubscription.CreateClient<StorageManagementClient>();
}
public NetworkManagementClient CreateNetworkClient()
{
return this.CurrentSubscription.CreateClient<NetworkManagementClient>();
}
private void LogDebug(string message)
{
// lock (runspaceLock)
// {
// using (var ps = PowerShell.Create())
// {
// ps.Runspace = runspace.Value;
// ps.AddCommand("Write-Debug");
// ps.AddParameter("Message", message);
// ps.AddParameter("Debug");
// ps.Invoke();
// }
// }
}
private Lazy<ManagementClient> client;
public ManagementClient ManagementClient
{
get { return client.Value; }
}
private Lazy<ComputeManagementClient> computeClient;
public ComputeManagementClient ComputeClient
{
get { return computeClient.Value; }
}
private Lazy<StorageManagementClient> storageClient;
public StorageManagementClient StorageClient
{
get { return storageClient.Value; }
}
private Lazy<NetworkManagementClient> networkClient;
public NetworkManagementClient NetworkClient
{
get { return networkClient.Value; }
}
protected override void InitChannelCurrentSubscription(bool force)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposing the client would also dispose the channel we are returning.")]
protected override IServiceManagement CreateChannel()
{
// If ShareChannel is set by a unit test, use the same channel that
// was passed into out constructor. This allows the test to submit
// a mock that we use for all network calls.
if (ShareChannel)
{
return Channel;
}
var messageInspectors = new List<IClientMessageInspector>
{
new ServiceManagementClientOutputMessageInspector(),
new HttpRestMessageInspector(this.WriteDebug)
};
var clientOptions = new ServiceManagementClientOptions(null, null, null, 0, RetryPolicy.NoRetryPolicy, ServiceManagementClientOptions.DefaultOptions.WaitTimeForOperationToComplete, messageInspectors);
var smClient = new ServiceManagementClient(new Uri(this.ServiceEndpoint), CurrentSubscription.SubscriptionId, CurrentSubscription.Certificate, clientOptions);
Type serviceManagementClientType = typeof(ServiceManagementClient);
PropertyInfo propertyInfo = serviceManagementClientType.GetProperty("SyncService", BindingFlags.Instance | BindingFlags.NonPublic);
var syncService = (IServiceManagement)propertyInfo.GetValue(smClient, null);
return syncService;
}
/// <summary>
/// Invoke the given operation within an OperationContextScope if the
/// channel supports it.
/// </summary>
/// <param name="action">The action to invoke.</param>
protected override void InvokeInOperationContext(Action action)
{
IContextChannel contextChannel = ToContextChannel();
if (contextChannel != null)
{
using (new OperationContextScope(contextChannel))
{
action();
}
}
else
{
action();
}
}
protected virtual IContextChannel ToContextChannel()
{
try
{
return Channel.ToContextChannel();
}
catch (Exception)
{
return null;
}
}
protected void ExecuteClientAction(object input, string operationDescription, Action<string> action)
{
Operation operation = null;
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionBeginOperation, operationDescription));
RetryCall(action);
operation = GetOperation();
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionCompletedOperation, operationDescription));
if (operation != null)
{
var context = new ManagementOperationContext
{
OperationDescription = operationDescription,
OperationId = operation.OperationTrackingId,
OperationStatus = operation.Status
};
WriteObject(context, true);
}
}
protected void ExecuteClientActionInOCS(object input, string operationDescription, Action<string> action)
{
IContextChannel contextChannel = null;
try
{
contextChannel = Channel.ToContextChannel();
}
catch (Exception)
{
// Do nothing, proceed.
}
if (contextChannel != null)
{
object context = null;
using (new OperationContextScope(contextChannel))
{
Operation operation = null;
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionInOCSBeginOperation, operationDescription));
try
{
RetryCall(action);
operation = GetOperation();
}
catch (ServiceManagementClientException ex)
{
WriteExceptionDetails(ex);
}
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionInOCSCompletedOperation, operationDescription));
if (operation != null)
{
context = new ManagementOperationContext
{
OperationDescription = operationDescription,
OperationId = operation.OperationTrackingId,
OperationStatus = operation.Status
};
}
}
if (context != null)
{
WriteObject(context, true);
}
}
else
{
RetryCall(action);
}
}
protected virtual void WriteExceptionDetails(Exception exception)
{
if (CommandRuntime != null)
{
WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
}
}
protected OperationStatusResponse GetOperationStatusNewSM(string operationId)
{
OperationStatusResponse response = this.ManagementClient.GetOperationStatus(operationId);
return response;
}
protected OperationStatusResponse GetOperationNewSM(string operationId)
{
OperationStatusResponse operation = null;
try
{
operation = GetOperationStatusNewSM(operationId);
if (operation.Status == OperationStatus.Failed)
{
var errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", operation.Status, operation.Error.Message);
var exception = new Exception(errorMessage);
WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
}
}
catch (AggregateException ex)
{
WriteExceptionDetails(ex);
}
return operation;
}
//TODO: Input argument is not used and should probably be removed.
protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action, Func<OperationStatusResponse, TResult, object> contextFactory) where TResult : OperationResponse
{
ExecuteClientActionNewSM(input, operationDescription, action, null, contextFactory);
}
protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action, Func<string, string, OperationStatusResponse> waitOperation, Func<OperationStatusResponse, TResult, object> contextFactory) where TResult : OperationResponse
{
TResult result = null;
OperationStatusResponse operation = null;
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionInOCSBeginOperation, operationDescription));
try
{
try
{
result = action();
}
catch (CloudException ex)
{
WriteExceptionDetails(ex);
}
if (waitOperation == null)
{
operation = result == null ? null : GetOperationNewSM(result.RequestId);
}
else
{
operation = result == null ? null : waitOperation(result.RequestId, operationDescription);
}
}
catch (AggregateException ex)
{
if (ex.InnerException is CloudException)
{
WriteExceptionDetails(ex.InnerException);
}
else
{
WriteExceptionDetails(ex);
}
}
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionInOCSCompletedOperation, operationDescription));
if (result != null)
{
var context = contextFactory(operation, result);
if (context != null)
{
WriteObject(context, true);
}
}
}
protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action) where TResult : OperationResponse
{
this.ExecuteClientActionNewSM(input, operationDescription, action, (s, response) => this.ContextFactory<OperationResponse, ManagementOperationContext>(response, s));
}
protected void ExecuteClientActionNewSM<TResult>(object input, string operationDescription, Func<TResult> action, Func<string, string, OperationStatusResponse> waitOperation) where TResult : OperationResponse
{
this.ExecuteClientActionNewSM(input, operationDescription, action, waitOperation, (s, response) => this.ContextFactory<OperationResponse, ManagementOperationContext>(response, s));
}
protected OperationStatusResponse WaitForNewGatewayOperation(string operationId, string opdesc)
{
try
{
var opStatus = this.NetworkClient.Gateways.GetOperationStatus(operationId);
var activityId = new Random().Next(1, 999999);
var progress = new ProgressRecord(activityId, opdesc, Resources.GatewayOperationStatus + opStatus);
while (opStatus.Status != GatewayOperationStatus.Successful && opStatus.Status != GatewayOperationStatus.Failed)
{
WriteProgress(progress);
Thread.Sleep(1 * 1000);
opStatus = this.NetworkClient.Gateways.GetOperationStatus(operationId);
}
if (opStatus.Status == GatewayOperationStatus.Failed)
{
var errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", opStatus.Status, opStatus.Error.Message);
var exception = new Exception(errorMessage);
WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
}
}
catch (CommunicationException ex)
{
WriteErrorDetails(ex);
}
return GetOperationNewSM(operationId);
}
protected void ExecuteClientActionInOCS<TResult>(object input, string operationDescription, Func<string, TResult> action, Func<Operation, TResult, object> contextFactory) where TResult : class
{
IContextChannel contextChannel = null;
try
{
contextChannel = Channel.ToContextChannel();
}
catch (Exception)
{
// Do nothing, proceed.
}
if (contextChannel != null)
{
object context = null;
using (new OperationContextScope(contextChannel))
{
TResult result = null;
Operation operation = null;
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionInOCSBeginOperation, operationDescription));
try
{
result = RetryCall(action);
operation = GetOperation();
}
catch (ServiceManagementClientException ex)
{
WriteExceptionDetails(ex);
}
WriteVerboseWithTimestamp(string.Format(Resources.ServiceManagementExecuteClientActionInOCSCompletedOperation, operationDescription));
if (result != null && operation != null)
{
context = contextFactory(operation, result);
}
}
if (context != null)
{
WriteObject(context, true);
}
}
else
{
TResult result = RetryCall(action);
if (result != null)
{
WriteObject(result, true);
}
}
}
protected Operation GetOperation()
{
Operation operation = null;
try
{
string operationId = RetrieveOperationId();
if (!string.IsNullOrEmpty(operationId))
{
operation = RetryCall(s => GetOperationStatus(this.CurrentSubscription.SubscriptionId, operationId));
if (string.Compare(operation.Status, OperationState.Failed, StringComparison.OrdinalIgnoreCase) == 0)
{
var errorMessage = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", operation.Status, operation.Error.Message);
var exception = new Exception(errorMessage);
WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
}
}
else
{
operation = new Operation
{
OperationTrackingId = string.Empty,
Status = OperationState.Failed
};
}
}
catch (ServiceManagementClientException ex)
{
WriteExceptionDetails(ex);
}
return operation;
}
protected override Operation GetOperationStatus(string subscriptionId, string operationId)
{
var channel = (IServiceManagement)Channel;
return channel.GetOperationStatus(subscriptionId, operationId);
}
protected T2 ContextFactory<T1, T2>(T1 source) where T2 : ManagementOperationContext
{
var context = Mapper.Map<T1, T2>(source);
context.OperationDescription = CommandRuntime.ToString();
return context;
}
protected T2 ContextFactory<T1, T2>(T1 source, OperationStatusResponse response) where T2 : ManagementOperationContext
{
var context = Mapper.Map<T1, T2>(source);
context = Mapper.Map(response, context);
context.OperationDescription = CommandRuntime.ToString();
return context;
}
protected T2 ContextFactory<T1, T2>(T1 source, T2 destination) where T2 : ManagementOperationContext
{
var context = Mapper.Map(source, destination);
return context;
}
}
} | 39.214145 | 280 | 0.553607 | [
"MIT"
] | Milstein/azure-sdk-tools | WindowsAzurePowershell/src/Commands.Utilities/Common/ServiceManagementBaseCmdlet.cs | 19,452 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core;
namespace Azure.DigitalTwins.Core
{
/// <inheritdoc />
[CodeGenModel("EventRoutesListOptions")]
public partial class GetDigitalTwinsEventRoutesOptions
{
// This class declaration changes the namespace and the class name; do not remove.
/// <summary> Identifies the request in a distributed tracing system. </summary>
[CodeGenMember("Traceparent")]
public string TraceParent { get; set; }
/// <summary> Provides vendor-specific trace identification information and is a companion to TraceParent. </summary>
[CodeGenMember("Tracestate")]
public string TraceState { get; set; }
}
}
| 33.652174 | 125 | 0.692506 | [
"MIT"
] | Penguinwizzard/azure-sdk-for-net | sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/Models/GetDigitalTwinsEventRoutesOptions.cs | 776 | C# |
//
// ToolStripStatusLabelTests.cs
//
// 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.
//
// Copyright (c) 2006 Jonathan Pobst
//
// Authors:
// Jonathan Pobst (monkey@jpobst.com)
//
#if NET_2_0
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Drawing;
using System.Windows.Forms;
namespace MonoTests.System.Windows.Forms
{
[TestFixture]
public class ToolStripStatusLabelTests : TestHelper
{
//[Test]
//public void Constructor ()
//{
// ToolStripLabel tsi = new ToolStripLabel ();
// Assert.AreEqual (Color.Red, tsi.ActiveLinkColor, "A1");
// Assert.AreEqual (false, tsi.CanSelect, "A2");
// Assert.AreEqual (false, tsi.IsLink, "A3");
// Assert.AreEqual (LinkBehavior.SystemDefault, tsi.LinkBehavior, "A4");
// Assert.AreEqual (Color.FromArgb (0,0,255), tsi.LinkColor, "A5");
// Assert.AreEqual (false, tsi.LinkVisited, "A6");
// Assert.AreEqual (Color.FromArgb (128, 0, 128), tsi.VisitedLinkColor, "A7");
// int count = 0;
// EventHandler oc = new EventHandler (delegate (object sender, EventArgs e) { count++; });
// Image i = new Bitmap (1,1);
// tsi = new ToolStripLabel (i);
// tsi.PerformClick();
// Assert.AreEqual (null, tsi.Text, "A8");
// Assert.AreSame (i, tsi.Image, "A9");
// Assert.AreEqual (false, tsi.IsLink, "A10");
// Assert.AreEqual (0, count, "A11");
// Assert.AreEqual (string.Empty, tsi.Name, "A12");
// tsi = new ToolStripLabel ("Text");
// tsi.PerformClick ();
// Assert.AreEqual ("Text", tsi.Text, "A13");
// Assert.AreSame (null, tsi.Image, "A14");
// Assert.AreEqual (false, tsi.IsLink, "A15");
// Assert.AreEqual (0, count, "A16");
// Assert.AreEqual (string.Empty, tsi.Name, "A17");
// tsi = new ToolStripLabel ("Text", i);
// tsi.PerformClick ();
// Assert.AreEqual ("Text", tsi.Text, "A18");
// Assert.AreSame (i, tsi.Image, "A19");
// Assert.AreEqual (false, tsi.IsLink, "A20");
// Assert.AreEqual (0, count, "A21");
// Assert.AreEqual (string.Empty, tsi.Name, "A22");
// tsi = new ToolStripLabel ("Text", i, true);
// tsi.PerformClick ();
// Assert.AreEqual ("Text", tsi.Text, "A23");
// Assert.AreSame (i, tsi.Image, "A24");
// Assert.AreEqual (true, tsi.IsLink, "A25");
// Assert.AreEqual (0, count, "A26");
// Assert.AreEqual (string.Empty, tsi.Name, "A27");
// tsi = new ToolStripLabel ("Text", i, true, oc);
// tsi.PerformClick ();
// Assert.AreEqual ("Text", tsi.Text, "A28");
// Assert.AreSame (i, tsi.Image, "A29");
// Assert.AreEqual (true, tsi.IsLink, "A30");
// Assert.AreEqual (1, count, "A31");
// Assert.AreEqual (string.Empty, tsi.Name, "A32");
// tsi = new ToolStripLabel ("Text", i, true, oc, "Name");
// tsi.PerformClick ();
// Assert.AreEqual ("Text", tsi.Text, "A33");
// Assert.AreSame (i, tsi.Image, "A34");
// Assert.AreEqual (true, tsi.IsLink, "A35");
// Assert.AreEqual (2, count, "A36");
// Assert.AreEqual ("Name", tsi.Name, "A37");
//}
[Test]
public void ProtectedProperties ()
{
ExposeProtectedProperties epp = new ExposeProtectedProperties ();
Assert.AreEqual (new Padding (0, 3, 0, 2), epp.DefaultMargin, "C3");
}
//[Test]
//public void PropertyActiveLinkColor ()
//{
// ToolStripLabel tsi = new ToolStripLabel ();
// tsi.ActiveLinkColor = Color.Green;
// Assert.AreEqual (Color.Green, tsi.ActiveLinkColor, "B1");
//}
//[Test]
//public void PropertyIsLink ()
//{
// ToolStripLabel tsi = new ToolStripLabel ();
// tsi.IsLink = true;
// Assert.AreEqual (true, tsi.IsLink, "B1");
//}
//[Test]
//public void PropertyLinkBehavior ()
//{
// ToolStripLabel tsi = new ToolStripLabel ();
// tsi.LinkBehavior = LinkBehavior.NeverUnderline;
// Assert.AreEqual (LinkBehavior.NeverUnderline, tsi.LinkBehavior, "B1");
//}
//[Test]
//public void PropertyLinkColor ()
//{
// ToolStripLabel tsi = new ToolStripLabel ();
// tsi.LinkColor = Color.Green;
// Assert.AreEqual (Color.Green, tsi.LinkColor, "B1");
//}
//[Test]
//public void PropertyLinkVisited ()
//{
// ToolStripLabel tsi = new ToolStripLabel ();
// tsi.LinkVisited = true;
// Assert.AreEqual (true, tsi.LinkVisited, "B1");
//}
//[Test]
//public void PropertyVisitedLinkColor ()
//{
// ToolStripLabel tsi = new ToolStripLabel ();
// tsi.VisitedLinkColor = Color.Green;
// Assert.AreEqual (Color.Green, tsi.VisitedLinkColor, "B1");
//}
//[Test]
//public void PropertyAnchorAndDocking ()
//{
// ToolStripItem ts = new NullToolStripItem ();
// ts.Anchor = AnchorStyles.Top | AnchorStyles.Bottom;
// Assert.AreEqual (AnchorStyles.Top | AnchorStyles.Bottom, ts.Anchor, "A1");
// Assert.AreEqual (DockStyle.None, ts.Dock, "A2");
// ts.Anchor = AnchorStyles.Left | AnchorStyles.Right;
// Assert.AreEqual (AnchorStyles.Left | AnchorStyles.Right, ts.Anchor, "A1");
// Assert.AreEqual (DockStyle.None, ts.Dock, "A2");
// ts.Dock = DockStyle.Left;
// Assert.AreEqual (AnchorStyles.Top | AnchorStyles.Left, ts.Anchor, "A1");
// Assert.AreEqual (DockStyle.Left, ts.Dock, "A2");
// ts.Dock = DockStyle.None;
// Assert.AreEqual (AnchorStyles.Top | AnchorStyles.Left, ts.Anchor, "A1");
// Assert.AreEqual (DockStyle.None, ts.Dock, "A2");
// ts.Dock = DockStyle.Top;
// Assert.AreEqual (AnchorStyles.Top | AnchorStyles.Left, ts.Anchor, "A1");
// Assert.AreEqual (DockStyle.Top, ts.Dock, "A2");
//}
private class ExposeProtectedProperties : ToolStripStatusLabel
{
public new Padding DefaultMargin { get { return base.DefaultMargin; } }
}
}
}
#endif | 35.922705 | 101 | 0.591044 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/Managed.Windows.Forms/Test/System.Windows.Forms/ToolStripStatusLabelTest.cs | 7,436 | C# |
using System.Threading.Tasks;
namespace AsyncConverter.Tests.Test.Data.FixReturnValueToTaskTests
{
public class MyClass
{
public async Task TestAsync()
{
await Task.Delay(1000).ConfigureAwait(false);
Method(5);
}
public void Method<T>(T i)
{
}
public Task MethodAsync<T>(T i) where T : MyClass
{
return Task.CompletedTask;
}
}
}
| 19.695652 | 66 | 0.554084 | [
"MIT"
] | charygao/AsyncConverter | AsyncConverter.Tests/Test/Data/Highlightings/CanBeUseAsyncMethod/GenericWithWhereOnMyClass.cs | 455 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NewSF64Toolkit
{
public partial class AboutControl : UserControl
{
public AboutControl()
{
InitializeComponent();
this.lblVersion.Text = string.Format("V.{0}.{1}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Major,
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Minor);
}
}
}
| 25.869565 | 137 | 0.690756 | [
"MIT"
] | ElatedEatrs/NewSF64Toolkit | NewSF64Toolkit/AboutControl.cs | 597 | C# |
namespace SimnOpt.Heuristics.Genetic
{
public interface IGaSolution
{
double Fitness { get; set; }
IGaSolution DeepClone();
}
}
| 15.363636 | 38 | 0.579882 | [
"MIT"
] | OpResCodes/SimulatedAnnealingHeuristic | src/SimnOpt.Heuristics/Genetic/IGaSolution.cs | 171 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2020 Jiang Yin. All rights reserved.
// Homepage: https://GameFramework.cn/
// Feedback: mailto:ellan@GameFramework.cn
//------------------------------------------------------------
namespace GX.Entity
{
internal sealed partial class EntityManager : GXModule, IEntityManager
{
/// <summary>
/// 实体状态。
/// </summary>
private enum EntityStatus : byte
{
Unknown = 0,
WillInit,
Inited,
WillShow,
Showed,
WillHide,
Hidden,
WillRecycle,
Recycled
}
}
}
| 25.689655 | 75 | 0.414765 | [
"MIT"
] | modi00012/GameFramework | GameFramework/Entity/EntityManager.EntityStatus.cs | 758 | C# |
namespace Cethleann.Structure.Table
{
public struct XLHeader
{
public ushort Magic { get; set; }
public ushort Version { get; set; }
public ushort FileSize { get; set; }
public ushort Types { get; set; }
public ushort Sets { get; set; }
public short Width { get; set; }
public short TableOffset { get; set; }
public short Unknown { get; set; }
}
}
| 28.333333 | 46 | 0.576471 | [
"MIT"
] | TGEnigma/Cethleann | Cethleann.Structure/Table/XLHeader.cs | 427 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Logging;
namespace Application.Common.Behaviours
{
/// <summary>
/// Behaviour used to log unhandled exceptions from the MediatR pipeline
/// (from all behaviours registered after this one), including commands and queries.
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public class UnhandledExceptionLoggingBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
#region Fields
private readonly ILogger<UnhandledExceptionLoggingBehaviour<TRequest, TResponse>> _logger;
#endregion
#region Constructors
public UnhandledExceptionLoggingBehaviour(ILogger<UnhandledExceptionLoggingBehaviour<TRequest, TResponse>> logger)
{
_logger = logger;
}
#endregion
#region IPipelineBehavior<TRequest, TResponse>
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
try
{
return await next();
}
catch (Exception ex)
{
string requestTypeFullName = typeof(TRequest).FullName;
_logger.LogError(ex, $"Unhandled exception when executing {requestTypeFullName}");
throw;
}
}
#endregion
}
} | 30.294118 | 138 | 0.642071 | [
"Apache-2.0"
] | BobMakhlin/XNews-backend | src/Application/Common/Behaviours/UnhandledExceptionLoggingBehaviour.cs | 1,545 | C# |
// <copyright file="Logger.cs" company="Hans Kesting">
// Copyright (c) Hans Kesting. All rights reserved.
// </copyright>
namespace PodcastDownloader.Logging
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// The logger (logging to console + a file).
/// </summary>
public static class Logger
{
private static readonly List<LogMessage> LogMessages = new List<LogMessage>();
private static readonly CancellationTokenSource CancellationTokenSource = new CancellationTokenSource();
private static readonly List<ILogTarget> LogTargets = new List<ILogTarget>();
private static Task outputTask;
private static TimeSpan Interval { get; } = TimeSpan.FromSeconds(2);
/// <summary>
/// Adds the specified message to the log.
/// </summary>
/// <param name="message">The message.</param>
public static void Log(LogMessage message)
{
lock (LogMessages)
{
LogMessages.Add(message);
}
}
/// <summary>
/// Adds the specified message to the log.
/// </summary>
/// <param name="severity">The severity of the message.</param>
/// <param name="category">The category.</param>
/// <param name="message">The message text.</param>
/// <param name="ex">The exception (if any).</param>
public static void Log(LogSeverity severity, string category, string message, Exception ex = null)
{
Log(new LogMessage(severity, category, message, ex));
}
/// <summary>
/// Adds the log target.
/// </summary>
/// <param name="target">The target.</param>
/// <exception cref="ArgumentNullException">target cannot be null.</exception>
public static void AddTarget(ILogTarget target)
{
LogTargets.Add(target ?? throw new ArgumentNullException(nameof(target)));
}
/// <summary>
/// Starts the logging to the logfile.
/// </summary>
public static void StartLogging()
{
// task needs to run in parallel, continuously
outputTask = Task.Run(ProcessLogQueue, CancellationTokenSource.Token);
}
/// <summary>
/// Stops the logging and flushes the queue.
/// </summary>
/// <returns>A Task.</returns>
public static async Task StopLogging()
{
try
{
CancellationTokenSource.Cancel();
await outputTask;
}
catch (OperationCanceledException)
{
// ignore
}
// flush
await ProcessBatch().ConfigureAwait(false);
}
private static async Task ProcessLogQueue()
{
while (!CancellationTokenSource.IsCancellationRequested)
{
await ProcessBatch().ConfigureAwait(false);
// Wait before writing the next batch
await Task.Delay(Interval, CancellationTokenSource.Token).ConfigureAwait(false);
}
}
/// <summary>
/// Processes one batch of messages.
/// </summary>
/// <returns>A Task.</returns>
private static async Task ProcessBatch()
{
var batch = new List<LogMessage>();
lock (LogMessages)
{
batch.AddRange(LogMessages);
LogMessages.Clear();
}
// Write the current batch out
if (batch.Any())
{
var tasks = LogTargets.Select(t => t.WriteBatchAsync(batch)).ToList();
await Task.WhenAll(tasks);
}
}
}
}
| 31.451613 | 112 | 0.552564 | [
"MIT"
] | hdkesting/PodcastDownloader | PodcastDownloader.Akka/Logging/Logger.cs | 3,902 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace Z3Data
{
public static class Global
{
public static CultureInfo culture = new CultureInfo("en-US");
public static void Say(string text)
{
Console.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + text);
}
}
}
| 22.894737 | 119 | 0.655172 | [
"MIT"
] | 0152la/z3test | ClusterExperiment/Z3Data/Global.cs | 437 | C# |
// %BANNER_BEGIN%
// ---------------------------------------------------------------------
// %COPYRIGHT_BEGIN%
//
// Copyright (c) 2019 Magic Leap, Inc. All Rights Reserved.
// Use of this file is governed by the Developer Agreement, located
// here: https://id.magicleap.com/terms/developer
//
// %COPYRIGHT_END%
// ---------------------------------------------------------------------
// %BANNER_END%
using System;
using System.Collections.Generic;
namespace UnityEngine.XR.MagicLeap
{
/// <summary>
/// Class to automatically handle connection/disconnection events of an input device. By default,
/// all device types are allowed but it could be modified through the inspector to limit which types to
/// allow. This class automatically handles the disconnection/reconnection of Control and MLA devices.
/// This class keeps track of all connected devices matching allowed types. If more than one allowed
/// device is connected, the first one connected is returned.
/// </summary>
[AddComponentMenu("XR/MagicLeap/Input/MLControllerConnectionHandlerBehavior")]
public sealed class MLControllerConnectionHandlerBehavior : MonoBehaviour
{
/// <summary>
/// Flags to determine which input devices to allow
/// </summary>
[Flags]
public enum DeviceTypesAllowed : int
{
MobileApp = 1 << 0,
ControllerLeft = 1 << 1,
ControllerRight = 1 << 2,
}
[SerializeField, MLBitMask(typeof(DeviceTypesAllowed)), Tooltip("Bitmask on which devices to allow.")]
private DeviceTypesAllowed _devicesAllowed = (DeviceTypesAllowed)~0;
private List<MLInput.Controller> _allowedConnectedDevices = new List<MLInput.Controller>();
/// <summary>
/// Getter for the first allowed connected device, could return null.
/// </summary>
public MLInput.Controller ConnectedController
{
get
{
return (_allowedConnectedDevices.Count == 0) ? null : _allowedConnectedDevices[0];
}
}
/// <summary>
/// Getter for devices allowed bitmask
/// </summary>
public DeviceTypesAllowed DevicesAllowed
{
get
{
return _devicesAllowed;
}
}
/// <summary>
/// Invoked when a valid controller has connected.
/// </summary>
public event Action<byte> OnControllerConnected = delegate { };
/// <summary>
/// Invoked when an invalid controller has disconnected.
/// </summary>
public event Action<byte> OnControllerDisconnected = delegate { };
/// <summary>
/// Starts the MLInput, initializes the first controller, and registers the connection handlers
/// </summary>
void Start()
{
if (_devicesAllowed == 0)
{
Debug.LogErrorFormat("Error: ControllerConnectionHandler._devicesAllowed is invalid, disabling script.");
enabled = false;
return;
}
bool requestCFUID = DevicesAllowed.HasFlag(DeviceTypesAllowed.ControllerLeft) ||
DevicesAllowed.HasFlag(DeviceTypesAllowed.ControllerRight);
#if PLATFORM_LUMIN
if (!MLInput.IsStarted)
{
MLInput.Configuration config = new MLInput.Configuration(requestCFUID,
MLInput.Configuration.DefaultTriggerDownThreshold,
MLInput.Configuration. DefaultTriggerUpThreshold);
MLResult result = MLInput.Start(config);
if (!result.IsOk)
{
Debug.LogErrorFormat("Error: ControllerConnectionHandler failed starting MLInput, disabling script. Reason: {0}", result);
enabled = false;
return;
}
}
MLInput.OnControllerConnected += HandleOnControllerConnected;
MLInput.OnControllerDisconnected += HandleOnControllerDisconnected;
#endif
GetAllowedInput();
}
/// <summary>
/// Unregisters the connection handlers and stops the MLInput
/// </summary>
void OnDestroy()
{
#if PLATFORM_LUMIN
if (MLInput.IsStarted)
{
MLInput.OnControllerDisconnected -= HandleOnControllerDisconnected;
MLInput.OnControllerConnected -= HandleOnControllerConnected;
MLInput.Stop();
}
#endif
}
/// <summary>
/// Fills allowed connected devices list with all the connected controllers matching
/// types set in _devicesAllowed.
/// </summary>
private void GetAllowedInput()
{
_allowedConnectedDevices.Clear();
#if PLATFORM_LUMIN
for (int i = 0; i < 2; ++i)
{
MLInput.Controller controller = MLInput.GetController(i);
if (IsDeviceAllowed(controller) && !_allowedConnectedDevices.Exists((device) => device.Id == controller.Id))
{
_allowedConnectedDevices.Add(controller);
}
}
#endif
}
/// <summary>
/// Checks if a controller exists, is connected, and is allowed.
/// </summary>
/// <param name="controller">The controller to be checked for</param>
/// <returns>True if the controller exists, is connected, and is allowed</returns>
private bool IsDeviceAllowed(MLInput.Controller controller)
{
#if PLATFORM_LUMIN
if (controller == null || !controller.Connected)
{
return false;
}
return (((_devicesAllowed & DeviceTypesAllowed.MobileApp) != 0 && controller.Type == MLInput.Controller.ControlType.MobileApp) ||
((_devicesAllowed & DeviceTypesAllowed.ControllerLeft) != 0 && controller.Type == MLInput.Controller.ControlType.Control && controller.Hand == MLInput.Hand.Left) ||
((_devicesAllowed & DeviceTypesAllowed.ControllerRight) != 0 && controller.Type == MLInput.Controller.ControlType.Control && controller.Hand == MLInput.Hand.Right));
#else
return false;
#endif
}
/// <summary>
/// Checks if there is a controller in the list. This method
/// does not check if the controller is of the allowed device type
/// since that's handled by the connection/disconnection handlers.
/// Should not be called from Awake() or OnEnable().
/// </summary>
/// <returns>True if the controller is ready for use, false otherwise</returns>
public bool IsControllerValid()
{
return (ConnectedController != null);
}
/// <summary>
/// Checks if controller list contains controller with input id.
/// This method does not check if the controller is of the allowed device
/// type since that's handled by the connection/disconnection handlers.
/// Should not be called from Awake() or OnEnable().
/// </summary>
/// <param name="controllerId"> Controller id to check against </param>
/// <returns>True if a controller is found, false otherwise</returns>
public bool IsControllerValid(byte controllerId)
{
#if PLATFORM_LUMIN
return _allowedConnectedDevices.Exists((device) => device.Id == controllerId);
#else
return false;
#endif
}
/// <summary>
/// Handles the event when a controller connects. If the connected controller
/// is valid, we add it to the _allowedConnectedDevices list.
/// </summary>
/// <param name="controllerId">The id of the controller.</param>
private void HandleOnControllerConnected(byte controllerId)
{
#if PLATFORM_LUMIN
MLInput.Controller newController = MLInput.GetController(controllerId);
if (IsDeviceAllowed(newController))
{
if(_allowedConnectedDevices.Exists((device) => device.Id == controllerId))
{
Debug.LogWarning(string.Format("Connected controller with id {0} already connected.", controllerId));
return;
}
_allowedConnectedDevices.Add(newController);
// Notify Listeners
if (OnControllerConnected != null)
{
OnControllerConnected.Invoke(controllerId);
}
}
#endif
}
/// <summary>
/// Handles the event when a controller disconnects. If the disconnected
/// controller happens to be in the _allowedConnectedDevices list, we
/// remove it from the list.
/// </summary>
/// <param name="controllerId">The id of the controller.</param>
private void HandleOnControllerDisconnected(byte controllerId)
{
#if PLATFORM_LUMIN
// Remove from the list of allowed devices.
int devicesRemoved = _allowedConnectedDevices.RemoveAll((device) => device.Id == controllerId);
// Notify Listeners of the disconnected device.
if (devicesRemoved > 0)
{
if (OnControllerDisconnected != null)
{
OnControllerDisconnected.Invoke(controllerId);
}
}
#endif
}
}
}
| 39.163347 | 181 | 0.571312 | [
"Apache-2.0"
] | kedarshashi/UnityTemplate | Assets/MagicLeap/Core/Scripts/Input/MLControllerConnectionHandlerBehavior.cs | 9,830 | C# |
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Definitions.Portuguese;
namespace Microsoft.Recognizers.Text.DateTime.Portuguese
{
public class PortugueseDurationParserConfiguration : BaseDateTimeOptionsConfiguration, IDurationParserConfiguration
{
public PortugueseDurationParserConfiguration(ICommonDateTimeParserConfiguration config)
: base(config)
{
CardinalExtractor = config.CardinalExtractor;
NumberParser = config.NumberParser;
DurationExtractor = new BaseDurationExtractor(new PortugueseDurationExtractorConfiguration(this), false);
NumberCombinedWithUnit = PortugueseDurationExtractorConfiguration.NumberCombinedWithUnit;
AnUnitRegex = PortugueseDurationExtractorConfiguration.AnUnitRegex;
DuringRegex = PortugueseDurationExtractorConfiguration.DuringRegex;
AllDateUnitRegex = PortugueseDurationExtractorConfiguration.AllRegex;
HalfDateUnitRegex = PortugueseDurationExtractorConfiguration.HalfRegex;
SuffixAndRegex = PortugueseDurationExtractorConfiguration.SuffixAndRegex;
UnitMap = config.UnitMap;
UnitValueMap = config.UnitValueMap;
DoubleNumbers = config.DoubleNumbers;
FollowedUnit = PortugueseDurationExtractorConfiguration.FollowedUnit;
ConjunctionRegex = PortugueseDurationExtractorConfiguration.ConjunctionRegex;
InexactNumberRegex = PortugueseDurationExtractorConfiguration.InexactNumberRegex;
InexactNumberUnitRegex = PortugueseDurationExtractorConfiguration.InexactNumberUnitRegex;
DurationUnitRegex = PortugueseDurationExtractorConfiguration.DurationUnitRegex;
SpecialNumberUnitRegex = PortugueseDurationExtractorConfiguration.SpecialNumberUnitRegex;
}
public IExtractor CardinalExtractor { get; }
public IParser NumberParser { get; }
public IExtractor DurationExtractor { get; }
public Regex NumberCombinedWithUnit { get; }
public Regex AnUnitRegex { get; }
public Regex DuringRegex { get; }
public Regex AllDateUnitRegex { get; }
public Regex HalfDateUnitRegex { get; }
public Regex SuffixAndRegex { get; }
public Regex FollowedUnit { get; }
public Regex ConjunctionRegex { get; }
public Regex InexactNumberRegex { get; }
public Regex InexactNumberUnitRegex { get; }
public Regex DurationUnitRegex { get; }
public Regex SpecialNumberUnitRegex { get; }
bool IDurationParserConfiguration.CheckBothBeforeAfter => DateTimeDefinitions.CheckBothBeforeAfter;
public IImmutableDictionary<string, string> UnitMap { get; }
public IImmutableDictionary<string, long> UnitValueMap { get; }
public IImmutableDictionary<string, double> DoubleNumbers { get; }
}
}
| 39.573333 | 119 | 0.733491 | [
"MIT"
] | tellarin/Recognizers-Text | .NET/Microsoft.Recognizers.Text.DateTime/Portuguese/Parsers/PortugueseDurationParserConfiguration.cs | 2,970 | C# |
namespace NetInterop.Routing
{
public interface IHeader
{
}
} | 13 | 29 | 0.615385 | [
"BSD-3-Clause"
] | davidbetz/netrouter | NetInterop.Routing/IHeader.cs | 78 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DocumentDB.Outputs
{
[OutputType]
public sealed class ApiPropertiesResponse
{
/// <summary>
/// Describes the ServerVersion of an a MongoDB account.
/// </summary>
public readonly string? ServerVersion;
[OutputConstructor]
private ApiPropertiesResponse(string? serverVersion)
{
ServerVersion = serverVersion;
}
}
}
| 26.357143 | 81 | 0.674797 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DocumentDB/Outputs/ApiPropertiesResponse.cs | 738 | C# |
using Xenko.Engine;
namespace MaterialShader
{
class MaterialShaderApp
{
static void Main(string[] args)
{
using (var game = new Game())
{
game.Run();
}
}
}
}
| 15.5 | 41 | 0.447581 | [
"MIT"
] | Aminator/xenko | samples/Graphics/MaterialShader/MaterialShader.Windows/MaterialShaderApp.cs | 248 | C# |
using System.Linq;
using System.Threading.Tasks;
using Android.Widget;
using Microsoft.Maui.DeviceTests.Stubs;
using Microsoft.Maui.Handlers;
using Xunit;
using SearchView = AndroidX.AppCompat.Widget.SearchView;
namespace Microsoft.Maui.DeviceTests
{
public partial class SearchBarHandlerTests
{
[Fact(DisplayName = "Horizontal TextAlignment Initializes Correctly")]
public async Task HorizontalTextAlignmentInitializesCorrectly()
{
var xplatHorizontalTextAlignment = TextAlignment.End;
var searchBarStub = new SearchBarStub()
{
Text = "Test",
HorizontalTextAlignment = xplatHorizontalTextAlignment
};
Android.Views.TextAlignment expectedValue = Android.Views.TextAlignment.ViewEnd;
var values = await GetValueAsync(searchBarStub, (handler) =>
{
return new
{
ViewValue = searchBarStub.HorizontalTextAlignment,
NativeViewValue = GetNativeTextAlignment(handler)
};
});
Assert.Equal(xplatHorizontalTextAlignment, values.ViewValue);
values.NativeViewValue.AssertHasFlag(expectedValue);
}
[Fact(DisplayName = "CharacterSpacing Initializes Correctly")]
public async Task CharacterSpacingInitializesCorrectly()
{
var xplatCharacterSpacing = 4;
var searchBar = new SearchBarStub()
{
CharacterSpacing = xplatCharacterSpacing,
Text = "Test"
};
float expectedValue = searchBar.CharacterSpacing.ToEm();
var values = await GetValueAsync(searchBar, (handler) =>
{
return new
{
ViewValue = searchBar.CharacterSpacing,
NativeViewValue = GetNativeCharacterSpacing(handler)
};
});
Assert.Equal(xplatCharacterSpacing, values.ViewValue);
Assert.Equal(expectedValue, values.NativeViewValue, EmCoefficientPrecision);
}
SearchView GetNativeSearchBar(SearchBarHandler searchBarHandler) =>
(SearchView)searchBarHandler.NativeView;
string GetNativeText(SearchBarHandler searchBarHandler) =>
GetNativeSearchBar(searchBarHandler).Query;
string GetNativePlaceholder(SearchBarHandler searchBarHandler) =>
GetNativeSearchBar(searchBarHandler).QueryHint;
double GetNativeCharacterSpacing(SearchBarHandler searchBarHandler)
{
var searchView = GetNativeSearchBar(searchBarHandler);
var editText = searchView.GetChildrenOfType<EditText>().FirstOrDefault();
if (editText != null)
{
return editText.LetterSpacing;
}
return -1;
}
Android.Views.TextAlignment GetNativeTextAlignment(SearchBarHandler searchBarHandler)
{
var searchView = GetNativeSearchBar(searchBarHandler);
var editText = searchView.GetChildrenOfType<EditText>().First();
return editText.TextAlignment;
}
double GetNativeUnscaledFontSize(SearchBarHandler searchBarHandler)
{
var searchView = GetNativeSearchBar(searchBarHandler);
var editText = searchView.GetChildrenOfType<EditText>().FirstOrDefault();
if (editText == null)
return -1;
return editText.TextSize / editText.Resources.DisplayMetrics.Density;
}
bool GetNativeIsBold(SearchBarHandler searchBarHandler)
{
var searchView = GetNativeSearchBar(searchBarHandler);
var editText = searchView.GetChildrenOfType<EditText>().FirstOrDefault();
if (editText == null)
return false;
return editText.Typeface.IsBold;
}
bool GetNativeIsItalic(SearchBarHandler searchBarHandler)
{
var searchView = GetNativeSearchBar(searchBarHandler);
var editText = searchView.GetChildrenOfType<EditText>().FirstOrDefault();
if (editText == null)
return false;
return editText.Typeface.IsItalic;
}
}
} | 27.952756 | 87 | 0.76 | [
"MIT"
] | Amir-Hossin-pr/maui | src/Core/tests/DeviceTests/Handlers/SearchBar/SearchBarHandlerTests.Android.cs | 3,552 | C# |
namespace SampleWeb
{
/// <summary>
/// This is a generated list of Enums that list the names/ID numbers for the feature bits used in your application.
/// </summary>
public enum Features
{
DummyOn = 1,
DummyOff = 2,
}
}
| 20.153846 | 119 | 0.599237 | [
"Apache-2.0"
] | dseelinger/feature-bits-sample | DotNet/SampleWeb/Features.cs | 262 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.