content stringlengths 23 1.05M |
|---|
using Mirage;
using UnityEngine;
namespace SyncVarTests.SyncVarsUnityComponent
{
class SyncVarsUnityComponent : NetworkBehaviour
{
[SyncVar]
TextMesh invalidVar;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SP579emulator {
/// <summary>
/// Calculates the checksum of a record
/// </summary>
public partial class Tri_CheckSumCalc : Form {
public Tri_CheckSumCalc() {
Icon = global::SP579emulator.Properties.Resources.app_icon;
InitializeComponent();
}
private void btnCalc_Click( object sender, EventArgs e ) {
txtResult.Text = calculateCheckSum( txtRecord.Text );
txtRecord.Text = string.Empty;
}
/// <summary>
/// Calculates the checksum of a record
/// </summary>
/// <param name="rec">An Hex value in a string that is two charecters wide</param>
/// <returns></returns>
private string calculateCheckSum( string rec ) {
string[] record = rec.Split( new char[] { '*', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries);
// Adding the number together
int result = int.Parse( record[1], System.Globalization.NumberStyles.HexNumber );
result += int.Parse( record[2], System.Globalization.NumberStyles.HexNumber );
string hex;
if ( record[0] == "2" ) {
for ( int i = 0; i < record[3].Length; i += 2 ) {
hex = record[3].Substring( i, 2 );
result += int.Parse( hex, System.Globalization.NumberStyles.HexNumber );
}
}
// Wrap around
hex = result.ToString( "X" );
string wrapAround = string.Empty;
while ( hex.Length > 2 ) {
wrapAround = hex.Substring( 0, hex.Length - 2 );
hex = hex.Substring( wrapAround.Length );
result = int.Parse( hex, System.Globalization.NumberStyles.HexNumber );
result += int.Parse( wrapAround, System.Globalization.NumberStyles.HexNumber );
hex = result.ToString( "X" );
}
// One's compliment
hex = result.ToString( "X" );
result = int.Parse( hex[0].ToString(), System.Globalization.NumberStyles.HexNumber );
result = 15 - result;
hex = result.ToString("X") + hex[1];
result = int.Parse( hex[1].ToString(), System.Globalization.NumberStyles.HexNumber );
result = 15 - result;
hex = hex[0] + result.ToString("X");
return hex;
}
private void txtResult_KeyPress( object sender, KeyPressEventArgs e ) {
e.Handled = true;
}
private void button1_Click( object sender, EventArgs e ) {
this.Close();
}
}
}
|
using Enterspeed.Source.Sdk.Api.Providers;
using Enterspeed.Source.Sdk.Configuration;
namespace Enterspeed.Source.UmbracoCms.V8.Providers
{
public class InMemoryEnterspeedUmbracoConfigurationProvider : IEnterspeedConfigurationProvider
{
public InMemoryEnterspeedUmbracoConfigurationProvider(EnterspeedConfiguration configuration)
{
Configuration = configuration;
}
public EnterspeedConfiguration Configuration { get; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace SynthTree
{
[Serializable]
public class Settings
{
public static Settings Instance { get; private set; }
const string FileName = "setting.xml";
public int SamplingFreq { get; set; }
public Settings()
{
SamplingFreq = 8000;
}
static Settings()
{
try
{
Instance = Deserialize();
}
catch (Exception)
{
Instance = new Settings();
Instance.Serialize();
}
}
public void Serialize()
{
var f = new XmlSerializer(typeof(Settings));
using (var file = new FileStream(FileName, FileMode.Create, FileAccess.Write))
{
f.Serialize(file, this);
}
}
static Settings Deserialize()
{
var f = new XmlSerializer(typeof(Settings));
using (var file = new FileStream(FileName, FileMode.Open, FileAccess.Read))
{
return f.Deserialize(file) as Settings;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Liepzig.Services.IService;
using Liepzig.Services;
using Liepzig.Services.Service;
namespace Forest.Controllers
{
public class LiepzigMusicController : Controller
{
private Liepzig.Services.Service.LiepzigMusicService _LiepzigMusicService;
public LiepzigMusicController()
{
_LiepzigMusicService = new Liepzig.Services.Service.LiepzigMusicService();
}
//
// GET: /LiepzigMusic/
public ActionResult Recordings(int genre)
{
return View(_LiepzigMusicService.GetLiepzigMusicRecordings(genre));
}
}
} |
using System.Threading.Tasks;
using Blockexplorer.Core.Domain;
namespace Blockexplorer.Core.Interfaces
{
public interface IBlockProvider
{
Task<Block> GetBlock(string id);
Task<Block> GetLastBlock();
}
}
|
//---------------------------------------------------------------------
// <copyright file="ContentFormat.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// List of content formats that data web service supports
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services
{
/// <summary>This enumeration provides values for the content format.</summary>
internal enum ContentFormat
{
/// <summary>A binary format with no additional modifications.</summary>
Binary,
/// <summary>The application/json format.</summary>
Json,
/// <summary>A text-based format with no additional markup.</summary>
Text,
/// <summary>The application/atom+xml format.</summary>
Atom,
/// <summary>An XML document for CSDL.</summary>
MetadataDocument,
/// <summary>An XML document for primitive and complex types.</summary>
PlainXml,
/// <summary>An as-yet-undetermined format.</summary>
Unknown,
/// <summary>An unsupported format.</summary>
Unsupported
}
}
|
// Copyright(C) David W. Jeske, 2013
// Released to the public domain. Use, modify and relicense at will.
using System;
using OpenTK;
namespace SimpleScene
{
public class SSCamera : SSObject
{
protected float pitchAngle = 0f;
protected float yawAngle = 0f;
public SSCamera () : base() {
}
public virtual Matrix4 viewMatrix()
{
return worldMat.Inverted();
}
public virtual Matrix4 rotationOnlyViewMatrix()
{
return rotationOnlyViewMatrixInverted().Inverted();
}
public virtual Matrix4 rotationOnlyViewMatrixInverted()
{
Matrix4 mat = Matrix4.Identity;
// rotation..
mat.M11 = _right.X;
mat.M12 = _right.Y;
mat.M13 = _right.Z;
mat.M21 = _up.X;
mat.M22 = _up.Y;
mat.M23 = _up.Z;
mat.M31 = _dir.X;
mat.M32 = _dir.Y;
mat.M33 = _dir.Z;
return mat;
}
public virtual void preRenderUpdate(float timeElapsed)
{
this.calcMatFromState ();
}
protected float DegreeToRadian(float angleInDegrees) {
return (float)Math.PI * angleInDegrees / 180.0f;
}
public void mouseDeltaOrient(float XDelta, float YDelta)
{
if (pitchAngle > (float)Math.PI/2f && pitchAngle < 1.5f*(float)Math.PI) {
// upside down
XDelta *= -1f;
}
pitchAngle += DegreeToRadian(YDelta);
yawAngle += DegreeToRadian(XDelta);
const float twoPi = (float)(2.0 * Math.PI);
if (pitchAngle < 0f) {
pitchAngle += twoPi;
} else if (pitchAngle > twoPi) {
pitchAngle -= twoPi;
}
//var pitchOri = Quaternion.FromAxisAngle(this.Up, pitchAngle);
var pitchOri = Quaternion.FromAxisAngle(Vector3.UnitY, -yawAngle);
var yawOri = Quaternion.FromAxisAngle(Vector3.UnitX, -pitchAngle);
this.Orient(pitchOri * yawOri);
this.calcMatFromState(); // make sure our local matrix is current
// openGL requires pre-multiplation of these matricies...
//Quaternion qResult = yawDelta * pitch_Rotation * this.localMat.ExtractRotation();
}
}
}
|
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSComctlLibApi
{
/// <summary>
/// DispatchInterface ITreeView
/// SupportByVersion MSComctlLib, 6
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
[EntityType(EntityType.IsDispatchInterface), BaseType]
public class ITreeView : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(ITreeView);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public ITreeView(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public ITreeView(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITreeView(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITreeView(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITreeView(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITreeView(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITreeView() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITreeView(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
[BaseResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.MSComctlLibApi.INode DropHighlight
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSComctlLibApi.INode>(this, "DropHighlight");
}
set
{
Factory.ExecuteReferencePropertySet(this, "DropHighlight", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool HideSelection
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "HideSelection");
}
set
{
Factory.ExecuteValuePropertySet(this, "HideSelection", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("MSComctlLib", 6), ProxyResult]
public object ImageList
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "ImageList");
}
set
{
Factory.ExecuteReferencePropertySet(this, "ImageList", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public Single Indentation
{
get
{
return Factory.ExecuteSinglePropertyGet(this, "Indentation");
}
set
{
Factory.ExecuteValuePropertySet(this, "Indentation", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.LabelEditConstants LabelEdit
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.LabelEditConstants>(this, "LabelEdit");
}
set
{
Factory.ExecuteEnumPropertySet(this, "LabelEdit", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.TreeLineStyleConstants LineStyle
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.TreeLineStyleConstants>(this, "LineStyle");
}
set
{
Factory.ExecuteEnumPropertySet(this, "LineStyle", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.MousePointerConstants MousePointer
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.MousePointerConstants>(this, "MousePointer");
}
set
{
Factory.ExecuteEnumPropertySet(this, "MousePointer", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6), NativeResult]
public stdole.Picture MouseIcon
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "MouseIcon", paramsArray);
return returnItem as stdole.Picture;
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "MouseIcon", paramsArray);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
[BaseResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.MSComctlLibApi.INodes Nodes
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSComctlLibApi.INodes>(this, "Nodes");
}
set
{
Factory.ExecuteReferencePropertySet(this, "Nodes", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public string PathSeparator
{
get
{
return Factory.ExecuteStringPropertyGet(this, "PathSeparator");
}
set
{
Factory.ExecuteValuePropertySet(this, "PathSeparator", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
[BaseResult]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public NetOffice.MSComctlLibApi.INode SelectedItem
{
get
{
return Factory.ExecuteBaseReferencePropertyGet<NetOffice.MSComctlLibApi.INode>(this, "SelectedItem");
}
set
{
Factory.ExecuteReferencePropertySet(this, "SelectedItem", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool Sorted
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "Sorted");
}
set
{
Factory.ExecuteValuePropertySet(this, "Sorted", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.TreeStyleConstants Style
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.TreeStyleConstants>(this, "Style");
}
set
{
Factory.ExecuteEnumPropertySet(this, "Style", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.OLEDragConstants OLEDragMode
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.OLEDragConstants>(this, "OLEDragMode");
}
set
{
Factory.ExecuteEnumPropertySet(this, "OLEDragMode", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.OLEDropConstants OLEDropMode
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.OLEDropConstants>(this, "OLEDropMode");
}
set
{
Factory.ExecuteEnumPropertySet(this, "OLEDropMode", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.AppearanceConstants Appearance
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.AppearanceConstants>(this, "Appearance");
}
set
{
Factory.ExecuteEnumPropertySet(this, "Appearance", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.Enums.BorderStyleConstants BorderStyle
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.MSComctlLibApi.Enums.BorderStyleConstants>(this, "BorderStyle");
}
set
{
Factory.ExecuteEnumPropertySet(this, "BorderStyle", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool Enabled
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "Enabled");
}
set
{
Factory.ExecuteValuePropertySet(this, "Enabled", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6), NativeResult]
public stdole.Font Font
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Font", paramsArray);
return returnItem as stdole.Font;
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Font", paramsArray);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Int32 hWnd
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "hWnd");
}
set
{
Factory.ExecuteValuePropertySet(this, "hWnd", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool Checkboxes
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "Checkboxes");
}
set
{
Factory.ExecuteValuePropertySet(this, "Checkboxes", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool FullRowSelect
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "FullRowSelect");
}
set
{
Factory.ExecuteValuePropertySet(this, "FullRowSelect", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool HotTracking
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "HotTracking");
}
set
{
Factory.ExecuteValuePropertySet(this, "HotTracking", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool Scroll
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "Scroll");
}
set
{
Factory.ExecuteValuePropertySet(this, "Scroll", value);
}
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// Get/Set
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public bool SingleSel
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "SingleSel");
}
set
{
Factory.ExecuteValuePropertySet(this, "SingleSel", value);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion MSComctlLib 6
/// </summary>
/// <param name="x">Single x</param>
/// <param name="y">Single y</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[BaseResult]
[SupportByVersion("MSComctlLib", 6)]
public NetOffice.MSComctlLibApi.INode HitTest(Single x, Single y)
{
return Factory.ExecuteBaseReferenceMethodGet<NetOffice.MSComctlLibApi.INode>(this, "HitTest", x, y);
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersion("MSComctlLib", 6)]
public Int32 GetVisibleCount()
{
return Factory.ExecuteInt32MethodGet(this, "GetVisibleCount");
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public void StartLabelEdit()
{
Factory.ExecuteMethod(this, "StartLabelEdit");
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public void Refresh()
{
Factory.ExecuteMethod(this, "Refresh");
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersion("MSComctlLib", 6)]
public void AboutBox()
{
Factory.ExecuteMethod(this, "AboutBox");
}
/// <summary>
/// SupportByVersion MSComctlLib 6
/// </summary>
[SupportByVersion("MSComctlLib", 6)]
public void OLEDrag()
{
Factory.ExecuteMethod(this, "OLEDrag");
}
#endregion
#pragma warning restore
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Headway.Core.Model
{
public class ConfigContainer
{
public ConfigContainer()
{
ConfigContainers = new List<ConfigContainer>();
}
public int ConfigContainerId { get; set; }
public bool IsRootContainer { get; set; }
public int Row { get; set; }
public int Column { get; set; }
public List<ConfigContainer> ConfigContainers { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(50, ErrorMessage = "Name must be between 1 and 50 characters")]
public string Name { get; set; }
[Required(ErrorMessage = "Container is required")]
[StringLength(150, ErrorMessage = "Container must be between 1 and 150 characters")]
public string Container { get; set; }
}
} |
//MIT, 2016-present, WinterDev
// some code from icu-project
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
using System;
using Typography.OpenFont;
namespace Typography.TextBreak
{
public enum SurrogatePairBreakingOption
{
OnlySurrogatePair,
ConsecutiveSurrogatePairs,
ConsecutiveSurrogatePairsAndJoiner
}
public class EngBreakingEngine : BreakingEngine
{
enum LexState
{
Init,
Whitespace,
Tab,
Text,
Number,
CollectSurrogatePair,
CollectConsecutiveUnicode,
}
public bool BreakNumberAfterText { get; set; }
public bool BreakPeroidInTextSpan { get; set; }
public bool EnableCustomAbbrv { get; set; }
public bool EnableUnicodeRangeBreaker { get; set; }
public bool IncludeLatinExtended { get; set; } = true;
public SurrogatePairBreakingOption SurrogatePairBreakingOption { get; set; } = SurrogatePairBreakingOption.ConsecutiveSurrogatePairsAndJoiner;
public CustomAbbrvDic EngCustomAbbrvDic { get; set; }
struct BreakBounds
{
public int startIndex;
public int length;
public WordKind kind;
public BreakBounds(int startIndex, int length, WordKind kind)
{
this.startIndex = startIndex;
this.length = length;
this.kind = kind;
}
}
static readonly SpanBreakInfo s_c0BasicLatin = new SpanBreakInfo(Unicode13RangeInfoList.C0_Controls_and_Basic_Latin, false, ScriptTagDefs.Latin.Tag);
static readonly SpanBreakInfo s_c1LatinSupplement = new SpanBreakInfo(Unicode13RangeInfoList.C1_Controls_and_Latin_1_Supplement, false, ScriptTagDefs.Latin.Tag);
static readonly SpanBreakInfo s_latinExtendA = new SpanBreakInfo(Unicode13RangeInfoList.Latin_Extended_A, false, ScriptTagDefs.Latin.Tag);
static readonly SpanBreakInfo s_latinExtendB = new SpanBreakInfo(Unicode13RangeInfoList.Latin_Extended_B, false, ScriptTagDefs.Latin.Tag);
static readonly SpanBreakInfo s_emoticon = new SpanBreakInfo(Unicode13RangeInfoList.Emoticons, false, ScriptTagDefs.Latin.Tag);
static readonly SpanBreakInfo s_latin = new SpanBreakInfo(false, ScriptTagDefs.Latin.Tag);//other
static readonly SpanBreakInfo s_unknown = new SpanBreakInfo(false, ScriptTagDefs.Latin.Tag);
public EngBreakingEngine()
{
}
internal override void BreakWord(WordVisitor visitor, char[] charBuff, int startAt, int len)
{
visitor.State = VisitorState.Parsing;
visitor.SpanBreakInfo = s_latin;
DoBreak(visitor, charBuff, startAt, len);
}
public override bool CanHandle(char c)
{
//this is basic eng + surrogate-pair( eg. emoji)
return (c <= 255) ||
char.IsHighSurrogate(c) ||
char.IsPunctuation(c) ||
char.IsWhiteSpace(c) ||
char.IsControl(c) ||
char.IsSymbol(c) ||
(IncludeLatinExtended && (IsLatinExtendedA(c) || IsLatinExtendedB(c)));
}
static bool IsLatinExtendedA(char c) => c >= 0x100 & c <= 0x017F;
static bool IsLatinExtendedB(char c) => c >= 0x0180 & c <= 0x024F;
//
public override bool CanBeStartChar(char c) => true;
//
static void OnBreak(WordVisitor vis, in BreakBounds bb) => vis.AddWordBreak_AndSetCurrentIndex(bb.startIndex + bb.length, bb.kind);
static void CollectConsecutiveUnicodeRange(char[] input, ref int start, int endBefore, out SpanBreakInfo spanBreakInfo)
{
char c1 = input[start];
if (UnicodeRangeFinder.GetUniCodeRangeFor(c1, out UnicodeRangeInfo unicodeRangeInfo, out spanBreakInfo))
{
int startCodePoint = unicodeRangeInfo.StartCodepoint;
int endCodePoint = unicodeRangeInfo.EndCodepoint;
for (int i = start; i < endBefore; ++i)
{
c1 = input[i];
if (c1 < startCodePoint || c1 > endCodePoint)
{
//out of range again
//break here
start = i;
return;
}
}
start = endBefore;
}
else
{
//for unknown,
//just collect until turn back to latin
#if DEBUG
System.Diagnostics.Debug.WriteLine("unknown unicode range:");
#endif
for (int i = start; i < endBefore; ++i)
{
c1 = input[i];
if ((c1 >= 0 && c1 < 256) || //eng range
char.IsHighSurrogate(c1) || //surrogate pair
UnicodeRangeFinder.GetUniCodeRangeFor(c1, out unicodeRangeInfo, out spanBreakInfo)) //or found some wellknown range
{
//break here
start = i;
return;
}
}
start = endBefore;
spanBreakInfo = s_unknown;
}
}
static void CollectConsecutiveSurrogatePairs(char[] input, ref int start, int len, bool withZeroWidthJoiner)
{
int lim = start + len;
for (int i = start; i < lim;) //start+1
{
char c = input[i];
if ((i + 1 < lim) &&
char.IsHighSurrogate(c) &&
char.IsLowSurrogate(input[i + 1]))
{
i += 2;//**
start = i;
}
else if (withZeroWidthJoiner && c == 8205)
{
//https://en.wikipedia.org/wiki/Zero-width_joiner
i += 1;
start = i;
}
else
{
//stop
start = i;
return;
}
}
}
bool IsInOurLetterRange(char c, out SpanBreakInfo brkInfo)
{
if (c >= 0 && c <= 127)
{
brkInfo = s_c0BasicLatin;
return true;
}
else if (c <= 255)
{
brkInfo = s_c1LatinSupplement;
return true;
}
else if (IncludeLatinExtended)
{
if (s_latinExtendA.UnicodeRange.IsInRange(c))
{
brkInfo = s_latinExtendA;
return true;
}
else if (s_latinExtendB.UnicodeRange.IsInRange(c))
{
brkInfo = s_latinExtendB;
return true;
}
}
brkInfo = null;
return false;
}
void DoBreak(WordVisitor visitor, char[] input, int start, int len)
{
//----------------------------------------
//simple break word/ num/ punc / space
//similar to lexer function
//----------------------------------------
int endBefore = start + len;
if (endBefore > input.Length)
throw new System.ArgumentOutOfRangeException(nameof(len), len, "The range provided was partially out of bounds.");
else if (start < 0)
throw new System.ArgumentOutOfRangeException(nameof(start), start, "The starting index was negative.");
//throw instead of skipping the entire for loop
else if (len < 0)
throw new System.ArgumentOutOfRangeException(nameof(len), len, "The length provided was negative.");
//----------------------------------------
LexState lexState = LexState.Init;
BreakBounds bb = new BreakBounds();
bb.startIndex = start;
bool enableUnicodeRangeBreaker = EnableUnicodeRangeBreaker;
bool breakPeroidInTextSpan = BreakPeroidInTextSpan;
visitor.SpanBreakInfo = s_c0BasicLatin;//default
for (int i = start; i < endBefore; ++i)
{
char c = input[i];
switch (lexState)
{
case LexState.Init:
{
//check char
if (c == '\r' && i < endBefore - 1 && input[i + 1] == '\n')
{
//this is '\r\n' linebreak
bb.startIndex = i;
bb.length = 2;
bb.kind = WordKind.NewLine;
//
OnBreak(visitor, bb);
//
bb.startIndex += 2;//***
bb.length = 0;
bb.kind = WordKind.Unknown;
lexState = LexState.Init;
i++;
continue;
}
else if (c == '\r' || c == '\n' || c == 0x85) //U+0085 NEXT LINE
{
bb.startIndex = i;
bb.length = 1;
bb.kind = WordKind.NewLine;
//
OnBreak(visitor, bb);
//
bb.length = 0;
bb.startIndex++;//***
bb.kind = WordKind.Unknown;
lexState = LexState.Init;
continue;
}
else if (c == ' ')
{
//explicit whitespace
//we collect whitespace
bb.startIndex = i;
bb.kind = WordKind.Whitespace;
lexState = LexState.Whitespace;
}
else if (c == '\t')
{
//explicit tab
bb.startIndex = i;
bb.kind = WordKind.Tab;
lexState = LexState.Tab;
}
else if (char.IsLetter(c))
{
if (!IsInOurLetterRange(c, out SpanBreakInfo brkInfo))
{
//letter is OUT_OF_RANGE
if (i > bb.startIndex)
{
//???TODO: review here
//flush
bb.length = i - bb.startIndex;
//
OnBreak(visitor, bb);
bb.startIndex += bb.length;//***
}
if (char.IsHighSurrogate(c))
{
lexState = LexState.CollectSurrogatePair;
goto case LexState.CollectSurrogatePair;
}
if (enableUnicodeRangeBreaker)
{
//collect text until end for specific unicode range eng
//find a proper unicode engine and collect until end of its range
lexState = LexState.CollectConsecutiveUnicode;
goto case LexState.CollectConsecutiveUnicode;
}
else
{
visitor.State = VisitorState.OutOfRangeChar;
return;
}
}
visitor.SpanBreakInfo = brkInfo;
//just collect
bb.startIndex = i;
bb.kind = WordKind.Text;
lexState = LexState.Text;
}
else if (char.IsNumber(c))
{
bb.startIndex = i;
bb.kind = WordKind.Number;
lexState = LexState.Number;
}
else if (char.IsWhiteSpace(c))
{
//other whitespace***=> similar to control
bb.startIndex = i;
bb.length = 1;
bb.kind = WordKind.OtherWhitespace;
//
OnBreak(visitor, bb);
//
bb.length = 0;
bb.startIndex++;
lexState = LexState.Init;
continue;
}
else if (char.IsControl(c))
{
//\t is control and \t is also whitespace
//we assign that \t to be a control
bb.startIndex = i;
bb.length = 1;
bb.kind = WordKind.Control;
//
OnBreak(visitor, bb);
//
bb.length = 0;
bb.startIndex++;
lexState = LexState.Init;
continue;
}
else if (char.IsPunctuation(c) || char.IsSymbol(c))
{
//for eng -
if (c == '-')
{
//check next char is number or not
if (i < endBefore - 1 &&
char.IsNumber(input[i + 1]))
{
bb.startIndex = i;
bb.kind = WordKind.Number;
lexState = LexState.Number;
continue;
}
}
bb.startIndex = i;
bb.length = 1;
bb.kind = WordKind.Punc;
//we not collect punc
OnBreak(visitor, bb);
//
bb.startIndex += 1;
bb.length = 0;
bb.kind = WordKind.Unknown;
lexState = LexState.Init;
continue;
}
else if (char.IsHighSurrogate(c))
{
lexState = LexState.CollectSurrogatePair;
goto case LexState.CollectSurrogatePair;
}
else
{
if (enableUnicodeRangeBreaker)
{
lexState = LexState.CollectConsecutiveUnicode;
goto case LexState.CollectConsecutiveUnicode;
}
else
{
visitor.State = VisitorState.OutOfRangeChar;
return;
}
}
}
break;
case LexState.Number:
{
//in number state
if (!char.IsNumber(c) && c != '.')
{
//if not
//flush current state
bb.length = i - bb.startIndex;
bb.kind = WordKind.Number;
//
OnBreak(visitor, bb);
//
bb.length = 0;
bb.startIndex = i;
bb.kind = WordKind.Unknown;
lexState = LexState.Init;
goto case LexState.Init;
}
}
break;
case LexState.Text:
{
//we are in letter mode
if (char.IsNumber(c))
{
//flush
if (BreakNumberAfterText)
{
bb.length = i - bb.startIndex;
bb.kind = WordKind.Text;
//
OnBreak(visitor, bb);
//
bb.length = 1;
bb.startIndex = i;
lexState = LexState.Number;
}
}
else if (char.IsLetter(c))
{
//c is letter
if (!IsInOurLetterRange(c, out SpanBreakInfo brkInfo))
{
if (i > bb.startIndex)
{
//flush
bb.length = i - bb.startIndex;
bb.kind = WordKind.Text;
//
OnBreak(visitor, bb);
//TODO: check if we should set startIndex and length
// like other 'after' onBreak()
bb.startIndex += bb.length;//***
}
if (char.IsHighSurrogate(c))
{
lexState = LexState.CollectSurrogatePair;
goto case LexState.CollectSurrogatePair;
}
if (enableUnicodeRangeBreaker)
{
lexState = LexState.CollectConsecutiveUnicode;
goto case LexState.CollectConsecutiveUnicode;
}
else
{
visitor.State = VisitorState.OutOfRangeChar;
return;
}
}
//if this is a letter in our range
//special for eng breaking ening, check
//if a letter is in basic latin range or not
//------------------
if (visitor.SpanBreakInfo != brkInfo)
{
//mixed span break info => change to general latin
visitor.SpanBreakInfo = s_latin;
}
}
else if (c == '.' && !breakPeroidInTextSpan)
{
//continue collecting
}
else
{
//other characer
//flush existing text ***
bb.length = i - bb.startIndex;
bb.kind = WordKind.Text;
//
OnBreak(visitor, bb);
//
bb.length = 0;
bb.startIndex = i;
bb.kind = WordKind.Unknown;
lexState = LexState.Init;
goto case LexState.Init;
}
}
break;
case LexState.Whitespace:
{
//for explicit whitespace
if (c != ' ')
{
bb.length = i - bb.startIndex;
bb.kind = WordKind.Whitespace;
//
OnBreak(visitor, bb);
//
bb.length = 0;
bb.startIndex = i;
bb.kind = WordKind.Unknown;
lexState = LexState.Init;
goto case LexState.Init;
}
}
break;
case LexState.Tab:
{
if (c != '\t')
{
bb.length = i - bb.startIndex;
bb.kind = WordKind.Tab;
//
OnBreak(visitor, bb);
//
bb.length = 0;
bb.startIndex = i;
bb.kind = WordKind.Unknown;
lexState = LexState.Init;
goto case LexState.Init;
}
}
break;
case LexState.CollectSurrogatePair:
{
if (i == endBefore - 1)
{
//can't check next char
//error
bb.length = 1;
bb.kind = WordKind.Unknown; //error
OnBreak(visitor, bb);
bb.length = 0; //reset
bb.startIndex++;
lexState = LexState.Init;
continue; //***
}
else
{
if (!char.IsLowSurrogate(input[i + 1]))
{
//the next one this not low surrogate
//so this is error too
bb.length = 1;
bb.kind = WordKind.Unknown; //error
OnBreak(visitor, bb);
bb.length = 0; //reset
bb.startIndex++;
lexState = LexState.Init;
continue; //***
}
else
{
//surrogate pair
//clear accum state
if (i > bb.startIndex)
{
//some remaining data
bb.length = i - bb.startIndex;
//
OnBreak(visitor, bb);
}
//-------------------------------
//surrogate pair
if (SurrogatePairBreakingOption == SurrogatePairBreakingOption.OnlySurrogatePair)
{
bb.startIndex = i;
bb.length = 2;
bb.kind = WordKind.SurrogatePair;
OnBreak(visitor, bb);
i++;//consume next***
bb.startIndex += 2;//reset
}
else
{
//see https://github.com/LayoutFarm/Typography/issues/18#issuecomment-345480185
int begin = i + 2;
CollectConsecutiveSurrogatePairs(input, ref begin, endBefore - begin, SurrogatePairBreakingOption == SurrogatePairBreakingOption.ConsecutiveSurrogatePairsAndJoiner);
bb.startIndex = i;
bb.length = begin - i;
bb.kind = WordKind.SurrogatePair;
OnBreak(visitor, bb);
i += bb.length - 1;//consume
bb.startIndex += bb.length;//reset
}
bb.length = 0; //reset
lexState = LexState.Init;
continue; //***
}
}
}
break;
case LexState.CollectConsecutiveUnicode:
{
int begin = i;
bb.startIndex = i;
bb.kind = WordKind.Text;
CollectConsecutiveUnicodeRange(input, ref begin, endBefore, out SpanBreakInfo spBreakInfo);
bb.length = begin - i;
if (bb.length > 0)
{
visitor.SpanBreakInfo = spBreakInfo;
OnBreak(visitor, bb); //flush
visitor.SpanBreakInfo = s_latin;//switch back
bb.length = 0;
bb.startIndex = begin;
}
else
{
throw new NotSupportedException();///???
}
i = begin - 1;
lexState = LexState.Init;
}
break;
}
}
if (lexState != LexState.Init &&
bb.startIndex < start + len)
{
//some remaining data
bb.length = (start + len) - bb.startIndex;
//
OnBreak(visitor, bb);
//
}
visitor.State = VisitorState.End;
}
}
}
|
using Pea.Geometry.General;
namespace Pea.Geometry2D.Transformations
{
public abstract class Transformation2D : Matrix<Vector2D>
{
public Transformation2D() : base(3)
{
}
public static Transformation2D operator *(Transformation2D transformation1, Transformation2D transformation2)
{
return ((Matrix<Vector2D>)transformation1 * (Matrix<Vector2D>)transformation2) as Transformation2D;
}
}
}
|
namespace SharedViewModels.Helpers
{
public static class StaticMessageBoxSpawner
{
public static IMessageBoxSpawner Spawner { get; set; }
public static void Show(string message)
=> Spawner.Show(message);
public static MessageBoxResult Show(string message, string title, MessageBoxButtons buttons)
=> Spawner.Show(message, title, buttons);
}
}
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Storage.Table;
namespace TableQueryParser.Core
{
public static class QueryParser
{
public static bool Validate<T>(string query, T data) where T : TableEntity
{
return ExpressionList
.From(new Statement(query, 0))
.Resolve(data);
}
public static IEnumerable<T> Filter<T>(string query, IEnumerable<T> data) where T : TableEntity
{
var expressionList = ExpressionList.From(new Statement(query, 0));
return data.Where(expressionList.Resolve);
}
}
} |
using System;
using Exemplo002_Composicao.Entities;
using Exemplo002_Composicao.Entities.Enums;
namespace Exemplo002_Composicao
{
class Program
{
static void Main(string[] args)
{
string nameDept, nome;
double salarioBase;
int numContratos, mes, ano;
string mesAno;
Console.Write("Entre com o nome do departamento: ");
nameDept = Console.ReadLine();
Console.WriteLine("Entre com os dados do trabalhador");
Console.Write("Nome: ");
nome = Console.ReadLine();
Console.Write("Level (Junior/MidLevel/Senior): ");
WorkerLevel level = Enum.Parse<WorkerLevel>(Console.ReadLine());
Console.Write("Insira o salário do trabalhador: ");
salarioBase = double.Parse(Console.ReadLine());
Department department = new Department(nameDept);
Worker worker = new Worker(nome, level, salarioBase, department);
Console.Write("Quantos contratos para esse trabalhador? ");
numContratos = int.Parse(Console.ReadLine());
for(int i = 0; i< numContratos; i++)
{
DateTime date;
double valorPorHora;
int duracao;
Console.WriteLine($"Entre com dos dados do contrato #{i+1} ");
Console.Write("Insira a data: DD/MM/AAAA: ");
date = DateTime.Parse(Console.ReadLine());
Console.Write("Valor por hora: ");
valorPorHora = double.Parse(Console.ReadLine());
Console.Write("Duração (em horas) do contrato: ");
duracao = int.Parse(Console.ReadLine());
HourContract contrato = new HourContract(date, valorPorHora, duracao);
worker.AddContract(contrato);
}
Console.WriteLine();
Console.Write("Entre com o mês e o ano no formato MM/AAAA para calcular os ganhos: ");
mesAno = Console.ReadLine();
mes = int.Parse(mesAno.Substring(0, 2));
ano = int.Parse(mesAno.Substring(3));
Console.WriteLine($"Nome: {worker.Name}");
Console.WriteLine($"Departamento: {worker.Department.Name}");
Console.WriteLine($"Ganhos em {mesAno}: {worker.Income(ano, mes)}");
}
}
}
|
using gifty.Shared.CQRS.Contracts;
using gifty.Shared.CQRS.Handlers;
using gifty.Shared.IoC;
using RawRabbit;
using RawRabbit.vNext;
namespace gifty.Shared.ServiceBus
{
internal sealed class ServiceBus : IServiceBus
{
private readonly IBusClient _busClient;
private readonly ICustomDependencyResolver _customDependencyResolver;
public ServiceBus(ICustomDependencyResolver customDependencyResolver)
{
_busClient = BusClientFactory.CreateDefault();
_customDependencyResolver = customDependencyResolver;
}
public void SubscribeToCommand<TCommand>(string queueName) where TCommand : ICommand
{
_busClient.SubscribeAsync<TCommand>(async (command, context) =>
{
var commandHandler = _customDependencyResolver.Resolve<ICommandHandler<TCommand>>();
await commandHandler.HandleAsync(command);
}, cfg => cfg.WithQueue(q => q.WithName(queueName)));
}
public void SubscribeToEvent<TEvent>(string queueName) where TEvent : IEvent
{
_busClient.SubscribeAsync<TEvent>(async (@event, context) =>
{
var commandHandler = _customDependencyResolver.Resolve<IEventHandler<TEvent>>();
await commandHandler.HandleAsync(@event);
}, cfg => cfg.WithQueue(q => q.WithName(queueName)));
}
}
} |
using NUnit.Framework;
using QuakeConsole.Tests.Utilities;
namespace QuakeConsole.Tests
{
[TestFixture]
public class AssignmentAutocompletionTestses : TestsBase
{
private const string FirstInstanceName = "instance";
private const string StaticClassName = "Podobranchia";
private const string TargetFieldName = FirstInstanceName + ".Cymidine";
private const string TargetBooleanType = StaticClassName + ".Gymnogen";
private const string StringInstanceNameAndValue = "instance_c";
public override void Setup()
{
base.Setup();
Interpreter.AddVariable(FirstInstanceName, new Kickup(), int.MaxValue);
Interpreter.AddVariable(StringInstanceNameAndValue, StringInstanceNameAndValue, int.MaxValue);
Interpreter.AddType(typeof(Podobranchia), int.MaxValue);
}
[Test]
public void DerivedInstanceAssignableToBaseInstanceType()
{
var baseVar = new Base();
var derivedVar = new Derived();
Interpreter.AddVariable("base", baseVar);
Interpreter.AddVariable("derived", derivedVar);
Input.Value = "base=";
Input.CaretIndex = Input.Length;
Interpreter.Autocomplete(Input, true); // =base
Interpreter.Autocomplete(Input, true); // =derived
Assert.AreEqual("base=derived", Input.Value);
}
[Test]
public void DerivedStaticAssignableToBaseInstanceType() // Python ctor syntax
{
var baseVar = new Base();
var derivedVar = new Derived();
Interpreter.AddVariable("base", baseVar);
Interpreter.AddVariable("derived", derivedVar);
Input.Value = "base=";
Input.CaretIndex = Input.Length;
Interpreter.Autocomplete(Input, true); // =base
Interpreter.Autocomplete(Input, true); // =derived
Interpreter.Autocomplete(Input, true); // =Base
Interpreter.Autocomplete(Input, true); // =Derived
Assert.AreEqual("base=Derived", Input.Value);
}
[Test]
public void InstanceStringFieldInput_Assignment_CaretAtEnd_Autocomplete_StringInstanceSelected()
{
Input.Value = TargetFieldName + Assignment;
Input.CaretIndex = Input.Length;
Interpreter.Autocomplete(Input, true);
Assert.AreEqual(TargetFieldName + Assignment + StringInstanceNameAndValue, Input.Value);
}
[Test]
public void InstanceStringFieldInput_Assignment_CaretAtEnd_AutocompleteTwice_StringTypeSelected()
{
Input.Value = TargetFieldName + Assignment;
Input.CaretIndex = Input.Length;
Interpreter.Autocomplete(Input, true);
Interpreter.Autocomplete(Input, true);
Assert.AreEqual(TargetFieldName + Assignment + "String", Input.Value);
}
[Test]
public void InstanceStringFieldInput_Assignment_Space_CaretAtEnd_Autocomplete_StringInstanceSelected()
{
Input.Value = TargetFieldName + Assignment + Space;
Input.CaretIndex = Input.Length;
Interpreter.Autocomplete(Input, true);
Assert.AreEqual(TargetFieldName + Assignment + Space + StringInstanceNameAndValue, Input.Value);
}
[Test]
public void BoolType_Assignment_CaretAtEnd_Autocomplete_PredefinedTypeSelected()
{
Input.Value = TargetBooleanType + Assignment;
Input.CaretIndex = Input.Length;
Interpreter.Autocomplete(Input, true);
Assert.AreEqual(TargetBooleanType + Assignment + "False", Input.Value);
}
[Test]
public void NewVariable_Assignment_CaretAtEnd_Autocomplete_FirstInstanceSelected()
{
Input.Value = "x" + Assignment;
Input.CaretIndex = Input.Length;
Interpreter.Autocomplete(Input, true);
Assert.AreEqual("x" + Assignment + FirstInstanceName, Input.Value);
}
}
public class Base
{
}
public class Derived : Base
{
}
}
|
namespace SkylordsRebornAPI.Replay.Data
{
public struct Card
{
public ushort Id { get; set; }
public ushort Upgrades { get; set; }
public byte Charges { get; set; }
}
} |
using System.Collections.Generic;
using TodoRESTService.Models;
namespace TodoRESTService.Services
{
public interface ITodoRepository
{
bool DoesItemExist(string id);
IEnumerable<TodoItem> All { get; }
TodoItem Find(string id);
void Insert(TodoItem item);
void Update(TodoItem item);
void Delete(string id);
}
}
|
using System.Collections.Generic;
using System.IO;
namespace Model.CsvReader
{
public static class CsvReader
{
public static IEnumerable<IEnumerable<string>> ReadCsv(string filePath)
{
using (var reader = new StreamReader(new FileStream(filePath, FileMode.Open)))
{
while(!reader.EndOfStream)
yield return reader.ReadLine()?.Split(';');
}
}
}
} |
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace BankSafe.Tests
{
public class BankVaultTests
{
private Dictionary<string, Item> vaultCells;
private BankVault bankVault;
private Item item;
[SetUp]
public void Setup()
{
bankVault = new BankVault();
item = new Item("Ivan", "1234");
this.vaultCells = new Dictionary<string, Item>
{
{"A1", null},
{"A2", null},
{"A3", null},
{"A4", null},
{"B1", null},
{"B2", null},
{"B3", null},
{"B4", null},
{"C1", null},
{"C2", null},
{"C3", null},
{"C4", null},
};
}
[Test]
public void TestConstructor()
{
int actualCount = vaultCells.Count;
int expectedCount = 12;
Assert.AreEqual(expectedCount, actualCount);
}
[Test]
public void ExceptionWhenItemIsNull()
{
Assert.Throws<ArgumentException>(() => bankVault.AddItem("A6", null));
}
[Test]
public void ExceptionWhenAlreadyExistingItem()
{
bankVault.AddItem("A1", item);
Assert.Throws<ArgumentException>(() => bankVault.AddItem("A1", null));
}
[Test]
public void TestAddItemMethod()
{
bankVault.AddItem("A1", item);
Assert.Throws<InvalidOperationException>(() => bankVault.AddItem("A2", item));
}
[Test]
public void TestReturnMessage()
{
Assert.That(bankVault.AddItem("A1", item), Is.EqualTo($"Item:{item.ItemId} saved successfully!"));
}
[Test]
public void ExceptionWhenRemoveOfNotExistingCell()
{
Assert.Throws<ArgumentException>(() => bankVault.RemoveItem("A7", null));
}
[Test]
public void ExceptionWhenRemoveOfNotExistingItem()
{
Assert.Throws<ArgumentException>(() => bankVault.RemoveItem("A1", item));
}
[Test]
public void TestRemoveItemMethod()
{
bankVault.AddItem("A1", item);
var result = bankVault.RemoveItem("A1", item);
var expected = $"Remove item:{item.ItemId} successfully!";
Assert.AreEqual(expected, result);
}
}
} |
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
namespace Trippit.ExtensionMethods
{
public static class TaskExtensions
{
public static void DoNotAwait(this Task task) { }
public static void DoNotAwait<T>(this Task<T> task) { }
public static void DoNotAwait(this IAsyncAction task) { }
private static readonly TaskFactory _myTaskFactory =
new TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return _myTaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func<Task> func)
{
_myTaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
}
}
|
using Microsoft.AspNetCore.Components;
namespace BlazorComponent
{
public partial class BTimelineItemOpposite<TTimelineItem> where TTimelineItem : ITimelineItem
{
public RenderFragment OppositeContent => Component.OppositeContent;
}
}
|
using Microsoft.Extensions.Configuration;
using System;
using YamlDotNet.Core;
using System.IO;
namespace SpoiledCat.Extensions.Configuration
{
public class YamlConfigurationProvider : FileConfigurationProvider
{
public YamlConfigurationProvider(YamlConfigurationSource source) : base(source) { }
public override void Load(Stream stream)
{
var parser = new YamlConfigurationFileParser();
try
{
Data = parser.Parse(stream);
}
catch (YamlException e)
{
throw new FormatException(e.Message, e);
}
}
}
}
|
using LineBotKit.Client.Request;
using LineBotKit.Client.Response;
using LinetBotKit.Common.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace LineBotKit.Client
{
public class UserClient: Request.LineClientBase,IUserClient
{
public UserClient(string channelAccessToken) : base(channelAccessToken)
{
}
/// <summary>
/// Get user profile
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public async Task<LineClientResult<Profile>> GetProfile(string userId)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException("The property user iden can't not be null");
}
var request = new LineGetRequest<Profile>(this, $"bot/profile/{userId}");
return await request.Execute();
}
}
}
|
using Alabo.Properties;
using Microsoft.AspNetCore.Identity;
namespace Alabo.Security.Identity.Describers {
/// <summary>
/// Identity中文错误描述
/// </summary>
public class IdentityErrorChineseDescriber : IdentityErrorDescriber {
/// <summary>
/// 密码太短
/// </summary>
public override IdentityError PasswordTooShort(int length) {
return new IdentityError {
Code = nameof(PasswordTooShort),
Description = string.Format(SecurityResource.PasswordTooShort, length)
};
}
/// <summary>
/// 密码应包含非字母和数字的特殊字符
/// </summary>
public override IdentityError PasswordRequiresNonAlphanumeric() {
return new IdentityError {
Code = nameof(PasswordRequiresNonAlphanumeric),
Description = SecurityResource.PasswordRequiresNonAlphanumeric
};
}
/// <summary>
/// 密码应包含大写字母
/// </summary>
public override IdentityError PasswordRequiresUpper() {
return new IdentityError {
Code = nameof(PasswordRequiresUpper),
Description = SecurityResource.PasswordRequiresUpper
};
}
/// <summary>
/// 密码应包含数字
/// </summary>
public override IdentityError PasswordRequiresDigit() {
return new IdentityError {
Code = nameof(PasswordRequiresDigit),
Description = SecurityResource.PasswordRequiresDigit
};
}
/// <summary>
/// 密码应包含不重复的字符数
/// </summary>
public override IdentityError PasswordRequiresUniqueChars(int uniqueChars) {
return new IdentityError {
Code = nameof(PasswordRequiresUniqueChars),
Description = string.Format(SecurityResource.PasswordRequiresUniqueChars, uniqueChars)
};
}
/// <summary>
/// 无效用户名
/// </summary>
public override IdentityError InvalidUserName(string userName) {
return new IdentityError {
Code = nameof(InvalidUserName),
Description = string.Format(SecurityResource.InvalidUserName, userName)
};
}
/// <summary>
/// 用户名重复
/// </summary>
public override IdentityError DuplicateUserName(string userName) {
return new IdentityError {
Code = nameof(DuplicateUserName),
Description = string.Format(SecurityResource.DuplicateUserName, userName)
};
}
/// <summary>
/// 电子邮件重复
/// </summary>
public override IdentityError DuplicateEmail(string email) {
return new IdentityError {
Code = nameof(DuplicateEmail),
Description = string.Format(SecurityResource.DuplicateEmail, email)
};
}
/// <summary>
/// 无效令牌
/// </summary>
public override IdentityError InvalidToken() {
return new IdentityError {
Code = nameof(InvalidToken),
Description = SecurityResource.InvalidToken
};
}
/// <summary>
/// 密码错误
/// </summary>
public override IdentityError PasswordMismatch() {
return new IdentityError {
Code = nameof(PasswordMismatch),
Description = SecurityResource.PasswordMismatch
};
}
/// <summary>
/// 角色名无效
/// </summary>
public override IdentityError InvalidRoleName(string role) {
return new IdentityError {
Code = nameof(InvalidRoleName),
Description = string.Format(SecurityResource.InvalidRoleName, role)
};
}
/// <summary>
/// 角色名重复
/// </summary>
public override IdentityError DuplicateRoleName(string role) {
return new IdentityError {
Code = nameof(DuplicateRoleName),
Description = string.Format(SecurityResource.DuplicateRoleName, role)
};
}
}
} |
using Newtonsoft.Json;
namespace TheMovieDbNet.Models.Common
{
/// <summary>
/// Represents a generic class that holds data about paged data.
/// </summary>
public class PagedResult<T> where T : Entity
{
[JsonConstructor]
internal PagedResult(T[] results, int total_results, int total_pages, int page)
{
Results = results;
TotalResults = total_results;
TotalPages = total_pages;
Page = page;
}
/// <summary>
/// Gets the array of resulting entities.
/// </summary>
public T[] Results { get; }
/// <summary>
/// Gets the total number of results available.
/// </summary>
public int TotalResults { get; }
/// <summary>
/// Gets the total number of pages available.
/// </summary>
public int TotalPages { get; }
/// <summary>
/// Gets the current page of the result.
/// </summary>
public int Page { get; }
}
} |
using System;
using TechTalk.SpecFlow;
namespace RestaurantApp.Voting.AcceptanceTests.Transforms
{
[Binding]
public class DateTimeTransforms
{
protected VotingTestContext VotingTestContext { get; set; }
public DateTimeTransforms(VotingTestContext context)
{
VotingTestContext = context;
}
[StepArgumentTransformation(@"de hoje")]
[StepArgumentTransformation(@"hoje")]
public DateTime GetTodaysDate()
{
return VotingTestContext.DateTimeProvider.Now.Date;
}
[StepArgumentTransformation(@"ontem")]
public DateTime GetYesterdaysDate()
{
return VotingTestContext.DateTimeProvider.Now.Date.AddDays(-1);
}
//[StepArgumentTransformation]
public DateTime ConvertDate(string date)
{
return DateTime.Parse(date);
}
}
}
|
using DockerVirtualBoxExpose.Common.Entities;
using DockerVirtualBoxExpose.DockerAgent.HostNotification;
using DockerVirtualBoxExpose.DockerAgent.Watchdog;
using NSubstitute;
using Xunit;
namespace DockerVirtualBoxExpose.DockerAgent.Tests.Watchdog
{
public class ExposedServiceWatcherTest
{
[Fact]
public void ShouldNotifyWhenCallingWatchEventRaised()
{
var notificationService = Substitute.For<IHostNotificationService>();
var watcher = new ExposedServiceWatcher(notificationService);
var exposedService = new ExposedService("test", 80);
watcher.WatchEventRaised(exposedService);
notificationService.Received().Notify(exposedService);
}
}
}
|
using NUnit.Framework;
using SQMImportExport.Import.Context;
using SQMImportExport.Import.DataSetters;
namespace SQMImportExport.Tests.Import
{
[TestFixture]
public class DoublePropertySetterTests
{
private double? _value;
private DoublePropertySetter _doublePropertySetter;
[SetUp]
public void Setup()
{
_doublePropertySetter = new DoublePropertySetter("camelot", x => _value = x);
}
[Test]
public void Expect_property_setter_to_set_property_on_match()
{
var inputText = @"camelot=5.45";
var matchResult = _doublePropertySetter.SetValueIfLineMatches(new SqmLine(inputText));
Assert.AreEqual(Result.Success, matchResult);
Assert.AreEqual(5.45, _value);
}
[Test]
public void Expect_to_not_set_property_and_return_failure_on_incorrect_property()
{
var inputText = @"model=32.42";
var matchResult = _doublePropertySetter.SetValueIfLineMatches(new SqmLine(inputText));
Assert.AreEqual(Result.Failure, matchResult);
Assert.AreNotEqual(32.42, _value);
}
[Test]
public void Expect_to_not_set_property_and_return_failure_on_incorrect_value()
{
var inputText = @"camelot=itsonlyamodel";
var matchResult = _doublePropertySetter.SetValueIfLineMatches(new SqmLine(inputText));
Assert.AreEqual(Result.Failure, matchResult);
Assert.AreNotEqual("itsonlyamodel", _value);
}
[Test]
public void Expect_failure_with_odd_string_value()
{
var inputText = @"She'sAWitch!";
var matchResult = _doublePropertySetter.SetValueIfLineMatches(new SqmLine(inputText));
Assert.AreEqual(Result.Failure, matchResult);
}
}
}
|
using System.Linq;
using FluentAssertions;
using NSubstitute;
using Wox.Plugin.Links;
using Wox.Plugin.Links.Parsers;
using Wox.Plugins.Common;
using Xunit;
namespace Wox.Links.Tests.Parsers {
public class ImportParserTests {
public ImportParserTests() {
var storage = Substitute.For<IStorage>();
_fileService = Substitute.For<IFileService>();
_saveParser = new ImportParser(storage, _fileService);
_queryInstance = @"link".CreateQuery(@"C:\file.json");
}
private const string FilePath = @"C:\file.json";
private readonly ImportParser _saveParser;
private readonly IFileService _fileService;
private readonly IQuery _queryInstance;
[Fact]
public void ImportedFileExisting_ReturnFalse() {
_fileService.Exists(FilePath).Returns(true);
_fileService.GetExtension(FilePath).Returns(".json");
_saveParser.TryParse(_queryInstance, out var results).Should()
.BeTrue();
results.Should().HaveCount(1);
results.Single().Title.Should().Be("Import configuration file 'file.json' and replace current");
}
[Fact]
public void ImportedFileNotExisting_ReturnFalse() {
_fileService.Exists(FilePath).Returns(false);
_saveParser.TryParse(_queryInstance, out var results).Should()
.BeFalse();
}
}
} |
using System;
namespace Magnesium
{
[Flags]
public enum MgColorComponentFlagBits : byte
{
R_BIT = 0x00000001,
G_BIT = 0x00000002,
B_BIT = 0x00000004,
A_BIT = 0x00000008,
}
}
|
using System.Runtime.CompilerServices;
namespace System.Reflection {
[Imported(TypeCheckCode = "{this}.type === 8")]
[Serializable]
public class MethodInfo : MethodBase {
public Type ReturnType { get; private set; }
[InlineCode("{$System.Script}.midel({this})")]
public Delegate CreateDelegate(Type delegateType) { return null; }
[InlineCode("{$System.Script}.midel({this}, {target})")]
public Delegate CreateDelegate(Type delegateType, object target) { return null; }
[InlineCode("{$System.Script}.midel({this})")]
public Delegate CreateDelegate() { return null; }
[InlineCode("{$System.Script}.midel({this}, {target})")]
public Delegate CreateDelegate(object target) { return null; }
[InlineCode("{$System.Script}.midel({this}, null, {typeArguments})")]
public Delegate CreateDelegate(Type[] typeArguments) { return null; }
[InlineCode("{$System.Script}.midel({this}, {target}, {typeArguments})")]
public Delegate CreateDelegate(object target, Type[] typeArguments) { return null; }
public int TypeParameterCount { [InlineCode("{this}.tpcount || 0")] get; [InlineCode("X")] private set; }
public bool IsGenericMethodDefinition { [InlineCode("!!{this}.tpcount")] get; [InlineCode("X")] private set; }
[InlineCode("{$System.Script}.midel({this}, {obj})({*arguments})", NonExpandedFormCode = "{$System.Script}.midel({this}, {obj}).apply(null, {arguments})")]
public object Invoke(object obj, params object[] arguments) { return null; }
[InlineCode("{$System.Script}.midel({this}, {obj}, {typeArguments})({*arguments})", NonExpandedFormCode = "{$System.Script}.midel({this}, {obj}, {typeArguments}).apply(null, {arguments})")]
public object Invoke(object obj, Type[] typeArguments, params object[] arguments) { return null; }
/// <summary>
/// Script name of the method. Null if the method has a special implementation.
/// </summary>
[ScriptName("sname")]
public string ScriptName { get; private set;}
/// <summary>
/// If true, this method should be invoked as a static method with the 'this' reference as the first argument. Note that this property does not affect the Invoke and CreateDelegate methods.
/// </summary>
[ScriptName("sm")]
public bool IsStaticMethodWithThisAsFirstArgument { [InlineCode("{this}.sm || false")] get; [InlineCode("{this}.sm = {value}")] private set; }
/// <summary>
/// For methods with a special implementation (eg. [InlineCode]), contains a delegate that represents the method. Null for normal methods.
/// </summary>
[ScriptName("def")]
public Delegate SpecialImplementation { get; private set; }
/// <summary>
/// Whether the [ExpandParams] attribute was specified on the method.
/// </summary>
public bool IsExpandParams { [InlineCode("{this}.exp || false")] get; [InlineCode("{this}.exp = {value}")] private set; }
internal MethodInfo() {}
}
} |
namespace Verno.Portal.Web.Modules.Returns
{
public static class ReturnsPermissionNames
{
public const string Documents = "Documents";
public const string Documents_Returns = Documents + ".Returns";
public const string Documents_Returns_GetFile = Documents_Returns + ".GetFile";
public const string Documents_Returns_UploadFile = Documents_Returns + ".UploadFile";
public const string Documents_Returns_DeleteFile = Documents_Returns + ".DeleteFile";
}
} |
// ****************************************************************
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace NUnit.UiException.Controls
{
/// <summary>
/// The interface through which ErrorList interacts with a painter to paint itself.
///
/// Direct implementation is:
/// - DefaultErrorListRenderer
/// </summary>
public interface IErrorListRenderer
{
/// <summary>
/// Draws the list on the given graphics.
/// </summary>
/// <param name="items">The item collection to paint on the graphics object</param>
/// <param name="selected">The item to paint with selection feature</param>
/// <param name="g">The target graphics object</param>
/// <param name="viewport">The viewport location</param>
void DrawToGraphics(ErrorItemCollection items, ErrorItem selected, Graphics g, Rectangle viewport);
/// <summary>
/// Draw the given item on the given graphics object.
/// </summary>
/// <param name="item">The item to be painted</param>
/// <param name="index">The item's index</param>
/// <param name="hovered">If true, this item can display hover feature</param>
/// <param name="selected">If true, this item can display selection feature</param>
/// <param name="g">The target graphics object</param>
/// <param name="viewport">The current viewport</param>
void DrawItem(ErrorItem item, int index, bool hovered, bool selected, Graphics g, Rectangle viewport);
/// <summary>
/// Given a collection of items and a graphics object, this method
/// measures in pixels the size of the collection.
/// </summary>
/// <param name="items">The collection</param>
/// <param name="g">The target graphics object</param>
/// <returns>The size in pixels of the collection</returns>
Size GetDocumentSize(ErrorItemCollection items, Graphics g);
/// <summary>
/// Gets the Item right under point.
/// </summary>
/// <param name="items">A collection of items</param>
/// <param name="g">The target graphics object</param>
/// <param name="point">Some client coordinate values</param>
/// <returns>One item in the collection or null the location doesn't match any item</returns>
ErrorItem ItemAt(ErrorItemCollection items, Graphics g, Point point);
/// <summary>
/// Gets and sets the font for this renderer
/// </summary>
Font Font { get; set; }
}
}
|
using System;
using System.Reflection;
using Glimpse.Mvc.Message;
namespace Glimpse.Mvc.Model
{
public class ExecutionModel
{
public ExecutionModel(IExecutionMessage message)
{
IsChildAction = message.IsChildAction;
ExecutedType = message.ExecutedType;
ExecutedMethod = message.ExecutedMethod;
Duration = message.Duration;
ActionName = message.ActionName;
ControllerName = message.ControllerName;
var filter = message as IFilterMessage;
if (filter != null)
{
Category = filter.Category;
}
var bounds = message as IBoundedFilterMessage;
if (bounds != null)
{
Bounds = bounds.Bounds;
}
}
public TimeSpan Duration { get; set; }
public MethodInfo ExecutedMethod { get; set; }
public Type ExecutedType { get; set; }
public FilterCategory? Category { get; set; }
public FilterBounds? Bounds { get; set; }
public bool IsChildAction { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
}
} |
using UnityEngine;
using UnityEditor;
using UnityEditor.AssetImporters;
namespace Pugrad {
// Supported colormap type list
public enum ColormapType { Viridis, Plasma, Magma, Inferno, Turbo, HSLuv }
// Custom importer for .pugrad files
[ScriptedImporter(1, "pugrad")]
public sealed class PugradImporter : ScriptedImporter
{
[SerializeField] ColormapType _colormap = ColormapType.Viridis;
[SerializeField] uint _resolution = 256;
[SerializeField] float _lightness = 0.5f;
public override void OnImportAsset(AssetImportContext context)
{
var texture = new Texture2D((int)_resolution, 1);
texture.wrapMode = TextureWrapMode.Clamp;
texture.SetPixels(GenerateColormap(_colormap, _resolution, _lightness));
texture.Apply();
context.AddObjectToAsset("colormap", texture);
context.SetMainObject(texture);
}
static Color[] GenerateColormap(ColormapType type, uint width, float light)
=> type switch
{ ColormapType.Viridis => MatplotlibColormaps.GenerateViridis(width),
ColormapType.Plasma => MatplotlibColormaps.GeneratePlasma(width),
ColormapType.Magma => MatplotlibColormaps.GenerateMagma(width),
ColormapType.Inferno => MatplotlibColormaps.GenerateInferno(width),
ColormapType.Turbo => TurboColormap.Generate(width),
ColormapType.HSLuv => HsluvColormap.Generate(width, light),
_ => null };
}
} // namespace Pugrad
|
//-----------------------------------------------------------------------------
// Runtime: 104ms
// Memory Usage: 28.4 MB
// Link: https://leetcode.com/submissions/detail/257942576/
//-----------------------------------------------------------------------------
using System;
namespace LeetCode
{
public class _0124_BinaryTreeMaximumPathSum
{
private int max_sum = int.MinValue;
public int MaxPathSum(TreeNode root)
{
MaxPathSumCore(root);
return max_sum;
}
public int MaxPathSumCore(TreeNode root)
{
if (root == null) return 0;
var leftSum = Math.Max(MaxPathSumCore(root.left), 0);
var rightSum = Math.Max(MaxPathSumCore(root.right), 0);
max_sum = Math.Max(max_sum, root.val + leftSum + rightSum);
return root.val + Math.Max(leftSum, rightSum);
}
}
}
|
/*
* Copyright 2016-2021 Disig a.s.
*
* 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.
*/
/*
* Written by:
* Marek KLEIN <kleinmrk@gmail.com>
*/
namespace Disig.TimeStampClient
{
/// <summary>
/// PKI statuses according to RFC 3161
/// </summary>
public enum PkiStatus
{
/// <summary>
/// When the PKIStatus contains the value zero a TimeStampToken, as requested, is present.
/// </summary>
Granted = 0,
/// <summary>
/// When the PKIStatus contains the value one a TimeStampToken, with modifications, is present.
/// </summary>
GrantedWithMods = 1,
/// <summary>
/// When the PKIStatus contains the value two a TimeStamp request was rejected.
/// </summary>
Rejection = 2,
/// <summary>
/// The request body part has not yet been processed, expect to hear more later.
/// </summary>
Waiting = 3,
/// <summary>
/// A warning that a revocation is imminent.
/// </summary>
RevocationWarning = 4,
/// <summary>
/// Revocation has occurred.
/// </summary>
RevocationNotification = 5
}
}
|
using UnityEngine;
namespace AAV.Drone.Script.PID {
/// <summary>
///
/// </summary>
[System.Serializable]
public class PidController {
/// <summary>
///
/// </summary>
[SerializeField] double _Kp;
/// <summary>
///
/// </summary>
[SerializeField] double _Ki;
/// <summary>
///
/// </summary>
[SerializeField] double _Kd;
double _error_sum;
/// <summary>
///
/// </summary>
public double _SetPoint;
/// <summary>
///
/// </summary>
public double _MaxWindup;
double _start_time;
double _last_timestamp;
double _last_error;
double _last_windup;
public PidController(
double kp = 0,
double ki = 0,
double kd = 0,
double max_windup = 20,
double start_time = 0) {
this._Kp = kp;
this._Ki = ki;
this._Kd = kd;
this._error_sum = 0;
this._SetPoint = 0;
this._MaxWindup = max_windup;
this._start_time = start_time;
this._last_timestamp = 0;
this._last_error = 0;
}
/// <summary>
///
/// </summary>
public System.Double LastWindup { get { return this._last_windup; } set { this._last_windup = value; } }
public System.Double StartTime { get { return this._start_time; } set { this._start_time = value; } }
public void Reset() {
this._Kp = 0;
this._Ki = 0;
this._Kd = 0;
this._SetPoint = 0;
this._error_sum = 0;
this._last_timestamp = 0;
this._last_error = 0;
this._last_windup = 0;
}
public void SetTarget(double target) { this._SetPoint = target; }
public void SetKp(double kp) { this._Kp = kp; }
public void SetKi(double ki) { this._Ki = ki; }
public void SetKd(double kd) { this._Kd = kd; }
public void SetMaxWindup(double max) { this._MaxWindup = max; }
public void SetStartTime(double time) { this._start_time = time; }
public double Update(double measured_value, double timestamp) {
var delta_time = timestamp - this._last_timestamp;
if (System.Math.Abs(delta_time) < float.Epsilon) {
Debug.Log("delta time was 0");
return 0;
}
var error = this._SetPoint - measured_value;
var delta_error = error - this._last_error;
this._last_timestamp = timestamp;
this._last_error = error;
this._error_sum += error * delta_time;
if (this._error_sum > this._MaxWindup) {
this._error_sum = this._MaxWindup;
} else if (this._error_sum < -this._MaxWindup) {
this._error_sum = -this._MaxWindup;
}
var p = this._Kp * error;
var i = this._Ki * this._error_sum;
var d = this._Kd * (delta_error / delta_time);
return p + i + d;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace projetoJogo1
{
public class pontos
{
bool condicao = false, bloquedo = false;
PictureBox pct;
public void getCondicao(bool parCondicao)
{
if (!bloquedo)
{
condicao = parCondicao;
}
}
public void get_pct(PictureBox par_pct)
{
pct = par_pct;
}
public bool setCondicao()
{
return condicao;
}
public void getBloquedo(bool parBloqueado)
{
bloquedo = parBloqueado;
}
public bool setBloqueado()
{
return bloquedo;
}
public void mudarPonto()
{
if (!bloquedo)
{
if (condicao)
{
condicao = false;
Image SprintPonto = Properties.Resources.pontoNetIcone2;
pct.Image = SprintPonto;
}
else
{
condicao = true;
Image SprintPonto = Properties.Resources.pontoNetIcone;
pct.Image = SprintPonto;
}
}
}
}
}
|
using System;
using System.Threading.Tasks;
using Autofac.Bot.Api.Services.Abstractions.Models;
namespace Autofac.Bot.Api.Services.Abstractions
{
public interface IProjectPublisher
{
Task<ProjectPublishResult> PublishAsync(Uri projectUri, Uri cloneBasePath);
}
} |
using Engine;
namespace Test
{
static internal partial class Program
{
static void Main()
{
Debug.OpenConsole();
E1M1();
Debug.Log("Releasing resources...");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ApiTest
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct GetFxrParams
{
public nuint size;
[MarshalAs(UnmanagedType.LPWStr)]
public string AsmPath;
[MarshalAs(UnmanagedType.LPWStr)]
public string DnRoot;
public void SetSize() { size = (nuint)UIntPtr.Size * 3; }
public void Reset()
{
AsmPath = null;
DnRoot = null;
}
};
internal readonly struct HGetFxrParams
{
[MarshalAs(UnmanagedType.SysInt)]
public readonly IntPtr p;
public unsafe HGetFxrParams(ref GetFxrParams managedp)
{
p = (IntPtr)Unsafe.AsPointer(ref managedp);
}
public static HGetFxrParams Null = new();
}
internal static class NetHost
{
private const string name = "nethost";
private const CallingConvention callconv = CallingConvention.StdCall;
private const CharSet chart = CharSet.Unicode;
[DllImport(name, CallingConvention = callconv, CharSet = chart,
EntryPoint = "get_hostfxr_path", ExactSpelling = true)]
public extern static int GetHostFxrPath(
[MarshalAs(UnmanagedType.LPArray)]
char[] buffer,
ref nuint size,
HGetFxrParams fxrparams
);
public static string GetFxr(ref char[] pathbuff, ref nuint size, HGetFxrParams h)
{
#pragma warning disable CS0652 // 与整数常量比较无意义;该常量不在类型的范围之内
if (GetHostFxrPath(pathbuff, ref size, h) == unchecked(0x80008098))
#pragma warning restore CS0652 // HRESULT
{
pathbuff = new char[size];
Debug.Assert(NetHost.GetHostFxrPath(pathbuff, ref size, h) == 0);
}
string fxrpath = pathbuff.AsSpan().Slice(0, (int)size).ToString();
return fxrpath;
}
}
}
|
using System.Runtime.CompilerServices;
namespace SFML.Graphics
{
public record RenderStates(
BlendMode BlendMode,
Transform Transform,
Texture? Texture,
Shader? Shader)
{
public static readonly RenderStates Default = new();
public RenderStates() : this(BlendMode.Alpha) { }
public RenderStates(BlendMode blendMode) : this(
blendMode,
Transform.Identity,
default,
default)
{ }
public RenderStates(Transform transform) : this(
BlendMode.Alpha,
transform,
default,
default)
{ }
public RenderStates(Texture texture) : this(
BlendMode.Alpha,
Transform.Identity,
texture,
default)
{ }
public RenderStates(Shader shader) : this(
BlendMode.Alpha,
Transform.Identity,
default,
shader)
{ }
internal readonly unsafe Native Handle = new(
BlendMode,
Transform,
Texture is not null ? Texture.Handle : null,
Shader is not null ? Shader.Handle : null);
internal unsafe ref Native GetPinnableReference()
{
return ref Unsafe.AsRef(in Handle);
}
internal readonly unsafe struct Native
{
public readonly BlendMode BlendMode;
public readonly Transform Transform;
public readonly Texture.Native* Texture;
public readonly Shader.Native* Shader;
public Native(
BlendMode blendMode,
Transform transform,
Texture.Native* texture,
Shader.Native* shader)
{
BlendMode = blendMode;
Transform = transform;
Texture = texture;
Shader = shader;
}
}
}
}
|
using Tizen.NUI;
using Tizen.NUI.BaseComponents;
using Tizen.NUI.CommonUI;
namespace NuiCommonUiSamples
{
public class DropDown : IExample
{
private SampleLayout root;
private Tizen.NUI.CommonUI.DropDown dropDown = null;
private Tizen.NUI.CommonUI.DropDown dropDown2 = null;
private ScrollBar scrollBar = null;
private TextLabel text = null;
private static string[] iconImage = new string[]
{
CommonResource.GetResourcePath() + "10. Drop Down/img_dropdown_fahrenheit.png",
CommonResource.GetResourcePath() + "10. Drop Down/img_dropdown_celsius.png",
};
public void Activate()
{
Window.Instance.BackgroundColor = Color.White;
root = new SampleLayout();
root.HeaderText = "DropDown";
text = new TextLabel();
text.Text = "DropDown Clicked item string is ";
text.PointSize = 14;
text.Size2D = new Size2D(880, 50);
text.Position2D = new Position2D(100, 10);
text.HorizontalAlignment = HorizontalAlignment.Center;
text.MultiLine = true;
root.Add(text);
dropDown = new Tizen.NUI.CommonUI.DropDown("HeaderDropDown");
dropDown.Size2D = new Size2D(1080, 108);
dropDown.Position2D = new Position2D(0, 100);
dropDown.ListSize2D = new Size2D(360, 500);
dropDown.HeaderText = "Header area";
dropDown.ButtonText = "Normal list 1";
dropDown.ItemClickEvent += DropDownItemClickEvent;
root.Add(dropDown);
for (int i = 0; i < 8; i++)
{
Tizen.NUI.CommonUI.DropDown.DropDownItemData item = new Tizen.NUI.CommonUI.DropDown.DropDownItemData("TextListItem");
item.Size2D = new Size2D(360, 96);
item.Text = "Normal list " + i;
dropDown.AddItem(item);
}
dropDown.SelectedItemIndex = 1;
////////Attach scrollbar///////////
scrollBar = new ScrollBar();
scrollBar.Direction = ScrollBar.DirectionType.Vertical;
scrollBar.Position2D = new Position2D(394, 2);
scrollBar.Size2D = new Size2D(4, 446);
scrollBar.TrackColor = Color.Green;
scrollBar.ThumbSize = new Size2D(4, 30);
scrollBar.ThumbColor = Color.Yellow;
scrollBar.TrackImageURL = CommonResource.GetResourcePath() + "component/c_progressbar/c_progressbar_white_buffering.png";
dropDown.AttachScrollBar(scrollBar);
//////////////////ListSpinner DropDown////////////////////////
dropDown2 = new Tizen.NUI.CommonUI.DropDown("ListDropDown");
dropDown2.Size2D = new Size2D(1080, 108);
dropDown2.Position2D = new Position2D(0, 300);
dropDown2.ListSize2D = new Size2D(360, 192);
dropDown2.HeaderText = "List area";
dropDown2.ButtonText = "Menu";
root.Add(dropDown2);
for (int i = 0; i < 2; i++)
{
Tizen.NUI.CommonUI.DropDown.DropDownItemData item = new Tizen.NUI.CommonUI.DropDown.DropDownItemData("IconListItem");
item.Size2D = new Size2D(360, 96);
item.IconResourceUrl = iconImage[i];
dropDown2.AddItem(item);
}
dropDown2.SelectedItemIndex = 0;
dropDown.RaiseToTop();
}
private void DropDownItemClickEvent(object sender, Tizen.NUI.CommonUI.DropDown.ItemClickEventArgs e)
{
text.Text = "DropDown Clicked item string is " + e.Text;
}
public void Deactivate()
{
if (root != null)
{
if (text != null)
{
root.Remove(text);
text.Dispose();
text = null;
}
if (dropDown != null)
{
if (scrollBar != null)
{
dropDown.DetachScrollBar();
scrollBar.Dispose();
scrollBar = null;
}
root.Remove(dropDown);
dropDown.Dispose();
dropDown = null;
}
if (dropDown2 != null)
{
root.Remove(dropDown2);
dropDown2.Dispose();
dropDown2 = null;
}
root.Dispose();
}
}
private void ButtonClickEvent(object sender, Tizen.NUI.CommonUI.Button.ClickEventArgs e)
{
Tizen.NUI.CommonUI.Button btn = sender as Tizen.NUI.CommonUI.Button;
}
}
}
|
using System.ComponentModel;
namespace LinqAn.Google.Dimensions
{
/// <summary>
/// DCM Floodlight advertiser ID associated with the floodlight conversion (premium only).
/// </summary>
[Description("DCM Floodlight advertiser ID associated with the floodlight conversion (premium only).")]
public class DcmFloodlightAdvertiserId: Dimension
{
/// <summary>
/// Instantiates a <seealso cref="DcmFloodlightAdvertiserId" />.
/// </summary>
public DcmFloodlightAdvertiserId(): base("DFA Advertiser ID",false,"ga:dcmFloodlightAdvertiserId")
{
}
}
}
|
using System;
namespace iSukces.Code.Interfaces
{
public partial class Auto
{
/// <summary>
/// Treat null as string.Empty or collection without elements
/// </summary>
public class NullIsEmptyAttribute : Attribute
{
}
}
} |
namespace CursoFoop_Exercicio3
{
class CalcularImposto
{
public decimal Calcular(ICalcularImpostoPais icalc)
{
return icalc.CalcularValorImposto();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FluentValidation.WebApi.Models
{
public class ResponseModel
{
public bool IsValid { get; set; }
public List<string> ValidationMessages { get; set; }
public ResponseModel()
{
IsValid = true;
ValidationMessages = new List<string>();
}
}
}
|
// <summary>
// Length, Height and Distance.
// </summary>
// <copyright file="Distance.cs" company="LiSoLi">
// Copyright (c) LiSoLi. All rights reserved.
// </copyright>
// <author>Lennie Wennerlund (lempa)</author>
// https://www.nottingham.ac.uk/manuscriptsandspecialcollections/researchguidance/weightsandmeasures/measurements.aspx
// https://coolconversion.com/lenght/meter-to-barleycorn
// .
// .
namespace LiTools.Helpers.Convert
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Distance.
/// </summary>
public static class Distance
{
/// <summary>
/// Meter Convert into?.
/// </summary>
/// <param name="to">Convert into.</param>
/// <param name="value">Meter Value as double.</param>
/// <returns>Selected value as double.</returns>
public static double Meter(DistanceEnums to, double value)
{
return to switch
{
DistanceEnums.Angstrom => value * 10000000000,
DistanceEnums.Bamboo => value * 0.3125,
DistanceEnums.Barleycorn => value * 117.647058824,
DistanceEnums.Centimeter => value * 100,
DistanceEnums.Fathom => value * 0.546806649169,
DistanceEnums.Finger => value * 8.7489063867,
DistanceEnums.Foot => value * 3.28083989501,
DistanceEnums.Hand => value * 9.84251968504,
DistanceEnums.Inch => value * 39.3700787402,
DistanceEnums.Kilometer => value / 0.001,
DistanceEnums.Meter => value,
DistanceEnums.Mile => value * 0.000621371192,
DistanceEnums.Millimeter => value * 1000,
DistanceEnums.Yard => value * 1.09361329834,
_ => throw new NotImplementedException(),
};
}
/// <summary>
/// Convert meter per second into knots.
/// </summary>
/// <param name="ms">meter per second.</param>
/// <returns>knots as double.</returns>
public static double Meter_PerSecond_To_Knots(double ms)
{
return ms * 1.94384449;
}
}
}
|
using System.ComponentModel.Composition;
namespace Beeffective.Presentation.Common
{
public class ContentViewModel : CoreViewModel
{
[ImportingConstructor]
public ContentViewModel(Main.Core core) : base(core)
{
}
private bool isSelected;
public bool IsSelected
{
get => isSelected;
set => SetProperty(ref isSelected, value);
}
}
} |
using System.ComponentModel.DataAnnotations;
using Abp.Application.Services.Dto;
using YoYoCms.AbpProjectTemplate.UserManagement.Users;
namespace YoYoCms.AbpProjectTemplate.Configuration.Host.Dto
{
public class SendTestEmailInput
{
[Required]
[MaxLength(User.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
}
} |
using Application.Contracts.Persistence;
using Domain.Entities;
using Infrastructure.Persistence;
namespace Infrastructure.Repositories {
public class UserRepository : MongoDBRepositoryBase<User>, IUserRepository {
//* İhtiyaca yönelik User repository
public UserRepository (UserMongoContext context) : base (context) { }
}
} |
using IOTCS.EdgeGateway.Application;
using IOTCS.EdgeGateway.Core;
using IOTCS.EdgeGateway.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace IOTCS.EdgeGateway.Infrastructure.WebApi.Filter
{
public class ManageVerifyAttribute : Attribute, IActionFilter
{
private readonly ILogger _logger;
private readonly RequestDelegate _next;
private readonly IAuthorizationService _authService;
public ManageVerifyAttribute()
{
_logger = IocManager.Instance.GetService<ILogger>();
_authService = IocManager.Instance.GetService<IAuthorizationService>();
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
string authentication = context.HttpContext.Request.Headers["XC-Token"];
if (authentication != null
&& !string.IsNullOrEmpty(authentication))
{
try
{
var isPassed = _authService.ValidateToken(authentication);
if (!isPassed)
{
_logger.Error($"身份验证失败!当前token=>{authentication}");
context.Result = new JsonResult($"身份验证失败!当前token=>{authentication}");
}
}
catch (Exception ex)
{
_logger.Error($"身份验证失败!当前token=>{authentication}, Msg=>{ex.Message},Stack=>{ex.StackTrace}");
context.Result = new JsonResult($"身份验证失败!当前token=>{authentication}");
}
}
else
{
_logger.Error($"身份验证失败!当前token=>{authentication}");
context.Result = new JsonResult($"身份验证失败!当前token=>{authentication}");
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Azure;
using Microsoft.Extensions.Logging;
using PcHubFunctionApp.Helper;
using PcHubFunctionApp.Model;
namespace PcHubFunctionApp.Dao;
internal class ComputerDao : Dao<Computer>
{
public ComputerDao(Config config, ILogger logger) : base(config, logger)
{
}
public List<Computer> GetFreeComputer(string location)
{
var oDataQueryEntities =
TableClient.Query<Computer>($"PartitionKey eq '{location}' and IsOnline eq true and IsReserved eq false");
return oDataQueryEntities.ToList();
}
public Computer GetComputerByEmail(string location, string email)
{
var oDataQueryEntities = TableClient.Query<Computer>($"PartitionKey eq '{location}' and Email eq '{email}'");
return oDataQueryEntities.FirstOrDefault();
}
public Computer GetComputerByMachineName(string location, string machineName)
{
var oDataQueryEntities =
TableClient.Query<Computer>($"PartitionKey eq '{location}' and MachineName eq '{machineName}'");
return oDataQueryEntities.FirstOrDefault();
}
public Computer GetComputerBySeatNumber(string location, int seatNumber)
{
var oDataQueryEntities =
TableClient.Query<Computer>($"PartitionKey eq '{location}'").OrderBy(c => c.MachineName);
return oDataQueryEntities.ElementAtOrDefault(seatNumber);
}
public bool UpdateReservation(Computer computer, string email)
{
try
{
computer.IsReserved = !string.IsNullOrEmpty(email);
computer.Email = email;
TableClient.UpdateEntity(computer, computer.ETag);
return true;
}
catch (RequestFailedException ex)
{
if (ex.Status == 412)
Logger.LogInformation("Optimistic concurrency violation – entity has changed since it was retrieved.");
else
Logger.LogError(ex.Message);
return false;
}
}
} |
using System.Linq;
namespace LivescoreDAL.Description
{
public interface ISearcher<TEntity>
{
IQueryable<TEntity> Search(IQueryable<TEntity> source);
}
}
|
using UnityEngine;
public class AutoRotation : MonoBehaviour
{
public float degPerSec = 60.0f;
public Vector3 rotAxis = Vector3.up;
private void Start()
{
rotAxis.Normalize();
}
private void Update()
{
transform.Rotate(rotAxis, degPerSec * Time.deltaTime);
}
}
|
using System;
using System.IO;
using DataTools.SqlBulkData.Serialisation;
using NUnit.Framework;
namespace DataTools.SqlBulkData.UnitTests.Serialisation
{
[TestFixture]
public class ChunkedFileReaderTests
{
[Test]
public void RestrictsChunkStreamToChunkDataSectionLength()
{
var stream = new MemoryStream(new byte[] {
0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x42
});
var reader = new ChunkedFileReader(stream, new ChunkedFileHeader());
Assume.That(reader.MoveNext(), Is.True);
var buffer = new byte[8];
var count = reader.Current.Stream.Read(buffer, 0, buffer.Length);
Assert.That(reader.Current.Stream.Length, Is.EqualTo(1));
Assert.That(count, Is.EqualTo(1));
Assert.That(buffer, Is.EqualTo(new byte[] { 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }));
}
[Test]
public void ChunkStreamPositionIsRelativeToChunkDataSection()
{
var stream = new MemoryStream(new byte[] {
0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x42, 0x43
});
var reader = new ChunkedFileReader(stream, new ChunkedFileHeader());
Assume.That(reader.MoveNext(), Is.True);
reader.Current.Stream.Position = 1;
Assert.That(Serialiser.ReadByte(reader.Current.Stream), Is.EqualTo(0x43));
}
[Test]
public void CanSeekToEarlierChunk()
{
var stream = new MemoryStream(new byte[] {
0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x42, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
});
var reader = new ChunkedFileReader(stream, new ChunkedFileHeader());
Assume.That(reader.MoveNext(), Is.True);
Assume.That(reader.Current.TypeId, Is.EqualTo(0x00000001));
var firstChunk = reader.Current.GetBookmark();
Assume.That(reader.MoveNext(), Is.True);
Assume.That(reader.Current.TypeId, Is.EqualTo(0x00000002));
reader.SeekTo(firstChunk);
Assert.That(reader.Current.TypeId, Is.EqualTo(0x00000001));
Assert.That(reader.Current.Stream.Length, Is.EqualTo(2));
Assert.That(Serialiser.ReadByte(reader.Current.Stream), Is.EqualTo(0x42));
}
[Test]
public void SeekingToInvalidBookmarkThrowsException()
{
var stream = new MemoryStream(new byte[] {
0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x42, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
});
var reader = new ChunkedFileReader(stream, new ChunkedFileHeader());
Assume.That(reader.MoveNext(), Is.True);
Assume.That(reader.MoveNext(), Is.True);
Assert.Throws<InvalidOperationException>(() => reader.SeekTo(new ChunkBookmark(0x00000001, 8)));
}
[Test]
public void MoveNextReturnsFalseAfterTheLastChunk()
{
var stream = new MemoryStream(new byte[] {
0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x42
});
var reader = new ChunkedFileReader(stream, new ChunkedFileHeader());
Assume.That(reader.MoveNext(), Is.True);
Assume.That(reader.MoveNext(), Is.False);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace _05.NetherRealms
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
Regex paternDemons = new Regex(@"[^((, ))]+");
List<string> demonsName = paternDemons.Matches(input)
.Cast<Match>()
.Select(x => x.Value.Trim())
.ToList();
Regex healthPattern = new Regex(@"[^0-9+\-*\/\.]");
Regex damagePattern = new Regex(@"\+|-?[0-9]+\.?[0-9]*");
Regex damageProcessingPattern = new Regex(@"[*\/]");
Dictionary<string, List<string>> demons = new Dictionary<string, List<string>>();
for (int i = 0; i < demonsName.Count; i++)
{
var healthLetters = healthPattern.Matches(demonsName[i]);
int health = CalculateDemonHealth(healthLetters);
var damageLetters = damagePattern.Matches(demonsName[i]);
double nonproceededDamage = CalculateDemonDamage(damageLetters);
var damageProcessingLetters = damageProcessingPattern.Matches(demonsName[i]);
double proceededDamage = CalculationsOnDamage(nonproceededDamage , damageProcessingLetters);
List<string> tempList = new List<string>();
tempList.Add(health.ToString());
tempList.Add(proceededDamage.ToString());
demons.Add(demonsName[i] , tempList);
}
demons = demons.OrderBy(x => x.Key).ToDictionary(x => x.Key , y => y.Value);
foreach (var demon in demons)
{
Console.WriteLine($"{demon.Key} - {demon.Value[0]} health, {double.Parse(demon.Value[1]):F2} damage");
}
}
public static int CalculateDemonHealth (MatchCollection healthLetters)
{
int health = 0;
foreach (Match match in healthLetters)
{
char temp = match.Value[0];
health += (int)temp;
}
return health;
}
public static double CalculateDemonDamage (MatchCollection damageLetters)
{
double damage = 0;
foreach (Match match in damageLetters)
{
string temp = match.Value;
StringBuilder tempSb = new StringBuilder();
tempSb.Append(temp);
double tempDamage;
if (tempSb[0] == '-')
{
tempSb.Remove(0,1);
tempDamage = double.Parse(tempSb.ToString());
damage -= tempDamage;
}
else if (tempSb[0] == '+')
{
tempSb.Remove(0,1);
tempDamage = double.Parse(tempSb.ToString());
damage += tempDamage;
}
else
{
tempDamage = double.Parse(tempSb.ToString());
damage += tempDamage;
}
}
return damage;
}
public static double CalculationsOnDamage (double nonproceededDamage ,MatchCollection damageProcessingLetters )
{
double damage = nonproceededDamage;
foreach (Match match in damageProcessingLetters)
{
if (match.Value == "*")
{
damage = damage * 2;
}
else if (match.Value == "/")
{
damage = damage / 2;
}
}
return damage;
}
}
}
|
using System.Runtime.InteropServices;
namespace NetShare.WLAN.WinAPI
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NDIS_OBJECT_HEADER
{
public string Type;
public string Revision;
public ushort Size;
}
} |
using System;
using System.Windows.Input;
using CarbonEmissionTool.Models;
namespace CarbonEmissionTool.ViewModels
{
/// <summary>
/// The <see cref="ICommand"/> to run <see cref="CarbonEmissionToolMain"/> mainline function.
/// </summary>
public class RunHbertCommand : ICommand
{
private IPublishDetails _publishDetails;
/// <summary>
/// Constructs a new <see cref="RunHbertCommand"/>.
/// </summary>
public RunHbertCommand(IPublishDetails publishDetails)
{
_publishDetails = publishDetails;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public void Execute(object parameter)
{
var projectDetails = (IProjectDetails) parameter;
CarbonEmissionToolMain.ComputeEmbodiedCarbon(projectDetails, _publishDetails);
}
}
}
|
@model DansBlog.ViewModels.BlogPostViewModel
@{
ViewBag.Title = "Home";
}
@{
Html.RenderPartial("_BlogPost", Model);
}
|
using System.ComponentModel.DataAnnotations;
using PS.Build.Types;
namespace PS.Build.Services
{
/// <summary>
/// Macro resolver service. Add possibility to resolve macro in strings.
/// </summary>
public interface IMacroResolver
{
#region Members
/// <summary>
/// Register macro handler.
/// </summary>
/// <param name="handler">Processor that could handle some of input macro</param>
void Register(IMacroHandler handler);
/// <summary>
/// Resolve input string macro
/// </summary>
/// <param name="source">Source string</param>
/// <param name="errors">The errors that occurred during the input string processing</param>
/// <returns></returns>
string Resolve(string source, out ValidationResult[] errors);
#endregion
}
} |
/// Used with permission from Mariano Omar Rodriguez
/// http://weblogs.asp.net/marianor/archive/2007/10/15/a-wpf-wrapper-around-windows-form-notifyicon.aspx
namespace WPFTaskbarNotifier
{
public enum BalloonTipIcon
{
None = 0,
Info = 1,
Warning = 2,
Error = 3,
}
} |
using System.Collections.Generic;
using Wkb2Gltf;
namespace B3dm.Tileset
{
public static class NodeRecursive
{
public static List<BoundingBox3D> GetBoundingBoxes3D(Node node)
{
var bboxes = new List<BoundingBox3D>();
foreach (var f in node.Features) {
bboxes.Add(f.BoundingBox3D);
}
foreach (var child in node.Children) {
var newboxes = GetBoundingBoxes3D(child);
bboxes.AddRange(newboxes);
}
return bboxes;
}
}
}
|
using System;
using System.Management.Automation;
using Migratio.Core;
using Migratio.Models;
namespace Migratio
{
[Cmdlet(VerbsCommon.Get, "MgScriptsForLatestIteration")]
[OutputType(typeof(Migration[]))]
public class GetMgScriptsForLatestIteration : DbCmdlet
{
public GetMgScriptsForLatestIteration()
{
}
public GetMgScriptsForLatestIteration(CmdletDependencies dependencies) : base(dependencies)
{
}
protected override void ProcessRecord()
{
DatabaseProvider.SetConnectionInfo(GetConnectionInfo());
if (!DatabaseProvider.MigrationTableExists()) throw new Exception("Migration table does not exist");
var processed = DatabaseProvider.GetAppliedScriptsForLatestIteration();
WriteObject(processed);
}
}
} |
namespace BackTesting.Model.MarketData
{
public static class Symbols
{
public static readonly string Sber = "sber";
public static readonly string Vtbr = "vtbr";
}
}
|
using System.Collections.Generic;
using System.Reactive.Linq;
using Caliburn.Micro;
using Espera.Core.Mobile;
using Espera.Core.Settings;
using Espera.View.ViewModels;
namespace Espera.View.DesignTime
{
internal class DesignTimeShellViewModel : ShellViewModel
{
public DesignTimeShellViewModel()
: base(DesignTime.LoadLibrary(), new ViewSettings(), new CoreSettings(), new WindowManager(),
new MobileApiInfo(Observable.Return(new List<MobileClient>()), Observable.Return(false)))
{ }
}
} |
namespace IdentityManager.Core
{
public class IdentityManagerResult<T> : IdentityManagerResult
{
public T Result { get; private set; }
public IdentityManagerResult(T result)
{
Result = result;
}
public IdentityManagerResult(params string[] errors)
: base(errors)
{
}
}
}
|
using System;
using System.Text.RegularExpressions;
namespace AdditionTask
{
class Program
{
static void Main()
{
string petternLogin = @"^[A-Za-z]+$";
string petternPassword = @"^[A-Za-z0-9\S]+$";
Console.Write("Введите логин: ");
string login = Console.ReadLine();
if (!Regex.IsMatch(login, petternLogin))
{
Console.WriteLine("Вы ввели логин который не соответствует шаблону!");
return;
}
Console.Write("Введите пароль: ");
string password = Console.ReadLine();
if (!Regex.IsMatch(password, petternPassword))
{
Console.WriteLine("Вы ввели пароль который не соответствует шаблону!");
return;
}
Console.WriteLine("Вы зарегестрированы!");
Console.ReadKey();
}
}
}
|
using MBP.Contracts.Entities;
using Microsoft.AspNetCore.Identity;
using System;
namespace MBP.Identity.Data.Entities
{
public class MbpRole : IdentityRole<Guid>, ICreatedEntity, IUpdatedEntity
{
public DateTime? CreatedAt { get; set; }
public string CreatedBy { get; set; }
public DateTime? UpdatedAt { get; set; }
public string UpdatedBy { get; set; }
}
}
|
namespace HotChocolate.Types.Filters
{
public interface ISingleFilter<out T> : ISingleFilter
{
T Element { get; }
}
}
|
using System;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Comandante.Tests.Commands
{
public class CommandTests
{
private IServiceProvider _provider;
public CommandTests()
{
var conf = new ServiceCollection();
conf.AddComandate(this.GetType().Assembly);
conf.Decorate(typeof(ICommandHandler<,>), typeof(CommandDecorator<,>));
_provider = conf.BuildServiceProvider();
}
[Fact]
public async Task Command_Is_Null_Throws_ArgumentException()
{
// ARRANGE
CreateUserCommand cmd = null;
var sut = _provider.GetRequiredService<ICommandDispatcher>();
// ACT + ASSERT
await Assert.ThrowsAsync<ArgumentException>(() => sut.Dispatch(cmd, default));
}
[Fact]
public async Task Command_Handle_As_Expected()
{
// ARRANGE
var cmd = new CreateUserCommand("The one");
var sut = _provider.GetRequiredService<ICommandDispatcher>();
// ACT
var userId = await sut.Dispatch(cmd, default);
// ASSERT
userId.Should().Be(42);
}
[Fact]
public async Task Command_Without_Handler_Throws_Exception()
{
// ARRANGE
var cmd = new MissingCommand();
var sut = _provider.GetRequiredService<ICommandDispatcher>();
// ACT + ASSERT
await Assert.ThrowsAsync<ComandanteException>(() => sut.Dispatch(cmd, default));
}
[Fact]
public async Task Command_Throws_Exception_CommandDispatcher_Rethrows_It()
{
// ARRANGE
var query = new ExceptionCommand();
var sut = _provider.GetRequiredService<ICommandDispatcher>();
// ACT + ASSERT
await Assert.ThrowsAsync<CommandException>(() => sut.Dispatch(query, default));
}
}
} |
namespace StrangeAttractor.Util.Functional.Interfaces
{
/// <summary>
/// Encapsulates a value.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IValue<out T>
{
T Value { get; }
bool HasValue { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace HateoasNet.Core.Sample.Models
{
public class Guild
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; }
[JsonIgnore] public ICollection<Member> Members { get; set; } = new List<Member>();
[JsonIgnore] public ICollection<Invite> Invites { get; set; } = new List<Invite>();
}
}
|
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using NvimClient.API;
using NvimClient.API.NvimPlugin;
using NvimClient.API.NvimPlugin.Attributes;
namespace NvimPluginHost
{
internal static class Program
{
private static void Main()
{
Log.WriteLine("Plugin host started");
var nvim = new NvimAPI(Console.OpenStandardOutput(),
Console.OpenStandardInput());
nvim.OnUnhandledRequest += (sender, request) =>
{
// Load the plugin and get the handler asynchronously
Task.Run(() =>
{
var handler = GetPluginHandler(nvim, request.MethodName);
if (handler == null)
{
var error =
$"Could not find request handler for {request.MethodName}";
request.SendResponse(null, error);
Log.WriteLine(error);
return;
}
Log.WriteLine($"Loaded handler for \"{request.MethodName}\"");
try
{
var result = handler(request.Arguments);
request.SendResponse(result);
}
catch (Exception exception)
{
request.SendResponse(null, exception);
}
});
};
nvim.OnUnhandledNotification += (sender, notification) =>
{
// Load the plugin and get the handler asynchronously
Task.Run(() =>
{
GetPluginHandler(nvim, notification.MethodName)
?.Invoke(notification.Arguments);
});
};
nvim.RegisterHandler("poll", args => "ok");
nvim.RegisterHandler("specs", args =>
{
var slnFilePath = (string) args.First();
var pluginType = GetPluginFromSolutionPath(slnFilePath);
return pluginType == null
? null
: PluginHost.GetPluginSpecs(pluginType);
});
nvim.WaitForDisconnect();
Log.WriteLine("Plugin host stopping");
}
private static Func<object[], object> GetPluginHandler(NvimAPI nvim,
string methodName)
{
var methodNameSplit = methodName.Split(':');
// On Windows absolute paths contain a colon after
// the drive letter, so the first two elements must
// be joined together to obtain the file path.
var slnFilePath =
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? $"{methodNameSplit[0]}:{methodNameSplit[1]}"
: methodNameSplit[0];
var pluginType = GetPluginFromSolutionPath(slnFilePath);
var exports =
PluginHost.RegisterPluginExports(nvim, slnFilePath, pluginType);
return exports.FirstOrDefault(export =>
export.HandlerName == methodName)?.Handler;
}
private static Type GetPluginFromSolutionPath(string slnFilePath)
{
var slnFileInfo = new FileInfo(slnFilePath);
// Run the dotnet build command, in case the plugin hasn't
// been built yet, or it needs to be rebuilt.
var buildProcess = Process.Start(
new ProcessStartInfo
{
FileName = "dotnet",
Arguments = "build " + slnFileInfo.FullName,
CreateNoWindow = true
});
buildProcess?.WaitForExit();
var plugin = slnFileInfo.Directory.EnumerateFiles(
"*.dll", SearchOption.AllDirectories)
.SelectMany(dll =>
{
try
{
return new AssemblyResolver(dll.FullName).Assembly.ExportedTypes;
}
catch
{
// Ignore assembly loading failures
return Enumerable.Empty<Type>();
}
})
.FirstOrDefault(type =>
{
try
{
return type.GetCustomAttribute<NvimPluginAttribute>() != null;
}
catch
{
// Ignore type resolution failures
return false;
}
});
return plugin;
}
}
}
|
using System.Collections.Generic;
using FluentAssertions;
using SeatsioDotNet.Events;
using SeatsioDotNet.HoldTokens;
using Xunit;
namespace SeatsioDotNet.Test.Events
{
public class ReleaseObjectsTest : SeatsioClientTest
{
[Fact]
public void Test()
{
var chartKey = CreateTestChart();
var evnt = Client.Events.Create(chartKey);
Client.Events.Book(evnt.Key, new[] {"A-1", "A-2"});
var result = Client.Events.Release(evnt.Key, new[] {"A-1", "A-2"});
Assert.Equal(ObjectStatus.Free, Client.Events.RetrieveObjectStatus(evnt.Key, "A-1").Status);
Assert.Equal(ObjectStatus.Free, Client.Events.RetrieveObjectStatus(evnt.Key, "A-2").Status);
CustomAssert.ContainsOnly(new[] {"A-1", "A-2"}, result.Objects.Keys);
}
[Fact]
public void HoldToken()
{
var chartKey = CreateTestChart();
var evnt = Client.Events.Create(chartKey);
HoldToken holdToken = Client.HoldTokens.Create();
Client.Events.Hold(evnt.Key, new[] {"A-1", "A-2"}, holdToken.Token);
Client.Events.Release(evnt.Key, new[] {"A-1", "A-2"}, holdToken.Token);
var status1 = Client.Events.RetrieveObjectStatus(evnt.Key, "A-1");
Assert.Equal(ObjectStatus.Free, status1.Status);
Assert.Null(status1.HoldToken);
var status2 = Client.Events.RetrieveObjectStatus(evnt.Key, "A-2");
Assert.Equal(ObjectStatus.Free, status2.Status);
Assert.Null(status2.HoldToken);
}
[Fact]
public void OrderId()
{
var chartKey = CreateTestChart();
var evnt = Client.Events.Create(chartKey);
Client.Events.Release(evnt.Key, new[] {"A-1", "A-2"}, null, "order1");
Assert.Equal("order1", Client.Events.RetrieveObjectStatus(evnt.Key, "A-1").OrderId);
Assert.Equal("order1", Client.Events.RetrieveObjectStatus(evnt.Key, "A-2").OrderId);
}
[Fact]
public void KeepExtraData()
{
var chartKey = CreateTestChart();
var evnt = Client.Events.Create(chartKey);
var extraData = new Dictionary<string, object> {{"foo1", "bar1"}};
Client.Events.Book(evnt.Key, new[] {new ObjectProperties("A-1", extraData)});
Client.Events.Release(evnt.Key, new[] {"A-1"}, null, null, true);
Assert.Equal(extraData, Client.Events.RetrieveObjectStatus(evnt.Key, "A-1").ExtraData);
}
[Fact]
public void ChannelKeys()
{
var chartKey = CreateTestChart();
var evnt = Client.Events.Create(chartKey);
var channels = new Dictionary<string, Channel>()
{
{ "channelKey1", new Channel("channel 1", "#FFFF00", 1) }
};
Client.Events.UpdateChannels(evnt.Key, channels);
Client.Events.AssignObjectsToChannel(evnt.Key, new
{
channelKey1 = new [] {"A-1", "A-2"}
});
Client.Events.Book(evnt.Key, new[] {"A-1"}, null, null, true, null, new[] {"channelKey1"});
Client.Events.Release(evnt.Key, new[] {"A-1"}, null, null, true, null, new[] {"channelKey1"});
Assert.Equal(ObjectStatus.Free, Client.Events.RetrieveObjectStatus(evnt.Key, "A-1").Status);
}
[Fact]
public void IgnoreChannels()
{
var chartKey = CreateTestChart();
var evnt = Client.Events.Create(chartKey);
var channels = new Dictionary<string, Channel>()
{
{ "channelKey1", new Channel("channel 1", "#FFFF00", 1) }
};
Client.Events.UpdateChannels(evnt.Key, channels);
Client.Events.AssignObjectsToChannel(evnt.Key, new
{
channelKey1 = new [] {"A-1", "A-2"}
});
Client.Events.Book(evnt.Key, new[] {"A-1"}, null, null, true, null, new[] {"channelKey1"});
Client.Events.Release(evnt.Key, new[] {"A-1"}, null, null, true, true);
Assert.Equal(ObjectStatus.Free, Client.Events.RetrieveObjectStatus(evnt.Key, "A-1").Status);
}
}
}
|
using System;
using System.IO;
using System.Configuration;
using System.Collections;
using TidyNet.Dom;
/*
HTML parser and pretty printer
Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts
Institute of Technology, Institut National de Recherche en
Informatique et en Automatique, Keio University). All Rights
Reserved.
Contributing Author(s):
Dave Raggett <dsr@w3.org>
Andy Quick <ac.quick@sympatico.ca> (translation to Java)
The contributing author(s) would like to thank all those who
helped with testing, bug fixes, and patience. This wouldn't
have been possible without all of you.
COPYRIGHT NOTICE:
This software and documentation is provided "as is," and
the copyright holders and contributing author(s) make no
representations or warranties, express or implied, including
but not limited to, warranties of merchantability or fitness
for any particular purpose or that the use of the software or
documentation will not infringe any third party patents,
copyrights, trademarks or other rights.
The copyright holders and contributing author(s) will not be
liable for any direct, indirect, special or consequential damages
arising out of any use of the software or documentation, even if
advised of the possibility of such damage.
Permission is hereby granted to use, copy, modify, and distribute
this source code, or portions hereof, documentation and executables,
for any purpose, without fee, subject to the following restrictions:
1. The origin of this source code must not be misrepresented.
2. Altered versions must be plainly marked as such and must
not be misrepresented as being the original source.
3. This Copyright notice may not be removed or altered from any
source or altered source distribution.
The copyright holders and contributing author(s) specifically
permit, without fee, and encourage the use of this source code
as a component for supporting the Hypertext Markup Language in
commercial products. If you use this source code in a product,
acknowledgment is not required but would be appreciated.
*/
namespace TidyNet
{
/// <summary>
/// <p>HTML parser and pretty printer</p>
///
/// <p>
/// (c) 1998-2000 (W3C) MIT, INRIA, Keio University
/// See Tidy.cs for the copyright notice.
/// Derived from <a href="http://www.w3.org/People/Raggett/tidy">
/// HTML Tidy Release 4 Aug 2000</a>
/// </p>
///
/// <p>
/// Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts
/// Institute of Technology, Institut National de Recherche en
/// Informatique et en Automatique, Keio University). All Rights
/// Reserved.
/// </p>
///
/// <p>
/// Contributing Author(s):<br>
/// <a href="mailto:dsr@w3.org">Dave Raggett</a><br>
/// <a href="mailto:ac.quick@sympatico.ca">Andy Quick</a> (translation to Java)
/// <a href="mailto:seth_yates@hotmail.com">Seth Yates</a> (translation to C#)
/// </p>
///
/// <p>
/// The contributing author(s) would like to thank all those who
/// helped with testing, bug fixes, and patience. This wouldn't
/// have been possible without all of you.
/// </p>
///
/// <p>
/// COPYRIGHT NOTICE:<br>
///
/// This software and documentation is provided "as is," and
/// the copyright holders and contributing author(s) make no
/// representations or warranties, express or implied, including
/// but not limited to, warranties of merchantability or fitness
/// for any particular purpose or that the use of the software or
/// documentation will not infringe any third party patents,
/// copyrights, trademarks or other rights.
/// </p>
///
/// <p>
/// The copyright holders and contributing author(s) will not be
/// liable for any direct, indirect, special or consequential damages
/// arising out of any use of the software or documentation, even if
/// advised of the possibility of such damage.
/// </p>
///
/// <p>
/// Permission is hereby granted to use, copy, modify, and distribute
/// this source code, or portions hereof, documentation and executables,
/// for any purpose, without fee, subject to the following restrictions:
/// </p>
///
/// <p>
/// <ol>
/// <li>The origin of this source code must not be misrepresented.</li>
/// <li>Altered versions must be plainly marked as such and must
/// not be misrepresented as being the original source.</li>
/// <li>This Copyright notice may not be removed or altered from any
/// source or altered source distribution.</li>
/// </ol>
/// </p>
///
/// <p>
/// The copyright holders and contributing author(s) specifically
/// permit, without fee, and encourage the use of this source code
/// as a component for supporting the Hypertext Markup Language in
/// commercial products. If you use this source code in a product,
/// acknowledgment is not required but would be appreciated.
/// </p>
///
/// </summary>
/// <author>Dave Raggett <dsr@w3.org></author>
/// <author>Andy Quick <ac.quick@sympatico.ca> (translation to Java)</author>
/// <author>Seth Yates <seth_yates@hotmail.com> (translation to C#)</author>
/// <version>1.0, 1999/05/22</version>
/// <version>1.0.1, 1999/05/29</version>
/// <version>1.1, 1999/06/18 Java Bean</version>
/// <version>1.2, 1999/07/10 Tidy Release 7 Jul 1999</version>
/// <version>1.3, 1999/07/30 Tidy Release 26 Jul 1999</version>
/// <version>1.4, 1999/09/04 DOM support</version>
/// <version>1.5, 1999/10/23 Tidy Release 27 Sep 1999</version>
/// <version>1.6, 1999/11/01 Tidy Release 22 Oct 1999</version>
/// <version>1.7, 1999/12/06 Tidy Release 30 Nov 1999</version>
/// <version>1.8, 2000/01/22 Tidy Release 13 Jan 2000</version>
/// <version>1.9, 2000/06/03 Tidy Release 30 Apr 2000</version>
/// <version>1.10, 2000/07/22 Tidy Release 8 Jul 2000</version>
/// <version>1.11, 2000/08/16 Tidy Release 4 Aug 2000</version>
[Serializable]
public class Tidy
{
public Tidy()
{
_options = new TidyOptions();
AttributeTable at = AttributeTable.DefaultAttributeTable;
if (at == null)
{
return;
}
TagTable tt = new TagTable();
if (tt == null)
{
return;
}
tt.Options = _options;
_options.tt = tt;
EntityTable et = EntityTable.DefaultEntityTable;
if (et == null)
{
return;
}
}
public TidyOptions Options
{
get
{
return _options;
}
}
/// <summary>
/// Parses the input stream and writes to the output.
/// </summary>
/// <param name="input">The input stream</param>
/// <param name="Output">The output stream</param>
/// <param name="messages">The messages</param>
public virtual void Parse(Stream input, Stream output, TidyMessageCollection messages)
{
try
{
Parse(input, null, output, messages);
}
catch (FileNotFoundException)
{
}
catch (IOException)
{
}
}
/// <summary>
/// Parses the input stream or file and writes to the output.
/// </summary>
/// <param name="input">The input stream</param>
/// <param name="file">The input file</param>
/// <param name="Output">The output stream</param>
/// <param name="messages">The messages</param>
public void Parse(Stream input, string file, Stream Output, TidyMessageCollection messages)
{
ParseInternal(input, file, Output, messages);
}
/// <summary> Parses InputStream in and returns the root Node.
/// If out is non-null, pretty prints to OutputStream out.
/// </summary>
internal virtual Node ParseInternal(Stream input, Stream output, TidyMessageCollection messages)
{
Node document = null;
try
{
document = ParseInternal(input, null, output, messages);
}
catch (FileNotFoundException)
{
}
catch (IOException)
{
}
return document;
}
/// <summary> Internal routine that actually does the parsing. The caller
/// can pass either an InputStream or file name. If both are passed,
/// the file name is preferred.
/// </summary>
internal Node ParseInternal(Stream input, string file, Stream Output, TidyMessageCollection messages)
{
Lexer lexer;
Node document = null;
Node doctype;
Out o = new OutImpl(); /* normal output stream */
PPrint pprint;
/* ensure config is self-consistent */
_options.Adjust();
if (file != null)
{
input = new FileStream(file, FileMode.Open, FileAccess.Read);
}
else if (input == null)
{
input = Console.OpenStandardInput();
}
if (input != null)
{
lexer = new Lexer(new ClsStreamInImpl(input, _options.CharEncoding, _options.TabSize), _options);
lexer.messages = messages;
/*
store pointer to lexer in input stream
to allow character encoding errors to be
reported
*/
lexer.input.Lexer = lexer;
/* Tidy doesn't alter the doctype for generic XML docs */
if (_options.XmlTags)
{
document = ParserImpl.parseXMLDocument(lexer);
}
else
{
document = ParserImpl.parseDocument(lexer);
if (!document.CheckNodeIntegrity())
{
Report.BadTree(lexer);
return null;
}
Clean cleaner = new Clean(_options.tt);
/* simplifies <b><b> ... </b> ...</b> etc. */
cleaner.NestedEmphasis(document);
/* cleans up <dir>indented text</dir> etc. */
cleaner.List2BQ(document);
cleaner.BQ2Div(document);
/* replaces i by em and b by strong */
if (_options.LogicalEmphasis)
{
cleaner.EmFromI(document);
}
if (_options.Word2000 && cleaner.IsWord2000(document, _options.tt))
{
/* prune Word2000's <![if ...]> ... <![endif]> */
cleaner.DropSections(lexer, document);
/* drop style & class attributes and empty p, span elements */
cleaner.CleanWord2000(lexer, document);
}
/* replaces presentational markup by style rules */
if (_options.MakeClean || _options.DropFontTags)
{
cleaner.CleanTree(lexer, document);
}
if (!document.CheckNodeIntegrity())
{
Report.BadTree(lexer);
return null;
}
doctype = document.FindDocType();
if (document.Content != null)
{
if (_options.Xhtml)
{
lexer.SetXhtmlDocType(document);
}
else
{
lexer.FixDocType(document);
}
if (_options.TidyMark)
{
lexer.AddGenerator(document);
}
}
/* ensure presence of initial <?XML version="1.0"?> */
if (_options.XmlOut && _options.XmlPi)
{
lexer.FixXmlPI(document);
}
if (document.Content != null)
{
Report.ReportVersion(lexer, doctype);
Report.ReportNumWarnings(lexer);
}
}
// Try to close the InputStream but only if if we created it.
if ((file != null) && (input != Console.OpenStandardOutput()))
{
try
{
input.Close();
}
catch (IOException)
{
}
}
if (lexer.messages.Errors > 0)
{
Report.NeedsAuthorIntervention(lexer);
}
o.State = StreamIn.FSM_ASCII;
o.Encoding = _options.CharEncoding;
if (lexer.messages.Errors == 0)
{
if (_options.BurstSlides)
{
Node body;
body = null;
/*
remove doctype to avoid potential clash with
markup introduced when bursting into slides
*/
/* discard the document type */
doctype = document.FindDocType();
if (doctype != null)
{
Node.DiscardElement(doctype);
}
/* slides use transitional features */
lexer.versions |= HtmlVersion.Html40Loose;
/* and patch up doctype to match */
if (_options.Xhtml)
{
lexer.SetXhtmlDocType(document);
}
else
{
lexer.FixDocType(document);
}
/* find the body element which may be implicit */
body = document.FindBody(_options.tt);
if (body != null)
{
pprint = new PPrint(_options);
Report.ReportNumberOfSlides(lexer, pprint.CountSlides(body));
pprint.CreateSlides(lexer, document);
}
else
{
Report.MissingBody(lexer);
}
}
else if (Output != null)
{
pprint = new PPrint(_options);
o.Output = Output;
if (_options.XmlTags)
{
pprint.PrintXmlTree(o, (short) 0, 0, lexer, document);
}
else
{
pprint.PrintTree(o, (short) 0, 0, lexer, document);
}
pprint.FlushLine(o, 0);
}
}
Report.ErrorSummary(lexer);
}
return document;
}
/// <summary> Parses InputStream in and returns a DOM Document node.
/// If out is non-null, pretty prints to OutputStream out.
/// </summary>
internal virtual IDocument ParseDom(Stream input, Stream Output, TidyMessageCollection messages)
{
Node document = ParseInternal(input, Output, messages);
if (document != null)
{
return (IDocument) document.Adapter;
}
else
{
return null;
}
}
/// <summary> Creates an empty DOM Document.</summary>
internal static IDocument CreateEmptyDocument()
{
Node document = new Node(Node.RootNode, new byte[0], 0, 0);
Node node = new Node(Node.StartTag, new byte[0], 0, 0, "html", new TagTable());
if (document != null && node != null)
{
Node.InsertNodeAtStart(document, node);
return (IDocument)document.Adapter;
}
else
{
return null;
}
}
/// <summary>Pretty-prints a DOM Document.</summary>
internal virtual void PrettyPrint(IDocument doc, Stream Output)
{
Out o = new OutImpl();
PPrint pprint;
Node document;
if (!(doc is DomDocumentImpl))
{
return;
}
document = ((DomDocumentImpl)doc).Adaptee;
o.State = StreamIn.FSM_ASCII;
o.Encoding = _options.CharEncoding;
if (Output != null)
{
pprint = new PPrint(_options);
o.Output = Output;
if (_options.XmlTags)
{
pprint.PrintXmlTree(o, (short) 0, 0, null, document);
}
else
{
pprint.PrintTree(o, (short) 0, 0, null, document);
}
pprint.FlushLine(o, 0);
}
}
private TidyOptions _options = new TidyOptions();
}
} |
using System;
using System.Collections.Generic;
using EasyEventSourcing.Domain.Orders;
using EasyEventSourcing.EventSourcing.Domain;
using EasyEventSourcing.Messages.Orders;
using EasyEventSourcing.Messages.Store;
using System.Linq;
namespace EasyEventSourcing.Domain.Store
{
public class ShoppingCart : Aggregate
{
public ShoppingCart() {}
protected override void RegisterAppliers()
{
this.RegisterApplier<CartCreated>(this.Apply);
this.RegisterApplier<ProductAddedToCart>(this.Apply);
this.RegisterApplier<ProductRemovedFromCart>(this.Apply);
this.RegisterApplier<CartEmptied>(this.Apply);
this.RegisterApplier<CartCheckedOut>(this.Apply);
}
private readonly Dictionary<Guid, Decimal> products = new Dictionary<Guid, decimal>();
private bool checkedOut;
private Guid clientId;
private ShoppingCart(Guid cartId, Guid customerId)
{
this.ApplyChanges(new CartCreated(cartId, customerId));
}
public static ShoppingCart Create(Guid cartId, Guid customerId)
{
return new ShoppingCart(cartId, customerId);
}
private void Apply(CartCreated evt)
{
this.id = evt.CartId;
this.clientId = evt.ClientId;
}
public void AddProduct(Guid productId, decimal price)
{
if(checkedOut)
{
throw new CartAlreadyCheckedOutException();
}
if (!products.ContainsKey(productId))
{
this.ApplyChanges(new ProductAddedToCart(this.id, productId, price));
}
}
private void Apply(ProductAddedToCart evt)
{
products.Add(evt.ProductId, evt.Price);
}
public void RemoveProduct(Guid productId)
{
if (checkedOut)
{
throw new CartAlreadyCheckedOutException();
}
if(products.ContainsKey(productId))
{
this.ApplyChanges(new ProductRemovedFromCart(this.id, productId));
}
}
private void Apply(ProductRemovedFromCart evt)
{
products.Remove(evt.ProductId);
}
public void Empty()
{
if (checkedOut)
{
throw new CartAlreadyCheckedOutException();
}
this.ApplyChanges(new CartEmptied(this.id));
}
private void Apply(CartEmptied evt)
{
products.Clear();
}
public EventStream Checkout()
{
if(this.products.Count == 0)
{
throw new CannotCheckoutEmptyCartException();
}
this.ApplyChanges(new CartCheckedOut(this.id));
return Order.Create(this.id, this.clientId, this.products.Select(x => new OrderItem(x.Key, x.Value)));
}
private void Apply(CartCheckedOut evt)
{
this.checkedOut = true;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace eQuantic.Core.Outcomes.Results
{
public class ListResult<T> : BasicResult
{
public virtual List<T> Items { get; set; }
[JsonProperty("__metadata", NullValueHandling = NullValueHandling.Ignore)]
public Metadata Metadata { get; set; }
public ListResult()
{
Items = new List<T>();
}
public ListResult(IEnumerable<T> items)
{
Items = items.ToList();
}
}
}
|
using FluentAssertions;
using System;
using Xunit;
namespace Atomiv.Core.Domain.UnitTest
{
public class PrimitiveIdentityTest
{
[Fact]
public void GuidIdentityCannotBeEmptyGuidValue()
{
Action action = () => new GuidIdentity(Guid.Empty);
action.Should().Throw<DomainException>();
}
[Fact]
public void GuidIdentityIdentical()
{
var guid = Guid.NewGuid();
var a = new GuidIdentity(guid);
var b = new GuidIdentity(guid);
(a == b).Should().BeTrue();
}
[Fact]
public void GuidIdentityImplicitConversion()
{
GuidIdentity a = null;
Guid b;
Action action = () => b = a;
action.Should().Throw<DomainException>();
}
[Fact]
public void GuidIdentityImplicitConversionNullable()
{
GuidIdentity a = null;
Guid? b = a;
b.Should().Be(null);
}
private class GuidIdentity : PrimitiveIdentity<Guid>
{
public GuidIdentity(Guid value) : base(value)
{
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 18.10.2020.
using NUnit.Framework;
using xEFCore_c
=Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.Common;
namespace EFCore_LcpiOleDb_Tests.General.Unit.Objects.DataProvider.Dbms.Firebird.Common.FB_Common__Utilities{
////////////////////////////////////////////////////////////////////////////////
//class TestsFor__TextToSqlLiteral__char
public static class TestsFor__TextToSqlLiteral__char
{
[Test]
public static void Test_01__from_0_to_32()
{
for(byte ch=0;ch!=' ';++ch)
{
string r="_utf8 x'"+ch.ToString("X2")+"'";
Assert.AreEqual
(r,
xEFCore_c.FB_Common__Utilities.TextToSqlLiteral((char)ch));
}//for ch
}//Test_01__from_0_to_32
//-----------------------------------------------------------------------
[Test]
public static void Test_02__single_quote()
{
Assert.AreEqual
("_utf8 ''''",
xEFCore_c.FB_Common__Utilities.TextToSqlLiteral('\''));
}//Test_02__single_quote
//-----------------------------------------------------------------------
private static readonly string sm_Data03
//01234567890123456789012345
="abcdefghijklmnopqrstuvwxyz"
+"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
[Test]
public static void Test_03()
{
foreach(char ch in sm_Data03)
{
Assert.AreEqual
("_utf8 '"+ch+"'",
xEFCore_c.FB_Common__Utilities.TextToSqlLiteral(ch));
}//foreach ch
}//Test_03
};//class TestsFor__TextToSqlLiteral__char
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Unit.Objects.DataProvider.Dbms.Firebird.Common.FB_Common__Utilities
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerData
{
public int mapOneHighScore;
public int mapTwoHighScore;
public long mapOneHighestWave;
public long mapTwoHighestWave;
}
|
/****************************************************************
Copyright 2021 Infosys Ltd.
Use of this source code is governed by Apache License Version 2.0 that can be found in the LICENSE file or at
http://www.apache.org/licenses/
***************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Infosys.Solutions.Ainauto.Resource.DataAccess.CustomDataEntity
{
public class ResourceDependencyDetails
{
public string Resourceid { get; set; }
public string DependencyResourceId { get; set; }
public string DependencyType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Ripple.Testing.Utils
{
public class PartitionedTests
{
public const string TestPrefixPattern = @"^(P(\d+)).*$";
private readonly SortedList<int, MethodInfo> _tests;
private int _expectedTest;
private bool _failed;
private Type _testAttributeType;
private PartitionedTests(SortedList<int, MethodInfo> tests, Type testAttribute)
{
_tests = tests;
_failed = false;
_testAttributeType = testAttribute;
}
public void PreTest(string testName, Action<List<MethodInfo>> onAnyPriors)
{
if (_failed)
{
throw new InvalidOperationException("Dependent on prior state");
}
var nth = GetTextIndex(testName);
if (nth > _expectedTest)
{
onAnyPriors(GetTestsPriorTo(nth));
}
_expectedTest++;
}
public void PostTest(bool failed)
{
if (failed)
{
_failed = true;
}
}
public static PartitionedTests Create (Type type, Type testAttribute)
{
var nl = Environment.NewLine;
var tests = GetTests(type, testAttribute);
var matches = tests.Select(m =>
{
var match = Regex.Match(m.Name, TestPrefixPattern);
return match;
}).ToList();
var matched = matches.Where(m => m.Success).ToList();
var unmatched = matches.Select((m, i) => tests[i].Name)
.Where((n, i) => !matches[i].Success)
.ToList();
if (unmatched.Count != 0)
{
throw new InvalidOperationException(
$"not all tests matched {TestPrefixPattern}:{nl}" +
$"{string.Join(nl, unmatched)} ");
}
var prefixes = matched.Select(m => m.Groups[1].Value).ToList();
var uniqueLengths = prefixes.Select(p => p.Length).Distinct().Count();
if (uniqueLengths != 1)
{
throw new InvalidOperationException(
"All test prefixes must be of equal length:" +
$"{nl}{string.Join(",", prefixes)}{nl}");
}
var sortedTests = new SortedList<int, MethodInfo>(
tests.ToDictionary(t => PNumberFromName(t.Name)));
return new PartitionedTests(sortedTests, testAttribute);
}
public static int PNumberFromName(string testName)
{
var match = Regex.Match(testName, TestPrefixPattern);
var groups = match.Groups;
var nth = int.Parse(groups[2].Value);
return nth;
}
public static List<MethodInfo> GetTests(Type type, Type testAttributeType)
{
return type.GetMethods()
.Where(y => y.GetCustomAttributes()
.Any(a => a.GetType() == testAttributeType))
.ToList();
}
public int GetTextIndex(string testName)
{
return _tests.IndexOfKey(PNumberFromName(testName));
}
public List<MethodInfo> GetTestsPriorTo(int nth)
{
// TODO: _tests.Values ?
return _tests.Where((kv, i) => i < nth)
.Select(kv => kv.Value)
.ToList();
}
}
} |
// <copyright file="Solution.cs" company="Ocean">
// Copyright (c) Ocean. All rights reserved.
// </copyright>
namespace Questions.LeetCode.No5.LongestPalindromicSubstring
{
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The solution of LeetCode No.5 question: Longest Palindrome Substring.
/// </summary>
public class Solution : IQuestion
{
/// <inheritdoc />
public string LongestPalindrome(string s)
{
// Step 0: Handles invalid or special cases.
if (string.IsNullOrWhiteSpace(s) ||
s.Length == 1 ||
s.Distinct().Count() == 1 ||
s.Reverse().SequenceEqual(s))
{
return s;
}
if (s.Length == 2)
{
return s.First().Equals(s.Last()) ? s : s.First().ToString();
}
if (s.Distinct().Count() == s.Length)
{
return s.First().ToString();
}
// Step 1: Handles normal cases.
var longestPalindromeSubstring = string.Empty;
for (var index = 0; index < s.Length && s.Length - index > longestPalindromeSubstring.Length; index++)
{
var currentChar = s[index];
var currentCharLastIndex = s.LastIndexOf(currentChar);
if (index == currentCharLastIndex)
{
if (!string.IsNullOrWhiteSpace(longestPalindromeSubstring) ||
longestPalindromeSubstring.Length > 1)
{
continue;
}
longestPalindromeSubstring = currentChar.ToString();
}
var currentCharIndexes = new Stack<int>();
for (var nextIndex = index + 1; nextIndex <= currentCharLastIndex; nextIndex++)
{
if (s[nextIndex] == currentChar)
{
currentCharIndexes.Push(nextIndex);
}
}
while (currentCharIndexes.Any())
{
var relatedIndex = currentCharIndexes.Pop();
var possibleStr = s.Substring(index, relatedIndex - index + 1);
var reversedPossibleStr = new string(possibleStr.ToCharArray().Reverse().ToArray());
if (!possibleStr.Equals(reversedPossibleStr) ||
possibleStr.Length < longestPalindromeSubstring.Length ||
possibleStr.Equals(longestPalindromeSubstring))
{
continue;
}
longestPalindromeSubstring = possibleStr;
}
}
return longestPalindromeSubstring;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Lsj.Util.Win32.NativeUI.Dialogs
{
/// <summary>
/// Base Dialog
/// </summary>
public abstract class BaseDialog
{
/// <summary>
/// Show Dialog
/// </summary>
/// <returns></returns>
public virtual ShowDialogResult ShowDialog() => ShowDialog(IntPtr.Zero);
/// <summary>
/// Show Dialog
/// </summary>
/// <param name="owner">Owner Handle</param>
/// <returns></returns>
public abstract ShowDialogResult ShowDialog(IntPtr owner);
}
/// <summary>
/// Base Dialog With Result
/// </summary>
/// <typeparam name="TResult"></typeparam>
public abstract class BaseDialog<TResult> : BaseDialog
{
/// <summary>
/// Result
/// </summary>
public virtual TResult? Result { get; protected set; }
}
}
|
using UnityEngine;
namespace Zenject.Tests.Factories.PrefabFactory
{
public class Foo : MonoBehaviour
{
public bool WasInitialized;
[Inject]
public void Init()
{
WasInitialized = true;
}
public class Factory : PlaceholderFactory<Object, Foo>
{
}
public class Factory2 : PlaceholderFactory<string, Foo>
{
}
}
}
|
using System.Globalization;
using System.Numerics;
namespace OpenSeaClient
{
internal static class BigIntegerExtensions
{
internal static int NumberOfDigits(this BigInteger value)
{
return (value * value.Sign).ToString().Length;
}
internal static BigInteger ParseInvariant(string value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
return BigInteger.Parse(value, CultureInfo.InvariantCulture);
}
}
}
|
using HtmlReader.Attributes.Prototypes;
using System;
namespace HtmlReader
{
[AttributeUsage(AttributeTargets.Property)]
public class ContentAttribute : HtmlElementAttribute
{
public bool TextOnly { get; }
public ContentAttribute()
{
}
public ContentAttribute(bool textOnly)
: this()
{
TextOnly = textOnly;
}
}
}
|
@model IEnumerable<BazaPoklona.Models.Poklon>
@{
ViewData["Title"] = "Index";
}
<h1>OstvareniPromet</h1>
<table class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.Naziv)</th>
<th>@Html.DisplayNameFor(model => model.VrstaRobe)</th>
<th>@Html.DisplayNameFor(model => model.Cijena)</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Naziv)</td>
<td>@Html.DisplayFor(modelItem => item.VrstaRobe)</td>
<td>
<span class="badge badge-secondary">@Html.DisplayFor(modelItem => item.Cijena)</span>
</td>
</tr>
}
</tbody>
</table>
|
namespace ME.ECS {
public interface IModuleBase {
void OnConstruct();
void OnDeconstruct();
}
public interface IModule<TState> : IModuleBase where TState : class, IState<TState>, new() {
IWorld<TState> world { get; set; }
void Update(TState state, float deltaTime);
void AdvanceTick(TState state, float deltaTime);
}
public interface IModuleValidation {
bool CouldBeAdded();
}
} |
using System;
using System.Collections.Generic;
namespace abc_bank
{
public class Account
{
public AccountType accountType {get; set;}
public List<Transaction> transactions;
public Account(AccountType accountType)
{
this.accountType = accountType;
transactions = new List<Transaction>();
}
public void AddTransaction(double amount)
{
if (amount == 0)
{
throw new ArgumentException("amount must be greater than zero");
}
else
{
transactions.Add(new Transaction(amount));
}
}
public double CalculateInterestEarned()
{
double amount = CalculateBalance();
switch(accountType){
case AccountType.SAVINGS:
if (amount <= 1000)
return amount * 0.001;
else
return 1 + (amount-1000) * 0.002;
case AccountType.MAXI_SAVINGS:
if (amount <= 1000)
return amount * 0.02;
if (amount <= 2000)
return 20 + (amount-1000) * 0.05;
return 70 + (amount-2000) * 0.1;
default:
return amount * 0.001;
}
}
public double CalculateBalance() {
double amount = 0.0;
foreach (var t in transactions)
amount += t.amount;
return amount;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
namespace AntDesign
{
public interface IModalTemplate
{
/// <summary>
/// Call back when OK button is triggered
/// 点击确定按钮时调用,可以重写它来放入自己的逻辑
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Please replace it with OnFeedbackOkAsync")]
Task OkAsync(ModalClosingEventArgs args);
/// <summary>
/// Call back when Cancel button is triggered
/// 点击取消按钮时调用,可以重写它来放入自己的逻辑
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Please replace it with OnFeedbackCancelAsync")]
Task CancelAsync(ModalClosingEventArgs args);
/// <summary>
/// Call back when OK button is triggered
/// 击确定按钮时调用,可以重写它来放入自己的逻辑
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
Task OnFeedbackOkAsync(ModalClosingEventArgs args);
/// <summary>
/// Call back when Cancel button is triggered
/// 点击取消按钮时调用,可以重写它来放入自己的逻辑
/// </summary>
Task OnFeedbackCancelAsync(ModalClosingEventArgs args);
}
}
|
namespace Quilt4.Service.Interface.Business
{
public interface IEmailSender
{
void Send(string to, string subject, string body);
}
} |
using System;
namespace CG.Olive.Web.Services
{
/// <summary>
/// This class provides access to important HTTP related tokens.
/// </summary>
public class TokenProvider
{
// *******************************************************************
// Properties.
// *******************************************************************
#region Properties
/// <summary>
/// This property contains a cross-reference forgery validation token.
/// </summary>
public string XsrfToken { get; set; }
/// <summary>
/// This property contains a bearer access token.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// This property contains a refresh token.
/// </summary>
public string RefreshToken { get; set; }
/// <summary>
/// This property indicates how long until the access token expires.
/// </summary>
public DateTimeOffset ExpiresAt { get; set; }
#endregion
}
}
|
using System;
using System.Diagnostics;
using System.Xml.Schema;
namespace Xml.Schema.Linq.CodeGen
{
internal class ListSimpleTypeInfo : ClrSimpleTypeInfo
{
private ClrSimpleTypeInfo itemType;
public ClrSimpleTypeInfo ItemType
{
get
{
if (this.itemType == null)
{
XmlSchemaSimpleType st = base.InnerType as XmlSchemaSimpleType;
if (st == null)
{
st = (base.InnerType as XmlSchemaComplexType).GetBaseSimpleType();
}
Debug.Assert(st.Datatype.Variety == XmlSchemaDatatypeVariety.List);
this.itemType = ClrSimpleTypeInfo.CreateSimpleTypeInfo(st.GetListItemType());
}
return this.itemType;
}
}
internal ListSimpleTypeInfo(XmlSchemaType innerType) : base(innerType)
{
}
}
} |
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.File;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Neptuo.Recollections.Entries
{
public class AzureFileStorage : IFileStorage
{
private readonly AzureStorageOptions options;
public bool CanStreamSeek => false;
public AzureFileStorage(IOptions<AzureStorageOptions> options)
{
Ensure.NotNull(options, "options");
this.options = options.Value;
}
private CloudFileDirectory GetRootDirectory()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(options.ConnectionString);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("entries");
if (!share.Exists())
throw Ensure.Exception.InvalidOperation("Missing file share.");
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
return rootDir;
}
private async Task<CloudFileDirectory> GetDirectoryAsync(Entry entry)
{
CloudFileDirectory rootDirectory = GetRootDirectory();
CloudFileDirectory userDirectory = rootDirectory.GetDirectoryReference(entry.UserId);
await userDirectory.CreateIfNotExistsAsync();
CloudFileDirectory entryDirectory = userDirectory.GetDirectoryReference(entry.Id);
await entryDirectory.CreateIfNotExistsAsync();
return entryDirectory;
}
private string GetImageFileName(Image image, ImageType type)
{
string AddSuffix(string name, string suffix)
=> Path.GetFileNameWithoutExtension(name) + suffix + Path.GetExtension(name);
switch (type)
{
case ImageType.Original:
return image.FileName;
case ImageType.Preview:
return AddSuffix(image.FileName, ".preview");
case ImageType.Thumbnail:
return AddSuffix(image.FileName, ".thumbnail");
default:
throw Ensure.Exception.NotSupported(type);
}
}
private async Task<CloudFile> GetFileAsync(Entry entry, Image image, ImageType type)
{
CloudFileDirectory entryDirectory = await GetDirectoryAsync(entry);
string fileName = GetImageFileName(image, type);
CloudFile imageFile = entryDirectory.GetFileReference(fileName);
return imageFile;
}
public async Task DeleteAsync(Entry entry, Image image, ImageType type)
{
CloudFile imageFile = await GetFileAsync(entry, image, type);
await imageFile.DeleteIfExistsAsync();
}
public async Task<Stream> FindAsync(Entry entry, Image image, ImageType type)
{
CloudFile imageFile = await GetFileAsync(entry, image, type);
if (await imageFile.ExistsAsync())
return await imageFile.OpenReadAsync();
return null;
}
public async Task SaveAsync(Entry entry, Image image, Stream content, ImageType type)
{
CloudFile imageFile = await GetFileAsync(entry, image, type);
using (CloudFileStream imageStream = await imageFile.OpenWriteAsync(content.Length))
{
await content.CopyToAsync(imageStream);
await imageStream.CommitAsync();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LoginApp.ViewModels
{
class BookMarkPageViewModel
{
public string Name { get; set; }
public BookMarkPageViewModel()
{
this.Name = "BookMark";
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.