content stringlengths 23 1.05M |
|---|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Db.Entities.Users
{
/// <summary>
/// 角色类
/// </summary>
public class Role:PrimaryKey
{
/// <summary>
/// 角色名称
/// </summary>
[Required,StringLength(64)]
public string Name { get; set; }
/// <summary>
/// 此处与UserRoleRel表建立外键,删除Role时自动删除所有对应关系,防止代码处理时忘记
/// </summary>
public List<UserRoleRel> UserRoleRel { get; set; }
public List<RoleFunctions> RoleFunctions { get; set; }
}
}
|
using BrawlLib.SSBBTypes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace BrawlLib.SSBB.ResourceNodes
{
public unsafe class MDL0DefNode : MDL0EntryNode
{
internal List<object> _items = new List<object>();
private int _len;
//internal List<MDL0Node2Class> _items2 = new List<MDL0Node2Class>();
//internal List<MDL0Node3Class> _items3 = new List<MDL0Node3Class>();
//internal List<MDL0NodeType4> _items4 = new List<MDL0NodeType4>();
//internal List<MDL0NodeType5> _items5 = new List<MDL0NodeType5>();
//[Category("MDL0 Nodes")]
//public List<MDL0Node2Class> NodeType2Items { get { return _items2; } }
//[Category("MDL0 Nodes")]
//public List<MDL0Node3Class> NodeType3Items { get { return _items3; } }
//[Category("MDL0 Nodes")]
//public List<MDL0NodeType4> NodeType4Items { get { return _items4; } }
//[Category("MDL0 Nodes")]
//public List<MDL0NodeType5> NodeType5Items { get { return _items5; } }
[Category("MDL0 Nodes")] public int DataLength => _len;
[Category("MDL0 Nodes")]
public object[] Items
{
get => _items.ToArray();
set => _items = value.ToList();
}
public override bool OnInitialize()
{
VoidPtr addr = WorkingUncompressed.Address;
object n = null;
while ((n = MDL0NodeClass.Create(ref addr)) != null)
{
_items.Add(n);
}
//while ((n = MDL0NodeClass.Create(ref addr)) != null)
//{
// if (n is MDL0Node2Class)
// _items2.Add(n as MDL0Node2Class);
// else if (n is MDL0Node3Class)
// _items3.Add(n as MDL0Node3Class);
// else if (n is MDL0NodeType4)
// _items4.Add((MDL0NodeType4)n);
// else if (n is MDL0NodeType5)
// _items5.Add((MDL0NodeType5)n);
//}
_len = addr - WorkingUncompressed.Address;
SetSizeInternal(_len);
return false;
}
}
} |
namespace Services.Products.Domain
{
using System;
using System.Collections.Generic;
public interface IProductRepository
{
Product Get(Guid id);
IEnumerable<Product> Get();
void Upsert(Product entity);
}
}
|
namespace MoiteRecepti.Web.ViewModels.Recipes
{
using MoiteRecepti.Data.Models;
using MoiteRecepti.Services.Mapping;
public class IngredientsViewModel : IMapFrom<RecipeIngredient>
{
public string IngredientName { get; set; }
public string Quantity { get; set; }
}
}
|
namespace ImageProcessingLib
{
using System.Drawing;
using System.Text;
/// <summary>
/// Represents a structuring element matrix for masking a <see cref="BinaryImage"/>.
/// The values for black and white are the same as for <see cref="BinaryImage.Black"/> and
/// <see cref="BinaryImage.White"/>. Values, that should be ignored are represented by the <strong>-1</strong>
/// respectively as a <strong>x</strong> in the string.
/// </summary>
/// <remarks>
/// <![CDATA[
/// Sample structuring element:
/// . - - - -> x, n
/// | x x x
/// | x 1 1
/// | x 0 0
/// v
/// y, m
/// Note: The x in the string representation of the structuring element matrix has the numeric value (-1) and
/// indicates that this pixel/position should be ignored for evaluation.
/// The x achsis represents the whidth and
/// the y achsis represents the height.
/// ]]>
/// </remarks>
public sealed class StructuringElement
{
private const int Ignore = -1;
private const string IgnoreCharacter = "x";
private readonly int[,] value;
public Size Size => new(this.value.GetLength(0), this.value.GetLength(1));
public int this[int m, int n] => this.value[m, n];
public StructuringElement(int[,] value)
{
this.value = value;
}
public override string ToString()
{
const int MaxCharactersToPrint = 20;
var numberOfCharactersPrinted = 0;
var stringBuilder = new StringBuilder();
for (var m = 0; m < this.Size.Height; m++)
{
for (var n = 0; n < this.Size.Width; n++)
{
string character = this.value[m, n] == Ignore ? IgnoreCharacter : this.value[m, n].ToString();
stringBuilder.Append(character);
numberOfCharactersPrinted++;
if (numberOfCharactersPrinted > MaxCharactersToPrint)
{
return stringBuilder + $"... ({this.Size.Height}x{this.Size.Width})";
}
}
// only add a new line if it's not the last row
if (m + 1 < this.Size.Height)
{
stringBuilder.AppendLine();
}
}
return stringBuilder.ToString();
}
}
} |
using System;
namespace Sproto {
public class SprotoStream {
public const int SEEK_BEGIN = 0;
public const int SEEK_CUR = 1;
public const int SEEK_END = 2;
public const int MAX_SIZE = 0x1000000;
private byte[] buffer;
private int pos;
public SprotoStream () {
this.buffer = new byte[256];
this.pos = 0;
}
public byte[] Buffer {
get {return this.buffer;}
set {this.buffer = value;}
}
public int Position {
get {return this.pos;}
}
public int Capcity {
get {return this.buffer.Length;}
}
public void Expand (int size) {
if (this.Capcity - this.pos < size) {
int old_capcity = this.Capcity;
int capcity = this.Capcity;
while (capcity - this.pos < size) {
capcity = capcity * 2;
}
if (capcity >= SprotoStream.MAX_SIZE) {
SprotoHelper.Error("object is too large(>{0})",SprotoStream.MAX_SIZE);
}
byte [] new_buffer = new byte[capcity];
for (int i = 0; i < old_capcity; i++) {
new_buffer[i] = this.buffer[i];
}
this.buffer = new_buffer;
}
}
private void _WriteByte (byte b) {
this.buffer[this.pos++] = b;
}
public void WriteByte (byte b) {
this.Expand(sizeof(byte));
this._WriteByte(b);
}
public void Write (byte[] data,int offset,int length) {
this.Expand(length);
for (int i = 0; i < length; i++) {
byte b = data[offset + i];
this._WriteByte(b);
}
}
public void Write(byte[] data,int offset,UInt32 length) {
this.Write(data,offset,(int)length);
}
public int Seek (int offset,int whence) {
switch (whence) {
case SprotoStream.SEEK_BEGIN:
this.pos = 0 + offset;
break;
case SprotoStream.SEEK_CUR:
this.pos = this.pos + offset;
break;
case SprotoStream.SEEK_END:
this.pos = this.Capcity + offset;
break;
default:
SprotoHelper.Error("[Sproto.Stream.Seek] invalid whence:{0}",whence);
break;
}
this.Expand(0);
return this.pos;
}
public int Seek (UInt32 offset,int whence) {
return this.Seek((int)offset,whence);
}
public byte ReadByte () {
return this.buffer[this.pos++];
}
public int Read (byte[] bytes,int offset,int length) {
for (int i = 0; i < length; i++) {
if (this.pos >= this.Capcity) {
return i;
}
bytes[offset + i] = this.ReadByte();
}
return length;
}
public int Read (byte[] bytes,int offset,UInt32 length) {
return this.Read(bytes,offset,(int)length);
}
}
}
|
using Deviax.QueryBuilder.Visitors;
namespace Deviax.QueryBuilder.Parts
{
public class ContainsPart : Part, IBooleanPart
{
public readonly IPart Left;
public readonly IPart Right;
public ContainsPart(IPart left, IPart right)
{
Left = left;
Right = right;
}
public override void Accept(INodeVisitor visitor) => visitor.Visit(this);
}
} |
using QuizyfyAPI.Contracts.Responses.Pagination;
namespace QuizyfyAPI.Data;
public interface IQuizRepository : IRepository
{
PagedList<Quiz> GetQuizzes(PagingParams pagingParams, bool includeQuestions = false);
Task<Quiz> GetQuiz(int id, bool includeQuestions = false);
}
|
// -----------------------------------------------------------------------
// <copyright file="ApplicationInsightsLoggerEventSource.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.
// All rights reserved. 2013
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Extensions.Logging.ApplicationInsights
{
using System.Diagnostics.Tracing;
using System.Reflection;
/// <summary>
/// EventSource for reporting errors and warnings from Logging module.
/// </summary>
#if REDFIELD
[EventSource(Name = "Redfield-Microsoft-ApplicationInsights-LoggerProvider")]
#else
[EventSource(Name = "Microsoft-ApplicationInsights-LoggerProvider")]
#endif
internal sealed class ApplicationInsightsLoggerEventSource : EventSource
{
public static readonly ApplicationInsightsLoggerEventSource Log = new ApplicationInsightsLoggerEventSource();
public readonly string ApplicationName;
private ApplicationInsightsLoggerEventSource()
{
this.ApplicationName = GetApplicationName();
}
[Event(1, Message = "Sending log to ApplicationInsightsLoggerProvider has failed. Error: {0}", Level = EventLevel.Error)]
public void FailedToLog(string error, string applicationName = null) => this.WriteEvent(1, error, applicationName ?? this.ApplicationName);
[NonEvent]
private static string GetApplicationName()
{
try
{
return Assembly.GetEntryAssembly().GetName().Name;
}
catch
{
return "Unknown";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
namespace G15Map.Parsers
{
public class Tileset
{
// 23:401F (0x8C01F) -> animation data; 0xFC bytes, 4 bytes per entry: [RAM address 2b][function address 2b]
// (addresses might be incorrect as anim *starts*)
// 23:401F: animated water (tile 03) + animated flowers (tile 38)
// 23:4023: animated flowers
// 23:4027: still water + animated flowers
// 23:402B: "" (diff frame?)
// 23:402F: "" (diff frame?)
// 23:4033: "" (diff frame?)
// 23:4037: "" (diff frame?)
// 23:403B: still water + still flowers
// 23:403F: "" (diff frame?)
// 23:4043: "" (diff frame?)
// 23:4047: "" (diff frame?)
// 23:404B: animated water (L/R) + still flowers
// 23:4053: still water + still flowers
// 23:4057: ""
// 23:405B: ""
// 23:405F: ""
// ...
// 23:4077: (animated water + tile 53; waterfalls?)
// ...
// 23:40A7: (animated water + tile 54; conveyor belts?)
// ...
// 23:40BB: (animated water + tile 54; conveyor belts?)
// ...
// 23:40CB: (animated tile 54)
// ...
// 23:40DF: (animated tile 4F)
// ...
public const int BlockDataSize = 0x800;
public const int TileDataSize = 0x600;
public const int CollisionDataSize = 0x400; // TODO verify
public const int TileDimensions = 8;
public const int CollisionDimensions = 16;
public const int BlockDimensions = 32;
public byte Bank { get; private set; }
public ushort BlockDataPointer { get; private set; }
public ushort TileDataPointer { get; private set; }
public ushort CollisionDataPointer { get; private set; }
public ushort AnimationDataPointer { get; private set; }
public byte Unknown0x09 { get; private set; }
public byte Unknown0x0A { get; private set; }
public byte[] BlockData { get; private set; }
public byte[] TileData { get; private set; }
public byte[] CollisionData { get; private set; }
public Tileset(BinaryReader reader)
{
Bank = reader.ReadByte();
BlockDataPointer = reader.ReadUInt16();
TileDataPointer = reader.ReadUInt16();
CollisionDataPointer = reader.ReadUInt16();
AnimationDataPointer = reader.ReadUInt16();
Unknown0x09 = reader.ReadByte();
Unknown0x0A = reader.ReadByte();
long positionBackup = reader.BaseStream.Position;
reader.BaseStream.Position = GameHelpers.CalculateOffset(Bank, BlockDataPointer);
BlockData = reader.ReadBytes(BlockDataSize);
reader.BaseStream.Position = GameHelpers.CalculateOffset(Bank, TileDataPointer);
TileData = reader.ReadBytes(TileDataSize);
reader.BaseStream.Position = GameHelpers.CalculateOffset(Bank, CollisionDataPointer);
CollisionData = reader.ReadBytes(CollisionDataSize);
reader.BaseStream.Position = positionBackup;
}
}
}
|
using static War3Api.Common;
namespace AzerothWarsCSharp.MacroTools.Commands
{
public class Command
{
public string Activator { get; }
public OnCommandDelegate OnCommand { get; }
public delegate void OnCommandDelegate(player triggerPlayer, string[] arguments);
protected Command(string activator, OnCommandDelegate onCommand)
{
Activator = activator;
OnCommand = onCommand;
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Buffer4096.cs" company="Catel development team">
// Copyright (c) 2008 - 2016 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Pooling
{
/// <summary>
/// Poolable buffer of 4096 bytes.
/// </summary>
public class Buffer4096Poolable : BufferPoolableBase
{
/// <summary>
/// Initializes a new instance of the <see cref="Buffer4096Poolable"/> class.
/// </summary>
public Buffer4096Poolable()
: base(4096)
{
}
}
} |
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef
using Beef.Caching;
using Beef.Caching.Policy;
using NUnit.Framework;
using System;
using System.Linq;
namespace Beef.Core.UnitTest.Caching
{
[TestFixture]
public class MultiTenantCacheTest
{
public static Guid ToGuid(int value)
{
return new Guid(value, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
[Test]
public void CreateAndGetWithInstanceFlush()
{
Policy.CachePolicyManagerTest.TestSetUp();
// Initialize the cache.
var mtc = new MultiTenantCache<KeyValueCache<int, string>>((g, p) =>
{
if (g.Equals(ToGuid(1)))
return new KeyValueCache<int, string>(p, (k) => k.ToString());
else
return new KeyValueCache<int, string>(p, (k) => "X" + k.ToString());
}, "MultiTenantCacheTest");
// Check the internal nocachepolicy.
var pa = CachePolicyManager.Current.GetPolicies();
Assert.AreEqual(1, pa.Length);
Assert.IsTrue(pa[0].Key.StartsWith("MultiTenantCacheTest_"));
Assert.IsInstanceOf(typeof(NoCachePolicy), pa[0].Value);
// Check the default policy for type.
Assert.AreEqual(mtc.PolicyKey, "MultiTenantCacheTest");
Assert.IsInstanceOf(typeof(NoExpiryCachePolicy), mtc.GetPolicy());
// Check that the cache is empty.
Assert.IsFalse(mtc.Contains(ToGuid(1)));
Assert.AreEqual(0, mtc.Count);
mtc.Remove(ToGuid(1));
// Check the first tenant.
var kvc1 = mtc.GetCache(ToGuid(1));
Assert.IsNotNull(kvc1);
Assert.AreEqual("1", kvc1[1]);
Assert.AreEqual(1, mtc.Count);
// No new PolicyManager policies should be created.
pa = CachePolicyManager.Current.GetPolicies();
Assert.AreEqual(2, pa.Length);
// Check the second tenant.
var kvc2 = mtc.GetCache(ToGuid(2));
Assert.IsNotNull(kvc2);
Assert.AreEqual("X1", kvc2[1]);
Assert.AreEqual(2, mtc.Count);
// Flush the cache - nothing should happen as they never expire.
mtc.Flush();
Assert.AreEqual(2, mtc.Count);
// Remove a tenant.
mtc.Remove(ToGuid(2));
Assert.IsTrue(mtc.Contains(ToGuid(1)));
Assert.IsFalse(mtc.Contains(ToGuid(2)));
Assert.AreEqual(1, mtc.Count);
Assert.AreEqual(0, kvc2.Count);
// Force flush the cache - should be removed.
mtc.Flush(true);
Assert.IsFalse(mtc.Contains(ToGuid(1)));
Assert.IsFalse(mtc.Contains(ToGuid(2)));
Assert.AreEqual(0, mtc.Count);
Assert.AreEqual(0, kvc1.Count);
}
[Test]
public void CreateAndGetWithForceFlush()
{
Policy.CachePolicyManagerTest.TestSetUp();
// Initialize the cache.
var mtc = new MultiTenantCache<KeyValueCache<int, string>>((g, p) =>
{
if (g.Equals(ToGuid(1)))
return new KeyValueCache<int, string>(p, (k) => k.ToString());
else
return new KeyValueCache<int, string>(p, (k) => "X" + k.ToString());
}, "MultiTenantCacheTest");
var pa = CachePolicyManager.Current.GetPolicies();
Assert.AreEqual(1, pa.Length);
// Check the internal nocachepolicy.
var p0 = pa.Where(x => x.Key.StartsWith("MultiTenantCacheTest_")).SingleOrDefault();
Assert.IsNotNull(p0);
Assert.IsInstanceOf(typeof(NoCachePolicy), p0.Value);
// Check that the cache is empty.
Assert.IsFalse(mtc.Contains(ToGuid(1)));
Assert.AreEqual(0, mtc.Count);
mtc.Remove(ToGuid(1));
// Check the first tenant.
var kvc1 = mtc.GetCache(ToGuid(1));
Assert.IsNotNull(kvc1);
Assert.AreEqual("1", kvc1[1]);
Assert.AreEqual(1, mtc.Count);
// Check the default policy for type.
pa = CachePolicyManager.Current.GetPolicies();
Assert.AreEqual(2, pa.Length);
var p1 = pa.Where(x => x.Key == "MultiTenantCacheTest").SingleOrDefault();
Assert.IsNotNull(p1);
Assert.IsInstanceOf(typeof(NoExpiryCachePolicy), p1.Value);
// Check the second tenant.
var kvc2 = mtc.GetCache(ToGuid(2));
Assert.IsNotNull(kvc2);
Assert.AreEqual("X1", kvc2[1]);
Assert.AreEqual(2, mtc.Count);
// No new PolicyManager policies should be created.
pa = CachePolicyManager.Current.GetPolicies();
Assert.AreEqual(2, pa.Length);
// Flush the cache - nothing should happen as they never expire.
CachePolicyManager.Current.Flush();
Assert.AreEqual(2, mtc.Count);
// Remove a tenant.
mtc.Remove(ToGuid(2));
Assert.IsTrue(mtc.Contains(ToGuid(1)));
Assert.IsFalse(mtc.Contains(ToGuid(2)));
Assert.AreEqual(1, mtc.Count);
Assert.AreEqual(0, kvc2.Count);
// Force flush the cache - should be removed.
CachePolicyManager.Current.ForceFlush();
Assert.IsFalse(mtc.Contains(ToGuid(1)));
Assert.IsFalse(mtc.Contains(ToGuid(2)));
Assert.AreEqual(0, mtc.Count);
Assert.AreEqual(0, kvc1.Count);
}
}
}
|
namespace System.Linq.Sql
{
#if DEBUG
public
#else
internal
#endif
struct CommandField
{
private readonly string field;
private readonly int ordinal;
private readonly string table;
public CommandField(string table, string field, int ordinal)
{
this.table = table;
this.field = field;
this.ordinal = ordinal;
}
// ----- Properties ----- //
public string Table => table;
public string FieldName => field;
public int Ordinal => ordinal;
}
}
|
using System;
using Newtonsoft.Json;
namespace Preact
{
[JsonObject(MemberSerialization.OptIn)]
public class Account
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "license_type")]
public string LicenseType { get; set; }
[JsonProperty(PropertyName = "license_count")]
public int? LicenseCount { get; set; }
[JsonProperty(PropertyName = "license_renewal")]
public DateTime? LicenseRenewal { get; set; }
[JsonProperty(PropertyName = "license_value")]
public int? LicenseValue { get; set; }
[JsonProperty(PropertyName = "license_mrr")]
public decimal? LicenseMRR { get; set; }
[JsonProperty(PropertyName = "license_duration")]
public int? LicenseDuration { get; set; }
[JsonProperty(PropertyName = "license_status")]
public string LicenseStatus { get; set; }
[JsonProperty(PropertyName = "customer_since")]
public DateTime? CustomerSince { get; set; }
[JsonProperty(PropertyName = "trial_start")]
public DateTime? TrialStart { get; set; }
[JsonProperty(PropertyName = "trial_end")]
public DateTime? TrialEnd { get; set; }
[JsonProperty(PropertyName = "account_manager_name")]
public string AccountManagerName { get; set; }
[JsonProperty(PropertyName = "account_manager_email")]
public string AccountManagerEmail { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PastryShop.Models;
namespace PastryShop.TestTools
{
[TestClass]
public class BreadTests
{
[TestMethod]
public void BreadConstructor_CreatesInstanceOfItem_Item()
{
Bread newBread = new Bread();
Assert.AreEqual(typeof(Bread), newBread.GetType());
}
[TestMethod]
public void FindTotal_ReturnsTotal_Int01()
{
int amount = 3;
int result = Bread.FindTotal(amount);
Assert.AreEqual(10, result);
}
[TestMethod]
public void FindTotal_ReturnsTotal_Int02()
{
int amount = 4;
int result = Bread.FindTotal(amount);
Assert.AreEqual(15, result);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LeetCode.Naive.Problems
{
/// <summary>
/// Problem: https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
/// Submission: https://leetcode.com/submissions/detail/252376293/
/// </summary>
internal class P0117
{
public class Solution
{
public Node Connect(Node root)
{
if (root == null)
return null;
Process(root, new Stack<Node>());
return root;
}
private void Process(Node node, Stack<Node> stack)
{
if (stack.Count > 0)
{
node.next = stack.Pop();
}
if (node.right != null)
Process(node.right, stack);
if (node.left != null)
Process(node.left, stack);
stack.Push(node);
}
}
}
}
|
using MetroLog.Layouts;
using MetroLog.Targets;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetroLog.Targets
{
/// <summary>
/// Defines a target that will append messages to a single file.
/// </summary>
public class StreamingFileTarget : FileTarget
{
public StreamingFileTarget()
: this(new SingleLineLayout())
{
}
public StreamingFileTarget(Layout layout)
: base(layout)
{
this.FileNamingParameters.IncludeLevel = false;
this.FileNamingParameters.IncludeLogger = false;
this.FileNamingParameters.IncludeSequence = false;
this.FileNamingParameters.IncludeSession = false;
this.FileNamingParameters.IncludeTimestamp = FileTimestampMode.Date;
FileNamingParameters.CreationMode = FileCreationMode.AppendIfExisting;
}
protected override Task WriteTextToFileCore(StreamWriter file, string contents)
{
return file.WriteLineAsync(contents);
}
}
[Obsolete("Use StreamingFileTarget")]
public class FileStreamingTarget : StreamingFileTarget
{
public FileStreamingTarget()
{
}
public FileStreamingTarget(Layout layout) : base(layout)
{
}
}
}
|
//Do not edit! This file was generated by Unity-ROS MessageGeneration.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Unity.Robotics.ROSTCPConnector.MessageGeneration;
using RosMessageTypes.Std;
namespace RosMessageTypes.Aruco
{
[Serializable]
public class MarkerMsg : Message
{
public const string k_RosMessageName = "aruco_msgs/Marker";
public override string RosMessageName => k_RosMessageName;
public HeaderMsg header;
public uint id;
public Geometry.PoseWithCovarianceMsg pose;
public double confidence;
public MarkerMsg()
{
this.header = new HeaderMsg();
this.id = 0;
this.pose = new Geometry.PoseWithCovarianceMsg();
this.confidence = 0.0;
}
public MarkerMsg(HeaderMsg header, uint id, Geometry.PoseWithCovarianceMsg pose, double confidence)
{
this.header = header;
this.id = id;
this.pose = pose;
this.confidence = confidence;
}
public static MarkerMsg Deserialize(MessageDeserializer deserializer) => new MarkerMsg(deserializer);
private MarkerMsg(MessageDeserializer deserializer)
{
this.header = HeaderMsg.Deserialize(deserializer);
deserializer.Read(out this.id);
this.pose = Geometry.PoseWithCovarianceMsg.Deserialize(deserializer);
deserializer.Read(out this.confidence);
}
public override void SerializeTo(MessageSerializer serializer)
{
serializer.Write(this.header);
serializer.Write(this.id);
serializer.Write(this.pose);
serializer.Write(this.confidence);
}
public override string ToString()
{
return "MarkerMsg: " +
"\nheader: " + header.ToString() +
"\nid: " + id.ToString() +
"\npose: " + pose.ToString() +
"\nconfidence: " + confidence.ToString();
}
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoadMethod]
#else
[UnityEngine.RuntimeInitializeOnLoadMethod]
#endif
public static void Register()
{
MessageRegistry.Register(k_RosMessageName, Deserialize);
}
}
}
|
using System.Collections.Generic;
using System.Diagnostics;
namespace AddressFinder.Tests
{
public class AddressValidationTestBase
{
[Conditional("DEBUG")]
protected void ExplainResult(PostalAddressSearchResult result)
{
Trace.WriteLine(string.Format("{0} - {1}", result.Score, result.Format.AddressOneLine));
//foreach (var explanation in result.Explanations)
//{
// //_testContext.WriteLine("{0}", explanation);
// Trace.WriteLine(string.Format("{0}", explanation));
//}
Trace.WriteLine(string.Empty);
}
[Conditional("DEBUG")]
protected void ExplainResult(IEnumerable<PostalAddressSearchResult> results)
{
foreach (var result in results)
{
ExplainResult(result);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ILRuntime.Runtime.Generated
{
}
|
using Baseline;
using Miru.Core;
using Scriban;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Miru.Userfy.Invitable;
public class Maker
{
public bool DryRun { get; set; }
public static Maker For(MiruPath currentDirectory)
{
return new Maker(new MiruSolution(currentDirectory));
}
public static Maker For(MiruPath currentDirectory, string solutionName)
{
if (Path.GetFileName(currentDirectory).Equals(solutionName) == false)
currentDirectory = Path.Combine(currentDirectory, solutionName);
return new Maker(new MiruSolution(currentDirectory));
}
public MiruSolution Solution { get; }
public Assembly Assembly { get; }
public Maker(MiruSolution solution, Assembly assembly = null)
{
DryRun = Environment.GetCommandLineArgs().Contains("--dry");
Solution = solution;
Assembly = assembly ?? typeof(Maker).GetTypeInfo().Assembly;
}
public void Directory(params string[] paths)
{
var newDir = paths.Length > 0
? A.Path / Solution.RootDir / paths
: A.Path / Solution.RootDir;
var shortDestination = Path.Combine(paths);
if (!DryRun)
System.IO.Directory.CreateDirectory(newDir);
Console2.YellowLine($"\tCreate\t{(paths.Length > 0 ? shortDestination : newDir.ToString())}");
}
public void Template(string templateName, params string[] to)
{
Template(templateName, new
{
Solution,
MiruInfo.MiruVersion
}, to);
}
public void Template(string templateName, object input, params string[] to)
{
var template = GetTemplate(templateName);
var shortDestination = Path.Combine(to);
var destination = Path.Combine(Solution.RootDir, shortDestination);
if (File.Exists(destination))
{
Console2.GreyLine($"\tSkip\t{Solution.RootDir.Relative(destination)}");
return;
}
Console2.YellowLine($"\tCreate\t{Solution.RootDir.Relative(destination)}");
var result = template.Render(new
{
Solution,
MiruInfo.MiruVersion,
input
}, member => member.Name);
if (!DryRun)
{
Directories.CreateIfNotExists(Path.GetDirectoryName(destination));
File.AppendAllText(destination, result);
}
}
private Template GetTemplate(string templateName)
{
if (!templateName.EndsWith(".stub"))
templateName += ".stub";
var templateText = ReadEmbedded(templateName);
var template = Scriban.Template.Parse(templateText);
return template;
}
public string ReadEmbedded(string fileName)
{
var @namespace = typeof(Maker).Namespace;
var resourceName = $"{@namespace}.Templates.{fileName}";
var stream = this.Assembly.GetManifestResourceStream(resourceName);
if (stream == null)
throw new FileNotFoundException($"Could not find the resource: {resourceName}");
using (stream)
{
return stream.ReadAllText();
}
}
public MiruPath Expand(string @in)
{
return Path.Combine(@in.Split("/"));
}
public string Namespace(string @in)
{
return @in
.Replace('\\', '.')
.Replace('/', '.');
}
public string Url(string urlIn)
{
return urlIn.Replace('\\', '/');
}
} |
using System.Collections.Generic;
using Course.Contracts;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Course.Services
{
public class MovieService : IMovieService
{
private readonly IMongoCollection<BsonDocument> _movies;
public MovieService(IDbClient client)
{
_movies = client.GetMoviesCollection();
}
public IEnumerable<BsonDocument> GetMoviesLabOne()
{
return _movies.Find(new BsonDocument())
.SortByDescending(m => m["runtime"])
.Limit(10)
.ToList();
}
}
} |
using UnityEngine;
namespace PicoUnity.Audio
{
internal class SfxEffectVibrato : SfxEffect
{
private Oscillator lfo;
private float maxFrequency;
private float minFrequency;
public SfxEffectVibrato(float minFrequency, float maxFrequency, float frequencyLFO)
{
lfo = new Oscillator(frequencyLFO, AudioSynth.Waveform.LFO);
this.maxFrequency = maxFrequency;
this.minFrequency = minFrequency;
}
public override void Reset()
{
}
public override void Step(double deltaTime, Oscillator oscillator)
{
float t = (float)lfo.Step(deltaTime);
oscillator.Frequency = Mathf.Lerp(minFrequency, maxFrequency, t);
}
}
}
|
namespace HandyControl.Data
{
public enum ChatMessageType
{
String,
Image,
Audio,
Custom
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using static ReedSolomonApp.NativeReedSolomon;
namespace ReedSolomonApp
{
public sealed class NativeReedSolomonImpl
{
private RSBuffer input;
private RSBuffer outEncoded;
#if NOISE_DECODE_ENABLE
private RSBuffer outDecoded;
private bool isNoised;
#endif
public byte[] Message { get; private set; }
public ushort GeneratorPolynomial { get; set; }
#if NOISE_DECODE_ENABLE
public ulong ErrorCount { get; set; }
public float ErrorFrequency { get; set; }
#endif
public event EventHandler<RSEventArgs> Encoded;
#if NOISE_DECODE_ENABLE
public event EventHandler<RSEventArgs> Noised;
public event EventHandler<RSExtEventArgs> Decoded;
#endif
public NativeReedSolomonImpl(IEnumerable<byte> message)
{
try
{
Message = message.ToArray();
input = new RSBuffer
{
Buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * Message.Length),
Length = Message.Length
};
Marshal.Copy(Message, 0, input.Buffer, Message.Length);
}
catch
{
throw new Exception("Can not create new instance of ReedSolomonApp.NativeReedSolomonImpl");
}
}
private (RSCode, IEnumerable<byte>) Encode()
{
if (Message == null)
{
#if DEBUG
throw new NullReferenceException("Message equals to null");
#else
return (RSCode.Unhandled, null);
#endif
}
outEncoded = new RSBuffer();
var code = ReedSolomonEncode(input, GeneratorPolynomial, ref outEncoded);
var encodedBytes = new byte[outEncoded.Length];
if (code == RSCode.Success)
{
Marshal.Copy(outEncoded.Buffer, encodedBytes, 0, outEncoded.Length);
}
return (code, encodedBytes);
}
public async void EncodeAsync()
{
var (code, bytes) = await Task.Run(() => Encode());
Encoded?.Invoke(this, new RSEventArgs(code, bytes));
}
#if NOISE_DECODE_ENABLE
private (RSCode, IEnumerable<byte>) Noise()
{
if (outEncoded.Buffer == IntPtr.Zero)
{
#if DEBUG
throw new NullReferenceException("outEncoded equals to ZERO");
#else
return (RSCode.Unhandled, null);
#endif
}
var code = ReedSolomonNoise(outEncoded, GeneratorPolynomial, ErrorCount, ErrorFrequency);
var noisedBytes = new byte[outEncoded.Length];
if (code == RSCode.Success)
{
Marshal.Copy(outEncoded.Buffer, noisedBytes, 0, outEncoded.Length);
isNoised = true;
}
return (code, noisedBytes);
}
public async void NoiseAsync()
{
var (code, bytes) = await Task.Run(() => Noise());
Noised?.Invoke(this, new RSEventArgs(code, bytes));
}
private (RSCode, IEnumerable<byte>) Decode()
{
if (outEncoded.Buffer == IntPtr.Zero)
{
#if DEBUG
throw new NullReferenceException("outEncoded equals to ZERO");
#else
return (RSCode.Unhandled, null);
#endif
}
outDecoded = new RSBuffer();
var code = ReedSolomonDecode(outEncoded, GeneratorPolynomial, ref outDecoded);
var decodedBytes = new byte[outDecoded.Length];
if (code == RSCode.Success)
{
Marshal.Copy(outDecoded.Buffer, decodedBytes, 0, outDecoded.Length);
}
return (code, decodedBytes);
}
public async void DecodeAsync()
{
var (code, bytes) = await Task.Run(() => Decode());
Decoded?.Invoke(this, new RSExtEventArgs(code, bytes, isNoised));
}
#endif
public void Dispose()
{
if (outEncoded.Buffer != IntPtr.Zero)
ReedSolomonFree(outEncoded);
#if NOISE_DECODE_ENABLE
if (outDecoded.Buffer != IntPtr.Zero)
ReedSolomonFree(outDecoded);
#endif
if (input != IntPtr.Zero)
Marshal.FreeHGlobal(input);
}
[DllImport("reed-solomon.dll", EntryPoint = "ReedSolomonFree", CallingConvention = CallingConvention.Cdecl)]
private static extern RSCode ReedSolomonFree(IntPtr ptr);
[DllImport("reed-solomon.dll", EntryPoint = "ReedSolomonEncode", CallingConvention = CallingConvention.Cdecl)]
private static extern RSCode ReedSolomonEncode(RSBuffer input, ushort gv, ref RSBuffer output);
#if NOISE_DECODE_ENABLE
[DllImport("reed-solomon.dll", EntryPoint = "ReedSolomonNoise", CallingConvention = CallingConvention.Cdecl)]
private static extern RSCode ReedSolomonNoise(RSBuffer buf, ushort gv, ulong ec, float freq);
[DllImport("reed-solomon.dll", EntryPoint = "ReedSolomonDecode", CallingConvention = CallingConvention.Cdecl)]
private static extern RSCode ReedSolomonDecode(RSBuffer input, ushort gv, ref RSBuffer output);
#endif
[StructLayout(LayoutKind.Sequential)]
private struct RSBuffer
{
public int Length;
public IntPtr Buffer;
public static implicit operator IntPtr(RSBuffer buf) => buf.Buffer;
}
}
} |
namespace CustomMediator.Implementation.Interfaces
{
public interface IBaseRequestHandler { }
}
|
using System;
namespace Engine
{
[Serializable]
public class RecordedEventArgs : EventArgs
{
public byte[] Data { get; private set; }
public int DataSize { get; private set; }
public int Channels { get; private set; }
public int BitPerChannel { get; private set; }
public int Frequency { get; private set; }
public RecordedEventArgs(byte[] data, int availableData, int channels, int bits, int frequency)
{
Data = data;
DataSize = availableData * channels * (bits / 8);
Channels = channels;
BitPerChannel = bits;
Frequency = frequency;
}
}
}
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.OpcUa.Protocol.Services {
using Microsoft.Azure.IIoT.Serializers.NewtonSoft;
using Microsoft.Azure.IIoT.Serializers;
using Opc.Ua;
using Xunit;
public class VariantEncoderUInt64Tests {
[Fact]
public void DecodeEncodeUInt64FromJValue() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(123Lu);
var variant = codec.Decode(str, BuiltInType.UInt64);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(str, encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromJArray() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromArray(123Lu, 124Lu, 125Lu);
var variant = codec.Decode(str, BuiltInType.UInt64);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(str, encoded);
}
[Fact]
public void DecodeEncodeUInt64FromJValueTypeNullIsInt64() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(123Lu);
var variant = codec.Decode(str, BuiltInType.Null);
var expected = new Variant(123L);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromJArrayTypeNullIsInt64() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromArray(123Lu, 124Lu, 125Lu);
var variant = codec.Decode(str, BuiltInType.Null);
var expected = new Variant(new long[] { 123L, 124L, 125L });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(str, encoded);
}
[Fact]
public void DecodeEncodeUInt64FromString() {
var codec = new VariantEncoderFactory().Default;
var str = "123";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromString() {
var codec = new VariantEncoderFactory().Default;
var str = "123, 124, 125";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromString2() {
var codec = new VariantEncoderFactory().Default;
var str = "[123, 124, 125]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromString3() {
var codec = new VariantEncoderFactory().Default;
var str = "[]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(new ulong[0]);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromStringTypeIntegerIsInt64() {
var codec = new VariantEncoderFactory().Default;
var str = "123";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Integer);
var expected = new Variant(123L);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromStringTypeIntegerIsInt641() {
var codec = new VariantEncoderFactory().Default;
var str = "[123, 124, 125]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Integer);
var expected = new Variant(new Variant[] {
new Variant(123L), new Variant(124L), new Variant(125L)
});
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromStringTypeIntegerIsInt642() {
var codec = new VariantEncoderFactory().Default;
var str = "[]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Integer);
var expected = new Variant(new Variant[0]);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromStringTypeNumberIsInt64() {
var codec = new VariantEncoderFactory().Default;
var str = "123";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Number);
var expected = new Variant(123L);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromStringTypeNumberIsInt641() {
var codec = new VariantEncoderFactory().Default;
var str = "[123, 124, 125]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Number);
var expected = new Variant(new Variant[] {
new Variant(123L), new Variant(124L), new Variant(125L)
});
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromStringTypeNumberIsInt642() {
var codec = new VariantEncoderFactory().Default;
var str = "[]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Number);
var expected = new Variant(new Variant[0]);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromStringTypeNullIsInt64() {
var codec = new VariantEncoderFactory().Default;
var str = "123";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(123L);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromStringTypeNullIsInt64() {
var codec = new VariantEncoderFactory().Default;
var str = "123, 124, 125";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(new long[] { 123L, 124L, 125L });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromStringTypeNullIsInt642() {
var codec = new VariantEncoderFactory().Default;
var str = "[123, 124, 125]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(new long[] { 123L, 124L, 125L });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromStringTypeNullIsNull() {
var codec = new VariantEncoderFactory().Default;
var str = "[]";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = Variant.Null;
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
}
[Fact]
public void DecodeEncodeUInt64FromQuotedString() {
var codec = new VariantEncoderFactory().Default;
var str = "\"123\"";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromSinglyQuotedString() {
var codec = new VariantEncoderFactory().Default;
var str = " '123'";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromQuotedString() {
var codec = new VariantEncoderFactory().Default;
var str = "\"123\",'124',\"125\"";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromQuotedString2() {
var codec = new VariantEncoderFactory().Default;
var str = " [\"123\",'124',\"125\"] ";
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromVariantJsonTokenTypeVariant() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
Type = "UInt64",
Body = 123Lu
});
var variant = codec.Decode(str, BuiltInType.Variant);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromVariantJsonTokenTypeVariant1() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
Type = "UInt64",
Body = new ulong[] { 123Lu, 124Lu, 125Lu }
});
var variant = codec.Decode(str, BuiltInType.Variant);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromVariantJsonTokenTypeVariant2() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
Type = "UInt64",
Body = new ulong[0]
});
var variant = codec.Decode(str, BuiltInType.Variant);
var expected = new Variant(new ulong[0]);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromVariantJsonStringTypeVariant() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
Type = "UInt64",
Body = 123Lu
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Variant);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromVariantJsonStringTypeVariant() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
Type = "UInt64",
Body = new ulong[] { 123Lu, 124Lu, 125Lu }
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Variant);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromVariantJsonTokenTypeNull() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
Type = "UInt64",
Body = 123Lu
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromVariantJsonTokenTypeNull1() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
TYPE = "UINT64",
BODY = new ulong[] { 123Lu, 124Lu, 125Lu }
});
var variant = codec.Decode(str, BuiltInType.Null);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromVariantJsonTokenTypeNull2() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
Type = "UInt64",
Body = new ulong[0]
});
var variant = codec.Decode(str, BuiltInType.Null);
var expected = new Variant(new ulong[0]);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromVariantJsonStringTypeNull() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
Type = "uint64",
Body = 123Lu
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromVariantJsonStringTypeNull() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
type = "UInt64",
body = new ulong[] { 123Lu, 124Lu, 125Lu }
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromVariantJsonTokenTypeNullMsftEncoding() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
DataType = "UInt64",
Value = 123Lu
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64FromVariantJsonStringTypeVariantMsftEncoding() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
DataType = "UInt64",
Value = 123Lu
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Variant);
var expected = new Variant(123Lu);
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromObject(123Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64ArrayFromVariantJsonTokenTypeVariantMsftEncoding() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.FromObject(new {
dataType = "UInt64",
value = new ulong[] { 123Lu, 124Lu, 125Lu }
});
var variant = codec.Decode(str, BuiltInType.Variant);
var expected = new Variant(new ulong[] { 123Lu, 124Lu, 125Lu });
var encoded = codec.Encode(variant);
Assert.Equal(expected, variant);
Assert.Equal(_serializer.FromArray(123Lu, 124Lu, 125Lu), encoded);
}
[Fact]
public void DecodeEncodeUInt64MatrixFromStringJsonTypeUInt64() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
}
);
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.UInt64);
var expected = new Variant(new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
});
var encoded = codec.Encode(variant);
Assert.True(expected.Value is Matrix);
Assert.True(variant.Value is Matrix);
Assert.Equal(((Matrix)expected.Value).Elements, ((Matrix)variant.Value).Elements);
Assert.Equal(((Matrix)expected.Value).Dimensions, ((Matrix)variant.Value).Dimensions);
}
[Fact]
public void DecodeEncodeUInt64MatrixFromVariantJsonTypeVariant() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
type = "UInt64",
body = new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
}
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Variant);
var expected = new Variant(new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
});
var encoded = codec.Encode(variant);
Assert.True(expected.Value is Matrix);
Assert.True(variant.Value is Matrix);
Assert.Equal(((Matrix)expected.Value).Elements, ((Matrix)variant.Value).Elements);
Assert.Equal(((Matrix)expected.Value).Dimensions, ((Matrix)variant.Value).Dimensions);
}
[Fact]
public void DecodeEncodeUInt64MatrixFromVariantJsonTokenTypeVariantMsftEncoding() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
dataType = "UInt64",
value = new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
}
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Variant);
var expected = new Variant(new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
});
var encoded = codec.Encode(variant);
Assert.True(expected.Value is Matrix);
Assert.True(variant.Value is Matrix);
Assert.Equal(((Matrix)expected.Value).Elements, ((Matrix)variant.Value).Elements);
Assert.Equal(((Matrix)expected.Value).Dimensions, ((Matrix)variant.Value).Dimensions);
}
[Fact]
public void DecodeEncodeUInt64MatrixFromVariantJsonTypeNull() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
type = "UInt64",
body = new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
}
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
});
var encoded = codec.Encode(variant);
Assert.True(expected.Value is Matrix);
Assert.True(variant.Value is Matrix);
Assert.Equal(((Matrix)expected.Value).Elements, ((Matrix)variant.Value).Elements);
Assert.Equal(((Matrix)expected.Value).Dimensions, ((Matrix)variant.Value).Dimensions);
}
[Fact]
public void DecodeEncodeUInt64MatrixFromVariantJsonTokenTypeNullMsftEncoding() {
var codec = new VariantEncoderFactory().Default;
var str = _serializer.SerializeToString(new {
dataType = "UInt64",
value = new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
}
});
var variant = codec.Decode(_serializer.FromObject(str), BuiltInType.Null);
var expected = new Variant(new ulong[,,] {
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } },
{ { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu }, { 123Lu, 124Lu, 125Lu } }
});
var encoded = codec.Encode(variant);
Assert.True(expected.Value is Matrix);
Assert.True(variant.Value is Matrix);
Assert.Equal(((Matrix)expected.Value).Elements, ((Matrix)variant.Value).Elements);
Assert.Equal(((Matrix)expected.Value).Dimensions, ((Matrix)variant.Value).Dimensions);
}
private readonly IJsonSerializer _serializer = new NewtonSoftJsonSerializer();
}
}
|
namespace Bing.Security.Claims
{
/// <summary>
/// 声明类型
/// </summary>
public static class BingClaimTypes
{
/// <summary>
/// 用户名。默认:<see cref="System.Security.Claims.ClaimTypes.Name"/>
/// </summary>
public static string UserName { get; set; } = System.Security.Claims.ClaimTypes.Name;
/// <summary>
/// 名字,默认:<see cref="System.Security.Claims.ClaimTypes.GivenName"/>
/// </summary>
public static string Name { get; set; } = System.Security.Claims.ClaimTypes.GivenName;
/// <summary>
/// 姓。默认:<see cref="System.Security.Claims.ClaimTypes.Surname"/>
/// </summary>
public static string SurName { get; set; } = System.Security.Claims.ClaimTypes.Surname;
/// <summary>
/// 姓名。默认:"full_name"
/// </summary>
public static string FullName { get; set; } = "full_name";
/// <summary>
/// 用户标识。默认:<see cref="System.Security.Claims.ClaimTypes.NameIdentifier"/>
/// </summary>
public static string UserId { get; set; } = System.Security.Claims.ClaimTypes.NameIdentifier;
/// <summary>
/// 电子邮件。默认:<see cref="System.Security.Claims.ClaimTypes.Email"/>
/// </summary>
public static string Email { get; set; } = System.Security.Claims.ClaimTypes.Email;
/// <summary>
/// 已验证电子邮件。默认:"email_verified"
/// </summary>
public static string EmailVerified { get; set; } = "email_verified";
/// <summary>
/// 手机号码。默认:"phone_number"
/// </summary>
public static string PhoneNumber { get; set; } = "phone_number";
/// <summary>
/// 已验证手机号码。默认:"phone_number_verified"
/// </summary>
public static string PhoneNumberVerified { get; set; } = "phone_number_verified";
/// <summary>
/// 版本标识。默认:"edition_id"
/// </summary>
public static string EditionId { get; set; } = "edition_id";
/// <summary>
/// 客户端标识。默认:"client_id"
/// </summary>
public static string ClientId { get; set; } = "client_id";
#region Application(应用程序)
/// <summary>
/// 应用程序标识。默认:"application_id"
/// </summary>
public static string ApplicationId { get; set; } = "application_id";
/// <summary>
/// 应用程序编码。默认:"application_code"
/// </summary>
public static string ApplicationCode { get; set; } = "application_code";
/// <summary>
/// 应用程序名称。默认:"application_name"
/// </summary>
public static string ApplicationName { get; set; } = "application_name";
#endregion
#region Tenant(租户)
/// <summary>
/// 租户标识。默认:"tenant_id"
/// </summary>
public static string TenantId { get; set; } = "tenant_id";
/// <summary>
/// 租户编码。默认:"tenant_code"
/// </summary>
public static string TenantCode { get; set; } = "tenant_code";
/// <summary>
/// 租户名称。默认:"tenant_name"
/// </summary>
public static string TenantName { get; set; } = "tenant_name";
#endregion
#region Role(角色)
/// <summary>
/// 角色。默认:<see cref="System.Security.Claims.ClaimTypes.Role"/>
/// </summary>
public static string Role { get; set; } = System.Security.Claims.ClaimTypes.Role;
/// <summary>
/// 角色标识列表。默认:"role_ids"
/// </summary>
public static string RoleIds { get; set; } = "role_ids";
/// <summary>
/// 角色编码列表。默认:"role_codes"
/// </summary>
public static string RoleCodes { get; set; } = "role_codes";
/// <summary>
/// 角色名称列表。默认:"role_names"
/// </summary>
public static string RoleNames { get; set; } = "role_names";
#endregion
}
}
|
using Teronis.Identity.Entities;
namespace Teronis.Identity.Datransjects
{
public class RoleDescriptorRoleConverter : IConvertRoleDescriptor<RoleDescriptorDatatransject, RoleEntity>
{
public RoleEntity Convert(RoleDescriptorDatatransject source) =>
source.ToRole();
}
}
|
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace JsonCons.JsonPath
{
interface IUnaryOperator
{
int PrecedenceLevel {get;}
bool IsRightAssociative {get;}
bool TryEvaluate(IValue elem, out IValue result);
};
abstract class UnaryOperator : IUnaryOperator
{
internal UnaryOperator(int precedenceLevel,
bool isRightAssociative = false)
{
PrecedenceLevel = precedenceLevel;
IsRightAssociative = isRightAssociative;
}
public int PrecedenceLevel {get;}
public bool IsRightAssociative {get;}
public abstract bool TryEvaluate(IValue elem, out IValue result);
};
sealed class NotOperator : UnaryOperator
{
internal static NotOperator Instance { get; } = new NotOperator();
internal NotOperator()
: base(8, true)
{}
public override bool TryEvaluate(IValue val, out IValue result)
{
result = Expression.IsFalse(val) ? JsonConstants.True : JsonConstants.False;
return true;
}
public override string ToString()
{
return "Not";
}
};
sealed class UnaryMinusOperator : UnaryOperator
{
internal static UnaryMinusOperator Instance { get; } = new UnaryMinusOperator();
internal UnaryMinusOperator()
: base(8, true)
{}
public override bool TryEvaluate(IValue val, out IValue result)
{
if (!(val.ValueKind == JsonValueKind.Number))
{
result = JsonConstants.Null;
return false; // type error
}
Decimal decVal;
double dblVal;
if (val.TryGetDecimal(out decVal))
{
result = new DecimalValue(-decVal);
return true;
}
else if (val.TryGetDouble(out dblVal))
{
result = new DoubleValue(-dblVal);
return true;
}
else
{
result = JsonConstants.Null;
return false;
}
}
public override string ToString()
{
return "Unary minus";
}
};
sealed class RegexOperator : UnaryOperator
{
Regex _regex;
internal RegexOperator(Regex regex)
: base(7, true)
{
_regex = regex;
}
public override bool TryEvaluate(IValue val, out IValue result)
{
if (!(val.ValueKind == JsonValueKind.String))
{
result = JsonConstants.Null;
return false; // type error
}
result = _regex.IsMatch(val.GetString()) ? JsonConstants.True : JsonConstants.False;
return true;
}
public override string ToString()
{
return "Regex";
}
};
} // namespace JsonCons.JsonPath
|
using System.Collections.Generic;
namespace FirebirdDbComparer.Interfaces
{
public interface IMetadata
{
string ConnectionString { get; }
void Initialize();
T GetSpecificDatabaseObject<T>() where T : IDatabaseObject;
IReadOnlyCollection<IDatabaseObject> DatabaseObjects { get; }
IMetadataCollations MetadataCollations { get; }
IMetadataConstraints MetadataConstraints { get; }
IMetadataDatabase MetadataDatabase { get; }
IMetadataDependencies MetadataDependencies { get; }
IMetadataExceptions MetadataExceptions { get; }
IMetadataFields MetadataFields { get; }
IMetadataFunctions MetadataFunctions { get; }
IMetadataGenerators MetadataGenerators { get; }
IMetadataCharacterSets MetadataCharacterSets { get; }
IMetadataIndices MetadataIndices { get; }
IMetadataProcedures MetadataProcedures { get; }
IMetadataRelations MetadataRelations { get; }
IMetadataRoles MetadataRoles { get; }
IMetadataTriggers MetadataTriggers { get; }
IMetadataUserPrivileges MetadataUserPrivileges { get; }
IMetadataPackages MetadataPackages { get; }
}
}
|
using ScriptsLevels.Inventory;
namespace ScriptsLevels.Bestiary
{
public class ReagentViewBestiaryItem : ViewBestiaryItem<ReagentItem>
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace FragmetApp
{
[Activity(Label = "DialogActivity")]
public class DialogActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var isLandscape = Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape;
if (isLandscape)
{
base.Finish();
}
var dialogId = base.Intent.Extras.GetInt(TitlesFragment.TitleDialogIdKey, 0);
var dialogFragment = DialogFragment.CreateInstance(dialogId);
base.FragmentManager
.BeginTransaction()
.Add(Android.Resource.Id.Content, dialogFragment)
.Commit();
}
}
} |
using Core.Hotels;
using ECS;
namespace Core.Components
{
public class HotelComponent : IComponent
{
public Hotel Hotel;
}
} |
//-----------------------------------------------------------------------
// <copyright file="Configs.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Exporters;
namespace Akka.Benchmarks.Configurations
{
/// <summary>
/// Basic BenchmarkDotNet configuration used for microbenchmarks.
/// </summary>
public class MicroBenchmarkConfig : ManualConfig
{
public MicroBenchmarkConfig()
{
this.Add(MemoryDiagnoser.Default);
this.Add(MarkdownExporter.GitHub);
}
}
/// <summary>
/// BenchmarkDotNet configuration used for monitored jobs (not for microbenchmarks).
/// </summary>
public class MonitoringConfig : ManualConfig
{
public MonitoringConfig()
{
this.Add(MarkdownExporter.GitHub);
}
}
}
|
@model Model.Product
@{
ViewBag.Title = "Delete Product";
}
<h2>Delete Product</h2>
|
namespace FeatureSwitches.Definitions;
public class FeatureFilterDefinition
{
/// <summary>
/// Gets or sets the filter name.
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// Gets or sets the filter settings.
/// </summary>
public object? Settings { get; set; }
/// <summary>
/// Gets or sets the filter group.
/// </summary>
public string? Group { get; set; }
}
|
using System;
using System.Threading.Tasks;
using Swan.Logging;
namespace Swan.Ldap.Samples
{
public static class Program
{
/// <summary>
/// Mains the specified arguments.
/// </summary>
/// <param name="args">The arguments.</param>
public static async Task Main(string[] args)
{
await TestLdapSearch();
Terminal.Flush();
Terminal.ReadKey("Enter any key to exit . . .");
}
private static async Task TestLdapSearch()
{
try
{
using (var cn = new LdapConnection())
{
await cn.Connect("ldap.forumsys.com", 389);
await cn.Bind("uid=riemann,dc=example,dc=com", "password");
var lsc = await cn.Search("ou=scientists,dc=example,dc=com", LdapScope.ScopeSub);
while (lsc.HasMore())
{
var entry = lsc.Next();
var ldapAttributes = entry.GetAttributeSet();
$"{ldapAttributes["uniqueMember"]?.StringValue ?? string.Empty}".Info();
}
}
}
catch (Exception ex)
{
ex.Error(nameof(Main), "Error LDAP");
}
}
}
} |
namespace Havit.Blazor.Components.Web.Bootstrap
{
public enum SpinnerType
{
/// <summary>
/// <a href="https://getbootstrap.com/docs/5.0/components/spinners/#border-spinner" />
/// </summary>
Border = 1,
/// <summary>
/// <a href="https://getbootstrap.com/docs/5.0/components/spinners/#growing-spinner" />
/// </summary>
Grow = 2
}
} |
namespace MassTransit.EventHubIntegration
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using Context;
using Pipeline;
using Pipeline.Observables;
public interface IEventHubProducerContext :
ISendPipe
{
Uri HostAddress { get; }
ILogContext LogContext { get; }
SendObservable SendObservers { get; }
IMessageSerializer Serializer { get; }
Task Produce(EventDataBatch eventDataBatch, CancellationToken cancellationToken);
Task Produce(IEnumerable<EventData> eventData, SendEventOptions options, CancellationToken cancellationToken);
ValueTask<EventDataBatch> CreateBatch(CreateBatchOptions options, CancellationToken cancellationToken);
}
}
|
namespace Hotfix
{
public enum EDataType
{
DataLogin,
DataPlayer,
}
} |
#region License
// Copyright (c) Pawel Balaga https://xreactor.codeplex.com/
// Licensed under MS-PL, See License file or http://opensource.org/licenses/MS-PL
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Agdur;
using xReactor.Common;
namespace xReactor.Tests.Benchmarks
{
public static class Benchmarks
{
static Expression<Func<string>> expression1 = GetTestExpression1();
static Expression<Func<string>> GetTestExpression1()
{
Room room = new Room();
return () => string.Format("{0} with {1} pieces of furniture",
room.Name, room.Furniture.Count);
}
[Benchmark("rx object creation")]
static void BenchmarkReactiveObjectCreation()
{
new Room();
}
[Benchmark("lightweight rx object creation")]
static void BenchmarkLightweightReactiveObjectCreation()
{
new CollectorBox();
}
[Benchmark("expression compilation")]
static void BenchmarkExpressionCompilation()
{
expression1.Compile();
}
[Benchmark("expression tree parsing")]
static void BenchmarkExpressionTreeParsing()
{
ExpressionHelper.GetUsedPropertiesAndAttachListeners(expression1);
}
[Benchmark("collection: adding items on a lightweight object (no tracking)")]
static void BenchmarkLightweightCollectionItemsAdded()
{
var room = new CollectorBox();
for (int index = 0; index < Program.DefaultNumInstances; index++)
{
room.Stamps.Add(new CollectorStamp());
}
}
[Benchmark("collection: adding items on a lightweight object with tracking")]
static void BenchmarkLightweightTrackingCollectionItemsAdded()
{
var room = new TrackingCollectorBox();
for (int index = 0; index < Program.DefaultNumInstances; index++)
{
room.Stamps.Add(new CollectorStamp());
}
}
[Benchmark("collection: adding items (no tracking)")]
static void BenchmarkCollectionItemsAdded()
{
var room = new Room();
for (int index = 0; index < Program.DefaultNumInstances; index++)
{
//room.Guests.Add(new Person());
room.Guests.Add(null);
}
}
[Benchmark("collection: adding items with tracking")]
static void BenchmarkCollectionWithTrackingItemsAdded()
{
var room = new Room();
for (int index = 0; index < Program.SmallNumInstances; index++)
{
room.Furniture.Add(new Sofa());
}
}
}
public static class BenchmarkCollectionItemPropertySetterClass
{
static Room room;
static Chair chair;
static BenchmarkCollectionItemPropertySetterClass()
{
room = new Room();
chair = new Chair();
//configure benchmark
for (int index = 0; index < Program.DefaultNumInstances; index++)
{
room.Furniture.Add(new Sofa());
}
room.Furniture.Add(chair);
}
[Benchmark("collection: tracked item property setter")]
static void BenchmarkCollectionItemPropertySetter()
{
chair.NumSeats = 10;
chair.NumSeats = 20;
}
}
}
|
using System;
using System.Linq;
using DesignPatterns.Creational.Prototypes.Serialization;
using FluentAssertions;
using Xunit;
namespace DesignPatterns.Tests.Creational.Prototypes.Serialization
{
public class BinaryTreeTests
{
private readonly Random _random;
public BinaryTreeTests()
{
_random = new Random();
}
private int GetNumber() => _random.Next(0, 10001);
[Fact]
public void CopyBinaryTree_ThroughJsonSerialization()
{
var binaryTree = new BinaryTree();
var numbers = new int[1000];
for (var index = 0; index < 1000; index++)
{
var number = GetNumber();
while (numbers.Any(n => n == number))
{
number = GetNumber();
}
numbers[index] = number;
}
var root = numbers.Aggregate<int, Node>(null, (current, number) => binaryTree.Insert(current, number));
var rootCopy = root.DeepCloneThroughJsonSerialization();
rootCopy.Should()
.NotBeSameAs(root)
.And
.BeEquivalentTo(root, options => options.AllowingInfiniteRecursion());
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using FiveSQD.Parallels.Runtime;
using FiveSQD.Parallels.Runtime.Engine.Scene;
public class TabController : MonoBehaviour
{
private class TabConfig
{
public string url;
public Stack<string> previous;
public Stack<string> next;
}
public ColorBlock activeColors;
public ColorBlock inactiveColors;
public Color activeTextColor;
public Color inactiveTextColor;
public Image icon;
public TextMeshProUGUI text;
public Button close;
public Button tab;
public bool active { get; private set; }
private TabsController tabsController;
private TabConfig tabConfig;
public Scene scene { get; private set; }
public void Initialize(TabsController controller, Scene tabScene)
{
tabsController = controller;
tabConfig = new TabConfig()
{
url = "",
previous = new Stack<string>(),
next = new Stack<string>()
};
scene = tabScene;
}
public void OnPress()
{
if (tabsController == null)
{
Debug.LogError("[TabController->OnPress] Tabs controller reference not set.");
return;
}
tabsController.SetActiveTab(this);
}
public void OnClose()
{
if (tabsController == null)
{
Debug.LogError("[TabController->OnClose] Tabs controller reference not set.");
return;
}
tabsController.RemoveTab(this);
}
public void Destroy()
{
Destroy(gameObject);
}
public void Resize(float size)
{
RectTransform rt = GetComponent<RectTransform>();
if (rt == null)
{
Debug.LogError("[TabController->Resize] No Rect Transform");
return;
}
rt.sizeDelta = new Vector2(size, 100);
}
public void SetInactive()
{
active = false;
tab.colors = inactiveColors;
text.color = inactiveTextColor;
}
public void SetActive()
{
active = true;
tab.colors = activeColors;
text.color = activeTextColor;
}
public void SetName(string name)
{
text.text = name;
}
public string GetName()
{
return text.text;
}
public string GoBack()
{
if (tabConfig.previous.Count == 0)
{
Debug.LogError("[TabController->GoBack] No back history.");
return null;
}
tabConfig.next.Push(tabConfig.url);
tabConfig.url = tabConfig.previous.Pop();
return tabConfig.url;
}
public string GoForward()
{
if (tabConfig.previous.Count == 0)
{
Debug.LogError("[TabController->GoForward] No forward history.");
return null;
}
tabConfig.previous.Push(tabConfig.url);
tabConfig.url = tabConfig.next.Pop();
return tabConfig.url;
}
public string GetURL()
{
return tabConfig.url;
}
public void UpdateURL(string url)
{
tabConfig.url = url;
}
public void LoadPage(string url)
{
StartCoroutine(Parallels.VEMLManager.StartVEMLRequest(url, PageLoaded));
}
public void PageLoaded(Scene.SceneInfo sceneInfo)
{
foreach (string script in sceneInfo.scripts)
{
Parallels.JavascriptManager.RunScript(script);
}
SetName(sceneInfo.title);
}
} |
using UnityEngine;
namespace UGF.CustomSettings.Runtime.Tests
{
public static class TestSettingsFile
{
public static CustomSettingsFile<TestSettingsData> Settings { get; } = new CustomSettingsFile<TestSettingsData>
(
$"{Application.streamingAssetsPath}/test.settings.json"
);
}
}
|
using System;
using System.Collections.Generic;
namespace GoCardlessApi.Events
{
public class Event
{
public string Id { get; set; }
/// <summary>
/// See <see cref="Events.Actions"/> for possible values.
/// </summary>
public string Action { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public CustomerNotifications CustomerNotifications { get; set; }
public Details Details { get; set; }
public EventLinks Links { get; set; }
public IDictionary<string, string> Metadata { get; set; }
/// <summary>
/// See <see cref="Events.ResourceType"/> for possible values.
/// </summary>
public string ResourceType { get; set; }
}
} |
//
// Copyright 2012 Hakan Kjellerstrand
//
// 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;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Google.OrTools.ConstraintSolver;
public class DiscreteTomography
{
// default problem
static int[] default_rowsums = { 0, 0, 8, 2, 6, 4, 5, 3, 7, 0, 0 };
static int[] default_colsums = { 0, 0, 7, 1, 6, 3, 4, 5, 2, 7, 0, 0 };
static int[] rowsums2;
static int[] colsums2;
/**
*
* Discrete tomography
*
* Problem from http://eclipse.crosscoreop.com/examples/tomo.ecl.txt
* """
* This is a little 'tomography' problem, taken from an old issue
* of Scientific American.
*
* A matrix which contains zeroes and ones gets "x-rayed" vertically and
* horizontally, giving the total number of ones in each row and column.
* The problem is to reconstruct the contents of the matrix from this
* information. Sample run:
*
* ?- go.
* 0 0 7 1 6 3 4 5 2 7 0 0
* 0
* 0
* 8 * * * * * * * *
* 2 * *
* 6 * * * * * *
* 4 * * * *
* 5 * * * * *
* 3 * * *
* 7 * * * * * * *
* 0
* 0
*
* Eclipse solution by Joachim Schimpf, IC-Parc
* """
*
* See http://www.hakank.org/or-tools/discrete_tomography.py
*
*/
private static void Solve(int[] rowsums, int[] colsums)
{
Solver solver = new Solver("DiscreteTomography");
//
// Data
//
int r = rowsums.Length;
int c = colsums.Length;
Console.Write("rowsums: ");
for (int i = 0; i < r; i++)
{
Console.Write(rowsums[i] + " ");
}
Console.Write("\ncolsums: ");
for (int j = 0; j < c; j++)
{
Console.Write(colsums[j] + " ");
}
Console.WriteLine("\n");
//
// Decision variables
//
IntVar[,] x = solver.MakeIntVarMatrix(r, c, 0, 1, "x");
IntVar[] x_flat = x.Flatten();
//
// Constraints
//
// row sums
for (int i = 0; i < r; i++)
{
var tmp = from j in Enumerable.Range(0, c) select x[i, j];
solver.Add(tmp.ToArray().Sum() == rowsums[i]);
}
// cols sums
for (int j = 0; j < c; j++)
{
var tmp = from i in Enumerable.Range(0, r) select x[i, j];
solver.Add(tmp.ToArray().Sum() == colsums[j]);
}
//
// Search
//
DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);
solver.NewSearch(db);
while (solver.NextSolution())
{
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
Console.Write("{0} ", x[i, j].Value() == 1 ? "#" : ".");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine("\nSolutions: {0}", solver.Solutions());
Console.WriteLine("WallTime: {0}ms", solver.WallTime());
Console.WriteLine("Failures: {0}", solver.Failures());
Console.WriteLine("Branches: {0} ", solver.Branches());
solver.EndSearch();
}
/**
*
* Reads a discrete tomography file.
* File format:
* # a comment which is ignored
* % a comment which also is ignored
* rowsums separated by [,\s]
* colsums separated by [,\s]
*
* e.g.
* """
* 0,0,8,2,6,4,5,3,7,0,0
* 0,0,7,1,6,3,4,5,2,7,0,0
* # comment
* % another comment
* """
*
*/
private static void readFile(String file)
{
Console.WriteLine("readFile(" + file + ")");
TextReader inr = new StreamReader(file);
String str;
int lineCount = 0;
while ((str = inr.ReadLine()) != null && str.Length > 0)
{
str = str.Trim();
// ignore comments
if (str.StartsWith("#") || str.StartsWith("%"))
{
continue;
}
if (lineCount == 0)
{
rowsums2 = ConvLine(str);
}
else if (lineCount == 1)
{
colsums2 = ConvLine(str);
break;
}
lineCount++;
} // end while
inr.Close();
} // end readFile
private static int[] ConvLine(String str)
{
String[] tmp = Regex.Split(str, "[,\\s]+");
int len = tmp.Length;
int[] sums = new int[len];
for (int i = 0; i < len; i++)
{
sums[i] = Convert.ToInt32(tmp[i]);
}
return sums;
}
public static void Main(String[] args)
{
if (args.Length > 0)
{
readFile(args[0]);
Solve(rowsums2, colsums2);
}
else
{
Solve(default_rowsums, default_colsums);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Web.Db
{
public partial class Supplier : ILocation, IPostStatus
{
public Supplier()
{
SupplierPpeTypes = new HashSet<SupplierPpeType>();
SupplierNotes = new HashSet<SupplierNote>();
NeedPpeTypes = new HashSet<NeedPpeType>();
}
public long Id { get; set; }
public long? UshahidiId { get; set; }
public DateTimeOffset Timestamp { get; set; }
public int StatusId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int SupplierTypeId { get; set; }
public string SupplierTypeOther { get; set; }
public string Email { get; set; }
public string Website { get; set; }
public string PhoneNumber { get; set; }
public string ContactName { get; set; }
public string Postcode { get; set; }
public string TellUsMore { get; set; }
public decimal? Latitude { get; set; }
public decimal? Longitude { get; set; }
/// <summary>
/// Added to retain the Ushahidi capacity data as was
/// </summary>
public string CapacityNotes { get; set; }
public TransportType TransportType { get; set; }
public string TransportTypeOther { get; set; }
public virtual ICollection<SupplierPpeType> SupplierPpeTypes { get; set; }
public virtual ICollection<SupplierNote> SupplierNotes { get; set; }
public virtual ICollection<NeedPpeType> NeedPpeTypes { get; set; }
}
}
|
using AspNetCoreStarterKit.Domain.Entities.OrganizationUnits;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
namespace AspNetCoreStarterKit.Domain.Entities.Authorization
{
public class User : IdentityUser<Guid>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string ProfileImageUrl { get; set; }
public DateTime CreationTime { get; set; }
public Guid? CreatorUserId { get; set; }
public DateTime? ModificationTime { get; set; }
public Guid? ModifierUserId { get; set; }
public bool IsDeleted { get; set; }
public Guid? DeleterUserId { get; set; }
public DateTime? DeletionTime { get; set; }
public virtual ICollection<UserClaim> UserClaims { get; set; }
public virtual ICollection<UserLogin> UserLogins { get; set; }
public virtual ICollection<UserToken> UserTokens { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
public virtual ICollection<OrganizationUnitUser> OrganizationUnitUsers { get; set; }
}
}
|
namespace GodotEngine
{
public enum Error : int
{
OK = 0,
FAILED = 1,
ERR_UNAVAILABLE = 2,
ERR_UNCONFIGURED = 3,
ERR_UNAUTHORIZED = 4,
ERR_PARAMETER_RANGE_ERROR = 5,
ERR_OUT_OF_MEMORY = 6,
ERR_FILE_NOT_FOUND = 7,
ERR_FILE_BAD_DRIVE = 8,
ERR_FILE_BAD_PATH = 9,
ERR_FILE_NO_PERMISSION = 10,
ERR_FILE_ALREADY_IN_USE = 11,
ERR_FILE_CANT_OPEN = 12,
ERR_FILE_CANT_WRITE = 13,
ERR_FILE_CANT_READ = 14,
ERR_FILE_UNRECOGNIZED = 15,
ERR_FILE_CORRUPT = 16,
ERR_FILE_MISSING_DEPENDENCIES = 17,
ERR_FILE_EOF = 18,
ERR_CANT_OPEN = 19,
ERR_CANT_CREATE = 20,
ERR_PARSE_ERROR = 43,
ERROR_QUERY_FAILED = 21,
ERR_ALREADY_IN_USE = 22,
ERR_LOCKED = 23,
ERR_TIMEOUT = 24,
ERR_CANT_AQUIRE_RESOURCE = 28,
ERR_INVALID_DATA = 30,
ERR_INVALID_PARAMETER = 31,
ERR_ALREADY_EXISTS = 32,
ERR_DOES_NOT_EXIST = 33,
ERR_DATABASE_CANT_READ = 34,
ERR_DATABASE_CANT_WRITE = 35,
ERR_COMPILATION_FAILED = 36,
ERR_METHOD_NOT_FOUND = 37,
ERR_LINK_FAILED = 38,
ERR_SCRIPT_FAILED = 39,
ERR_CYCLIC_LINK = 40,
ERR_BUSY = 44,
ERR_HELP = 46,
ERR_BUG = 47,
ERR_WTF = 49
}
}
|
namespace Rocket.Chat.Net.Portability.Contracts
{
using System;
using Rocket.Chat.Net.Portability.Websockets;
public abstract class PortableWebSocketBase
{
public PortableWebSocketBase(string url)
{
}
public abstract event EventHandler<PortableMessageReceivedEventArgs> MessageReceived;
public abstract event EventHandler Closed;
public abstract event EventHandler<PortableErrorEventArgs> Error;
public abstract event EventHandler Opened;
public abstract void Open();
public abstract void Close();
public abstract void Send(string json);
}
} |
using NUnit.Framework;
namespace AdventOfCode2021;
[TestFixture]
public class Day3
{
private List<string> binaryNumbers;
private int numberOfBits;
[SetUp]
public void SetUp()
{
binaryNumbers = File.ReadAllLines("Day3.txt").ToList();
numberOfBits = binaryNumbers[0].Length;
}
[Test]
public void Part1()
{
var gammaRate = new string(Enumerable.Range(0, numberOfBits)
.Select(i => binaryNumbers.Count(c => c[i] == '1') >
binaryNumbers.Count(c => c[i] == '0') ? '1' : '0')
.ToArray());
var epsilonRate = new string(gammaRate.Select(x => x == '1' ? '0' : '1')
.ToArray());
var powerConsumption = Convert.ToInt32(gammaRate, 2) * Convert.ToInt32(epsilonRate, 2);
Assert.That(powerConsumption, Is.EqualTo(3912944));
}
[Test]
public void Part2()
{
var oxygenGeneratorRating = GetOxygenGeneratorRating();
var co2ScrubberRating = GetCo2ScrubberRating();
var lifeSupportRating = oxygenGeneratorRating * co2ScrubberRating;
Assert.That(lifeSupportRating, Is.EqualTo(4996233));
}
private int GetOxygenGeneratorRating()
{
var numbers = binaryNumbers.ToList();
for (var i = 0; i < numberOfBits; i++)
{
var mostCommonValue = numbers.Count(c => c[i] == '1') >= numbers.Count(c => c[i] == '0') ? '1' : '0';
numbers.RemoveAll(x => x[i] != mostCommonValue);
if (numbers.Count == 1) break;
}
return Convert.ToInt32(numbers.First(), 2);
}
private int GetCo2ScrubberRating()
{
var numbers = binaryNumbers.ToList();
for (var i = 0; i < numberOfBits; i++)
{
var leastCommonValue = numbers.Count(c => c[i] == '1') < numbers.Count(c => c[i] == '0') ? '1' : '0';
numbers.RemoveAll(x => x[i] != leastCommonValue);
if (numbers.Count == 1) break;
}
return Convert.ToInt32(numbers.First(), 2);
}
} |
namespace HipChatConnect.Core.Models
{
public class CapabilitiesDocument
{
public Capabilities capabilities { get; set; }
public string description { get; set; }
public string key { get; set; }
public Links links { get; set; }
public string name { get; set; }
public Vendor vendor { get; set; }
}
} |
// Copyright (c) Samuel Cragg.
//
// Licensed under the MIT license. See LICENSE file in the project root for
// full license information.
namespace Crest.Host.Diagnostics
{
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Crest.Abstractions;
/// <summary>
/// Displays the health of the service when requested.
/// </summary>
internal class HealthPage
{
private readonly ExecutingAssembly assemblyInfo;
private readonly Metrics metrics;
private readonly ProcessAdapter process;
private readonly IHtmlTemplateProvider template;
private readonly ITimeProvider time;
/// <summary>
/// Initializes a new instance of the <see cref="HealthPage"/> class.
/// </summary>
/// <param name="template">Used to format the HTML data.</param>
/// <param name="time">Used to provide the current time.</param>
/// <param name="process">
/// Used to provide information about the current process.
/// </param>
/// <param name="assemblyInfo">
/// Used to provide information about the current assembly.
/// </param>
/// <param name="metrics">Contains the application metrics.</param>
public HealthPage(
IHtmlTemplateProvider template,
ITimeProvider time,
ProcessAdapter process,
ExecutingAssembly assemblyInfo,
Metrics metrics)
{
this.template = template;
this.time = time;
this.process = process;
this.assemblyInfo = assemblyInfo;
this.metrics = metrics;
}
/// <summary>
/// Initializes a new instance of the <see cref="HealthPage"/> class.
/// </summary>
/// <remarks>
/// This constructor is only used to allow the type to be mocked in unit tests.
/// </remarks>
protected HealthPage()
{
}
/// <summary>
/// Gets the current health information of the service and writes it,
/// as HTML, to the specified stream.
/// </summary>
/// <param name="stream">The stream to write the data to.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public virtual async Task<long> WriteToAsync(Stream stream)
{
char[] htmlTempalte = this.template.Template.ToCharArray();
int insertIndex = this.template.ContentLocation;
using (var writer = new StreamWriter(stream))
{
await writer.WriteLineAsync(htmlTempalte, 0, insertIndex).ConfigureAwait(false);
await writer.WriteLineAsync("<h1>Service Health</h1>").ConfigureAwait(false);
await this.WriteSummaryAsync(writer).ConfigureAwait(false);
await this.WriteMetricsAsync(writer).ConfigureAwait(false);
await this.WriteAssembliesAsync(writer).ConfigureAwait(false);
int count = htmlTempalte.Length - insertIndex;
await writer.WriteAsync(htmlTempalte, insertIndex, count).ConfigureAwait(false);
}
// Don't include the health page size in stats
return 0;
}
private static async Task WriteTableRowAsync(TextWriter writer, string label, string value)
{
await writer.WriteAsync("<tr><td>").ConfigureAwait(false);
await writer.WriteAsync(label).ConfigureAwait(false);
await writer.WriteAsync("</td><td>").ConfigureAwait(false);
await writer.WriteAsync(WebUtility.HtmlEncode(value)).ConfigureAwait(false);
await writer.WriteLineAsync("</td></tr>").ConfigureAwait(false);
}
private async Task WriteAssembliesAsync(StreamWriter writer)
{
await writer.WriteLineAsync("<h2>Assemblies</h2><p>").ConfigureAwait(false);
foreach (ExecutingAssembly.AssemblyInfo assembly in this.assemblyInfo.GetCompileLibraries())
{
await writer.WriteAsync(WebUtility.HtmlEncode(assembly.Name)).ConfigureAwait(false);
await writer.WriteAsync(" - ").ConfigureAwait(false);
await writer.WriteAsync(WebUtility.HtmlEncode(assembly.Version)).ConfigureAwait(false);
await writer.WriteLineAsync("<br>").ConfigureAwait(false);
}
await writer.WriteAsync("</p>").ConfigureAwait(false);
}
private async Task WriteMetricsAsync(StreamWriter writer)
{
await writer.WriteLineAsync("<h2>Metrics</h2><p>").ConfigureAwait(false);
string report;
using (var reporter = new HtmlReporter())
{
this.metrics.WriteTo(reporter);
report = reporter.GenerateReport();
}
await writer.WriteAsync(report).ConfigureAwait(false);
await writer.WriteLineAsync("</p>").ConfigureAwait(false);
}
private async Task WriteSummaryAsync(TextWriter writer)
{
string FormatBytes(long value)
{
var bytes = new BytesUnit();
return bytes.Format(value);
}
string FormatTime(TimeSpan time)
{
return time.TotalHours.ToString("f0", CultureInfo.InvariantCulture) +
time.ToString(@"\:mm\:ss", CultureInfo.InvariantCulture);
}
await writer.WriteLineAsync("<h2>Summary</h2>").ConfigureAwait(false);
await writer.WriteLineAsync("<table>").ConfigureAwait(false);
await WriteTableRowAsync(
writer,
"System time",
this.time.GetUtc().ToString("u", CultureInfo.InvariantCulture)).ConfigureAwait(false);
await WriteTableRowAsync(
writer,
"Machine name",
Environment.MachineName).ConfigureAwait(false);
await WriteTableRowAsync(
writer,
"Process uptime",
FormatTime(this.process.UpTime)).ConfigureAwait(false);
await WriteTableRowAsync(
writer,
"CPU time (application)",
FormatTime(this.process.ApplicationCpuTime)).ConfigureAwait(false);
await WriteTableRowAsync(
writer,
"CPU time (system)",
FormatTime(this.process.SystemCpuTime)).ConfigureAwait(false);
await WriteTableRowAsync(
writer,
"Memory (private)",
FormatBytes(this.process.PrivateMemory)).ConfigureAwait(false);
await WriteTableRowAsync(
writer,
"Memory (working)",
FormatBytes(this.process.WorkingMemory)).ConfigureAwait(false);
await writer.WriteLineAsync("</table>").ConfigureAwait(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Kata.Properties;
using Newtonsoft.Json.Linq;
using YamlDotNet.Serialization;
namespace Kata
{
/// <inheritdoc cref="Window" />
/// <summary>
/// Interaction logic for KataWindow.xaml
/// </summary>
public partial class KataWindow : Window
{
private enum KataTypes : byte
{
Drawabox,
Music
};
private enum KataLessons : byte
{
Basics,
Forms,
Plants,
Insects,
Animals,
Objects
};
// loaded from file (when resume button pressed)
private Queue<int> _resumeSelections = new Queue<int>();
// saved to file (when hits bottom of species tree)
private Queue<int> _saveSelections = new Queue<int>();
private bool _resuming = false;
public KataWindow()
{
InitializeComponent();
}
private void PopulateList(string filePath)
{
dynamic katas = LoadYaml(filePath);
JArray array = JArray.Parse(katas.Lessons.List.ToString());
foreach (var item in array) {
ComboBox_Lesson.Items.Add(item);
}
}
private static string GetPythonPath()
{
using (StreamReader reader = new StreamReader(@"Configuration\Helper_Code\python_path.txt")) {
string line = "";
return (line = reader.ReadLine()) != null ? line : "";
}
}
private string LoadYamlToJsonPython(string yamlFileName)
{
const string pythonFileName = @"Configuration\Helper_Code\YamlToJson.py";
Process process = new Process {
StartInfo = new ProcessStartInfo {
FileName = GetPythonPath(),
Arguments = $"{pythonFileName} {yamlFileName}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
// object initializer
process.Start();
string jsonString = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
if (error.Length > 0) {
MessageBox.Show(error);
}
process.WaitForExit();
return jsonString;
}
private static dynamic LoadYaml(string file)
{
using (StreamReader r = new StreamReader(file)) {
string yamlString = r.ReadToEnd();
var yamlObject = new DeserializerBuilder().Build().Deserialize(
new StringReader(yamlString)
);
//var jsonString = LoadYamlToJsonPython(file);
// Old YamlDotNet serializer, needs support for Aliases in JSON
//
/*
var serializer = new SerializerBuilder()
.JsonCompatible()
.WithMaximumRecursion(200)
.Build();
var jsonString = serializer.Serialize(yamlObject);
*/
var serializer = new Newtonsoft.Json.JsonSerializer();
var jsonStringWriter = new StringWriter();
serializer.Serialize(jsonStringWriter, yamlObject);
var jsonString = jsonStringWriter.ToString();
var jsonObject = JObject.Parse(jsonString);
return jsonObject;
}
}
private void SaveSelections()
{
FileStream fs = null;
try {
fs = new FileStream("Configuration\\selections.txt", FileMode.Create);
using (StreamWriter writer = new StreamWriter(fs)) {
while (_saveSelections.Count > 0) {
writer.WriteLine(_saveSelections.Dequeue().ToString());
}
}
} finally {
fs?.Dispose();
}
MessageBox.Show(Properties.Resources.ResourceManager.GetString(
"String_PartialTaxonomySelected"));
Button_Resume.Visibility = Visibility.Visible;
ResetQueues();
}
private void ReadSelections()
{
ResetQueues();
using (StreamReader reader = new StreamReader("Configuration\\selections.txt")) {
string line = "";
while ((line = reader.ReadLine()) != null) {
if (int.TryParse(line, out var lineValue)) {
_resumeSelections.Enqueue(lineValue);
} else {
throw new Exception("Error parsing line from selections.txt!");
}
}
}
Button_Resume.Visibility = Visibility.Hidden;
}
private void ResetQueues()
{
// loaded from file (when resume button pressed)
_resumeSelections = new Queue<int>();
// saved to file (when hits bottom of species tree)
_saveSelections = new Queue<int>();
}
/*
*
*
*
* Private Static Methods
*
*
*
*/
// generate a random number from 0 to max, inclusive that is [0, max]
private static int RandomNumber(int max)
{
Random rng = new Random();
return rng.Next(0, max + 1);
}
private static int SelectLessonNum(dynamic katas)
{
int numLessons = katas.Lessons.Content.Count;
return RandomNumber(numLessons - 1);
}
private static int SelectExerciseNum(dynamic lesson)
{
int numExercises = lesson.Exercises.Count;
int exerciseNum = RandomNumber(numExercises - 1);
return exerciseNum;
}
private static dynamic SelectEverydayObject(int exerciseNum)
{
const string everydayObjectsFile = "Configuration\\YAML\\EverydayObjects.yaml";
dynamic everydayObjects = LoadYaml(everydayObjectsFile);
dynamic everydayObjectGroup = everydayObjects["Everyday Objects"][exerciseNum];
int exerciseCount = everydayObjectGroup.Content.Count;
int subExerciseNum = RandomNumber(exerciseCount - 1);
return everydayObjectGroup.Content[subExerciseNum];
}
/*
*
*
* Private methods
*
*
*/
private dynamic GetAnimaliaPhylum(dynamic phyla, int lessonNum)
{
dynamic selectedPhylum = null;
int selectedPhylumIndex = 0;
if (_resuming && _resumeSelections.Count > 0) {
selectedPhylumIndex = _resumeSelections.Dequeue();
selectedPhylum = phyla[selectedPhylumIndex];
} else {
_resuming = false;
int i = 0;
foreach (dynamic phylum in phyla) {
if (phylum.Taxon_Name == "Chordata" &&
lessonNum == (byte)KataLessons.Animals
) {
selectedPhylum = phylum;
selectedPhylumIndex = i;
} else if (phylum.Taxon_Name == "Arthropoda" &&
lessonNum == (byte)KataLessons.Insects
) {
selectedPhylum = phylum;
selectedPhylumIndex = i;
}
i++;
}
}
_saveSelections.Enqueue(selectedPhylumIndex);
return selectedPhylum;
}
private dynamic SelectAnimal(dynamic kingdom, dynamic exercise, int exerciseNum)
{
dynamic phylum = GetAnimaliaPhylum(kingdom.Content.Content, (int)KataLessons.Animals);
return DescendTaxon(phylum, "");
}
private dynamic SelectInsect(dynamic kingdom, dynamic exercise, int exerciseNum)
{
dynamic phylum = GetAnimaliaPhylum(kingdom.Content.Content, (int)KataLessons.Insects);
return DescendTaxon(phylum, "");
}
private int GetTaxonNum(dynamic taxonomicRank)
{
int taxonNum = 0;
if (_resuming && _resumeSelections.Count > 0) {
taxonNum = _resumeSelections.Dequeue();
} else {
_resuming = false;
taxonNum = RandomNumber(taxonomicRank.Content.Count - 1);
}
_saveSelections.Enqueue(taxonNum);
return taxonNum;
}
private dynamic PickNextTaxon(dynamic currentTaxon, string taxonString)
{
dynamic taxonomicRank = currentTaxon.Content;
if (taxonomicRank.Content != null) {
int taxonNum = GetTaxonNum(taxonomicRank);
dynamic taxon = taxonomicRank.Content[taxonNum];
if (taxonomicRank.Taxonomic_Rank == "Species" || taxonomicRank["Bottom"] != null) {
// we're done!
return taxon.Taxon_Name;
} else {
return DescendTaxon(taxon, taxonString);
}
} else {
SaveSelections();
return taxonString + " " + currentTaxon.Taxon_Name.ToString();
}
}
private dynamic DescendTaxon(dynamic currentTaxon, string taxonString)
{
try {
if (currentTaxon.Content != null) {
return PickNextTaxon(currentTaxon, taxonString + " " + currentTaxon.Taxon_Name.ToString());
} else {
SaveSelections();
return taxonString + " " + currentTaxon.Taxon_Name.ToString();
}
} catch (Exception e) {
MessageBox.Show("Could not descend taxon: got error " + e.InnerException
+ " with taxon:" + currentTaxon + " and string: " + taxonString);
return "";
}
}
private dynamic SelectPlant(dynamic kingdom, dynamic exercise, int exerciseNum)
{
return DescendTaxon(kingdom, "");
}
private dynamic GetKingdom(dynamic kingdoms, int lessonNum)
{
dynamic selectedKingdom = null;
int selectedKingdomIndex = 0;
if (_resuming && _resumeSelections.Count > 0) {
selectedKingdomIndex = _resumeSelections.Dequeue();
selectedKingdom = kingdoms[selectedKingdomIndex];
} else {
_resuming = false;
int i = 0;
foreach (dynamic kingdom in kingdoms) {
if (kingdom.Taxon_Name == "Plantae" && lessonNum == (byte) KataLessons.Plants) {
selectedKingdom = kingdom;
selectedKingdomIndex = i;
} else if (kingdom.Taxon_Name == "Animalia" && (lessonNum == (byte) KataLessons.Animals ||
lessonNum == (byte) KataLessons.Insects)) {
selectedKingdom = kingdom;
selectedKingdomIndex = i;
}
i++;
}
}
_saveSelections.Enqueue(selectedKingdomIndex);
return selectedKingdom;
}
private dynamic SelectSpecies(dynamic exercise, int lessonNum, int exerciseNum)
{
const string speciesFile = "Configuration\\YAML\\Species.yaml";
try {
File.Copy("../../" + speciesFile, speciesFile, true);
} catch (Exception e) {
MessageBox.Show(
Properties.Resources.
String_SelectSpeciesError_CouldNotUpdateSpeciesYaml
+ e.InnerException);
}
dynamic species = LoadYaml(speciesFile);
dynamic kingdom = GetKingdom(species.Kingdoms, lessonNum);
switch (lessonNum) {
case (byte)KataLessons.Plants:
return SelectPlant(kingdom, exercise, exerciseNum);
case (byte)KataLessons.Insects:
return SelectInsect(kingdom, exercise, exerciseNum);
case (byte)KataLessons.Animals:
return SelectAnimal(kingdom, exercise, exerciseNum);
default:
MessageBox.Show(
Properties.Resources.
String_SelectSpeciesError_IncorrectLesson
);
return "";
}
}
private int GetLessonNum(dynamic katas)
{
int lessonNum = 0;
if (ComboBox_Lesson.SelectedIndex >= 0) {
// handles selecting from only one lesson, for now
lessonNum = ComboBox_Lesson.SelectedIndex;
} else {
if (_resuming && _resumeSelections.Count > 0) {
lessonNum = _resumeSelections.Dequeue();
} else {
_resuming = false;
lessonNum = SelectLessonNum(katas);
}
}
_saveSelections.Enqueue(lessonNum);
return lessonNum;
}
private int GetExerciseNum(dynamic lesson)
{
int exerciseNum = 0;
if (_resuming && _resumeSelections.Count > 0) {
exerciseNum = _resumeSelections.Dequeue();
} else {
_resuming = false;
exerciseNum = SelectExerciseNum(lesson);
}
_saveSelections.Enqueue(exerciseNum);
return exerciseNum;
}
private void PickDrawaboxExerciseRandomly()
{
const string kataFile = "Configuration\\YAML\\DrawaboxKatas.yaml";
dynamic katas = LoadYaml(kataFile);
int lessonNum = GetLessonNum(katas);
dynamic lesson = null;
lesson = katas.Lessons.Content[lessonNum];
int exerciseNum = GetExerciseNum(lesson);
dynamic exercise = null;
if (exerciseNum <= lesson.Exercises.Count - 1) {
exercise = lesson.Exercises[exerciseNum];
} else {
MessageBox.Show($@"Error, exercise {exerciseNum} out of bounds, size: {lesson.Exercise.Count}!");
}
dynamic subExercise = null;
switch (lessonNum) {
case (byte)KataLessons.Objects:
subExercise = SelectEverydayObject(exerciseNum);
break;
case (byte)KataLessons.Animals:
case (byte)KataLessons.Insects:
//Kingdom Plantae exercise
case (byte)KataLessons.Plants when exerciseNum == 2:
subExercise = SelectSpecies(exercise, lessonNum, exerciseNum);
break;
// ReSharper disable once RedundantEmptySwitchSection
default:
// lesson has no sub-exercise
break;
}
string messageExercise = string.Format("Lesson: {0}\nExercise: {1}", lesson.Name, exercise);
string messageSubexercise = "";
if (subExercise != null) {
messageSubexercise = string.Format("\nSubexercise: {0}", subExercise);
}
string message = messageExercise + messageSubexercise;
Label_Result.Content = message;
}
private void PickMusicExerciseRandomly()
{
const string musicKataFile = "Configuration\\YAML\\Music.yaml";
dynamic musicKatas = LoadYaml(musicKataFile);
int bpmIndex = RandomNumber(musicKatas.BPM.Count - 1);
int bpm = musicKatas.BPM[bpmIndex];
int keyIndex = RandomNumber(musicKatas.Key.Count - 1);
string key = musicKatas.Key[keyIndex];
string message = $"BPM - {bpm}\nKey - {key}";
Label_Result.Content = message;
}
private void ButtonRandomlySelect_Click(object sender, EventArgs e)
{
switch (ComboBox_KataType.SelectedIndex) {
case (byte)KataTypes.Drawabox:
PickDrawaboxExerciseRandomly();
break;
case (byte)KataTypes.Music:
PickMusicExerciseRandomly();
break;
default:
Label_Result.Content = Properties.Resources.String_Error_NoKatTypeSelected;
break;
}
}
private void ComboBoxKataType_SelectionChanged(object sender, EventArgs e)
{
if (ComboBox_Lesson != null) {
if (ComboBox_KataType.SelectedIndex == (byte)KataTypes.Music) {
ComboBox_Lesson.Visibility = Visibility.Hidden;
} else {
ComboBox_Lesson.Visibility = Visibility.Visible;
PopulateList("Configuration\\YAML\\DrawaboxKatas.yaml");
}
}
}
private void ResetResultText()
{
Label_Result.Content = Properties.Resources.String_SelectedKata;
}
private void Reset()
{
ComboBox_KataType.SelectedIndex = -1;
ComboBox_KataType.Text = Properties.Resources.String_KataType;
ComboBox_Lesson.SelectedIndex = -1;
ComboBox_Lesson.Text = Properties.Resources.String_OnlyOneLesson;
ResetResultText();
}
private void ButtonReset_Click(object sender, EventArgs e)
{
Reset();
}
private void ButtonResume_Click(object sender, EventArgs e)
{
ResetResultText();
ReadSelections();
_resuming = true;
PickDrawaboxExerciseRandomly();
}
}
}
|
using System;
using System.Collections.Generic;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
namespace NetTopologySuite.Index.IntervalRTree
{
public abstract class IntervalRTreeNode<T>
{
public double Min { get; protected set; }
public double Max { get; protected set; }
protected IntervalRTreeNode()
{
Min = double.PositiveInfinity;
Max = double.NegativeInfinity;
}
protected IntervalRTreeNode(double min, double max)
{
Min = min;
Max = max;
}
public abstract void Query(double queryMin, double queryMax, IItemVisitor<T> visitor);
protected bool Intersects(double queryMin, double queryMax)
{
if (Min > queryMax
|| Max < queryMin)
return false;
return true;
}
/// <inheritdoc cref="object.ToString()"/>
public override string ToString()
{
return WKTWriter.ToLineString(new Coordinate(Min, 0), new Coordinate(Max, 0));
}
public class NodeComparator : IComparer<IntervalRTreeNode<T>>
{
public static NodeComparator Instance = new NodeComparator();
public int Compare(IntervalRTreeNode<T> n1, IntervalRTreeNode<T> n2)
{
double mid1 = (n1.Min + n1.Max) / 2;
double mid2 = (n2.Min + n2.Max) / 2;
if (mid1 < mid2) return -1;
if (mid1 > mid2) return 1;
return 0;
}
}
}
} |
using Microsoft.AspNetCore.SignalR;
namespace YourBrand.Payments.Hubs;
public class PaymentsHub : Hub<IPaymentsHubClient>
{
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
var httpContext = Context.GetHttpContext();
if (httpContext is not null)
{
if (httpContext.Request.Query.TryGetValue("paymentId", out var paymentId))
{
await Groups.AddToGroupAsync(Context.ConnectionId, $"payment-{paymentId}");
}
}
}
}
|
using System;
using System.Reflection;
namespace ITGlobal.Fountain.Parser
{
public class EnumValueDesc: IDeprecatableDesc, IDescriptableDesc
{
public string Description { get; set; }
public bool IsDeprecated { get; set; }
public string DeprecationCause { get; set; }
public object Value { get; set; }
public MemberInfo MemberInfo { get; set; }
public Type EnumType { get; set; }
public string JsonName { get; set; }
}
} |
namespace OmniNumbers
{
/// <summary>
/// Part of the <see cref="Number"/> responsible for math operations.
/// </summary>
/// <author>
/// Krzysztof Dobrzyński - https://github.com/Sejoslaw/OmniNumbers
/// </author>
public partial class Number
{
public static Number operator +(Number n1, Number n2) => n1.Add(n2);
public static Number operator -(Number n1, Number n2) => n1.Subtract(n2);
public static Number operator *(Number n1, Number n2) => n1.Multiply(n2);
public static Number operator /(Number n1, Number n2) => n1.Divide(n2);
public static Number operator ^(Number n1, Number n2) => n1.Power(n2);
public virtual Number Add(Number n)
{
// TODO: Add logic
}
public virtual Number Subtract(Number n)
{
// TODO: Add logic
}
public virtual Number Multiply(Number n)
{
// TODO: Add logic
}
public virtual Number Divide(Number n)
{
// TODO: Add logic
}
public virtual Number Power(Number n)
{
// TODO: Add logic
}
}
} |
using System;
namespace SharpGlyph {
public class ContextualGlyphSubstitutionSubtable {
public STXHeader stxHeader;
public uint substitutionTable;
public ushort newState;
public ushort flags;
public ushort markIndex;
public ushort currentIndex;
}
}
|
@model FreelanceTech.Models.Job
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<h4>Job</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="jobId" class="control-label"></label>
<input asp-for="jobId" class="form-control" />
<span asp-validation-for="jobId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="status" class="control-label"></label>
<input asp-for="status" class="form-control" />
<span asp-validation-for="status" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="title" class="control-label"></label>
<input asp-for="title" class="form-control" />
<span asp-validation-for="title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="category" class="control-label"></label>
<input asp-for="category" class="form-control" />
<span asp-validation-for="category" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="startDate" class="control-label"></label>
<input asp-for="startDate" class="form-control" />
<span asp-validation-for="startDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="endDate" class="control-label"></label>
<input asp-for="endDate" class="form-control" />
<span asp-validation-for="endDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="startPrice" class="control-label"></label>
<input asp-for="startPrice" class="form-control" />
<span asp-validation-for="startPrice" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="endPrice" class="control-label"></label>
<input asp-for="endPrice" class="form-control" />
<span asp-validation-for="endPrice" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="level" class="control-label"></label>
<input asp-for="level" class="form-control" />
<span asp-validation-for="level" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Payment_Amount" class="control-label"></label>
<input asp-for="Payment_Amount" class="form-control" />
<span asp-validation-for="Payment_Amount" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="customerId" class="control-label"></label>
<select asp-for="customerId" class ="form-control" asp-items="ViewBag.customerId"></select>
</div>
<div class="form-group">
<label asp-for="freelancerId" class="control-label"></label>
<input asp-for="freelancerId" class="form-control" />
<span asp-validation-for="freelancerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="contractId" class="control-label"></label>
<input asp-for="contractId" class="form-control" />
<span asp-validation-for="contractId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="businessAnalystId" class="control-label"></label>
<input asp-for="businessAnalystId" class="form-control" />
<span asp-validation-for="businessAnalystId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="comment" class="control-label"></label>
<input asp-for="comment" class="form-control" />
<span asp-validation-for="comment" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="rate" class="control-label"></label>
<input asp-for="rate" class="form-control" />
<span asp-validation-for="rate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="description" class="control-label"></label>
<input asp-for="description" class="form-control" />
<span asp-validation-for="description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="postedDate" class="control-label"></label>
<input asp-for="postedDate" class="form-control" />
<span asp-validation-for="postedDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
|
using Prism.Navigation;
using Prism.Commands;
namespace PrismSample.ViewModels
{
public class ResultPageViewModel
{
private readonly INavigationService _navigationService;
public DelegateCommand GoBackCommand { get; private set; }
public ResultPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
GoBackCommand = new DelegateCommand(GoBack);
}
private async void GoBack()
{
await _navigationService.GoBackAsync();
}
}
}
|
using System.Collections.Generic;
namespace timebot.Classes
{
public class botcommand
{
public int id { get; set; }
public ulong serverid { get; set; }
public string commandname { get; set; }
}
public class commands_json
{
public string api_key { get; set; }
public List<Command> commands { get; set; }
}
} |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Cursed.Models.Entities.Data;
namespace Cursed.Models.Context
{
public partial class CursedDataContext : DbContext
{
public CursedDataContext()
{
}
public CursedDataContext(DbContextOptions<CursedDataContext> options)
: base(options)
{
}
public virtual DbSet<Company> Company { get; set; }
public virtual DbSet<Facility> Facility { get; set; }
public virtual DbSet<License> License { get; set; }
public virtual DbSet<Operation> Operation { get; set; }
public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<ProductCatalog> ProductCatalog { get; set; }
public virtual DbSet<Recipe> Recipe { get; set; }
public virtual DbSet<RecipeInheritance> RecipeInheritance { get; set; }
public virtual DbSet<RecipeProductChanges> RecipeProductChanges { get; set; }
public virtual DbSet<Storage> Storage { get; set; }
public virtual DbSet<TechProcess> TechProcess { get; set; }
public virtual DbSet<TransactionBatch> TransactionBatch { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>(entity =>
{
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<Facility>(entity =>
{
entity.Property(e => e.Latitude).HasColumnType("decimal(8, 6)");
entity.Property(e => e.Longitude).HasColumnType("decimal(8, 6)");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<License>(entity =>
{
entity.Property(e => e.Date).HasColumnType("date");
entity.HasOne(d => d.Product)
.WithMany(p => p.License)
.HasForeignKey(d => d.ProductId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_License_Product_Id");
});
modelBuilder.Entity<Operation>(entity =>
{
entity.Property(e => e.Price).HasColumnType("decimal(9, 2)");
entity.Property(e => e.Quantity).HasColumnType("decimal(9, 2)");
entity.HasOne(d => d.Product)
.WithMany(p => p.Operation)
.HasForeignKey(d => d.ProductId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Operation_Product_Id");
entity.HasOne(d => d.StorageFrom)
.WithMany(p => p.OperationStorageFrom)
.HasForeignKey(d => d.StorageFromId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Operation_StorageFrom_Id");
entity.HasOne(d => d.StorageTo)
.WithMany(p => p.OperationStorageTo)
.HasForeignKey(d => d.StorageToId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Operation_StorageTo_Id");
entity.HasOne(d => d.Transaction)
.WithMany(p => p.Operation)
.HasForeignKey(d => d.TransactionId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Operation_Transaction_Id");
});
modelBuilder.Entity<Product>(entity =>
{
entity.Property(e => e.Price).HasColumnType("decimal(9, 2)");
entity.Property(e => e.Quantity).HasColumnType("decimal(9, 2)");
entity.Property(e => e.QuantityUnit)
.IsRequired()
.HasMaxLength(3);
entity.Property(e => e.Uid).HasColumnName("UId");
entity.HasOne(d => d.Storage)
.WithMany(p => p.Product)
.HasForeignKey(d => d.StorageId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Product_Storage_Id");
entity.HasOne(d => d.U)
.WithMany(p => p.Product)
.HasForeignKey(d => d.Uid)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Product_ProductCatalog_Id");
});
modelBuilder.Entity<ProductCatalog>(entity =>
{
entity.Property(e => e.Cas)
.HasColumnName("CAS")
.IsRequired();
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<Recipe>(entity =>
{
entity.Property(e => e.Content).IsRequired();
});
modelBuilder.Entity<RecipeInheritance>(entity =>
{
//entity.HasNoKey();
entity.HasKey(e => new { e.ChildId, e.ParentId })
.HasName("CK_RecipeInheritance_ChildId_ParentId");
entity.HasOne(d => d.Child)
.WithMany(p => p.RecipeInheritanceChild)
.HasForeignKey(d => d.ChildId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_RecipeInheritance_Recipe_CId");
entity.HasOne(d => d.Parent)
.WithMany(p => p.RecipeInheritanceParent)
.HasForeignKey(d => d.ParentId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_RecipeInheritance_Recipe_PId");
});
modelBuilder.Entity<RecipeProductChanges>(entity =>
{
entity.HasKey(e => new { e.RecipeId, e.ProductId, e.Type })
.HasName("CK_RecipeProductChanges_RecipeId_ProductId_Type");
entity.Property(e => e.Type)
.HasMaxLength(16)
.IsUnicode(false);
entity.Property(e => e.Quantity).HasColumnType("decimal(9, 2)");
entity.HasOne(d => d.Product)
.WithMany(p => p.RecipeProductChanges)
.HasForeignKey(d => d.ProductId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_RecipeProductChanges_ProductCatalog_Id");
entity.HasOne(d => d.Recipe)
.WithMany(p => p.RecipeProductChanges)
.HasForeignKey(d => d.RecipeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_RecipeProductChanges_Recipe_Id");
});
modelBuilder.Entity<Storage>(entity =>
{
entity.Property(e => e.Latitude).HasColumnType("decimal(8, 6)");
entity.Property(e => e.Longitude).HasColumnType("decimal(8, 6)");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
entity.HasOne(d => d.Company)
.WithMany(p => p.Storage)
.HasForeignKey(d => d.CompanyId)
.HasConstraintName("FK_Storage_Company_Id");
});
modelBuilder.Entity<TechProcess>(entity =>
{
//entity.HasNoKey();
entity.HasKey(e => new { e.FacilityId, e.RecipeId })
.HasName("CK_TechProcess_FacilityId_RecipeId");
entity.Property(e => e.DayEfficiency).HasColumnType("decimal(9, 2)");
entity.HasOne(d => d.Facility)
.WithMany(p => p.TechProcess)
.HasForeignKey(d => d.FacilityId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_TechProcess_Facility_Id");
entity.HasOne(d => d.Recipe)
.WithMany(p => p.TechProcess)
.HasForeignKey(d => d.RecipeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_TechProcess_Recipe_Id");
});
modelBuilder.Entity<TransactionBatch>(entity =>
{
entity.Property(e => e.Date).HasColumnType("date");
entity.Property(e => e.IsOpen)
.IsRequired();
entity.Property(e => e.Type)
.IsRequired()
.HasMaxLength(16)
.IsUnicode(false);
entity.HasOne(d => d.Company)
.WithMany(p => p.TransactionBatch)
.HasForeignKey(d => d.CompanyId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Operation_Company_Id");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
|
using GenerationAttributes;
public static class MacroAssembly2
{
public static void test() {
var s = MacroAssembly1.macro1(42);
}
[LazyProperty] public static string lazyTest {
get { return "str"; }
}
[LazyProperty] public static string lazyTest2 => "str";
[Implicit] static int xz;
public static void x() {
Generic2<int, bool>.NesetedGeneric<string>.withImplicit();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cocon90.Db.Common.Data
{
public enum DbTypeEnum
{
SqlServer = 0,
Mysql = 1,
Sqlite = 2
}
}
|
using System;
using System.Text;
using Bonsai.Exceptions;
namespace Bonsai.Persistence.Helpers
{
public class PasswordHelper
{
public PasswordHelper()
{
}
public void CreatePasswordHashAndSalt(string password, out byte[] hash, out byte[] salt)
{
if (string.IsNullOrWhiteSpace(password))
throw new ValidationException("Password cannot be empty!");
using (var hmac = new System.Security.Cryptography.HMACSHA512())
{
salt = hmac.Key;
hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
}
}
public bool VerifyPassword(string password, byte[] hash, byte[] salt)
{
if (string.IsNullOrWhiteSpace(password))
throw new ValidationException("Password cannot be empty!");
using (var hmac = new System.Security.Cryptography.HMACSHA512(salt))
{
var passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
for (int i = 0; i < passwordHash.Length; i++)
{
if (passwordHash[i] != hash[i])
return false;
}
}
return true;
}
}
}
|
using MinecraftMappings.Internal.Textures.Block;
namespace MinecraftMappings.Minecraft.Java.Textures.Block
{
public class NetheriteBlock : JavaBlockTexture
{
public NetheriteBlock() : base("Netherite Block")
{
AddVersion("netherite_block");
//.WithDefaultModel<Java.Models.Block.NetheriteBlock>()
//.MapsToBedrockBlock<MinecraftMappings.Minecraft.Bedrock.Textures.Block.NetheriteBlock>();
}
}
}
|
namespace Labyrinth.Console
{
using System;
using Labyrinth.Common;
using Labyrinth.Common.Enums;
using Labyrinth.Logic.Interfaces;
/// <summary>
/// Interacts with console user, process commands.
/// </summary>
public class ConsoleInterface : IUserInterface
{
/// <summary>
/// Gets the input text from the user.
/// </summary>
/// <returns>The input as <see cref="System.String"/></returns>
public string GetUserInput()
{
var input = Console.ReadLine();
return input;
}
/// <summary>
/// Get user input from keyboard
/// </summary>
public string GetButtonInput()
{
var input = Console.ReadKey();
return input.Key.ToString().ToUpper();
}
/// <summary>
/// Process input from the user.
/// </summary>
/// <returns>Command for execute</returns>
public Commands GetCommandFromInput()
{
string input = this.GetButtonInput();
switch (input)
{
case GlobalConstants.ExitCommand:
return Commands.Exit;
case GlobalConstants.Exit:
return Commands.Exit;
case GlobalConstants.HighScoreCommand:
return Commands.HighScore;
case GlobalConstants.RestartCommand:
return Commands.Restart;
case GlobalConstants.UpKeyCommand:
return Commands.MoveUp;
case GlobalConstants.DownKeyCommand:
return Commands.MoveDown;
case GlobalConstants.LeftKeyCommand:
return Commands.MoveLeft;
case GlobalConstants.RigthKeyCommand:
return Commands.MoveRight;
case GlobalConstants.LevelA:
return Commands.LevelA;
case GlobalConstants.LevelB:
return Commands.LevelB;
case GlobalConstants.LevelC:
return Commands.LevelC;
case GlobalConstants.SaveCommand:
return Commands.Save;
case GlobalConstants.LoadCommand:
return Commands.Load;
case GlobalConstants.StartCommand:
return Commands.Start;
case GlobalConstants.HowToPlayCommand:
return Commands.HowTo;
default:
return Commands.Invalid;
}
}
/// <summary>
/// Method for ending game
/// </summary>
public void ExitGame()
{
Environment.Exit(0);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class I_am_an_Object : MonoBehaviour
{
private Transform target;
public Transform angle;
public GameObject Explosion_PF;
const int Player_Layer = 3, Object_Layer = 6;
private float Health, MaxHealth;
private Rigidbody2D rb;
private bool isMoving;
private Animator anim;
private void Start()
{
gameObject.layer = Object_Layer;
anim = gameObject.GetComponent<Animator>();
rb = gameObject.GetComponent<Rigidbody2D>();
MaxHealth = 5; Health = MaxHealth;
}
private void Update()
{
if (isMoving)
{
if (rb.velocity == Vector2.zero)
{
isMoving = false;
ShortenFuse();
}
}
}
public void PunchMe(float f, Quaternion r)
{
if (gameObject.CompareTag("Bomb"))
{
angle.rotation = r;
rb.AddForce(r * Vector2.left * 7500000, ForceMode2D.Impulse);
isMoving = true;
}
if (gameObject.CompareTag("Block"))
{
Health -= f;
if (Health <= 0)
{
anim.SetTrigger("Rubble_Crumble");
GameManager.PLAYER.GetComponent<AudioSource>().clip = GameManager.PLAYER.FindSound("Rubble_Break2");
GameManager.PLAYER.GetComponent<AudioSource>().Play();
}
else
{
float d = ((Health - MaxHealth) / MaxHealth) * -1;
// Debug.Log(Health + " of " + MaxHealth + " is " + (d * 100) + "%");
anim.SetFloat("Damage", d);
GameManager.PLAYER.GetComponent<AudioSource>().clip = GameManager.PLAYER.FindSound("Rubble_Break");
GameManager.PLAYER.GetComponent<AudioSource>().Play();
}
}
}
public void BlastMe()
{
anim.SetTrigger("Rubble_Crumble");
GameManager.PLAYER.GetComponent<AudioSource>().clip = GameManager.PLAYER.FindSound("Rubble_Break2");
GameManager.PLAYER.GetComponent<AudioSource>().Play();
}
public void Land()
{
if(gameObject.CompareTag("Block"))GetComponent<BoxCollider2D>().isTrigger = false;
if(gameObject.CompareTag("Bomb"))GetComponent<CircleCollider2D>().isTrigger = false;
Collider2D[] col = Physics2D.OverlapBoxAll(transform.position, new Vector2(1, 1), 0);
for (int _i = 0; _i < col.Length; _i++)
if (col[_i].CompareTag("Player") && gameObject.CompareTag("Block"))
{
anim.SetTrigger("Rubble_Crumble");
GameManager.PLAYER.Player_Death();
}
}
private void ShortenFuse()
{
if (gameObject.tag == "Bomb") anim.SetTrigger("Short_Fuse");
}
public void Boom()
{
Instantiate(Explosion_PF, transform.position, Quaternion.identity);
Destroy(gameObject);
}
public void DefuseBomb()
{
if (!isMoving)
{
Destroy(gameObject);
}
}
}
|
/*
* Copyright (c) Johnny Z. All rights reserved.
*
* https://github.com/StormHub/NetUV
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com)
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.NetUV.Channels
{
using DotNetty.NetUV.Handles;
internal interface IStreamConsumer<in T>
where T : StreamHandle
{
void Consume(T stream, IStreamReadCompletion readCompletion);
}
}
|
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CommonGUI
{
public class PopUpPanel : Form
{
bool isShowingDialogueBox = false;
public PopUpPanel ()
{
ShowInTaskbar = false;
FormBorderStyle = FormBorderStyle.None;
}
protected override void OnDeactivate (EventArgs e)
{
base.OnDeactivate(e);
if (!isShowingDialogueBox)
{
// Close();
}
}
public DialogResult ShowDialogueBox(string message, MessageBoxButtons buttons, string caption = "")
{
isShowingDialogueBox = true;
DialogResult result = MessageBox.Show(TopLevelControl, message, caption, buttons);
isShowingDialogueBox = false;
return result;
}
public void Show (Control parent, int x, int y, int width, int height)
{
Show(parent, new Rectangle (x, y, width, height));
}
public void Show (Control parent, Rectangle rectangle)
{
Bounds = MapRectangle(parent, parent.TopLevelControl, rectangle);
Show(parent.TopLevelControl);
Bounds = MapRectangle(parent, parent.TopLevelControl, rectangle);
Select();
}
public Rectangle MapRectangle (Control from, Control to, Rectangle rectangle)
{
Point topLeftFrom = new Point (rectangle.Left, rectangle.Top);
Point bottomRightFrom = new Point (rectangle.Right, rectangle.Bottom);
Point topLeftTo = to.PointToClient(from.PointToScreen(topLeftFrom));
Point bottomRightTo = to.PointToClient(from.PointToScreen(bottomRightFrom));
return new Rectangle (topLeftTo.X, topLeftTo.Y, bottomRightTo.X - topLeftTo.X, bottomRightTo.Y - topLeftTo.Y);
}
}
} |
using System.Collections.Generic;
using JoyGodot.Assets.Scripts.Entities.Abilities;
using JoyGodot.Assets.Scripts.Helpers;
namespace JoyGodot.Assets.Scripts.Items
{
public struct IdentifiedItem
{
public string name;
public string description;
public int value;
public IEnumerable<IAbility> abilities;
public int weighting;
public int lightLevel;
public IEnumerable<string> skills;
public IDictionary<string, int> materials;
public IEnumerable<string> tags;
public float size;
public IEnumerable<string> slots;
public string spriteSheet;
public int range;
public IEnumerable<IEnumerable<BaseItemType>> components;
public IdentifiedItem(
string nameRef,
IEnumerable<string> tagsRef,
string descriptionRef,
int valueRef,
IEnumerable<IAbility> abilitiesRef,
int weightingRef,
IEnumerable<string> skills,
IDictionary<string, int> materialsRef,
float sizeRef,
IEnumerable<string> slotsRef,
string spriteSheetRef,
int range = 1,
IEnumerable<IEnumerable<BaseItemType>> componentsRef = null,
int lightLevelRef = 0)
{
this.name = nameRef;
this.tags = tagsRef;
this.components = componentsRef ?? new List<IEnumerable<BaseItemType>>();
this.description = descriptionRef;
this.value = valueRef;
this.abilities = abilitiesRef;
this.weighting = weightingRef;
this.skills = skills;
this.materials = materialsRef;
this.size = sizeRef;
this.slots = slotsRef;
this.spriteSheet = spriteSheetRef;
this.lightLevel = lightLevelRef;
this.range = range;
}
}
public struct UnidentifiedItem
{
public string name;
public string description;
public string identifiedName;
public UnidentifiedItem(string nameRef, string descriptionRef,
string identifiedName)
{
this.name = nameRef;
this.description = descriptionRef;
this.identifiedName = identifiedName;
}
}
} |
namespace Atlasd.Battlenet.Protocols.Udp
{
enum Messages : byte
{
PKT_STORM = 0x00,
PKT_CLIENTREQ = 0x03,
PKT_SERVERPING = 0x05,
PKT_KEEPALIVE = 0x07,
PKT_CONNTEST = 0x08,
PKT_CONNTEST2 = 0x09,
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using Photon.Pun;
using UnityEngine.UI;
using Photon.Realtime;
public class ScoreManager : MonoBehaviourPunCallbacks, IPunObservable
{
//public static ScoreManager instance;
public int value = 1;
public TextMeshProUGUI text;
public TextMeshProUGUI healthtext;
int score;
private Rigidbody2D myRigidBody;
public float sec = 5f;
public Joystick joystick;
private float curHealth = 200;
private float minHealth = 0;
private float maxHealth = 200;
PlayerMovement playermovement;
public int currentPlayersIN = 0;
public int startingPlayers = 0;
public int position = 0;
private bool isWinner = false;
GameObject coin;
public GameObject endUI;
//public float damageTaken = 20;
// Start is called before the first frame update
void Start()
{
joystick = GetComponent<PlayerMovement>().joystick;
playermovement = gameObject.GetComponent<PlayerMovement>();
startingPlayers = PhotonNetwork.CurrentRoom.PlayerCount;
currentPlayersIN = startingPlayers;
Debug.Log(startingPlayers.ToString());
Debug.Log(isWinner.ToString());
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Coin")
{
//if (photonView.IsMine)
//{
coin = collision.gameObject;
Destroy(coin);
ChangeScore(value);
//}
}
StartCoroutine(MyCoroutine(collision));
}
private bool condition(Collider2D collision)
{
Player owner = collision.gameObject.GetComponent<Bullet>().Owner;
return (owner != PhotonNetwork.LocalPlayer);
}
IEnumerator MyCoroutine(Collider2D collision)
{
if (collision.gameObject.tag == "Bullet")
{
if (condition(collision))
{
gameObject.GetComponent<Animator>().Play("PlayerHurt");
if (photonView.IsMine)
{
photonView.RPC("Damage", RpcTarget.AllBuffered);
playermovement.disconnectflag = true;
playermovement.DisconnectController();
yield return new WaitForSeconds(sec); //Wait one frame
playermovement.disconnectflag = false;
playermovement.ConnectController();
}
}
else
{
if(gameObject.tag == "Player")
{
Physics2D.IgnoreCollision(gameObject.GetComponent<Collider2D>(),collision);
}
if(gameObject.tag == "Enemy")
gameObject.GetComponent<Animator>().Play("PlayerHurt");
}
}
}
[PunRPC]
void Damage()
{
curHealth -= 20;
/*if (curHealth == minHealth)
{
Die();
Debug.Log("placed " + position.ToString() + '/' + startingPlayers.ToString());
Debug.Log(isWinner.ToString());
//FindObjectOfType<PauseMenu>().EndGame();
EndGame.info = "placed " + position.ToString() + '/' + startingPlayers.ToString();
Debug.Log("Damage Pinged");
FindObjectOfType<EndGame>().EndGamePanel();
}*/
}
void Update(){
if(joystick == null)
{
joystick = GetComponent<PlayerMovement>().joystick;
}
if (curHealth > maxHealth)
{
curHealth = maxHealth;
}
if (curHealth < minHealth)
{
curHealth = minHealth;
}
if (curHealth == minHealth)
{
Die();
}
/*if (currentPlayersIN == 1 && isalive)
{
isWinner = true;
Debug.Log("is winner pinged" + isWinner.ToString());
position = currentPlayersIN;
}
else
{
Debug.Log("is winner pinged" + isWinner.ToString());
isWinner = false;
}
if (isWinner)
{
EndGame.info = "WINNER!";
FindObjectOfType<EndGame>().EndGamePanel();
}*/
}
public void Die()
{
/*if(GetComponent<PhotonView>().InstantiationId == 0)
{
Destroy(gameObject);
}
else
{
if (PhotonNetwork.IsMasterClient)
{
PhotonNetwork.Destroy(gameObject);
}
}*/
position = currentPlayersIN;
currentPlayersIN -= 1;
photonView.RPC("RPC_UpdatePlayerCount", RpcTarget.AllBuffered, currentPlayersIN);
this.gameObject.SetActive(false);
//EndGame.info = "YOU PLACED " + position.ToString() + '/' + startingPlayers.ToString();
//PauseMenu.EndGame();
//endUI.SetActive(true);
//FindObjectOfType<EndGame>().EndGamePanel();
Debug.Log("Die Pinged");
//PhotonNetwork.LeaveRoom();
EndGame.info = "YOU PLACED " + position.ToString() + '/' + startingPlayers.ToString();
Debug.Log("Winner Pinged");
FindObjectOfType<EndGame>().EndGamePanel();
}
[PunRPC]
public void RPC_UpdatePlayerCount(int playerCountSyncInt)
{
currentPlayersIN = playerCountSyncInt;
//playerCountText.text = playerCount.ToString();
}
void FixedUpdate()
{
healthtext.text = curHealth.ToString();
}
public void ChangeScore(int coinValue)
{
score += coinValue;
text.text = score.ToString();
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
// We own this player: send the others our data
stream.SendNext(score);
stream.SendNext(text.text);
stream.SendNext(curHealth);
}
else
{
// Network player, receive data
score = (int)stream.ReceiveNext();
text.text = (string)stream.ReceiveNext();
curHealth = (float)stream.ReceiveNext();
}
}
}
|
using System;
using System.IO;
using System.Net.Sockets;
using NewLife.Messaging;
using NewLife.Net.Sockets;
using NewLife.Reflection;
namespace NewLife.Net.Common
{
/// <summary>网络服务消息提供者</summary>
/// <remarks>
/// 服务端是异步接收,在处理消息时不方便进一步了解网络相关数据,可通过<see cref="Message.UserState"/>附带用户会话。
/// 采用线程静态的弱引用<see cref="Session"/>来保存用户会话,便于发送消息。
/// </remarks>
public class ServerMessageProvider : MessageProvider
{
private NetServer _Server;
/// <summary>网络会话</summary>
public NetServer Server
{
get { return _Server; }
set
{
_Server = value;
if (value != null)
MaxMessageSize = value.ProtocolType == ProtocolType.Udp ? 1472 : 1460;
else
MaxMessageSize = 0;
}
}
/// <summary>实例化一个网络服务消息提供者</summary>
/// <param name="server"></param>
public ServerMessageProvider(NetServer server)
{
Server = server;
server.Received += server_Received;
}
/// <summary>当前会话</summary>
[ThreadStatic]
private static WeakReference<ISocketSession> Session = null;
void server_Received(object sender, ReceivedEventArgs e)
{
var session = sender as ISocketSession;
Session = new WeakReference<ISocketSession>(session);
var stream = e.Stream;
//// 如果上次还留有数据,复制进去
//if (session.Stream != null && session.Stream.Position < session.Stream.Length)
//{
// // 这个流是上一次的完整数据,位置在最后,直接合并即可
// var ms = session.Stream;
// var p = ms.Position;
// ms.Position = ms.Length;
// stream.CopyTo(ms);
// ms.Position = p;
// stream = ms;
//}
OnReceive(session, stream);
}
/// <summary>收到数据流</summary>
/// <param name="session"></param>
/// <param name="stream"></param>
protected virtual void OnReceive(ISocketSession session, Stream stream)
{
try
{
Process(stream, session, session.Remote);
//// 如果还有剩下,写入数据流,供下次使用
//if (stream.Position < stream.Length)
//{
// var ms = new MemoryStream();
// stream.CopyTo(ms);
// ms.Position = 0;
// session.Stream = ms;
//}
//else
// session.Stream = null;
}
catch (Exception ex)
{
if (NetHelper.Debug) NetHelper.WriteLog(ex.ToString());
// 去掉内部异常,以免过大
if (ex.InnerException != null) ex.SetValue("_innerException", null);
var msg = new ExceptionMessage() { Value = ex };
//session.Send(msg.GetStream());
OnSend(msg.GetStream());
//// 出错后清空数据流,避免连锁反应
//session.Stream = null;
}
}
/// <summary>发送数据流。</summary>
/// <param name="stream"></param>
protected override void OnSend(Stream stream)
{
var session = Session.Target;
// 如果为空,这里让它报错,否则无法查找问题所在
//if (session != null) session.Send(stream);
session.Send(stream);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Xml.Linq;
namespace Novacode
{
internal static class Extensions
{
internal static string ToHex(this Color source)
{
byte red = source.R;
byte green = source.G;
byte blue = source.B;
string redHex = red.ToString("X");
if (redHex.Length < 2)
redHex = "0" + redHex;
string blueHex = blue.ToString("X");
if (blueHex.Length < 2)
blueHex = "0" + blueHex;
string greenHex = green.ToString("X");
if (greenHex.Length < 2)
greenHex = "0" + greenHex;
return string.Format("{0}{1}{2}", redHex, greenHex, blueHex);
}
public static void Flatten(this XElement e, XName name, List<XElement> flat)
{
// Add this element (without its children) to the flat list.
XElement clone = CloneElement(e);
clone.Elements().Remove();
// Filter elements using XName.
if (clone.Name == name)
flat.Add(clone);
// Process the children.
if (e.HasElements)
foreach (XElement elem in e.Elements(name)) // Filter elements using XName
elem.Flatten(name, flat);
}
static XElement CloneElement(XElement element)
{
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n =>
{
XElement e = n as XElement;
if (e != null)
return CloneElement(e);
return n;
}
)
);
}
public static string GetAttribute(this XElement el, XName name, string defaultValue = "")
{
var attr = el.Attribute(name);
if (attr != null)
return attr.Value;
return defaultValue;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Merge;
/// <summary>
/// 排序算法类模板。
/// </summary>
public abstract class BaseSort
{
/// <summary>
/// 对数组 a 进行排序,用各种不同的方式进行实现。
/// </summary>
/// <typeparam name="T">用于排序的类型。</typeparam>
/// <param name="a">需要排序的数组。</param>
public abstract void Sort<T>(T[] a) where T : IComparable<T>;
/// <summary>
/// 比较第一个参数是否小于第二个参数。
/// </summary>
/// <param name="v">第一个参数。</param>
/// <param name="w">第二个参数。</param>
/// <returns>如果第一个参数小于第二个参数则返回 true,
/// 否则返回 false。</returns>
protected bool Less<T>(T v, T w) where T : IComparable<T>
{
return v.CompareTo(w) < 0;
}
/// <summary>
/// 使用指定的比较器比较第一个参数是否小于第二个参数。
/// </summary>
/// <typeparam name="T">比较的元素类型。</typeparam>
/// <param name="v">比较的第一个元素。</param>
/// <param name="w">比较的第二个元素</param>
/// <param name="c">比较器。</param>
/// <returns>如果 <paramref name="v"/> 小于 <paramref name="w"/> 返回 <c>true</c>,否则返回 <c>false</c>。</returns>
protected bool Less<T>(T v, T w, IComparer<T> c)
{
return c.Compare(v, w) < 0;
}
/// <summary>
/// 交换数组中下标为 i, j 的两个元素。
/// </summary>
/// <typeparam name="T">元素的类型。</typeparam>
/// <param name="a">元素所在的数组。</param>
/// <param name="i">需要交换的第一个元素。</param>
/// <param name="j">需要交换的第二个元素。</param>
protected void Exch<T>(T[] a, int i, int j)
{
var t = a[i];
a[i] = a[j];
a[j] = t;
}
/// <summary>
/// 将数组的内容打印在一行中。
/// </summary>
/// <param name="a">需要打印的数组。</param>
protected void Show<T>(T[] a) where T : IComparable<T>
{
for (var i = 0; i < a.Length; i++)
{
Console.Write(a[i] + " ");
}
Console.WriteLine();
}
/// <summary>
/// 检查数组是否有序(升序)。
/// </summary>
/// <param name="a">需要检查的数组。</param>
/// <returns>有序则返回 true,否则返回 false。</returns>
public bool IsSorted<T>(T[] a) where T : IComparable<T>
{
for (var i = 1; i < a.Length; i++)
{
if (Less(a[i], a[i - 1]))
return false;
}
return true;
}
/// <summary>
/// 检查数组是否有序。(使用指定的比较器)
/// </summary>
/// <param name="a">需要检查的数组。</param>
/// <param name="c">比较器。</param>
/// <returns>有序则返回 true,否则返回 false。</returns>
public bool IsSorted<T>(T[] a, IComparer<T> c)
{
for (var i = 1; i < a.Length; i++)
{
if (Less(a[i], a[i - 1], c))
return false;
}
return true;
}
/// <summary>
/// 检查数组在范围 [lo, hi] 内是否有序(升序)。
/// </summary>
/// <param name="a">需要检查的数组。</param>
/// <param name="lo">检查范围的下界。</param>
/// <param name="hi">检查范围的上界。</param>
/// <returns>有序则返回 true,否则返回 false。</returns>
public bool IsSorted<T>(T[] a, int lo, int hi) where T : IComparable<T>
{
for (var i = lo + 1; i <= hi; i++)
{
if (Less(a[i], a[i - 1]))
return false;
}
return true;
}
/// <summary>
/// 检查数组在指定范围内是否有序。(使用指定的比较器)
/// </summary>
/// <typeparam name="T">数组的元素类型。</typeparam>
/// <param name="a">需要检查的数组。</param>
/// <param name="lo">检查范围的下界。</param>
/// <param name="hi">检查范围的上界。</param>
/// <param name="c">比较器。</param>
/// <returns>有序则返回 true,否则返回 false。</returns>
public bool IsSorted<T>(T[] a, int lo, int hi, IComparer<T> c)
{
for (var i = lo + 1; i <= hi; i++)
{
if (Less(a[i], a[i - 1], c))
return false;
}
return true;
}
} |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SimplCommerce.Infrastructure.Data;
using SimplCommerce.Infrastructure.Web;
using SimplCommerce.Module.Core.Extensions;
using SimplCommerce.Module.Orders.Models;
using SimplCommerce.Module.Reviews.Areas.Reviews.ViewModels;
using SimplCommerce.Module.Reviews.Models;
namespace SimplCommerce.Module.Reviews.Areas.Reviews.Components
{
public class ReviewViewComponent : ViewComponent
{
private readonly IRepository<Review> _reviewRepository;
private readonly IWorkContext _workContext;
private readonly IRepository<OrderItem> _orderItemRepository;
public ReviewViewComponent(IRepository<Review> reviewRepository, IWorkContext workContext, IRepository<OrderItem> orderItemRepository )
{
_reviewRepository = reviewRepository;
_workContext = workContext;
_orderItemRepository = orderItemRepository;
}
public async Task<IViewComponentResult> InvokeAsync(long entityId, string entityTypeId)
{
var model = new ReviewVm
{
EntityId = entityId,
EntityTypeId = entityTypeId
};
model.Items.Data = await _reviewRepository
.Query()
.Where(x => (x.EntityId == entityId) && (x.EntityTypeId == entityTypeId) && (x.Status == ReviewStatus.Approved))
.OrderByDescending(x => x.CreatedOn)
.Select(x => new ReviewItem
{
Id = x.Id,
Title = x.Title,
Rating = x.Rating,
Comment = x.Comment,
ReviewerName = x.ReviewerName,
CreatedOn = x.CreatedOn,
Replies = x.Replies
.Where(r => r.Status == ReplyStatus.Approved)
.OrderByDescending(r => r.CreatedOn)
.Select(r => new ViewModels.Reply
{
Comment = r.Comment,
ReplierName = r.ReplierName,
CreatedOn = r.CreatedOn
})
.ToList()
}).ToListAsync();
model.ReviewsCount = model.Items.Data.Count;
model.Rating1Count = model.Items.Data.Count(x => x.Rating == 1);
model.Rating2Count = model.Items.Data.Count(x => x.Rating == 2);
model.Rating3Count = model.Items.Data.Count(x => x.Rating == 3);
model.Rating4Count = model.Items.Data.Count(x => x.Rating == 4);
model.Rating5Count = model.Items.Data.Count(x => x.Rating == 5);
if (User.Identity.IsAuthenticated)
{
var user = await _workContext.GetCurrentUser();
model.LoggedUserName = user.FullName;
var query = _orderItemRepository.Query().Where(x => x.Order.CustomerId == user.Id && (x.Product.Id == entityId || x.Product.LinkedProductLinks.Any(i => i.Product.Id == entityId)));
if(query.Count() > 0)
{
model.HasBoughtProduct = true;
}
else
{
model.HasBoughtProduct = false;
}
}
else
{
model.LoggedUserName = string.Empty;
model.HasBoughtProduct = false;
}
return View(this.GetViewPath(), model);
}
}
}
|
using System.Collections.Generic;
namespace TextComposerLib.Code.JavaScript
{
public interface IJsCodeHtmlPageGenerator
{
string HtmlTemplateText { get; }
string HtmlPageTitle { get; }
IEnumerable<string> JavaScriptIncludes { get; }
string GetJavaScriptCode();
}
} |
namespace Machete.X12Schema.V5010.Maps
{
using X12;
using X12.Configuration;
public class LoopL0_304Map :
X12LayoutMap<LoopL0_304, X12Entity>
{
public LoopL0_304Map()
{
Id = "Loop_L0_304";
Name = "Loop L0";
Segment(x => x.LineItemQuantityAndWeight, 0);
Segment(x => x.Measurements, 1);
Segment(x => x.ExtendedReferenceInformation, 2);
Layout(x => x.LoopPO4, 3);
Segment(x => x.QuantityInformation, 4);
Segment(x => x.Measurement, 5);
Segment(x => x.HazardousCertification, 6);
Layout(x => x.LoopPAL, 7);
Layout(x => x.LoopCTP, 8);
Segment(x => x.DescriptionMarksAndNumbers, 9);
Segment(x => x.ItemIdentification, 10);
Segment(x => x.AlternateLadingDescription, 11);
Segment(x => x.YesNoQuestion, 12);
Layout(x => x.LoopL1, 13);
Segment(x => x.TariffReference, 14);
Layout(x => x.LoopSAC, 15);
Layout(x => x.LoopL9, 16);
Segment(x => x.ExportLicense, 17);
Segment(x => x.ImportLicense, 18);
Layout(x => x.LoopC8, 19);
Layout(x => x.LoopH1, 20);
Layout(x => x.LoopLH1, 21);
Layout(x => x.LoopN1, 22);
}
}
} |
/* ====================================================================
This file is part of the fyiReporting RDL project.
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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace fyiReporting.RDL
{
internal class DrawEllipse : DrawBase
{
internal DrawEllipse(Single Xin, Single Yin, Single WidthIn, Single HeightIn, System.Collections.Hashtable ObjectTableIn)
{
X = Xin;
Y = Yin;
Width = WidthIn;
Height = HeightIn;
items = new List<PageItem>();
}
public List<PageItem> Process(int Flags, byte[] RecordData)
{
MemoryStream _ms = null;
BinaryReader _br = null;
MemoryStream _fs = null;
BinaryReader _fr = null;
try
{
_fs = new MemoryStream(BitConverter.GetBytes(Flags));
_fr = new BinaryReader(_fs);
byte ObjectID = _fr.ReadByte();
//Byte 1 will be ignored
byte RealFlags = _fr.ReadByte();
//Byte 2 will be brushtype
// 0 1 2 3 4 5 6 7
// X X X X X X C X
// if C = 1 int16, 0 = Points are Float (ignore P)
bool Compressed = ((RealFlags & (int)Math.Pow(2, 6)) == (int)Math.Pow(2, 6));
_ms = new MemoryStream(RecordData);
_br = new BinaryReader(_ms);
EMFPen EMFp = (EMFPen)ObjectTable[ObjectID];
Pen p = EMFp.myPen;
if (Compressed)
{
Int16 Xp = _br.ReadInt16();
Int16 Yp = _br.ReadInt16();
Int16 Wid = _br.ReadInt16();
Int16 Hgt = _br.ReadInt16();
DoEllipse(p, Xp, Yp, Wid, Hgt);
}
else
{
Single Xp = _br.ReadSingle();
Single Yp = _br.ReadSingle();
Single Wid = _br.ReadSingle();
Single Hgt = _br.ReadSingle();
DoEllipse(p, Xp, Yp, Wid, Hgt);
}
return items;
}
finally
{
if (_br != null)
_br.Close();
if (_ms != null)
_ms.Dispose();
if (_fr != null)
_fr.Close();
if (_fs != null)
_fs.Dispose();
}
}
private void DoEllipse(Pen p, Single Xp, Single Yp, Single Wid, Single Hgt)
{
BorderStyleEnum ls = getLineStyle(p);
Color col = Color.Black;
if (p.Brush.GetType().Name.Equals("SolidBrush"))
{
System.Drawing.SolidBrush theBrush = (System.Drawing.SolidBrush)p.Brush;
col = theBrush.Color;
}
PageEllipse pl = new PageEllipse();
pl.X = X + Xp * SCALEFACTOR;
pl.Y = Y + Yp * SCALEFACTOR;
pl.W = Wid * SCALEFACTOR;
pl.H = Hgt * SCALEFACTOR;
StyleInfo SI = new StyleInfo();
SI.Color = col;
SI.BColorTop = col;
SI.BStyleTop = ls;
SI.BWidthTop = p.Width * SCALEFACTOR;
pl.SI = SI;
items.Add(pl);
//Lines.AppendFormat("\r\n"); //CrLf
//Lines.AppendFormat("q\t"); //Push graphics state onto stack
//Lines.AppendFormat("{0} w\t", p.Width * ScaleX); //set width of path
//Lines.AppendFormat("{0} \t", linestyle); //line style from pen...
//Lines.AppendFormat("{0} {1} {2} RG\t", Math.Round(R / 255.0, 3), Math.Round(G / 255.0, 3), Math.Round(B / 255.0, 3)); //Set RGB colours
//Lines.AppendFormat("{0} {1} {2} rg\t", Math.Round(R / 255.0, 3), Math.Round(G / 255.0, 3), Math.Round(B / 255.0, 3)); //Set RGB colours
////Need some bezier curves to draw an ellipse.. we can't draw a circle, but we can get close.
//Double k = 0.5522847498;
//Double RadiusX = (Wid / 2.0) * ScaleX;
//Double RadiusY = (Hgt / 2.0) * ScaleY;
//Double Y4 = Y + Height - Yp * ScaleY;
//Double X1 = Xp * ScaleX + X;
//Double Y1 = Y4 - RadiusY;
//Double X4 = X1 + RadiusX;
//Lines.AppendFormat("{0} {1} m\t", X1, Y1);//FirstPoint..
//Double kRy = k * RadiusY;
//Double kRx = k * RadiusX;
////Control Point 1 will be on the same X as point 1 and be -kRy Y
//Double X2 = X1;
//Double Y2 = Y1 + kRy;
//Double X3 = X4 - kRx;
//Double Y3 = Y4;
//Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X2, Y2, X3, Y3, X4, Y4); //Upper Left Quadrant
//X1 += 2 * RadiusX;
//X2 = X1;
//X3 += 2 * kRx;
//Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X3, Y3, X2, Y2, X1, Y1); //Upper Right Quadrant
//Y2 -= 2 * kRy;
//Y3 -= 2 * RadiusY;
//Y4 = Y3;
//Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X2, Y2, X3, Y3, X4, Y4); //Lower Right Quadrant
//X1 -= 2 * RadiusX;
//X2 = X1;
//X3 -= 2 * kRx;
//Lines.AppendFormat("{0} {1} {2} {3} {4} {5} c\t", X3, Y3, X2, Y2, X1, Y1); //Lower Right Quadrant
//Lines.AppendFormat("S\t");//Stroke path
//Lines.AppendFormat("Q\t");//Pop graphics state from stack
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Options;
namespace PEDollController.Commands
{
// Command "unhook": Uninstalls a hook.
// unhook 0xOEP
class CmdUnhook : ICommand
{
public string HelpResId() => "Commands.Help.Unhook";
public string HelpShortResId() => "Commands.HelpShort.Unhook";
public Dictionary<string, object> Parse(string cmd)
{
int id = -1;
OptionSet options = new OptionSet()
{
{ "<>", (uint x) => id = (int)x }
};
Util.ParseOptions(cmd, options);
return new Dictionary<string, object>()
{
{ "verb", "unhook" },
{ "id", id }
};
}
public void Invoke(Dictionary<string, object> options)
{
int id = (int)options["id"];
Threads.Client client = Threads.CmdEngine.theInstance.GetTargetClient(false);
if(id >= client.hooks.Count || client.hooks[id].name == null)
throw new ArgumentException(Program.GetResourceString("Commands.Unhook.NotFound"));
Threads.HookEntry entry = client.hooks[id];
// If client is under the current hook, cancel the operation with TargetNotApplicable
if (client.hookOep == entry.oep)
throw new ArgumentException(Program.GetResourceString("Threads.CmdEngine.TargetNotApplicable"));
// Prepare & send CMD_UNHOOK packets
client.Send(Puppet.Util.Serialize(new Puppet.PACKET_CMD_UNHOOK(0)));
client.Send(Puppet.Util.Serialize(new Puppet.PACKET_INTEGER(entry.oep)));
// Expect ACK(0)
Puppet.PACKET_ACK pktAck;
pktAck = Puppet.Util.Deserialize<Puppet.PACKET_ACK>(client.Expect(Puppet.PACKET_TYPE.ACK));
if (pktAck.status != 0)
throw new ArgumentException(Util.Win32ErrorToMessage((int)pktAck.status));
// Remove entry from client's hooks
//client.hooks.Remove(entry); // This will cause following hooks' IDs change
client.hooks[id] = new Threads.HookEntry();
Logger.I(Program.GetResourceString("Commands.Unhook.Uninstalled", id, entry.name));
Threads.Gui.theInstance.InvokeOn((FMain Me) => Me.RefreshGuiHooks());
}
}
}
|
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Xml;
using ICSharpCode.SharpDevelop.Gui;
namespace ICSharpCode.XmlEditor
{
/// <summary>
/// Represents an xml comment in the tree.
/// </summary>
public class XmlCommentTreeNode : XmlCharacterDataTreeNode
{
public const string XmlCommentTreeNodeImageKey = "XmlCommentTreeNodeImage";
public const string XmlCommentTreeNodeGhostImageKey = "XmlCommentTreeNodeGhostImage";
XmlComment comment;
public XmlCommentTreeNode(XmlComment comment)
: base(comment)
{
this.comment = comment;
ImageKey = XmlCommentTreeNodeImageKey;
SelectedImageKey = ImageKey;
Update();
}
/// <summary>
/// Gets the XmlComment associated with this tree node.
/// </summary>
public XmlComment XmlComment {
get {
return comment;
}
}
/// <summary>
/// Gets or sets whether to show the ghost image which is
/// displayed when cutting the node.
/// </summary>
public bool ShowGhostImage {
get {
return ImageKey == XmlCommentTreeNodeGhostImageKey;
}
set {
if (value) {
ImageKey = XmlCommentTreeNodeGhostImageKey;
} else {
ImageKey = XmlCommentTreeNodeImageKey;
}
SelectedImageKey = ImageKey;
}
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Prism.AppModel
{
public interface IApplicationStore
{
IDictionary<string, object> Properties { get; }
Task SavePropertiesAsync();
}
}
|
using RecommendationSystem.Knn.Foundation.Models;
using RecommendationSystem.SimpleKnn.Users;
namespace RecommendationSystem.SimpleKnn.Models
{
public interface ISimpleKnnModel : IKnnModel<ISimpleKnnUser>
{}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SeattleScotchSociety.ScotchNight.Api.Models
{
public class SummaryNote
{
[Required]
public Guid BottleId { get; set; }
[Range(0, 5)]
public float? Rating { get; set; }
public Dictionary<string, int> Tags { get; set; }
}
}
|
using System;
namespace Sugar.Language.Tokens.Enums
{
internal enum DescriberType : byte
{
Static = 0,
Function = 1,
Mutability = 2,
Inhertiance = 3,
AccessModifier = 4
}
}
|
using System.Threading.Tasks;
namespace Camunda.Api.Client.History
{
public class HistoricCaseInstanceResource
{
private IHistoricCaseInstanceRestService _api;
private string _caseInstanceId;
internal HistoricCaseInstanceResource(IHistoricCaseInstanceRestService api, string caseInstanceId)
{
_api = api;
_caseInstanceId = caseInstanceId;
}
/// <summary>
/// Retrieves a historic case instance by id, according to the <see cref="HistoricCaseInstance"/> interface in the engine.
/// </summary>
/// <returns></returns>
public Task<HistoricCaseInstance> Get() => _api.Get(_caseInstanceId);
}
} |
using System.Collections.Generic;
namespace CSharpDesignPatterns
{
/// <summary>
/// Client
/// </summary>
public class MementoTest
{
public static void Run()
{
var editor = new Editor();
var history = new History();
editor.Content = "a";
history.Push(editor.CreateState());
editor.Content = "b";
history.Push(editor.CreateState());
editor.Restore(history.Pop());
System.Console.WriteLine(editor.Content);
editor.Content = "c";
history.Push(editor.CreateState());
System.Console.WriteLine(editor.Content);
editor.Restore(history.Pop());
System.Console.WriteLine(editor.Content);
}
}
/// <summary>
/// Originator.
/// </summary>
internal class Editor
{
internal string Content { get; set; }
internal EditorState CreateState()
{
return new EditorState(Content);
}
internal void Restore(EditorState state)
{
Content = state.Content;
}
}
/// <summary>
/// Momento.
/// </summary>
internal class EditorState
{
internal EditorState(string content)
{
Content = content;
}
internal string Content { get; }
}
/// <summary>
/// Caretaker.
/// </summary>
internal class History
{
private Stack<EditorState> states = new Stack<EditorState>();
internal void Push(EditorState state)
{
states.Push(state);
}
internal EditorState Pop()
{
states.Pop();
return states.Peek();
}
}
} |
// Copyright (c) 2020 Sergio Aquilini
// This code is licensed under MIT license (see LICENSE file for details)
using System;
using Silverback.Messaging.Configuration.Kafka;
using Silverback.Util;
namespace Silverback.Messaging.Configuration
{
/// <summary>
/// Adds the <c>AddKafkaEndpoints</c> method to the <see cref="IEndpointsConfigurationBuilder" />.
/// </summary>
public static class EndpointsConfigurationBuilderAddKafkaEndpointsExtensions
{
/// <summary>
/// Adds the Kafka endpoints.
/// </summary>
/// <param name="endpointsConfigurationBuilder">
/// The <see cref="IEndpointsConfigurationBuilder" />.
/// </param>
/// <param name="kafkaEndpointsBuilderAction">
/// An <see cref="Action{T}" /> that takes the <see cref="IKafkaEndpointsConfigurationBuilder" />,
/// configures the connection to the message broker and adds the inbound and outbound endpoints.
/// </param>
/// <returns>
/// The <see cref="IEndpointsConfigurationBuilder" /> so that additional calls can be chained.
/// </returns>
public static IEndpointsConfigurationBuilder AddKafkaEndpoints(
this IEndpointsConfigurationBuilder endpointsConfigurationBuilder,
Action<IKafkaEndpointsConfigurationBuilder> kafkaEndpointsBuilderAction)
{
Check.NotNull(endpointsConfigurationBuilder, nameof(endpointsConfigurationBuilder));
Check.NotNull(kafkaEndpointsBuilderAction, nameof(kafkaEndpointsBuilderAction));
var kafkaEndpointsBuilder = new KafkaEndpointsConfigurationBuilder(endpointsConfigurationBuilder);
kafkaEndpointsBuilderAction.Invoke(kafkaEndpointsBuilder);
return endpointsConfigurationBuilder;
}
}
}
|
@using EA.Iws.Web.Areas.Admin.Views.ExportNotification
@model EA.Iws.Web.Areas.Admin.ViewModels.ExportNotification.NewOrExistingNotificationViewModel
@{
ViewBag.Title = NewOrExistingNotificationResources.Header;
}
<h1 class="heading-large">@NewOrExistingNotificationResources.Header</h1>
@using (Html.BeginForm())
{
@Html.Gds().ValidationSummary()
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.CompetentAuthority)
@Html.HiddenFor(m => m.NotificationType)
<div class="form-group @Html.Gds().FormGroupClass(m => m.GenerateNew)">
@Html.Gds().LabelFor(m => m.GenerateNew, new { @class = "visually-hidden" })
@Html.Gds().ValidationMessageFor(m => m.GenerateNew)
<fieldset>
<div class="multiple-choice">
@Html.RadioButtonFor(m => m.GenerateNew, true, new { id = "GenerateNew" })
<label for="GenerateNew">
@NewOrExistingNotificationResources.GenerateNewNumber
</label>
</div>
<div class="multiple-choice">
@Html.RadioButtonFor(m => m.GenerateNew, false, new { id = "EnterNumber" })
<label for="EnterNumber">
@NewOrExistingNotificationResources.EnterExistingNumber
</label>
</div>
</fieldset>
</div>
<div class="form-group">
<button class="button" type="submit">@Constants.ContinueButtonText</button>
</div>
} |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class PauseButton : MonoBehaviour, IPointerDownHandler
{
private bool _pauseActive = false;
private Image _buttonImage;
void Start()
{
_buttonImage = GetComponent<Image>();
}
public void Paused(){
if(_pauseActive == false)
Time.timeScale = 0;
else
Time.timeScale = 1;
if(_pauseActive){
_buttonImage.color = Color.white;
}
else
_buttonImage.color = Color.gray;
_pauseActive = !_pauseActive;
if(_pauseActive){
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerScript>().Move();
}
}
public void OnPointerDown (PointerEventData eventData){
Paused();
}
}
|
using CovidSharp.owiData.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace CovidSharp.Models
{
public class Country
{
public string CountryCode;
public string CountryName;
public int Population;
public List<OwidDay> CovidData { get; set; }
}
}
|
// Copyright (c) 2021 DXNET - Pomianowski Leszek & Contributors
// Copyright (c) 2010-2019 SharpDX - Alexandre Mutel & SharpDX Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// Original code from NAudio project. http://naudio.codeplex.com/
// Greetings to Mark Heath.
// -----------------------------------------------------------------------------
namespace DXNET.Multimedia
{
/// <summary>
/// HID_USAGE_PAGE
/// </summary>
public enum UsagePage : short
{
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_UNDEFINED</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_UNDEFINED</unmanaged-short>
Undefined = unchecked((System.Int16)(0)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_GENERIC</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_GENERIC</unmanaged-short>
Generic = unchecked((System.Int16)(1)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_SIMULATION</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_SIMULATION</unmanaged-short>
Simulation = unchecked((System.Int16)(2)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_VR</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_VR</unmanaged-short>
Vr = unchecked((System.Int16)(3)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_SPORT</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_SPORT</unmanaged-short>
Sport = unchecked((System.Int16)(4)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_GAME</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_GAME</unmanaged-short>
Game = unchecked((System.Int16)(5)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_GENERIC_DEVICE</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_GENERIC_DEVICE</unmanaged-short>
GenericDevice = unchecked((System.Int16)(6)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_KEYBOARD</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_KEYBOARD</unmanaged-short>
Keyboard = unchecked((System.Int16)(7)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_LED</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_LED</unmanaged-short>
Led = unchecked((System.Int16)(8)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_BUTTON</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_BUTTON</unmanaged-short>
Button = unchecked((System.Int16)(9)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_ORDINAL</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_ORDINAL</unmanaged-short>
Ordinal = unchecked((System.Int16)(10)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_TELEPHONY</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_TELEPHONY</unmanaged-short>
Telephony = unchecked((System.Int16)(11)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_CONSUMER</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_CONSUMER</unmanaged-short>
Consumer = unchecked((System.Int16)(12)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_DIGITIZER</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_DIGITIZER</unmanaged-short>
Digitizer = unchecked((System.Int16)(13)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_HAPTICS</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_HAPTICS</unmanaged-short>
Haptics = unchecked((System.Int16)(14)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_PID</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_PID</unmanaged-short>
Pid = unchecked((System.Int16)(15)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_UNICODE</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_UNICODE</unmanaged-short>
Unicode = unchecked((System.Int16)(16)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_ALPHANUMERIC</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_ALPHANUMERIC</unmanaged-short>
Alphanumeric = unchecked((System.Int16)(20)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_SENSOR</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_SENSOR</unmanaged-short>
Sensor = unchecked((System.Int16)(32)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_BARCODE_SCANNER</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_BARCODE_SCANNER</unmanaged-short>
BarcodeScanner = unchecked((System.Int16)(140)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_WEIGHING_DEVICE</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_WEIGHING_DEVICE</unmanaged-short>
WeighingDevice = unchecked((System.Int16)(141)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MAGNETIC_STRIPE_READER</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MAGNETIC_STRIPE_READER</unmanaged-short>
MagneticStripeReader = unchecked((System.Int16)(142)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_CAMERA_CONTROL</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_CAMERA_CONTROL</unmanaged-short>
CameraControl = unchecked((System.Int16)(144)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_ARCADE</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_ARCADE</unmanaged-short>
Arcade = unchecked((System.Int16)(145)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MICROSOFT_BLUETOOTH_HANDSFREE</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MICROSOFT_BLUETOOTH_HANDSFREE</unmanaged-short>
MicrosoftBluetoothHandsfree = unchecked((System.Int16)(65523)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_VENDOR_DEFINED_BEGIN</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_VENDOR_DEFINED_BEGIN</unmanaged-short>
VendorDefinedBegin = unchecked((System.Int16)(65280)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_VENDOR_DEFINED_END</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_VENDOR_DEFINED_END</unmanaged-short>
VendorDefinedEnd = unchecked((System.Int16)(65535)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_LIGHTING_ILLUMINATION</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_LIGHTING_ILLUMINATION</unmanaged-short>
LightingIllumination = unchecked((System.Int16)(89)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MEDICAL</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MEDICAL</unmanaged-short>
Medical = unchecked((System.Int16)(64)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MONITOR_PAGE0</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MONITOR_PAGE0</unmanaged-short>
MonitorPage0 = unchecked((System.Int16)(128)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MONITOR_PAGE1</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MONITOR_PAGE1</unmanaged-short>
MonitorPage1 = unchecked((System.Int16)(129)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MONITOR_PAGE2</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MONITOR_PAGE2</unmanaged-short>
MonitorPage2 = unchecked((System.Int16)(130)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MONITOR_PAGE3</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MONITOR_PAGE3</unmanaged-short>
MonitorPage3 = unchecked((System.Int16)(131)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_POWER_PAGE0</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_POWER_PAGE0</unmanaged-short>
PowerPage0 = unchecked((System.Int16)(132)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_POWER_PAGE1</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_POWER_PAGE1</unmanaged-short>
PowerPage1 = unchecked((System.Int16)(133)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_POWER_PAGE2</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_POWER_PAGE2</unmanaged-short>
PowerPage2 = unchecked((System.Int16)(134)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_POWER_PAGE3</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_POWER_PAGE3</unmanaged-short>
PowerPage3 = unchecked((System.Int16)(135)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_BARCODE</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_BARCODE</unmanaged-short>
Barcode = unchecked((System.Int16)(140)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_SCALE</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_SCALE</unmanaged-short>
Scale = unchecked((System.Int16)(141)),
/// <summary>
/// No documentation.
/// </summary>
/// <unmanaged>HID_USAGE_PAGE_MSR</unmanaged>
/// <unmanaged-short>HID_USAGE_PAGE_MSR</unmanaged-short>
Msr = unchecked((System.Int16)(142))
}
}
|
namespace GRA.CommandLine.DataGenerator
{
internal class GeneratedUser
{
public Domain.Model.User User { get; set; }
public string Password { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace csConsoleApp
{
class Program
{
[DllImport(@"cppDll4cs.dll")]
//[DllImport(@"d:\git\cpp\cppDll4cs\x64\Release\cppDll4cs.dll")]
public static extern int add(int a, int b);
[DllImport(@"cppDll4cs.dll", EntryPoint ="test")]
//[DllImport(@"D:\git\cpp\cppDll4cs\x64\Release\cppDll4cs.dll", EntryPoint ="test")]
public static extern int Test(string s);
//public static extern int test([MarshalAs(UnmanagedType.LPStr)] string s);
[DllImport("cppDll4cs.dll", EntryPoint = "encrypt")]
public static extern void Encrypt(string mse1, string mse2);
static void Main(string[] args)
{
Console.WriteLine("cs app using cpp dll function");
int x = add(100, 200);
Console.WriteLine(x);
string s = "hi";
int z = Test(s);
//Console.WriteLine(z);
string temp = Path.GetTempFileName();
Console.WriteLine(temp);
string mse = @"D:\git\cpp\msTesting\src_encrypt.mse";
Encrypt(mse, temp+".mse");
Test("Done, 我是中文呢");
Console.ReadKey();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Asset_Management_Utility : SingletonComponent<Asset_Management_Utility>
{
public static Asset_Management_Utility Instance
{
get { return ((Asset_Management_Utility)_Instance); }
set { _Instance = value; }
}
public GameObject gO;
public void LoadFromResource(string name)
{
//gO = Resources.Load<GameObject>(name) as GameObject;
//Instantiate(gO);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.